@launchdarkly/cloudflare-server-sdk 2.6.0 → 2.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/index.js.map +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/package.json +2 -2
package/dist/esm/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{EventEmitter as e}from"node:events";import t from"semver";import i from"crypto-js";var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n={},s={};Object.defineProperty(s,"__esModule",{value:!0});s.default=class{constructor(e){this._onRequestStatus=e}getStatus(){return this._lastStatus}async requireStatus(){return this._lastStatus||await this._onRequestStatus(),this._lastStatus}notify(){var e;this._lastStatus&&(null===(e=this._listener)||void 0===e||e.call(this,this._lastStatus))}setListener(e){this._listener=e}setStatus(e){this._lastStatus=e}};var a={},o={};!function(e){function t(e){return e.indexOf("~")?e.replace(/~1/g,"/").replace(/~0/g,"~"):e}class i{constructor(e,i=!1){if(i){const t=e;this._components=[t],this.isValid=""!==t,this.redactionName=t.startsWith("/")?`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`:t}else{if(this.redactionName=e,""===e||"/"===e||e.match(/\/\/|(^\/.*~[^0|^1])|~$/))return this.isValid=!1,void(this._components=[]);!function(e){return!e.startsWith("/")}(e)?e.indexOf("/",1)<0?this._components=[t(e.slice(1))]:this._components=function(e){return(e.startsWith("/")?e.substring(1):e).split("/").map((e=>t(e)))}(e):this._components=[e],"_meta"===this._components[0]?this.isValid=!1:this.isValid=!0}}get(e){const{_components:t,isValid:i}=this;if(!i)return;let r=e;for(let e=0;e<t.length;e+=1){const i=t[e];if(null==r||!Object.prototype.hasOwnProperty.call(r,i)||"object"!=typeof r||Array.isArray(r))return;r=r[i]}return r}getComponent(e){return this._components[e]}get depth(){return this._components.length}get isKind(){return 1===this._components.length&&"kind"===this._components[0]}compare(e){return this.depth===e.depth&&this._components.every(((t,i)=>t===e.getComponent(i)))}}i.InvalidReference=new i("");class r{is(e){if(Array.isArray(e))return!1;const t=typeof e;return"function"===t||"object"===t}getType(){return"factory method or object"}}class n{constructor(e,t){this._typeName=e,this.typeOf=typeof t}is(e){return!Array.isArray(e)&&typeof e===this.typeOf}getType(){return this._typeName}}class s{constructor(e,t){this._typeName=e,this.typeOf=typeof t}is(e){return!!Array.isArray(e)&&(!(e.length>0)||e.every((e=>typeof e===this.typeOf)))}getType(){return this._typeName}}class a extends n{constructor(e){super(`number with minimum value of ${e}`,0),this.min=e}is(e){return typeof e===this.typeOf&&e>=this.min}}class o extends n{constructor(e){super(`string matching ${e}`,""),this.expression=e}is(e){return"string"==typeof e&&!!e.match(this.expression)}}class l{is(e){return"function"==typeof e}getType(){return"function"}}class u{is(e){return"boolean"==typeof e||null==e}getType(){return"boolean | undefined | null"}}const c=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/;class d{is(e){return"number"==typeof e||"string"==typeof e&&c.test(e)}getType(){return"date"}}class h extends o{constructor(){super(/^(\w|\.|-)+$/)}is(e){return super.is(e)&&"kind"!==e}}class f{static createTypeArray(e,t){return new s(e,t)}static numberWithMin(e){return new a(e)}static stringMatchingRegex(e){return new o(e)}}function g(e){return"kind"in e&&(f.String.is(e.kind)&&"multi"!==e.kind)}function v(e){return"kind"in e&&(f.String.is(e.kind)&&"multi"===e.kind)}function _(e){return!("kind"in e)||null===e.kind||void 0===e.kind}f.String=new n("string",""),f.Number=new n("number",0),f.ObjectOrFactory=new r,f.Object=new n("object",{}),f.StringArray=new s("string[]",""),f.Boolean=new n("boolean",!0),f.Function=new l,f.Date=new d,f.Kind=new h,f.NullableBoolean=new u;const p="user";function y(e){return e.includes("%")||e.includes(":")?e.replace(/%/g,"%25").replace(/:/g,"%3A"):e}function m(e){return f.Kind.is(e)}function b(e){return f.String.is(e)&&""!==e}function w(e,t=!1){return e?e.map((e=>new i(e,t))):[]}class S{constructor(e,t,i){this._isMulti=!1,this._isUser=!1,this._wasLegacy=!1,this._contexts={},this.kind=t,this.valid=e,this.message=i}static _contextForError(e,t){return new S(!1,e,t)}static _getValueFromContext(e,t){if(t&&e.isValid)return 1===e.depth&&"anonymous"===e.getComponent(0)?!!t?.anonymous:e.get(t)}_contextForKind(e){return this._isMulti?this._contexts[e]:this.kind===e?this._context:void 0}static _fromMultiKindContext(e){const t=Object.keys(e).filter((e=>"kind"!==e)),i=t.every(m);if(!t.length)return S._contextForError("multi","A multi-kind context must contain at least one kind");if(!i)return S._contextForError("multi","Context contains invalid kinds");const r={};let n=!0;const s=t.reduce(((t,i)=>{const s=e[i];var a;return(a=s)&&f.Object.is(a)?(t[i]=s,r[i]=w(s._meta?.privateAttributes)):n=!1,t}),{});if(!n)return S._contextForError("multi","Context contained contexts that were not objects");if(!Object.values(s).every((e=>b(e.key))))return S._contextForError("multi","Context contained invalid keys");if(1===t.length){const e=t[0],i=new S(!0,e);return i._context={...s[e],kind:e},i._privateAttributeReferences=r,i._isUser="user"===e,i}const a=new S(!0,e.kind);return a._contexts=s,a._privateAttributeReferences=r,a._isMulti=!0,a}static _fromSingleKindContext(e){const{key:t,kind:i}=e,r=m(i),n=b(t);if(!r)return S._contextForError(i??"unknown","The kind was not valid for the context");if(!n)return S._contextForError(i,"The key for the context was not valid");const s=w(e._meta?.privateAttributes),a=new S(!0,i);return a._isUser="user"===i,a._context=e,a._privateAttributeReferences={[i]:s},a}static _fromLegacyUser(e){if(!(void 0!==e.key&&null!==e.key))return S._contextForError("user","The key for the context was not valid");const t=new S(!0,"user");return t._isUser=!0,t._wasLegacy=!0,t._context=function(e){const t={...e.custom||[],kind:"user",key:String(e.key)};if(null!=e.anonymous){const i=!!e.anonymous;delete t.anonymous,t.anonymous=i}return null!==e.name&&void 0!==e.name&&(t.name=e.name),null!==e.ip&&void 0!==e.ip&&(t.ip=e.ip),null!==e.firstName&&void 0!==e.firstName&&(t.firstName=e.firstName),null!==e.lastName&&void 0!==e.lastName&&(t.lastName=e.lastName),null!==e.email&&void 0!==e.email&&(t.email=e.email),null!==e.avatar&&void 0!==e.avatar&&(t.avatar=e.avatar),null!==e.country&&void 0!==e.country&&(t.country=e.country),null!==e.privateAttributeNames&&void 0!==e.privateAttributeNames&&(t._meta={privateAttributes:e.privateAttributeNames}),t}(e),t._privateAttributeReferences={user:w(e.privateAttributeNames,!0)},t}static fromLDContext(e){return e?g(e)?S._fromSingleKindContext(e):v(e)?S._fromMultiKindContext(e):_(e)?S._fromLegacyUser(e):S._contextForError("unknown","Context was not of a valid kind"):S._contextForError("unknown","No context specified. Returning default value")}static toLDContext(e){if(!e.valid)return;const t=e.getContexts();if(!e._isMulti)return t[0][1];const i={kind:"multi"};return t.forEach((e=>{const t=e[0],r=e[1];i[t]=r})),i}valueForKind(e,t=p){return e.isKind?this.kinds:S._getValueFromContext(e,this._contextForKind(t))}key(e=p){return this._contextForKind(e)?.key}get isMultiKind(){return this._isMulti}get canonicalKey(){return this._isUser?this._context.key:this._isMulti?Object.keys(this._contexts).sort().map((e=>`${e}:${y(this._contexts[e].key)}`)).join(":"):`${this.kind}:${y(this._context.key)}`}get kinds(){return this._isMulti?Object.keys(this._contexts):[this.kind]}get kindsAndKeys(){return this._isMulti?Object.entries(this._contexts).reduce(((e,[t,i])=>(e[t]=i.key,e)),{}):{[this.kind]:this._context.key}}privateAttributes(e){return this._privateAttributeReferences?.[e]||[]}getContexts(){return this._isMulti?Object.entries(this._contexts):[[this.kind,this._context]]}get legacy(){return this._wasLegacy}}S.UserKind=p;const k=["key","kind","_meta","anonymous"].map((e=>new i(e,!0))),E=["name","ip","firstName","lastName","email","avatar","country"];class O{constructor(e,t){this._allAttributesPrivate=e,this._privateAttributes=t}filter(e,t=!1){const i=e.getContexts();if(1===i.length)return this._filterSingleKind(e,i[0][1],i[0][0],t);const r={kind:"multi"};return i.forEach((([i,n])=>{r[i]=this._filterSingleKind(e,n,i,t)})),r}_getAttributesToFilter(e,t,r,n){return(n?Object.keys(t).map((e=>new i(e,!0))):[...this._privateAttributes,...e.privateAttributes(r)]).filter((e=>!k.some((t=>t.compare(e)))))}_filterSingleKind(e,t,i,r){const n=this._allAttributesPrivate||r&&!0===t.anonymous,{cloned:s,excluded:a}=function(e,t){const i=[],r={},n=[];for(i.push(...Object.keys(e).map((t=>({key:t,ptr:[t],source:e,parent:r,visited:[e]}))));i.length;){const e=i.pop(),r=t.find((t=>{return i=t,r=e.ptr,i.depth===r.length&&r.every(((e,t)=>e===i.getComponent(t)));var i,r}));if(r)n.push(r.redactionName);else{const t=e.source[e.key];null===t?e.parent[e.key]=t:Array.isArray(t)?e.parent[e.key]=[...t]:"object"==typeof t?e.visited.includes(t)||(e.parent[e.key]={},i.push(...Object.keys(t).map((i=>({key:i,ptr:[...e.ptr,i],source:t,parent:e.parent[e.key],visited:[...e.visited,t]}))))):e.parent[e.key]=t}}return{cloned:r,excluded:n.sort()}}(t,this._getAttributesToFilter(e,t,i,n));return e.legacy&&E.forEach((e=>{e in s&&(s[e]=String(s[e]))})),a.length&&(s._meta||(s._meta={}),s._meta.redactedAttributes=a),s._meta&&(delete s._meta.privateAttributes,0===Object.keys(s._meta).length&&delete s._meta),s}}var x,D,M,P;e.DataSourceErrorKind=void 0,(x=e.DataSourceErrorKind||(e.DataSourceErrorKind={})).Unknown="UNKNOWN",x.NetworkError="NETWORK_ERROR",x.ErrorResponse="ERROR_RESPONSE",x.InvalidData="INVALID_DATA";class T extends Error{constructor(e){super(e),this.name="LaunchDarklyFileDataSourceError"}}class C extends Error{constructor(e,t,i,r=!0){super(t),this.kind=e,this.status=i,this.name="LaunchDarklyPollingError",this.recoverable=r}}class F extends Error{constructor(e,t,i,r=!0){super(t),this.kind=e,this.code=i,this.name="LaunchDarklyStreamingError",this.recoverable=r}}e.AutoEnvAttributes=void 0,(D=e.AutoEnvAttributes||(e.AutoEnvAttributes={}))[D.Disabled=0]="Disabled",D[D.Enabled=1]="Enabled",function(e){e[e.AnalyticsEvents=0]="AnalyticsEvents",e[e.DiagnosticEvent=1]="DiagnosticEvent"}(M||(M={})),function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed",e[e.FailedAndMustShutDown=2]="FailedAndMustShutDown"}(P||(P={}));var I=Object.freeze({__proto__:null,get LDDeliveryStatus(){return P},get LDEventType(){return M}});function j(e){if("string"==typeof e)return e;if(void 0===e)return"undefined";if(null===e)return"null";if(Object.prototype.hasOwnProperty.call(e,"toString"))try{return e.toString()}catch{}if("bigint"==typeof e)return`${e}n`;try{return JSON.stringify(e)}catch(e){return e instanceof TypeError&&e.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}const R={s:e=>j(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=>j(e),o:e=>j(e),O:e=>j(e),c:()=>""};function A(...e){const t=e.shift();if(f.String.is(t)){let i="",r=0;for(;r<t.length;){const n=t.charAt(r);if("%"===n){if(r+1<t.length){const n=t.charAt(r+1);if(n in R&&e.length){const t=e.shift();i+=R[n]?.(t)}else i+="%"===n?"%":`%${n}`;r+=2}}else i+=n,r+=1}return e.length&&(i.length&&(i+=" "),i+=e.map(j).join(" ")),i}return e.map(j).join(" ")}const V={debug:0,info:1,warn:2,error:3,none:4},N=["debug","info","warn","error","none"];class L{static get(){return new L({})}constructor(e){this._logLevel=V[e.level??"info"]??V.info,this._name=e.name??"LaunchDarkly",this._destination=e.destination,this._formatter=e.formatter}_tryFormat(...e){try{return this._formatter?this._formatter?.(...e):A(...e)}catch{return A(...e)}}_tryWrite(e){try{this._destination(e)}catch{console.error(e)}}_log(e,t){if(e>=this._logLevel){const i=`${N[e]}: [${this._name}]`;try{this._destination?this._tryWrite(`${i} ${this._tryFormat(...t)}`):console.error(...t)}catch{console.error(...t)}}}error(...e){this._log(V.error,e)}warn(...e){this._log(V.warn,e)}info(...e){this._log(V.info,e)}debug(...e){this._log(V.debug,e)}}const K={error:f.Function,warn:f.Function,info:f.Function,debug:f.Function};class ${constructor(e,t){Object.entries(K).forEach((([t,i])=>{if(!i.is(e[t]))throw new Error(`Provided logger instance must support logger.${t}(...) method`)})),this._logger=e,this._fallback=t}_log(e,t){try{this._logger[e](...t)}catch{this._fallback[e](...t)}}error(...e){this._log("error",e)}warn(...e){this._log("warn",e)}info(...e){this._log("info",e)}debug(...e){this._log("debug",e)}}class U{static deprecated(e,t){return`"${e}" is deprecated, please use "${t}"`}static optionBelowMinimum(e,t,i){return`Config option "${e}" had invalid value of ${t}, using minimum of ${i} instead`}static unknownOption(e){return`Ignoring unknown config option "${e}"`}static wrongOptionType(e,t,i){return`Config option "${e}" should be of type ${t}, got ${i}, using default value`}static wrongOptionTypeBoolean(e,t){return`Config option "${e}" should be a boolean, got ${t}, converting to boolean`}static invalidTagValue(e){return`Config option "${e}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(e){return`Value of "${e}" was longer than 64 characters and was discarded.`}static partialEndpoint(e){return`You have set custom uris without specifying the ${e} URI; connections may not work properly`}}const z=f.stringMatchingRegex(/^(\w|\.|-)+$/),B=(e,t)=>z.is(e)?e.length>64?{valid:!1,message:U.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:U.invalidTagValue(t)};function q(e){return e.replace(/\/+$/,"")}function H(e){return e.replace(/^\/+/,"").replace(/\?$/,"")}class W{constructor(e,t,i=W.DEFAULT_EVENTS,r="/bulk",n="/diagnostic",s=!0,a){this.streaming=q(e),this.polling=q(t),this.events=q(i),this.analyticsEventPath=r,this.diagnosticEventPath=n,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}}function J(e,t){if(0===t.length)return e;return`${e}?${t.map((({key:e,value:t})=>`${e}=${t}`)).join("&")}`}function G(e,t,i){const r=H(t),n=[...i];return e.payloadFilterKey&&n.push({key:"filter",value:e.payloadFilterKey}),J(`${e.streaming}/${r}`,n)}function X(e,t,i){const r=H(t);return J(`${e.events}/${r}`,i)}W.DEFAULT_EVENTS="https://events.launchdarkly.com";class Y extends Error{constructor(e){super(e),this.name="LaunchDarklyUnexpectedResponseError"}}class Q extends Error{constructor(e){super(e),this.name="LaunchDarklyClientError"}}class Z extends Error{constructor(e){super(e),this.name="LaunchDarklyTimeoutError"}}function ee(e){return!(e>=400&&e<500)||(400===e||408===e||429===e)}function te(e){return 413===e||ee(e)}const ie=(e,t)=>e?Object.entries(e).reduce(((e,[i,r])=>(!Boolean(r)||(e=>"{}"===JSON.stringify(e))(r)||t?.includes(i)||(e[i]="object"==typeof r?ie(r,t):r),e)),{}):e;function re(e,t,i){let r;r=e.status?`error ${e.status}${401===e.status?" (invalid SDK key)":""}`:`I/O error (${e.message||"unknown error"})`;return`Received ${r} for ${t} - ${i??"giving up permanently"}`}function ne({status:e}){return!e||ee(e)}const se=async(e=1e3)=>new Promise((t=>{setTimeout(t,e)}));var ae;!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"}(ae||(ae={}));var oe=ae;class le{static invalidMetricValue(e){return`The track function was called with a non-numeric "metricValue" (${e}), only numeric metric values are supported.`}}le.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";class ue{constructor(e,t){const{basicConfiguration:i,platform:r}=e,{serviceEndpoints:{analyticsEventPath:n,diagnosticEventPath:s}}=i,{crypto:a,requests:o}=r;this._defaultHeaders={...t},this._eventsUri=X(i.serviceEndpoints,n,[]),this._diagnosticEventsUri=X(i.serviceEndpoints,s,[]),this._requests=o,this._crypto=a}async _tryPostingEvents(e,t,i,r){const n={status:P.Succeeded},s={...this._defaultHeaders,"content-type":"application/json"};let a;i&&(s["x-launchdarkly-payload-id"]=i,s["x-launchDarkly-event-schema"]="4");try{const{status:i,headers:r}=await this._requests.fetch(t,{headers:s,body:JSON.stringify(e),method:"POST",keepalive:!0}),o=Date.parse(r.get("date")||"");if(o&&(n.serverTime=o),i<=204)return n;if(a=new Y(re({status:i,message:"some events were dropped"},"event posting")),!ee(i))return te(i)?n.status=P.Failed:n.status=P.FailedAndMustShutDown,n.error=a,n}catch(e){a=e}return a&&!r?(n.status=P.Failed,n.error=a,n):(await se(),this._tryPostingEvents(e,this._eventsUri,i,!1))}async sendEventData(e,t){const i=e===M.AnalyticsEvents?this._crypto.randomUUID():void 0,r=e===M.AnalyticsEvents?this._eventsUri:this._diagnosticEventsUri;return this._tryPostingEvents(t,r,i,!0)}}function ce(e){return"feature"===e.kind}class de{constructor(e,t,i,r,n,s){this.count=e,this.key=t,this.value=i,this.version=n,this.variation=s,this.default=r}increment(){this.count+=1}}class he{constructor(){this._startDate=0,this._endDate=0,this._counters={},this._contextKinds={}}summarizeEvent(e){if(ce(e)&&!e.excludeFromSummaries){const t=function(e){return`${e.key}:${null!==e.variation&&void 0!==e.variation?e.variation:""}:${null!==e.version&&void 0!==e.version?e.version:""}`}(e),i=this._counters[t];let r=this._contextKinds[e.key];r||(r=new Set,this._contextKinds[e.key]=r),e.context.kinds.forEach((e=>r.add(e))),i?i.increment():this._counters[t]=new de(1,e.key,e.value,e.default,e.version,e.variation),(0===this._startDate||e.creationDate<this._startDate)&&(this._startDate=e.creationDate),e.creationDate>this._endDate&&(this._endDate=e.creationDate)}}getSummary(){const e=Object.values(this._counters).reduce(((e,t)=>{let i=e[t.key];i||(i={default:t.default,counters:[],contextKinds:[...this._contextKinds[t.key]]},e[t.key]=i);const r={value:t.value,count:t.count};return void 0!==t.variation&&null!==t.variation&&(r.variation=t.variation),void 0!==t.version&&null!==t.version?r.version=t.version:r.unknown=!0,i.counters.push(r),e}),{});return{startDate:this._startDate,endDate:this._endDate,features:e,kind:"summary"}}clearSummary(){this._startDate=0,this._endDate=0,this._counters={},this._contextKinds={}}}class fe extends Error{constructor(e){super(e),this.name="LaunchDarklyInvalidSDKKeyError"}}function ge(e){const t=Math.trunc(e);return 1===t||0!==t&&0===Math.floor(Math.random()*t)}class ve{constructor(e,t,i,r,n=1,s){this.context=e,this.key=t,this.data=i,this.metricValue=r,this.samplingRatio=n,this.url=s,this.kind="custom",this.creationDate=Date.now(),this.context=e}}class _e{constructor(e,t,i,r,n,s,a,o,l,u,c,d,h=1){this.withReasons=e,this.context=t,this.key=i,this.samplingRatio=h,this.kind="feature",this.creationDate=Date.now(),this.value=r,this.default=n,void 0!==s&&(this.version=s),void 0!==a&&(this.variation=a),void 0!==o&&(this.trackEvents=o),void 0!==l&&(this.prereqOf=l),void 0!==u&&(this.reason=u),void 0!==c&&(this.debugEventsUntilDate=c),void 0!==d&&(this.excludeFromSummaries=d)}}class pe{constructor(e,t=1){this.context=e,this.samplingRatio=t,this.kind="identify",this.creationDate=Date.now()}}var ye=Object.freeze({__proto__:null,ClientMessages:le,DiagnosticsManager:class{constructor(e,t,i){this._platform=t,this._diagnosticInitConfig=i,this._streamInits=[],this._startTime=Date.now(),this._dataSinceDate=this._startTime,this._id={diagnosticId:t.crypto.randomUUID(),sdkKeySuffix:e.length>6?e.substring(e.length-6):e}}createInitEvent(){const e=this._platform.info.sdkData(),t=this._platform.info.platformData();return{kind:"diagnostic-init",id:this._id,creationDate:this._startTime,sdk:e,configuration:this._diagnosticInitConfig,platform:{name:t.name,osArch:t.os?.arch,osName:t.os?.name,osVersion:t.os?.version,...t.additional||{}}}}recordStreamInit(e,t,i){const r={timestamp:e,failed:t,durationMillis:i};this._streamInits.push(r)}createStatsEventAndReset(e,t,i){const r=Date.now(),n={kind:"diagnostic",id:this._id,creationDate:r,dataSinceDate:this._dataSinceDate,droppedEvents:e,deduplicatedUsers:t,eventsInLastBatch:i,streamInits:this._streamInits};return this._streamInits=[],this._dataSinceDate=r,n}},ErrorKinds:oe,EventFactoryBase:class{constructor(e){this._withReasons=e}evalEvent(e){return new _e(this._withReasons,e.context,e.flagKey,e.value,e.defaultVal,e.version,e.variation??void 0,e.trackEvents||e.addExperimentData,e.prereqOfFlagKey,this._withReasons||e.addExperimentData?e.reason:void 0,e.debugEventsUntilDate,e.excludeFromSummaries,e.samplingRatio)}unknownFlagEvent(e,t,i){return new _e(this._withReasons,i,e,t,t,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(e){return new pe(e,1)}customEvent(e,t,i,r,n=1){return new ve(t,e,i??void 0,r??void 0,n)}},EventProcessor:class{constructor(e,t,r,n,s,a=!0){this._config=e,this._contextDeduplicator=n,this._diagnosticsManager=s,this._summarizer=new he,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 ue(t,r),this._contextFilter=new O(e.allAttributesPrivate,e.privateAttributes.map((e=>new i(e)))),a&&this.start()}start(){if(void 0!==this._contextDeduplicator?.flushInterval&&(this._flushUsersTimer=setInterval((()=>{this._contextDeduplicator?.flush()}),1e3*this._contextDeduplicator.flushInterval)),this._flushTimer=setInterval((async()=>{try{await this.flush()}catch(e){this._logger?.debug(`Flush failed: ${e}`)}}),1e3*this._config.flushInterval),this._diagnosticsManager){const e=this._diagnosticsManager.createInitEvent();this._postDiagnosticEvent(e),this._diagnosticsTimer=setInterval((()=>{const e=this._diagnosticsManager.createStatsEventAndReset(this._droppedEvents,this._deduplicatedUsers,this._eventsInLastBatch);this._droppedEvents=0,this._deduplicatedUsers=0,this._postDiagnosticEvent(e)}),1e3*this._config.diagnosticRecordingInterval)}this._logger?.debug("Started EventProcessor.")}_postDiagnosticEvent(e){this._eventSender.sendEventData(M.DiagnosticEvent,e)}close(){clearInterval(this._flushTimer),this._flushUsersTimer&&clearInterval(this._flushUsersTimer),this._diagnosticsTimer&&clearInterval(this._diagnosticsTimer)}async flush(){if(this._shutdown)throw new fe("Events cannot be posted because a permanent error has been encountered. This is most likely an invalid SDK key. The specific error information is logged independently.");const e=this._queue;this._queue=[];const t=this._summarizer.getSummary();this._summarizer.clearSummary(),Object.keys(t.features).length&&e.push(t),e.length&&(this._eventsInLastBatch=e.length,this._logger?.debug("Flushing %d events",e.length),await this._tryPostingEvents(e))}sendEvent(e){if(this._shutdown)return;if("migration_op"===e.kind){if(ge(e.samplingRatio)){const t={...e};1===t.samplingRatio&&delete t.samplingRatio,this._enqueue(t)}return}this._summarizer.summarizeEvent(e);const t=ce(e),i=t&&e.trackEvents||!t,r=this._shouldDebugEvent(e),n=function(e){return"identify"===e.kind}(e),s=this._contextDeduplicator?.processContext(e.context);s||n||(this._deduplicatedUsers+=1);s&&!n&&this._enqueue(this._makeOutputEvent({kind:"index",creationDate:e.creationDate,context:e.context,samplingRatio:1},!1)),i&&ge(e.samplingRatio)&&this._enqueue(this._makeOutputEvent(e,!1)),r&&ge(e.samplingRatio)&&this._enqueue(this._makeOutputEvent(e,!0))}_makeOutputEvent(e,t){switch(e.kind){case"feature":{const i={kind:t?"debug":"feature",creationDate:e.creationDate,context:this._contextFilter.filter(e.context,!t),key:e.key,value:e.value,default:e.default};return 1!==e.samplingRatio&&(i.samplingRatio=e.samplingRatio),e.prereqOf&&(i.prereqOf=e.prereqOf),void 0!==e.variation&&(i.variation=e.variation),void 0!==e.version&&(i.version=e.version),e.reason&&(i.reason=e.reason),i}case"index":case"identify":{const t={kind:e.kind,creationDate:e.creationDate,context:this._contextFilter.filter(e.context)};return 1!==e.samplingRatio&&(t.samplingRatio=e.samplingRatio),t}case"custom":{const t={kind:"custom",creationDate:e.creationDate,key:e.key,contextKeys:e.context.kindsAndKeys};return 1!==e.samplingRatio&&(t.samplingRatio=e.samplingRatio),void 0!==e.data&&(t.data=e.data),void 0!==e.metricValue&&(t.metricValue=e.metricValue),void 0!==e.url&&(t.url=e.url),t}case"click":return{kind:"click",creationDate:e.creationDate,contextKeys:e.context.kindsAndKeys,key:e.key,url:e.url,selector:e.selector};case"pageview":return{kind:"pageview",creationDate:e.creationDate,contextKeys:e.context.kindsAndKeys,key:e.key,url:e.url};default:return e}}_enqueue(e){this._queue.length<this._capacity?(this._queue.push(e),this._exceededCapacity=!1):(this._exceededCapacity||(this._exceededCapacity=!0,this._logger?.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this._droppedEvents+=1)}_shouldDebugEvent(e){return ce(e)&&e.debugEventsUntilDate&&e.debugEventsUntilDate>this._lastKnownPastTime&&e.debugEventsUntilDate>Date.now()}async _tryPostingEvents(e){const t=await this._eventSender.sendEventData(M.AnalyticsEvents,e);if(t.status===P.FailedAndMustShutDown&&(this._shutdown=!0),t.serverTime&&(this._lastKnownPastTime=t.serverTime),t.error)throw t.error}},InputCustomEvent:ve,InputEvalEvent:_e,InputIdentifyEvent:pe,NullEventProcessor:class{close(){}async flush(){}sendEvent(){}},StreamingProcessor:class{constructor(e,t,i,r,n,s,a,o=1){this._listeners=r,this._diagnosticsManager=s,this._errorHandler=a,this._streamInitialReconnectDelay=o;const{basicConfiguration:l,platform:u}=e,{logger:c}=l,{requests:d}=u;this._headers={...n},this._logger=c,this._requests=d,this._streamUri=G(l.serviceEndpoints,t,i)}_logConnectionStarted(){this._connectionAttemptStartTime=Date.now()}_logConnectionResult(e){this._connectionAttemptStartTime&&this._diagnosticsManager&&this._diagnosticsManager.recordStreamInit(this._connectionAttemptStartTime,!e,Date.now()-this._connectionAttemptStartTime),this._connectionAttemptStartTime=void 0}_retryAndHandleError(t){return ne(t)?(this._logger?.warn(re(t,"streaming request","will retry")),this._logConnectionResult(!1),this._logConnectionStarted(),!0):(this._logConnectionResult(!1),this._errorHandler?.(new F(e.DataSourceErrorKind.ErrorResponse,t.message,t.status)),this._logger?.error(re(t,"streaming request")),!1)}start(){this._logConnectionStarted();const t=this._requests.createEventSource(this._streamUri,{headers:this._headers,errorFilter:e=>this._retryAndHandleError(e),initialRetryDelayMillis:1e3*this._streamInitialReconnectDelay,readTimeoutMillis:3e5,retryResetIntervalMillis:6e4});this._eventSource=t,t.onclose=()=>{this._logger?.info("Closed LaunchDarkly stream connection")},t.onerror=()=>{},t.onopen=()=>{this._logger?.info("Opened LaunchDarkly stream connection")},t.onretrying=e=>{this._logger?.info(`Will retry stream connection in ${e.delayMillis} milliseconds`)},this._listeners.forEach((({deserializeData:i,processJson:r},n)=>{t.addEventListener(n,(t=>{if(this._logger?.debug(`Received ${n} event`),t?.data){this._logConnectionResult(!0);const{data:s}=t,a=i(s);if(!a)return void((t,i,r,n)=>{r?.error(`Stream received invalid data in "${t}" message`),r?.debug(`Invalid JSON follows: ${i}`),n?.(new F(e.DataSourceErrorKind.InvalidData,"Malformed JSON data in event stream"))})(n,s,this._logger,this._errorHandler);r(a)}else this._errorHandler?.(new F(e.DataSourceErrorKind.Unknown,"Unexpected payload from event stream"))}))}))}stop(){this._eventSource?.close(),this._eventSource=void 0}close(){this.stop()}},isLegacyUser:_,isMultiKind:v,isSingleKind:g,shouldSample:ge});e.ApplicationTags=class{constructor(e){const t={},i=e?.application,r=e?.logger;i&&Object.entries(i).forEach((([e,i])=>{if(null!=i){const{valid:n,message:s}=B(i,`application.${e}`);n?"versionName"===e?t["application-version-name"]=[i]:t[`application-${e}`]=[i]:r?.warn(s)}}));const n=Object.keys(t);n.length&&(this.value=n.sort().flatMap((e=>t[e].sort().map((t=>`${e}/${t}`)))).join(" "))}},e.AttributeReference=i,e.BasicLogger=L,e.ClientContext=class{constructor(e,t,i){this.platform=i,this.basicConfiguration={tags:t.tags,logger:t.logger,offline:t.offline,serviceEndpoints:t.serviceEndpoints,sdkKey:e}}},e.Context=S,e.ContextFilter=O,e.DateValidator=d,e.FactoryOrInstance=r,e.Function=l,e.KindValidator=h,e.LDClientError=Q,e.LDFileDataSourceError=T,e.LDPollingError=C,e.LDStreamingError=F,e.LDTimeoutError=Z,e.LDUnexpectedResponseError=Y,e.NullableBoolean=u,e.NumberWithMinimum=a,e.OptionMessages=U,e.SafeLogger=$,e.ServiceEndpoints=W,e.StringMatchingRegex=o,e.Type=n,e.TypeArray=s,e.TypeValidators=f,e.base64UrlEncode=(e,t)=>t.btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.cancelableTimedPromise=function(e,t){let i,r;return{promise:new Promise(((n,s)=>{r=n,i=setTimeout((()=>{s(new Z(`${t} timed out after ${e} seconds.`))}),1e3*e)})),cancel:()=>{r(),clearTimeout(i)}}},e.clone=function(e){return null==e?e:JSON.parse(JSON.stringify(e))},e.createSafeLogger=e=>{const t=new L({level:"info",destination:console.error,formatter:A});return e?new $(e,t):t},e.debounce=(e,t=5e3)=>{let i;return(...r)=>{clearTimeout(i),i=setTimeout((()=>{e(...r)}),t)}},e.deepCompact=ie,e.defaultHeaders=function(e,t,i,r=!0,n="user-agent"){const{userAgentBase:s,version:a,wrapperName:o,wrapperVersion:l}=t.sdkData(),u={[n]:`${s??"NodeJSClient"}/${a}`};return r&&(u.authorization=e),o&&(u["x-launchdarkly-wrapper"]=l?`${o}/${l}`:o),i?.value&&(u["x-launchdarkly-tags"]=i.value),u},e.fastDeepEqual=function e(t,i){if(t===i)return!0;if(t&&i&&"object"==typeof t&&"object"==typeof i){if(t.constructor!==i.constructor)return!1;var r,n,s;if(Array.isArray(t)){if((r=t.length)!=i.length)return!1;for(n=r;0!=n--;)if(!e(t[n],i[n]))return!1;return!0}if(t instanceof Map&&i instanceof Map){if(t.size!==i.size)return!1;for(n of t.entries())if(!i.has(n[0]))return!1;for(n of t.entries())if(!e(n[1],i.get(n[0])))return!1;return!0}if(t instanceof Set&&i instanceof Set){if(t.size!==i.size)return!1;for(n of t.entries())if(!i.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(i)){if((r=t.length)!=i.length)return!1;for(n=r;0!=n--;)if(t[n]!==i[n])return!1;return!0}if(t.constructor===RegExp)return t.source===i.source&&t.flags===i.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===i.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===i.toString();if((r=(s=Object.keys(t)).length)!==Object.keys(i).length)return!1;for(n=r;0!=n--;)if(!Object.prototype.hasOwnProperty.call(i,s[n]))return!1;for(n=r;0!=n--;){var a=s[n];if(!e(t[a],i[a]))return!1}return!0}return t!=t&&i!=i},e.getEventsUri=X,e.getPollingUri=function(e,t,i){const r=H(t),n=[...i];return e.payloadFilterKey&&n.push({key:"filter",value:e.payloadFilterKey}),J(`${e.polling}/${r}`,n)},e.getStreamingUri=G,e.httpErrorMessage=re,e.internal=ye,e.isHttpLocallyRecoverable=te,e.isHttpRecoverable=ee,e.noop=()=>{},e.secondsToMillis=function(e){return Math.trunc(1e3*e)},e.shouldRetry=ne,e.sleep=se,e.subsystem=I,e.timedPromise=(e,t)=>new Promise(((i,r)=>{setTimeout((()=>{r(new Z(`${t} timed out after ${e} seconds.`))}),1e3*e)}))}(o);var l={},u={},c={};Object.defineProperty(c,"__esModule",{value:!0});var d={};Object.defineProperty(d,"__esModule",{value:!0});var h,f,g={};Object.defineProperty(g,"__esModule",{value:!0}),g.IsMigrationStage=g.LDMigrationStage=void 0,(f=h||(g.LDMigrationStage=h={})).Off="off",f.DualWrite="dualwrite",f.Shadow="shadow",f.Live="live",f.RampDown="rampdown",f.Complete="complete",g.IsMigrationStage=function(e){return Object.values(h).includes(e)};var v={};Object.defineProperty(v,"__esModule",{value:!0});var _,p,y,m,b,w={};Object.defineProperty(w,"__esModule",{value:!0}),w.LDConsistencyCheck=void 0,(p=_||(w.LDConsistencyCheck=_={}))[p.Inconsistent=0]="Inconsistent",p[p.Consistent=1]="Consistent",p[p.NotChecked=2]="NotChecked",y=u,m=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),b=r&&r.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||m(t,e,i)},Object.defineProperty(y,"__esModule",{value:!0}),b(c,y),b(d,y),b(g,y),b(v,y),b(w,y);var S={},k={};Object.defineProperty(k,"__esModule",{value:!0});var E={};Object.defineProperty(E,"__esModule",{value:!0});var O={};Object.defineProperty(O,"__esModule",{value:!0});var x={};Object.defineProperty(x,"__esModule",{value:!0});var D,M,P,T,C={};Object.defineProperty(C,"__esModule",{value:!0}),C.LDConcurrentExecution=C.LDSerialExecution=C.LDExecution=C.LDExecutionOrdering=void 0,(M=D||(C.LDExecutionOrdering=D={}))[M.Fixed=0]="Fixed",M[M.Random=1]="Random",(T=P||(C.LDExecution=P={}))[T.Serial=0]="Serial",T[T.Concurrent=1]="Concurrent";C.LDSerialExecution=class{constructor(e){this.ordering=e,this.type=P.Serial}};C.LDConcurrentExecution=class{constructor(){this.type=P.Concurrent}},function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i(k,e),i(E,e),i(O,e),i(x,e),i(C,e)}(S);var F={};Object.defineProperty(F,"__esModule",{value:!0});var I={};Object.defineProperty(I,"__esModule",{value:!0});var j={};Object.defineProperty(j,"__esModule",{value:!0});var R={};Object.defineProperty(R,"__esModule",{value:!0});var A={};Object.defineProperty(A,"__esModule",{value:!0});var V={},N={};Object.defineProperty(N,"__esModule",{value:!0});var L={};Object.defineProperty(L,"__esModule",{value:!0}),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i(N,e),i(L,e)}(V);var K={},$={};Object.defineProperty($,"__esModule",{value:!0});var U={};Object.defineProperty(U,"__esModule",{value:!0});var z={};Object.defineProperty(z,"__esModule",{value:!0});var B={};Object.defineProperty(B,"__esModule",{value:!0});var q={};Object.defineProperty(q,"__esModule",{value:!0});var H={};Object.defineProperty(H,"__esModule",{value:!0});var W={};Object.defineProperty(W,"__esModule",{value:!0});var J={};Object.defineProperty(J,"__esModule",{value:!0});var G={};Object.defineProperty(G,"__esModule",{value:!0});var X={};Object.defineProperty(X,"__esModule",{value:!0}),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i($,e),i(U,e),i(z,e),i(B,e),i(q,e),i(j,e),i(H,e),i(W,e),i(J,e),i(G,e),i(X,e)}(K);var Y={},Q={};Object.defineProperty(Q,"__esModule",{value:!0});var Z={};Object.defineProperty(Z,"__esModule",{value:!0}),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i(Q,e),i(R,e),i(Z,e)}(Y),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.subsystems=e.interfaces=e.integrations=void 0,i(u,e),i(S,e),i(F,e),i(I,e),i(j,e),i(R,e),i(A,e),e.integrations=V,e.interfaces=K,e.subsystems=Y}(l);var ee={},te={};Object.defineProperty(te,"__esModule",{value:!0});te.default=class{constructor(e){this._keyMap=new Map,this._head=0,this._tail=0,this._size=0;const{max:t}=e;this._max=t,this._values=new Array(t),this._keys=new Array(t),this._next=new Uint32Array(t),this._prev=new Uint32Array(t),e.maxAge?(this._lastUpdated=new Array(t).fill(0),this._maxAge=e.maxAge):(this._lastUpdated=[],this._maxAge=0)}set(e,t){let i=this._keyMap.get(e);void 0===i?(i=this._index(),this._keys[i]=e,this._keyMap.set(e,i),this._next[this._tail]=i,this._prev[i]=this._tail,this._tail=i,this._size+=1):this._setTail(i),this._values[i]=t,this._maxAge&&(this._lastUpdated[i]=Date.now())}get(e){const t=this._keyMap.get(e);if(void 0!==t){if(this._maxAge){const e=this._lastUpdated[t];if(Date.now()-e>this._maxAge)return}return this._setTail(t),this._maxAge&&(this._lastUpdated[t]=Date.now()),this._values[t]}}clear(){this._head=0,this._tail=0,this._size=0,this._values.fill(void 0),this._keys.fill(void 0),this._next.fill(0),this._prev.fill(0),this._keyMap.clear()}_index(){return 0===this._size?this._tail:this._size===this._max?this._evict():this._size}_evict(){const{_head:e}=this,t=this._keys[e];return this._head=this._next[e],this._keyMap.delete(t),this._size-=1,e}_link(e,t){this._prev[t]=e,this._next[e]=t}_setTail(e){e!==this._tail&&(e===this._head?this._head=this._next[e]:this._link(this._prev[e],this._next[e]),this._link(this._tail,e),this._tail=e)}},Object.defineProperty(ee,"__esModule",{value:!0});const ie=o,re=s,ne=te;ee.default=class{constructor(e,t,i,r){this._store=e,this._logger=i,this._crypto=r,this.statusProvider=new re.default((async()=>this._pollStoreAndUpdateStatus())),this._staleTimeMs=1e3*(ie.TypeValidators.Number.is(t.staleAfter)&&t.staleAfter>0?t.staleAfter:120);const n=1e3*(ie.TypeValidators.Number.is(t.statusPollInterval)&&t.statusPollInterval>0?t.statusPollInterval:5);this._pollHandle=e?setInterval((()=>this._pollStoreAndUpdateStatus()),n):null,e&&(this._cache=new ne.default({max:t.userCacheSize||1e3,maxAge:1e3*(t.userCacheTime||5)}))}close(){this._pollHandle&&(clearInterval(this._pollHandle),this._pollHandle=void 0),this._store&&this._store.close()}async getUserMembership(e){var t,i,r;if(!this._store)return;const n=null===(t=this._cache)||void 0===t?void 0:t.get(e);let s;if(n)s=n.membership;else try{s=await this._store.getUserMembership(this._hashForUserKey(e));const t={membership:s};null===(i=this._cache)||void 0===i||i.set(e,t)}catch(e){return null===(r=this._logger)||void 0===r||r.error(`Big Segment store membership query returned error: ${e}`),[null,"STORE_ERROR"]}this.statusProvider.getStatus()||await this._pollStoreAndUpdateStatus();const a=this.statusProvider.getStatus();return a.available?[s||null,a.stale?"STALE":"HEALTHY"]:[s||null,"STORE_ERROR"]}async _pollStoreAndUpdateStatus(){var e,t,i;if(!this._store)return void this.statusProvider.setStatus({available:!1,stale:!1});let r;null===(e=this._logger)||void 0===e||e.debug("Querying Big Segment store status");try{const e=await this._store.getMetadata();r={available:!0,stale:!e||!e.lastUpToDate||this._isStale(e.lastUpToDate)}}catch(e){null===(t=this._logger)||void 0===t||t.error(`Big Segment store status query returned error: ${e}`),r={available:!1,stale:!1}}const n=this.statusProvider.getStatus();n&&n.available===r.available&&n.stale===r.stale||(null===(i=this._logger)||void 0===i||i.debug("Big Segment store status changed from %s to %s",JSON.stringify(n),JSON.stringify(r)),this.statusProvider.setStatus(r),this.statusProvider.notify())}_hashForUserKey(e){const t=this._crypto.createHash("sha256");if(t.update(e),!t.digest)throw new Error("Platform must implement digest or asyncDigest");return t.digest("base64")}_isStale(e){return Date.now()-e>=this._staleTimeMs}};var se={},ae={},oe={};Object.defineProperty(oe,"__esModule",{value:!0});class le{static getKeyFromPath(e,t){return t.startsWith(e.streamApiPath)?t.substring(e.streamApiPath.length):void 0}}le.Features={namespace:"features",streamApiPath:"/flags/"},le.Segments={namespace:"segments",streamApiPath:"/segments/"},oe.default=le,Object.defineProperty(ae,"__esModule",{value:!0}),ae.deserializeSegment=ae.serializeSegment=ae.deserializeFlag=ae.serializeFlag=ae.deserializeDelete=ae.deserializePatch=ae.deserializePoll=ae.deserializeAll=ae.processSegment=ae.processFlag=ae.replacer=ae.nullReplacer=void 0;const ue=o,ce=oe,de=100;function he(e,t){const i=[];if(null==e)return;const r=Object.entries(e).filter((([e,i])=>!(null==t?void 0:t.includes(e))));for(i.push(...r.map((([t,i])=>({key:t,value:i,parent:e}))));i.length;){const e=i.pop();null!==e.value||Array.isArray(e.parent)?"object"==typeof e.value&&null!==e.value&&i.push(...Object.entries(e.value).map((([t,i])=>({key:t,value:i,parent:e.value})))):delete e.parent[e.key]}}function fe(e,t){if(!(t instanceof ue.AttributeReference||Array.isArray(t)&&t[0]&&t[0]instanceof ue.AttributeReference))return null==t||(t.generated_includedSet&&(t.included=[...t.generated_includedSet],delete t.generated_includedSet),t.generated_excludedSet&&(t.excluded=[...t.generated_excludedSet],delete t.generated_excludedSet),t.includedContexts&&t.includedContexts.forEach((e=>{e.generated_valuesSet&&(e.values=[...e.generated_valuesSet]),delete e.generated_valuesSet})),t.excludedContexts&&t.excludedContexts.forEach((e=>{e.generated_valuesSet&&(e.values=[...e.generated_valuesSet]),delete e.generated_valuesSet}))),t}function ge(e){e&&e.bucketBy&&(e.bucketByAttributeReference=new ue.AttributeReference(e.bucketBy,!e.contextKind))}function ve(e){var t;if(he(e,["variations"]),e.fallthrough&&e.fallthrough.rollout){ge(e.fallthrough.rollout)}null===(t=null==e?void 0:e.rules)||void 0===t||t.forEach((e=>{var t;ge(e.rollout),null===(t=null==e?void 0:e.clauses)||void 0===t||t.forEach((e=>{e&&e.attribute?e.attributeReference=new ue.AttributeReference(e.attribute,!e.contextKind):e&&(e.attributeReference=ue.AttributeReference.InvalidReference)}))}))}function _e(e){var t,i,r,n,s;he(e),(null===(t=null==e?void 0:e.included)||void 0===t?void 0:t.length)&&e.included.length>de&&(e.generated_includedSet=new Set(e.included),delete e.included),(null===(i=null==e?void 0:e.excluded)||void 0===i?void 0:i.length)&&e.excluded.length>de&&(e.generated_excludedSet=new Set(e.excluded),delete e.excluded),(null===(r=null==e?void 0:e.includedContexts)||void 0===r?void 0:r.length)&&e.includedContexts.forEach((e=>{var t;(null===(t=null==e?void 0:e.values)||void 0===t?void 0:t.length)&&e.values.length>de&&(e.generated_valuesSet=new Set(e.values),e.values=[])})),(null===(n=null==e?void 0:e.excludedContexts)||void 0===n?void 0:n.length)&&e.excludedContexts.forEach((e=>{var t;(null===(t=null==e?void 0:e.values)||void 0===t?void 0:t.length)&&e.values.length>de&&(e.generated_valuesSet=new Set(e.values),e.values=[])})),null===(s=null==e?void 0:e.rules)||void 0===s||s.forEach((e=>{var t;e.bucketBy&&(e.bucketByAttributeReference=new ue.AttributeReference(e.bucketBy,!e.rolloutContextKind)),null===(t=null==e?void 0:e.clauses)||void 0===t||t.forEach((e=>{e&&e.attribute?e.attributeReference=new ue.AttributeReference(e.attribute,!e.contextKind):e&&(e.attributeReference=ue.AttributeReference.InvalidReference)}))}))}function pe(e){try{return JSON.parse(e)}catch(e){return}}ae.nullReplacer=he,ae.replacer=fe,ae.processFlag=ve,ae.processSegment=_e,ae.deserializeAll=function(e){var t,i;const r=pe(e);if(r)return Object.values((null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.flags)||[]).forEach((e=>{ve(e)})),Object.values((null===(i=null==r?void 0:r.data)||void 0===i?void 0:i.segments)||[]).forEach((e=>{_e(e)})),r},ae.deserializePoll=function(e){const t=pe(e);if(t)return Object.values((null==t?void 0:t.flags)||[]).forEach((e=>{ve(e)})),Object.values((null==t?void 0:t.segments)||[]).forEach((e=>{_e(e)})),t},ae.deserializePatch=function(e){const t=pe(e);if(t)return t.path.startsWith(ce.default.Features.streamApiPath)?(ve(t.data),t.kind=ce.default.Features):t.path.startsWith(ce.default.Segments.streamApiPath)&&(_e(t.data),t.kind=ce.default.Segments),t},ae.deserializeDelete=function(e){const t=pe(e);if(t)return t.path.startsWith(ce.default.Features.streamApiPath)?t.kind=ce.default.Features:t.path.startsWith(ce.default.Segments.streamApiPath)&&(t.kind=ce.default.Segments),t},ae.serializeFlag=function(e){return JSON.stringify(e,fe)},ae.deserializeFlag=function(e){const t=pe(e);if(t)return ve(t),t},ae.serializeSegment=function(e){return JSON.stringify(e,fe)},ae.deserializeSegment=function(e){const t=pe(e);if(t)return _e(t),t},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createStreamListeners=e.createDeleteListener=e.createPatchListener=e.createPutListener=void 0;const t=ae,i=oe;e.createPutListener=(e,r,n=()=>{})=>({deserializeData:t.deserializeAll,processJson:async({data:{flags:t,segments:s}})=>{const a={[i.default.Features.namespace]:t,[i.default.Segments.namespace]:s};null==r||r.debug("Initializing all data"),e.init(a,n)}});e.createPatchListener=(e,r,n=()=>{})=>({deserializeData:t.deserializePatch,processJson:async({data:t,kind:s,path:a})=>{if(s){const o=i.default.getKeyFromPath(s,a);o&&(null==r||r.debug(`Updating ${o} in ${s.namespace}`),e.upsert(s,t,n))}}});e.createDeleteListener=(e,r,n=()=>{})=>({deserializeData:t.deserializeDelete,processJson:async({kind:t,path:s,version:a})=>{if(t){const o=i.default.getKeyFromPath(t,s);o&&(null==r||r.debug(`Deleting ${o} in ${t.namespace}`),e.upsert(t,{key:o,version:a,deleted:!0},n))}}});e.createStreamListeners=(t,i,r)=>{const n=new Map;return n.set("put",(0,e.createPutListener)(t,i,null==r?void 0:r.put)),n.set("patch",(0,e.createPatchListener)(t,i,null==r?void 0:r.patch)),n.set("delete",(0,e.createDeleteListener)(t,i,null==r?void 0:r.delete)),n}}(se);var ye={},me={},be={};Object.defineProperty(be,"__esModule",{value:!0});be.default=class{constructor(){this._itemsByNamespace={}}get(e,t){var i;return null===(i=this._itemsByNamespace[e])||void 0===i?void 0:i[t]}set(e,t,i){e in this._itemsByNamespace||(this._itemsByNamespace[e]={}),this._itemsByNamespace[e][t]=i}remove(e,t){const i=this._itemsByNamespace[e];i&&delete i[t]}removeAll(){this._itemsByNamespace={}}enumerate(e){Object.entries(this._itemsByNamespace).forEach((([t,i])=>{Object.entries(i).forEach((([i,r])=>{e(t,i,r)}))}))}mergeFrom(e){e.enumerate(this.set.bind(this))}},Object.defineProperty(me,"__esModule",{value:!0});const we=be;me.default=class{constructor(){this._dependenciesFrom=new we.default,this._dependenciesTo=new we.default}updateDependenciesFrom(e,t,i){const r=this._dependenciesFrom.get(e,t);null==r||r.enumerate(((i,r)=>{const n=this._dependenciesTo.get(i,r);null==n||n.remove(e,t)})),this._dependenciesFrom.set(e,t,i),null==i||i.enumerate(((i,r)=>{let n=this._dependenciesTo.get(i,r);n||(n=new we.default,this._dependenciesTo.set(i,r,n)),n.set(e,t,!0)}))}updateModifiedItems(e,t,i){if(!e.get(t,i)){e.set(t,i,!0);const r=this._dependenciesTo.get(t,i);null==r||r.enumerate(((t,i)=>{this.updateModifiedItems(e,t,i)}))}}reset(){this._dependenciesFrom.removeAll(),this._dependenciesTo.removeAll()}},Object.defineProperty(ye,"__esModule",{value:!0});const Se=oe,ke=me,Ee=be;function Oe(e,t){var i,r;const n=new Ee.default,s=e===Se.default.Features.namespace,a=e===Se.default.Segments.namespace;if(s){const r=t;null===(i=null==r?void 0:r.prerequisites)||void 0===i||i.forEach((t=>{n.set(e,t.key,!0)}))}if(s||a){const e=t;null===(r=null==e?void 0:e.rules)||void 0===r||r.forEach((e=>{var t;null===(t=e.clauses)||void 0===t||t.forEach((e=>{"segmentMatch"===e.op&&e.values.forEach((e=>{n.set(Se.default.Segments.namespace,e,!0)}))}))}))}return n}ye.default=class{constructor(e,t,i){this._featureStore=e,this._hasEventListeners=t,this._onChange=i,this._dependencyTracker=new ke.default}init(e,t){const i=this._hasEventListeners(),r=r=>{this._featureStore.init(e,(()=>{Promise.resolve().then((()=>{if(this._dependencyTracker.reset(),Object.entries(e).forEach((([e,t])=>{Object.keys(t||{}).forEach((i=>{const r=t[i];this._dependencyTracker.updateDependenciesFrom(e,i,Oe(e,r))}))})),i){const t=new Ee.default;Object.keys(e).forEach((i=>{const n=(null==r?void 0:r[i])||{},s=e[i],a=Object.assign(Object.assign({},n),s);Object.keys(a).forEach((e=>{this.addIfModified(i,e,n&&n[e],s&&s[e],t)}))})),this.sendChangeEvents(t)}})),null==t||t()}))};i?this._featureStore.all(Se.default.Features,(e=>{this._featureStore.all(Se.default.Segments,(t=>{const i={[Se.default.Features.namespace]:e,[Se.default.Segments.namespace]:t};r(i)}))})):r()}upsert(e,t,i){const{key:r}=t,n=this._hasEventListeners(),s=s=>{this._featureStore.upsert(e,t,(()=>{Promise.resolve().then((()=>{if(this._dependencyTracker.updateDependenciesFrom(e.namespace,r,Oe(e.namespace,t)),n){const i=new Ee.default;this.addIfModified(e.namespace,r,s,t,i),this.sendChangeEvents(i)}})),null==i||i()}))};n?this._featureStore.get(e,r,s):s()}addIfModified(e,t,i,r,n){r&&i&&r.version<=i.version||this._dependencyTracker.updateModifiedItems(n,e,t)}sendChangeEvents(e){e.enumerate(((e,t)=>{e===Se.default.Features.namespace&&this._onChange(t)}))}};var xe={},De={},Me={},Pe={};Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.default=function(e){return new Promise((t=>{e((e=>{t(e)}))}))},Object.defineProperty(Me,"__esModule",{value:!0});const Te=Pe;Me.default=class{constructor(e){this._store=e}async get(e,t){return(0,Te.default)((i=>{this._store.get(e,t,i)}))}async all(e){return(0,Te.default)((t=>{this._store.all(e,t)}))}async init(e){return(0,Te.default)((t=>{this._store.init(e,t)}))}async delete(e,t,i){return(0,Te.default)((r=>{this._store.delete(e,t,i,r)}))}async upsert(e,t){return(0,Te.default)((i=>{this._store.upsert(e,t,i)}))}async initialized(){return(0,Te.default)((e=>{this._store.initialized(e)}))}close(){this._store.close()}};var Ce={},Fe={};function Ie(e){return Date.now()>e.expiration}Object.defineProperty(Fe,"__esModule",{value:!0});Fe.default=class{constructor(e){this._options=e,this._storage=new Map,this._checkIntervalHandle=setInterval((()=>{this._purgeStale()}),1e3*e.checkInterval)}get(e){const t=this._storage.get(e);if(!t||!Ie(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)=>{Ie(e)&&this._storage.delete(t)}))}get size(){return this._storage.size}};var je={};Object.defineProperty(je,"__esModule",{value:!0}),je.persistentStoreKinds=void 0;const Re=ae,Ae=oe;je.persistentStoreKinds={segments:{namespace:Ae.default.Segments.namespace,deserialize:e=>{const t=(0,Re.deserializeSegment)(e);if(t)return{version:t.version,item:t}},serialize:e=>{const t=(0,Re.serializeSegment)(e);return{version:e.version,deleted:e.deleted,serializedItem:t}},priority:0},features:{namespace:Ae.default.Features.namespace,deserialize:e=>{const t=(0,Re.deserializeFlag)(e);if(t)return{version:t.version,item:t}},serialize:e=>{const t=(0,Re.serializeFlag)(e);return{version:e.version,deleted:e.deleted,serializedItem:t}},priority:1}};var Ve={};Object.defineProperty(Ve,"__esModule",{value:!0});const Ne=je;function Le(e,t){const i=[],r=new Set(Object.keys(t)),n=s=>{if(!r.has(s))return;r.delete(s);const a=t[s];var o;"features"===e.namespace&&(o=a,o.prerequisites&&o.prerequisites.length?o.prerequisites.map((e=>e.key)):[]).forEach((e=>{n(e)})),i.push({key:s,item:e.serialize(a)})};for(;r.size>0;){const e=r.values().next().value;n(e)}return i}Ve.default=function(e){const t=[];return Object.keys(e).forEach((i=>{const r=Ne.persistentStoreKinds[i];t.push({key:r,item:Le(r,e[i])})})),t.sort(((e,t)=>e.key.priority-t.key.priority)),t};var Ke={};Object.defineProperty(Ke,"__esModule",{value:!0});Ke.default=class{constructor(){this._queue=[]}enqueue(e,t){this._queue.push([e,t]),1===this._queue.length&&this.executePendingUpdates()}executePendingUpdates(){if(this._queue.length>0){const[e,t]=this._queue[0];e((()=>{this._queue.shift(),this._queue.length>0&&setTimeout((()=>this.executePendingUpdates()),0),null==t||t()}))}}},Object.defineProperty(Ce,"__esModule",{value:!0});const $e=Fe,Ue=je,ze=Ve,Be=Ke;function qe(e,t){return`${e.namespace}:${t}`}function He(e){return`$all:${e.namespace}`}const We="$checkedInit";function Je(e){return!e||e.item.deleted?null:e.item}function Ge(e){return{version:e,item:{version:e,deleted:!0}}}function Xe(e,t){if(t.deleted||!t.serializedItem)return Ge(t.version);const i=e.deserialize(t.serializedItem);return void 0===i?Ge(t.version):0===i.version||i.version===t.version||void 0===i.item?i:{version:t.version,item:i.item}}Ce.default=class{constructor(e,t){this._core=e,this._isInitialized=!1,this._queue=new Be.default,t&&(this._itemCache=new $e.default({ttl:t,checkInterval:600}),this._allItemsCache=new $e.default({ttl:t,checkInterval:600}))}init(e,t){this._queue.enqueue((t=>{this._core.init((0,ze.default)(e),(()=>{this._isInitialized=!0,this._itemCache&&(this._itemCache.clear(),this._allItemsCache.clear(),Object.keys(e).forEach((t=>{const i=Ue.persistentStoreKinds[t],r=e[t];this._allItemsCache.set(He(i),r),Object.keys(r).forEach((e=>{const t=r[e],n={version:t.version,item:t};this._itemCache.set(qe(i,e),n)}))}))),t()}))}),t)}get(e,t,i){if(this._itemCache){const r=this._itemCache.get(qe(e,t));if(r)return void i(Je(r))}const r=Ue.persistentStoreKinds[e.namespace];this._core.get(r,t,(n=>{var s;if(n&&n.serializedItem){const a=Xe(r,n);return null===(s=this._itemCache)||void 0===s||s.set(qe(e,t),a),void i(Je(a))}i(null)}))}initialized(e){var t;this._isInitialized?e(!0):(null===(t=this._itemCache)||void 0===t?void 0:t.get(We))?e(!1):this._core.initialized((t=>{var i;this._isInitialized=t,this._isInitialized||null===(i=this._itemCache)||void 0===i||i.set(We,!0),e(this._isInitialized)}))}all(e,t){var i;const r=null===(i=this._allItemsCache)||void 0===i?void 0:i.get(He(e));if(r)return void t(r);const n=Ue.persistentStoreKinds[e.namespace];this._core.getAll(n,(i=>{var r;if(!i)return void t({});const s={};i.forEach((({key:e,item:t})=>{const i=Je(Xe(n,t));i&&(s[e]=i)})),null===(r=this._allItemsCache)||void 0===r||r.set(He(e),s),t(s)}))}upsert(e,t,i){this._queue.enqueue((i=>{this._allItemsCache&&this._allItemsCache.clear();const r=Ue.persistentStoreKinds[e.namespace];this._core.upsert(r,t.key,r.serialize(t),((n,s)=>{var a,o;if(!n&&s)if(s.serializedItem){const i=Xe(r,s);null===(a=this._itemCache)||void 0===a||a.set(qe(e,t.key),i)}else s.deleted&&(null===(o=this._itemCache)||void 0===o||o.set(t.key,{key:t.key,version:s.version,deleted:!0}));i()}))}),i)}delete(e,t,i,r){this.upsert(e,{key:t,version:i,deleted:!0},r)}close(){var e,t;null===(e=this._itemCache)||void 0===e||e.close(),null===(t=this._allItemsCache)||void 0===t||t.close(),this._core.close()}getDescription(){return this._core.getDescription()}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.deserializePoll=e.PersistentDataStoreWrapper=e.AsyncStoreFacade=void 0;const t=Me;e.AsyncStoreFacade=t.default;const i=Ce;e.PersistentDataStoreWrapper=i.default;const r=ae;Object.defineProperty(e,"deserializePoll",{enumerable:!0,get:function(){return r.deserializePoll}})}(De),Object.defineProperty(xe,"__esModule",{value:!0});const Ye=o,Qe=De,Ze=oe;xe.default=class{constructor(e,t,i,r=()=>{},n){this._requestor=t,this._featureStore=i,this._initSuccessHandler=r,this._errorHandler=n,this._stopped=!1,this._logger=e.logger,this._pollInterval=e.pollInterval}_poll(){var e;if(this._stopped)return;const t=e=>{var t,i,r;null===(t=this._logger)||void 0===t||t.error("Polling received invalid data"),null===(i=this._logger)||void 0===i||i.debug(`Invalid JSON follows: ${e}`),null===(r=this._errorHandler)||void 0===r||r.call(this,new Ye.LDPollingError(Ye.DataSourceErrorKind.InvalidData,"Malformed JSON data in polling response"))},i=Date.now();null===(e=this._logger)||void 0===e||e.debug("Polling LaunchDarkly for feature flag updates"),this._requestor.requestAllData(((e,r)=>{var n,s,a,o;const l=Date.now()-i,u=Math.max(1e3*this._pollInterval-l,0);if(null===(n=this._logger)||void 0===n||n.debug("Elapsed: %d ms, sleeping for %d ms",l,u),e){const{status:t}=e;if(t&&!(0,Ye.isHttpRecoverable)(t)){const i=(0,Ye.httpErrorMessage)(e,"polling request");return null===(s=this._logger)||void 0===s||s.error(i),void(null===(a=this._errorHandler)||void 0===a||a.call(this,new Ye.LDPollingError(Ye.DataSourceErrorKind.ErrorResponse,i,t)))}null===(o=this._logger)||void 0===o||o.warn((0,Ye.httpErrorMessage)(e,"polling request","will retry"))}else if(r){const e=(0,Qe.deserializePoll)(r);if(e){const t={[Ze.default.Features.namespace]:e.flags,[Ze.default.Segments.namespace]:e.segments};return void this._featureStore.init(t,(()=>{this._initSuccessHandler(),this._timeoutHandle=setTimeout((()=>{this._poll()}),u)}))}t(r)}this._timeoutHandle=setTimeout((()=>{this._poll()}),u)}))}start(){this._poll()}stop(){this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),this._stopped=!0}close(){this.stop()}};var et={};Object.defineProperty(et,"__esModule",{value:!0});const tt=o;et.default=class{constructor(e,t,i){this._requests=t,this._eTagCache={},this._headers=Object.assign({},i),this._uri=(0,tt.getPollingUri)(e.serviceEndpoints,"/sdk/latest-all",[])}async _requestWithETagCache(e,t){const i=this._eTagCache[e],r=null==i?void 0:i.etag,n=r?Object.assign(Object.assign({},t),{headers:Object.assign(Object.assign({},t.headers),{"if-none-match":r})}):t,s=await this._requests.fetch(e,n);if(304===s.status&&i)return{res:s,body:i.body};const a=s.headers.get("etag"),o=await s.text();return a&&(this._eTagCache[e]={etag:a,body:o}),{res:s,body:o}}async requestAllData(e){const t={method:"GET",headers:this._headers};try{const{res:i,body:r}=await this._requestWithETagCache(this._uri,t);if(200!==i.status&&304!==i.status){return e(new tt.LDPollingError(tt.DataSourceErrorKind.ErrorResponse,`Unexpected status code: ${i.status}`,i.status),void 0)}return e(void 0,304===i.status?null:r)}catch(t){return e(t,void 0)}}};var it={},rt={},nt={};Object.defineProperty(nt,"__esModule",{value:!0});nt.default=class{constructor(){this._allData={},this._initCalled=!1}_addItem(e,t,i){let r=this._allData[e.namespace];if(r||(r={},this._allData[e.namespace]=r),Object.hasOwnProperty.call(r,t)){const e=r[t];(!e||e.version<i.version)&&(r[t]=i)}else r[t]=i}get(e,t,i){const r=this._allData[e.namespace];if(r&&Object.prototype.hasOwnProperty.call(r,t)){const e=r[t];if(e&&!e.deleted)return null==i?void 0:i(e)}return null==i?void 0:i(null)}all(e,t){var i;const r={},n=null!==(i=this._allData[e.namespace])&&void 0!==i?i:{};Object.entries(n).forEach((([e,t])=>{t&&!t.deleted&&(r[e]=t)})),null==t||t(r)}init(e,t){this._initCalled=!0,this._allData=e,null==t||t()}delete(e,t,i,r){const n={version:i,deleted:!0};this._addItem(e,t,n),null==r||r()}upsert(e,t,i){this._addItem(e,t.key,t),null==i||i()}initialized(e){return null==e?void 0:e(this._initCalled)}close(){}getDescription(){return"memory"}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.defaultValues=void 0;const t=o,i=nt,r={baseUri:t.TypeValidators.String,streamUri:t.TypeValidators.String,eventsUri:t.TypeValidators.String,timeout:t.TypeValidators.Number,capacity:t.TypeValidators.Number,logger:t.TypeValidators.Object,featureStore:t.TypeValidators.ObjectOrFactory,bigSegments:t.TypeValidators.Object,updateProcessor:t.TypeValidators.ObjectOrFactory,flushInterval:t.TypeValidators.Number,pollInterval:t.TypeValidators.numberWithMin(30),proxyOptions:t.TypeValidators.Object,offline:t.TypeValidators.Boolean,stream:t.TypeValidators.Boolean,streamInitialReconnectDelay:t.TypeValidators.Number,useLdd:t.TypeValidators.Boolean,sendEvents:t.TypeValidators.Boolean,allAttributesPrivate:t.TypeValidators.Boolean,privateAttributes:t.TypeValidators.StringArray,contextKeysCapacity:t.TypeValidators.Number,contextKeysFlushInterval:t.TypeValidators.Number,tlsParams:t.TypeValidators.Object,diagnosticOptOut:t.TypeValidators.Boolean,diagnosticRecordingInterval:t.TypeValidators.numberWithMin(60),wrapperName:t.TypeValidators.String,wrapperVersion:t.TypeValidators.String,application:t.TypeValidators.Object,payloadFilterKey:t.TypeValidators.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:t.TypeValidators.createTypeArray("Hook[]",{})};e.defaultValues={baseUri:"https://sdk.launchdarkly.com",streamUri:"https://stream.launchdarkly.com",eventsUri:t.ServiceEndpoints.DEFAULT_EVENTS,stream:!0,streamInitialReconnectDelay:1,sendEvents:!0,timeout:5,capacity:1e4,flushInterval:5,pollInterval:30,offline:!1,useLdd:!1,allAttributesPrivate:!1,privateAttributes:[],contextKeysCapacity:1e3,contextKeysFlushInterval:300,diagnosticOptOut:!1,diagnosticRecordingInterval:900,featureStore:()=>new i.default};e.default=class{constructor(i={},n={}){i=i||{},this.logger=i.logger;const{errors:s,validatedOptions:a}=function(i){const n=[],s=Object.assign({},e.defaultValues);return Object.keys(i).forEach((a=>{var o;const l=i[a],u=r[a];if(u)if(u.is(l))s[a]=l;else if("boolean"===u.getType())n.push(t.OptionMessages.wrongOptionTypeBoolean(a,typeof l)),s[a]=!!l;else if(u instanceof t.NumberWithMinimum&&t.TypeValidators.Number.is(l)){const{min:e}=u;n.push(t.OptionMessages.optionBelowMinimum(a,l,e)),s[a]=e}else n.push(t.OptionMessages.wrongOptionType(a,u.getType(),typeof l)),s[a]=e.defaultValues[a];else null===(o=i.logger)||void 0===o||o.warn(t.OptionMessages.unknownOption(a))})),{errors:n,validatedOptions:s}}(i);s.forEach((e=>{var t;null===(t=this.logger)||void 0===t||t.warn(e)})),function(e,i){var r,n,s;const{baseUri:a,streamUri:o,eventsUri:l}=e,u=null!=o,c=null!=a,d=null!=l;u===c&&u===d||(!u&&i.stream&&(null===(r=i.logger)||void 0===r||r.warn(t.OptionMessages.partialEndpoint("streamUri"))),c||null===(n=i.logger)||void 0===n||n.warn(t.OptionMessages.partialEndpoint("baseUri")),!d&&i.sendEvents&&(null===(s=i.logger)||void 0===s||s.warn(t.OptionMessages.partialEndpoint("eventsUri"))))}(i,a),this.serviceEndpoints=new t.ServiceEndpoints(a.streamUri,a.baseUri,a.eventsUri,n.analyticsEventPath,n.diagnosticEventPath,n.includeAuthorizationHeader,a.payloadFilterKey),this.eventsCapacity=a.capacity,this.timeout=a.timeout,this.bigSegments=a.bigSegments,this.flushInterval=a.flushInterval,this.pollInterval=a.pollInterval,this.proxyOptions=a.proxyOptions,this.offline=a.offline,this.stream=a.stream,this.streamInitialReconnectDelay=a.streamInitialReconnectDelay,this.useLdd=a.useLdd,this.sendEvents=a.sendEvents,this.allAttributesPrivate=a.allAttributesPrivate,this.privateAttributes=a.privateAttributes,this.contextKeysCapacity=a.contextKeysCapacity,this.contextKeysFlushInterval=a.contextKeysFlushInterval,this.tlsParams=a.tlsParams,this.diagnosticOptOut=a.diagnosticOptOut,this.wrapperName=a.wrapperName,this.payloadFilterKey=a.payloadFilterKey,this.wrapperVersion=a.wrapperVersion,this.tags=new t.ApplicationTags(a),this.diagnosticRecordingInterval=a.diagnosticRecordingInterval,t.TypeValidators.Function.is(a.updateProcessor)?this.updateProcessorFactory=a.updateProcessor:this.updateProcessorFactory=()=>a.updateProcessor,t.TypeValidators.Function.is(a.featureStore)?this.featureStoreFactory=a.featureStore:this.featureStoreFactory=()=>a.featureStore,this.hooks=a.hooks}}}(rt),Object.defineProperty(it,"__esModule",{value:!0});const st=o,at=rt;it.default=(e,t,i)=>{var r,n,s,a,o,l;return{customBaseURI:e.serviceEndpoints.polling!==at.defaultValues.baseUri,customStreamURI:e.serviceEndpoints.streaming!==at.defaultValues.streamUri,customEventsURI:e.serviceEndpoints.events!==at.defaultValues.eventsUri,eventsCapacity:e.eventsCapacity,connectTimeoutMillis:(0,st.secondsToMillis)(e.timeout),socketTimeoutMillis:(0,st.secondsToMillis)(e.timeout),eventsFlushIntervalMillis:(0,st.secondsToMillis)(e.flushInterval),pollingIntervalMillis:(0,st.secondsToMillis)(e.pollInterval),reconnectTimeMillis:(0,st.secondsToMillis)(e.streamInitialReconnectDelay),contextKeysFlushIntervalMillis:(0,st.secondsToMillis)(e.contextKeysFlushInterval),diagnosticRecordingIntervalMillis:(0,st.secondsToMillis)(e.diagnosticRecordingInterval),streamingDisabled:!e.stream,usingRelayDaemon:e.useLdd,offline:e.offline,allAttributesPrivate:e.allAttributesPrivate,contextKeysCapacity:e.contextKeysCapacity,usingProxy:!!(null===(n=(r=t.requests).usingProxy)||void 0===n?void 0:n.call(r)),usingProxyAuthenticator:!!(null===(a=(s=t.requests).usingProxyAuth)||void 0===a?void 0:a.call(s)),dataStoreType:null!==(l=null===(o=i.getDescription)||void 0===o?void 0:o.call(i))&&void 0!==l?l:"memory"}};var ot={};Object.defineProperty(ot,"__esModule",{value:!0}),ot.allAsync=ot.firstSeriesAsync=ot.allSeriesAsync=ot.firstResult=void 0,ot.firstResult=function(e,t){let i;return null==e||e.some(((e,r)=>(i=t(e,r),!!i))),i};function lt(e,t,i,r,n){e?r<(null==e?void 0:e.length)?t(e[r],r,(s=>{if(i){if(!s)return void n(!1)}else if(s)return void n(!0);e.length>50?Promise.resolve().then((()=>{lt(e,t,i,r+1,n)})):lt(e,t,i,r+1,n)})):n(i):n(!1)}ot.allSeriesAsync=function(e,t,i){lt(e,t,!0,0,i)},ot.firstSeriesAsync=function(e,t,i){lt(e,t,!1,0,i)},ot.allAsync=function(e,t,i){e?Promise.all(null==e?void 0:e.map((e=>new Promise((i=>{t(e,i)}))))).then((e=>{i(e.every((e=>e)))})):i(!1)};var ut={},ct={};Object.defineProperty(ct,"__esModule",{value:!0});class dt{static prerequisiteFailed(e){return{kind:"PREREQUISITE_FAILED",prerequisiteKey:e}}static ruleMatch(e,t){return{kind:"RULE_MATCH",ruleId:e,ruleIndex:t}}}dt.Fallthrough={kind:"FALLTHROUGH"},dt.Off={kind:"OFF"},dt.TargetMatch={kind:"TARGET_MATCH"},ct.default=dt,Object.defineProperty(ut,"__esModule",{value:!0});const ht=ct;class ft{constructor(e,t,i){this.isError=e,this.detail=t,this.message=i,this.isError=e,this.detail=t,this.message=i}get isOff(){return this.detail.reason.kind===ht.default.Off.kind}setDefault(e){this.detail.value=e}static forError(e,t,i){return new ft(!0,{value:null!=i?i:null,variationIndex:null,reason:{kind:"ERROR",errorKind:e}},t)}static forSuccess(e,t,i){return new ft(!1,{value:e,variationIndex:void 0===i?null:i,reason:t})}}ut.default=ft;var gt={},vt={};Object.defineProperty(vt,"__esModule",{value:!0});vt.default=class{constructor(e){this._crypto=e}_sha1Hex(e){const t=this._crypto.createHash("sha1");if(t.update(e),!t.digest)throw new Error("Platform must implement digest or asyncDigest");return t.digest("hex")}bucket(e,t,i,r,n="user",s){const a=function(e){return"string"==typeof e?e:Number.isInteger(e)?String(e):null}(e.valueForKind(i,n));if(null===a){return[0,e.kinds.indexOf(n)>=0]}const o=`${s?Number(s):`${t}.${r}`}.${a}`;return[parseInt(this._sha1Hex(o).substring(0,15),16)/0x1000000000000000,!0]}};var _t={},pt={};Object.defineProperty(pt,"__esModule",{value:!0}),pt.getBucketBy=pt.getOffVariation=pt.getVariation=void 0;const yt=o,mt=ut,{ErrorKinds:bt}=yt.internal,wt=new yt.AttributeReference("key");function St(e,t,i){return yt.TypeValidators.Number.is(t)&&t>=0&&t<e.variations.length?mt.default.forSuccess(e.variations[t],i,t):mt.default.forError(bt.MalformedFlag,"Invalid variation index in flag")}pt.getVariation=St,pt.getOffVariation=function(e,t){return yt.TypeValidators.Number.is(e.offVariation)?St(e,e.offVariation,t):mt.default.forSuccess(null,t)},pt.getBucketBy=function(e,t){var i;return null!==(i=e?void 0:t)&&void 0!==i?i:wt},Object.defineProperty(_t,"__esModule",{value:!0});const kt=o,Et=ot,Ot=ct,xt=pt;function Dt(e,t,i){const r=i.key(t.contextKind);if(void 0!==r){if(t.values.indexOf(r)>=0)return(0,xt.getVariation)(e,t.variation,Ot.default.TargetMatch)}}_t.default=function(e,t){var i;return(null===(i=e.contextTargets)||void 0===i?void 0:i.length)?(0,Et.firstResult)(e.contextTargets,(i=>{if(!i.contextKind||i.contextKind===kt.Context.UserKind){const r=(e.targets||[]).find((e=>e.variation===i.variation));return r?Dt(e,r,t):void 0}return Dt(e,i,t)})):(0,Et.firstResult)(e.targets,(i=>Dt(e,i,t)))};var Mt={};Object.defineProperty(Mt,"__esModule",{value:!0}),Mt.default=function(e){return`${e.key}.g${e.generation}`};var Pt={},Tt={};Object.defineProperty(Tt,"__esModule",{value:!0});const Ct=t,Ft=o,It=/^\d+(\.\d+)?(\.\d+)?/;function jt(e){if(Ft.TypeValidators.String.is(e)&&!e.startsWith("v")){const t=(0,Ct.parse)(e);if(t)return t;const i=It.exec(e);if(i){let t=i[0];for(let e=1;e<i.length;e+=1)void 0===i[e]&&(t+=".0");return t+=e.substring(i[0].length),(0,Ct.parse)(t)}}return null}function Rt(e){return(t,i)=>{const r=jt(t),n=jt(i);return!!(r&&n&&e(r,n))}}function At(e,t,i){return(r,n)=>!(!t.is(r)||!t.is(n))&&(i?e(i(r),i(n)):e(r,n))}function Vt(e){return"number"==typeof e?e:Date.parse(e)}const Nt={in:(e,t)=>e===t,endsWith:At(((e,t)=>e.endsWith(t)),Ft.TypeValidators.String),startsWith:At(((e,t)=>e.startsWith(t)),Ft.TypeValidators.String),matches:At(((e,t)=>function(e,t){try{return new RegExp(e).test(t)}catch(e){return!1}}(t,e)),Ft.TypeValidators.String),contains:At(((e,t)=>e.indexOf(t)>-1),Ft.TypeValidators.String),lessThan:At(((e,t)=>e<t),Ft.TypeValidators.Number),lessThanOrEqual:At(((e,t)=>e<=t),Ft.TypeValidators.Number),greaterThan:At(((e,t)=>e>t),Ft.TypeValidators.Number),greaterThanOrEqual:At(((e,t)=>e>=t),Ft.TypeValidators.Number),before:At(((e,t)=>e<t),Ft.TypeValidators.Date,Vt),after:At(((e,t)=>e>t),Ft.TypeValidators.Date,Vt),semVerEqual:Rt(((e,t)=>0===e.compare(t))),semVerLessThan:Rt(((e,t)=>e.compare(t)<0)),semVerGreaterThan:Rt(((e,t)=>e.compare(t)>0))};Tt.default=class{static is(e){return Object.prototype.hasOwnProperty.call(Nt,e)}static execute(e,t,i){var r,n;return null!==(n=null===(r=Nt[e])||void 0===r?void 0:r.call(Nt,t,i))&&void 0!==n&&n}},Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.maybeNegate=void 0;const Lt=Tt;function Kt(e,t){return e.negate?!t:t}function $t(e,t,i){return i.some((i=>Lt.default.execute(e,t,i)))}Pt.maybeNegate=Kt,Pt.default=function(e,t){const i=t.valueForKind(e.attributeReference,e.contextKind);return null!=i&&(Array.isArray(i)?Kt(e,i.some((t=>$t(e.op,t,e.values)))):Kt(e,$t(e.op,i,e.values)))};var Ut={};function zt(e,t,i,r){if(t)for(let i=0;i<t.length;i+=1){const r=t[i],n=e.key(r.contextKind);if(n)if(r.generated_valuesSet){if(r.generated_valuesSet.has(n))return!0}else if(r.values.includes(n))return!0}if(r){const t=e.key("user");if(t&&r.has(t))return!0}else if(i){const t=e.key("user");if(t&&i.includes(t))return!0}return!1}Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.default=function(e,t){if(zt(t,e.includedContexts,e.included,e.generated_includedSet))return!0;const i=zt(t,e.excludedContexts,e.excluded,e.generated_excludedSet);return i?!i:void 0},Object.defineProperty(gt,"__esModule",{value:!0});const Bt=o,qt=vt,Ht=ot,Wt=ut,Jt=_t,Gt=Mt,Xt=Pt,Yt=Ut,Qt=ct,Zt=pt,{ErrorKinds:ei}=Bt.internal,ti={HEALTHY:1,STALE:2,STORE_ERROR:3,NOT_CONFIGURED:4};function ii(e){return void 0!==e&&ti[e]||0}function ri(e,t){return void 0!==e&&ii(e)>ii(t)?e:t}function ni(e){return{error:!1,isMatch:e,result:void 0}}function si(e){return{error:!0,isMatch:!1,result:e}}gt.default=class{constructor(e,t){this._queries=t,this._bucketer=new qt.default(e.crypto)}async evaluate(e,t,i){return new Promise((r=>{this.evaluateCb(e,t,r,i)}))}evaluateCb(e,t,i,r){const n={};this._evaluateInternal(e,t,n,[],(e=>{n.bigSegmentsStatus&&(e.detail.reason=Object.assign(Object.assign({},e.detail.reason),{bigSegmentsStatus:n.bigSegmentsStatus})),n.prerequisites&&(e.prerequisites=n.prerequisites),e.events=n.events,i(e)}),!0,r)}_evaluateInternal(e,t,i,r,n,s,a){e.on?this._checkPrerequisites(e,t,i,r,(r=>{if(r)return void n(r);const s=(0,Jt.default)(e,t);s?n(s):this._evaluateRules(e,t,i,(i=>{n(i||this._variationForContext(e.fallthrough,t,e,Qt.default.Fallthrough))}))}),s,a):n((0,Zt.getOffVariation)(e,Qt.default.Off))}_checkPrerequisites(e,t,i,r,n,s,a){let o;e.prerequisites&&e.prerequisites.length?(0,Ht.allSeriesAsync)(e.prerequisites,((n,l,u)=>{if(-1!==r.indexOf(n.key))return o=Wt.default.forError(ei.MalformedFlag,`Prerequisite of ${e.key} causing a circular reference. This is probably a temporary condition due to an incomplete update.`),void u(!0);const c=[...r,n.key];this._queries.getFlag(n.key,(r=>{if(!r)return o=(0,Zt.getOffVariation)(e,Qt.default.prerequisiteFailed(n.key)),void u(!1);this._evaluateInternal(r,t,i,c,(l=>{var c,d;return null!==(c=i.events)&&void 0!==c||(i.events=[]),s&&(null!==(d=i.prerequisites)&&void 0!==d||(i.prerequisites=[]),i.prerequisites.push(r.key)),a&&i.events.push(a.evalEventServer(r,t,l.detail,null,e)),l.isError?(o=l,u(!1)):l.isOff||l.detail.variationIndex!==n.variation?(o=(0,Zt.getOffVariation)(e,Qt.default.prerequisiteFailed(n.key)),u(!1)):u(!0)}),!1,a)}))}),(()=>{n(o)})):n(void 0)}_evaluateRules(e,t,i,r){let n;(0,Ht.firstSeriesAsync)(e.rules,((r,s,a)=>{this._ruleMatchContext(e,r,s,t,i,[],(e=>{n=e,a(!!e)}))}),(()=>r(n)))}_clauseMatchContext(e,t,i,r,n){let s;"segmentMatch"!==e.op?e.attributeReference.isValid?n(ni((0,Xt.default)(e,t))):n(si(Wt.default.forError(ei.MalformedFlag,"Invalid attribute reference in clause"))):(0,Ht.firstSeriesAsync)(e.values,((e,n,a)=>{this._queries.getSegment(e,(e=>{if(e){if(i.includes(e.key))return s=Wt.default.forError(ei.MalformedFlag,`Segment rule referencing segment ${e.key} caused a circular reference. This is probably a temporary condition due to an incomplete update`),void a(!0);const n=[...i,null==e?void 0:e.key];this.segmentMatchContext(e,t,r,n,(e=>{e.error&&(s=e.result),a(e.error||e.isMatch)}))}else a(!1)}))}),(t=>n(s?si(s):ni((0,Xt.maybeNegate)(e,t)))))}_ruleMatchContext(e,t,i,r,n,s,a){if(!t.clauses)return void a(void 0);let o;(0,Ht.allSeriesAsync)(t.clauses,((e,t,i)=>{this._clauseMatchContext(e,r,s,n,(e=>(o=e.result,i(e.error||e.isMatch))))}),(n=>a(o||(n?this._variationForContext(t,r,e,Qt.default.ruleMatch(t.id,i)):void 0))))}_variationForContext(e,t,i,r){if(void 0===e)return Wt.default.forError(ei.MalformedFlag,"Fallthrough variation undefined");if(void 0!==e.variation)return(0,Zt.getVariation)(i,e.variation,r);if(e.rollout){const{rollout:n}=e,{variations:s}=n,a="experiment"===n.kind;if(s&&s.length){const e=(0,Zt.getBucketBy)(a,n.bucketByAttributeReference);if(!e.isValid)return Wt.default.forError(ei.MalformedFlag,"Invalid attribute reference for bucketBy in rollout");const[o,l]=this._bucketer.bucket(t,i.key,e,i.salt||"",n.contextKind,n.seed),u=Object.assign({},r);let c=0;for(let e=0;e<s.length;e+=1){const t=s[e];if(c+=t.weight/1e5,o<c)return a&&l&&!t.untracked&&(u.inExperiment=!0),(0,Zt.getVariation)(i,t.variation,u)}const d=s[s.length-1];return a&&!d.untracked&&(u.inExperiment=!0),(0,Zt.getVariation)(i,d.variation,u)}}return Wt.default.forError(ei.MalformedFlag,"Variation/rollout object with no variation or rollout")}segmentRuleMatchContext(e,t,i,r,n,s){let a;(0,Ht.allSeriesAsync)(t.clauses,((e,t,s)=>{this._clauseMatchContext(e,i,n,r,(e=>{a=e.result,s(e.error||e.isMatch)}))}),(r=>{if(a)return s(si(a));if(r){if(void 0===t.weight)return s(ni(r));const n=(0,Zt.getBucketBy)(!1,t.bucketByAttributeReference);if(!n.isValid)return s(si(Wt.default.forError(ei.MalformedFlag,"Invalid attribute reference in clause")));const[a]=this._bucketer.bucket(i,e.key,n,e.salt||"",t.rolloutContextKind);return s(ni(a<t.weight/1e5))}return s(ni(!1))}))}simpleSegmentMatchContext(e,t,i,r,n){if(!e.unbounded){const i=(0,Yt.default)(e,t);if(void 0!==i)return void n(ni(i))}let s;(0,Ht.firstSeriesAsync)(e.rules,((n,a,o)=>{this.segmentRuleMatchContext(e,n,t,i,r,(e=>(s=e.result,o(e.error||e.isMatch))))}),(e=>n(s?si(s):ni(e))))}segmentMatchContext(e,t,i,r,n){if(!e.unbounded)return void this.simpleSegmentMatchContext(e,t,i,r,n);const s=e.unboundedContextKind||"user",a=t.key(s);if(a)return e.generation?void(i.bigSegmentsMembership&&i.bigSegmentsMembership[a]?this.bigSegmentMatchContext(i.bigSegmentsMembership[a],e,t,i).then(n):this._queries.getBigSegmentsMembership(a).then((r=>{if(i.bigSegmentsMembership=i.bigSegmentsMembership||{},r){const[e,t]=r;i.bigSegmentsMembership[a]=e,i.bigSegmentsStatus=ri(i.bigSegmentsStatus,t)}else i.bigSegmentsStatus=ri(i.bigSegmentsStatus,"NOT_CONFIGURED");this.bigSegmentMatchContext(i.bigSegmentsMembership[a],e,t,i).then(n)}))):(i.bigSegmentsStatus=ri(i.bigSegmentsStatus,"NOT_CONFIGURED"),void n(ni(!1)));n(ni(!1))}bigSegmentMatchContext(e,t,i,r){const n=(0,Gt.default)(t),s=null==e?void 0:e[n];return new Promise((e=>{null==s?this.simpleSegmentMatchContext(t,i,r,[],e):e(ni(s))}))}};var ai={};Object.defineProperty(ai,"__esModule",{value:!0});const oi=te;ai.default=class{constructor(e){this._contextKeysCache=new oi.default({max:e.contextKeysCapacity}),this.flushInterval=e.contextKeysFlushInterval}processContext(e){const{canonicalKey:t}=e,i=this._contextKeysCache.get(t);return this._contextKeysCache.set(t,!0),!i}flush(){this._contextKeysCache.clear()}};var li={},ui={};Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=function(e,t){if(t){if(t.inExperiment)return!0;switch(t.kind){case"RULE_MATCH":{const i=t.ruleIndex;if(void 0!==i){const t=e.rules||[];return i>=0&&i<t.length&&!!t[i].trackEvents}break}case"FALLTHROUGH":return!!e.trackEventsFallthrough}}return!1},Object.defineProperty(li,"__esModule",{value:!0});const ci=o,di=ui;class hi extends ci.internal.EventFactoryBase{evalEventServer(e,t,i,r,n){var s;const a=(0,di.default)(e,i.reason);return super.evalEvent({addExperimentData:a,context:t,debugEventsUntilDate:e.debugEventsUntilDate,defaultVal:r,excludeFromSummaries:e.excludeFromSummaries,flagKey:e.key,prereqOfFlagKey:null==n?void 0:n.key,reason:i.reason,samplingRatio:e.samplingRatio,trackEvents:e.trackEvents||a,value:i.value,variation:null!==(s=i.variationIndex)&&void 0!==s?s:void 0,version:e.version})}}li.default=hi;var fi={};Object.defineProperty(fi,"__esModule",{value:!0});fi.default=class{constructor(e,t){this._valid=e,this._withReasons=t,this._flagValues={},this._flagMetadata={}}addFlag(e,t,i,r,n,s,a,o){this._flagValues[e.key]=t;const l={};void 0!==i&&(l.variation=i);const u=a&&!n&&!s&&void 0===e.debugEventsUntilDate;u||(l.version=e.version),r&&(s||this._withReasons&&!u)&&(l.reason=r),n&&(l.trackEvents=!0),s&&(l.trackReason=!0),void 0!==e.debugEventsUntilDate&&(l.debugEventsUntilDate=e.debugEventsUntilDate),o&&o.length&&(l.prerequisites=o),this._flagMetadata[e.key]=l}build(){return{valid:this._valid,allValues:()=>this._flagValues,getFlagValue:e=>this._flagValues[e],getFlagReason:e=>{var t;return null!==(t=this._flagMetadata[e]?this._flagMetadata[e].reason:null)&&void 0!==t?t:null},toJSON:()=>Object.assign(Object.assign({},this._flagValues),{$flagsState:this._flagMetadata,$valid:this._valid})}}};var gi={};Object.defineProperty(gi,"__esModule",{value:!0});const vi="unknown hook";gi.default=class{constructor(e,t){this._logger=e,this._hooks=[],this._hooks.push(...t)}async withEvaluationSeries(e,t,i,r,n){return 0===this._hooks.length?n():this.withEvaluationSeriesExtraDetail(e,t,i,r,(async()=>({detail:await n()}))).then((({detail:e})=>e))}async withEvaluationSeriesExtraDetail(e,t,i,r,n){if(0===this._hooks.length)return n();const{hooks:s,hookContext:a}=this._prepareHooks(e,t,i,r),o=this._executeBeforeEvaluation(s,a),l=await n();return this._executeAfterEvaluation(s,a,o,l.detail),l}_tryExecuteStage(e,t,i){var r;try{return i()}catch(i){return null===(r=this._logger)||void 0===r||r.error(`An error was encountered in "${e}" of the "${t}" hook: ${i}`),{}}}_hookName(e){var t,i;try{return null!==(t=null==e?void 0:e.getMetadata().name)&&void 0!==t?t:vi}catch(e){return null===(i=this._logger)||void 0===i||i.error("Exception thrown getting metadata for hook. Unable to get hook name."),vi}}_executeAfterEvaluation(e,t,i,r){var n;for(let s=e.length-1;s>=0;s-=1){const a=e[s],o=null!==(n=i[s])&&void 0!==n?n:{};this._tryExecuteStage("afterEvaluation",this._hookName(a),(()=>{var e,i;return null!==(i=null===(e=null==a?void 0:a.afterEvaluation)||void 0===e?void 0:e.call(a,t,o,r))&&void 0!==i?i:{}}))}}_executeBeforeEvaluation(e,t){return e.map((e=>this._tryExecuteStage("beforeEvaluation",this._hookName(e),(()=>{var i,r;return null!==(r=null===(i=null==e?void 0:e.beforeEvaluation)||void 0===i?void 0:i.call(e,t,{}))&&void 0!==r?r:{}}))))}_prepareHooks(e,t,i,r){return{hooks:[...this._hooks],hookContext:{flagKey:e,context:t,defaultValue:i,method:r}}}addHook(e){this._hooks.push(e)}};var _i={};Object.defineProperty(_i,"__esModule",{value:!0});const pi=o;function yi(e){const t=e.old,i=e.new;return!(void 0!==t&&!pi.TypeValidators.Boolean.is(t))&&!(void 0!==i&&!pi.TypeValidators.Boolean.is(i))}function mi(e){if(pi.TypeValidators.String.is(e.key)&&""!==e.key){if("latency_ms"===e.key){if(!pi.TypeValidators.Object.is(e.values))return;if(!function(e){const t=e.old,i=e.new;return!(void 0!==t&&!pi.TypeValidators.Number.is(t)||void 0!==i&&!pi.TypeValidators.Number.is(i))}(e.values))return;return{key:e.key,values:{old:e.values.old,new:e.values.new}}}if(function(e){return"error"===e.key}(e)){if(!pi.TypeValidators.Object.is(e.values))return;if(!yi(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(!pi.TypeValidators.Boolean.is(e.value)||!pi.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(!pi.TypeValidators.Object.is(e.values))return;if(!yi(e.values))return;return{key:e.key,values:{old:e.values.old,new:e.values.new}}}}}_i.default=function(e){var t,i;if("migration_op"!==e.kind)return;if(i=e.operation,!pi.TypeValidators.String.is(i)||"read"!==i&&"write"!==i)return;if(!pi.TypeValidators.Object.is(e.contextKeys))return;if(!pi.TypeValidators.Number.is(e.creationDate))return;if(!Object.keys(e.contextKeys).every((e=>pi.TypeValidators.Kind.is(e))))return;const r=null!==(t=e.samplingRatio)&&void 0!==t?t:1;if(!pi.TypeValidators.Number.is(r))return;if(!Object.values(e.contextKeys).every((e=>pi.TypeValidators.String.is(e)&&""!==e)))return;const n=function(e){if(!pi.TypeValidators.String.is(e.key)||""===e.key)return;if(!pi.TypeValidators.Object.is(e.reason))return;if(!pi.TypeValidators.String.is(e.reason.kind)||""===e.reason.kind)return;const t={key:e.key,value:e.value,default:e.default,reason:{kind:e.reason.kind}},i=e.reason,r=t.reason;return pi.TypeValidators.String.is(i.errorKind)&&(r.errorKind=i.errorKind),pi.TypeValidators.String.is(i.ruleId)&&(r.ruleId=i.ruleId),pi.TypeValidators.String.is(i.prerequisiteKey)&&(r.prerequisiteKey=i.prerequisiteKey),pi.TypeValidators.Boolean.is(i.inExperiment)&&(r.inExperiment=i.inExperiment),pi.TypeValidators.Number.is(i.ruleIndex)&&(r.ruleIndex=i.ruleIndex),pi.TypeValidators.String.is(i.bigSegmentsStatus)&&(r.bigSegmentsStatus=i.bigSegmentsStatus),void 0!==e.variation&&pi.TypeValidators.Number.is(e.variation)&&(t.variation=e.variation),void 0!==e.version&&pi.TypeValidators.Number.is(e.version)&&(t.version=e.version),t}(e.evaluation);var s;return n?{kind:e.kind,operation:e.operation,creationDate:e.creationDate,contextKeys:Object.assign({},e.contextKeys),measurements:(s=e.measurements,s.map(mi).filter((e=>void 0!==e))),evaluation:n,samplingRatio:r}:void 0};var bi={};Object.defineProperty(bi,"__esModule",{value:!0});const wi=o,Si=u;function ki(e){return!Number.isNaN(e)}bi.default=class{constructor(e,t,i,r,n,s,a,o,l,u){this._flagKey=e,this._contextKeys=t,this._defaultStage=i,this._stage=r,this._reason=n,this._checkRatio=s,this._variation=a,this._version=o,this._samplingRatio=l,this._logger=u,this._errors={old:!1,new:!1},this._wasInvoked={old:!1,new:!1},this._consistencyCheck=Si.LDConsistencyCheck.NotChecked,this._latencyMeasurement={old:NaN,new:NaN}}op(e){this._operation=e}error(e){this._errors[e]=!0}consistency(e){var t,i;if(wi.internal.shouldSample(null!==(t=this._checkRatio)&&void 0!==t?t:1))try{const t=e();this._consistencyCheck=t?Si.LDConsistencyCheck.Consistent:Si.LDConsistencyCheck.Inconsistent}catch(e){null===(i=this._logger)||void 0===i||i.error(`Exception when executing consistency check function for migration '${this._flagKey}' the consistency check will not be included in the generated migration op event. Exception: ${e}`)}}latency(e,t){this._latencyMeasurement[e]=t}invoked(e){this._wasInvoked[e]=!0}createEvent(){var e,t,i,r,n;if(!wi.TypeValidators.String.is(this._flagKey)||""===this._flagKey)return void(null===(e=this._logger)||void 0===e||e.error("The flag key for a migration operation must be a non-empty string."));if(!this._operation)return void(null===(t=this._logger)||void 0===t||t.error('The operation must be set using "op" before an event can be created.'));if(0===Object.keys(this._contextKeys).length)return void(null===(i=this._logger)||void 0===i||i.error("The migration was not done against a valid context and cannot generate an event."));if(!this._wasInvoked.old&&!this._wasInvoked.new)return void(null===(r=this._logger)||void 0===r||r.error('The migration invoked neither the "old" or "new" implementation andan event cannot be generated'));if(!this._measurementConsistencyCheck())return;const s=[];return this._populateInvoked(s),this._populateConsistency(s),this._populateLatency(s),this._populateErrors(s),{kind:"migration_op",operation:this._operation,creationDate:Date.now(),contextKeys:this._contextKeys,evaluation:{key:this._flagKey,value:this._stage,default:this._defaultStage,reason:this._reason,variation:this._variation,version:this._version},measurements:s,samplingRatio:null!==(n=this._samplingRatio)&&void 0!==n?n:1}}_logTag(){return`For migration ${this._operation}-${this._flagKey}:`}_latencyConsistencyMessage(e){return`Latency measurement for "${e}", but "${e}" was not invoked.`}_errorConsistencyMessage(e){return`Error occurred for "${e}", but "${e}" was not invoked.`}_consistencyCheckConsistencyMessage(e){return`Consistency check was done, but "${e}" was not invoked.Both "old" and "new" must be invoked to do a consistency check.`}_checkOriginEventConsistency(e){var t,i,r;return!!this._wasInvoked[e]||(Number.isNaN(this._latencyMeasurement[e])?this._errors[e]?(null===(i=this._logger)||void 0===i||i.error(`${this._logTag()} ${this._errorConsistencyMessage(e)}`),!1):this._consistencyCheck===Si.LDConsistencyCheck.NotChecked||(null===(r=this._logger)||void 0===r||r.error(`${this._logTag()} ${this._consistencyCheckConsistencyMessage(e)}`),!1):(null===(t=this._logger)||void 0===t||t.error(`${this._logTag()} ${this._latencyConsistencyMessage(e)}`),!1))}_measurementConsistencyCheck(){return this._checkOriginEventConsistency("old")&&this._checkOriginEventConsistency("new")}_populateInvoked(e){var t;const i={key:"invoked",values:{}};this._wasInvoked.old||this._wasInvoked.new||null===(t=this._logger)||void 0===t||t.error("Migration op completed without executing any origins (old/new)."),this._wasInvoked.old&&(i.values.old=!0),this._wasInvoked.new&&(i.values.new=!0),e.push(i)}_populateConsistency(e){var t;void 0!==this._consistencyCheck&&this._consistencyCheck!==Si.LDConsistencyCheck.NotChecked&&e.push({key:"consistent",value:this._consistencyCheck===Si.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=ki(this._latencyMeasurement.new),i=ki(this._latencyMeasurement.old);if(t||i){const r={};t&&(r.new=this._latencyMeasurement.new),i&&(r.old=this._latencyMeasurement.old),e.push({key:"latency_ms",values:r})}}},Object.defineProperty(a,"__esModule",{value:!0});const Ei=o,Oi=l,xi=ee,Di=se,Mi=ye,Pi=xe,Ti=et,Ci=it,Fi=ot,Ii=ut,ji=gt,Ri=ai,Ai=li,Vi=ui,Ni=fi,Li=gi,Ki=_i,$i=bi,Ui=rt,zi=oe,{ClientMessages:Bi,ErrorKinds:qi,NullEventProcessor:Hi}=Ei.internal;var Wi,Ji;(Ji=Wi||(Wi={}))[Ji.Initializing=0]="Initializing",Ji[Ji.Initialized=1]="Initialized",Ji[Ji.Failed=2]="Failed";a.default=class{constructor(e,t,i,r,n){var s,a,o,l,u;this._sdkKey=e,this._platform=t,this._initState=Wi.Initializing,this._eventFactoryDefault=new Ai.default(!1),this._eventFactoryWithReasons=new Ai.default(!0),this._onError=r.onError,this._onFailed=r.onFailed,this._onReady=r.onReady;const{onUpdate:c,hasEventListeners:d}=r,h=new Ui.default(i,n);if(this._hookRunner=new Li.default(h.logger,h.hooks||[]),!e&&!h.offline)throw new Error("You must configure the client with an SDK key");this._config=h,this._logger=h.logger;const f=(0,Ei.defaultHeaders)(e,t.info,h.tags),g=new Ei.ClientContext(e,h,t),v=h.featureStoreFactory(g),_=new Mi.default(v,d,c);!h.sendEvents||h.offline||h.diagnosticOptOut||(this._diagnosticsManager=new Ei.internal.DiagnosticsManager(e,t,(0,Ci.default)(h,t,v))),!h.sendEvents||h.offline?this._eventProcessor=new Hi:this._eventProcessor=new Ei.internal.EventProcessor(h,g,f,new Ri.default(h),this._diagnosticsManager),this._featureStore=v;const p=new xi.default(null===(a=null===(s=h.bigSegments)||void 0===s?void 0:s.store)||void 0===a?void 0:a.call(s,g),null!==(o=h.bigSegments)&&void 0!==o?o:{},h.logger,this._platform.crypto);this._bigSegmentsManager=p,this.bigSegmentStatusProviderInternal=p.statusProvider;const y={getFlag(e,t){v.get(zi.default.Features,e,(e=>t(e)))},getSegment(e,t){v.get(zi.default.Segments,e,(e=>t(e)))},getBigSegmentsMembership:e=>p.getUserMembership(e)};this._evaluator=new ji.default(this._platform,y);const m=(0,Di.createStreamListeners)(_,this._logger,{put:()=>this._initSuccess()}),b=()=>h.stream?new Ei.internal.StreamingProcessor(g,"/all",[],m,f,this._diagnosticsManager,(e=>this._dataSourceErrorHandler(e)),this._config.streamInitialReconnectDelay):new Pi.default(h,new Ti.default(h,this._platform.requests,f),_,(()=>this._initSuccess()),(e=>this._dataSourceErrorHandler(e)));h.offline||h.useLdd||(this._updateProcessor=null!==(u=null===(l=h.updateProcessorFactory)||void 0===l?void 0:l.call(h,g,_,(()=>this._initSuccess()),(e=>this._dataSourceErrorHandler(e))))&&void 0!==u?u:b()),this._updateProcessor?this._updateProcessor.start():setTimeout((()=>this._initSuccess()),0)}initialized(){return this._initState===Wi.Initialized}waitForInitialization(e){var t,i;return void 0===(null==e?void 0:e.timeout)&&void 0!==this._updateProcessor&&(null===(t=this._logger)||void 0===t||t.warn("The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied.")),void 0!==(null==e?void 0:e.timeout)&&(null==e?void 0:e.timeout)>60&&void 0!==this._updateProcessor&&(null===(i=this._logger)||void 0===i||i.warn("The waitForInitialization function was called with a timeout greater than 60 seconds. We recommend a timeout of less than 60 seconds.")),this._initializedPromise?this._clientWithTimeout(this._initializedPromise,null==e?void 0:e.timeout,this._logger):this._initState===Wi.Initialized?(this._initializedPromise=Promise.resolve(this),this._initializedPromise):this._initState===Wi.Failed?(this._initializedPromise=Promise.reject(this._rejectionReason),this._initializedPromise):(this._initializedPromise||(this._initializedPromise=new Promise(((e,t)=>{this._initResolve=e,this._initReject=t}))),this._clientWithTimeout(this._initializedPromise,null==e?void 0:e.timeout,this._logger))}variation(e,t,i,r){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.variation",(()=>new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryDefault,(e=>{r(e.detail)}))})))).then((e=>(null==r||r(null,e.value),e.value)))}variationDetail(e,t,i,r){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.variationDetail",(()=>new Promise((n=>{this._evaluateIfPossible(e,t,i,this._eventFactoryWithReasons,(e=>{n(e.detail),null==r||r(null,e.detail)}))}))))}_typedEval(e,t,i,r,n,s){return this._hookRunner.withEvaluationSeries(e,t,i,n,(()=>new Promise((n=>{this._evaluateIfPossible(e,t,i,r,(e=>{const t={value:e.detail.value,reason:e.detail.reason,variationIndex:e.detail.variationIndex};n(t)}),s)}))))}async boolVariation(e,t,i){return(await this._typedEval(e,t,i,this._eventFactoryDefault,"LDClient.boolVariation",(e=>[Ei.TypeValidators.Boolean.is(e),Ei.TypeValidators.Boolean.getType()]))).value}async numberVariation(e,t,i){return(await this._typedEval(e,t,i,this._eventFactoryDefault,"LDClient.numberVariation",(e=>[Ei.TypeValidators.Number.is(e),Ei.TypeValidators.Number.getType()]))).value}async stringVariation(e,t,i){return(await this._typedEval(e,t,i,this._eventFactoryDefault,"LDClient.stringVariation",(e=>[Ei.TypeValidators.String.is(e),Ei.TypeValidators.String.getType()]))).value}jsonVariation(e,t,i){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.jsonVariation",(()=>new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryDefault,(e=>{r(e.detail)}))})))).then((e=>e.value))}boolVariationDetail(e,t,i){return this._typedEval(e,t,i,this._eventFactoryWithReasons,"LDClient.boolVariationDetail",(e=>[Ei.TypeValidators.Boolean.is(e),Ei.TypeValidators.Boolean.getType()]))}numberVariationDetail(e,t,i){return this._typedEval(e,t,i,this._eventFactoryWithReasons,"LDClient.numberVariationDetail",(e=>[Ei.TypeValidators.Number.is(e),Ei.TypeValidators.Number.getType()]))}stringVariationDetail(e,t,i){return this._typedEval(e,t,i,this._eventFactoryWithReasons,"LDClient.stringVariationDetail",(e=>[Ei.TypeValidators.String.is(e),Ei.TypeValidators.String.getType()]))}jsonVariationDetail(e,t,i){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.jsonVariationDetail",(()=>new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryWithReasons,(e=>{r(e.detail)}))}))))}async _migrationVariationInternal(e,t,i){var r;const n=Ei.Context.fromLDContext(t),s=await new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryWithReasons,(({detail:t},n)=>{if((0,Oi.IsMigrationStage)(t.value))r({detail:t,flag:n});else{const t=new Error(`Unrecognized MigrationState for "${e}"; returning default value.`);this._onError(t);const s={kind:"ERROR",errorKind:qi.WrongType};r({detail:{value:i,reason:s},flag:n})}}))})),{detail:a,flag:o}=s,l=n.valid?n.kindsAndKeys:{},u=null===(r=null==o?void 0:o.migration)||void 0===r?void 0:r.checkRatio,c=null==o?void 0:o.samplingRatio;return{detail:a,migration:{value:a.value,tracker:new $i.default(e,l,i,a.value,a.reason,u,null===a.variationIndex?void 0:a.variationIndex,null==o?void 0:o.version,c,this._logger)}}}async migrationVariation(e,t,i){return(await this._hookRunner.withEvaluationSeriesExtraDetail(e,t,i,"LDClient.migrationVariation",(()=>this._migrationVariationInternal(e,t,i)))).migration}allFlagsState(e,t,i){var r,n,s;if(this._config.offline){null===(r=this._logger)||void 0===r||r.info("allFlagsState() called in offline mode. Returning empty state.");const e=new Ni.default(!1,!1).build();return null==i||i(null,e),Promise.resolve(e)}const a=Ei.Context.fromLDContext(e);return a.valid?new Promise((e=>{const r=r=>this._featureStore.all(zi.default.Features,(n=>{const s=new Ni.default(r,!!(null==t?void 0:t.withReasons)),o=!!(null==t?void 0:t.clientSideOnly),l=!!(null==t?void 0:t.detailsOnlyForTrackedFlags);(0,Fi.allAsync)(Object.values(n),((e,t)=>{var i;const r=e;!o||(null===(i=r.clientSideAvailability)||void 0===i?void 0:i.usingEnvironmentId)?this._evaluator.evaluateCb(r,a,(e=>{var i;e.isError&&this._onError(new Error(`Error for feature flag "${r.key}" while evaluating all flags: ${e.message}`));const n=(0,Vi.default)(r,e.detail.reason);s.addFlag(r,e.detail.value,null!==(i=e.detail.variationIndex)&&void 0!==i?i:void 0,e.detail.reason,r.trackEvents||n,n,l,e.prerequisites),t(!0)})):t(!0)}),(()=>{const t=s.build();null==i||i(null,t),e(t)}))}));this.initialized()?r(!0):this._featureStore.initialized((e=>{var t,i;let n=!0;e?null===(t=this._logger)||void 0===t||t.warn("Called allFlagsState before client initialization; using last known values from data store"):(null===(i=this._logger)||void 0===i||i.warn("Called allFlagsState before client initialization. Data store not available; returning empty state"),n=!1),r(n)}))})):(null===(n=this._logger)||void 0===n||n.info(`${null!==(s=a.message)&&void 0!==s?s:"Invalid context."}. Returning empty state.`),Promise.resolve(new Ni.default(!1,!1).build()))}secureModeHash(e){const t=Ei.Context.fromLDContext(e),i=t.valid?t.canonicalKey:void 0;if(!this._platform.crypto.createHmac)throw new Error("Platform must implement createHmac");const r=this._platform.crypto.createHmac("sha256",this._sdkKey);if(void 0===i)throw new Ei.LDClientError("Could not generate secure mode hash for invalid context");return r.update(i),r.digest("hex")}close(){var e;this._eventProcessor.close(),null===(e=this._updateProcessor)||void 0===e||e.close(),this._featureStore.close(),this._bigSegmentsManager.close()}isOffline(){return this._config.offline}track(e,t,i,r){var n,s;const a=Ei.Context.fromLDContext(t);a.valid?(void 0===r||Ei.TypeValidators.Number.is(r)||null===(s=this._logger)||void 0===s||s.warn(Bi.invalidMetricValue(typeof r)),this._eventProcessor.sendEvent(this._eventFactoryDefault.customEvent(e,a,i,r))):null===(n=this._logger)||void 0===n||n.warn(Bi.MissingContextKeyNoEvent)}trackMigration(e){const t=(0,Ki.default)(e);t&&this._eventProcessor.sendEvent(t)}identify(e){var t;const i=Ei.Context.fromLDContext(e);i.valid?this._eventProcessor.sendEvent(this._eventFactoryDefault.identifyEvent(i)):null===(t=this._logger)||void 0===t||t.warn(Bi.MissingContextKeyNoEvent)}async flush(e){try{await this._eventProcessor.flush()}catch(t){null==e||e(t,!1)}null==e||e(null,!0)}addHook(e){this._hookRunner.addHook(e)}_variationInternal(e,t,i,r,n,s){var a,o;if(this._config.offline)return null===(a=this._logger)||void 0===a||a.info("Variation called in offline mode. Returning default value."),void n(Ii.default.forError(qi.ClientNotReady,void 0,i));const l=Ei.Context.fromLDContext(t);if(!l.valid)return this._onError(new Ei.LDClientError(`${null!==(o=l.message)&&void 0!==o?o:"Context not valid;"} returning default value.`)),void n(Ii.default.forError(qi.UserNotSpecified,void 0,i));this._featureStore.get(zi.default.Features,e,(t=>{const a=t;if(!a){const t=new Ei.LDClientError(`Unknown feature flag "${e}"; returning default value`);this._onError(t);const r=Ii.default.forError(qi.FlagNotFound,void 0,i);return this._eventProcessor.sendEvent(this._eventFactoryDefault.unknownFlagEvent(e,i,l)),void n(r)}this._evaluator.evaluateCb(a,l,(t=>{var o;if(void 0!==t.detail.variationIndex&&null!==t.detail.variationIndex||(null===(o=this._logger)||void 0===o||o.debug("Result value is null in variation"),t.setDefault(i)),s){const[o,u]=s(t.detail.value);if(!o){const t=Ii.default.forError(qi.WrongType,`Did not receive expected type (${u}) evaluating feature flag "${e}"`,i);return this._sendEvalEvent(t,r,a,l,i),void n(t,a)}}this._sendEvalEvent(t,r,a,l,i),n(t,a)}),r)}))}_sendEvalEvent(e,t,i,r,n){var s;null===(s=e.events)||void 0===s||s.forEach((e=>{this._eventProcessor.sendEvent(Object.assign({},e))})),this._eventProcessor.sendEvent(t.evalEventServer(i,r,e.detail,n,void 0))}_evaluateIfPossible(e,t,i,r,n,s){this.initialized()?this._variationInternal(e,t,i,r,n,s):this._featureStore.initialized((a=>{var o,l;if(a)return null===(o=this._logger)||void 0===o||o.warn("Variation called before LaunchDarkly client initialization completed (did you wait for the 'ready' event?) - using last known values from feature store"),void this._variationInternal(e,t,i,r,n,s);null===(l=this._logger)||void 0===l||l.warn("Variation called before LaunchDarkly client initialization completed (did you wait for the'ready' event?) - using default value"),n(Ii.default.forError(qi.ClientNotReady,void 0,i))}))}_dataSourceErrorHandler(e){var t;const i=401===e.code?new Error("Authentication failed. Double check your SDK key."):e;this._onError(i),this._onFailed(i),this.initialized()||(this._initState=Wi.Failed,this._rejectionReason=i,null===(t=this._initReject)||void 0===t||t.call(this,i))}_initSuccess(){var e;this.initialized()||(this._initState=Wi.Initialized,null===(e=this._initResolve)||void 0===e||e.call(this,this),this._onReady())}_clientWithTimeout(e,t,i){if(t){const r=(0,Ei.cancelableTimedPromise)(t,"waitForInitialization");return Promise.race([e.then((()=>r.cancel())).then((()=>this)),r.promise.then((()=>this))]).catch((e=>{throw e instanceof Ei.LDTimeoutError&&(null==i||i.error(e.message)),e}))}return e}};var Gi={};Object.defineProperty(Gi,"__esModule",{value:!0}),Gi.createMigration=Gi.LDMigrationError=Gi.LDMigrationSuccess=void 0;const Xi=l,Yi=C;Gi.LDMigrationSuccess=function(e){return{success:!0,result:e}},Gi.LDMigrationError=function(e){return{success:!1,error:e}};class Qi{constructor(e,t){var i,r;this._client=e,this._config=t,this._readTable={[Xi.LDMigrationStage.Off]:async e=>this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),[Xi.LDMigrationStage.DualWrite]:async e=>this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),[Xi.LDMigrationStage.Shadow]:async e=>{const{fromOld:t,fromNew:i}=await this._doRead(e);return this._trackConsistency(e,t,i),t},[Xi.LDMigrationStage.Live]:async e=>{const{fromNew:t,fromOld:i}=await this._doRead(e);return this._trackConsistency(e,i,t),t},[Xi.LDMigrationStage.RampDown]:async e=>this._doSingleOp(e,"new",this._config.readNew.bind(this._config)),[Xi.LDMigrationStage.Complete]:async e=>this._doSingleOp(e,"new",this._config.readNew.bind(this._config))},this._writeTable={[Xi.LDMigrationStage.Off]:async e=>({authoritative:await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config))}),[Xi.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))}},[Xi.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))}},[Xi.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))}},[Xi.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))}},[Xi.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 Yi.LDConcurrentExecution,this._latencyTracking=null===(i=this._config.latencyTracking)||void 0===i||i,this._errorTracking=null===(r=this._config.errorTracking)||void 0===r||r}async read(e,t,i,r){const n=await this._client.migrationVariation(e,t,i),s=await this._readTable[n.value]({payload:r,tracker:n.tracker});return n.tracker.op("read"),this._sendEvent(n.tracker),s}async write(e,t,i,r){const n=await this._client.migrationVariation(e,t,i),s=await this._writeTable[n.value]({payload:r,tracker:n.tracker});return n.tracker.op("write"),this._sendEvent(n.tracker),s}_sendEvent(e){const t=e.createEvent();t&&this._client.trackMigration(t)}_trackConsistency(e,t,i){this._config.check&&t.success&&i.success&&e.tracker.consistency((()=>this._config.check(t.result,i.result)))}async _readSequentialFixed(e){return{fromOld:await this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),fromNew:await this._doSingleOp(e,"new",this._config.readNew.bind(this._config))}}async _readConcurrent(e){const t=this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),i=this._doSingleOp(e,"new",this._config.readNew.bind(this._config)),[r,n]=await Promise.all([t,i]);return{fromOld:r,fromNew:n}}async _readSequentialRandom(e){if(0===Math.floor(2*Math.random())){return{fromOld:await this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),fromNew:await this._doSingleOp(e,"new",this._config.readNew.bind(this._config))}}const t=await this._doSingleOp(e,"new",this._config.readNew.bind(this._config));return{fromOld:await this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),fromNew:t}}async _doRead(e){var t;if((null===(t=this._execution)||void 0===t?void 0:t.type)===Yi.LDExecution.Serial){return this._execution.ordering===Yi.LDExecutionOrdering.Fixed?this._readSequentialFixed(e):this._readSequentialRandom(e)}return this._readConcurrent(e)}async _doSingleOp(e,t,i){e.tracker.invoked(t);const r=await this._trackLatency(e.tracker,t,(()=>async function(e){try{return await e()}catch(e){return{success:!1,error:e}}}((()=>i(e.payload)))));return!r.success&&this._errorTracking&&e.tracker.error(t),Object.assign({origin:t},r)}async _trackLatency(e,t,i){if(!this._latencyTracking)return i();let r,n,s;"undefined"!=typeof performance?(r=performance.now(),s=await i(),n=performance.now()):(r=Date.now(),s=await i(),n=Date.now());const a=n-r;return e.latency(t,a),s}}Gi.createMigration=function(e,t){return new Qi(e,t)};var Zi={},er={},tr={},ir={};Object.defineProperty(ir,"__esModule",{value:!0});ir.default=class{constructor(e,t,i,r){this._filesystem=e,this._paths=t,this._watch=i,this._callback=r,this._watchers=[],this._fileData={},this._fileTimestamps={}}async loadAndWatch(){const e=this._paths.map((async e=>({data:await this._filesystem.readFile(e),path:e,timeStamp:await this._filesystem.getFileTimestamp(e)}))),t=await Promise.all(e);t.forEach((e=>{this._fileData[e.path]=e.data,this._fileTimestamps[e.path]=e.timeStamp})),this._callback(t),this._watch&&this._paths.forEach((e=>{const t=this._filesystem.watch(e,(async(e,t)=>{const i=await this._filesystem.getFileTimestamp(t);if(i===this._fileTimestamps[t])return;this._fileTimestamps[t]=i;const r=await this._filesystem.readFile(t);this._fileData[t]=r,this._debounceCallback()}));this._watchers.push(t)}))}close(){this._watchers.forEach((e=>e.close()))}_debounceCallback(){this._debounceHandle||(this._debounceHandle=setTimeout((()=>{this._debounceHandle=void 0,this._callback(Object.entries(this._fileData).reduce(((e,[t,i])=>(e.push({path:t,data:i}),e)),[]))}),10))}},Object.defineProperty(tr,"__esModule",{value:!0});const rr=ae,nr=oe,sr=ir;tr.default=class{constructor(e,t,i,r=()=>{},n){var s;this._featureStore=i,this._initSuccessHandler=r,this._errorHandler=n,this._allData={},this._fileLoader=new sr.default(t,e.paths,null!==(s=e.autoUpdate)&&void 0!==s&&s,(e=>{var t,i;try{this._processFileData(e)}catch(e){null===(t=this._errorHandler)||void 0===t||t.call(this,e),null===(i=this._logger)||void 0===i||i.error(`Error processing files: ${e}`)}})),this._logger=e.logger,this._yamlParser=e.yamlParser}start(){(async()=>{var e;try{await this._fileLoader.loadAndWatch()}catch(t){null===(e=this._errorHandler)||void 0===e||e.call(this,t)}})()}stop(){this._fileLoader.close()}close(){this.stop()}_addItem(e,t){if(this._allData[e.namespace]||(this._allData[e.namespace]={}),this._allData[e.namespace][t.key])throw new Error(`found duplicate key: "${t.key}"`);this._allData[e.namespace][t.key]=t}_processFileData(e){const t=this._allData;this._allData={},e.forEach((e=>{let i;if(e.path.endsWith(".yml")||e.path.endsWith(".yaml")){if(!this._yamlParser)throw new Error(`Attempted to parse yaml file (${e.path}) without parser.`);i=this._yamlParser(e.data)}else i=JSON.parse(e.data);this._processParsedData(i,t)})),this._featureStore.init(this._allData,(()=>{this._initSuccessHandler(),this._initSuccessHandler=()=>{}}))}_processParsedData(e,t){Object.keys(e.flags||{}).forEach((t=>{(0,rr.processFlag)(e.flags[t]),this._addItem(nr.default.Features,e.flags[t])})),Object.keys(e.flagValues||{}).forEach((i=>{var r,n;const s=null===(r=t[nr.default.Features.namespace])||void 0===r?void 0:r[i];let{version:a}=null!=s?s:{version:1};s&&JSON.stringify(e.flagValues[i])!==JSON.stringify(null===(n=null==s?void 0:s.variations)||void 0===n?void 0:n[0])&&(a+=1);const o=function(e,t,i){return{key:e,on:!0,fallthrough:{variation:0},variations:[t],version:i}}(i,e.flagValues[i],a);(0,rr.processFlag)(o),this._addItem(nr.default.Features,o)})),Object.keys(e.segments||{}).forEach((t=>{(0,rr.processSegment)(e.segments[t]),this._addItem(nr.default.Segments,e.segments[t])}))}},Object.defineProperty(er,"__esModule",{value:!0});const ar=tr;er.default=class{constructor(e){this._options=e}create(e,t,i,r){const n={paths:this._options.paths,autoUpdate:this._options.autoUpdate,logger:this._options.logger||e.basicConfiguration.logger,yamlParser:this._options.yamlParser};return new ar.default(n,e.platform.fileSystem,t,i,r)}getFactory(){return(e,t,i,r)=>this.create(e,t,i,r)}};var or={},lr={},ur={},cr={};!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}}(cr);var dr={};Object.defineProperty(dr,"__esModule",{value:!0});const hr=o,fr=cr;class gr{constructor(e,t,i){this._flagBuilder=e,this._clauses=[],t&&(this._clauses=[...t]),void 0!==i&&(this._variation=i)}andMatch(e,t,...i){return this._clauses.push({contextKind:e,attribute:t,attributeReference:new hr.AttributeReference(t),op:"in",values:i,negate:!1}),this}andNotMatch(e,t,...i){return this._clauses.push({contextKind:e,attribute:t,attributeReference:new hr.AttributeReference(t),op:"in",values:i,negate:!0}),this}thenReturn(e){return hr.TypeValidators.Boolean.is(e)?(this._flagBuilder.booleanFlag(),this.thenReturn((0,fr.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 gr(this._flagBuilder,this._clauses,this._variation)}}dr.default=gr,Object.defineProperty(ur,"__esModule",{value:!0});const vr=o,_r=cr,pr=dr;class yr{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[_r.TRUE_VARIATION_INDEX]&&!1===this._data.variations[_r.FALSE_VARIATION_INDEX]}booleanFlag(){return this._isBooleanFlag?this:this.variations(!0,!1).fallthroughVariation(_r.TRUE_VARIATION_INDEX).offVariation(_r.FALSE_VARIATION_INDEX)}variations(...e){return this._data.variations=[...e],this}on(e){return this._data.on=e,this}fallthroughVariation(e){return vr.TypeValidators.Boolean.is(e)?this.booleanFlag().fallthroughVariation((0,_r.variationForBoolean)(e)):(this._data.fallthroughVariation=e,this)}offVariation(e){return vr.TypeValidators.Boolean.is(e)?this.booleanFlag().offVariation((0,_r.variationForBoolean)(e)):(this._data.offVariation=e,this)}variationForAll(e){return this.on(!0).clearRules().clearAllTargets().fallthroughVariation(e)}valueForAll(e){return this.variations(e).variationForAll(0)}variationForUser(e,t){return this.variationForContext("user",e,t)}variationForContext(e,t,i){return vr.TypeValidators.Boolean.is(i)?this.booleanFlag().variationForContext(e,t,(0,_r.variationForBoolean)(i)):(this._data.targetsByVariation||(this._data.targetsByVariation={}),this._data.variations.forEach(((r,n)=>{if(n===i){const i=this._data.targetsByVariation[n]||{};e in i||(i[e]=[]);-1!==i[e].indexOf(t)||i[e].push(t),this._data.targetsByVariation[n]=i}else{const i=this._data.targetsByVariation[n];if(i){const r=i[e];if(r){const n=r.indexOf(t);-1!==n&&(r.splice(n,1),r.length||delete i[e])}Object.keys(i).length||delete this._data.targetsByVariation[n]}}})),this)}clearRules(){return delete this._data.rules,this}clearAllTargets(){return delete this._data.targetsByVariation,this}ifMatch(e,t,...i){return new pr.default(this).andMatch(e,t,...i)}ifNotMatch(e,t,...i){return new pr.default(this).andNotMatch(e,t,...i)}checkRatio(e){var t;return this._data.migration=null!==(t=this._data.migration)&&void 0!==t?t:{},this._data.migration.checkRatio=e,this}samplingRatio(e){return this._data.samplingRatio=e,this}addRule(e){this._data.rules||(this._data.rules=[]),this._data.rules.push(e)}build(e){const t={key:this._key,version:e,on:this._data.on,offVariation:this._data.offVariation,fallthrough:{variation:this._data.fallthroughVariation},variations:[...this._data.variations],migration:this._data.migration,samplingRatio:this._data.samplingRatio};if(this._data.targetsByVariation){const e=[],i=[];Object.entries(this._data.targetsByVariation).forEach((([t,r])=>{Object.entries(r).forEach((([r,n])=>{const s=parseInt(t,10);e.push({contextKind:r,values:"user"===r?[]:n,variation:s}),"user"===r&&i.push({values:n,variation:s})}))})),t.targets=i,t.contextTargets=e}return this._data.rules&&(t.rules=this._data.rules.map(((e,t)=>e.build(String(t))))),t}clone(){return new yr(this._key,this._data)}getKey(){return this._key}}ur.default=yr;var mr={};Object.defineProperty(mr,"__esModule",{value:!0});mr.default=class{constructor(e,t,i,r,n){this._featureStore=e,this._onStop=r,this._listeners=n,this._flags=Object.assign({},t),this._segments=Object.assign({},i)}async start(){this._listeners.forEach((({processJson:e})=>{e({data:{flags:this._flags,segments:this._segments}})}))}stop(){this._onStop(this)}close(){this.stop()}async upsert(e,t){return this._featureStore.upsert(e,t)}},Object.defineProperty(lr,"__esModule",{value:!0});const br=se,wr=Me,Sr=ae,kr=oe,Er=ur,Or=mr;lr.default=class{constructor(){this._currentFlags={},this._currentSegments={},this._dataSources=[],this._flagBuilders={}}getFactory(){return(e,t,i,r)=>{const n=(0,br.createStreamListeners)(t,e.basicConfiguration.logger,{put:i}),s=new Or.default(new wr.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 Er.default(e).booleanFlag()}update(e){const t=e.getKey(),i=this._currentFlags[t],r=i?i.version:0,n=e.build(r+1);return this._currentFlags[t]=n,this._flagBuilders[t]=e.clone(),Promise.all(this._dataSources.map((e=>e.upsert(kr.default.Features,n))))}usePreconfiguredFlag(e){const t=JSON.parse(JSON.stringify(e)),i=this._currentFlags[t.key],r=Object.assign(Object.assign({},t),{version:i?i.version+1:t.version});return(0,Sr.processFlag)(r),this._currentFlags[t.key]=r,Promise.all(this._dataSources.map((e=>e.upsert(kr.default.Features,r))))}usePreconfiguredSegment(e){const t=JSON.parse(JSON.stringify(e)),i=this._currentSegments[t.key],r=Object.assign(Object.assign({},t),{version:i?i.version+1:t.version});return(0,Sr.processSegment)(r),this._currentSegments[t.key]=r,Promise.all(this._dataSources.map((e=>e.upsert(kr.default.Segments,r))))}},Object.defineProperty(or,"__esModule",{value:!0}),or.TestDataRuleBuilder=or.TestDataFlagBuilder=or.TestData=void 0;const xr=lr;or.TestData=xr.default;const Dr=ur;or.TestDataFlagBuilder=Dr.default;const Mr=dr;or.TestDataRuleBuilder=Mr.default,function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.FileDataSourceFactory=void 0;const n=er;e.FileDataSourceFactory=n.default,i(or,e),i(V,e)}(Zi);var Pr={},Tr={};Object.defineProperty(Tr,"__esModule",{value:!0});Tr.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(Pr,"__esModule",{value:!0}),Pr.NullEventSource=void 0;const Cr=Tr;Pr.NullEventSource=Cr.default,function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.createMigration=e.LDMigrationSuccess=e.LDMigrationError=e.BigSegmentStoreStatusProviderImpl=e.LDClientImpl=e.platform=e.integrations=void 0;const n=s;e.BigSegmentStoreStatusProviderImpl=n.default;const u=a;e.LDClientImpl=u.default;const c=Gi;Object.defineProperty(e,"createMigration",{enumerable:!0,get:function(){return c.createMigration}}),Object.defineProperty(e,"LDMigrationError",{enumerable:!0,get:function(){return c.LDMigrationError}}),Object.defineProperty(e,"LDMigrationSuccess",{enumerable:!0,get:function(){return c.LDMigrationSuccess}}),e.integrations=Zi,e.platform=o,i(l,e),i(De,e),i(Pr,e),i(o,e)}(n);class Fr{constructor(e){let t;switch(e){case"sha1":t=i.algo.SHA1;break;case"sha256":t=i.algo.SHA256;break;default:throw new Error("unsupported hash algorithm. Only sha1 and sha256 are supported.")}this._cryptoJSHasher=t.create()}digest(e){const t=this._cryptoJSHasher.finalize();let r;switch(e){case"base64":r=i.enc.Base64;break;case"hex":r=i.enc.Hex;break;default:throw new Error("unsupported output encoding. Only base64 and hex are supported.")}return t.toString(r)}update(e){return this._cryptoJSHasher.update(e),this}}class Ir{constructor(e,t){let r;switch(e){case"sha1":r=i.algo.SHA1;break;case"sha256":r=i.algo.SHA256;break;default:throw new Error("unsupported hash algorithm. Only sha1 and sha256 are supported.")}this._cryptoJSHmac=i.algo.HMAC.create(r,t)}digest(e){const t=this._cryptoJSHmac.finalize();if("base64"===e)return t.toString(i.enc.Base64);if("hex"===e)return t.toString(i.enc.Hex);throw new Error("unsupported output encoding. Only base64 and hex are supported.")}update(e){return this._cryptoJSHmac.update(e),this}}class jr{createHash(e){return new Fr(e)}createHmac(e,t){return new Ir(e,t)}randomUUID(){return crypto.randomUUID()}}class Rr{fetch(e,t={}){return fetch(e,t)}createEventSource(e,t){return new n.NullEventSource(e,t)}getEventSourceCapabilities(){return{readTimeout:!1,headers:!1,customMethod:!1}}}class Ar{constructor(e){this.crypto=new jr,this.requests=new Rr,this.info=e}}const Vr={stream:!1,sendEvents:!1,useLdd:!0,diagnosticOptOut:!0,logger:n.BasicLogger.get()};class Nr extends n.LDClientImpl{constructor(t,i,r){const s=new e,a=new Ar(i),o={analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1},l=(e=>{var t;const i=Object.assign(Object.assign({},Vr),e);return null===(t=i.logger)||void 0===t||t.debug(`Using LD options: ${JSON.stringify(i)}`),i})(r);var u,c;super(t,a,l,(u=s,c=l.logger,{onError:e=>{u.listenerCount("error")?u.emit("error",e):null==c||c.error(e.message)},onFailed:e=>{u.emit("failed",e)},onReady:()=>{u.emit("ready")},onUpdate:n.noop,hasEventListeners:()=>!1}),o),this.emitter=s}}class Lr{constructor(e,t,i,r){this._edgeProvider=e,this._description=i,this._logger=r,this.close=n.noop,this.delete=n.noop,this.upsert=n.noop,this._rootKey=`LD-Env-${t}`}async get(e,t,i){const{namespace:r}=e,s="features"===r?"flags":r;this._logger.debug(`Requesting ${t} from ${this._rootKey}.${s}`);try{const e=await this._edgeProvider.get(this._rootKey);if(!e)throw new Error(`${this._rootKey}.${s} is not found in KV.`);const a=n.deserializePoll(e);if(!a)throw new Error(`Error deserializing ${s}`);switch(r){case"features":i(a.flags[t]);break;case"segments":i(a.segments[t]);break;default:i(null)}}catch(e){this._logger.error(e),i(null)}}async all(e,t=n.noop){const{namespace:i}=e,r="features"===i?"flags":i;this._logger.debug(`Requesting all from ${this._rootKey}.${r}`);try{const e=await this._edgeProvider.get(this._rootKey);if(!e)throw new Error(`${this._rootKey}.${r} is not found in KV.`);const s=n.deserializePoll(e);if(!s)throw new Error(`Error deserializing ${r}`);switch(i){case"features":t(s.flags);break;case"segments":t(s.segments);break;default:t({})}}catch(e){this._logger.error(e),t({})}}async initialized(e=n.noop){const t=null!==await this._edgeProvider.get(this._rootKey);this._logger.debug(`Is ${this._rootKey} initialized? ${t}`),e(t)}init(e,t){t()}getDescription(){return this._description}}const Kr=(e,t)=>{const{featureStore:i,logger:r,sendEvents:n}=t,s=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(e);n<r.length;n++)t.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]])}return i}(t,["featureStore","logger","sendEvents"]);if(!e)throw new Error("You must configure the client with a client key");if(!i||"object"!=typeof i||!i.get)throw new Error("You must configure the client with a feature store");if(!r)throw new Error("You must configure the client with a logger");if("{}"!==JSON.stringify(s))throw new Error(`Invalid configuration: ${Object.keys(s).toString()} not supported`);return!0};class $r{platformData(){return{name:"Cloudflare"}}sdkData(){return{name:"@launchdarkly/cloudflare-server-sdk",version:"2.6.0",userAgentBase:"CloudflareEdgeSDK"}}}var Ur=Object.defineProperty,zr=Object.getOwnPropertySymbols,Br=Object.prototype.hasOwnProperty,qr=Object.prototype.propertyIsEnumerable,Hr=(e,t,i)=>t in e?Ur(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;const Wr=(e,t,i={})=>{var r;const s=null!=(r=i.logger)?r:n.BasicLogger.get();return((e,t,i)=>(Kr(e,i),new Nr(e,t,i)))(e,new $r,((e,t)=>{for(var i in t||(t={}))Br.call(t,i)&&Hr(e,i,t[i]);if(zr)for(var i of zr(t))qr.call(t,i)&&Hr(e,i,t[i]);return e})({featureStore:new Lr(t,e,"Cloudflare",s),logger:s},i))};export{Lr as EdgeFeatureStore,Wr as init};
|
|
1
|
+
import{EventEmitter as e}from"node:events";import t from"semver";import i from"crypto-js";var r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},n={},s={};Object.defineProperty(s,"__esModule",{value:!0});s.default=class{constructor(e){this._onRequestStatus=e}getStatus(){return this._lastStatus}async requireStatus(){return this._lastStatus||await this._onRequestStatus(),this._lastStatus}notify(){var e;this._lastStatus&&(null===(e=this._listener)||void 0===e||e.call(this,this._lastStatus))}setListener(e){this._listener=e}setStatus(e){this._lastStatus=e}};var a={},o={};!function(e){function t(e){return e.indexOf("~")?e.replace(/~1/g,"/").replace(/~0/g,"~"):e}class i{constructor(e,i=!1){if(i){const t=e;this._components=[t],this.isValid=""!==t,this.redactionName=t.startsWith("/")?`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`:t}else{if(this.redactionName=e,""===e||"/"===e||e.match(/\/\/|(^\/.*~[^0|^1])|~$/))return this.isValid=!1,void(this._components=[]);!function(e){return!e.startsWith("/")}(e)?e.indexOf("/",1)<0?this._components=[t(e.slice(1))]:this._components=function(e){return(e.startsWith("/")?e.substring(1):e).split("/").map((e=>t(e)))}(e):this._components=[e],"_meta"===this._components[0]?this.isValid=!1:this.isValid=!0}}get(e){const{_components:t,isValid:i}=this;if(!i)return;let r=e;for(let e=0;e<t.length;e+=1){const i=t[e];if(null==r||!Object.prototype.hasOwnProperty.call(r,i)||"object"!=typeof r||Array.isArray(r))return;r=r[i]}return r}getComponent(e){return this._components[e]}get depth(){return this._components.length}get isKind(){return 1===this._components.length&&"kind"===this._components[0]}compare(e){return this.depth===e.depth&&this._components.every(((t,i)=>t===e.getComponent(i)))}}i.InvalidReference=new i("");class r{is(e){if(Array.isArray(e))return!1;const t=typeof e;return"function"===t||"object"===t}getType(){return"factory method or object"}}class n{constructor(e,t){this._typeName=e,this.typeOf=typeof t}is(e){return!Array.isArray(e)&&typeof e===this.typeOf}getType(){return this._typeName}}class s{constructor(e,t){this._typeName=e,this.typeOf=typeof t}is(e){return!!Array.isArray(e)&&(!(e.length>0)||e.every((e=>typeof e===this.typeOf)))}getType(){return this._typeName}}class a extends n{constructor(e){super(`number with minimum value of ${e}`,0),this.min=e}is(e){return typeof e===this.typeOf&&e>=this.min}}class o extends n{constructor(e){super(`string matching ${e}`,""),this.expression=e}is(e){return"string"==typeof e&&!!e.match(this.expression)}}class l{is(e){return"function"==typeof e}getType(){return"function"}}class u{is(e){return"boolean"==typeof e||null==e}getType(){return"boolean | undefined | null"}}const c=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/;class d{is(e){return"number"==typeof e||"string"==typeof e&&c.test(e)}getType(){return"date"}}class h extends o{constructor(){super(/^(\w|\.|-)+$/)}is(e){return super.is(e)&&"kind"!==e}}class f{static createTypeArray(e,t){return new s(e,t)}static numberWithMin(e){return new a(e)}static stringMatchingRegex(e){return new o(e)}}function g(e){return"kind"in e&&(f.String.is(e.kind)&&"multi"!==e.kind)}function v(e){return"kind"in e&&(f.String.is(e.kind)&&"multi"===e.kind)}function _(e){return!("kind"in e)||null===e.kind||void 0===e.kind}f.String=new n("string",""),f.Number=new n("number",0),f.ObjectOrFactory=new r,f.Object=new n("object",{}),f.StringArray=new s("string[]",""),f.Boolean=new n("boolean",!0),f.Function=new l,f.Date=new d,f.Kind=new h,f.NullableBoolean=new u;const p="user";function y(e){return e.includes("%")||e.includes(":")?e.replace(/%/g,"%25").replace(/:/g,"%3A"):e}function m(e){return f.Kind.is(e)}function b(e){return f.String.is(e)&&""!==e}function w(e,t=!1){return e?e.map((e=>new i(e,t))):[]}class S{constructor(e,t,i){this._isMulti=!1,this._isUser=!1,this._wasLegacy=!1,this._contexts={},this.kind=t,this.valid=e,this.message=i}static _contextForError(e,t){return new S(!1,e,t)}static _getValueFromContext(e,t){if(t&&e.isValid)return 1===e.depth&&"anonymous"===e.getComponent(0)?!!t?.anonymous:e.get(t)}_contextForKind(e){return this._isMulti?this._contexts[e]:this.kind===e?this._context:void 0}static _fromMultiKindContext(e){const t=Object.keys(e).filter((e=>"kind"!==e)),i=t.every(m);if(!t.length)return S._contextForError("multi","A multi-kind context must contain at least one kind");if(!i)return S._contextForError("multi","Context contains invalid kinds");const r={};let n=!0;const s=t.reduce(((t,i)=>{const s=e[i];var a;return(a=s)&&f.Object.is(a)?(t[i]=s,r[i]=w(s._meta?.privateAttributes)):n=!1,t}),{});if(!n)return S._contextForError("multi","Context contained contexts that were not objects");if(!Object.values(s).every((e=>b(e.key))))return S._contextForError("multi","Context contained invalid keys");if(1===t.length){const e=t[0],i=new S(!0,e);return i._context={...s[e],kind:e},i._privateAttributeReferences=r,i._isUser="user"===e,i}const a=new S(!0,e.kind);return a._contexts=s,a._privateAttributeReferences=r,a._isMulti=!0,a}static _fromSingleKindContext(e){const{key:t,kind:i}=e,r=m(i),n=b(t);if(!r)return S._contextForError(i??"unknown","The kind was not valid for the context");if(!n)return S._contextForError(i,"The key for the context was not valid");const s=w(e._meta?.privateAttributes),a=new S(!0,i);return a._isUser="user"===i,a._context=e,a._privateAttributeReferences={[i]:s},a}static _fromLegacyUser(e){if(!(void 0!==e.key&&null!==e.key))return S._contextForError("user","The key for the context was not valid");const t=new S(!0,"user");return t._isUser=!0,t._wasLegacy=!0,t._context=function(e){const t={...e.custom||[],kind:"user",key:String(e.key)};if(null!=e.anonymous){const i=!!e.anonymous;delete t.anonymous,t.anonymous=i}return null!==e.name&&void 0!==e.name&&(t.name=e.name),null!==e.ip&&void 0!==e.ip&&(t.ip=e.ip),null!==e.firstName&&void 0!==e.firstName&&(t.firstName=e.firstName),null!==e.lastName&&void 0!==e.lastName&&(t.lastName=e.lastName),null!==e.email&&void 0!==e.email&&(t.email=e.email),null!==e.avatar&&void 0!==e.avatar&&(t.avatar=e.avatar),null!==e.country&&void 0!==e.country&&(t.country=e.country),null!==e.privateAttributeNames&&void 0!==e.privateAttributeNames&&(t._meta={privateAttributes:e.privateAttributeNames}),t}(e),t._privateAttributeReferences={user:w(e.privateAttributeNames,!0)},t}static fromLDContext(e){return e?g(e)?S._fromSingleKindContext(e):v(e)?S._fromMultiKindContext(e):_(e)?S._fromLegacyUser(e):S._contextForError("unknown","Context was not of a valid kind"):S._contextForError("unknown","No context specified. Returning default value")}static toLDContext(e){if(!e.valid)return;const t=e.getContexts();if(!e._isMulti)return t[0][1];const i={kind:"multi"};return t.forEach((e=>{const t=e[0],r=e[1];i[t]=r})),i}valueForKind(e,t=p){return e.isKind?this.kinds:S._getValueFromContext(e,this._contextForKind(t))}key(e=p){return this._contextForKind(e)?.key}get isMultiKind(){return this._isMulti}get canonicalKey(){return this._isUser?this._context.key:this._isMulti?Object.keys(this._contexts).sort().map((e=>`${e}:${y(this._contexts[e].key)}`)).join(":"):`${this.kind}:${y(this._context.key)}`}get kinds(){return this._isMulti?Object.keys(this._contexts):[this.kind]}get kindsAndKeys(){return this._isMulti?Object.entries(this._contexts).reduce(((e,[t,i])=>(e[t]=i.key,e)),{}):{[this.kind]:this._context.key}}privateAttributes(e){return this._privateAttributeReferences?.[e]||[]}getContexts(){return this._isMulti?Object.entries(this._contexts):[[this.kind,this._context]]}get legacy(){return this._wasLegacy}}S.UserKind=p;const k=["key","kind","_meta","anonymous"].map((e=>new i(e,!0))),E=["name","ip","firstName","lastName","email","avatar","country"];class O{constructor(e,t){this._allAttributesPrivate=e,this._privateAttributes=t}filter(e,t=!1){const i=e.getContexts();if(1===i.length)return this._filterSingleKind(e,i[0][1],i[0][0],t);const r={kind:"multi"};return i.forEach((([i,n])=>{r[i]=this._filterSingleKind(e,n,i,t)})),r}_getAttributesToFilter(e,t,r,n){return(n?Object.keys(t).map((e=>new i(e,!0))):[...this._privateAttributes,...e.privateAttributes(r)]).filter((e=>!k.some((t=>t.compare(e)))))}_filterSingleKind(e,t,i,r){const n=this._allAttributesPrivate||r&&!0===t.anonymous,{cloned:s,excluded:a}=function(e,t){const i=[],r={},n=[];for(i.push(...Object.keys(e).map((t=>({key:t,ptr:[t],source:e,parent:r,visited:[e]}))));i.length;){const e=i.pop(),r=t.find((t=>{return i=t,r=e.ptr,i.depth===r.length&&r.every(((e,t)=>e===i.getComponent(t)));var i,r}));if(r)n.push(r.redactionName);else{const t=e.source[e.key];null===t?e.parent[e.key]=t:Array.isArray(t)?e.parent[e.key]=[...t]:"object"==typeof t?e.visited.includes(t)||(e.parent[e.key]={},i.push(...Object.keys(t).map((i=>({key:i,ptr:[...e.ptr,i],source:t,parent:e.parent[e.key],visited:[...e.visited,t]}))))):e.parent[e.key]=t}}return{cloned:r,excluded:n.sort()}}(t,this._getAttributesToFilter(e,t,i,n));return e.legacy&&E.forEach((e=>{e in s&&(s[e]=String(s[e]))})),a.length&&(s._meta||(s._meta={}),s._meta.redactedAttributes=a),s._meta&&(delete s._meta.privateAttributes,0===Object.keys(s._meta).length&&delete s._meta),s}}var x,D,M,P;e.DataSourceErrorKind=void 0,(x=e.DataSourceErrorKind||(e.DataSourceErrorKind={})).Unknown="UNKNOWN",x.NetworkError="NETWORK_ERROR",x.ErrorResponse="ERROR_RESPONSE",x.InvalidData="INVALID_DATA";class T extends Error{constructor(e){super(e),this.name="LaunchDarklyFileDataSourceError"}}class C extends Error{constructor(e,t,i,r=!0){super(t),this.kind=e,this.status=i,this.name="LaunchDarklyPollingError",this.recoverable=r}}class F extends Error{constructor(e,t,i,r=!0){super(t),this.kind=e,this.code=i,this.name="LaunchDarklyStreamingError",this.recoverable=r}}e.AutoEnvAttributes=void 0,(D=e.AutoEnvAttributes||(e.AutoEnvAttributes={}))[D.Disabled=0]="Disabled",D[D.Enabled=1]="Enabled",function(e){e[e.AnalyticsEvents=0]="AnalyticsEvents",e[e.DiagnosticEvent=1]="DiagnosticEvent"}(M||(M={})),function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed",e[e.FailedAndMustShutDown=2]="FailedAndMustShutDown"}(P||(P={}));var I=Object.freeze({__proto__:null,get LDDeliveryStatus(){return P},get LDEventType(){return M}});function j(e){if("string"==typeof e)return e;if(void 0===e)return"undefined";if(null===e)return"null";if(Object.prototype.hasOwnProperty.call(e,"toString"))try{return e.toString()}catch{}if("bigint"==typeof e)return`${e}n`;try{return JSON.stringify(e)}catch(e){return e instanceof TypeError&&e.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}const R={s:e=>j(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=>j(e),o:e=>j(e),O:e=>j(e),c:()=>""};function A(...e){const t=e.shift();if(f.String.is(t)){let i="",r=0;for(;r<t.length;){const n=t.charAt(r);if("%"===n){if(r+1<t.length){const n=t.charAt(r+1);if(n in R&&e.length){const t=e.shift();i+=R[n]?.(t)}else i+="%"===n?"%":`%${n}`;r+=2}}else i+=n,r+=1}return e.length&&(i.length&&(i+=" "),i+=e.map(j).join(" ")),i}return e.map(j).join(" ")}var V;!function(e){e[e.debug=0]="debug",e[e.info=1]="info",e[e.warn=2]="warn",e[e.error=3]="error",e[e.none=4]="none"}(V||(V={}));const N=["debug","info","warn","error","none"];class L{static get(){return new L({})}constructor(e){if(this._logLevel=V[e.level??"info"]??V.info,this._name=e.name??"LaunchDarkly",this._formatter=e.formatter,"object"==typeof e.destination)this._destinations={[V.debug]:e.destination.debug,[V.info]:e.destination.info,[V.warn]:e.destination.warn,[V.error]:e.destination.error};else if("function"==typeof e.destination){const{destination:t}=e;this._destinations={[V.debug]:t,[V.info]:t,[V.warn]:t,[V.error]:t}}}_tryFormat(...e){try{return this._formatter?this._formatter?.(...e):A(...e)}catch{return A(...e)}}_tryWrite(e,t){try{e(t)}catch{console.error(t)}}_log(e,t){if(e>=this._logLevel){const i=`${N[e]}: [${this._name}]`;try{const r=this._destinations?.[e];r?this._tryWrite(r,`${i} ${this._tryFormat(...t)}`):console.error(...t)}catch{console.error(...t)}}}error(...e){this._log(V.error,e)}warn(...e){this._log(V.warn,e)}info(...e){this._log(V.info,e)}debug(...e){this._log(V.debug,e)}}const K={error:f.Function,warn:f.Function,info:f.Function,debug:f.Function};class ${constructor(e,t){Object.entries(K).forEach((([t,i])=>{if(!i.is(e[t]))throw new Error(`Provided logger instance must support logger.${t}(...) method`)})),this._logger=e,this._fallback=t}_log(e,t){try{this._logger[e](...t)}catch{this._fallback[e](...t)}}error(...e){this._log("error",e)}warn(...e){this._log("warn",e)}info(...e){this._log("info",e)}debug(...e){this._log("debug",e)}}class U{static deprecated(e,t){return`"${e}" is deprecated, please use "${t}"`}static optionBelowMinimum(e,t,i){return`Config option "${e}" had invalid value of ${t}, using minimum of ${i} instead`}static unknownOption(e){return`Ignoring unknown config option "${e}"`}static wrongOptionType(e,t,i){return`Config option "${e}" should be of type ${t}, got ${i}, using default value`}static wrongOptionTypeBoolean(e,t){return`Config option "${e}" should be a boolean, got ${t}, converting to boolean`}static invalidTagValue(e){return`Config option "${e}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(e){return`Value of "${e}" was longer than 64 characters and was discarded.`}static partialEndpoint(e){return`You have set custom uris without specifying the ${e} URI; connections may not work properly`}}const z=f.stringMatchingRegex(/^(\w|\.|-)+$/),B=(e,t)=>z.is(e)?e.length>64?{valid:!1,message:U.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:U.invalidTagValue(t)};function q(e){return e.replace(/\/+$/,"")}function H(e){return e.replace(/^\/+/,"").replace(/\?$/,"")}class W{constructor(e,t,i=W.DEFAULT_EVENTS,r="/bulk",n="/diagnostic",s=!0,a){this.streaming=q(e),this.polling=q(t),this.events=q(i),this.analyticsEventPath=r,this.diagnosticEventPath=n,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}}function J(e,t){if(0===t.length)return e;return`${e}?${t.map((({key:e,value:t})=>`${e}=${t}`)).join("&")}`}function G(e,t,i){const r=H(t),n=[...i];return e.payloadFilterKey&&n.push({key:"filter",value:e.payloadFilterKey}),J(`${e.streaming}/${r}`,n)}function X(e,t,i){const r=H(t);return J(`${e.events}/${r}`,i)}W.DEFAULT_EVENTS="https://events.launchdarkly.com";class Y extends Error{constructor(e){super(e),this.name="LaunchDarklyUnexpectedResponseError"}}class Q extends Error{constructor(e){super(e),this.name="LaunchDarklyClientError"}}class Z extends Error{constructor(e){super(e),this.name="LaunchDarklyTimeoutError"}}function ee(e){return!(e>=400&&e<500)||(400===e||408===e||429===e)}function te(e){return 413===e||ee(e)}const ie=(e,t)=>e?Object.entries(e).reduce(((e,[i,r])=>(!Boolean(r)||(e=>"{}"===JSON.stringify(e))(r)||t?.includes(i)||(e[i]="object"==typeof r?ie(r,t):r),e)),{}):e;function re(e,t,i){let r;r=e.status?`error ${e.status}${401===e.status?" (invalid SDK key)":""}`:`I/O error (${e.message||"unknown error"})`;return`Received ${r} for ${t} - ${i??"giving up permanently"}`}function ne({status:e}){return!e||ee(e)}const se=async(e=1e3)=>new Promise((t=>{setTimeout(t,e)}));var ae;!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"}(ae||(ae={}));var oe=ae;class le{static invalidMetricValue(e){return`The track function was called with a non-numeric "metricValue" (${e}), only numeric metric values are supported.`}}le.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";class ue{constructor(e,t){const{basicConfiguration:i,platform:r}=e,{serviceEndpoints:{analyticsEventPath:n,diagnosticEventPath:s}}=i,{crypto:a,requests:o}=r;this._defaultHeaders={...t},this._eventsUri=X(i.serviceEndpoints,n,[]),this._diagnosticEventsUri=X(i.serviceEndpoints,s,[]),this._requests=o,this._crypto=a}async _tryPostingEvents(e,t,i,r){const n={status:P.Succeeded},s={...this._defaultHeaders,"content-type":"application/json"};let a;i&&(s["x-launchdarkly-payload-id"]=i,s["x-launchDarkly-event-schema"]="4");try{const{status:i,headers:r}=await this._requests.fetch(t,{headers:s,body:JSON.stringify(e),method:"POST",keepalive:!0}),o=Date.parse(r.get("date")||"");if(o&&(n.serverTime=o),i<=204)return n;if(a=new Y(re({status:i,message:"some events were dropped"},"event posting")),!ee(i))return te(i)?n.status=P.Failed:n.status=P.FailedAndMustShutDown,n.error=a,n}catch(e){a=e}return a&&!r?(n.status=P.Failed,n.error=a,n):(await se(),this._tryPostingEvents(e,this._eventsUri,i,!1))}async sendEventData(e,t){const i=e===M.AnalyticsEvents?this._crypto.randomUUID():void 0,r=e===M.AnalyticsEvents?this._eventsUri:this._diagnosticEventsUri;return this._tryPostingEvents(t,r,i,!0)}}function ce(e){return"feature"===e.kind}class de{constructor(e,t,i,r,n,s){this.count=e,this.key=t,this.value=i,this.version=n,this.variation=s,this.default=r}increment(){this.count+=1}}class he{constructor(){this._startDate=0,this._endDate=0,this._counters={},this._contextKinds={}}summarizeEvent(e){if(ce(e)&&!e.excludeFromSummaries){const t=function(e){return`${e.key}:${null!==e.variation&&void 0!==e.variation?e.variation:""}:${null!==e.version&&void 0!==e.version?e.version:""}`}(e),i=this._counters[t];let r=this._contextKinds[e.key];r||(r=new Set,this._contextKinds[e.key]=r),e.context.kinds.forEach((e=>r.add(e))),i?i.increment():this._counters[t]=new de(1,e.key,e.value,e.default,e.version,e.variation),(0===this._startDate||e.creationDate<this._startDate)&&(this._startDate=e.creationDate),e.creationDate>this._endDate&&(this._endDate=e.creationDate)}}getSummary(){const e=Object.values(this._counters).reduce(((e,t)=>{let i=e[t.key];i||(i={default:t.default,counters:[],contextKinds:[...this._contextKinds[t.key]]},e[t.key]=i);const r={value:t.value,count:t.count};return void 0!==t.variation&&null!==t.variation&&(r.variation=t.variation),void 0!==t.version&&null!==t.version?r.version=t.version:r.unknown=!0,i.counters.push(r),e}),{});return{startDate:this._startDate,endDate:this._endDate,features:e,kind:"summary"}}clearSummary(){this._startDate=0,this._endDate=0,this._counters={},this._contextKinds={}}}class fe extends Error{constructor(e){super(e),this.name="LaunchDarklyInvalidSDKKeyError"}}function ge(e){const t=Math.trunc(e);return 1===t||0!==t&&0===Math.floor(Math.random()*t)}class ve{constructor(e,t,i,r,n=1,s){this.context=e,this.key=t,this.data=i,this.metricValue=r,this.samplingRatio=n,this.url=s,this.kind="custom",this.creationDate=Date.now(),this.context=e}}class _e{constructor(e,t,i,r,n,s,a,o,l,u,c,d,h=1){this.withReasons=e,this.context=t,this.key=i,this.samplingRatio=h,this.kind="feature",this.creationDate=Date.now(),this.value=r,this.default=n,void 0!==s&&(this.version=s),void 0!==a&&(this.variation=a),void 0!==o&&(this.trackEvents=o),void 0!==l&&(this.prereqOf=l),void 0!==u&&(this.reason=u),void 0!==c&&(this.debugEventsUntilDate=c),void 0!==d&&(this.excludeFromSummaries=d)}}class pe{constructor(e,t=1){this.context=e,this.samplingRatio=t,this.kind="identify",this.creationDate=Date.now()}}var ye=Object.freeze({__proto__:null,ClientMessages:le,DiagnosticsManager:class{constructor(e,t,i){this._platform=t,this._diagnosticInitConfig=i,this._streamInits=[],this._startTime=Date.now(),this._dataSinceDate=this._startTime,this._id={diagnosticId:t.crypto.randomUUID(),sdkKeySuffix:e.length>6?e.substring(e.length-6):e}}createInitEvent(){const e=this._platform.info.sdkData(),t=this._platform.info.platformData();return{kind:"diagnostic-init",id:this._id,creationDate:this._startTime,sdk:e,configuration:this._diagnosticInitConfig,platform:{name:t.name,osArch:t.os?.arch,osName:t.os?.name,osVersion:t.os?.version,...t.additional||{}}}}recordStreamInit(e,t,i){const r={timestamp:e,failed:t,durationMillis:i};this._streamInits.push(r)}createStatsEventAndReset(e,t,i){const r=Date.now(),n={kind:"diagnostic",id:this._id,creationDate:r,dataSinceDate:this._dataSinceDate,droppedEvents:e,deduplicatedUsers:t,eventsInLastBatch:i,streamInits:this._streamInits};return this._streamInits=[],this._dataSinceDate=r,n}},ErrorKinds:oe,EventFactoryBase:class{constructor(e){this._withReasons=e}evalEvent(e){return new _e(this._withReasons,e.context,e.flagKey,e.value,e.defaultVal,e.version,e.variation??void 0,e.trackEvents||e.addExperimentData,e.prereqOfFlagKey,this._withReasons||e.addExperimentData?e.reason:void 0,e.debugEventsUntilDate,e.excludeFromSummaries,e.samplingRatio)}unknownFlagEvent(e,t,i){return new _e(this._withReasons,i,e,t,t,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(e){return new pe(e,1)}customEvent(e,t,i,r,n=1){return new ve(t,e,i??void 0,r??void 0,n)}},EventProcessor:class{constructor(e,t,r,n,s,a=!0){this._config=e,this._contextDeduplicator=n,this._diagnosticsManager=s,this._summarizer=new he,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 ue(t,r),this._contextFilter=new O(e.allAttributesPrivate,e.privateAttributes.map((e=>new i(e)))),a&&this.start()}start(){if(void 0!==this._contextDeduplicator?.flushInterval&&(this._flushUsersTimer=setInterval((()=>{this._contextDeduplicator?.flush()}),1e3*this._contextDeduplicator.flushInterval)),this._flushTimer=setInterval((async()=>{try{await this.flush()}catch(e){this._logger?.debug(`Flush failed: ${e}`)}}),1e3*this._config.flushInterval),this._diagnosticsManager){const e=this._diagnosticsManager.createInitEvent();this._postDiagnosticEvent(e),this._diagnosticsTimer=setInterval((()=>{const e=this._diagnosticsManager.createStatsEventAndReset(this._droppedEvents,this._deduplicatedUsers,this._eventsInLastBatch);this._droppedEvents=0,this._deduplicatedUsers=0,this._postDiagnosticEvent(e)}),1e3*this._config.diagnosticRecordingInterval)}this._logger?.debug("Started EventProcessor.")}_postDiagnosticEvent(e){this._eventSender.sendEventData(M.DiagnosticEvent,e)}close(){clearInterval(this._flushTimer),this._flushUsersTimer&&clearInterval(this._flushUsersTimer),this._diagnosticsTimer&&clearInterval(this._diagnosticsTimer)}async flush(){if(this._shutdown)throw new fe("Events cannot be posted because a permanent error has been encountered. This is most likely an invalid SDK key. The specific error information is logged independently.");const e=this._queue;this._queue=[];const t=this._summarizer.getSummary();this._summarizer.clearSummary(),Object.keys(t.features).length&&e.push(t),e.length&&(this._eventsInLastBatch=e.length,this._logger?.debug("Flushing %d events",e.length),await this._tryPostingEvents(e))}sendEvent(e){if(this._shutdown)return;if("migration_op"===e.kind){if(ge(e.samplingRatio)){const t={...e};1===t.samplingRatio&&delete t.samplingRatio,this._enqueue(t)}return}this._summarizer.summarizeEvent(e);const t=ce(e),i=t&&e.trackEvents||!t,r=this._shouldDebugEvent(e),n=function(e){return"identify"===e.kind}(e),s=this._contextDeduplicator?.processContext(e.context);s||n||(this._deduplicatedUsers+=1);s&&!n&&this._enqueue(this._makeOutputEvent({kind:"index",creationDate:e.creationDate,context:e.context,samplingRatio:1},!1)),i&&ge(e.samplingRatio)&&this._enqueue(this._makeOutputEvent(e,!1)),r&&ge(e.samplingRatio)&&this._enqueue(this._makeOutputEvent(e,!0))}_makeOutputEvent(e,t){switch(e.kind){case"feature":{const i={kind:t?"debug":"feature",creationDate:e.creationDate,context:this._contextFilter.filter(e.context,!t),key:e.key,value:e.value,default:e.default};return 1!==e.samplingRatio&&(i.samplingRatio=e.samplingRatio),e.prereqOf&&(i.prereqOf=e.prereqOf),void 0!==e.variation&&(i.variation=e.variation),void 0!==e.version&&(i.version=e.version),e.reason&&(i.reason=e.reason),i}case"index":case"identify":{const t={kind:e.kind,creationDate:e.creationDate,context:this._contextFilter.filter(e.context)};return 1!==e.samplingRatio&&(t.samplingRatio=e.samplingRatio),t}case"custom":{const t={kind:"custom",creationDate:e.creationDate,key:e.key,contextKeys:e.context.kindsAndKeys};return 1!==e.samplingRatio&&(t.samplingRatio=e.samplingRatio),void 0!==e.data&&(t.data=e.data),void 0!==e.metricValue&&(t.metricValue=e.metricValue),void 0!==e.url&&(t.url=e.url),t}case"click":return{kind:"click",creationDate:e.creationDate,contextKeys:e.context.kindsAndKeys,key:e.key,url:e.url,selector:e.selector};case"pageview":return{kind:"pageview",creationDate:e.creationDate,contextKeys:e.context.kindsAndKeys,key:e.key,url:e.url};default:return e}}_enqueue(e){this._queue.length<this._capacity?(this._queue.push(e),this._exceededCapacity=!1):(this._exceededCapacity||(this._exceededCapacity=!0,this._logger?.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this._droppedEvents+=1)}_shouldDebugEvent(e){return ce(e)&&e.debugEventsUntilDate&&e.debugEventsUntilDate>this._lastKnownPastTime&&e.debugEventsUntilDate>Date.now()}async _tryPostingEvents(e){const t=await this._eventSender.sendEventData(M.AnalyticsEvents,e);if(t.status===P.FailedAndMustShutDown&&(this._shutdown=!0),t.serverTime&&(this._lastKnownPastTime=t.serverTime),t.error)throw t.error}},InputCustomEvent:ve,InputEvalEvent:_e,InputIdentifyEvent:pe,NullEventProcessor:class{close(){}async flush(){}sendEvent(){}},StreamingProcessor:class{constructor(e,t,i,r,n,s,a,o=1){this._listeners=r,this._diagnosticsManager=s,this._errorHandler=a,this._streamInitialReconnectDelay=o;const{basicConfiguration:l,platform:u}=e,{logger:c}=l,{requests:d}=u;this._headers={...n},this._logger=c,this._requests=d,this._streamUri=G(l.serviceEndpoints,t,i)}_logConnectionStarted(){this._connectionAttemptStartTime=Date.now()}_logConnectionResult(e){this._connectionAttemptStartTime&&this._diagnosticsManager&&this._diagnosticsManager.recordStreamInit(this._connectionAttemptStartTime,!e,Date.now()-this._connectionAttemptStartTime),this._connectionAttemptStartTime=void 0}_retryAndHandleError(t){return ne(t)?(this._logger?.warn(re(t,"streaming request","will retry")),this._logConnectionResult(!1),this._logConnectionStarted(),!0):(this._logConnectionResult(!1),this._errorHandler?.(new F(e.DataSourceErrorKind.ErrorResponse,t.message,t.status)),this._logger?.error(re(t,"streaming request")),!1)}start(){this._logConnectionStarted();const t=this._requests.createEventSource(this._streamUri,{headers:this._headers,errorFilter:e=>this._retryAndHandleError(e),initialRetryDelayMillis:1e3*this._streamInitialReconnectDelay,readTimeoutMillis:3e5,retryResetIntervalMillis:6e4});this._eventSource=t,t.onclose=()=>{this._logger?.info("Closed LaunchDarkly stream connection")},t.onerror=()=>{},t.onopen=()=>{this._logger?.info("Opened LaunchDarkly stream connection")},t.onretrying=e=>{this._logger?.info(`Will retry stream connection in ${e.delayMillis} milliseconds`)},this._listeners.forEach((({deserializeData:i,processJson:r},n)=>{t.addEventListener(n,(t=>{if(this._logger?.debug(`Received ${n} event`),t?.data){this._logConnectionResult(!0);const{data:s}=t,a=i(s);if(!a)return void((t,i,r,n)=>{r?.error(`Stream received invalid data in "${t}" message`),r?.debug(`Invalid JSON follows: ${i}`),n?.(new F(e.DataSourceErrorKind.InvalidData,"Malformed JSON data in event stream"))})(n,s,this._logger,this._errorHandler);r(a)}else this._errorHandler?.(new F(e.DataSourceErrorKind.Unknown,"Unexpected payload from event stream"))}))}))}stop(){this._eventSource?.close(),this._eventSource=void 0}close(){this.stop()}},isLegacyUser:_,isMultiKind:v,isSingleKind:g,shouldSample:ge});e.ApplicationTags=class{constructor(e){const t={},i=e?.application,r=e?.logger;i&&Object.entries(i).forEach((([e,i])=>{if(null!=i){const{valid:n,message:s}=B(i,`application.${e}`);n?"versionName"===e?t["application-version-name"]=[i]:t[`application-${e}`]=[i]:r?.warn(s)}}));const n=Object.keys(t);n.length&&(this.value=n.sort().flatMap((e=>t[e].sort().map((t=>`${e}/${t}`)))).join(" "))}},e.AttributeReference=i,e.BasicLogger=L,e.ClientContext=class{constructor(e,t,i){this.platform=i,this.basicConfiguration={tags:t.tags,logger:t.logger,offline:t.offline,serviceEndpoints:t.serviceEndpoints,sdkKey:e}}},e.Context=S,e.ContextFilter=O,e.DateValidator=d,e.FactoryOrInstance=r,e.Function=l,e.KindValidator=h,e.LDClientError=Q,e.LDFileDataSourceError=T,e.LDPollingError=C,e.LDStreamingError=F,e.LDTimeoutError=Z,e.LDUnexpectedResponseError=Y,e.NullableBoolean=u,e.NumberWithMinimum=a,e.OptionMessages=U,e.SafeLogger=$,e.ServiceEndpoints=W,e.StringMatchingRegex=o,e.Type=n,e.TypeArray=s,e.TypeValidators=f,e.base64UrlEncode=(e,t)=>t.btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),e.cancelableTimedPromise=function(e,t){let i,r;return{promise:new Promise(((n,s)=>{r=n,i=setTimeout((()=>{s(new Z(`${t} timed out after ${e} seconds.`))}),1e3*e)})),cancel:()=>{r(),clearTimeout(i)}}},e.clone=function(e){return null==e?e:JSON.parse(JSON.stringify(e))},e.createSafeLogger=e=>{const t=new L({level:"info",destination:console.error,formatter:A});return e?new $(e,t):t},e.debounce=(e,t=5e3)=>{let i;return(...r)=>{clearTimeout(i),i=setTimeout((()=>{e(...r)}),t)}},e.deepCompact=ie,e.defaultHeaders=function(e,t,i,r=!0,n="user-agent"){const{userAgentBase:s,version:a,wrapperName:o,wrapperVersion:l}=t.sdkData(),u={[n]:`${s??"NodeJSClient"}/${a}`};return r&&(u.authorization=e),o&&(u["x-launchdarkly-wrapper"]=l?`${o}/${l}`:o),i?.value&&(u["x-launchdarkly-tags"]=i.value),u},e.fastDeepEqual=function e(t,i){if(t===i)return!0;if(t&&i&&"object"==typeof t&&"object"==typeof i){if(t.constructor!==i.constructor)return!1;var r,n,s;if(Array.isArray(t)){if((r=t.length)!=i.length)return!1;for(n=r;0!=n--;)if(!e(t[n],i[n]))return!1;return!0}if(t instanceof Map&&i instanceof Map){if(t.size!==i.size)return!1;for(n of t.entries())if(!i.has(n[0]))return!1;for(n of t.entries())if(!e(n[1],i.get(n[0])))return!1;return!0}if(t instanceof Set&&i instanceof Set){if(t.size!==i.size)return!1;for(n of t.entries())if(!i.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(i)){if((r=t.length)!=i.length)return!1;for(n=r;0!=n--;)if(t[n]!==i[n])return!1;return!0}if(t.constructor===RegExp)return t.source===i.source&&t.flags===i.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===i.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===i.toString();if((r=(s=Object.keys(t)).length)!==Object.keys(i).length)return!1;for(n=r;0!=n--;)if(!Object.prototype.hasOwnProperty.call(i,s[n]))return!1;for(n=r;0!=n--;){var a=s[n];if(!e(t[a],i[a]))return!1}return!0}return t!=t&&i!=i},e.getEventsUri=X,e.getPollingUri=function(e,t,i){const r=H(t),n=[...i];return e.payloadFilterKey&&n.push({key:"filter",value:e.payloadFilterKey}),J(`${e.polling}/${r}`,n)},e.getStreamingUri=G,e.httpErrorMessage=re,e.internal=ye,e.isHttpLocallyRecoverable=te,e.isHttpRecoverable=ee,e.noop=()=>{},e.secondsToMillis=function(e){return Math.trunc(1e3*e)},e.shouldRetry=ne,e.sleep=se,e.subsystem=I,e.timedPromise=(e,t)=>new Promise(((i,r)=>{setTimeout((()=>{r(new Z(`${t} timed out after ${e} seconds.`))}),1e3*e)}))}(o);var l={},u={},c={};Object.defineProperty(c,"__esModule",{value:!0});var d={};Object.defineProperty(d,"__esModule",{value:!0});var h,f,g={};Object.defineProperty(g,"__esModule",{value:!0}),g.IsMigrationStage=g.LDMigrationStage=void 0,(f=h||(g.LDMigrationStage=h={})).Off="off",f.DualWrite="dualwrite",f.Shadow="shadow",f.Live="live",f.RampDown="rampdown",f.Complete="complete",g.IsMigrationStage=function(e){return Object.values(h).includes(e)};var v={};Object.defineProperty(v,"__esModule",{value:!0});var _,p,y,m,b,w={};Object.defineProperty(w,"__esModule",{value:!0}),w.LDConsistencyCheck=void 0,(p=_||(w.LDConsistencyCheck=_={}))[p.Inconsistent=0]="Inconsistent",p[p.Consistent=1]="Consistent",p[p.NotChecked=2]="NotChecked",y=u,m=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),b=r&&r.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||m(t,e,i)},Object.defineProperty(y,"__esModule",{value:!0}),b(c,y),b(d,y),b(g,y),b(v,y),b(w,y);var S={},k={};Object.defineProperty(k,"__esModule",{value:!0});var E={};Object.defineProperty(E,"__esModule",{value:!0});var O={};Object.defineProperty(O,"__esModule",{value:!0});var x={};Object.defineProperty(x,"__esModule",{value:!0});var D,M,P,T,C={};Object.defineProperty(C,"__esModule",{value:!0}),C.LDConcurrentExecution=C.LDSerialExecution=C.LDExecution=C.LDExecutionOrdering=void 0,(M=D||(C.LDExecutionOrdering=D={}))[M.Fixed=0]="Fixed",M[M.Random=1]="Random",(T=P||(C.LDExecution=P={}))[T.Serial=0]="Serial",T[T.Concurrent=1]="Concurrent";C.LDSerialExecution=class{constructor(e){this.ordering=e,this.type=P.Serial}};C.LDConcurrentExecution=class{constructor(){this.type=P.Concurrent}},function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i(k,e),i(E,e),i(O,e),i(x,e),i(C,e)}(S);var F={};Object.defineProperty(F,"__esModule",{value:!0});var I={};Object.defineProperty(I,"__esModule",{value:!0});var j={};Object.defineProperty(j,"__esModule",{value:!0});var R={};Object.defineProperty(R,"__esModule",{value:!0});var A={};Object.defineProperty(A,"__esModule",{value:!0});var V={},N={};Object.defineProperty(N,"__esModule",{value:!0});var L={};Object.defineProperty(L,"__esModule",{value:!0}),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i(N,e),i(L,e)}(V);var K={},$={};Object.defineProperty($,"__esModule",{value:!0});var U={};Object.defineProperty(U,"__esModule",{value:!0});var z={};Object.defineProperty(z,"__esModule",{value:!0});var B={};Object.defineProperty(B,"__esModule",{value:!0});var q={};Object.defineProperty(q,"__esModule",{value:!0});var H={};Object.defineProperty(H,"__esModule",{value:!0});var W={};Object.defineProperty(W,"__esModule",{value:!0});var J={};Object.defineProperty(J,"__esModule",{value:!0});var G={};Object.defineProperty(G,"__esModule",{value:!0});var X={};Object.defineProperty(X,"__esModule",{value:!0}),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i($,e),i(U,e),i(z,e),i(B,e),i(q,e),i(j,e),i(H,e),i(W,e),i(J,e),i(G,e),i(X,e)}(K);var Y={},Q={};Object.defineProperty(Q,"__esModule",{value:!0});var Z={};Object.defineProperty(Z,"__esModule",{value:!0}),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),i(Q,e),i(R,e),i(Z,e)}(Y),function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.subsystems=e.interfaces=e.integrations=void 0,i(u,e),i(S,e),i(F,e),i(I,e),i(j,e),i(R,e),i(A,e),e.integrations=V,e.interfaces=K,e.subsystems=Y}(l);var ee={},te={};Object.defineProperty(te,"__esModule",{value:!0});te.default=class{constructor(e){this._keyMap=new Map,this._head=0,this._tail=0,this._size=0;const{max:t}=e;this._max=t,this._values=new Array(t),this._keys=new Array(t),this._next=new Uint32Array(t),this._prev=new Uint32Array(t),e.maxAge?(this._lastUpdated=new Array(t).fill(0),this._maxAge=e.maxAge):(this._lastUpdated=[],this._maxAge=0)}set(e,t){let i=this._keyMap.get(e);void 0===i?(i=this._index(),this._keys[i]=e,this._keyMap.set(e,i),this._next[this._tail]=i,this._prev[i]=this._tail,this._tail=i,this._size+=1):this._setTail(i),this._values[i]=t,this._maxAge&&(this._lastUpdated[i]=Date.now())}get(e){const t=this._keyMap.get(e);if(void 0!==t){if(this._maxAge){const e=this._lastUpdated[t];if(Date.now()-e>this._maxAge)return}return this._setTail(t),this._maxAge&&(this._lastUpdated[t]=Date.now()),this._values[t]}}clear(){this._head=0,this._tail=0,this._size=0,this._values.fill(void 0),this._keys.fill(void 0),this._next.fill(0),this._prev.fill(0),this._keyMap.clear()}_index(){return 0===this._size?this._tail:this._size===this._max?this._evict():this._size}_evict(){const{_head:e}=this,t=this._keys[e];return this._head=this._next[e],this._keyMap.delete(t),this._size-=1,e}_link(e,t){this._prev[t]=e,this._next[e]=t}_setTail(e){e!==this._tail&&(e===this._head?this._head=this._next[e]:this._link(this._prev[e],this._next[e]),this._link(this._tail,e),this._tail=e)}},Object.defineProperty(ee,"__esModule",{value:!0});const ie=o,re=s,ne=te;ee.default=class{constructor(e,t,i,r){this._store=e,this._logger=i,this._crypto=r,this.statusProvider=new re.default((async()=>this._pollStoreAndUpdateStatus())),this._staleTimeMs=1e3*(ie.TypeValidators.Number.is(t.staleAfter)&&t.staleAfter>0?t.staleAfter:120);const n=1e3*(ie.TypeValidators.Number.is(t.statusPollInterval)&&t.statusPollInterval>0?t.statusPollInterval:5);this._pollHandle=e?setInterval((()=>this._pollStoreAndUpdateStatus()),n):null,e&&(this._cache=new ne.default({max:t.userCacheSize||1e3,maxAge:1e3*(t.userCacheTime||5)}))}close(){this._pollHandle&&(clearInterval(this._pollHandle),this._pollHandle=void 0),this._store&&this._store.close()}async getUserMembership(e){var t,i,r;if(!this._store)return;const n=null===(t=this._cache)||void 0===t?void 0:t.get(e);let s;if(n)s=n.membership;else try{s=await this._store.getUserMembership(this._hashForUserKey(e));const t={membership:s};null===(i=this._cache)||void 0===i||i.set(e,t)}catch(e){return null===(r=this._logger)||void 0===r||r.error(`Big Segment store membership query returned error: ${e}`),[null,"STORE_ERROR"]}this.statusProvider.getStatus()||await this._pollStoreAndUpdateStatus();const a=this.statusProvider.getStatus();return a.available?[s||null,a.stale?"STALE":"HEALTHY"]:[s||null,"STORE_ERROR"]}async _pollStoreAndUpdateStatus(){var e,t,i;if(!this._store)return void this.statusProvider.setStatus({available:!1,stale:!1});let r;null===(e=this._logger)||void 0===e||e.debug("Querying Big Segment store status");try{const e=await this._store.getMetadata();r={available:!0,stale:!e||!e.lastUpToDate||this._isStale(e.lastUpToDate)}}catch(e){null===(t=this._logger)||void 0===t||t.error(`Big Segment store status query returned error: ${e}`),r={available:!1,stale:!1}}const n=this.statusProvider.getStatus();n&&n.available===r.available&&n.stale===r.stale||(null===(i=this._logger)||void 0===i||i.debug("Big Segment store status changed from %s to %s",JSON.stringify(n),JSON.stringify(r)),this.statusProvider.setStatus(r),this.statusProvider.notify())}_hashForUserKey(e){const t=this._crypto.createHash("sha256");if(t.update(e),!t.digest)throw new Error("Platform must implement digest or asyncDigest");return t.digest("base64")}_isStale(e){return Date.now()-e>=this._staleTimeMs}};var se={},ae={},oe={};Object.defineProperty(oe,"__esModule",{value:!0});class le{static getKeyFromPath(e,t){return t.startsWith(e.streamApiPath)?t.substring(e.streamApiPath.length):void 0}}le.Features={namespace:"features",streamApiPath:"/flags/"},le.Segments={namespace:"segments",streamApiPath:"/segments/"},oe.default=le,Object.defineProperty(ae,"__esModule",{value:!0}),ae.deserializeSegment=ae.serializeSegment=ae.deserializeFlag=ae.serializeFlag=ae.deserializeDelete=ae.deserializePatch=ae.deserializePoll=ae.deserializeAll=ae.processSegment=ae.processFlag=ae.replacer=ae.nullReplacer=void 0;const ue=o,ce=oe,de=100;function he(e,t){const i=[];if(null==e)return;const r=Object.entries(e).filter((([e,i])=>!(null==t?void 0:t.includes(e))));for(i.push(...r.map((([t,i])=>({key:t,value:i,parent:e}))));i.length;){const e=i.pop();null!==e.value||Array.isArray(e.parent)?"object"==typeof e.value&&null!==e.value&&i.push(...Object.entries(e.value).map((([t,i])=>({key:t,value:i,parent:e.value})))):delete e.parent[e.key]}}function fe(e,t){if(!(t instanceof ue.AttributeReference||Array.isArray(t)&&t[0]&&t[0]instanceof ue.AttributeReference))return null==t||(t.generated_includedSet&&(t.included=[...t.generated_includedSet],delete t.generated_includedSet),t.generated_excludedSet&&(t.excluded=[...t.generated_excludedSet],delete t.generated_excludedSet),t.includedContexts&&t.includedContexts.forEach((e=>{e.generated_valuesSet&&(e.values=[...e.generated_valuesSet]),delete e.generated_valuesSet})),t.excludedContexts&&t.excludedContexts.forEach((e=>{e.generated_valuesSet&&(e.values=[...e.generated_valuesSet]),delete e.generated_valuesSet}))),t}function ge(e){e&&e.bucketBy&&(e.bucketByAttributeReference=new ue.AttributeReference(e.bucketBy,!e.contextKind))}function ve(e){var t;if(he(e,["variations"]),e.fallthrough&&e.fallthrough.rollout){ge(e.fallthrough.rollout)}null===(t=null==e?void 0:e.rules)||void 0===t||t.forEach((e=>{var t;ge(e.rollout),null===(t=null==e?void 0:e.clauses)||void 0===t||t.forEach((e=>{e&&e.attribute?e.attributeReference=new ue.AttributeReference(e.attribute,!e.contextKind):e&&(e.attributeReference=ue.AttributeReference.InvalidReference)}))}))}function _e(e){var t,i,r,n,s;he(e),(null===(t=null==e?void 0:e.included)||void 0===t?void 0:t.length)&&e.included.length>de&&(e.generated_includedSet=new Set(e.included),delete e.included),(null===(i=null==e?void 0:e.excluded)||void 0===i?void 0:i.length)&&e.excluded.length>de&&(e.generated_excludedSet=new Set(e.excluded),delete e.excluded),(null===(r=null==e?void 0:e.includedContexts)||void 0===r?void 0:r.length)&&e.includedContexts.forEach((e=>{var t;(null===(t=null==e?void 0:e.values)||void 0===t?void 0:t.length)&&e.values.length>de&&(e.generated_valuesSet=new Set(e.values),e.values=[])})),(null===(n=null==e?void 0:e.excludedContexts)||void 0===n?void 0:n.length)&&e.excludedContexts.forEach((e=>{var t;(null===(t=null==e?void 0:e.values)||void 0===t?void 0:t.length)&&e.values.length>de&&(e.generated_valuesSet=new Set(e.values),e.values=[])})),null===(s=null==e?void 0:e.rules)||void 0===s||s.forEach((e=>{var t;e.bucketBy&&(e.bucketByAttributeReference=new ue.AttributeReference(e.bucketBy,!e.rolloutContextKind)),null===(t=null==e?void 0:e.clauses)||void 0===t||t.forEach((e=>{e&&e.attribute?e.attributeReference=new ue.AttributeReference(e.attribute,!e.contextKind):e&&(e.attributeReference=ue.AttributeReference.InvalidReference)}))}))}function pe(e){try{return JSON.parse(e)}catch(e){return}}ae.nullReplacer=he,ae.replacer=fe,ae.processFlag=ve,ae.processSegment=_e,ae.deserializeAll=function(e){var t,i;const r=pe(e);if(r)return Object.values((null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.flags)||[]).forEach((e=>{ve(e)})),Object.values((null===(i=null==r?void 0:r.data)||void 0===i?void 0:i.segments)||[]).forEach((e=>{_e(e)})),r},ae.deserializePoll=function(e){const t=pe(e);if(t)return Object.values((null==t?void 0:t.flags)||[]).forEach((e=>{ve(e)})),Object.values((null==t?void 0:t.segments)||[]).forEach((e=>{_e(e)})),t},ae.deserializePatch=function(e){const t=pe(e);if(t)return t.path.startsWith(ce.default.Features.streamApiPath)?(ve(t.data),t.kind=ce.default.Features):t.path.startsWith(ce.default.Segments.streamApiPath)&&(_e(t.data),t.kind=ce.default.Segments),t},ae.deserializeDelete=function(e){const t=pe(e);if(t)return t.path.startsWith(ce.default.Features.streamApiPath)?t.kind=ce.default.Features:t.path.startsWith(ce.default.Segments.streamApiPath)&&(t.kind=ce.default.Segments),t},ae.serializeFlag=function(e){return JSON.stringify(e,fe)},ae.deserializeFlag=function(e){const t=pe(e);if(t)return ve(t),t},ae.serializeSegment=function(e){return JSON.stringify(e,fe)},ae.deserializeSegment=function(e){const t=pe(e);if(t)return _e(t),t},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createStreamListeners=e.createDeleteListener=e.createPatchListener=e.createPutListener=void 0;const t=ae,i=oe;e.createPutListener=(e,r,n=()=>{})=>({deserializeData:t.deserializeAll,processJson:async({data:{flags:t,segments:s}})=>{const a={[i.default.Features.namespace]:t,[i.default.Segments.namespace]:s};null==r||r.debug("Initializing all data"),e.init(a,n)}});e.createPatchListener=(e,r,n=()=>{})=>({deserializeData:t.deserializePatch,processJson:async({data:t,kind:s,path:a})=>{if(s){const o=i.default.getKeyFromPath(s,a);o&&(null==r||r.debug(`Updating ${o} in ${s.namespace}`),e.upsert(s,t,n))}}});e.createDeleteListener=(e,r,n=()=>{})=>({deserializeData:t.deserializeDelete,processJson:async({kind:t,path:s,version:a})=>{if(t){const o=i.default.getKeyFromPath(t,s);o&&(null==r||r.debug(`Deleting ${o} in ${t.namespace}`),e.upsert(t,{key:o,version:a,deleted:!0},n))}}});e.createStreamListeners=(t,i,r)=>{const n=new Map;return n.set("put",(0,e.createPutListener)(t,i,null==r?void 0:r.put)),n.set("patch",(0,e.createPatchListener)(t,i,null==r?void 0:r.patch)),n.set("delete",(0,e.createDeleteListener)(t,i,null==r?void 0:r.delete)),n}}(se);var ye={},me={},be={};Object.defineProperty(be,"__esModule",{value:!0});be.default=class{constructor(){this._itemsByNamespace={}}get(e,t){var i;return null===(i=this._itemsByNamespace[e])||void 0===i?void 0:i[t]}set(e,t,i){e in this._itemsByNamespace||(this._itemsByNamespace[e]={}),this._itemsByNamespace[e][t]=i}remove(e,t){const i=this._itemsByNamespace[e];i&&delete i[t]}removeAll(){this._itemsByNamespace={}}enumerate(e){Object.entries(this._itemsByNamespace).forEach((([t,i])=>{Object.entries(i).forEach((([i,r])=>{e(t,i,r)}))}))}mergeFrom(e){e.enumerate(this.set.bind(this))}},Object.defineProperty(me,"__esModule",{value:!0});const we=be;me.default=class{constructor(){this._dependenciesFrom=new we.default,this._dependenciesTo=new we.default}updateDependenciesFrom(e,t,i){const r=this._dependenciesFrom.get(e,t);null==r||r.enumerate(((i,r)=>{const n=this._dependenciesTo.get(i,r);null==n||n.remove(e,t)})),this._dependenciesFrom.set(e,t,i),null==i||i.enumerate(((i,r)=>{let n=this._dependenciesTo.get(i,r);n||(n=new we.default,this._dependenciesTo.set(i,r,n)),n.set(e,t,!0)}))}updateModifiedItems(e,t,i){if(!e.get(t,i)){e.set(t,i,!0);const r=this._dependenciesTo.get(t,i);null==r||r.enumerate(((t,i)=>{this.updateModifiedItems(e,t,i)}))}}reset(){this._dependenciesFrom.removeAll(),this._dependenciesTo.removeAll()}},Object.defineProperty(ye,"__esModule",{value:!0});const Se=oe,ke=me,Ee=be;function Oe(e,t){var i,r;const n=new Ee.default,s=e===Se.default.Features.namespace,a=e===Se.default.Segments.namespace;if(s){const r=t;null===(i=null==r?void 0:r.prerequisites)||void 0===i||i.forEach((t=>{n.set(e,t.key,!0)}))}if(s||a){const e=t;null===(r=null==e?void 0:e.rules)||void 0===r||r.forEach((e=>{var t;null===(t=e.clauses)||void 0===t||t.forEach((e=>{"segmentMatch"===e.op&&e.values.forEach((e=>{n.set(Se.default.Segments.namespace,e,!0)}))}))}))}return n}ye.default=class{constructor(e,t,i){this._featureStore=e,this._hasEventListeners=t,this._onChange=i,this._dependencyTracker=new ke.default}init(e,t){const i=this._hasEventListeners(),r=r=>{this._featureStore.init(e,(()=>{Promise.resolve().then((()=>{if(this._dependencyTracker.reset(),Object.entries(e).forEach((([e,t])=>{Object.keys(t||{}).forEach((i=>{const r=t[i];this._dependencyTracker.updateDependenciesFrom(e,i,Oe(e,r))}))})),i){const t=new Ee.default;Object.keys(e).forEach((i=>{const n=(null==r?void 0:r[i])||{},s=e[i],a=Object.assign(Object.assign({},n),s);Object.keys(a).forEach((e=>{this.addIfModified(i,e,n&&n[e],s&&s[e],t)}))})),this.sendChangeEvents(t)}})),null==t||t()}))};i?this._featureStore.all(Se.default.Features,(e=>{this._featureStore.all(Se.default.Segments,(t=>{const i={[Se.default.Features.namespace]:e,[Se.default.Segments.namespace]:t};r(i)}))})):r()}upsert(e,t,i){const{key:r}=t,n=this._hasEventListeners(),s=s=>{this._featureStore.upsert(e,t,(()=>{Promise.resolve().then((()=>{if(this._dependencyTracker.updateDependenciesFrom(e.namespace,r,Oe(e.namespace,t)),n){const i=new Ee.default;this.addIfModified(e.namespace,r,s,t,i),this.sendChangeEvents(i)}})),null==i||i()}))};n?this._featureStore.get(e,r,s):s()}addIfModified(e,t,i,r,n){r&&i&&r.version<=i.version||this._dependencyTracker.updateModifiedItems(n,e,t)}sendChangeEvents(e){e.enumerate(((e,t)=>{e===Se.default.Features.namespace&&this._onChange(t)}))}};var xe={},De={},Me={},Pe={};Object.defineProperty(Pe,"__esModule",{value:!0}),Pe.default=function(e){return new Promise((t=>{e((e=>{t(e)}))}))},Object.defineProperty(Me,"__esModule",{value:!0});const Te=Pe;Me.default=class{constructor(e){this._store=e}async get(e,t){return(0,Te.default)((i=>{this._store.get(e,t,i)}))}async all(e){return(0,Te.default)((t=>{this._store.all(e,t)}))}async init(e){return(0,Te.default)((t=>{this._store.init(e,t)}))}async delete(e,t,i){return(0,Te.default)((r=>{this._store.delete(e,t,i,r)}))}async upsert(e,t){return(0,Te.default)((i=>{this._store.upsert(e,t,i)}))}async initialized(){return(0,Te.default)((e=>{this._store.initialized(e)}))}close(){this._store.close()}};var Ce={},Fe={};function Ie(e){return Date.now()>e.expiration}Object.defineProperty(Fe,"__esModule",{value:!0});Fe.default=class{constructor(e){this._options=e,this._storage=new Map,this._checkIntervalHandle=setInterval((()=>{this._purgeStale()}),1e3*e.checkInterval)}get(e){const t=this._storage.get(e);if(!t||!Ie(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)=>{Ie(e)&&this._storage.delete(t)}))}get size(){return this._storage.size}};var je={};Object.defineProperty(je,"__esModule",{value:!0}),je.persistentStoreKinds=void 0;const Re=ae,Ae=oe;je.persistentStoreKinds={segments:{namespace:Ae.default.Segments.namespace,deserialize:e=>{const t=(0,Re.deserializeSegment)(e);if(t)return{version:t.version,item:t}},serialize:e=>{const t=(0,Re.serializeSegment)(e);return{version:e.version,deleted:e.deleted,serializedItem:t}},priority:0},features:{namespace:Ae.default.Features.namespace,deserialize:e=>{const t=(0,Re.deserializeFlag)(e);if(t)return{version:t.version,item:t}},serialize:e=>{const t=(0,Re.serializeFlag)(e);return{version:e.version,deleted:e.deleted,serializedItem:t}},priority:1}};var Ve={};Object.defineProperty(Ve,"__esModule",{value:!0});const Ne=je;function Le(e,t){const i=[],r=new Set(Object.keys(t)),n=s=>{if(!r.has(s))return;r.delete(s);const a=t[s];var o;"features"===e.namespace&&(o=a,o.prerequisites&&o.prerequisites.length?o.prerequisites.map((e=>e.key)):[]).forEach((e=>{n(e)})),i.push({key:s,item:e.serialize(a)})};for(;r.size>0;){const e=r.values().next().value;n(e)}return i}Ve.default=function(e){const t=[];return Object.keys(e).forEach((i=>{const r=Ne.persistentStoreKinds[i];t.push({key:r,item:Le(r,e[i])})})),t.sort(((e,t)=>e.key.priority-t.key.priority)),t};var Ke={};Object.defineProperty(Ke,"__esModule",{value:!0});Ke.default=class{constructor(){this._queue=[]}enqueue(e,t){this._queue.push([e,t]),1===this._queue.length&&this.executePendingUpdates()}executePendingUpdates(){if(this._queue.length>0){const[e,t]=this._queue[0];e((()=>{this._queue.shift(),this._queue.length>0&&setTimeout((()=>this.executePendingUpdates()),0),null==t||t()}))}}},Object.defineProperty(Ce,"__esModule",{value:!0});const $e=Fe,Ue=je,ze=Ve,Be=Ke;function qe(e,t){return`${e.namespace}:${t}`}function He(e){return`$all:${e.namespace}`}const We="$checkedInit";function Je(e){return!e||e.item.deleted?null:e.item}function Ge(e){return{version:e,item:{version:e,deleted:!0}}}function Xe(e,t){if(t.deleted||!t.serializedItem)return Ge(t.version);const i=e.deserialize(t.serializedItem);return void 0===i?Ge(t.version):0===i.version||i.version===t.version||void 0===i.item?i:{version:t.version,item:i.item}}Ce.default=class{constructor(e,t){this._core=e,this._isInitialized=!1,this._queue=new Be.default,t&&(this._itemCache=new $e.default({ttl:t,checkInterval:600}),this._allItemsCache=new $e.default({ttl:t,checkInterval:600}))}init(e,t){this._queue.enqueue((t=>{this._core.init((0,ze.default)(e),(()=>{this._isInitialized=!0,this._itemCache&&(this._itemCache.clear(),this._allItemsCache.clear(),Object.keys(e).forEach((t=>{const i=Ue.persistentStoreKinds[t],r=e[t];this._allItemsCache.set(He(i),r),Object.keys(r).forEach((e=>{const t=r[e],n={version:t.version,item:t};this._itemCache.set(qe(i,e),n)}))}))),t()}))}),t)}get(e,t,i){if(this._itemCache){const r=this._itemCache.get(qe(e,t));if(r)return void i(Je(r))}const r=Ue.persistentStoreKinds[e.namespace];this._core.get(r,t,(n=>{var s;if(n&&n.serializedItem){const a=Xe(r,n);return null===(s=this._itemCache)||void 0===s||s.set(qe(e,t),a),void i(Je(a))}i(null)}))}initialized(e){var t;this._isInitialized?e(!0):(null===(t=this._itemCache)||void 0===t?void 0:t.get(We))?e(!1):this._core.initialized((t=>{var i;this._isInitialized=t,this._isInitialized||null===(i=this._itemCache)||void 0===i||i.set(We,!0),e(this._isInitialized)}))}all(e,t){var i;const r=null===(i=this._allItemsCache)||void 0===i?void 0:i.get(He(e));if(r)return void t(r);const n=Ue.persistentStoreKinds[e.namespace];this._core.getAll(n,(i=>{var r;if(!i)return void t({});const s={};i.forEach((({key:e,item:t})=>{const i=Je(Xe(n,t));i&&(s[e]=i)})),null===(r=this._allItemsCache)||void 0===r||r.set(He(e),s),t(s)}))}upsert(e,t,i){this._queue.enqueue((i=>{this._allItemsCache&&this._allItemsCache.clear();const r=Ue.persistentStoreKinds[e.namespace];this._core.upsert(r,t.key,r.serialize(t),((n,s)=>{var a,o;if(!n&&s)if(s.serializedItem){const i=Xe(r,s);null===(a=this._itemCache)||void 0===a||a.set(qe(e,t.key),i)}else s.deleted&&(null===(o=this._itemCache)||void 0===o||o.set(t.key,{key:t.key,version:s.version,deleted:!0}));i()}))}),i)}delete(e,t,i,r){this.upsert(e,{key:t,version:i,deleted:!0},r)}close(){var e,t;null===(e=this._itemCache)||void 0===e||e.close(),null===(t=this._allItemsCache)||void 0===t||t.close(),this._core.close()}getDescription(){return this._core.getDescription()}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.deserializePoll=e.PersistentDataStoreWrapper=e.AsyncStoreFacade=void 0;const t=Me;e.AsyncStoreFacade=t.default;const i=Ce;e.PersistentDataStoreWrapper=i.default;const r=ae;Object.defineProperty(e,"deserializePoll",{enumerable:!0,get:function(){return r.deserializePoll}})}(De),Object.defineProperty(xe,"__esModule",{value:!0});const Ye=o,Qe=De,Ze=oe;xe.default=class{constructor(e,t,i,r=()=>{},n){this._requestor=t,this._featureStore=i,this._initSuccessHandler=r,this._errorHandler=n,this._stopped=!1,this._logger=e.logger,this._pollInterval=e.pollInterval}_poll(){var e;if(this._stopped)return;const t=e=>{var t,i,r;null===(t=this._logger)||void 0===t||t.error("Polling received invalid data"),null===(i=this._logger)||void 0===i||i.debug(`Invalid JSON follows: ${e}`),null===(r=this._errorHandler)||void 0===r||r.call(this,new Ye.LDPollingError(Ye.DataSourceErrorKind.InvalidData,"Malformed JSON data in polling response"))},i=Date.now();null===(e=this._logger)||void 0===e||e.debug("Polling LaunchDarkly for feature flag updates"),this._requestor.requestAllData(((e,r)=>{var n,s,a,o;const l=Date.now()-i,u=Math.max(1e3*this._pollInterval-l,0);if(null===(n=this._logger)||void 0===n||n.debug("Elapsed: %d ms, sleeping for %d ms",l,u),e){const{status:t}=e;if(t&&!(0,Ye.isHttpRecoverable)(t)){const i=(0,Ye.httpErrorMessage)(e,"polling request");return null===(s=this._logger)||void 0===s||s.error(i),void(null===(a=this._errorHandler)||void 0===a||a.call(this,new Ye.LDPollingError(Ye.DataSourceErrorKind.ErrorResponse,i,t)))}null===(o=this._logger)||void 0===o||o.warn((0,Ye.httpErrorMessage)(e,"polling request","will retry"))}else if(r){const e=(0,Qe.deserializePoll)(r);if(e){const t={[Ze.default.Features.namespace]:e.flags,[Ze.default.Segments.namespace]:e.segments};return void this._featureStore.init(t,(()=>{this._initSuccessHandler(),this._timeoutHandle=setTimeout((()=>{this._poll()}),u)}))}t(r)}this._timeoutHandle=setTimeout((()=>{this._poll()}),u)}))}start(){this._poll()}stop(){this._timeoutHandle&&(clearTimeout(this._timeoutHandle),this._timeoutHandle=void 0),this._stopped=!0}close(){this.stop()}};var et={};Object.defineProperty(et,"__esModule",{value:!0});const tt=o;et.default=class{constructor(e,t,i){this._requests=t,this._eTagCache={},this._headers=Object.assign({},i),this._uri=(0,tt.getPollingUri)(e.serviceEndpoints,"/sdk/latest-all",[])}async _requestWithETagCache(e,t){const i=this._eTagCache[e],r=null==i?void 0:i.etag,n=r?Object.assign(Object.assign({},t),{headers:Object.assign(Object.assign({},t.headers),{"if-none-match":r})}):t,s=await this._requests.fetch(e,n);if(304===s.status&&i)return{res:s,body:i.body};const a=s.headers.get("etag"),o=await s.text();return a&&(this._eTagCache[e]={etag:a,body:o}),{res:s,body:o}}async requestAllData(e){const t={method:"GET",headers:this._headers};try{const{res:i,body:r}=await this._requestWithETagCache(this._uri,t);if(200!==i.status&&304!==i.status){return e(new tt.LDPollingError(tt.DataSourceErrorKind.ErrorResponse,`Unexpected status code: ${i.status}`,i.status),void 0)}return e(void 0,304===i.status?null:r)}catch(t){return e(t,void 0)}}};var it={},rt={},nt={};Object.defineProperty(nt,"__esModule",{value:!0});nt.default=class{constructor(){this._allData={},this._initCalled=!1}_addItem(e,t,i){let r=this._allData[e.namespace];if(r||(r={},this._allData[e.namespace]=r),Object.hasOwnProperty.call(r,t)){const e=r[t];(!e||e.version<i.version)&&(r[t]=i)}else r[t]=i}get(e,t,i){const r=this._allData[e.namespace];if(r&&Object.prototype.hasOwnProperty.call(r,t)){const e=r[t];if(e&&!e.deleted)return null==i?void 0:i(e)}return null==i?void 0:i(null)}all(e,t){var i;const r={},n=null!==(i=this._allData[e.namespace])&&void 0!==i?i:{};Object.entries(n).forEach((([e,t])=>{t&&!t.deleted&&(r[e]=t)})),null==t||t(r)}init(e,t){this._initCalled=!0,this._allData=e,null==t||t()}delete(e,t,i,r){const n={version:i,deleted:!0};this._addItem(e,t,n),null==r||r()}upsert(e,t,i){this._addItem(e,t.key,t),null==i||i()}initialized(e){return null==e?void 0:e(this._initCalled)}close(){}getDescription(){return"memory"}},function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.defaultValues=void 0;const t=o,i=nt,r={baseUri:t.TypeValidators.String,streamUri:t.TypeValidators.String,eventsUri:t.TypeValidators.String,timeout:t.TypeValidators.Number,capacity:t.TypeValidators.Number,logger:t.TypeValidators.Object,featureStore:t.TypeValidators.ObjectOrFactory,bigSegments:t.TypeValidators.Object,updateProcessor:t.TypeValidators.ObjectOrFactory,flushInterval:t.TypeValidators.Number,pollInterval:t.TypeValidators.numberWithMin(30),proxyOptions:t.TypeValidators.Object,offline:t.TypeValidators.Boolean,stream:t.TypeValidators.Boolean,streamInitialReconnectDelay:t.TypeValidators.Number,useLdd:t.TypeValidators.Boolean,sendEvents:t.TypeValidators.Boolean,allAttributesPrivate:t.TypeValidators.Boolean,privateAttributes:t.TypeValidators.StringArray,contextKeysCapacity:t.TypeValidators.Number,contextKeysFlushInterval:t.TypeValidators.Number,tlsParams:t.TypeValidators.Object,diagnosticOptOut:t.TypeValidators.Boolean,diagnosticRecordingInterval:t.TypeValidators.numberWithMin(60),wrapperName:t.TypeValidators.String,wrapperVersion:t.TypeValidators.String,application:t.TypeValidators.Object,payloadFilterKey:t.TypeValidators.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:t.TypeValidators.createTypeArray("Hook[]",{})};e.defaultValues={baseUri:"https://sdk.launchdarkly.com",streamUri:"https://stream.launchdarkly.com",eventsUri:t.ServiceEndpoints.DEFAULT_EVENTS,stream:!0,streamInitialReconnectDelay:1,sendEvents:!0,timeout:5,capacity:1e4,flushInterval:5,pollInterval:30,offline:!1,useLdd:!1,allAttributesPrivate:!1,privateAttributes:[],contextKeysCapacity:1e3,contextKeysFlushInterval:300,diagnosticOptOut:!1,diagnosticRecordingInterval:900,featureStore:()=>new i.default};e.default=class{constructor(i={},n={}){i=i||{},this.logger=i.logger;const{errors:s,validatedOptions:a}=function(i){const n=[],s=Object.assign({},e.defaultValues);return Object.keys(i).forEach((a=>{var o;const l=i[a],u=r[a];if(u)if(u.is(l))s[a]=l;else if("boolean"===u.getType())n.push(t.OptionMessages.wrongOptionTypeBoolean(a,typeof l)),s[a]=!!l;else if(u instanceof t.NumberWithMinimum&&t.TypeValidators.Number.is(l)){const{min:e}=u;n.push(t.OptionMessages.optionBelowMinimum(a,l,e)),s[a]=e}else n.push(t.OptionMessages.wrongOptionType(a,u.getType(),typeof l)),s[a]=e.defaultValues[a];else null===(o=i.logger)||void 0===o||o.warn(t.OptionMessages.unknownOption(a))})),{errors:n,validatedOptions:s}}(i);s.forEach((e=>{var t;null===(t=this.logger)||void 0===t||t.warn(e)})),function(e,i){var r,n,s;const{baseUri:a,streamUri:o,eventsUri:l}=e,u=null!=o,c=null!=a,d=null!=l;u===c&&u===d||(!u&&i.stream&&(null===(r=i.logger)||void 0===r||r.warn(t.OptionMessages.partialEndpoint("streamUri"))),c||null===(n=i.logger)||void 0===n||n.warn(t.OptionMessages.partialEndpoint("baseUri")),!d&&i.sendEvents&&(null===(s=i.logger)||void 0===s||s.warn(t.OptionMessages.partialEndpoint("eventsUri"))))}(i,a),this.serviceEndpoints=new t.ServiceEndpoints(a.streamUri,a.baseUri,a.eventsUri,n.analyticsEventPath,n.diagnosticEventPath,n.includeAuthorizationHeader,a.payloadFilterKey),this.eventsCapacity=a.capacity,this.timeout=a.timeout,this.bigSegments=a.bigSegments,this.flushInterval=a.flushInterval,this.pollInterval=a.pollInterval,this.proxyOptions=a.proxyOptions,this.offline=a.offline,this.stream=a.stream,this.streamInitialReconnectDelay=a.streamInitialReconnectDelay,this.useLdd=a.useLdd,this.sendEvents=a.sendEvents,this.allAttributesPrivate=a.allAttributesPrivate,this.privateAttributes=a.privateAttributes,this.contextKeysCapacity=a.contextKeysCapacity,this.contextKeysFlushInterval=a.contextKeysFlushInterval,this.tlsParams=a.tlsParams,this.diagnosticOptOut=a.diagnosticOptOut,this.wrapperName=a.wrapperName,this.payloadFilterKey=a.payloadFilterKey,this.wrapperVersion=a.wrapperVersion,this.tags=new t.ApplicationTags(a),this.diagnosticRecordingInterval=a.diagnosticRecordingInterval,t.TypeValidators.Function.is(a.updateProcessor)?this.updateProcessorFactory=a.updateProcessor:this.updateProcessorFactory=()=>a.updateProcessor,t.TypeValidators.Function.is(a.featureStore)?this.featureStoreFactory=a.featureStore:this.featureStoreFactory=()=>a.featureStore,this.hooks=a.hooks}}}(rt),Object.defineProperty(it,"__esModule",{value:!0});const st=o,at=rt;it.default=(e,t,i)=>{var r,n,s,a,o,l;return{customBaseURI:e.serviceEndpoints.polling!==at.defaultValues.baseUri,customStreamURI:e.serviceEndpoints.streaming!==at.defaultValues.streamUri,customEventsURI:e.serviceEndpoints.events!==at.defaultValues.eventsUri,eventsCapacity:e.eventsCapacity,connectTimeoutMillis:(0,st.secondsToMillis)(e.timeout),socketTimeoutMillis:(0,st.secondsToMillis)(e.timeout),eventsFlushIntervalMillis:(0,st.secondsToMillis)(e.flushInterval),pollingIntervalMillis:(0,st.secondsToMillis)(e.pollInterval),reconnectTimeMillis:(0,st.secondsToMillis)(e.streamInitialReconnectDelay),contextKeysFlushIntervalMillis:(0,st.secondsToMillis)(e.contextKeysFlushInterval),diagnosticRecordingIntervalMillis:(0,st.secondsToMillis)(e.diagnosticRecordingInterval),streamingDisabled:!e.stream,usingRelayDaemon:e.useLdd,offline:e.offline,allAttributesPrivate:e.allAttributesPrivate,contextKeysCapacity:e.contextKeysCapacity,usingProxy:!!(null===(n=(r=t.requests).usingProxy)||void 0===n?void 0:n.call(r)),usingProxyAuthenticator:!!(null===(a=(s=t.requests).usingProxyAuth)||void 0===a?void 0:a.call(s)),dataStoreType:null!==(l=null===(o=i.getDescription)||void 0===o?void 0:o.call(i))&&void 0!==l?l:"memory"}};var ot={};Object.defineProperty(ot,"__esModule",{value:!0}),ot.allAsync=ot.firstSeriesAsync=ot.allSeriesAsync=ot.firstResult=void 0,ot.firstResult=function(e,t){let i;return null==e||e.some(((e,r)=>(i=t(e,r),!!i))),i};function lt(e,t,i,r,n){e?r<(null==e?void 0:e.length)?t(e[r],r,(s=>{if(i){if(!s)return void n(!1)}else if(s)return void n(!0);e.length>50?Promise.resolve().then((()=>{lt(e,t,i,r+1,n)})):lt(e,t,i,r+1,n)})):n(i):n(!1)}ot.allSeriesAsync=function(e,t,i){lt(e,t,!0,0,i)},ot.firstSeriesAsync=function(e,t,i){lt(e,t,!1,0,i)},ot.allAsync=function(e,t,i){e?Promise.all(null==e?void 0:e.map((e=>new Promise((i=>{t(e,i)}))))).then((e=>{i(e.every((e=>e)))})):i(!1)};var ut={},ct={};Object.defineProperty(ct,"__esModule",{value:!0});class dt{static prerequisiteFailed(e){return{kind:"PREREQUISITE_FAILED",prerequisiteKey:e}}static ruleMatch(e,t){return{kind:"RULE_MATCH",ruleId:e,ruleIndex:t}}}dt.Fallthrough={kind:"FALLTHROUGH"},dt.Off={kind:"OFF"},dt.TargetMatch={kind:"TARGET_MATCH"},ct.default=dt,Object.defineProperty(ut,"__esModule",{value:!0});const ht=ct;class ft{constructor(e,t,i){this.isError=e,this.detail=t,this.message=i,this.isError=e,this.detail=t,this.message=i}get isOff(){return this.detail.reason.kind===ht.default.Off.kind}setDefault(e){this.detail.value=e}static forError(e,t,i){return new ft(!0,{value:null!=i?i:null,variationIndex:null,reason:{kind:"ERROR",errorKind:e}},t)}static forSuccess(e,t,i){return new ft(!1,{value:e,variationIndex:void 0===i?null:i,reason:t})}}ut.default=ft;var gt={},vt={};Object.defineProperty(vt,"__esModule",{value:!0});vt.default=class{constructor(e){this._crypto=e}_sha1Hex(e){const t=this._crypto.createHash("sha1");if(t.update(e),!t.digest)throw new Error("Platform must implement digest or asyncDigest");return t.digest("hex")}bucket(e,t,i,r,n="user",s){const a=function(e){return"string"==typeof e?e:Number.isInteger(e)?String(e):null}(e.valueForKind(i,n));if(null===a){return[0,e.kinds.indexOf(n)>=0]}const o=`${s?Number(s):`${t}.${r}`}.${a}`;return[parseInt(this._sha1Hex(o).substring(0,15),16)/0x1000000000000000,!0]}};var _t={},pt={};Object.defineProperty(pt,"__esModule",{value:!0}),pt.getBucketBy=pt.getOffVariation=pt.getVariation=void 0;const yt=o,mt=ut,{ErrorKinds:bt}=yt.internal,wt=new yt.AttributeReference("key");function St(e,t,i){return yt.TypeValidators.Number.is(t)&&t>=0&&t<e.variations.length?mt.default.forSuccess(e.variations[t],i,t):mt.default.forError(bt.MalformedFlag,"Invalid variation index in flag")}pt.getVariation=St,pt.getOffVariation=function(e,t){return yt.TypeValidators.Number.is(e.offVariation)?St(e,e.offVariation,t):mt.default.forSuccess(null,t)},pt.getBucketBy=function(e,t){var i;return null!==(i=e?void 0:t)&&void 0!==i?i:wt},Object.defineProperty(_t,"__esModule",{value:!0});const kt=o,Et=ot,Ot=ct,xt=pt;function Dt(e,t,i){const r=i.key(t.contextKind);if(void 0!==r){if(t.values.indexOf(r)>=0)return(0,xt.getVariation)(e,t.variation,Ot.default.TargetMatch)}}_t.default=function(e,t){var i;return(null===(i=e.contextTargets)||void 0===i?void 0:i.length)?(0,Et.firstResult)(e.contextTargets,(i=>{if(!i.contextKind||i.contextKind===kt.Context.UserKind){const r=(e.targets||[]).find((e=>e.variation===i.variation));return r?Dt(e,r,t):void 0}return Dt(e,i,t)})):(0,Et.firstResult)(e.targets,(i=>Dt(e,i,t)))};var Mt={};Object.defineProperty(Mt,"__esModule",{value:!0}),Mt.default=function(e){return`${e.key}.g${e.generation}`};var Pt={},Tt={};Object.defineProperty(Tt,"__esModule",{value:!0});const Ct=t,Ft=o,It=/^\d+(\.\d+)?(\.\d+)?/;function jt(e){if(Ft.TypeValidators.String.is(e)&&!e.startsWith("v")){const t=(0,Ct.parse)(e);if(t)return t;const i=It.exec(e);if(i){let t=i[0];for(let e=1;e<i.length;e+=1)void 0===i[e]&&(t+=".0");return t+=e.substring(i[0].length),(0,Ct.parse)(t)}}return null}function Rt(e){return(t,i)=>{const r=jt(t),n=jt(i);return!!(r&&n&&e(r,n))}}function At(e,t,i){return(r,n)=>!(!t.is(r)||!t.is(n))&&(i?e(i(r),i(n)):e(r,n))}function Vt(e){return"number"==typeof e?e:Date.parse(e)}const Nt={in:(e,t)=>e===t,endsWith:At(((e,t)=>e.endsWith(t)),Ft.TypeValidators.String),startsWith:At(((e,t)=>e.startsWith(t)),Ft.TypeValidators.String),matches:At(((e,t)=>function(e,t){try{return new RegExp(e).test(t)}catch(e){return!1}}(t,e)),Ft.TypeValidators.String),contains:At(((e,t)=>e.indexOf(t)>-1),Ft.TypeValidators.String),lessThan:At(((e,t)=>e<t),Ft.TypeValidators.Number),lessThanOrEqual:At(((e,t)=>e<=t),Ft.TypeValidators.Number),greaterThan:At(((e,t)=>e>t),Ft.TypeValidators.Number),greaterThanOrEqual:At(((e,t)=>e>=t),Ft.TypeValidators.Number),before:At(((e,t)=>e<t),Ft.TypeValidators.Date,Vt),after:At(((e,t)=>e>t),Ft.TypeValidators.Date,Vt),semVerEqual:Rt(((e,t)=>0===e.compare(t))),semVerLessThan:Rt(((e,t)=>e.compare(t)<0)),semVerGreaterThan:Rt(((e,t)=>e.compare(t)>0))};Tt.default=class{static is(e){return Object.prototype.hasOwnProperty.call(Nt,e)}static execute(e,t,i){var r,n;return null!==(n=null===(r=Nt[e])||void 0===r?void 0:r.call(Nt,t,i))&&void 0!==n&&n}},Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.maybeNegate=void 0;const Lt=Tt;function Kt(e,t){return e.negate?!t:t}function $t(e,t,i){return i.some((i=>Lt.default.execute(e,t,i)))}Pt.maybeNegate=Kt,Pt.default=function(e,t){const i=t.valueForKind(e.attributeReference,e.contextKind);return null!=i&&(Array.isArray(i)?Kt(e,i.some((t=>$t(e.op,t,e.values)))):Kt(e,$t(e.op,i,e.values)))};var Ut={};function zt(e,t,i,r){if(t)for(let i=0;i<t.length;i+=1){const r=t[i],n=e.key(r.contextKind);if(n)if(r.generated_valuesSet){if(r.generated_valuesSet.has(n))return!0}else if(r.values.includes(n))return!0}if(r){const t=e.key("user");if(t&&r.has(t))return!0}else if(i){const t=e.key("user");if(t&&i.includes(t))return!0}return!1}Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.default=function(e,t){if(zt(t,e.includedContexts,e.included,e.generated_includedSet))return!0;const i=zt(t,e.excludedContexts,e.excluded,e.generated_excludedSet);return i?!i:void 0},Object.defineProperty(gt,"__esModule",{value:!0});const Bt=o,qt=vt,Ht=ot,Wt=ut,Jt=_t,Gt=Mt,Xt=Pt,Yt=Ut,Qt=ct,Zt=pt,{ErrorKinds:ei}=Bt.internal,ti={HEALTHY:1,STALE:2,STORE_ERROR:3,NOT_CONFIGURED:4};function ii(e){return void 0!==e&&ti[e]||0}function ri(e,t){return void 0!==e&&ii(e)>ii(t)?e:t}function ni(e){return{error:!1,isMatch:e,result:void 0}}function si(e){return{error:!0,isMatch:!1,result:e}}gt.default=class{constructor(e,t){this._queries=t,this._bucketer=new qt.default(e.crypto)}async evaluate(e,t,i){return new Promise((r=>{this.evaluateCb(e,t,r,i)}))}evaluateCb(e,t,i,r){const n={};this._evaluateInternal(e,t,n,[],(e=>{n.bigSegmentsStatus&&(e.detail.reason=Object.assign(Object.assign({},e.detail.reason),{bigSegmentsStatus:n.bigSegmentsStatus})),n.prerequisites&&(e.prerequisites=n.prerequisites),e.events=n.events,i(e)}),!0,r)}_evaluateInternal(e,t,i,r,n,s,a){e.on?this._checkPrerequisites(e,t,i,r,(r=>{if(r)return void n(r);const s=(0,Jt.default)(e,t);s?n(s):this._evaluateRules(e,t,i,(i=>{n(i||this._variationForContext(e.fallthrough,t,e,Qt.default.Fallthrough))}))}),s,a):n((0,Zt.getOffVariation)(e,Qt.default.Off))}_checkPrerequisites(e,t,i,r,n,s,a){let o;e.prerequisites&&e.prerequisites.length?(0,Ht.allSeriesAsync)(e.prerequisites,((n,l,u)=>{if(-1!==r.indexOf(n.key))return o=Wt.default.forError(ei.MalformedFlag,`Prerequisite of ${e.key} causing a circular reference. This is probably a temporary condition due to an incomplete update.`),void u(!0);const c=[...r,n.key];this._queries.getFlag(n.key,(r=>{if(!r)return o=(0,Zt.getOffVariation)(e,Qt.default.prerequisiteFailed(n.key)),void u(!1);this._evaluateInternal(r,t,i,c,(l=>{var c,d;return null!==(c=i.events)&&void 0!==c||(i.events=[]),s&&(null!==(d=i.prerequisites)&&void 0!==d||(i.prerequisites=[]),i.prerequisites.push(r.key)),a&&i.events.push(a.evalEventServer(r,t,l.detail,null,e)),l.isError?(o=l,u(!1)):l.isOff||l.detail.variationIndex!==n.variation?(o=(0,Zt.getOffVariation)(e,Qt.default.prerequisiteFailed(n.key)),u(!1)):u(!0)}),!1,a)}))}),(()=>{n(o)})):n(void 0)}_evaluateRules(e,t,i,r){let n;(0,Ht.firstSeriesAsync)(e.rules,((r,s,a)=>{this._ruleMatchContext(e,r,s,t,i,[],(e=>{n=e,a(!!e)}))}),(()=>r(n)))}_clauseMatchContext(e,t,i,r,n){let s;"segmentMatch"!==e.op?e.attributeReference.isValid?n(ni((0,Xt.default)(e,t))):n(si(Wt.default.forError(ei.MalformedFlag,"Invalid attribute reference in clause"))):(0,Ht.firstSeriesAsync)(e.values,((e,n,a)=>{this._queries.getSegment(e,(e=>{if(e){if(i.includes(e.key))return s=Wt.default.forError(ei.MalformedFlag,`Segment rule referencing segment ${e.key} caused a circular reference. This is probably a temporary condition due to an incomplete update`),void a(!0);const n=[...i,null==e?void 0:e.key];this.segmentMatchContext(e,t,r,n,(e=>{e.error&&(s=e.result),a(e.error||e.isMatch)}))}else a(!1)}))}),(t=>n(s?si(s):ni((0,Xt.maybeNegate)(e,t)))))}_ruleMatchContext(e,t,i,r,n,s,a){if(!t.clauses)return void a(void 0);let o;(0,Ht.allSeriesAsync)(t.clauses,((e,t,i)=>{this._clauseMatchContext(e,r,s,n,(e=>(o=e.result,i(e.error||e.isMatch))))}),(n=>a(o||(n?this._variationForContext(t,r,e,Qt.default.ruleMatch(t.id,i)):void 0))))}_variationForContext(e,t,i,r){if(void 0===e)return Wt.default.forError(ei.MalformedFlag,"Fallthrough variation undefined");if(void 0!==e.variation)return(0,Zt.getVariation)(i,e.variation,r);if(e.rollout){const{rollout:n}=e,{variations:s}=n,a="experiment"===n.kind;if(s&&s.length){const e=(0,Zt.getBucketBy)(a,n.bucketByAttributeReference);if(!e.isValid)return Wt.default.forError(ei.MalformedFlag,"Invalid attribute reference for bucketBy in rollout");const[o,l]=this._bucketer.bucket(t,i.key,e,i.salt||"",n.contextKind,n.seed),u=Object.assign({},r);let c=0;for(let e=0;e<s.length;e+=1){const t=s[e];if(c+=t.weight/1e5,o<c)return a&&l&&!t.untracked&&(u.inExperiment=!0),(0,Zt.getVariation)(i,t.variation,u)}const d=s[s.length-1];return a&&!d.untracked&&(u.inExperiment=!0),(0,Zt.getVariation)(i,d.variation,u)}}return Wt.default.forError(ei.MalformedFlag,"Variation/rollout object with no variation or rollout")}segmentRuleMatchContext(e,t,i,r,n,s){let a;(0,Ht.allSeriesAsync)(t.clauses,((e,t,s)=>{this._clauseMatchContext(e,i,n,r,(e=>{a=e.result,s(e.error||e.isMatch)}))}),(r=>{if(a)return s(si(a));if(r){if(void 0===t.weight)return s(ni(r));const n=(0,Zt.getBucketBy)(!1,t.bucketByAttributeReference);if(!n.isValid)return s(si(Wt.default.forError(ei.MalformedFlag,"Invalid attribute reference in clause")));const[a]=this._bucketer.bucket(i,e.key,n,e.salt||"",t.rolloutContextKind);return s(ni(a<t.weight/1e5))}return s(ni(!1))}))}simpleSegmentMatchContext(e,t,i,r,n){if(!e.unbounded){const i=(0,Yt.default)(e,t);if(void 0!==i)return void n(ni(i))}let s;(0,Ht.firstSeriesAsync)(e.rules,((n,a,o)=>{this.segmentRuleMatchContext(e,n,t,i,r,(e=>(s=e.result,o(e.error||e.isMatch))))}),(e=>n(s?si(s):ni(e))))}segmentMatchContext(e,t,i,r,n){if(!e.unbounded)return void this.simpleSegmentMatchContext(e,t,i,r,n);const s=e.unboundedContextKind||"user",a=t.key(s);if(a)return e.generation?void(i.bigSegmentsMembership&&i.bigSegmentsMembership[a]?this.bigSegmentMatchContext(i.bigSegmentsMembership[a],e,t,i).then(n):this._queries.getBigSegmentsMembership(a).then((r=>{if(i.bigSegmentsMembership=i.bigSegmentsMembership||{},r){const[e,t]=r;i.bigSegmentsMembership[a]=e,i.bigSegmentsStatus=ri(i.bigSegmentsStatus,t)}else i.bigSegmentsStatus=ri(i.bigSegmentsStatus,"NOT_CONFIGURED");this.bigSegmentMatchContext(i.bigSegmentsMembership[a],e,t,i).then(n)}))):(i.bigSegmentsStatus=ri(i.bigSegmentsStatus,"NOT_CONFIGURED"),void n(ni(!1)));n(ni(!1))}bigSegmentMatchContext(e,t,i,r){const n=(0,Gt.default)(t),s=null==e?void 0:e[n];return new Promise((e=>{null==s?this.simpleSegmentMatchContext(t,i,r,[],e):e(ni(s))}))}};var ai={};Object.defineProperty(ai,"__esModule",{value:!0});const oi=te;ai.default=class{constructor(e){this._contextKeysCache=new oi.default({max:e.contextKeysCapacity}),this.flushInterval=e.contextKeysFlushInterval}processContext(e){const{canonicalKey:t}=e,i=this._contextKeysCache.get(t);return this._contextKeysCache.set(t,!0),!i}flush(){this._contextKeysCache.clear()}};var li={},ui={};Object.defineProperty(ui,"__esModule",{value:!0}),ui.default=function(e,t){if(t){if(t.inExperiment)return!0;switch(t.kind){case"RULE_MATCH":{const i=t.ruleIndex;if(void 0!==i){const t=e.rules||[];return i>=0&&i<t.length&&!!t[i].trackEvents}break}case"FALLTHROUGH":return!!e.trackEventsFallthrough}}return!1},Object.defineProperty(li,"__esModule",{value:!0});const ci=o,di=ui;class hi extends ci.internal.EventFactoryBase{evalEventServer(e,t,i,r,n){var s;const a=(0,di.default)(e,i.reason);return super.evalEvent({addExperimentData:a,context:t,debugEventsUntilDate:e.debugEventsUntilDate,defaultVal:r,excludeFromSummaries:e.excludeFromSummaries,flagKey:e.key,prereqOfFlagKey:null==n?void 0:n.key,reason:i.reason,samplingRatio:e.samplingRatio,trackEvents:e.trackEvents||a,value:i.value,variation:null!==(s=i.variationIndex)&&void 0!==s?s:void 0,version:e.version})}}li.default=hi;var fi={};Object.defineProperty(fi,"__esModule",{value:!0});fi.default=class{constructor(e,t){this._valid=e,this._withReasons=t,this._flagValues={},this._flagMetadata={}}addFlag(e,t,i,r,n,s,a,o){this._flagValues[e.key]=t;const l={};void 0!==i&&(l.variation=i);const u=a&&!n&&!s&&void 0===e.debugEventsUntilDate;u||(l.version=e.version),r&&(s||this._withReasons&&!u)&&(l.reason=r),n&&(l.trackEvents=!0),s&&(l.trackReason=!0),void 0!==e.debugEventsUntilDate&&(l.debugEventsUntilDate=e.debugEventsUntilDate),o&&o.length&&(l.prerequisites=o),this._flagMetadata[e.key]=l}build(){return{valid:this._valid,allValues:()=>this._flagValues,getFlagValue:e=>this._flagValues[e],getFlagReason:e=>{var t;return null!==(t=this._flagMetadata[e]?this._flagMetadata[e].reason:null)&&void 0!==t?t:null},toJSON:()=>Object.assign(Object.assign({},this._flagValues),{$flagsState:this._flagMetadata,$valid:this._valid})}}};var gi={};Object.defineProperty(gi,"__esModule",{value:!0});const vi="unknown hook";gi.default=class{constructor(e,t){this._logger=e,this._hooks=[],this._hooks.push(...t)}async withEvaluationSeries(e,t,i,r,n){return 0===this._hooks.length?n():this.withEvaluationSeriesExtraDetail(e,t,i,r,(async()=>({detail:await n()}))).then((({detail:e})=>e))}async withEvaluationSeriesExtraDetail(e,t,i,r,n){if(0===this._hooks.length)return n();const{hooks:s,hookContext:a}=this._prepareHooks(e,t,i,r),o=this._executeBeforeEvaluation(s,a),l=await n();return this._executeAfterEvaluation(s,a,o,l.detail),l}_tryExecuteStage(e,t,i){var r;try{return i()}catch(i){return null===(r=this._logger)||void 0===r||r.error(`An error was encountered in "${e}" of the "${t}" hook: ${i}`),{}}}_hookName(e){var t,i;try{return null!==(t=null==e?void 0:e.getMetadata().name)&&void 0!==t?t:vi}catch(e){return null===(i=this._logger)||void 0===i||i.error("Exception thrown getting metadata for hook. Unable to get hook name."),vi}}_executeAfterEvaluation(e,t,i,r){var n;for(let s=e.length-1;s>=0;s-=1){const a=e[s],o=null!==(n=i[s])&&void 0!==n?n:{};this._tryExecuteStage("afterEvaluation",this._hookName(a),(()=>{var e,i;return null!==(i=null===(e=null==a?void 0:a.afterEvaluation)||void 0===e?void 0:e.call(a,t,o,r))&&void 0!==i?i:{}}))}}_executeBeforeEvaluation(e,t){return e.map((e=>this._tryExecuteStage("beforeEvaluation",this._hookName(e),(()=>{var i,r;return null!==(r=null===(i=null==e?void 0:e.beforeEvaluation)||void 0===i?void 0:i.call(e,t,{}))&&void 0!==r?r:{}}))))}_prepareHooks(e,t,i,r){return{hooks:[...this._hooks],hookContext:{flagKey:e,context:t,defaultValue:i,method:r}}}addHook(e){this._hooks.push(e)}};var _i={};Object.defineProperty(_i,"__esModule",{value:!0});const pi=o;function yi(e){const t=e.old,i=e.new;return!(void 0!==t&&!pi.TypeValidators.Boolean.is(t))&&!(void 0!==i&&!pi.TypeValidators.Boolean.is(i))}function mi(e){if(pi.TypeValidators.String.is(e.key)&&""!==e.key){if("latency_ms"===e.key){if(!pi.TypeValidators.Object.is(e.values))return;if(!function(e){const t=e.old,i=e.new;return!(void 0!==t&&!pi.TypeValidators.Number.is(t)||void 0!==i&&!pi.TypeValidators.Number.is(i))}(e.values))return;return{key:e.key,values:{old:e.values.old,new:e.values.new}}}if(function(e){return"error"===e.key}(e)){if(!pi.TypeValidators.Object.is(e.values))return;if(!yi(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(!pi.TypeValidators.Boolean.is(e.value)||!pi.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(!pi.TypeValidators.Object.is(e.values))return;if(!yi(e.values))return;return{key:e.key,values:{old:e.values.old,new:e.values.new}}}}}_i.default=function(e){var t,i;if("migration_op"!==e.kind)return;if(i=e.operation,!pi.TypeValidators.String.is(i)||"read"!==i&&"write"!==i)return;if(!pi.TypeValidators.Object.is(e.contextKeys))return;if(!pi.TypeValidators.Number.is(e.creationDate))return;if(!Object.keys(e.contextKeys).every((e=>pi.TypeValidators.Kind.is(e))))return;const r=null!==(t=e.samplingRatio)&&void 0!==t?t:1;if(!pi.TypeValidators.Number.is(r))return;if(!Object.values(e.contextKeys).every((e=>pi.TypeValidators.String.is(e)&&""!==e)))return;const n=function(e){if(!pi.TypeValidators.String.is(e.key)||""===e.key)return;if(!pi.TypeValidators.Object.is(e.reason))return;if(!pi.TypeValidators.String.is(e.reason.kind)||""===e.reason.kind)return;const t={key:e.key,value:e.value,default:e.default,reason:{kind:e.reason.kind}},i=e.reason,r=t.reason;return pi.TypeValidators.String.is(i.errorKind)&&(r.errorKind=i.errorKind),pi.TypeValidators.String.is(i.ruleId)&&(r.ruleId=i.ruleId),pi.TypeValidators.String.is(i.prerequisiteKey)&&(r.prerequisiteKey=i.prerequisiteKey),pi.TypeValidators.Boolean.is(i.inExperiment)&&(r.inExperiment=i.inExperiment),pi.TypeValidators.Number.is(i.ruleIndex)&&(r.ruleIndex=i.ruleIndex),pi.TypeValidators.String.is(i.bigSegmentsStatus)&&(r.bigSegmentsStatus=i.bigSegmentsStatus),void 0!==e.variation&&pi.TypeValidators.Number.is(e.variation)&&(t.variation=e.variation),void 0!==e.version&&pi.TypeValidators.Number.is(e.version)&&(t.version=e.version),t}(e.evaluation);var s;return n?{kind:e.kind,operation:e.operation,creationDate:e.creationDate,contextKeys:Object.assign({},e.contextKeys),measurements:(s=e.measurements,s.map(mi).filter((e=>void 0!==e))),evaluation:n,samplingRatio:r}:void 0};var bi={};Object.defineProperty(bi,"__esModule",{value:!0});const wi=o,Si=u;function ki(e){return!Number.isNaN(e)}bi.default=class{constructor(e,t,i,r,n,s,a,o,l,u){this._flagKey=e,this._contextKeys=t,this._defaultStage=i,this._stage=r,this._reason=n,this._checkRatio=s,this._variation=a,this._version=o,this._samplingRatio=l,this._logger=u,this._errors={old:!1,new:!1},this._wasInvoked={old:!1,new:!1},this._consistencyCheck=Si.LDConsistencyCheck.NotChecked,this._latencyMeasurement={old:NaN,new:NaN}}op(e){this._operation=e}error(e){this._errors[e]=!0}consistency(e){var t,i;if(wi.internal.shouldSample(null!==(t=this._checkRatio)&&void 0!==t?t:1))try{const t=e();this._consistencyCheck=t?Si.LDConsistencyCheck.Consistent:Si.LDConsistencyCheck.Inconsistent}catch(e){null===(i=this._logger)||void 0===i||i.error(`Exception when executing consistency check function for migration '${this._flagKey}' the consistency check will not be included in the generated migration op event. Exception: ${e}`)}}latency(e,t){this._latencyMeasurement[e]=t}invoked(e){this._wasInvoked[e]=!0}createEvent(){var e,t,i,r,n;if(!wi.TypeValidators.String.is(this._flagKey)||""===this._flagKey)return void(null===(e=this._logger)||void 0===e||e.error("The flag key for a migration operation must be a non-empty string."));if(!this._operation)return void(null===(t=this._logger)||void 0===t||t.error('The operation must be set using "op" before an event can be created.'));if(0===Object.keys(this._contextKeys).length)return void(null===(i=this._logger)||void 0===i||i.error("The migration was not done against a valid context and cannot generate an event."));if(!this._wasInvoked.old&&!this._wasInvoked.new)return void(null===(r=this._logger)||void 0===r||r.error('The migration invoked neither the "old" or "new" implementation andan event cannot be generated'));if(!this._measurementConsistencyCheck())return;const s=[];return this._populateInvoked(s),this._populateConsistency(s),this._populateLatency(s),this._populateErrors(s),{kind:"migration_op",operation:this._operation,creationDate:Date.now(),contextKeys:this._contextKeys,evaluation:{key:this._flagKey,value:this._stage,default:this._defaultStage,reason:this._reason,variation:this._variation,version:this._version},measurements:s,samplingRatio:null!==(n=this._samplingRatio)&&void 0!==n?n:1}}_logTag(){return`For migration ${this._operation}-${this._flagKey}:`}_latencyConsistencyMessage(e){return`Latency measurement for "${e}", but "${e}" was not invoked.`}_errorConsistencyMessage(e){return`Error occurred for "${e}", but "${e}" was not invoked.`}_consistencyCheckConsistencyMessage(e){return`Consistency check was done, but "${e}" was not invoked.Both "old" and "new" must be invoked to do a consistency check.`}_checkOriginEventConsistency(e){var t,i,r;return!!this._wasInvoked[e]||(Number.isNaN(this._latencyMeasurement[e])?this._errors[e]?(null===(i=this._logger)||void 0===i||i.error(`${this._logTag()} ${this._errorConsistencyMessage(e)}`),!1):this._consistencyCheck===Si.LDConsistencyCheck.NotChecked||(null===(r=this._logger)||void 0===r||r.error(`${this._logTag()} ${this._consistencyCheckConsistencyMessage(e)}`),!1):(null===(t=this._logger)||void 0===t||t.error(`${this._logTag()} ${this._latencyConsistencyMessage(e)}`),!1))}_measurementConsistencyCheck(){return this._checkOriginEventConsistency("old")&&this._checkOriginEventConsistency("new")}_populateInvoked(e){var t;const i={key:"invoked",values:{}};this._wasInvoked.old||this._wasInvoked.new||null===(t=this._logger)||void 0===t||t.error("Migration op completed without executing any origins (old/new)."),this._wasInvoked.old&&(i.values.old=!0),this._wasInvoked.new&&(i.values.new=!0),e.push(i)}_populateConsistency(e){var t;void 0!==this._consistencyCheck&&this._consistencyCheck!==Si.LDConsistencyCheck.NotChecked&&e.push({key:"consistent",value:this._consistencyCheck===Si.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=ki(this._latencyMeasurement.new),i=ki(this._latencyMeasurement.old);if(t||i){const r={};t&&(r.new=this._latencyMeasurement.new),i&&(r.old=this._latencyMeasurement.old),e.push({key:"latency_ms",values:r})}}},Object.defineProperty(a,"__esModule",{value:!0});const Ei=o,Oi=l,xi=ee,Di=se,Mi=ye,Pi=xe,Ti=et,Ci=it,Fi=ot,Ii=ut,ji=gt,Ri=ai,Ai=li,Vi=ui,Ni=fi,Li=gi,Ki=_i,$i=bi,Ui=rt,zi=oe,{ClientMessages:Bi,ErrorKinds:qi,NullEventProcessor:Hi}=Ei.internal;var Wi,Ji;(Ji=Wi||(Wi={}))[Ji.Initializing=0]="Initializing",Ji[Ji.Initialized=1]="Initialized",Ji[Ji.Failed=2]="Failed";a.default=class{get logger(){return this._logger}constructor(e,t,i,r,n){var s,a,o,l,u;this._sdkKey=e,this._platform=t,this._initState=Wi.Initializing,this._eventFactoryDefault=new Ai.default(!1),this._eventFactoryWithReasons=new Ai.default(!0),this._onError=r.onError,this._onFailed=r.onFailed,this._onReady=r.onReady;const{onUpdate:c,hasEventListeners:d}=r,h=new Ui.default(i,n);if(this._hookRunner=new Li.default(h.logger,h.hooks||[]),!e&&!h.offline)throw new Error("You must configure the client with an SDK key");this._config=h,this._logger=h.logger;const f=(0,Ei.defaultHeaders)(e,t.info,h.tags),g=new Ei.ClientContext(e,h,t),v=h.featureStoreFactory(g),_=new Mi.default(v,d,c);!h.sendEvents||h.offline||h.diagnosticOptOut||(this._diagnosticsManager=new Ei.internal.DiagnosticsManager(e,t,(0,Ci.default)(h,t,v))),!h.sendEvents||h.offline?this._eventProcessor=new Hi:this._eventProcessor=new Ei.internal.EventProcessor(h,g,f,new Ri.default(h),this._diagnosticsManager),this._featureStore=v;const p=new xi.default(null===(a=null===(s=h.bigSegments)||void 0===s?void 0:s.store)||void 0===a?void 0:a.call(s,g),null!==(o=h.bigSegments)&&void 0!==o?o:{},h.logger,this._platform.crypto);this._bigSegmentsManager=p,this.bigSegmentStatusProviderInternal=p.statusProvider;const y={getFlag(e,t){v.get(zi.default.Features,e,(e=>t(e)))},getSegment(e,t){v.get(zi.default.Segments,e,(e=>t(e)))},getBigSegmentsMembership:e=>p.getUserMembership(e)};this._evaluator=new ji.default(this._platform,y);const m=(0,Di.createStreamListeners)(_,this._logger,{put:()=>this._initSuccess()}),b=()=>h.stream?new Ei.internal.StreamingProcessor(g,"/all",[],m,f,this._diagnosticsManager,(e=>this._dataSourceErrorHandler(e)),this._config.streamInitialReconnectDelay):new Pi.default(h,new Ti.default(h,this._platform.requests,f),_,(()=>this._initSuccess()),(e=>this._dataSourceErrorHandler(e)));h.offline||h.useLdd||(this._updateProcessor=null!==(u=null===(l=h.updateProcessorFactory)||void 0===l?void 0:l.call(h,g,_,(()=>this._initSuccess()),(e=>this._dataSourceErrorHandler(e))))&&void 0!==u?u:b()),this._updateProcessor?this._updateProcessor.start():setTimeout((()=>this._initSuccess()),0)}initialized(){return this._initState===Wi.Initialized}waitForInitialization(e){var t,i;return void 0===(null==e?void 0:e.timeout)&&void 0!==this._updateProcessor&&(null===(t=this._logger)||void 0===t||t.warn("The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied.")),void 0!==(null==e?void 0:e.timeout)&&(null==e?void 0:e.timeout)>60&&void 0!==this._updateProcessor&&(null===(i=this._logger)||void 0===i||i.warn("The waitForInitialization function was called with a timeout greater than 60 seconds. We recommend a timeout of less than 60 seconds.")),this._initializedPromise?this._clientWithTimeout(this._initializedPromise,null==e?void 0:e.timeout,this._logger):this._initState===Wi.Initialized?(this._initializedPromise=Promise.resolve(this),this._initializedPromise):this._initState===Wi.Failed?(this._initializedPromise=Promise.reject(this._rejectionReason),this._initializedPromise):(this._initializedPromise||(this._initializedPromise=new Promise(((e,t)=>{this._initResolve=e,this._initReject=t}))),this._clientWithTimeout(this._initializedPromise,null==e?void 0:e.timeout,this._logger))}variation(e,t,i,r){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.variation",(()=>new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryDefault,(e=>{r(e.detail)}))})))).then((e=>(null==r||r(null,e.value),e.value)))}variationDetail(e,t,i,r){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.variationDetail",(()=>new Promise((n=>{this._evaluateIfPossible(e,t,i,this._eventFactoryWithReasons,(e=>{n(e.detail),null==r||r(null,e.detail)}))}))))}_typedEval(e,t,i,r,n,s){return this._hookRunner.withEvaluationSeries(e,t,i,n,(()=>new Promise((n=>{this._evaluateIfPossible(e,t,i,r,(e=>{const t={value:e.detail.value,reason:e.detail.reason,variationIndex:e.detail.variationIndex};n(t)}),s)}))))}async boolVariation(e,t,i){return(await this._typedEval(e,t,i,this._eventFactoryDefault,"LDClient.boolVariation",(e=>[Ei.TypeValidators.Boolean.is(e),Ei.TypeValidators.Boolean.getType()]))).value}async numberVariation(e,t,i){return(await this._typedEval(e,t,i,this._eventFactoryDefault,"LDClient.numberVariation",(e=>[Ei.TypeValidators.Number.is(e),Ei.TypeValidators.Number.getType()]))).value}async stringVariation(e,t,i){return(await this._typedEval(e,t,i,this._eventFactoryDefault,"LDClient.stringVariation",(e=>[Ei.TypeValidators.String.is(e),Ei.TypeValidators.String.getType()]))).value}jsonVariation(e,t,i){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.jsonVariation",(()=>new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryDefault,(e=>{r(e.detail)}))})))).then((e=>e.value))}boolVariationDetail(e,t,i){return this._typedEval(e,t,i,this._eventFactoryWithReasons,"LDClient.boolVariationDetail",(e=>[Ei.TypeValidators.Boolean.is(e),Ei.TypeValidators.Boolean.getType()]))}numberVariationDetail(e,t,i){return this._typedEval(e,t,i,this._eventFactoryWithReasons,"LDClient.numberVariationDetail",(e=>[Ei.TypeValidators.Number.is(e),Ei.TypeValidators.Number.getType()]))}stringVariationDetail(e,t,i){return this._typedEval(e,t,i,this._eventFactoryWithReasons,"LDClient.stringVariationDetail",(e=>[Ei.TypeValidators.String.is(e),Ei.TypeValidators.String.getType()]))}jsonVariationDetail(e,t,i){return this._hookRunner.withEvaluationSeries(e,t,i,"LDClient.jsonVariationDetail",(()=>new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryWithReasons,(e=>{r(e.detail)}))}))))}async _migrationVariationInternal(e,t,i){var r;const n=Ei.Context.fromLDContext(t),s=await new Promise((r=>{this._evaluateIfPossible(e,t,i,this._eventFactoryWithReasons,(({detail:t},n)=>{if((0,Oi.IsMigrationStage)(t.value))r({detail:t,flag:n});else{const t=new Error(`Unrecognized MigrationState for "${e}"; returning default value.`);this._onError(t);const s={kind:"ERROR",errorKind:qi.WrongType};r({detail:{value:i,reason:s},flag:n})}}))})),{detail:a,flag:o}=s,l=n.valid?n.kindsAndKeys:{},u=null===(r=null==o?void 0:o.migration)||void 0===r?void 0:r.checkRatio,c=null==o?void 0:o.samplingRatio;return{detail:a,migration:{value:a.value,tracker:new $i.default(e,l,i,a.value,a.reason,u,null===a.variationIndex?void 0:a.variationIndex,null==o?void 0:o.version,c,this._logger)}}}async migrationVariation(e,t,i){return(await this._hookRunner.withEvaluationSeriesExtraDetail(e,t,i,"LDClient.migrationVariation",(()=>this._migrationVariationInternal(e,t,i)))).migration}allFlagsState(e,t,i){var r,n,s;if(this._config.offline){null===(r=this._logger)||void 0===r||r.info("allFlagsState() called in offline mode. Returning empty state.");const e=new Ni.default(!1,!1).build();return null==i||i(null,e),Promise.resolve(e)}const a=Ei.Context.fromLDContext(e);return a.valid?new Promise((e=>{const r=r=>this._featureStore.all(zi.default.Features,(n=>{const s=new Ni.default(r,!!(null==t?void 0:t.withReasons)),o=!!(null==t?void 0:t.clientSideOnly),l=!!(null==t?void 0:t.detailsOnlyForTrackedFlags);(0,Fi.allAsync)(Object.values(n),((e,t)=>{var i;const r=e;!o||(null===(i=r.clientSideAvailability)||void 0===i?void 0:i.usingEnvironmentId)?this._evaluator.evaluateCb(r,a,(e=>{var i;e.isError&&this._onError(new Error(`Error for feature flag "${r.key}" while evaluating all flags: ${e.message}`));const n=(0,Vi.default)(r,e.detail.reason);s.addFlag(r,e.detail.value,null!==(i=e.detail.variationIndex)&&void 0!==i?i:void 0,e.detail.reason,r.trackEvents||n,n,l,e.prerequisites),t(!0)})):t(!0)}),(()=>{const t=s.build();null==i||i(null,t),e(t)}))}));this.initialized()?r(!0):this._featureStore.initialized((e=>{var t,i;let n=!0;e?null===(t=this._logger)||void 0===t||t.warn("Called allFlagsState before client initialization; using last known values from data store"):(null===(i=this._logger)||void 0===i||i.warn("Called allFlagsState before client initialization. Data store not available; returning empty state"),n=!1),r(n)}))})):(null===(n=this._logger)||void 0===n||n.info(`${null!==(s=a.message)&&void 0!==s?s:"Invalid context."}. Returning empty state.`),Promise.resolve(new Ni.default(!1,!1).build()))}secureModeHash(e){const t=Ei.Context.fromLDContext(e),i=t.valid?t.canonicalKey:void 0;if(!this._platform.crypto.createHmac)throw new Error("Platform must implement createHmac");const r=this._platform.crypto.createHmac("sha256",this._sdkKey);if(void 0===i)throw new Ei.LDClientError("Could not generate secure mode hash for invalid context");return r.update(i),r.digest("hex")}close(){var e;this._eventProcessor.close(),null===(e=this._updateProcessor)||void 0===e||e.close(),this._featureStore.close(),this._bigSegmentsManager.close()}isOffline(){return this._config.offline}track(e,t,i,r){var n,s;const a=Ei.Context.fromLDContext(t);a.valid?(void 0===r||Ei.TypeValidators.Number.is(r)||null===(s=this._logger)||void 0===s||s.warn(Bi.invalidMetricValue(typeof r)),this._eventProcessor.sendEvent(this._eventFactoryDefault.customEvent(e,a,i,r))):null===(n=this._logger)||void 0===n||n.warn(Bi.MissingContextKeyNoEvent)}trackMigration(e){const t=(0,Ki.default)(e);t&&this._eventProcessor.sendEvent(t)}identify(e){var t;const i=Ei.Context.fromLDContext(e);i.valid?this._eventProcessor.sendEvent(this._eventFactoryDefault.identifyEvent(i)):null===(t=this._logger)||void 0===t||t.warn(Bi.MissingContextKeyNoEvent)}async flush(e){try{await this._eventProcessor.flush()}catch(t){null==e||e(t,!1)}null==e||e(null,!0)}addHook(e){this._hookRunner.addHook(e)}_variationInternal(e,t,i,r,n,s){var a,o;if(this._config.offline)return null===(a=this._logger)||void 0===a||a.info("Variation called in offline mode. Returning default value."),void n(Ii.default.forError(qi.ClientNotReady,void 0,i));const l=Ei.Context.fromLDContext(t);if(!l.valid)return this._onError(new Ei.LDClientError(`${null!==(o=l.message)&&void 0!==o?o:"Context not valid;"} returning default value.`)),void n(Ii.default.forError(qi.UserNotSpecified,void 0,i));this._featureStore.get(zi.default.Features,e,(t=>{const a=t;if(!a){const t=new Ei.LDClientError(`Unknown feature flag "${e}"; returning default value`);this._onError(t);const r=Ii.default.forError(qi.FlagNotFound,void 0,i);return this._eventProcessor.sendEvent(this._eventFactoryDefault.unknownFlagEvent(e,i,l)),void n(r)}this._evaluator.evaluateCb(a,l,(t=>{var o;if(void 0!==t.detail.variationIndex&&null!==t.detail.variationIndex||(null===(o=this._logger)||void 0===o||o.debug("Result value is null in variation"),t.setDefault(i)),s){const[o,u]=s(t.detail.value);if(!o){const t=Ii.default.forError(qi.WrongType,`Did not receive expected type (${u}) evaluating feature flag "${e}"`,i);return this._sendEvalEvent(t,r,a,l,i),void n(t,a)}}this._sendEvalEvent(t,r,a,l,i),n(t,a)}),r)}))}_sendEvalEvent(e,t,i,r,n){var s;null===(s=e.events)||void 0===s||s.forEach((e=>{this._eventProcessor.sendEvent(Object.assign({},e))})),this._eventProcessor.sendEvent(t.evalEventServer(i,r,e.detail,n,void 0))}_evaluateIfPossible(e,t,i,r,n,s){this.initialized()?this._variationInternal(e,t,i,r,n,s):this._featureStore.initialized((a=>{var o,l;if(a)return null===(o=this._logger)||void 0===o||o.warn("Variation called before LaunchDarkly client initialization completed (did you wait for the 'ready' event?) - using last known values from feature store"),void this._variationInternal(e,t,i,r,n,s);null===(l=this._logger)||void 0===l||l.warn("Variation called before LaunchDarkly client initialization completed (did you wait for the'ready' event?) - using default value"),n(Ii.default.forError(qi.ClientNotReady,void 0,i))}))}_dataSourceErrorHandler(e){var t;const i=401===e.code?new Error("Authentication failed. Double check your SDK key."):e;this._onError(i),this._onFailed(i),this.initialized()||(this._initState=Wi.Failed,this._rejectionReason=i,null===(t=this._initReject)||void 0===t||t.call(this,i))}_initSuccess(){var e;this.initialized()||(this._initState=Wi.Initialized,null===(e=this._initResolve)||void 0===e||e.call(this,this),this._onReady())}_clientWithTimeout(e,t,i){if(t){const r=(0,Ei.cancelableTimedPromise)(t,"waitForInitialization");return Promise.race([e.then((()=>r.cancel())).then((()=>this)),r.promise.then((()=>this))]).catch((e=>{throw e instanceof Ei.LDTimeoutError&&(null==i||i.error(e.message)),e}))}return e}};var Gi={};Object.defineProperty(Gi,"__esModule",{value:!0}),Gi.createMigration=Gi.LDMigrationError=Gi.LDMigrationSuccess=void 0;const Xi=l,Yi=C;Gi.LDMigrationSuccess=function(e){return{success:!0,result:e}},Gi.LDMigrationError=function(e){return{success:!1,error:e}};class Qi{constructor(e,t){var i,r;this._client=e,this._config=t,this._readTable={[Xi.LDMigrationStage.Off]:async e=>this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),[Xi.LDMigrationStage.DualWrite]:async e=>this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),[Xi.LDMigrationStage.Shadow]:async e=>{const{fromOld:t,fromNew:i}=await this._doRead(e);return this._trackConsistency(e,t,i),t},[Xi.LDMigrationStage.Live]:async e=>{const{fromNew:t,fromOld:i}=await this._doRead(e);return this._trackConsistency(e,i,t),t},[Xi.LDMigrationStage.RampDown]:async e=>this._doSingleOp(e,"new",this._config.readNew.bind(this._config)),[Xi.LDMigrationStage.Complete]:async e=>this._doSingleOp(e,"new",this._config.readNew.bind(this._config))},this._writeTable={[Xi.LDMigrationStage.Off]:async e=>({authoritative:await this._doSingleOp(e,"old",this._config.writeOld.bind(this._config))}),[Xi.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))}},[Xi.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))}},[Xi.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))}},[Xi.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))}},[Xi.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 Yi.LDConcurrentExecution,this._latencyTracking=null===(i=this._config.latencyTracking)||void 0===i||i,this._errorTracking=null===(r=this._config.errorTracking)||void 0===r||r}async read(e,t,i,r){const n=await this._client.migrationVariation(e,t,i),s=await this._readTable[n.value]({payload:r,tracker:n.tracker});return n.tracker.op("read"),this._sendEvent(n.tracker),s}async write(e,t,i,r){const n=await this._client.migrationVariation(e,t,i),s=await this._writeTable[n.value]({payload:r,tracker:n.tracker});return n.tracker.op("write"),this._sendEvent(n.tracker),s}_sendEvent(e){const t=e.createEvent();t&&this._client.trackMigration(t)}_trackConsistency(e,t,i){this._config.check&&t.success&&i.success&&e.tracker.consistency((()=>this._config.check(t.result,i.result)))}async _readSequentialFixed(e){return{fromOld:await this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),fromNew:await this._doSingleOp(e,"new",this._config.readNew.bind(this._config))}}async _readConcurrent(e){const t=this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),i=this._doSingleOp(e,"new",this._config.readNew.bind(this._config)),[r,n]=await Promise.all([t,i]);return{fromOld:r,fromNew:n}}async _readSequentialRandom(e){if(0===Math.floor(2*Math.random())){return{fromOld:await this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),fromNew:await this._doSingleOp(e,"new",this._config.readNew.bind(this._config))}}const t=await this._doSingleOp(e,"new",this._config.readNew.bind(this._config));return{fromOld:await this._doSingleOp(e,"old",this._config.readOld.bind(this._config)),fromNew:t}}async _doRead(e){var t;if((null===(t=this._execution)||void 0===t?void 0:t.type)===Yi.LDExecution.Serial){return this._execution.ordering===Yi.LDExecutionOrdering.Fixed?this._readSequentialFixed(e):this._readSequentialRandom(e)}return this._readConcurrent(e)}async _doSingleOp(e,t,i){e.tracker.invoked(t);const r=await this._trackLatency(e.tracker,t,(()=>async function(e){try{return await e()}catch(e){return{success:!1,error:e}}}((()=>i(e.payload)))));return!r.success&&this._errorTracking&&e.tracker.error(t),Object.assign({origin:t},r)}async _trackLatency(e,t,i){if(!this._latencyTracking)return i();let r,n,s;"undefined"!=typeof performance?(r=performance.now(),s=await i(),n=performance.now()):(r=Date.now(),s=await i(),n=Date.now());const a=n-r;return e.latency(t,a),s}}Gi.createMigration=function(e,t){return new Qi(e,t)};var Zi={},er={},tr={},ir={};Object.defineProperty(ir,"__esModule",{value:!0});ir.default=class{constructor(e,t,i,r){this._filesystem=e,this._paths=t,this._watch=i,this._callback=r,this._watchers=[],this._fileData={},this._fileTimestamps={}}async loadAndWatch(){const e=this._paths.map((async e=>({data:await this._filesystem.readFile(e),path:e,timeStamp:await this._filesystem.getFileTimestamp(e)}))),t=await Promise.all(e);t.forEach((e=>{this._fileData[e.path]=e.data,this._fileTimestamps[e.path]=e.timeStamp})),this._callback(t),this._watch&&this._paths.forEach((e=>{const t=this._filesystem.watch(e,(async(e,t)=>{const i=await this._filesystem.getFileTimestamp(t);if(i===this._fileTimestamps[t])return;this._fileTimestamps[t]=i;const r=await this._filesystem.readFile(t);this._fileData[t]=r,this._debounceCallback()}));this._watchers.push(t)}))}close(){this._watchers.forEach((e=>e.close()))}_debounceCallback(){this._debounceHandle||(this._debounceHandle=setTimeout((()=>{this._debounceHandle=void 0,this._callback(Object.entries(this._fileData).reduce(((e,[t,i])=>(e.push({path:t,data:i}),e)),[]))}),10))}},Object.defineProperty(tr,"__esModule",{value:!0});const rr=ae,nr=oe,sr=ir;tr.default=class{constructor(e,t,i,r=()=>{},n){var s;this._featureStore=i,this._initSuccessHandler=r,this._errorHandler=n,this._allData={},this._fileLoader=new sr.default(t,e.paths,null!==(s=e.autoUpdate)&&void 0!==s&&s,(e=>{var t,i;try{this._processFileData(e)}catch(e){null===(t=this._errorHandler)||void 0===t||t.call(this,e),null===(i=this._logger)||void 0===i||i.error(`Error processing files: ${e}`)}})),this._logger=e.logger,this._yamlParser=e.yamlParser}start(){(async()=>{var e;try{await this._fileLoader.loadAndWatch()}catch(t){null===(e=this._errorHandler)||void 0===e||e.call(this,t)}})()}stop(){this._fileLoader.close()}close(){this.stop()}_addItem(e,t){if(this._allData[e.namespace]||(this._allData[e.namespace]={}),this._allData[e.namespace][t.key])throw new Error(`found duplicate key: "${t.key}"`);this._allData[e.namespace][t.key]=t}_processFileData(e){const t=this._allData;this._allData={},e.forEach((e=>{let i;if(e.path.endsWith(".yml")||e.path.endsWith(".yaml")){if(!this._yamlParser)throw new Error(`Attempted to parse yaml file (${e.path}) without parser.`);i=this._yamlParser(e.data)}else i=JSON.parse(e.data);this._processParsedData(i,t)})),this._featureStore.init(this._allData,(()=>{this._initSuccessHandler(),this._initSuccessHandler=()=>{}}))}_processParsedData(e,t){Object.keys(e.flags||{}).forEach((t=>{(0,rr.processFlag)(e.flags[t]),this._addItem(nr.default.Features,e.flags[t])})),Object.keys(e.flagValues||{}).forEach((i=>{var r,n;const s=null===(r=t[nr.default.Features.namespace])||void 0===r?void 0:r[i];let{version:a}=null!=s?s:{version:1};s&&JSON.stringify(e.flagValues[i])!==JSON.stringify(null===(n=null==s?void 0:s.variations)||void 0===n?void 0:n[0])&&(a+=1);const o=function(e,t,i){return{key:e,on:!0,fallthrough:{variation:0},variations:[t],version:i}}(i,e.flagValues[i],a);(0,rr.processFlag)(o),this._addItem(nr.default.Features,o)})),Object.keys(e.segments||{}).forEach((t=>{(0,rr.processSegment)(e.segments[t]),this._addItem(nr.default.Segments,e.segments[t])}))}},Object.defineProperty(er,"__esModule",{value:!0});const ar=tr;er.default=class{constructor(e){this._options=e}create(e,t,i,r){const n={paths:this._options.paths,autoUpdate:this._options.autoUpdate,logger:this._options.logger||e.basicConfiguration.logger,yamlParser:this._options.yamlParser};return new ar.default(n,e.platform.fileSystem,t,i,r)}getFactory(){return(e,t,i,r)=>this.create(e,t,i,r)}};var or={},lr={},ur={},cr={};!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}}(cr);var dr={};Object.defineProperty(dr,"__esModule",{value:!0});const hr=o,fr=cr;class gr{constructor(e,t,i){this._flagBuilder=e,this._clauses=[],t&&(this._clauses=[...t]),void 0!==i&&(this._variation=i)}andMatch(e,t,...i){return this._clauses.push({contextKind:e,attribute:t,attributeReference:new hr.AttributeReference(t),op:"in",values:i,negate:!1}),this}andNotMatch(e,t,...i){return this._clauses.push({contextKind:e,attribute:t,attributeReference:new hr.AttributeReference(t),op:"in",values:i,negate:!0}),this}thenReturn(e){return hr.TypeValidators.Boolean.is(e)?(this._flagBuilder.booleanFlag(),this.thenReturn((0,fr.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 gr(this._flagBuilder,this._clauses,this._variation)}}dr.default=gr,Object.defineProperty(ur,"__esModule",{value:!0});const vr=o,_r=cr,pr=dr;class yr{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[_r.TRUE_VARIATION_INDEX]&&!1===this._data.variations[_r.FALSE_VARIATION_INDEX]}booleanFlag(){return this._isBooleanFlag?this:this.variations(!0,!1).fallthroughVariation(_r.TRUE_VARIATION_INDEX).offVariation(_r.FALSE_VARIATION_INDEX)}variations(...e){return this._data.variations=[...e],this}on(e){return this._data.on=e,this}fallthroughVariation(e){return vr.TypeValidators.Boolean.is(e)?this.booleanFlag().fallthroughVariation((0,_r.variationForBoolean)(e)):(this._data.fallthroughVariation=e,this)}offVariation(e){return vr.TypeValidators.Boolean.is(e)?this.booleanFlag().offVariation((0,_r.variationForBoolean)(e)):(this._data.offVariation=e,this)}variationForAll(e){return this.on(!0).clearRules().clearAllTargets().fallthroughVariation(e)}valueForAll(e){return this.variations(e).variationForAll(0)}variationForUser(e,t){return this.variationForContext("user",e,t)}variationForContext(e,t,i){return vr.TypeValidators.Boolean.is(i)?this.booleanFlag().variationForContext(e,t,(0,_r.variationForBoolean)(i)):(this._data.targetsByVariation||(this._data.targetsByVariation={}),this._data.variations.forEach(((r,n)=>{if(n===i){const i=this._data.targetsByVariation[n]||{};e in i||(i[e]=[]);-1!==i[e].indexOf(t)||i[e].push(t),this._data.targetsByVariation[n]=i}else{const i=this._data.targetsByVariation[n];if(i){const r=i[e];if(r){const n=r.indexOf(t);-1!==n&&(r.splice(n,1),r.length||delete i[e])}Object.keys(i).length||delete this._data.targetsByVariation[n]}}})),this)}clearRules(){return delete this._data.rules,this}clearAllTargets(){return delete this._data.targetsByVariation,this}ifMatch(e,t,...i){return new pr.default(this).andMatch(e,t,...i)}ifNotMatch(e,t,...i){return new pr.default(this).andNotMatch(e,t,...i)}checkRatio(e){var t;return this._data.migration=null!==(t=this._data.migration)&&void 0!==t?t:{},this._data.migration.checkRatio=e,this}samplingRatio(e){return this._data.samplingRatio=e,this}addRule(e){this._data.rules||(this._data.rules=[]),this._data.rules.push(e)}build(e){const t={key:this._key,version:e,on:this._data.on,offVariation:this._data.offVariation,fallthrough:{variation:this._data.fallthroughVariation},variations:[...this._data.variations],migration:this._data.migration,samplingRatio:this._data.samplingRatio};if(this._data.targetsByVariation){const e=[],i=[];Object.entries(this._data.targetsByVariation).forEach((([t,r])=>{Object.entries(r).forEach((([r,n])=>{const s=parseInt(t,10);e.push({contextKind:r,values:"user"===r?[]:n,variation:s}),"user"===r&&i.push({values:n,variation:s})}))})),t.targets=i,t.contextTargets=e}return this._data.rules&&(t.rules=this._data.rules.map(((e,t)=>e.build(String(t))))),t}clone(){return new yr(this._key,this._data)}getKey(){return this._key}}ur.default=yr;var mr={};Object.defineProperty(mr,"__esModule",{value:!0});mr.default=class{constructor(e,t,i,r,n){this._featureStore=e,this._onStop=r,this._listeners=n,this._flags=Object.assign({},t),this._segments=Object.assign({},i)}async start(){this._listeners.forEach((({processJson:e})=>{e({data:{flags:this._flags,segments:this._segments}})}))}stop(){this._onStop(this)}close(){this.stop()}async upsert(e,t){return this._featureStore.upsert(e,t)}},Object.defineProperty(lr,"__esModule",{value:!0});const br=se,wr=Me,Sr=ae,kr=oe,Er=ur,Or=mr;lr.default=class{constructor(){this._currentFlags={},this._currentSegments={},this._dataSources=[],this._flagBuilders={}}getFactory(){return(e,t,i,r)=>{const n=(0,br.createStreamListeners)(t,e.basicConfiguration.logger,{put:i}),s=new Or.default(new wr.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 Er.default(e).booleanFlag()}update(e){const t=e.getKey(),i=this._currentFlags[t],r=i?i.version:0,n=e.build(r+1);return this._currentFlags[t]=n,this._flagBuilders[t]=e.clone(),Promise.all(this._dataSources.map((e=>e.upsert(kr.default.Features,n))))}usePreconfiguredFlag(e){const t=JSON.parse(JSON.stringify(e)),i=this._currentFlags[t.key],r=Object.assign(Object.assign({},t),{version:i?i.version+1:t.version});return(0,Sr.processFlag)(r),this._currentFlags[t.key]=r,Promise.all(this._dataSources.map((e=>e.upsert(kr.default.Features,r))))}usePreconfiguredSegment(e){const t=JSON.parse(JSON.stringify(e)),i=this._currentSegments[t.key],r=Object.assign(Object.assign({},t),{version:i?i.version+1:t.version});return(0,Sr.processSegment)(r),this._currentSegments[t.key]=r,Promise.all(this._dataSources.map((e=>e.upsert(kr.default.Segments,r))))}},Object.defineProperty(or,"__esModule",{value:!0}),or.TestDataRuleBuilder=or.TestDataFlagBuilder=or.TestData=void 0;const xr=lr;or.TestData=xr.default;const Dr=ur;or.TestDataFlagBuilder=Dr.default;const Mr=dr;or.TestDataRuleBuilder=Mr.default,function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.FileDataSourceFactory=void 0;const n=er;e.FileDataSourceFactory=n.default,i(or,e),i(V,e)}(Zi);var Pr={},Tr={};Object.defineProperty(Tr,"__esModule",{value:!0});Tr.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(Pr,"__esModule",{value:!0}),Pr.NullEventSource=void 0;const Cr=Tr;Pr.NullEventSource=Cr.default,function(e){var t=r&&r.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,n)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),i=r&&r.__exportStar||function(e,i){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(i,r)||t(i,e,r)};Object.defineProperty(e,"__esModule",{value:!0}),e.createMigration=e.LDMigrationSuccess=e.LDMigrationError=e.BigSegmentStoreStatusProviderImpl=e.LDClientImpl=e.platform=e.integrations=void 0;const n=s;e.BigSegmentStoreStatusProviderImpl=n.default;const u=a;e.LDClientImpl=u.default;const c=Gi;Object.defineProperty(e,"createMigration",{enumerable:!0,get:function(){return c.createMigration}}),Object.defineProperty(e,"LDMigrationError",{enumerable:!0,get:function(){return c.LDMigrationError}}),Object.defineProperty(e,"LDMigrationSuccess",{enumerable:!0,get:function(){return c.LDMigrationSuccess}}),e.integrations=Zi,e.platform=o,i(l,e),i(De,e),i(Pr,e),i(o,e)}(n);class Fr{constructor(e){let t;switch(e){case"sha1":t=i.algo.SHA1;break;case"sha256":t=i.algo.SHA256;break;default:throw new Error("unsupported hash algorithm. Only sha1 and sha256 are supported.")}this._cryptoJSHasher=t.create()}digest(e){const t=this._cryptoJSHasher.finalize();let r;switch(e){case"base64":r=i.enc.Base64;break;case"hex":r=i.enc.Hex;break;default:throw new Error("unsupported output encoding. Only base64 and hex are supported.")}return t.toString(r)}update(e){return this._cryptoJSHasher.update(e),this}}class Ir{constructor(e,t){let r;switch(e){case"sha1":r=i.algo.SHA1;break;case"sha256":r=i.algo.SHA256;break;default:throw new Error("unsupported hash algorithm. Only sha1 and sha256 are supported.")}this._cryptoJSHmac=i.algo.HMAC.create(r,t)}digest(e){const t=this._cryptoJSHmac.finalize();if("base64"===e)return t.toString(i.enc.Base64);if("hex"===e)return t.toString(i.enc.Hex);throw new Error("unsupported output encoding. Only base64 and hex are supported.")}update(e){return this._cryptoJSHmac.update(e),this}}class jr{createHash(e){return new Fr(e)}createHmac(e,t){return new Ir(e,t)}randomUUID(){return crypto.randomUUID()}}class Rr{fetch(e,t={}){return fetch(e,t)}createEventSource(e,t){return new n.NullEventSource(e,t)}getEventSourceCapabilities(){return{readTimeout:!1,headers:!1,customMethod:!1}}}class Ar{constructor(e){this.crypto=new jr,this.requests=new Rr,this.info=e}}const Vr={stream:!1,sendEvents:!1,useLdd:!0,diagnosticOptOut:!0,logger:n.BasicLogger.get()};class Nr extends n.LDClientImpl{constructor(t,i,r){const s=new e,a=new Ar(i),o={analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1},l=(e=>{var t;const i=Object.assign(Object.assign({},Vr),e);return null===(t=i.logger)||void 0===t||t.debug(`Using LD options: ${JSON.stringify(i)}`),i})(r);var u,c;super(t,a,l,(u=s,c=l.logger,{onError:e=>{u.listenerCount("error")?u.emit("error",e):null==c||c.error(e.message)},onFailed:e=>{u.emit("failed",e)},onReady:()=>{u.emit("ready")},onUpdate:n.noop,hasEventListeners:()=>!1}),o),this.emitter=s}}class Lr{constructor(e,t,i,r){this._edgeProvider=e,this._description=i,this._logger=r,this.close=n.noop,this.delete=n.noop,this.upsert=n.noop,this._rootKey=`LD-Env-${t}`}async get(e,t,i){const{namespace:r}=e,s="features"===r?"flags":r;this._logger.debug(`Requesting ${t} from ${this._rootKey}.${s}`);try{const e=await this._edgeProvider.get(this._rootKey);if(!e)throw new Error(`${this._rootKey}.${s} is not found in KV.`);const a=n.deserializePoll(e);if(!a)throw new Error(`Error deserializing ${s}`);switch(r){case"features":i(a.flags[t]);break;case"segments":i(a.segments[t]);break;default:i(null)}}catch(e){this._logger.error(e),i(null)}}async all(e,t=n.noop){const{namespace:i}=e,r="features"===i?"flags":i;this._logger.debug(`Requesting all from ${this._rootKey}.${r}`);try{const e=await this._edgeProvider.get(this._rootKey);if(!e)throw new Error(`${this._rootKey}.${r} is not found in KV.`);const s=n.deserializePoll(e);if(!s)throw new Error(`Error deserializing ${r}`);switch(i){case"features":t(s.flags);break;case"segments":t(s.segments);break;default:t({})}}catch(e){this._logger.error(e),t({})}}async initialized(e=n.noop){const t=null!==await this._edgeProvider.get(this._rootKey);this._logger.debug(`Is ${this._rootKey} initialized? ${t}`),e(t)}init(e,t){t()}getDescription(){return this._description}}const Kr=(e,t)=>{const{featureStore:i,logger:r,sendEvents:n}=t,s=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(e);n<r.length;n++)t.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(e,r[n])&&(i[r[n]]=e[r[n]])}return i}(t,["featureStore","logger","sendEvents"]);if(!e)throw new Error("You must configure the client with a client key");if(!i||"object"!=typeof i||!i.get)throw new Error("You must configure the client with a feature store");if(!r)throw new Error("You must configure the client with a logger");if("{}"!==JSON.stringify(s))throw new Error(`Invalid configuration: ${Object.keys(s).toString()} not supported`);return!0};class $r{platformData(){return{name:"Cloudflare"}}sdkData(){return{name:"@launchdarkly/cloudflare-server-sdk",version:"2.6.2",userAgentBase:"CloudflareEdgeSDK"}}}var Ur=Object.defineProperty,zr=Object.getOwnPropertySymbols,Br=Object.prototype.hasOwnProperty,qr=Object.prototype.propertyIsEnumerable,Hr=(e,t,i)=>t in e?Ur(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i;const Wr=(e,t,i={})=>{var r;const s=null!=(r=i.logger)?r:n.BasicLogger.get();return((e,t,i)=>(Kr(e,i),new Nr(e,t,i)))(e,new $r,((e,t)=>{for(var i in t||(t={}))Br.call(t,i)&&Hr(e,i,t[i]);if(zr)for(var i of zr(t))qr.call(t,i)&&Hr(e,i,t[i]);return e})({featureStore:new Lr(t,e,"Cloudflare",s),logger:s},i))};export{Lr as EdgeFeatureStore,Wr as init};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|