@launchdarkly/browser 0.1.8 → 0.1.9
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 +9 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -345,7 +345,7 @@ Project ID: ${this.sessionData.projectID}
|
|
|
345
345
|
SessionSecureID: ${this.sessionData.sessionSecureID}`),this.options.sessionSecureID=this.sessionData.sessionSecureID,this.zn.postMessage({message:{type:Ne.Initialize,sessionSecureID:this.sessionData.sessionSecureID,backend:this.pn,debug:!!this.debugOptions.clientInteractions,recordingStartTime:this.Bn}});for(let g of this.xn)g.init(this.sessionData.sessionSecureID);if(this.sessionData.userIdentifier&&this.identify(this.sessionData.userIdentifier,this.sessionData.userObject),this.pushPayloadTimerId&&(clearTimeout(this.pushPayloadTimerId),this.pushPayloadTimerId=void 0),this.po||(this.pushPayloadTimerId=setTimeout(()=>{this.Ss()},ig)),this.options.disableSessionRecording){this.logger.log("Highlight is NOT RECORDING a session replay per H.init setting."),this.ready=!0,this.state="Recording",this.manualStopped=!1;return}let f=(g,S)=>{S&&this.logger.log("received isCheckout emit",{event:g}),this.events.push(g)};f.bind(this);let m=!!this.Sn;this.Sn&&(this.Sn(),this.Sn=void 0);let[d,v]=SF(this.privacySetting);this.Sn=Ge({ignoreClass:"highlight-ignore",blockClass:"highlight-block",emit:f,recordCrossOriginIframes:this.options.recordCrossOriginIframe,privacySetting:this.privacySetting,maskAllInputs:d,maskInputOptions:v,recordCanvas:this.enableCanvasRecording,sampling:{canvas:{fps:this.samplingStrategy.canvas,fpsManual:this.samplingStrategy.canvasManualSnapshot,resizeFactor:this.samplingStrategy.canvasFactor,clearWebGLBuffer:this.samplingStrategy.canvasClearWebGLBuffer,initialSnapshotDelay:this.samplingStrategy.canvasInitialSnapshotDelay,dataURLOptions:this.samplingStrategy.dataUrlOptions,maxSnapshotDimension:this.samplingStrategy.canvasMaxSnapshotDimension}},keepIframeSrcFn:g=>!this.options.recordCrossOriginIframe,inlineImages:this.inlineImages,inlineVideos:this.inlineVideos,collectFonts:this.inlineImages,inlineStylesheet:this.inlineStylesheet,plugins:[QX()],logger:typeof this.options.debug=="boolean"&&this.options.debug||typeof this.options.debug=="object"&&this.options.debug.domRecording?{debug:this.logger.log,warn:Ht.bind("RecordSDK","warn")}:void 0}),m||this.options.recordCrossOriginIframe&&this.nl(),document.referrer&&(window&&document.referrer.includes(window.location.origin)||(this.addCustomEvent("Referrer",document.referrer),this.addProperties({referrer:document.referrer},{type:"session"}))),this.rl(),this.ready=!0,this.state="Recording",this.manualStopped=!1}catch(u){Ht("initializeSession _setupWindowListeners","warn",u)}})}ws(e){return Yt(this,null,function*(){if(this.manualStopped){this.logger.log("Ignoring visibility event due to manual stop.");return}new Date().getTime()-this.vs<mX||(this.vs=new Date().getTime(),this.logger.log(`Detected window ${e?"hidden":"visible"}.`),e?(this.addCustomEvent("TabHidden",!0),this.options.disableBackgroundRecording&&this.stop()):(this.options.disableBackgroundRecording&&(yield this.start()),this.addCustomEvent("TabHidden",!1)))})}el(){return Yt(this,null,function*(){this.logger.log("highlight in cross-origin iframe is waiting "),yield new Promise(e=>{let n=r=>{if(r.data.highlight===fb){let i=r.data;this.logger.log("highlight got window message ",i),this.sessionData.projectID=i.projectID,this.sessionData.sessionSecureID=i.sessionSecureID,window.parent.postMessage({highlight:mb},"*"),window.removeEventListener("message",n),e()}};window.addEventListener("message",n)})})}nl(){this.logger.log("highlight setting up cross origin iframe parent notification"),setInterval(()=>{window.document.querySelectorAll("iframe").forEach(e=>{var n;(n=e.contentWindow)==null||n.postMessage({highlight:fb,projectID:this.sessionData.projectID,sessionSecureID:this.sessionData.sessionSecureID},"*")})},ig),window.addEventListener("message",e=>{e.data.highlight===mb&&this.logger.log("highlight got response from initialized iframe")})}rl(){var e;try{let r=this;this.enableSegmentIntegration&&this.listeners.push(EF(o=>{if(o.type==="track"){let s={};s["segment-event"]=o.event,r.addProperties(s,{type:"track",source:"segment"})}else if(o.type==="identify"){let s=o.userId.replace(/^"(.*)"$/,"$1");r.identify(s,o.traits,"segment")}})),this.listeners.push(vF(o=>{this.reloaded?(this.addCustomEvent("Reload",o),this.reloaded=!1,r.addProperties({reload:!0},{type:"session"})):this.addCustomEvent("Navigate",o)})),this.listeners.push(DX(o=>{this.addCustomEvent("Viewport",o)})),this.listeners.push(wF((o,s)=>{let a=null,c=null;if(s&&s.target){let l=s.target;a=AX(l),c=l.textContent,c&&c.length>2e3&&(c=c.substring(0,2e3))}this.addCustomEvent("Click",{clickTarget:o,clickTextContent:c,clickSelector:a})})),this.listeners.push(IF(o=>{o&&this.addCustomEvent("Focus",o)})),this.sessionShortcut&&CF(this.sessionShortcut,()=>{window.open(this.getCurrentSessionURLWithTimestamp(),"_blank")}),this.gs||((e=window.electron)!=null&&e.ipcRenderer?(window.electron.ipcRenderer.on("highlight.run",({visible:o})=>{this.ws(!o)}),this.logger.log("Set up Electron highlight.run events.")):(TF(o=>this.ws(o)),this.logger.log("Set up document visibility listener.")),this.gs=!0);let i=()=>{this.hasSessionUnloaded=!0,this.pushPayloadTimerId&&(clearTimeout(this.pushPayloadTimerId),this.pushPayloadTimerId=void 0)};window.addEventListener("beforeunload",i),this.listeners.push(()=>window.removeEventListener("beforeunload",i))}catch(r){Ht("initializeSession _setupWindowListeners","warn",r)}let n=()=>{this.addCustomEvent("Page Unload",""),li(this.sessionData.sessionSecureID),wn(this.sessionData)};if(window.addEventListener("beforeunload",n),this.listeners.push(()=>window.removeEventListener("beforeunload",n)),navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/iPhone/i)){let r=()=>{this.addCustomEvent("Page Unload",""),li(this.sessionData.sessionSecureID),wn(this.sessionData)};window.addEventListener("pagehide",r),this.listeners.push(()=>window.removeEventListener("beforeunload",r))}}stop(e){this.manualStopped=!!e,this.manualStopped&&this.addCustomEvent("Stop","H.stop() was called which stops Highlight from recording."),this.state="NotRecording",e&&this.Sn&&(this.Sn(),this.Sn=void 0),this.listeners.forEach(n=>n()),this.listeners=[]}getCurrentSessionURLWithTimestamp(){let e=new Date().getTime(),{projectID:n,sessionSecureID:r}=this.sessionData,i=(e-this.Bn)/1e3;return`https://${sg}/${n}/sessions/${r}?ts=${i}`}getCurrentSessionURL(){let e=this.sessionData.projectID,n=this.sessionData.sessionSecureID;return e&&n?`https://${sg}/${e}/sessions/${n}`:null}snapshot(e){return Yt(this,null,function*(){yield Ge.snapshotCanvas(e)})}addSessionFeedback({timestamp:e,verbatim:n,user_email:r,user_name:i}){var o;this.zn.postMessage({message:{type:Ne.Feedback,verbatim:n,timestamp:e,userName:i||this.sessionData.userIdentifier,userEmail:r||((o=this.sessionData.userObject)==null?void 0:o.name)}})}Ss(){return Yt(this,null,function*(){var e;try{this.state==="Recording"&&this.listeners&&this.sessionData.sessionStartTime&&Date.now()-this.sessionData.sessionStartTime>fX&&(this.logger.log("Resetting session",{start:this.sessionData.sessionStartTime}),yield this.bs({}));let n;((e=this.options)==null?void 0:e.sendMode)==="local"&&(n=r=>Yt(this,null,function*(){let i=new Blob([JSON.stringify({query:Nb(Ub),variables:r})],{type:"application/json"});return yield window.fetch(`${this.pn}`,{method:"POST",body:i}),0})),yield this.il({sendFn:n}),this.hasPushedData=!0,this.sessionData.lastPushTime=Date.now(),wn(this.sessionData)}catch(n){Ht("_save","warn",n)}this.state==="Recording"&&(this.pushPayloadTimerId&&(clearTimeout(this.pushPayloadTimerId),this.pushPayloadTimerId=void 0),this.pushPayloadTimerId=setTimeout(()=>{this.Ss()},dX))})}addCustomEvent(e,n){if(this.state==="NotRecording"){let r,i=()=>{clearInterval(r),this.state==="Recording"&&this.events.length>0?hb(e,n):r=setTimeout(i,500)};r=setTimeout(i,500)}else this.state==="Recording"&&(this.events.length>0||this.hasPushedData)&&hb(e,n)}il(e){return Yt(this,arguments,function*({sendFn:n}){let r=[...this.events],{bytes:i,time:o}=this.enableCanvasRecording?og.canvas:og.normal;this.br>=i&&new Date().getTime()-this.mo>=o&&this.takeFullSnapshot(),this.logger.log(`Sending: ${r.length} events,
|
|
346
346
|
To: ${this.pn}
|
|
347
347
|
Org: ${this.organizationID}
|
|
348
|
-
SessionSecureID: ${this.sessionData.sessionSecureID}`);let s=XF();n?yield n({session_secure_id:this.sessionData.sessionSecureID,payload_id:(this.sessionData.payloadID++).toString(),events:{events:r},messages:_L({messages:[]}),resources:JSON.stringify({resources:[]}),web_socket_events:JSON.stringify({webSocketEvents:[]}),errors:[],is_beacon:!1,has_session_unloaded:this.hasSessionUnloaded,highlight_logs:s||void 0}):this.zn.postMessage({message:{type:Ne.AsyncEvents,id:this.sessionData.payloadID++,events:r,messages:[],errors:[],resourcesString:JSON.stringify({resources:[]}),webSocketEventsString:JSON.stringify({webSocketEvents:[]}),hasSessionUnloaded:this.hasSessionUnloaded,highlightLogs:s}}),wn(this.sessionData),this.events=this.events.slice(r.length),WF(s)})}takeFullSnapshot(){if(!this.Sn){this.logger.log("skipping full snapshot as rrweb is not running");return}this.logger.log("taking full snapshot",{bytesSinceSnapshot:this.br,lastSnapshotTime:this.mo}),Ge.takeFullSnapshot(),this.br=0,this.mo=new Date().getTime()}register(e,n){this.xn.push(new hu(e,n))}getHooks(e){return this.xn.flatMap(n=>{var r,i;return(i=(r=n.getHooks)==null?void 0:r.call(n,e))!=null?i:[]})}getRecordingState(){var e;return(e=this==null?void 0:this.state)!=null?e:"NotRecording"}getSession(){let e=this.sessionData.sessionSecureID,n=Zs(e);if(!n)return null;let r=`${this.getFrontendUrl()}/sessions/${e}`;if(!r||!(n!=null&&n.sessionStartTime))return null;let i=new Date().getTime(),o=new URL(r),s=new URL(r),a=(i-this.Bn)/1e3;return s.searchParams.set("ts",a.toString()),{url:o.toString(),urlWithTimestamp:s.toString(),sessionSecureID:e}}getFrontendUrl(){var e,n;let r=this.pn.match(vX);if(r&&(e=r==null?void 0:r.groups)!=null&&e.domain){let i=(n=r.groups.domain)!=null?n:"";return`https://${gX[i]}${bX}`}return yX}},Ci=class extends YX{constructor(e,n){var r=(...f)=>(super(...f),Y(this,"record"),this),i,o,s,a,c,l,u,h,p;try{if(r(n),typeof window>"u"||typeof document>"u"){console.warn("@launchdarkly/session-replay is not initializing because it is not supported in this environment.");return}if(typeof Worker>"u"){console.warn("@launchdarkly/session-replay is not initializing because Worker is not supported.");return}if(!e){console.warn("@launchdarkly/session-replay is not initializing because projectID was passed undefined.");return}let f=Kt(z({},n),{organizationID:e,firstloadVersion:JF,environment:(n==null?void 0:n.environment)||"production",appVersion:n==null?void 0:n.version,sessionSecureID:this.sessionSecureID,privacySetting:(i=n==null?void 0:n.privacySetting)!=null?i:"strict"});this.record=new ih(f),n!=null&&n.manualStart||this.record.start(),In.load(this.record),!((s=(o=n==null?void 0:n.integrations)==null?void 0:o.mixpanel)!=null&&s.disabled)&&(c=(a=n==null?void 0:n.integrations)==null?void 0:a.mixpanel)!=null&&c.projectToken&&FF(n.integrations.mixpanel),!((u=(l=n==null?void 0:n.integrations)==null?void 0:l.amplitude)!=null&&u.disabled)&&(p=(h=n==null?void 0:n.integrations)==null?void 0:h.amplitude)!=null&&p.apiKey&&MF(n.integrations.amplitude)}catch(f){Ht("Error initializing @launchdarkly/session-replay SDK","error",f)}}getMetadata(){return{name:"@launchdarkly/session-replay"}}register(e,n){var r;(r=this.record)==null||r.register(e,n)}getHooks(e){return[{getMetadata:()=>({name:"@launchdarkly/session-replay/hooks"}),afterIdentify:(n,r,i)=>{var o,s,a,c,l,u,h;for(let p of(a=(s=(o=this.record)==null?void 0:o.getHooks)==null?void 0:s.call(o,e))!=null?a:[])(c=p.afterIdentify)==null||c.call(p,n,r,i);if(i.status==="completed"){let p=PX(n.context),f=MX(n.context);(h=this.record)==null||h.identify(typeof f=="string"?f:(u=(l=f.user)==null?void 0:l.toString())!=null?u:p,Kt(z({key:p},typeof f=="object"?f:{}),{timeout:n.timeout}),"LaunchDarkly")}return r},afterEvaluation:(n,r,i)=>{var o,s,a,c;for(let l of(a=(s=(o=this.record)==null?void 0:o.getHooks)==null?void 0:s.call(o,e))!=null?a:[])(c=l.afterEvaluation)==null||c.call(l,n,r,i);return r},afterTrack:n=>{var r,i,o,s,a;for(let c of(o=(i=(r=this.record)==null?void 0:r.getHooks)==null?void 0:i.call(r,e))!=null?o:[])(s=c.afterTrack)==null||s.call(c,n);(a=this.record)==null||a.track(n.key,{data:n.data,value:n.metricValue})}}]}}});var q0=Object.defineProperty,tS=Object.defineProperties,eS=Object.getOwnPropertyDescriptors,Pi=Object.getOwnPropertySymbols,pp=Object.prototype.hasOwnProperty,dp=Object.prototype.propertyIsEnumerable,Dh=(t,e,n)=>e in t?q0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,st=(t,e)=>{for(var n in e||(e={}))pp.call(e,n)&&Dh(t,n,e[n]);if(Pi)for(var n of Pi(e))dp.call(e,n)&&Dh(t,n,e[n]);return t},me=(t,e)=>tS(t,eS(e)),fp=(t,e)=>{var n={};for(var r in t)pp.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&Pi)for(var r of Pi(t))e.indexOf(r)<0&&dp.call(t,r)&&(n[r]=t[r]);return n};function nS(t){return`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`}function mp(t){return t.indexOf("~")?t.replace(/~1/g,"/").replace(/~0/g,"~"):t}function rS(t){return(t.startsWith("/")?t.substring(1):t).split("/").map(e=>mp(e))}function iS(t){return!t.startsWith("/")}function oS(t){return!t.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var Nn=class{constructor(t,e=!1){if(e){let n=t;this.m=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?nS(n):n}else{if(this.redactionName=t,t===""||t==="/"||!oS(t)){this.isValid=!1,this.m=[];return}iS(t)?this.m=[t]:t.indexOf("/",1)<0?this.m=[mp(t.slice(1))]:this.m=rS(t),this.m[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{m:e,isValid:n}=this;if(!n)return;let r=t;for(let i=0;i<e.length;i+=1){let o=e[i];if(r!=null&&Object.prototype.hasOwnProperty.call(r,o)&&typeof r=="object"&&!Array.isArray(r))r=r[o];else return}return r}getComponent(t){return this.m[t]}get depth(){return this.m.length}get isKind(){return this.m.length===1&&this.m[0]==="kind"}compare(t){return this.depth===t.depth&&this.m.every((e,n)=>e===t.getComponent(n))}get components(){return[...this.m]}};Nn.InvalidReference=new Nn("");var sS=class{is(t){if(Array.isArray(t))return!1;let e=typeof t;return e==="function"||e==="object"}getType(){return"factory method or object"}},Ln=class{constructor(t,e){this.ft=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.ft}},yp=class{constructor(t,e){this.ft=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?t.length>0?t.every(e=>typeof e===this.typeOf):!0:!1}getType(){return this.ft}},gp=class extends Ln{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},bp=class extends Ln{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},aS=class{is(t){return typeof t=="function"}getType(){return"function"}},lS=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},cS=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,uS=class{is(t){return typeof t=="number"||typeof t=="string"&&cS.test(t)}getType(){return"date"}},hS=class extends bp{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},G=class{static createTypeArray(t,e){return new yp(t,e)}static numberWithMin(t){return new gp(t)}static stringMatchingRegex(t){return new bp(t)}};G.String=new Ln("string","");G.Number=new Ln("number",0);G.ObjectOrFactory=new sS;G.Object=new Ln("object",{});G.StringArray=new yp("string[]","");G.Boolean=new Ln("boolean",!0);G.Function=new aS;G.Date=new uS;G.Kind=new hS;G.NullableBoolean=new lS;function vp(t){return"kind"in t?G.String.is(t.kind)&&t.kind!=="multi":!1}function Sp(t){return"kind"in t?G.String.is(t.kind)&&t.kind==="multi":!1}function wp(t){return!("kind"in t)||t.kind===null||t.kind===void 0}function Mi(t,e=[]){if(t===null||typeof t!="object")return JSON.stringify(t);if(e.includes(t))throw new Error("Cycle detected");return Array.isArray(t)?`[${t.map(n=>Mi(n,[...e,t])).map(n=>n===void 0?"null":n).join(",")}]`:`{${Object.keys(t).sort().map(n=>{let r=Mi(t[n],[...e,t]);if(r!==void 0)return`${JSON.stringify(n)}:${r}`}).filter(n=>n!==void 0).join(",")}}`}var La="user";function Yh(t){return t.includes("%")||t.includes(":")?t.replace(/%/g,"%25").replace(/:/g,"%3A"):t}function pS(t){return t&&G.Object.is(t)}function Kh(t){return G.Kind.is(t)}function _h(t){return G.String.is(t)&&t!==""}function Ra(t,e=!1){return t?t.map(n=>new Nn(n,e)):[]}function dS(t){return t!=null}function fS(t){let e=me(st({},t.custom||[]),{kind:"user",key:String(t.key)});if(dS(t.anonymous)){let n=!!t.anonymous;delete e.anonymous,e.anonymous=n}return t.name!==null&&t.name!==void 0&&(e.name=t.name),t.ip!==null&&t.ip!==void 0&&(e.ip=t.ip),t.firstName!==null&&t.firstName!==void 0&&(e.firstName=t.firstName),t.lastName!==null&&t.lastName!==void 0&&(e.lastName=t.lastName),t.email!==null&&t.email!==void 0&&(e.email=t.email),t.avatar!==null&&t.avatar!==void 0&&(e.avatar=t.avatar),t.country!==null&&t.country!==void 0&&(e.country=t.country),t.privateAttributeNames!==null&&t.privateAttributeNames!==void 0&&(e._meta={privateAttributes:t.privateAttributeNames}),e}var xn=class wt{constructor(e,n,r){this.C=!1,this.Q=!1,this.qt=!1,this.N={},this.kind=n,this.valid=e,this.message=r}static b(e,n){return new wt(!1,e,n)}static Ae(e,n){if(!(!n||!e.isValid))return e.depth===1&&e.getComponent(0)==="anonymous"?!!(n!=null&&n.anonymous):e.get(n)}Jt(e){if(this.C)return this.N[e];if(this.kind===e)return this.y}static Pe(e){let n=Object.keys(e).filter(c=>c!=="kind"),r=n.every(Kh);if(!n.length)return wt.b("multi","A multi-kind context must contain at least one kind");if(!r)return wt.b("multi","Context contains invalid kinds");let i={},o=!0,s=n.reduce((c,l)=>{var u;let h=e[l];return pS(h)?(c[l]=h,i[l]=Ra((u=h._meta)==null?void 0:u.privateAttributes)):o=!1,c},{});if(!o)return wt.b("multi","Context contained contexts that were not objects");if(!Object.values(s).every(c=>_h(c.key)))return wt.b("multi","Context contained invalid keys");if(n.length===1){let c=n[0],l=new wt(!0,c);return l.y=me(st({},s[c]),{kind:c}),l.tt=i,l.Q=c==="user",l}let a=new wt(!0,e.kind);return a.N=s,a.tt=i,a.C=!0,a}static Te(e){var n;let{key:r,kind:i}=e,o=Kh(i),s=_h(r);if(!o)return wt.b(i!=null?i:"unknown","The kind was not valid for the context");if(!s)return wt.b(i,"The key for the context was not valid");let a=Ra((n=e._meta)==null?void 0:n.privateAttributes),c=new wt(!0,i);return c.Q=i==="user",c.y=e,c.tt={[i]:a},c}static Ne(e){if(!(e.key!==void 0&&e.key!==null))return wt.b("user","The key for the context was not valid");let n=new wt(!0,"user");return n.Q=!0,n.qt=!0,n.y=fS(e),n.tt={user:Ra(e.privateAttributeNames,!0)},n}static fromLDContext(e){return e?vp(e)?wt.Te(e):Sp(e)?wt.Pe(e):wp(e)?wt.Ne(e):wt.b("unknown","Context was not of a valid kind"):wt.b("unknown","No context specified. Returning default value")}static toLDContext(e){if(!e.valid)return;let n=e.getContexts();if(!e.C)return n[0][1];let r={kind:"multi"};return n.forEach(i=>{let o=i[0],s=i[1];r[o]=s}),r}valueForKind(e,n=La){return e.isKind?this.kinds:wt.Ae(e,this.Jt(n))}key(e=La){var n;return(n=this.Jt(e))==null?void 0:n.key}get isMultiKind(){return this.C}get canonicalKey(){return this.Q?this.y.key:this.C?Object.keys(this.N).sort().map(e=>`${e}:${Yh(this.N[e].key)}`).join(":"):`${this.kind}:${Yh(this.y.key)}`}get kinds(){return this.C?Object.keys(this.N):[this.kind]}get kindsAndKeys(){return this.C?Object.entries(this.N).reduce((e,[n,r])=>(e[n]=r.key,e),{}):{[this.kind]:this.y.key}}privateAttributes(e){var n;return((n=this.tt)==null?void 0:n[e])||[]}getContexts(){return this.C?Object.entries(this.N):[[this.kind,this.y]]}get legacy(){return this.qt}canonicalUnfilteredJson(){if(this.valid){if(this.pt)return this.pt;try{this.pt=Mi(wt.toLDContext(this))}catch(e){}return this.pt}}};xn.UserKind=La;var mS=["key","kind","_meta","anonymous"].map(t=>new Nn(t,!0)),yS=["name","ip","firstName","lastName","email","avatar","country"];function gS(t,e){return t.depth===e.length&&e.every((n,r)=>n===t.getComponent(r))}function bS(t,e){let n=[],r={},i=[];for(n.push(...Object.keys(t).map(o=>({key:o,ptr:[o],source:t,parent:r,visited:[t]})));n.length;){let o=n.pop(),s=e.find(a=>gS(a,o.ptr));if(s)i.push(s.redactionName);else{let a=o.source[o.key];a===null?o.parent[o.key]=a:Array.isArray(a)?o.parent[o.key]=[...a]:typeof a=="object"?o.visited.includes(a)||(o.parent[o.key]={},n.push(...Object.keys(a).map(c=>({key:c,ptr:[...o.ptr,c],source:a,parent:o.parent[o.key],visited:[...o.visited,a]})))):o.parent[o.key]=a}}return{cloned:r,excluded:i.sort()}}var vS=class{constructor(t,e){this.$e=t,this.Re=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.Yt(t,n[0][1],n[0][0],e);let r={kind:"multi"};return n.forEach(([i,o])=>{r[i]=this.Yt(t,o,i,e)}),r}Me(t,e,n,r){return(r?Object.keys(e).map(i=>new Nn(i,!0)):[...this.Re,...t.privateAttributes(n)]).filter(i=>!mS.some(o=>o.compare(i)))}Yt(t,e,n,r){let i=this.$e||r&&e.anonymous===!0,{cloned:o,excluded:s}=bS(e,this.Me(t,e,n,i));return t.legacy&&yS.forEach(a=>{a in o&&(o[a]=String(o[a]))}),s.length&&(o._meta||(o._meta={}),o._meta.redactedAttributes=s),o._meta&&(delete o._meta.privateAttributes,Object.keys(o._meta).length===0&&delete o._meta),o}},Hh=30*1e3,SS=.5,wS=class{constructor(t,e,n=Math.random){this.Fe=e,this.Ue=n,this.gt=0,this.Zt=Math.max(1,t),this.Ve=Math.ceil(Math.log2(Hh/this.Zt))}I(){let t=Math.min(this.gt,this.Ve),e=this.Zt*2**t;return Math.min(e,Hh)}je(t){return t-Math.trunc(this.Ue()*SS*t)}success(t=Date.now()){this.mt=t}fail(t=Date.now()){this.mt!==void 0&&t-this.mt>this.Fe&&(this.gt=0),this.mt=void 0;let e=this.je(this.I());return this.gt+=1,e}},zh;(function(t){t[t.Valid=0]="Valid",t[t.Initializing=1]="Initializing",t[t.Interrupted=2]="Interrupted",t[t.Closed=3]="Closed"})(zh||(zh={}));var Fi=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=r}},Xa=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=r}},YF=120*1e3,KF=300*1e3,At;(function(t){t.Unknown="UNKNOWN",t.NetworkError="NETWORK_ERROR",t.ErrorResponse="ERROR_RESPONSE",t.InvalidData="INVALID_DATA"})(At||(At={}));var Ai;(function(t){t[t.Disabled=0]="Disabled",t[t.Enabled=1]="Enabled"})(Ai||(Ai={}));var On;(function(t){t[t.AnalyticsEvents=0]="AnalyticsEvents",t[t.DiagnosticEvent=1]="DiagnosticEvent"})(On||(On={}));var qe;(function(t){t[t.Succeeded=0]="Succeeded",t[t.Failed=1]="Failed",t[t.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(qe||(qe={}));function Vn(t){if(typeof t=="string")return t;if(t===void 0)return"undefined";if(t===null)return"null";if(Object.prototype.hasOwnProperty.call(t,"toString"))try{return t.toString()}catch(e){}if(typeof t=="bigint")return`${t}n`;try{return JSON.stringify(t)}catch(e){return e instanceof TypeError&&e.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}function IS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(Number(t))}function TS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(parseInt(t,10))}function ES(t){return typeof t=="symbol"?"NaN":String(parseFloat(t))}var Ca={s:t=>Vn(t),d:t=>IS(t),i:t=>TS(t),f:t=>ES(t),j:t=>Vn(t),o:t=>Vn(t),O:t=>Vn(t),c:()=>""};function Wa(...t){var e;let n=t.shift();if(G.String.is(n)){let r="",i=0;for(;i<n.length;){let o=n.charAt(i);if(o==="%"){if(i+1<n.length){let s=n.charAt(i+1);if(s in Ca&&t.length){let a=t.shift();r+=(e=Ca[s])==null?void 0:e.call(Ca,a)}else s==="%"?r+="%":r+=`%${s}`;i+=2}}else r+=o,i+=1}return t.length&&(r.length&&(r+=" "),r+=t.map(Vn).join(" ")),r}return t.map(Vn).join(" ")}var Vt;(function(t){t[t.debug=0]="debug",t[t.info=1]="info",t[t.warn=2]="warn",t[t.error=3]="error",t[t.none=4]="none"})(Vt||(Vt={}));var RS=["debug","info","warn","error","none"],Ma=class Ip{static get(){return new Ip({})}constructor(e){var n,r,i;if(this.qe=(r=Vt[(n=e.level)!=null?n:"info"])!=null?r:Vt.info,this.Je=(i=e.name)!=null?i:"LaunchDarkly",this.ie=e.formatter,typeof e.destination=="object")this.ne={[Vt.debug]:e.destination.debug,[Vt.info]:e.destination.info,[Vt.warn]:e.destination.warn,[Vt.error]:e.destination.error};else if(typeof e.destination=="function"){let{destination:o}=e;this.ne={[Vt.debug]:o,[Vt.info]:o,[Vt.warn]:o,[Vt.error]:o}}}Ye(...e){var n;try{return this.ie?(n=this.ie)==null?void 0:n.call(this,...e):Wa(...e)}catch(r){return Wa(...e)}}Ze(e,n){try{e(n)}catch(r){console.error(n)}}k(e,n){var r;if(e>=this.qe){let i=`${RS[e]}: [${this.Je}]`;try{let o=(r=this.ne)==null?void 0:r[e];o?this.Ze(o,`${i} ${this.Ye(...n)}`):console.error(...n)}catch(o){console.error(...n)}}}error(...e){this.k(Vt.error,e)}warn(...e){this.k(Vt.warn,e)}info(...e){this.k(Vt.info,e)}debug(...e){this.k(Vt.debug,e)}},CS={error:G.Function,warn:G.Function,info:G.Function,debug:G.Function},Tp=class{constructor(t,e){Object.entries(CS).forEach(([n,r])=>{if(!r.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.Xe=e}k(t,e){try{this.t[t](...e)}catch(n){this.Xe[t](...e)}}error(...t){this.k("error",t)}warn(...t){this.k("warn",t)}info(...t){this.k("info",t)}debug(...t){this.k("debug",t)}},Ep=t=>{let e=new Ma({level:"info",destination:console.error,formatter:Wa});return t?new Tp(t,e):e},Ue=class{static deprecated(t,e){return`"${t}" is deprecated, please use "${e}"`}static optionBelowMinimum(t,e,n){return`Config option "${t}" had invalid value of ${e}, using minimum of ${n} instead`}static unknownOption(t){return`Ignoring unknown config option "${t}"`}static wrongOptionType(t,e,n){return`Config option "${t}" should be of type ${e}, got ${n}, using default value`}static wrongOptionTypeBoolean(t,e){return`Config option "${t}" should be a boolean, got ${e}, converting to boolean`}static invalidTagValue(t){return`Config option "${t}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(t){return`Value of "${t}" was longer than 64 characters and was discarded.`}static partialEndpoint(t){return`You have set custom uris without specifying the ${t} URI; connections may not work properly`}},ZS=/^(\w|\.|-)+$/,kS=G.stringMatchingRegex(ZS),VS={is:(t,e)=>kS.is(t)?t.length>64?{valid:!1,message:Ue.tagValueTooLong(e)}:{valid:!0}:{valid:!1,message:Ue.invalidTagValue(e)}},xS=class{constructor(t){let e={},n=t==null?void 0:t.application,r=t==null?void 0:t.logger;n&&Object.entries(n).forEach(([o,s])=>{if(s!=null){let{valid:a,message:c}=VS.is(s,`application.${o}`);a?o==="versionName"?e["application-version-name"]=[s]:e[`application-${o}`]=[s]:r==null||r.warn(c)}});let i=Object.keys(e);i.length&&(this.value=i.sort().flatMap(o=>e[o].sort().map(s=>`${o}/${s}`)).join(" "))}},NS=class{constructor(t,e,n){this.platform=n,this.basicConfiguration={tags:e.tags,logger:e.logger,offline:e.offline,serviceEndpoints:e.serviceEndpoints,sdkKey:t}}};function Za(t){return t.replace(/\/+$/,"")}function Fa(t){return t.replace(/^\/+/,"").replace(/\?$/,"")}var Ji=class Rp{constructor(e,n,r=Rp.DEFAULT_EVENTS,i="/bulk",o="/diagnostic",s=!0,a){this.streaming=Za(e),this.polling=Za(n),this.events=Za(r),this.analyticsEventPath=i,this.diagnosticEventPath=o,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}};Ji.DEFAULT_EVENTS="https://events.launchdarkly.com";function Aa(t,e=[]){if(e.length===0)return t;let n=e.map(({key:r,value:i})=>`${r}=${i}`);return`${t}?${n.join("&")}`}function OS(t,e,n){let r=Fa(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Aa(`${t.streaming}/${r}`,i)}function GS(t,e,n=[]){let r=Fa(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Aa(`${t.polling}/${r}`,i)}function Bh(t,e,n=[]){let r=Fa(e);return Aa(`${t.events}/${r}`,n)}var Cp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},LS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},Zp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function Ki(t){return t>=400&&t<500?t===400||t===408||t===429:!0}function XS(t){return t===413?!0:Ki(t)}function WS(t,e){let n,r;return{promise:new Promise((i,o)=>{r=i,n=setTimeout(()=>{let s=`${e} timed out after ${t} seconds.`;o(new Zp(s))},t*1e3)}),cancel:()=>{r(),clearTimeout(n)}}}function kp(t){return t==null?t:JSON.parse(JSON.stringify(t))}function ka(t){return Math.trunc(t*1e3)}var US=t=>JSON.stringify(t)==="{}",Ja=(t,e)=>t&&Object.entries(t).reduce((n,[r,i])=>(i&&!US(i)&&!(e!=null&&e.includes(r))&&(n[r]=typeof i=="object"?Ja(i,e):i),n),{});function Wi(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(t.constructor!==e.constructor)return!1;var n,r,i;if(Array.isArray(t)){if(n=t.length,n!=e.length)return!1;for(r=n;r--!==0;)if(!Wi(t[r],e[r]))return!1;return!0}if(t instanceof Map&&e instanceof Map){if(t.size!==e.size)return!1;for(r of t.entries())if(!e.has(r[0]))return!1;for(r of t.entries())if(!Wi(r[1],e.get(r[0])))return!1;return!0}if(t instanceof Set&&e instanceof Set){if(t.size!==e.size)return!1;for(r of t.entries())if(!e.has(r[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(e)){if(n=t.length,n!=e.length)return!1;for(r=n;r--!==0;)if(t[r]!==e[r])return!1;return!0}if(t.constructor===RegExp)return t.source===e.source&&t.flags===e.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===e.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===e.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(e).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(e,i[r]))return!1;for(r=n;r--!==0;){var o=i[r];if(!Wi(t[o],e[o]))return!1}return!0}return t!==t&&e!==e}function PS(t,e,n,r=!0,i="user-agent"){let{userAgentBase:o,version:s,wrapperName:a,wrapperVersion:c}=e.sdkData(),l={[i]:`${o!=null?o:"NodeJSClient"}/${s}`};return r&&(l.authorization=t),a&&(l["x-launchdarkly-wrapper"]=c?`${a}/${c}`:a),n!=null&&n.value&&(l["x-launchdarkly-tags"]=n.value),l}function Gn(t,e,n){let r;t.status?r=`error ${t.status}${t.status===401?" (invalid SDK key)":""}`:r=`I/O error (${t.message||"unknown error"})`;let i=n!=null?n:"giving up permanently";return`Received ${r} for ${e} - ${i}`}function Vp({status:t}){return t?Ki(t):!0}var jh=(t,e)=>e.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),xp=async(t=1e3)=>new Promise(e=>{setTimeout(e,t)}),MS=class{constructor(t,e,n){this.p=e,this.Qe=n,this.wt=[],this.re=Date.now(),this.se=this.re,this.ae={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var t,e,n;let r=this.p.info.sdkData(),i=this.p.info.platformData();return{kind:"diagnostic-init",id:this.ae,creationDate:this.re,sdk:r,configuration:this.Qe,platform:st({name:i.name,osArch:(t=i.os)==null?void 0:t.arch,osName:(e=i.os)==null?void 0:e.name,osVersion:(n=i.os)==null?void 0:n.version},i.additional||{})}}recordStreamInit(t,e,n){let r={timestamp:t,failed:e,durationMillis:n};this.wt.push(r)}createStatsEventAndReset(t,e,n){let r=Date.now(),i={kind:"diagnostic",id:this.ae,creationDate:r,dataSinceDate:this.se,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.wt};return this.wt=[],this.se=r,i}},Ua;(function(t){t.MalformedFlag="MALFORMED_FLAG",t.UserNotSpecified="USER_NOT_SPECIFIED",t.FlagNotFound="FLAG_NOT_FOUND",t.ClientNotReady="CLIENT_NOT_READY",t.WrongType="WRONG_TYPE"})(Ua||(Ua={}));var FS=Ua,Np=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};Np.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var AS=class{constructor(t,e){let{basicConfiguration:n,platform:r}=t,{serviceEndpoints:{analyticsEventPath:i,diagnosticEventPath:o}}=n,{crypto:s,requests:a}=r;this.ti=st({},e),this.oe=Bh(n.serviceEndpoints,i,[]),this.ei=Bh(n.serviceEndpoints,o,[]),this.V=a,this.ii=s}async et(t,e,n,r){let i={status:qe.Succeeded},o=me(st({},this.ti),{"content-type":"application/json"});n&&(o["x-launchdarkly-payload-id"]=n,o["x-launchDarkly-event-schema"]="4");let s;try{let{status:a,headers:c}=await this.V.fetch(e,{headers:o,body:JSON.stringify(t),compressBodyIfPossible:!0,method:"POST",keepalive:!0}),l=Date.parse(c.get("date")||"");if(l&&(i.serverTime=l),a<=204)return i;if(s=new Cp(Gn({status:a,message:"some events were dropped"},"event posting")),!Ki(a))return XS(a)?i.status=qe.Failed:i.status=qe.FailedAndMustShutDown,i.error=s,i}catch(a){s=a}return s&&!r?(i.status=qe.Failed,i.error=s,i):(await xp(),this.et(t,this.oe,n,!1))}async sendEventData(t,e){let n=t===On.AnalyticsEvents?this.ii.randomUUID():void 0,r=t===On.AnalyticsEvents?this.oe:this.ei;return this.et(e,r,n,!0)}};function Di(t){return t.kind==="feature"}function JS(t){return t.kind==="identify"}function DS(t){return t.kind==="migration_op"}var YS=class{constructor(t,e,n,r,i,o){this.count=t,this.key=e,this.value=n,this.version=i,this.variation=o,this.default=r}increment(){this.count+=1}};function KS(t){return`${t.key}:${t.variation!==null&&t.variation!==void 0?t.variation:""}:${t.version!==null&&t.version!==void 0?t.version:""}`}var Op=class{constructor(t=!1,e){this.ni=t,this.x=e,this.W=0,this.it=0,this.nt={},this.rt={}}summarizeEvent(t){if(Di(t)&&!t.excludeFromSummaries){this.y||(this.y=t.context);let e=KS(t),n=this.nt[e],r=this.rt[t.key];r||(r=new Set,this.rt[t.key]=r),t.context.kinds.forEach(i=>r.add(i)),n?n.increment():this.nt[e]=new YS(1,t.key,t.value,t.default,t.version,t.variation),(this.W===0||t.creationDate<this.W)&&(this.W=t.creationDate),t.creationDate>this.it&&(this.it=t.creationDate)}}getSummary(){var t;let e=Object.values(this.nt).reduce((r,i)=>{let o=r[i.key];o||(o={default:i.default,counters:[],contextKinds:[...this.rt[i.key]]},r[i.key]=o);let s={value:i.value,count:i.count};return i.variation!==void 0&&i.variation!==null&&(s.variation=i.variation),i.version!==void 0&&i.version!==null?s.version=i.version:s.unknown=!0,o.counters.push(s),r},{}),n={startDate:this.W,endDate:this.it,features:e,kind:"summary",context:this.y!==void 0&&this.ni?(t=this.x)==null?void 0:t.filter(this.y):void 0};return this.ri(),n}ri(){this.W=0,this.it=0,this.nt={},this.rt={}}},_S=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}},HS=class{constructor(t,e){this.x=t,this.t=e,this.q={}}summarizeEvent(t){var e;if(Di(t)){let n=t.context.canonicalUnfilteredJson();if(!n){t.context.valid&&((e=this.t)==null||e.error("Unable to serialize context, likely the context contains a cycle."));return}let r=this.q[n];r||(this.q[n]=new Op(!0,this.x),r=this.q[n]),r.summarizeEvent(t)}}getSummaries(){let t=this.q;return this.q={},Object.values(t).map(e=>e.getSummary())}};function Ui(t){let e=Math.trunc(t);return e===1?!0:e===0?!1:Math.floor(Math.random()*e)===0}function zS(t){return t.getSummaries!==void 0}var BS=class{constructor(t,e,n,r,i,o=!0,s=!1){this.e=t,this.st=r,this.S=i,this.at=[],this.ce=0,this.Et=0,this.Dt=0,this.bt=!1,this.le=0,this.kt=!1,this.xt=null,this.si=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.ue=new AS(e,n),this.x=new vS(t.allAttributesPrivate,t.privateAttributes.map(a=>new Nn(a))),s?this.J=new HS(this.x,this.t):this.J=new Op,o&&this.start()}start(){var t,e;if(((t=this.st)==null?void 0:t.flushInterval)!==void 0&&(this.xt=setInterval(()=>{var n;(n=this.st)==null||n.flush()},this.st.flushInterval*1e3)),this.ai=setInterval(async()=>{var n;try{await this.flush()}catch(r){(n=this.t)==null||n.debug(`Flush failed: ${r}`)}},this.e.flushInterval*1e3),this.S){let n=this.S.createInitEvent();this.he(n),this.de=setInterval(()=>{let r=this.S.createStatsEventAndReset(this.Et,this.Dt,this.le);this.Et=0,this.Dt=0,this.he(r)},this.e.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}he(t){this.ue.sendEventData(On.DiagnosticEvent,t)}close(){clearInterval(this.ai),this.xt&&clearInterval(this.xt),this.de&&clearInterval(this.de)}async flush(){var t;if(this.kt)throw new _S("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.");let e=this.at;if(this.at=[],zS(this.J))this.J.getSummaries().forEach(n=>{Object.keys(n.features).length&&e.push(n)});else{let n=this.J.getSummary();Object.keys(n.features).length&&e.push(n)}e.length&&(this.le=e.length,(t=this.t)==null||t.debug("Flushing %d events",e.length),await this.et(e))}sendEvent(t){var e;if(this.kt)return;if(DS(t)){if(Ui(t.samplingRatio)){let a=me(st({},t),{context:t.context?this.x.filter(t.context):void 0});a.samplingRatio===1&&delete a.samplingRatio,this.ot(a)}return}this.J.summarizeEvent(t);let n=Di(t),r=n&&t.trackEvents||!n,i=this.oi(t),o=JS(t),s=(e=this.st)==null?void 0:e.processContext(t.context);s||o||(this.Dt+=1),s&&!o&&this.ot(this.St({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),r&&Ui(t.samplingRatio)&&this.ot(this.St(t,!1)),i&&Ui(t.samplingRatio)&&this.ot(this.St(t,!0))}St(t,e){switch(t.kind){case"feature":{let n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.x.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.prereqOf&&(n.prereqOf=t.prereqOf),t.variation!==void 0&&(n.variation=t.variation),t.version!==void 0&&(n.version=t.version),t.reason&&(n.reason=t.reason),n}case"index":case"identify":{let n={kind:t.kind,creationDate:t.creationDate,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),n}case"custom":{let n={kind:"custom",creationDate:t.creationDate,key:t.key,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.data!==void 0&&(n.data=t.data),t.metricValue!==void 0&&(n.metricValue=t.metricValue),t.url!==void 0&&(n.url=t.url),n}case"click":return{kind:"click",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url,selector:t.selector};case"pageview":return{kind:"pageview",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url};default:return t}}ot(t){var e;this.at.length<this.si?(this.at.push(t),this.bt=!1):(this.bt||(this.bt=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.Et+=1)}oi(t){return Di(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.ce&&t.debugEventsUntilDate>Date.now()}async et(t){let e=await this.ue.sendEventData(On.AnalyticsEvents,t);if(e.status===qe.FailedAndMustShutDown&&(this.kt=!0),e.serverTime&&(this.ce=e.serverTime),e.error)throw e.error}},Gp=class{constructor(t,e,n,r,i=1,o){this.context=t,this.key=e,this.data=n,this.metricValue=r,this.samplingRatio=i,this.url=o,this.kind="custom",this.creationDate=Date.now(),this.context=t}},Pa=class{constructor(t,e,n,r,i,o,s,a,c,l,u,h,p=1){this.withReasons=t,this.context=e,this.key=n,this.samplingRatio=p,this.kind="feature",this.creationDate=Date.now(),this.value=r,this.default=i,o!==void 0&&(this.version=o),s!==void 0&&(this.variation=s),a!==void 0&&(this.trackEvents=a),c!==void 0&&(this.prereqOf=c),l!==void 0&&(this.reason=l),u!==void 0&&(this.debugEventsUntilDate=u),h!==void 0&&(this.excludeFromSummaries=h)}},Lp=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},jS=class{close(){}async flush(){}sendEvent(){}},QS=class{constructor(t){this.Lt=t}evalEvent(t){var e;return new Pa(this.Lt,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.Lt||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new Pa(this.Lt,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new Lp(t,1)}customEvent(t,e,n,r,i=1){return new Gp(e,t,n!=null?n:void 0,r!=null?r:void 0,i)}},Qh="FDv1Fallback";function $S(t){return{ci:t,fe:"",useSelector(e){return this.fe=e,this},processFullTransfer(e){let n=[{event:"server-intent",data:{payloads:[{id:Qh,target:1,intentCode:"xfer-full",reason:"payload-missing"}]}}];Object.entries((e==null?void 0:e.flags)||[]).forEach(([r,i])=>{n.push({event:"put-object",data:{kind:"flag",key:r,version:i.version||1,object:i}})}),Object.entries((e==null?void 0:e.segments)||[]).forEach(([r,i])=>{n.push({event:"put-object",data:{kind:"segment",key:r,version:i.version||1,object:i}})}),n.push({event:"payload-transferred",data:{state:this.fe,version:1,id:Qh}}),this.ci.processEvents(n)}}}var pe={type:"none"};function Xp(t,e){let n="inactive",r,i="partial",o=[];function s(g,S){var T;return(T=t[g])==null?void 0:T.call(t,S)}function a(){n="inactive",r=void 0,i="partial",o=[]}function c(){n="changes",i="partial",o=[]}function l(){o=[]}function u(g){return!g.id||!g.target?pe:{type:"payload",payload:{id:g.id,version:g.target,type:"none",updates:[]}}}function h(g){var S;if(!((S=g.payloads)!=null&&S.length))return{type:"error",kind:"MISSING_PAYLOAD",message:"No payload present in server-intent"};let T=g.payloads[0];switch(T==null?void 0:T.intentCode){case"xfer-full":return n="full",o=[],i="full",r=T.id,pe;case"xfer-changes":return n="changes",o=[],i="partial",r=T.id,pe;case"none":return n="changes",o=[],i="partial",r=T.id,u(T);default:return e==null||e.warn(`Unable to process intent code '${T==null?void 0:T.intentCode}'.`),pe}}function p(g){if(n==="inactive"||!r||!g.kind||!g.key||!g.version||!g.object)return pe;let S=s(g.kind,g.object);return S?(o.push({kind:g.kind,key:g.key,version:g.version,object:S}),pe):(e==null||e.warn(`Unable to process object for kind: '${g.kind}'`),pe)}function f(g){return n==="inactive"||!r||!g.kind||!g.key||!g.version||o.push({kind:g.kind,key:g.key,version:g.version,deleted:!0}),pe}function m(g){if(n==="inactive")return{type:"error",kind:"PROTOCOL_ERROR",message:"A payload transferred has been received without an intent having been established."};if(!r||g.state===null||g.state===void 0||!g.version)return a(),pe;let S={type:"payload",payload:{id:r,version:g.version,state:g.state,type:i,updates:o}};return c(),S}function d(g){return e==null||e.info(`Goodbye was received from the LaunchDarkly connection with reason: ${g.reason}.`),a(),{type:"goodbye",reason:g.reason}}function v(g){return e==null||e.info(`An issue was encountered receiving updates for payload ${r} with reason: ${g.reason}.`),l(),{type:"serverError",id:g.payload_id,reason:g.reason}}return{get state(){return n},processEvent(g){switch(g.event){case"server-intent":return h(g.data);case"put-object":return p(g.data);case"delete-object":return f(g.data);case"payload-transferred":return m(g.data);case"goodbye":return d(g.data);case"error":return v(g.data);case"heart-beat":return pe;default:return{type:"error",kind:"UNKNOWN_EVENT",message:`Received an unknown event of type '${g.event}'`}}},reset(){a()}}}function qS(t){return t==="MISSING_PAYLOAD"||t==="PROTOCOL_ERROR"}var Wp=class{constructor(t,e,n){this.g=e,this.t=n,this.n=[],this.li=Xp(t,n)}addPayloadListener(t){this.n.push(t)}removePayloadListener(t){let e=this.n.indexOf(t,0);e>-1&&this.n.splice(e,1)}processEvents(t){t.forEach(e=>{var n,r;let i=this.li.processEvent(e);switch(i.type){case"payload":this.n.forEach(o=>o(i.payload));break;case"error":qS(i.kind)?(n=this.g)==null||n.call(this,At.InvalidData,i.message):(r=this.t)==null||r.warn(i.message);break}})}},tw=class{constructor(t,e,n,r){this.g=n,this.t=r,this.H(t,"server-intent"),this.H(t,"put-object"),this.H(t,"delete-object"),this.H(t,"payload-transferred"),this.H(t,"goodbye"),this.H(t,"error"),this.Ct=new Wp(e,n,r)}addPayloadListener(t){this.Ct.addPayloadListener(t)}removePayloadListener(t){this.Ct.removePayloadListener(t)}H(t,e){t.addEventListener(e,async n=>{var r,i,o,s,a;if(n!=null&&n.data){(r=this.t)==null||r.debug(`Received ${e} event. Data is ${n.data}`);try{this.Ct.processEvents([{event:e,data:JSON.parse(n.data)}])}catch(c){(i=this.t)==null||i.error(`Stream received data that was unable to be processed in "${e}" message`),(o=this.t)==null||o.debug(`Data follows: ${n.data}`),(s=this.g)==null||s.call(this,At.InvalidData,"Malformed data in EventStream.")}}else(a=this.g)==null||a.call(this,At.Unknown,"Event from EventStream missing data.")})}};function ew(t){if(t){let e=Object.keys(t).find(n=>n.toLowerCase()==="x-ld-envid");if(e)return{environmentId:t[e]}}}var $h="unknown plugin";function Yi(t,e){try{return e.getMetadata().name||$h}catch(n){return t.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),$h}}function nw(t,e,n){let r=[];return n.forEach(i=>{var o;try{let s=(o=i.getHooks)==null?void 0:o.call(i,e);s===void 0?t.error(`Plugin ${Yi(t,i)} returned undefined from getHooks.`):s&&s.length>0&&r.push(...s)}catch(s){t.error(`Exception thrown getting hooks for plugin ${Yi(t,i)}. Unable to get hooks.`)}}),r}function rw(t,e,n,r){r.forEach(i=>{try{i.register(n,e)}catch(o){t.error(`Exception thrown registering plugin ${Yi(t,i)}.`)}})}var de=Object.freeze({__proto__:null,ClientMessages:Np,DiagnosticsManager:MS,ErrorKinds:FS,EventFactoryBase:QS,EventProcessor:BS,FDv1PayloadAdaptor:$S,InputCustomEvent:Gp,InputEvalEvent:Pa,InputIdentifyEvent:Lp,NullEventProcessor:jS,PayloadProcessor:Wp,PayloadStreamReader:tw,canonicalize:Mi,createProtocolHandler:Xp,initMetadataFromHeaders:ew,isLegacyUser:wp,isMultiKind:Sp,isSingleKind:vp,safeGetHooks:nw,safeGetName:Yi,safeRegisterPlugins:rw,shouldSample:Ui}),iw={Initializing:"INITIALIZING",Valid:"VALID",Interrupted:"INTERRUPTED",SetOffline:"SET_OFFLINE",Closed:"CLOSED"};function ow(t){return t>=200&&t<=299}var qh=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}};function tp(t,e,n,r,i,o,s,a,c,l){let u,h="GET",p=st({},o);c&&(h="REPORT",p["content-type"]="application/json",u=t);let f=c?n.pathReport(i,t):n.pathGet(i,t),m=[...s!=null?s:[]];a&&m.push({key:"withReasons",value:"true"}),l&&m.push({key:"h",value:l});let d=GS(e,f,m);return{async requestPayload(){let v;try{let g=await r.fetch(d,{method:h,headers:p,body:u});if(ow(g.status))return await g.text();v=g.status}catch(g){throw new qh(g==null?void 0:g.message)}throw new qh(`Unexpected status code: ${v}`,v)}}}var ep=new Error("Task has already been executed or shed. This is likely an implementation error. The task will not be executed again.");function sw(t,e,n=!1){let r,i=new Promise(a=>{r=(c,l)=>{var u;try{(u=t.after)==null||u.call(t,c,l)}catch(h){e==null||e.error(`Error in after callback: ${h}`)}a(c)}}),o=t.before?t.before():Promise.resolve(void 0),s=!1;return{execute:()=>{s&&(e==null||e.error(ep)),s=!0,o.then(a=>{t.execute(a).then(c=>r({status:"complete",result:c},a)).catch(c=>r({status:"error",error:c},a))}).catch(a=>{e==null||e.error(a),r({status:"error",error:a},void 0)})},shed:()=>{s&&(e==null||e.error(ep)),s=!0,o.then(a=>{r({status:"shed"},a)})},promise:i,sheddable:n}}function aw(t){let e,n=[];function r(){if(!e&&n.length>0){let i=n.shift();e=i.promise.finally(()=>{e=void 0,r()}),i.execute()}}return{execute(i,o=!1){var s,a;let c=sw(i,t,o);return e?((s=n[n.length-1])!=null&&s.sheddable&&((a=n.pop())==null||a.shed()),n.push(c)):(e=c.promise.finally(()=>{e=void 0,r()}),c.execute()),c.promise},pendingCount(){return n.length}}}var lw={logger:G.Object,maxCachedContexts:G.numberWithMin(0),baseUri:G.String,streamUri:G.String,eventsUri:G.String,capacity:G.numberWithMin(1),diagnosticRecordingInterval:G.numberWithMin(2),flushInterval:G.numberWithMin(2),streamInitialReconnectDelay:G.numberWithMin(0),allAttributesPrivate:G.Boolean,debug:G.Boolean,diagnosticOptOut:G.Boolean,withReasons:G.Boolean,sendEvents:G.Boolean,pollInterval:G.numberWithMin(30),useReport:G.Boolean,privateAttributes:G.StringArray,applicationInfo:G.Object,wrapperName:G.String,wrapperVersion:G.String,payloadFilterKey:G.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:G.createTypeArray("Hook[]",{}),inspectors:G.createTypeArray("LDInspection",{}),cleanOldPersistentData:G.Boolean},cw=300,Up="https://clientsdk.launchdarkly.com",Pp="https://clientstream.launchdarkly.com";function uw(t){return t instanceof Tp?t:Ep(t)}var hw=class{constructor(t={},e={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var n,r,i;this.logger=Ep(),this.baseUri=Up,this.eventsUri=Ji.DEFAULT_EVENTS,this.streamUri=Pp,this.maxCachedContexts=5,this.capacity=100,this.diagnosticRecordingInterval=900,this.flushInterval=30,this.streamInitialReconnectDelay=1,this.allAttributesPrivate=!1,this.debug=!1,this.diagnosticOptOut=!1,this.sendEvents=!0,this.sendLDHeaders=!0,this.useReport=!1,this.withReasons=!1,this.privateAttributes=[],this.pollInterval=cw,this.hooks=[],this.inspectors=[],this.logger=uw(t.logger),this.ui(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new Ji(this.streamUri,this.baseUri,this.eventsUri,e.analyticsEventPath,e.diagnosticEventPath,e.includeAuthorizationHeader,t.payloadFilterKey),this.useReport=(n=t.useReport)!=null?n:!1,this.tags=new xS({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(r=e.userAgentHeaderName)!=null?r:"user-agent",this.trackEventModifier=(i=e.trackEventModifier)!=null?i:(o=>o),this.credentialType=e.credentialType,this.getImplementationHooks=e.getImplementationHooks}ui(t){let e=[];return Object.entries(t).forEach(([n,r])=>{let i=lw[n];if(i)if(i.is(r))n==="logger"||(this[n]=r!=null?r:void 0);else{let o=i.getType();if(o==="boolean")e.push(Ue.wrongOptionTypeBoolean(n,typeof r)),this[n]=!!r;else if(o==="boolean | undefined | null")e.push(Ue.wrongOptionTypeBoolean(n,typeof r)),typeof r!="boolean"&&typeof r!="undefined"&&r!==null&&(this[n]=!!r);else if(i instanceof gp&&G.Number.is(r)){let{min:s}=i;e.push(Ue.optionBelowMinimum(n,r,s)),this[n]=s}else e.push(Ue.wrongOptionType(n,i.getType(),typeof r))}else e.push(Ue.unknownOption(n))}),e}};async function Mp(t,e){if(t.digest)return t.digest(e);if(t.asyncDigest)return t.asyncDigest(e);throw new Error("Platform must implement digest or asyncDigest")}var Fp=async(t,{crypto:e,storage:n})=>{let r=await(n==null?void 0:n.get(t));return r||(r=e.randomUUID(),await(n==null?void 0:n.set(t,r))),r};function Ap(t){return async e=>Mp(t.createHash("sha256").update(e),"base64")}var fe=async t=>t;async function gr(t){return(await Promise.all(t.map(e=>e.transform(e.value)))).join("_")}async function pw(t,e){return gr([{value:"LaunchDarkly",transform:fe},{value:e,transform:Ap(t)}])}async function dw(t){return gr([{value:"LaunchDarkly",transform:fe},{value:"AnonymousKeys",transform:fe},{value:t,transform:fe}])}async function fw(t){return gr([{value:"LaunchDarkly",transform:fe},{value:"ContextKeys",transform:fe},{value:t,transform:fe}])}async function mw(t){return gr([{value:t,transform:fe},{value:"ContextIndex",transform:fe}])}async function np(t,e,n){return gr([{value:e,transform:fe},{value:n.canonicalKey,transform:Ap(t)}])}var{isLegacyUser:yw,isSingleKind:Va,isMultiKind:rp}=de,Jp="1.0",gw=t=>{let e=t,{kind:n}=e,r=fp(e,["kind"]);return{kind:"multi",[n]:r}},bw=async({crypto:t,info:e},{applicationInfo:n})=>{var r;let{ld_application:i}=e.platformData(),o=(r=Ja(i))!=null?r:{},s=(n==null?void 0:n.id)||(o==null?void 0:o.id);if(s){let a=(n==null?void 0:n.version)||(o==null?void 0:o.version),c=(n==null?void 0:n.name)||(o==null?void 0:o.name),l=(n==null?void 0:n.versionName)||(o==null?void 0:o.versionName);return o=st(st(st(me(st({},o),{id:s}),a?{version:a}:{}),c?{name:c}:{}),l?{versionName:l}:{}),o.key=await Mp(t.createHash("sha256").update(s),"base64"),o.envAttributesVersion=o.envAttributesVersion||Jp,o}},vw=async t=>{var e,n,r,i;let{ld_device:o,os:s}=t.info.platformData(),a=(e=Ja(o))!=null?e:{},c=(s==null?void 0:s.name)||((n=a.os)==null?void 0:n.name),l=(s==null?void 0:s.version)||((r=a.os)==null?void 0:r.version),u=(i=a.os)==null?void 0:i.family;if((c||l||u)&&(a.os=st(st(st({},c?{name:c}:{}),l?{version:l}:{}),u?{family:u}:{})),Object.keys(a).filter(h=>h!=="key"&&h!=="envAttributesVersion").length){let h=await fw("ld_device");return a.key=await Fp(h,t),a.envAttributesVersion=a.envAttributesVersion||Jp,a}},Sw=async(t,e,n)=>{if(yw(t))return t;let r,i;if(Va(t)&&t.kind!=="ld_application"||rp(t)&&!t.ld_application?r=await bw(e,n):n.logger.warn("Not adding ld_application environment attributes because it already exists."),Va(t)&&t.kind!=="ld_device"||rp(t)&&!t.ld_device?i=await vw(e):n.logger.warn("Not adding ld_device environment attributes because it already exists."),r||i){let o=Va(t)?gw(t):t;return st(st(st({},o),r?{ld_application:r}:{}),i?{ld_device:i}:{})}return t};function ww(){let t,e;return{set(n,r){t=n,e=r},getContext(){return e},getUnwrappedContext(){return t},newIdentificationPromise(){let n,r;return{identifyPromise:new Promise((i,o)=>{n=i,r=o}),identifyResolve:n,identifyReject:r}},hasContext(){return e!==void 0},hasValidContext(){return this.hasContext()&&e.valid}}}var{isLegacyUser:Iw,isMultiKind:Tw,isSingleKind:Ew}=de,Da=async(t,e,n)=>{let{anonymous:r,key:i}=e;if(r&&!i){let o=await dw(t);e.key=await Fp(o,n)}},Rw=async(t,e)=>{await Da(t.kind,t,e)},Cw=async(t,e)=>{let n=t,{kind:r}=n,i=fp(n,["kind"]);return Promise.all(Object.entries(i).map(([o,s])=>Da(o,s,e)))},Zw=async(t,e)=>{await Da("user",t,e)},kw=async(t,e)=>{let n=kp(t);return Ew(n)&&await Rw(n,e),Tw(n)&&await Cw(n,e),Iw(n)&&await Zw(n,e),n},Vw=t=>({customBaseURI:t.serviceEndpoints.polling!==Up,customStreamURI:t.serviceEndpoints.streaming!==Pp,customEventsURI:t.serviceEndpoints.events!==Ji.DEFAULT_EVENTS,eventsCapacity:t.capacity,eventsFlushIntervalMillis:ka(t.flushInterval),reconnectTimeMillis:ka(t.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:ka(t.diagnosticRecordingInterval),allAttributesPrivate:t.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),xw=(t,e,n)=>{if(e.sendEvents&&!e.diagnosticOptOut)return new de.DiagnosticsManager(t,n,Vw(e))};function ip(t,e){return{value:e!=null?e:null,variationIndex:null,reason:{kind:"ERROR",errorKind:t}}}function op(t,e,n){return st({value:t,variationIndex:e!=null?e:null},n!==void 0&&{reason:n})}var Nw=(t,e,n,r,i)=>{if(e.sendEvents)return new de.EventProcessor(me(st({},e),{eventsCapacity:e.capacity}),new NS(t,e,n),r,void 0,i,!1,!0)},sp=class extends de.EventFactoryBase{evalEventClient(t,e,n,r,i,o){let{trackEvents:s,debugEventsUntilDate:a,trackReason:c,flagVersion:l,version:u,variation:h}=r;return super.evalEvent({addExperimentData:c,context:i,debugEventsUntilDate:a,defaultVal:n,flagKey:t,reason:o,trackEvents:!!s,value:e,variation:h,version:l!=null?l:u})}},xa=class Dp{constructor(){this.container={index:new Array}}static fromJson(e){let n=new Dp;try{n.container=JSON.parse(e)}catch(r){}return n}toJson(){return JSON.stringify(this.container)}notice(e,n){let r=this.container.index.find(i=>i.id===e);r===void 0?this.container.index.push({id:e,timestamp:n}):r.timestamp=n}prune(e){let n=Math.max(e,0);return this.container.index.length>n?(this.container.index.sort((r,i)=>r.timestamp-i.timestamp),this.container.index.splice(0,this.container.index.length-n)):[]}},Ow=class{constructor(t,e,n,r,i,o,s=()=>Date.now()){this.p=t,this.It=e,this.hi=n,this.P=r,this.w=i,this.t=o,this.di=s,this.pe=mw(this.It)}async init(t,e){this.w.init(t,e),await this.ge(t)}async upsert(t,e,n){return this.w.upsert(t,e,n)?(await this.ge(t),!0):!1}async loadCached(t){var e,n,r,i;let o=await np(this.p.crypto,this.It,t),s=await((e=this.p.storage)==null?void 0:e.get(o));if(s==null){if(s=await((n=this.p.storage)==null?void 0:n.get(t.canonicalKey)),s==null)return!1;await((r=this.p.storage)==null?void 0:r.set(o,s)),await((i=this.p.storage)==null?void 0:i.clear(t.canonicalKey))}try{let a=JSON.parse(s),c=Object.entries(a).reduce((l,[u,h])=>(l[u]={version:h.version,flag:h},l),{});return this.w.initCached(t,c),this.t.debug("Loaded cached flag evaluations from persistent storage"),!0}catch(a){return this.t.warn(`Could not load cached flag evaluations from persistent storage: ${a.message}`),!1}}async fi(){var t;if(this.B!==void 0)return this.B;let e=await((t=this.p.storage)==null?void 0:t.get(await this.pe));if(!e)return this.B=new xa,this.B;try{this.B=xa.fromJson(e),this.t.debug("Loaded context index from persistent storage")}catch(n){this.t.warn(`Could not load index from persistent storage: ${n.message}`),this.B=new xa}return this.B}async ge(t){var e,n;let r=await this.fi(),i=await np(this.p.crypto,this.It,t);r.notice(i,this.di());let o=r.prune(this.hi);await Promise.all(o.map(async l=>{var u;return(u=this.p.storage)==null?void 0:u.clear(l.id)})),await((e=this.p.storage)==null?void 0:e.set(await this.pe,r.toJson()));let s=this.P.getAll(),a=Object.entries(s).reduce((l,[u,h])=>(h.flag!==null&&h.flag!==void 0&&(l[u]=h.flag),l),{}),c=JSON.stringify(a);await((n=this.p.storage)==null?void 0:n.set(i,c))}};function Gw(){let t={};return{init(e){t=Object.entries(e).reduce((n,[r,i])=>(n[r]=i,n),{})},insertOrUpdate(e,n){t[e]=n},get(e){if(Object.prototype.hasOwnProperty.call(t,e))return t[e]},getAll(){return t}}}function Lw(t,e){let n=[];return Object.entries(t).forEach(([r,i])=>{let o=e[r];(!o||!Wi(i,o))&&n.push(r)}),Object.keys(e).forEach(r=>{t[r]||n.push(r)}),n}function Xw(t,e){let n=t,r=e,i,o=new Array;return{handleFlagChanges(s,a){i?o.forEach(c=>{try{c(i,s,a)}catch(l){}}):r.warn("Received a change event without an active context. Changes will not be propagated.")},init(s,a){i=s;let c=n.getAll();n.init(a);let l=Lw(c,a);l.length>0&&this.handleFlagChanges(l,"init")},initCached(s,a){(i==null?void 0:i.canonicalKey)!==s.canonicalKey&&this.init(s,a)},upsert(s,a,c){if((i==null?void 0:i.canonicalKey)!==s.canonicalKey)return r.warn("Received an update for an inactive context."),!1;let l=n.get(a);return l!==void 0&&l.version>=c.version?!1:(n.insertOrUpdate(a,c),this.handleFlagChanges([a],"patch"),!0)},on(s){o.push(s)},off(s){let a=o.indexOf(s);a>-1&&o.splice(a,1)}}}var Ww=class{constructor(t,e,n,r,i=()=>Date.now()){this.P=Gw(),this.w=Xw(this.P,r),this.Ot=this.pi(t,e,n,r,i)}async pi(t,e,n,r,i=()=>Date.now()){let o=await pw(t.crypto,e);return new Ow(t,o,n,this.P,this.w,r,i)}get(t){return this.r&&Object.prototype.hasOwnProperty.call(this.r,t)?this.At(this.r[t]):this.P.get(t)}getAll(){return this.r?st(st({},this.P.getAll()),Object.entries(this.r).reduce((t,[e,n])=>(t[e]=this.At(n),t),{})):this.P.getAll()}presetFlags(t){this.P.init(t)}setBootstrap(t,e){this.w.init(t,e)}async init(t,e){return(await this.Ot).init(t,e)}async upsert(t,e,n){return(await this.Ot).upsert(t,e,n)}async loadCached(t){return(await this.Ot).loadCached(t)}on(t){this.w.on(t)}off(t){this.w.off(t)}At(t){return{flag:{value:t,version:0},version:0}}setOverride(t,e){this.r||(this.r={}),this.r[t]=e,this.w.handleFlagChanges([t],"override")}removeOverride(t){!this.r||!Object.prototype.hasOwnProperty.call(this.r,t)||(delete this.r[t],Object.keys(this.r).length===0&&(this.r=void 0),this.w.handleFlagChanges([t],"override"))}clearAllOverrides(){if(this.r){let t=st({},this.r);this.r=void 0,this.w.handleFlagChanges(Object.keys(t),"override")}}getAllOverrides(){if(!this.r)return{};let t={};return Object.entries(this.r).forEach(([e,n])=>{t[e]=this.At(n)}),t}getDebugOverride(){return{setOverride:this.setOverride.bind(this),removeOverride:this.removeOverride.bind(this),clearAllOverrides:this.clearAllOverrides.bind(this),getAllOverrides:this.getAllOverrides.bind(this)}}},ap="unknown hook",Yp="beforeEvaluation",Kp="afterEvaluation",Uw="afterTrack";function br(t,e,n,r,i){try{return r()}catch(o){return t==null||t.error(`An error was encountered in "${e}" of the "${n}" hook: ${o}`),i}}function vr(t,e){try{return e.getMetadata().name||ap}catch(n){return t.error("Exception thrown getting metadata for hook. Unable to get hook name."),ap}}function Pw(t,e,n){return e.map(r=>br(t,Yp,vr(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeEvaluation)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Mw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];br(t,Kp,vr(t,s),()=>{var c,l;return(l=(c=s==null?void 0:s.afterEvaluation)==null?void 0:c.call(s,n,a,i))!=null?l:{}},{})}}function Fw(t,e,n){return e.map(r=>br(t,Yp,vr(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeIdentify)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Aw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];br(t,Kp,vr(t,s),()=>{var c,l;return(l=(c=s==null?void 0:s.afterIdentify)==null?void 0:c.call(s,n,a,i))!=null?l:{}},{})}}function Jw(t,e,n){for(let r=e.length-1;r>=0;r-=1){let i=e[r];br(t,Uw,vr(t,i),()=>{var o;return(o=i==null?void 0:i.afterTrack)==null?void 0:o.call(i,n)},void 0)}}var Dw=class{constructor(t,e){this.t=t,this.$=[],this.$.push(...e)}withEvaluation(t,e,n,r){if(this.$.length===0)return r();let i=[...this.$],o={flagKey:t,context:e,defaultValue:n},s=Pw(this.t,i,o),a=r();return Mw(this.t,i,o,s,a),a}identify(t,e){let n=[...this.$],r={context:t,timeout:e},i=Fw(this.t,n,r);return o=>{Aw(this.t,n,r,i,o)}}addHook(t){this.$.push(t)}afterTrack(t){if(this.$.length===0)return;let e=[...this.$];Jw(this.t,e,t)}};function Yw(t){return{getMetadata(){return{name:"LaunchDarkly-Inspector-Adapter"}},afterEvaluation:(e,n,r)=>(t.onFlagUsed(e.flagKey,r,e.context),n),afterIdentify(e,n,r){return t.onIdentityChanged(e.context),n}}}function Kw(t,e){return`an inspector: "${e}" of an invalid type (${t}) was configured`}function _w(t,e){return`an inspector: "${e}" of type: "${t}" generated an exception`}function Hw(t,e){let n=!1,r={method:(...i)=>{try{t.method(...i)}catch(o){n||(n=!0,e.warn(_w(r.type,r.name)))}},type:t.type,name:t.name,synchronous:t.synchronous};return r}var _p="flag-used",Hp="flag-details-changed",zp="flag-detail-changed",Bp="client-identity-changed",zw=[_p,Hp,zp,Bp];function Bw(t,e){let n=zw.includes(t.type)&&t.method&&typeof t.method=="function";return n||e.warn(Kw(t.type,t.name)),n}var jw=class{constructor(t,e){this.z=[];let n=t.filter(r=>Bw(r,e));this.z=n.map(r=>Hw(r,e))}hasInspectors(){return this.z.length!==0}onFlagUsed(t,e,n){this.z.forEach(r=>{r.type===_p&&r.method(t,e,n)})}onFlagsChanged(t){this.z.forEach(e=>{e.type===Hp&&e.method(t)})}onFlagChanged(t,e){this.z.forEach(n=>{n.type===zp&&n.method(t,e)})}onIdentityChanged(t){this.z.forEach(e=>{e.type===Bp&&e.method(t)})}},Qw=class{constructor(t){this.t=t,this.n=new Map}on(t,e){var n,r;if(typeof t!="string"){(n=this.t)==null||n.warn("Only string event names are supported.");return}this.n.has(t)?(r=this.n.get(t))==null||r.push(e):this.n.set(t,[e])}off(t,e){let n=this.n.get(t);if(n){if(e){let r=n.filter(i=>i!==e);r.length===0?this.n.delete(t):this.n.set(t,r);return}this.n.delete(t)}}gi(t,e,...n){var r;try{t(...n)}catch(i){(r=this.t)==null||r.error(`Encountered error invoking handler for "${e}", detail: "${i}"`)}}emit(t,...e){let n=this.n.get(t);n==null||n.forEach(r=>this.gi(r,t,...e))}eventNames(){return[...this.n.keys()]}listenerCount(t){var e,n;return(n=(e=this.n.get(t))==null?void 0:e.length)!=null?n:0}};function $w(t,e,n){let r=e.info.sdkData(),i;n.applicationInfo&&(n.applicationInfo.id&&(i=i!=null?i:{},i.id=n.applicationInfo.id),n.applicationInfo.version&&(i=i!=null?i:{},i.version=n.applicationInfo.version),n.applicationInfo.name&&(i=i!=null?i:{},i.name=n.applicationInfo.name),n.applicationInfo.versionName&&(i=i!=null?i:{},i.versionName=n.applicationInfo.versionName));let o={name:r.userAgentBase,version:r.version};r.wrapperName&&(o.wrapperName=r.wrapperName),r.wrapperVersion&&(o.wrapperVersion=r.wrapperVersion);let s={sdk:o,[n.credentialType]:t};return i&&(s.application=i),s}var{ClientMessages:lp,ErrorKinds:cp}=de,qw=5,tI=class{constructor(t,e,n,r,i,o){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.a=ww(),this.Pt=15,this.T=new sp(!1),this.ct=new sp(!0),this.Tt=!1,this.mi=aw(),!t)throw new Error("You must configure the client with a client-side SDK key");if(!n.encoding)throw new Error("Platform must implement Encoding because btoa is required.");this.e=new hw(r,o),this.logger=this.e.logger,this.me=PS(this.sdkKey,this.platform.info,this.e.tags,this.e.serviceEndpoints.includeAuthorizationHeader,this.e.userAgentHeaderName),this.R=new Ww(this.platform,t,this.e.maxCachedContexts,this.e.logger),this.S=xw(t,this.e,n),this.E=Nw(t,this.e,n,this.me,this.S),this.emitter=new Qw,this.emitter.on("error",(a,c)=>{this.logger.error(`error: ${c}, context: ${JSON.stringify(a)}`)}),this.R.on((a,c,l)=>{this.yi(c,l);let u=xn.toLDContext(a);this.emitter.emit("change",u,c),c.forEach(h=>{this.emitter.emit(`change:${h}`,u)})}),this.dataManager=i(this.R,this.e,this.me,this.emitter,this.S);let s=[...this.e.hooks];if(this.environmentMetadata=$w(this.sdkKey,this.platform,this.e),this.e.getImplementationHooks(this.environmentMetadata).forEach(a=>{s.push(a)}),this.M=new Dw(this.logger,s),this.Y=new jw(this.e.inspectors,this.logger),this.Y.hasInspectors()&&this.M.addHook(Yw(this.Y)),r.cleanOldPersistentData&&o!=null&&o.getLegacyStorageKeys&&this.platform.storage)try{this.logger.debug("Cleaning old persistent data."),Promise.all(o.getLegacyStorageKeys().map(a=>{var c;return(c=this.platform.storage)==null?void 0:c.clear(a)})).catch(a=>{this.logger.error(`Error cleaning old persistent data: ${a}`)}).finally(()=>{this.logger.debug("Cleaned old persistent data.")})}catch(a){this.logger.error(`Error cleaning old persistent data: ${a}`)}}allFlags(){return Object.entries(this.R.getAll()).reduce((t,[e,n])=>(n.flag!==null&&n.flag!==void 0&&!n.flag.deleted&&(t[e]=n.flag.value),t),{})}async close(){var t;await this.flush(),(t=this.E)==null||t.close(),this.dataManager.close(),this.logger.debug("Closed event processor and data source.")}async flush(){var t;try{await((t=this.E)==null?void 0:t.flush()),this.logger.debug("Successfully flushed event processor.")}catch(e){return this.logger.error(`Error flushing event processor: ${e}.`),{error:e,result:!1}}return{result:!0}}getContext(){return this.a.hasContext()?kp(this.a.getUnwrappedContext()):void 0}getInternalContext(){return this.a.getContext()}presetFlags(t){this.R.presetFlags(t)}async identify(t,e){let n=await this.identifyResult(t,e);if(n.status==="error")throw n.error;if(n.status==="timeout"){let r=new Zp(`identify timed out after ${n.timeout} seconds.`);throw this.logger.error(r.message),r}}async identifyResult(t,e){var n,r;let i=(n=e==null?void 0:e.timeout)!=null?n:qw,o=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;i>this.Pt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Pt} seconds. We recommend a timeout of less than ${this.Pt} seconds.`);let s=this.mi.execute({before:async()=>{let c=await kw(t,this.platform);this.autoEnvAttributes===Ai.Enabled&&(c=await Sw(c,this.platform,this.e));let l=xn.fromLDContext(c);if(l.valid){let u=this.M.identify(c,e==null?void 0:e.timeout);return{context:c,checkedContext:l,afterIdentify:u}}return{context:c,checkedContext:l}},execute:async c=>{var l;let{context:u,checkedContext:h}=c;if(!h.valid){let d=new Error("Context was unspecified or had no key");return this.emitter.emit("error",u,d),Promise.reject(d)}this.a.set(u,h),(l=this.E)==null||l.sendEvent(this.T.identifyEvent(h));let{identifyPromise:p,identifyResolve:f,identifyReject:m}=this.a.newIdentificationPromise();return this.logger.debug(`Identifying ${JSON.stringify(h)}`),await this.dataManager.identify(f,m,h,e),p},after:async(c,l)=>{var u,h,p;c.status==="complete"?(u=l==null?void 0:l.afterIdentify)==null||u.call(l,{status:"completed"}):c.status==="shed"?(h=l==null?void 0:l.afterIdentify)==null||h.call(l,{status:"shed"}):c.status==="error"&&((p=l==null?void 0:l.afterIdentify)==null||p.call(l,{status:"error"}))}},(r=e==null?void 0:e.sheddable)!=null?r:!1).then(c=>{if(c.status==="error"){let u={status:"error",error:c.error};return this.maybeSetInitializationResult({status:"failed",error:c.error}),u}if(c.status==="shed")return{status:"shed"};let l={status:"completed"};return this.maybeSetInitializationResult({status:"complete"}),l});if(o)return s;let a=new Promise(c=>{setTimeout(()=>{c({status:"timeout",timeout:i})},i*1e3)});return Promise.race([s,a])}maybeSetInitializationResult(t){this.initializeResult===void 0&&(this.initializeResult=t,this.emitter.emit("ready"),t.status==="complete"&&this.emitter.emit("initialized"),this.initResolve&&(this.initResolve(t),this.initResolve=void 0))}waitForInitialization(t){var e;let n=(e=t==null?void 0:t.timeout)!=null?e:5;return this.initializeResult?Promise.resolve(this.initializeResult):this.initializedPromise?this.promiseWithTimeout(this.initializedPromise,n):(this.initializedPromise||(this.initializedPromise=new Promise(r=>{this.initResolve=r})),this.promiseWithTimeout(this.initializedPromise,n))}promiseWithTimeout(t,e){let n=WS(e,"waitForInitialization");return Promise.race([t.then(r=>(n.cancel(),r)),n.promise.then(()=>({status:"complete"})).catch(()=>({status:"timeout"}))]).catch(r=>{var i;return(i=this.logger)==null||i.error(r.message),{status:"failed",error:r}})}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}track(t,e,n){var r,i;if(!this.a.hasValidContext()){this.logger.warn(lp.MissingContextKeyNoEvent);return}n!==void 0&&!G.Number.is(n)&&((r=this.logger)==null||r.warn(lp.invalidMetricValue(typeof n))),(i=this.E)==null||i.sendEvent(this.e.trackEventModifier(this.T.customEvent(t,this.a.getContext(),e,n))),this.M.afterTrack({key:t,context:this.a.getUnwrappedContext(),data:e,metricValue:n})}lt(t,e,n,r){var i,o,s,a,c;let l=this.a.hasContext();l||(i=this.logger)==null||i.warn("Flag evaluation called before client is fully initialized, data from this evaulation could be stale.");let u=this.a.getContext(),h=this.R.get(t);if(h===void 0||h.flag.deleted){let g=e!=null?e:null;return(o=this.logger)==null||o.warn(`Unknown feature flag "${t}"; returning default value ${g}.`),l&&((s=this.E)==null||s.sendEvent(this.T.unknownFlagEvent(t,g,u))),ip(cp.FlagNotFound,e)}let{reason:p,value:f,variation:m,prerequisites:d}=h.flag;if(r){let[g,S]=r(f);if(!g){l&&((a=this.E)==null||a.sendEvent(n.evalEventClient(t,e,e,h.flag,u,p)));let T=new LS(`Wrong type "${S}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.a.getUnwrappedContext(),T),ip(cp.WrongType,e)}}let v=op(f,m,p);return f==null&&(this.logger.debug("Result value is null. Providing default value."),v.value=e),d==null||d.forEach(g=>{this.lt(g,void 0,this.T)}),l&&((c=this.E)==null||c.sendEvent(n.evalEventClient(t,f,e,h.flag,u,p))),v}variation(t,e){let{value:n}=this.M.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.lt(t,e,this.T));return n}variationDetail(t,e){return this.M.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.lt(t,e,this.ct))}G(t,e,n,r){return this.M.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.lt(t,e,n,r))}boolVariation(t,e){return this.G(t,e,this.T,n=>[G.Boolean.is(n),G.Boolean.getType()]).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.G(t,e,this.T,n=>[G.Number.is(n),G.Number.getType()]).value}stringVariation(t,e){return this.G(t,e,this.T,n=>[G.String.is(n),G.String.getType()]).value}boolVariationDetail(t,e){return this.G(t,e,this.ct,n=>[G.Boolean.is(n),G.Boolean.getType()])}numberVariationDetail(t,e){return this.G(t,e,this.ct,n=>[G.Number.is(n),G.Number.getType()])}stringVariationDetail(t,e){return this.G(t,e,this.ct,n=>[G.String.is(n),G.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.M.addHook(t)}setEventSendingEnabled(t,e){var n,r,i,o;this.Tt!==t&&(this.Tt=t,t?(this.logger.debug("Starting event processor"),(n=this.E)==null||n.start()):e?((r=this.logger)==null||r.debug("Flushing event processor before disabling."),this.flush().then(()=>{var s,a;this.Tt||((s=this.logger)==null||s.debug("Stopping event processor."),(a=this.E)==null||a.close())})):((i=this.logger)==null||i.debug("Stopping event processor."),(o=this.E)==null||o.close()))}sendEvent(t){var e;(e=this.E)==null||e.sendEvent(t)}getDebugOverrides(){var t,e;return(e=(t=this.R).getDebugOverride)==null?void 0:e.call(t)}yi(t,e){if(!this.Y.hasInspectors())return;let n={};t.forEach(r=>{let i=this.R.get(r);if(i!=null&&i.flag&&!i.flag.deleted){let{reason:o,value:s,variation:a}=i.flag;n[r]=op(s,a,o)}else n[r]={value:void 0,variationIndex:null}}),e==="init"?this.Y.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([r,i])=>{this.Y.onFlagChanged(r,i)})}};function eI(t,e,n){n.forEach(r=>{var i;try{(i=r.registerDebug)==null||i.call(r,e)}catch(o){t.error(`Exception thrown registering plugin ${de.safeGetName(t,r)}.`)}})}function jp(t,e){let n=Object.keys(e),r="$flagsState",i="$valid",o=e[r];!o&&n.length&&t.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),e[i]===!1&&t.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");let s={};return n.forEach(a=>{if(a!==r&&a!==i){let c;o&&o[a]?c=st({value:e[a]},o[a]):c={value:e[a],version:0},s[a]={version:c.version,flag:c}}}),s}function nI(t,e,n){return{async handlePut(r,i){n.debug(`Got PUT: ${Object.keys(i)}`);let o=Object.entries(i).reduce((s,[a,c])=>(s[a]={version:c.version,flag:c},s),{});await t.init(r,o),e.requestStateUpdate("VALID")},async handlePatch(r,i){n.debug(`Got PATCH ${JSON.stringify(i,null,2)}`),t.upsert(r,i.key,{version:i.version,flag:i})},async handleDelete(r,i){n.debug(`Got DELETE ${JSON.stringify(i,null,2)}`),t.upsert(r,i.key,{version:i.version,flag:me(st({},i),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})},handleStreamingError(r){e.reportError(r.kind,r.message,r.code,r.recoverable)},handlePollingError(r){e.reportError(r.kind,r.message,r.status,r.recoverable)}}}function rI(t,e=()=>Date.now()){let n="CLOSED",r=e(),i;function o(){return{state:n,stateSince:r,lastError:i}}function s(a,c=!1){let l=a==="INTERRUPTED"&&n==="INITIALIZING"?"INITIALIZING":a,u=n!==l;u&&(n=l,r=e()),(u||c)&&t.emit("dataSourceStatus",o())}return{get status(){return o()},requestStateUpdate(a){s(a)},reportError(a,c,l,u=!1){i={kind:a,message:c,statusCode:l,time:e()},s(u?"INTERRUPTED":"CLOSED",!0)}}}function up(t){t==null||t.debug("Poll completed after the processor was closed. Skipping processing.")}var iI=class{constructor(t,e,n,r,i){this.vi=t,this.wi=e,this.Ei=n,this.g=r,this.t=i,this.u=!1}async ye(){var t,e,n,r,i,o,s;if(this.u)return;let a=h=>{var p,f,m;(p=this.t)==null||p.error("Polling received invalid data"),(f=this.t)==null||f.debug(`Invalid JSON follows: ${h}`),(m=this.g)==null||m.call(this,new Fi(At.InvalidData,"Malformed JSON data in polling response"))};(t=this.t)==null||t.debug("Polling LaunchDarkly for feature flag updates");let c=Date.now();try{let h=await this.vi.requestPayload();try{if(this.u){up(this.t);return}let p=JSON.parse(h);try{(e=this.Ei)==null||e.call(this,p)}catch(f){(n=this.t)==null||n.error(`Exception from data handler: ${f}`)}}catch(p){a(h)}}catch(h){if(this.u){up(this.t);return}let p=h;if(p.status!==void 0&&!Ki(p.status)){(r=this.t)==null||r.error(Gn(h,"polling request")),(i=this.g)==null||i.call(this,new Fi(At.ErrorResponse,p.message,p.status));return}(o=this.t)==null||o.error(Gn(h,"polling request","will retry"))}let l=Date.now()-c,u=Math.max(this.wi*1e3-l,0);(s=this.t)==null||s.debug("Elapsed: %d ms, sleeping for %d ms",l,u),this.Nt=setTimeout(()=>{this.ye()},u)}start(){this.ye()}stop(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0),this.u=!0}close(){this.stop()}},oI=(t,e,n,r)=>{n==null||n.error(`Stream received invalid data in "${t}" message`),n==null||n.debug(`Invalid JSON follows: ${e}`),r==null||r(new Xa(At.InvalidData,"Malformed JSON data in event stream"))};function sI(t,e){e==null||e.debug(`Received ${t} event after processor was closed. Skipping processing.`)}function hp(t){t==null||t.debug("Ping completed after processor was closed. Skipping processing.")}var aI=class{constructor(t,e,n,r,i,o,s,a,c){var l;this.Di=t,this.$t=e,this.n=n,this.V=r,this.bi=o,this.S=s,this.g=a,this.t=c,this.u=!1;let u;e.useReport&&!r.getEventSourceCapabilities().customMethod?u=e.paths.pathPing(i,t):u=e.useReport?e.paths.pathReport(i,t):e.paths.pathGet(i,t);let h=[...(l=e.queryParameters)!=null?l:[]];this.$t.withReasons&&h.push({key:"withReasons",value:"true"}),this.V=r,this.ve=st({},e.baseHeaders),this.t=c,this.ki=OS(e.serviceEndpoints,u,h)}we(){this.ut=Date.now()}Rt(t){this.ut&&this.S&&this.S.recordStreamInit(this.ut,!t,Date.now()-this.ut),this.ut=void 0}xi(t){var e,n,r;return Vp(t)?((r=this.t)==null||r.warn(Gn(t,"streaming request","will retry")),this.Rt(!1),this.we(),!0):(this.Rt(!1),(e=this.g)==null||e.call(this,new Xa(At.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error(Gn(t,"streaming request")),!1)}start(){this.we();let t;this.$t.useReport?(this.ve["content-type"]="application/json",t={method:"REPORT",body:this.Di}):t={};let e=this.V.createEventSource(this.ki,me(st({headers:this.ve},t),{errorFilter:n=>this.xi(n),initialRetryDelayMillis:this.$t.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3}));this.Ee=e,e.onclose=()=>{var n;(n=this.t)==null||n.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var n;(n=this.t)==null||n.info("Opened LaunchDarkly stream connection")},e.onretrying=n=>{var r;(r=this.t)==null||r.info(`Will retry stream connection in ${n.delayMillis} milliseconds`)},this.n.forEach(({deserializeData:n,processJson:r},i)=>{e.addEventListener(i,o=>{var s,a;if(this.u){sI(i,this.t);return}if((s=this.t)==null||s.debug(`Received ${i} event`),o!=null&&o.data){this.Rt(!0);let{data:c}=o,l=n(c);if(!l){oI(i,c,this.t,this.g);return}r(l)}else(a=this.g)==null||a.call(this,new Xa(At.InvalidData,"Unexpected payload from event stream"))})}),e.addEventListener("ping",async()=>{var n,r,i,o,s,a,c;(n=this.t)==null||n.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let l=await this.bi.requestPayload();try{if(this.u){hp(this.t);return}let u=JSON.parse(l);try{(r=this.n.get("put"))==null||r.processJson(u)}catch(h){(i=this.t)==null||i.error(`Exception from data handler: ${h}`)}}catch(u){(o=this.t)==null||o.error("Polling after ping received invalid data"),(s=this.t)==null||s.debug(`Invalid JSON follows: ${l}`),(a=this.g)==null||a.call(this,new Fi(At.InvalidData,"Malformed JSON data in ping polling response"))}}catch(l){if(this.u){hp(this.t);return}let u=l;(c=this.g)==null||c.call(this,new Fi(At.ErrorResponse,u.message,u.status))}})}stop(){var t;(t=this.Ee)==null||t.close(),this.Ee=void 0,this.u=!0}close(){this.stop()}},lI=class{constructor(t,e,n,r,i,o,s,a,c){this.platform=t,this.flagManager=e,this.credential=n,this.config=r,this.getPollingPaths=i,this.getStreamingPaths=o,this.baseHeaders=s,this.emitter=a,this.diagnosticsManager=c,this.closed=!1,this.logger=r.logger,this.dataSourceStatusManager=rI(a),this.K=nI(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.Si=t}createPollingProcessor(t,e,n,r,i){let o=new iI(n,this.config.pollInterval,async s=>{await this.K.handlePut(e,s),r==null||r()},s=>{this.emitter.emit("error",t,s),this.K.handlePollingError(s),i==null||i(s)},this.logger);this.updateProcessor=this.De(o,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,r,i){var o;let s=new aI(JSON.stringify(t),{credential:this.credential,serviceEndpoints:this.config.serviceEndpoints,paths:this.getStreamingPaths(),baseHeaders:this.baseHeaders,initialRetryDelayMillis:this.config.streamInitialReconnectDelay*1e3,withReasons:this.config.withReasons,useReport:this.config.useReport,queryParameters:(o=this.Si)==null?void 0:o.queryParameters},this.createStreamListeners(e,r),this.platform.requests,this.platform.encoding,n,this.diagnosticsManager,a=>{this.emitter.emit("error",t,a),this.K.handleStreamingError(a),i==null||i(a)},this.logger);this.updateProcessor=this.De(s,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async r=>{await this.K.handlePut(t,r),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async r=>{this.K.handlePatch(t,r)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async r=>{this.K.handleDelete(t,r)}}),n}De(t,e){return{start:()=>{e.requestStateUpdate("INITIALIZING"),t.start()},stop:()=>{t.stop(),e.requestStateUpdate("CLOSED")},close:()=>{t.close(),e.requestStateUpdate("CLOSED")}}}close(){var t;(t=this.updateProcessor)==null||t.close(),this.closed=!0}};function _i(){return typeof document!==void 0}function Ya(){return typeof window!==void 0}function Qp(t,e,n){return _i()?(document.addEventListener(t,e,n),()=>{document.removeEventListener(t,e,n)}):()=>{}}function $p(t,e,n){return _i()?(window.addEventListener(t,e,n),()=>{window.removeEventListener(t,e,n)}):()=>{}}function yr(){return Ya()?window.location.href:""}function cI(){return Ya()?window.location.search:""}function uI(){return Ya()?window.location.hash:""}function hI(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function pI(){return _i()?document.visibilityState:"visibile"}function dI(t){if(_i())return document.querySelectorAll(t)}var fI="[BrowserDataManager]",mI=class extends lI{constructor(t,e,n,r,i,o,s,a,c,l){super(t,e,n,r,o,s,a,c,l),this.Ui=i,this.Z=void 0,this.Mt=!1,this.Z=i.streaming}L(t,...e){this.logger.debug(`${fI} ${t}`,...e)}async identify(t,e,n,r){if(this.closed){this.L("Identify called after data manager was closed.");return}this.context=n;let i=r;i!=null&&i.hash?this.setConnectionParams({queryParameters:[{key:"h",value:i.hash}]}):this.setConnectionParams(),this.Ft=i==null?void 0:i.hash,i!=null&&i.bootstrap?this.Li(n,i,t):(await this.flagManager.loadCached(n)&&this.L("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Ci(n,t,e)),this.Ut()}async Ii(t){let e=JSON.stringify(xn.toLDContext(t)),n=tp(e,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ft),r=3,i;for(let o=0;o<=r;o+=1)try{return await n.requestPayload()}catch(s){if(!Vp(s))throw s;i=s,o<r&&(this.L(Gn(s,"initial poll request","will retry")),await xp(1e3))}throw i}async Ci(t,e,n){var r,i;try{this.dataSourceStatusManager.requestStateUpdate(iw.Initializing);let o=await this.Ii(t);try{let s=this.createStreamListeners(t,e).get("put");s.processJson(s.deserializeData(o))}catch(s){this.dataSourceStatusManager.reportError(At.InvalidData,(r=s.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(At.NetworkError,(i=o.message)!=null?i:"unexpected network error",o.status),n(o)}}Li(t,e,n){let{bootstrapParsed:r}=e;r||(r=jp(this.logger,e.bootstrap)),this.flagManager.setBootstrap(t,r),this.L("Identify - Initialization completed from bootstrap"),n()}setForcedStreaming(t){this.Z=t,this.Ut()}setAutomaticStreamingState(t){this.Mt=t,this.Ut()}Ut(){let t=this.Z||this.Mt&&this.Z===void 0;this.L(`Updating streaming state. forced(${this.Z}) automatic(${this.Mt})`),t?this.Oi():this.Ai()}Ai(){var t;this.updateProcessor&&this.L("Stopping update processor."),(t=this.updateProcessor)==null||t.close(),this.updateProcessor=void 0}Oi(){if(this.updateProcessor){this.L("Update processor already active. Not changing state.");return}if(!this.context){this.L("Context not set, not starting update processor.");return}this.L("Starting update processor."),this.Pi(this.context)}Pi(t,e,n){var r;let i=xn.toLDContext(t);(r=this.updateProcessor)==null||r.close();let o=JSON.stringify(xn.toLDContext(t)),s=tp(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ft);this.createStreamingProcessor(i,t,s,e,n),this.updateProcessor.start()}};function yI(t){let e=Qp("visibilitychange",()=>{pI()==="hidden"&&t()}),n=$p("pagehide",t);return()=>{e(),n()}}function Na(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function gI(t,e,n,r){let i=((t.kind==="substring"||t.kind==="regex")&&r.includes("/")?e:e.replace(r,"")).replace(n,"");switch(t.kind){case"exact":return new RegExp(`^${Na(t.url)}/?$`).test(e);case"canonical":return new RegExp(`^${Na(t.url)}/?$`).test(i);case"substring":return new RegExp(`.*${Na(t.substring)}.*$`).test(i);case"regex":return new RegExp(t.pattern).test(i);default:return!1}}function bI(t,e){let n=[];return e.forEach(r=>{let i=t.target,{selector:o}=r,s=dI(o);for(;i&&s!=null&&s.length;){for(let a=0;a<s.length;a+=1)if(i===s[a]){n.push(r);break}i=i.parentNode}}),n}var vI=class{constructor(t,e){let n=t.filter(o=>{var s;return(s=o.urls)==null?void 0:s.some(a=>gI(a,yr(),cI(),uI()))}),r=n.filter(o=>o.kind==="pageview"),i=n.filter(o=>o.kind==="click");if(r.forEach(o=>e(o)),i.length){let o=s=>{bI(s,i).forEach(a=>{e(a)})};this.be=Qp("click",o)}}close(){var t;(t=this.be)==null||t.call(this)}},SI=300,wI=class{constructor(t){this.Vt=yr();let e=()=>{let r=yr();r!==this.Vt&&(this.Vt=r,t())};this.jt=setInterval(e,SI);let n=$p("popstate",e);this.ke=()=>{n()}}close(){var t;this.jt&&clearInterval(this.jt),(t=this.ke)==null||t.call(this)}},II=class{constructor(t,e,n,r,i,o=s=>new wI(s)){this.V=e,this.$i=r,this.Ni=i,this.ht=[],this.Se=!1,this.dt=`${n}/sdk/goals/${t}`,this.xe=o(()=>{this.Bt()})}async initialize(){await this.Ti(),this.Bt()}startTracking(){this.Se=!0,this.Bt()}Bt(){var t;this.Se&&((t=this.Ht)==null||t.close(),this.ht&&this.ht.length&&(this.Ht=new vI(this.ht,e=>{this.Ni(yr(),e)})))}async Ti(){try{let t=await this.V.fetch(this.dt);this.ht=await t.json()}catch(t){this.$i(new Cp(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.xe)==null||t.close(),(e=this.Ht)==null||e.close()}};function TI(t){return t.kind==="click"}var EI=2,qp={fetchGoals:!0,eventUrlTransformer:t=>t,streaming:void 0,plugins:[]},RI={fetchGoals:G.Boolean,eventUrlTransformer:G.Function,streaming:G.Boolean,plugins:G.createTypeArray("LDPlugin",{})};function CI(t){var e;let n=st({},t);return(e=n.flushInterval)!=null||(n.flushInterval=EI),n}function ZI(t){let e=CI(t);return Object.keys(qp).forEach(n=>{delete e[n]}),e}function kI(t,e){let n=st({},qp);return Object.entries(RI).forEach(r=>{let[i,o]=r,s=t[i];s!==void 0&&(o.is(s)?n[i]=s:e.warn(Ue.wrongOptionType(i,o.getType(),typeof s)))}),n}var VI=class{constructor(t,e){switch(this.Ri=t,this.Le=[],e){case"sha1":this.zt="SHA-1";break;case"sha256":this.zt="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.Le.join(""),n=new TextEncoder().encode(e),r=await this.Ri.subtle.digest(this.zt,n);switch(t){case"base64":return btoa(String.fromCharCode(...new Uint8Array(r)));case"hex":return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("");default:throw new Error(`Encoding is not supported ${t}`)}}update(t){return this.Le.push(t),this}},xI={start:0,end:3},NI={start:4,end:5},Oa={start:6,end:7},Ga={start:8,end:8},OI={start:9,end:9},GI={start:10,end:15};function LI(){if(crypto&&crypto.getRandomValues){let e=new Uint8Array(16);return crypto.getRandomValues(e),[...e.values()]}let t=[];for(let e=0;e<16;e+=1)t.push(Math.floor(Math.random()*256));return t}function kn(t,e){let n="";for(let r=e.start;r<=e.end;r+=1)n+=t[r].toString(16).padStart(2,"0");return n}function XI(t){return t[Ga.start]=(t[Ga.start]|128)&191,t[Oa.start]=t[Oa.start]&15|64,`${kn(t,xI)}-${kn(t,NI)}-${kn(t,Oa)}-${kn(t,Ga)}${kn(t,OI)}-${kn(t,GI)}`}function WI(){let t=LI();return XI(t)}function UI(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():WI()}var PI=class{createHash(t){return new VI(hI(),t)}randomUUID(){return UI()}};function MI(t){let e=Array.from(t,n=>String.fromCodePoint(n)).join("");return btoa(e)}var FI=class{btoa(t){return MI(new TextEncoder().encode(t))}},AI=class{constructor(t){this.e=t}platformData(){return{name:"JS"}}sdkData(){let t={name:"@launchdarkly/js-client-sdk",version:"4.2.0",userAgentBase:"JSClient"};return this.e.wrapperName&&(t.wrapperName=this.e.wrapperName),this.e.wrapperVersion&&(t.wrapperVersion=this.e.wrapperVersion),t}},JI=class{constructor(t,e){this.dt=t,this.n={},this.I=new wS(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.Ce=e.errorFilter,this.Ie()}Ie(){this._=new EventSource(this.dt),this._.onopen=()=>{var t;this.I.success(),(t=this.onopen)==null||t.call(this)},this._.onerror=t=>{var e;this.Mi(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.n).forEach(([t,e])=>{e.forEach(n=>{var r;(r=this._)==null||r.addEventListener(t,n)})})}addEventListener(t,e){var n,r,i;(r=(n=this.n)[t])!=null||(n[t]=[]),this.n[t].push(e),(i=this._)==null||i.addEventListener(t,e)}close(){var t,e;clearTimeout(this.Gt),this.Gt=void 0,(t=this._)==null||t.close(),(e=this.onclose)==null||e.call(this)}Fi(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.Gt=setTimeout(()=>{this.Ie()},t)}Mi(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.Ce(t))&&this.Fi(this.I.fail())}},DI=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new JI(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function td(){return typeof localStorage!="undefined"}function YI(){if(!td())return[];let t=[];for(let e=0;e<localStorage.length;e+=1){let n=localStorage.key(e);n&&t.push(n)}return t}var KI=class{constructor(t){this.t=t}async clear(t){var e;try{localStorage.removeItem(t)}catch(n){(e=this.t)==null||e.error(`Error clearing key from localStorage: ${t}, reason: ${n}`)}}async get(t){var e;try{let n=localStorage.getItem(t);return n!=null?n:null}catch(n){return(e=this.t)==null||e.error(`Error getting key from localStorage: ${t}, reason: ${n}`),null}}async set(t,e){var n;try{localStorage.setItem(t,e)}catch(r){(n=this.t)==null||n.error(`Error setting key in localStorage: ${t}, reason: ${r}`)}}},_I=class{constructor(t,e){this.encoding=new FI,this.crypto=new PI,this.requests=new DI,td()&&(this.storage=new KI(t)),this.info=new AI(e)}},HI=class extends tI{constructor(t,e,n={},r){var i;let{logger:o,debug:s}=n,a=o!=null?o:new Ma({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:s?"debug":"info"}),c=(i=n.baseUri)!=null?i:"https://clientsdk.launchdarkly.com",l=r!=null?r:new _I(a,n),u=kI(n,a),h=ZI(me(st({},n),{logger:a})),{eventUrlTransformer:p}=u;super(t,e,l,h,(f,m,d,v,g)=>new mI(l,f,t,m,u,()=>({pathGet(S,T){return`/sdk/evalx/${t}/contexts/${jh(T,S)}`},pathReport(S,T){return`/sdk/evalx/${t}/context`},pathPing(S,T){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(S,T){return`/eval/${t}/${jh(T,S)}`},pathReport(S,T){return`/eval/${t}`},pathPing(S,T){return`/ping/${t}`}}),d,v,g),{getLegacyStorageKeys:()=>YI().filter(f=>f.startsWith(`ld:${t}:`)),analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:f=>new de.InputCustomEvent(f.context,f.key,f.data,f.metricValue,f.samplingRatio,p(yr())),getImplementationHooks:f=>de.safeGetHooks(a,f,u.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),this.yo=u.plugins,u.fetchGoals&&(this.Kt=new II(t,l.requests,c,f=>{a.error(f.message)},(f,m)=>{let d=this.getInternalContext();if(!d)return;let v=p(f);TI(m)?this.sendEvent({kind:"click",url:v,samplingRatio:1,key:m.key,creationDate:Date.now(),context:d,selector:m.selector}):this.sendEvent({kind:"pageview",url:v,samplingRatio:1,key:m.key,creationDate:Date.now(),context:d})}),this.Kt.initialize(),u.automaticBackgroundHandling&&yI(()=>this.flush()))}registerPlugins(t){de.safeRegisterPlugins(this.logger,this.environmentMetadata,t,this.yo||[]);let e=this.getDebugOverrides();e&&eI(this.logger,e,this.yo||[])}setInitialContext(t){this.Wt=t}async identify(t,e){return super.identify(t,e)}async identifyResult(t,e){var n;if(!this.X)return this.logger.error("Client must be started before it can identify a context, did you forget to call start()?"),{status:"error",error:new Error("Identify called before start")};let r=st({},e);(e==null?void 0:e.sheddable)===void 0&&(r.sheddable=!0);let i=await super.identifyResult(t,r);return(n=this.Kt)==null||n.startTracking(),i}start(t){var e,n;if(this.initializeResult)return Promise.resolve(this.initializeResult);if(this.X)return this.X;if(!this.Wt)return this.logger.error("Initial context not set"),Promise.resolve({status:"failed",error:new Error("Initial context not set")});let r=me(st({},(e=t==null?void 0:t.identifyOptions)!=null?e:{}),{sheddable:!1});if(t!=null&&t.bootstrap&&!r.bootstrap&&(r.bootstrap=t.bootstrap),r!=null&&r.bootstrap)try{r.bootstrapParsed||(r.bootstrapParsed=jp(this.logger,r.bootstrap)),this.presetFlags(r.bootstrapParsed)}catch(i){this.logger.error("Failed to bootstrap data",i)}return this.initializedPromise||(this.initializedPromise=new Promise(i=>{this.initResolve=i})),this.X=this.promiseWithTimeout(this.initializedPromise,(n=t==null?void 0:t.timeout)!=null?n:5),this.identifyResult(this.Wt,r),this.X}setStreaming(t){this.dataManager.setForcedStreaming(t)}Oe(){let t=this.dataManager,e=this.emitter.eventNames().some(n=>n.startsWith("change:")||n==="change");t.setAutomaticStreamingState(e)}on(t,e){super.on(t,e),this.Oe()}off(t,e){super.off(t,e),this.Oe()}};function zI(t,e,n,r={},i){let o=new HI(t,n,r,i);o.setInitialContext(e);let s={variation:(a,c)=>o.variation(a,c),variationDetail:(a,c)=>o.variationDetail(a,c),boolVariation:(a,c)=>o.boolVariation(a,c),boolVariationDetail:(a,c)=>o.boolVariationDetail(a,c),numberVariation:(a,c)=>o.numberVariation(a,c),numberVariationDetail:(a,c)=>o.numberVariationDetail(a,c),stringVariation:(a,c)=>o.stringVariation(a,c),stringVariationDetail:(a,c)=>o.stringVariationDetail(a,c),jsonVariation:(a,c)=>o.jsonVariation(a,c),jsonVariationDetail:(a,c)=>o.jsonVariationDetail(a,c),track:(a,c,l)=>o.track(a,c,l),on:(a,c)=>o.on(a,c),off:(a,c)=>o.off(a,c),flush:()=>o.flush(),setStreaming:a=>o.setStreaming(a),identify:(a,c)=>o.identifyResult(a,c),getContext:()=>o.getContext(),close:()=>o.close(),allFlags:()=>o.allFlags(),addHook:a=>o.addHook(a),waitForInitialization:a=>o.waitForInitialization(a),logger:o.logger,start:a=>o.start(a)};return o.registerPlugins(s),s}function _F(t){return new Ma(t)}function ed(t,e,n){return zI(t,e,Ai.Disabled,n)}var BI=Object.defineProperty,jI=(t,e,n)=>e in t?BI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Te=(t,e,n)=>jI(t,typeof e!="symbol"?e+"":e,n),QI=(t,e,n)=>new Promise((r,i)=>{var o=c=>{try{a(n.next(c))}catch(l){i(l)}},s=c=>{try{a(n.throw(c))}catch(l){i(l)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(o,s);a((n=n.apply(t,e)).next())}),ke=(t,e,...n)=>{let r=`[@launchdarkly plugins]: (${t}): `;console[e].apply(console,[r,...n]),$I(r,...n)},$I=(t,...e)=>QI(void 0,null,function*(){try{let{LDObserve:n}=yield Promise.resolve().then(()=>rR);n.recordLog(`${t}${e}`,"warn")}catch(n){}}),qI=class{constructor(t,e){Te(this,"debug"),Te(this,"name"),this.debug=t,this.name=e}log(...t){if(this.debug){let e=`[${Date.now()}]`;this.name&&(e+=` - ${this.name}`),console.log.apply(console,[e,...t])}}warn(...t){let e=`[${Date.now()}]`;this.name&&(e+=` - ${this.name}`),console.warn.apply(console,[e,...t])}},vo=class{constructor(){Te(this,"_sdk"),Te(this,"_isLoaded",!1),Te(this,"_callBuffer",[]),Te(this,"_capacity",1e5),Te(this,"_droppedEvents",0),Te(this,"_exceededCapacity",!1),Te(this,"_logger",new qI)}h(e,n){if(this.Nn)try{return this.jn[e](...n)}catch(r){ke(`Error executing buffered call to ${e}:`,"error",r)}else{this.Pr({method:e,args:n});return}}Pr(e){this.wn.length<this.Is?(this.wn.push(e),this.Qn=!1):(this.Qn||(this.Qn=!0,ke("Exceeded event queue capacity. Increase capacity to avoid dropping events.","warn")),this.Ts+=1)}load(e){this.jn=e,this.Nn=!0;for(let{method:n,args:r}of this.wn)try{this.jn[n](...r)}catch(i){ke(`Error executing buffered call to ${n}:`,"error",i)}this.wn=[]}},tT=Object.defineProperty,eT=Object.defineProperties,nT=Object.getOwnPropertyDescriptors,So=Object.getOwnPropertySymbols,Mf=Object.prototype.hasOwnProperty,Ff=Object.prototype.propertyIsEnumerable,Zl=(t,e,n)=>e in t?tT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,j=(t,e)=>{for(var n in e||(e={}))Mf.call(e,n)&&Zl(t,n,e[n]);if(So)for(var n of So(e))Ff.call(e,n)&&Zl(t,n,e[n]);return t},An=(t,e)=>eT(t,nT(e)),xr=(t,e)=>{var n={};for(var r in t)Mf.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&So)for(var r of So(t))e.indexOf(r)<0&&Ff.call(t,r)&&(n[r]=t[r]);return n},Wr=(t,e,n)=>Zl(t,typeof e!="symbol"?e+"":e,n),Dn=(t,e,n)=>new Promise((r,i)=>{var o=c=>{try{a(n.next(c))}catch(l){i(l)}},s=c=>{try{a(n.throw(c))}catch(l){i(l)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(o,s);a((n=n.apply(t,e)).next())});function rT(t,e){for(var n=0;n<e.length;n++){let r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(let i in r)if(i!=="default"&&!(i in t)){let o=Object.getOwnPropertyDescriptor(r,i);o&&Object.defineProperty(t,i,o.get?o:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}function lo(t,e){throw new Error(e)}function iT(t){return typeof t=="object"&&t!==null}function oT(t,e){throw new Error("Unexpected invariant triggered.")}var sT=/\r\n|[\n\r]/g;function kl(t,e){let n=0,r=1;for(let i of t.body.matchAll(sT)){if(typeof i.index=="number"||oT(),i.index>=e)break;n=i.index+i[0].length,r+=1}return{line:r,column:e+1-n}}function aT(t){return Af(t.source,kl(t.source,t.start))}function Af(t,e){let n=t.locationOffset.column-1,r="".padStart(n)+t.body,i=e.line-1,o=t.locationOffset.line-1,s=e.line+o,a=e.line===1?n:0,c=e.column+a,l=`${t.name}:${s}:${c}
|
|
348
|
+
SessionSecureID: ${this.sessionData.sessionSecureID}`);let s=XF();n?yield n({session_secure_id:this.sessionData.sessionSecureID,payload_id:(this.sessionData.payloadID++).toString(),events:{events:r},messages:_L({messages:[]}),resources:JSON.stringify({resources:[]}),web_socket_events:JSON.stringify({webSocketEvents:[]}),errors:[],is_beacon:!1,has_session_unloaded:this.hasSessionUnloaded,highlight_logs:s||void 0}):this.zn.postMessage({message:{type:Ne.AsyncEvents,id:this.sessionData.payloadID++,events:r,messages:[],errors:[],resourcesString:JSON.stringify({resources:[]}),webSocketEventsString:JSON.stringify({webSocketEvents:[]}),hasSessionUnloaded:this.hasSessionUnloaded,highlightLogs:s}}),wn(this.sessionData),this.events=this.events.slice(r.length),WF(s)})}takeFullSnapshot(){if(!this.Sn){this.logger.log("skipping full snapshot as rrweb is not running");return}this.logger.log("taking full snapshot",{bytesSinceSnapshot:this.br,lastSnapshotTime:this.mo}),Ge.takeFullSnapshot(),this.br=0,this.mo=new Date().getTime()}register(e,n){this.xn.push(new hu(e,n))}getHooks(e){return this.xn.flatMap(n=>{var r,i;return(i=(r=n.getHooks)==null?void 0:r.call(n,e))!=null?i:[]})}getRecordingState(){var e;return(e=this==null?void 0:this.state)!=null?e:"NotRecording"}getSession(){let e=this.sessionData.sessionSecureID,n=Zs(e);if(!n)return null;let r=`${this.getFrontendUrl()}/sessions/${e}`;if(!r||!(n!=null&&n.sessionStartTime))return null;let i=new Date().getTime(),o=new URL(r),s=new URL(r),a=(i-this.Bn)/1e3;return s.searchParams.set("ts",a.toString()),{url:o.toString(),urlWithTimestamp:s.toString(),sessionSecureID:e}}getFrontendUrl(){var e,n;let r=this.pn.match(vX);if(r&&(e=r==null?void 0:r.groups)!=null&&e.domain){let i=(n=r.groups.domain)!=null?n:"";return`https://${gX[i]}${bX}`}return yX}},Ci=class extends YX{constructor(e,n){var r=(...f)=>(super(...f),Y(this,"record"),this),i,o,s,a,c,l,u,h,p;try{if(r(n),typeof window>"u"||typeof document>"u"){console.warn("@launchdarkly/session-replay is not initializing because it is not supported in this environment.");return}if(typeof Worker>"u"){console.warn("@launchdarkly/session-replay is not initializing because Worker is not supported.");return}if(!e){console.warn("@launchdarkly/session-replay is not initializing because projectID was passed undefined.");return}let f=Kt(z({},n),{organizationID:e,firstloadVersion:JF,environment:(n==null?void 0:n.environment)||"production",appVersion:n==null?void 0:n.version,sessionSecureID:this.sessionSecureID,privacySetting:(i=n==null?void 0:n.privacySetting)!=null?i:"strict"});this.record=new ih(f),n!=null&&n.manualStart||this.record.start(),In.load(this.record),!((s=(o=n==null?void 0:n.integrations)==null?void 0:o.mixpanel)!=null&&s.disabled)&&(c=(a=n==null?void 0:n.integrations)==null?void 0:a.mixpanel)!=null&&c.projectToken&&FF(n.integrations.mixpanel),!((u=(l=n==null?void 0:n.integrations)==null?void 0:l.amplitude)!=null&&u.disabled)&&(p=(h=n==null?void 0:n.integrations)==null?void 0:h.amplitude)!=null&&p.apiKey&&MF(n.integrations.amplitude)}catch(f){Ht("Error initializing @launchdarkly/session-replay SDK","error",f)}}getMetadata(){return{name:"@launchdarkly/session-replay"}}register(e,n){var r;(r=this.record)==null||r.register(e,n)}getHooks(e){return[{getMetadata:()=>({name:"@launchdarkly/session-replay/hooks"}),afterIdentify:(n,r,i)=>{var o,s,a,c,l,u,h;for(let p of(a=(s=(o=this.record)==null?void 0:o.getHooks)==null?void 0:s.call(o,e))!=null?a:[])(c=p.afterIdentify)==null||c.call(p,n,r,i);if(i.status==="completed"){let p=PX(n.context),f=MX(n.context);(h=this.record)==null||h.identify(typeof f=="string"?f:(u=(l=f.user)==null?void 0:l.toString())!=null?u:p,Kt(z({key:p},typeof f=="object"?f:{}),{timeout:n.timeout}),"LaunchDarkly")}return r},afterEvaluation:(n,r,i)=>{var o,s,a,c;for(let l of(a=(s=(o=this.record)==null?void 0:o.getHooks)==null?void 0:s.call(o,e))!=null?a:[])(c=l.afterEvaluation)==null||c.call(l,n,r,i);return r},afterTrack:n=>{var r,i,o,s,a;for(let c of(o=(i=(r=this.record)==null?void 0:r.getHooks)==null?void 0:i.call(r,e))!=null?o:[])(s=c.afterTrack)==null||s.call(c,n);(a=this.record)==null||a.track(n.key,{data:n.data,value:n.metricValue})}}]}}});var q0=Object.defineProperty,tS=Object.defineProperties,eS=Object.getOwnPropertyDescriptors,Pi=Object.getOwnPropertySymbols,pp=Object.prototype.hasOwnProperty,dp=Object.prototype.propertyIsEnumerable,Dh=(t,e,n)=>e in t?q0(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,st=(t,e)=>{for(var n in e||(e={}))pp.call(e,n)&&Dh(t,n,e[n]);if(Pi)for(var n of Pi(e))dp.call(e,n)&&Dh(t,n,e[n]);return t},me=(t,e)=>tS(t,eS(e)),fp=(t,e)=>{var n={};for(var r in t)pp.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&Pi)for(var r of Pi(t))e.indexOf(r)<0&&dp.call(t,r)&&(n[r]=t[r]);return n};function nS(t){return`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`}function mp(t){return t.indexOf("~")?t.replace(/~1/g,"/").replace(/~0/g,"~"):t}function rS(t){return(t.startsWith("/")?t.substring(1):t).split("/").map(e=>mp(e))}function iS(t){return!t.startsWith("/")}function oS(t){return!t.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var Nn=class{constructor(t,e=!1){if(e){let n=t;this.m=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?nS(n):n}else{if(this.redactionName=t,t===""||t==="/"||!oS(t)){this.isValid=!1,this.m=[];return}iS(t)?this.m=[t]:t.indexOf("/",1)<0?this.m=[mp(t.slice(1))]:this.m=rS(t),this.m[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{m:e,isValid:n}=this;if(!n)return;let r=t;for(let i=0;i<e.length;i+=1){let o=e[i];if(r!=null&&Object.prototype.hasOwnProperty.call(r,o)&&typeof r=="object"&&!Array.isArray(r))r=r[o];else return}return r}getComponent(t){return this.m[t]}get depth(){return this.m.length}get isKind(){return this.m.length===1&&this.m[0]==="kind"}compare(t){return this.depth===t.depth&&this.m.every((e,n)=>e===t.getComponent(n))}get components(){return[...this.m]}};Nn.InvalidReference=new Nn("");var sS=class{is(t){if(Array.isArray(t))return!1;let e=typeof t;return e==="function"||e==="object"}getType(){return"factory method or object"}},Ln=class{constructor(t,e){this.ft=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.ft}},yp=class{constructor(t,e){this.ft=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?t.length>0?t.every(e=>typeof e===this.typeOf):!0:!1}getType(){return this.ft}},gp=class extends Ln{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},bp=class extends Ln{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},aS=class{is(t){return typeof t=="function"}getType(){return"function"}},lS=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},cS=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,uS=class{is(t){return typeof t=="number"||typeof t=="string"&&cS.test(t)}getType(){return"date"}},hS=class extends bp{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},G=class{static createTypeArray(t,e){return new yp(t,e)}static numberWithMin(t){return new gp(t)}static stringMatchingRegex(t){return new bp(t)}};G.String=new Ln("string","");G.Number=new Ln("number",0);G.ObjectOrFactory=new sS;G.Object=new Ln("object",{});G.StringArray=new yp("string[]","");G.Boolean=new Ln("boolean",!0);G.Function=new aS;G.Date=new uS;G.Kind=new hS;G.NullableBoolean=new lS;function vp(t){return"kind"in t?G.String.is(t.kind)&&t.kind!=="multi":!1}function Sp(t){return"kind"in t?G.String.is(t.kind)&&t.kind==="multi":!1}function wp(t){return!("kind"in t)||t.kind===null||t.kind===void 0}function Mi(t,e=[]){if(t===null||typeof t!="object")return JSON.stringify(t);if(e.includes(t))throw new Error("Cycle detected");return Array.isArray(t)?`[${t.map(n=>Mi(n,[...e,t])).map(n=>n===void 0?"null":n).join(",")}]`:`{${Object.keys(t).sort().map(n=>{let r=Mi(t[n],[...e,t]);if(r!==void 0)return`${JSON.stringify(n)}:${r}`}).filter(n=>n!==void 0).join(",")}}`}var La="user";function Yh(t){return t.includes("%")||t.includes(":")?t.replace(/%/g,"%25").replace(/:/g,"%3A"):t}function pS(t){return t&&G.Object.is(t)}function Kh(t){return G.Kind.is(t)}function _h(t){return G.String.is(t)&&t!==""}function Ra(t,e=!1){return t?t.map(n=>new Nn(n,e)):[]}function dS(t){return t!=null}function fS(t){let e=me(st({},t.custom||[]),{kind:"user",key:String(t.key)});if(dS(t.anonymous)){let n=!!t.anonymous;delete e.anonymous,e.anonymous=n}return t.name!==null&&t.name!==void 0&&(e.name=t.name),t.ip!==null&&t.ip!==void 0&&(e.ip=t.ip),t.firstName!==null&&t.firstName!==void 0&&(e.firstName=t.firstName),t.lastName!==null&&t.lastName!==void 0&&(e.lastName=t.lastName),t.email!==null&&t.email!==void 0&&(e.email=t.email),t.avatar!==null&&t.avatar!==void 0&&(e.avatar=t.avatar),t.country!==null&&t.country!==void 0&&(e.country=t.country),t.privateAttributeNames!==null&&t.privateAttributeNames!==void 0&&(e._meta={privateAttributes:t.privateAttributeNames}),e}var xn=class wt{constructor(e,n,r){this.C=!1,this.Q=!1,this.qt=!1,this.N={},this.kind=n,this.valid=e,this.message=r}static b(e,n){return new wt(!1,e,n)}static Ae(e,n){if(!(!n||!e.isValid))return e.depth===1&&e.getComponent(0)==="anonymous"?!!(n!=null&&n.anonymous):e.get(n)}Jt(e){if(this.C)return this.N[e];if(this.kind===e)return this.y}static Pe(e){let n=Object.keys(e).filter(c=>c!=="kind"),r=n.every(Kh);if(!n.length)return wt.b("multi","A multi-kind context must contain at least one kind");if(!r)return wt.b("multi","Context contains invalid kinds");let i={},o=!0,s=n.reduce((c,l)=>{var u;let h=e[l];return pS(h)?(c[l]=h,i[l]=Ra((u=h._meta)==null?void 0:u.privateAttributes)):o=!1,c},{});if(!o)return wt.b("multi","Context contained contexts that were not objects");if(!Object.values(s).every(c=>_h(c.key)))return wt.b("multi","Context contained invalid keys");if(n.length===1){let c=n[0],l=new wt(!0,c);return l.y=me(st({},s[c]),{kind:c}),l.tt=i,l.Q=c==="user",l}let a=new wt(!0,e.kind);return a.N=s,a.tt=i,a.C=!0,a}static Te(e){var n;let{key:r,kind:i}=e,o=Kh(i),s=_h(r);if(!o)return wt.b(i!=null?i:"unknown","The kind was not valid for the context");if(!s)return wt.b(i,"The key for the context was not valid");let a=Ra((n=e._meta)==null?void 0:n.privateAttributes),c=new wt(!0,i);return c.Q=i==="user",c.y=e,c.tt={[i]:a},c}static Ne(e){if(!(e.key!==void 0&&e.key!==null))return wt.b("user","The key for the context was not valid");let n=new wt(!0,"user");return n.Q=!0,n.qt=!0,n.y=fS(e),n.tt={user:Ra(e.privateAttributeNames,!0)},n}static fromLDContext(e){return e?vp(e)?wt.Te(e):Sp(e)?wt.Pe(e):wp(e)?wt.Ne(e):wt.b("unknown","Context was not of a valid kind"):wt.b("unknown","No context specified. Returning default value")}static toLDContext(e){if(!e.valid)return;let n=e.getContexts();if(!e.C)return n[0][1];let r={kind:"multi"};return n.forEach(i=>{let o=i[0],s=i[1];r[o]=s}),r}valueForKind(e,n=La){return e.isKind?this.kinds:wt.Ae(e,this.Jt(n))}key(e=La){var n;return(n=this.Jt(e))==null?void 0:n.key}get isMultiKind(){return this.C}get canonicalKey(){return this.Q?this.y.key:this.C?Object.keys(this.N).sort().map(e=>`${e}:${Yh(this.N[e].key)}`).join(":"):`${this.kind}:${Yh(this.y.key)}`}get kinds(){return this.C?Object.keys(this.N):[this.kind]}get kindsAndKeys(){return this.C?Object.entries(this.N).reduce((e,[n,r])=>(e[n]=r.key,e),{}):{[this.kind]:this.y.key}}privateAttributes(e){var n;return((n=this.tt)==null?void 0:n[e])||[]}getContexts(){return this.C?Object.entries(this.N):[[this.kind,this.y]]}get legacy(){return this.qt}canonicalUnfilteredJson(){if(this.valid){if(this.pt)return this.pt;try{this.pt=Mi(wt.toLDContext(this))}catch(e){}return this.pt}}};xn.UserKind=La;var mS=["key","kind","_meta","anonymous"].map(t=>new Nn(t,!0)),yS=["name","ip","firstName","lastName","email","avatar","country"];function gS(t,e){return t.depth===e.length&&e.every((n,r)=>n===t.getComponent(r))}function bS(t,e){let n=[],r={},i=[];for(n.push(...Object.keys(t).map(o=>({key:o,ptr:[o],source:t,parent:r,visited:[t]})));n.length;){let o=n.pop(),s=e.find(a=>gS(a,o.ptr));if(s)i.push(s.redactionName);else{let a=o.source[o.key];a===null?o.parent[o.key]=a:Array.isArray(a)?o.parent[o.key]=[...a]:typeof a=="object"?o.visited.includes(a)||(o.parent[o.key]={},n.push(...Object.keys(a).map(c=>({key:c,ptr:[...o.ptr,c],source:a,parent:o.parent[o.key],visited:[...o.visited,a]})))):o.parent[o.key]=a}}return{cloned:r,excluded:i.sort()}}var vS=class{constructor(t,e){this.$e=t,this.Re=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.Yt(t,n[0][1],n[0][0],e);let r={kind:"multi"};return n.forEach(([i,o])=>{r[i]=this.Yt(t,o,i,e)}),r}Me(t,e,n,r){return(r?Object.keys(e).map(i=>new Nn(i,!0)):[...this.Re,...t.privateAttributes(n)]).filter(i=>!mS.some(o=>o.compare(i)))}Yt(t,e,n,r){let i=this.$e||r&&e.anonymous===!0,{cloned:o,excluded:s}=bS(e,this.Me(t,e,n,i));return t.legacy&&yS.forEach(a=>{a in o&&(o[a]=String(o[a]))}),s.length&&(o._meta||(o._meta={}),o._meta.redactedAttributes=s),o._meta&&(delete o._meta.privateAttributes,Object.keys(o._meta).length===0&&delete o._meta),o}},Hh=30*1e3,SS=.5,wS=class{constructor(t,e,n=Math.random){this.Fe=e,this.Ue=n,this.gt=0,this.Zt=Math.max(1,t),this.Ve=Math.ceil(Math.log2(Hh/this.Zt))}I(){let t=Math.min(this.gt,this.Ve),e=this.Zt*2**t;return Math.min(e,Hh)}je(t){return t-Math.trunc(this.Ue()*SS*t)}success(t=Date.now()){this.mt=t}fail(t=Date.now()){this.mt!==void 0&&t-this.mt>this.Fe&&(this.gt=0),this.mt=void 0;let e=this.je(this.I());return this.gt+=1,e}},zh;(function(t){t[t.Valid=0]="Valid",t[t.Initializing=1]="Initializing",t[t.Interrupted=2]="Interrupted",t[t.Closed=3]="Closed"})(zh||(zh={}));var Fi=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=r}},Xa=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=r}},YF=120*1e3,KF=300*1e3,At;(function(t){t.Unknown="UNKNOWN",t.NetworkError="NETWORK_ERROR",t.ErrorResponse="ERROR_RESPONSE",t.InvalidData="INVALID_DATA"})(At||(At={}));var Ai;(function(t){t[t.Disabled=0]="Disabled",t[t.Enabled=1]="Enabled"})(Ai||(Ai={}));var On;(function(t){t[t.AnalyticsEvents=0]="AnalyticsEvents",t[t.DiagnosticEvent=1]="DiagnosticEvent"})(On||(On={}));var qe;(function(t){t[t.Succeeded=0]="Succeeded",t[t.Failed=1]="Failed",t[t.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(qe||(qe={}));function Vn(t){if(typeof t=="string")return t;if(t===void 0)return"undefined";if(t===null)return"null";if(Object.prototype.hasOwnProperty.call(t,"toString"))try{return t.toString()}catch(e){}if(typeof t=="bigint")return`${t}n`;try{return JSON.stringify(t)}catch(e){return e instanceof TypeError&&e.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}function IS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(Number(t))}function TS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(parseInt(t,10))}function ES(t){return typeof t=="symbol"?"NaN":String(parseFloat(t))}var Ca={s:t=>Vn(t),d:t=>IS(t),i:t=>TS(t),f:t=>ES(t),j:t=>Vn(t),o:t=>Vn(t),O:t=>Vn(t),c:()=>""};function Wa(...t){var e;let n=t.shift();if(G.String.is(n)){let r="",i=0;for(;i<n.length;){let o=n.charAt(i);if(o==="%"){if(i+1<n.length){let s=n.charAt(i+1);if(s in Ca&&t.length){let a=t.shift();r+=(e=Ca[s])==null?void 0:e.call(Ca,a)}else s==="%"?r+="%":r+=`%${s}`;i+=2}}else r+=o,i+=1}return t.length&&(r.length&&(r+=" "),r+=t.map(Vn).join(" ")),r}return t.map(Vn).join(" ")}var Vt;(function(t){t[t.debug=0]="debug",t[t.info=1]="info",t[t.warn=2]="warn",t[t.error=3]="error",t[t.none=4]="none"})(Vt||(Vt={}));var RS=["debug","info","warn","error","none"],Ma=class Ip{static get(){return new Ip({})}constructor(e){var n,r,i;if(this.qe=(r=Vt[(n=e.level)!=null?n:"info"])!=null?r:Vt.info,this.Je=(i=e.name)!=null?i:"LaunchDarkly",this.ie=e.formatter,typeof e.destination=="object")this.ne={[Vt.debug]:e.destination.debug,[Vt.info]:e.destination.info,[Vt.warn]:e.destination.warn,[Vt.error]:e.destination.error};else if(typeof e.destination=="function"){let{destination:o}=e;this.ne={[Vt.debug]:o,[Vt.info]:o,[Vt.warn]:o,[Vt.error]:o}}}Ye(...e){var n;try{return this.ie?(n=this.ie)==null?void 0:n.call(this,...e):Wa(...e)}catch(r){return Wa(...e)}}Ze(e,n){try{e(n)}catch(r){console.error(n)}}k(e,n){var r;if(e>=this.qe){let i=`${RS[e]}: [${this.Je}]`;try{let o=(r=this.ne)==null?void 0:r[e];o?this.Ze(o,`${i} ${this.Ye(...n)}`):console.error(...n)}catch(o){console.error(...n)}}}error(...e){this.k(Vt.error,e)}warn(...e){this.k(Vt.warn,e)}info(...e){this.k(Vt.info,e)}debug(...e){this.k(Vt.debug,e)}},CS={error:G.Function,warn:G.Function,info:G.Function,debug:G.Function},Tp=class{constructor(t,e){Object.entries(CS).forEach(([n,r])=>{if(!r.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.Xe=e}k(t,e){try{this.t[t](...e)}catch(n){this.Xe[t](...e)}}error(...t){this.k("error",t)}warn(...t){this.k("warn",t)}info(...t){this.k("info",t)}debug(...t){this.k("debug",t)}},Ep=t=>{let e=new Ma({level:"info",destination:console.error,formatter:Wa});return t?new Tp(t,e):e},Ue=class{static deprecated(t,e){return`"${t}" is deprecated, please use "${e}"`}static optionBelowMinimum(t,e,n){return`Config option "${t}" had invalid value of ${e}, using minimum of ${n} instead`}static unknownOption(t){return`Ignoring unknown config option "${t}"`}static wrongOptionType(t,e,n){return`Config option "${t}" should be of type ${e}, got ${n}, using default value`}static wrongOptionTypeBoolean(t,e){return`Config option "${t}" should be a boolean, got ${e}, converting to boolean`}static invalidTagValue(t){return`Config option "${t}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(t){return`Value of "${t}" was longer than 64 characters and was discarded.`}static partialEndpoint(t){return`You have set custom uris without specifying the ${t} URI; connections may not work properly`}},ZS=/^(\w|\.|-)+$/,kS=G.stringMatchingRegex(ZS),VS={is:(t,e)=>kS.is(t)?t.length>64?{valid:!1,message:Ue.tagValueTooLong(e)}:{valid:!0}:{valid:!1,message:Ue.invalidTagValue(e)}},xS=class{constructor(t){let e={},n=t==null?void 0:t.application,r=t==null?void 0:t.logger;n&&Object.entries(n).forEach(([o,s])=>{if(s!=null){let{valid:a,message:c}=VS.is(s,`application.${o}`);a?o==="versionName"?e["application-version-name"]=[s]:e[`application-${o}`]=[s]:r==null||r.warn(c)}});let i=Object.keys(e);i.length&&(this.value=i.sort().flatMap(o=>e[o].sort().map(s=>`${o}/${s}`)).join(" "))}},NS=class{constructor(t,e,n){this.platform=n,this.basicConfiguration={tags:e.tags,logger:e.logger,offline:e.offline,serviceEndpoints:e.serviceEndpoints,sdkKey:t}}};function Za(t){return t.replace(/\/+$/,"")}function Fa(t){return t.replace(/^\/+/,"").replace(/\?$/,"")}var Ji=class Rp{constructor(e,n,r=Rp.DEFAULT_EVENTS,i="/bulk",o="/diagnostic",s=!0,a){this.streaming=Za(e),this.polling=Za(n),this.events=Za(r),this.analyticsEventPath=i,this.diagnosticEventPath=o,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}};Ji.DEFAULT_EVENTS="https://events.launchdarkly.com";function Aa(t,e=[]){if(e.length===0)return t;let n=e.map(({key:r,value:i})=>`${r}=${i}`);return`${t}?${n.join("&")}`}function OS(t,e,n){let r=Fa(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Aa(`${t.streaming}/${r}`,i)}function GS(t,e,n=[]){let r=Fa(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Aa(`${t.polling}/${r}`,i)}function Bh(t,e,n=[]){let r=Fa(e);return Aa(`${t.events}/${r}`,n)}var Cp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},LS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},Zp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function Ki(t){return t>=400&&t<500?t===400||t===408||t===429:!0}function XS(t){return t===413?!0:Ki(t)}function WS(t,e){let n,r;return{promise:new Promise((i,o)=>{r=i,n=setTimeout(()=>{let s=`${e} timed out after ${t} seconds.`;o(new Zp(s))},t*1e3)}),cancel:()=>{r(),clearTimeout(n)}}}function kp(t){return t==null?t:JSON.parse(JSON.stringify(t))}function ka(t){return Math.trunc(t*1e3)}var US=t=>JSON.stringify(t)==="{}",Ja=(t,e)=>t&&Object.entries(t).reduce((n,[r,i])=>(i&&!US(i)&&!(e!=null&&e.includes(r))&&(n[r]=typeof i=="object"?Ja(i,e):i),n),{});function Wi(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(t.constructor!==e.constructor)return!1;var n,r,i;if(Array.isArray(t)){if(n=t.length,n!=e.length)return!1;for(r=n;r--!==0;)if(!Wi(t[r],e[r]))return!1;return!0}if(t instanceof Map&&e instanceof Map){if(t.size!==e.size)return!1;for(r of t.entries())if(!e.has(r[0]))return!1;for(r of t.entries())if(!Wi(r[1],e.get(r[0])))return!1;return!0}if(t instanceof Set&&e instanceof Set){if(t.size!==e.size)return!1;for(r of t.entries())if(!e.has(r[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(e)){if(n=t.length,n!=e.length)return!1;for(r=n;r--!==0;)if(t[r]!==e[r])return!1;return!0}if(t.constructor===RegExp)return t.source===e.source&&t.flags===e.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===e.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===e.toString();if(i=Object.keys(t),n=i.length,n!==Object.keys(e).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(e,i[r]))return!1;for(r=n;r--!==0;){var o=i[r];if(!Wi(t[o],e[o]))return!1}return!0}return t!==t&&e!==e}function PS(t,e,n,r=!0,i="user-agent"){let{userAgentBase:o,version:s,wrapperName:a,wrapperVersion:c}=e.sdkData(),l={[i]:`${o!=null?o:"NodeJSClient"}/${s}`};return r&&(l.authorization=t),a&&(l["x-launchdarkly-wrapper"]=c?`${a}/${c}`:a),n!=null&&n.value&&(l["x-launchdarkly-tags"]=n.value),l}function Gn(t,e,n){let r;t.status?r=`error ${t.status}${t.status===401?" (invalid SDK key)":""}`:r=`I/O error (${t.message||"unknown error"})`;let i=n!=null?n:"giving up permanently";return`Received ${r} for ${e} - ${i}`}function Vp({status:t}){return t?Ki(t):!0}var jh=(t,e)=>e.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),xp=async(t=1e3)=>new Promise(e=>{setTimeout(e,t)}),MS=class{constructor(t,e,n){this.p=e,this.Qe=n,this.wt=[],this.re=Date.now(),this.se=this.re,this.ae={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var t,e,n;let r=this.p.info.sdkData(),i=this.p.info.platformData();return{kind:"diagnostic-init",id:this.ae,creationDate:this.re,sdk:r,configuration:this.Qe,platform:st({name:i.name,osArch:(t=i.os)==null?void 0:t.arch,osName:(e=i.os)==null?void 0:e.name,osVersion:(n=i.os)==null?void 0:n.version},i.additional||{})}}recordStreamInit(t,e,n){let r={timestamp:t,failed:e,durationMillis:n};this.wt.push(r)}createStatsEventAndReset(t,e,n){let r=Date.now(),i={kind:"diagnostic",id:this.ae,creationDate:r,dataSinceDate:this.se,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.wt};return this.wt=[],this.se=r,i}},Ua;(function(t){t.MalformedFlag="MALFORMED_FLAG",t.UserNotSpecified="USER_NOT_SPECIFIED",t.FlagNotFound="FLAG_NOT_FOUND",t.ClientNotReady="CLIENT_NOT_READY",t.WrongType="WRONG_TYPE"})(Ua||(Ua={}));var FS=Ua,Np=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};Np.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var AS=class{constructor(t,e){let{basicConfiguration:n,platform:r}=t,{serviceEndpoints:{analyticsEventPath:i,diagnosticEventPath:o}}=n,{crypto:s,requests:a}=r;this.ti=st({},e),this.oe=Bh(n.serviceEndpoints,i,[]),this.ei=Bh(n.serviceEndpoints,o,[]),this.V=a,this.ii=s}async et(t,e,n,r){let i={status:qe.Succeeded},o=me(st({},this.ti),{"content-type":"application/json"});n&&(o["x-launchdarkly-payload-id"]=n,o["x-launchDarkly-event-schema"]="4");let s;try{let{status:a,headers:c}=await this.V.fetch(e,{headers:o,body:JSON.stringify(t),compressBodyIfPossible:!0,method:"POST",keepalive:!0}),l=Date.parse(c.get("date")||"");if(l&&(i.serverTime=l),a<=204)return i;if(s=new Cp(Gn({status:a,message:"some events were dropped"},"event posting")),!Ki(a))return XS(a)?i.status=qe.Failed:i.status=qe.FailedAndMustShutDown,i.error=s,i}catch(a){s=a}return s&&!r?(i.status=qe.Failed,i.error=s,i):(await xp(),this.et(t,this.oe,n,!1))}async sendEventData(t,e){let n=t===On.AnalyticsEvents?this.ii.randomUUID():void 0,r=t===On.AnalyticsEvents?this.oe:this.ei;return this.et(e,r,n,!0)}};function Di(t){return t.kind==="feature"}function JS(t){return t.kind==="identify"}function DS(t){return t.kind==="migration_op"}var YS=class{constructor(t,e,n,r,i,o){this.count=t,this.key=e,this.value=n,this.version=i,this.variation=o,this.default=r}increment(){this.count+=1}};function KS(t){return`${t.key}:${t.variation!==null&&t.variation!==void 0?t.variation:""}:${t.version!==null&&t.version!==void 0?t.version:""}`}var Op=class{constructor(t=!1,e){this.ni=t,this.x=e,this.W=0,this.it=0,this.nt={},this.rt={}}summarizeEvent(t){if(Di(t)&&!t.excludeFromSummaries){this.y||(this.y=t.context);let e=KS(t),n=this.nt[e],r=this.rt[t.key];r||(r=new Set,this.rt[t.key]=r),t.context.kinds.forEach(i=>r.add(i)),n?n.increment():this.nt[e]=new YS(1,t.key,t.value,t.default,t.version,t.variation),(this.W===0||t.creationDate<this.W)&&(this.W=t.creationDate),t.creationDate>this.it&&(this.it=t.creationDate)}}getSummary(){var t;let e=Object.values(this.nt).reduce((r,i)=>{let o=r[i.key];o||(o={default:i.default,counters:[],contextKinds:[...this.rt[i.key]]},r[i.key]=o);let s={value:i.value,count:i.count};return i.variation!==void 0&&i.variation!==null&&(s.variation=i.variation),i.version!==void 0&&i.version!==null?s.version=i.version:s.unknown=!0,o.counters.push(s),r},{}),n={startDate:this.W,endDate:this.it,features:e,kind:"summary",context:this.y!==void 0&&this.ni?(t=this.x)==null?void 0:t.filter(this.y):void 0};return this.ri(),n}ri(){this.W=0,this.it=0,this.nt={},this.rt={}}},_S=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}},HS=class{constructor(t,e){this.x=t,this.t=e,this.q={}}summarizeEvent(t){var e;if(Di(t)){let n=t.context.canonicalUnfilteredJson();if(!n){t.context.valid&&((e=this.t)==null||e.error("Unable to serialize context, likely the context contains a cycle."));return}let r=this.q[n];r||(this.q[n]=new Op(!0,this.x),r=this.q[n]),r.summarizeEvent(t)}}getSummaries(){let t=this.q;return this.q={},Object.values(t).map(e=>e.getSummary())}};function Ui(t){let e=Math.trunc(t);return e===1?!0:e===0?!1:Math.floor(Math.random()*e)===0}function zS(t){return t.getSummaries!==void 0}var BS=class{constructor(t,e,n,r,i,o=!0,s=!1){this.e=t,this.st=r,this.S=i,this.at=[],this.ce=0,this.Et=0,this.Dt=0,this.bt=!1,this.le=0,this.kt=!1,this.xt=null,this.si=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.ue=new AS(e,n),this.x=new vS(t.allAttributesPrivate,t.privateAttributes.map(a=>new Nn(a))),s?this.J=new HS(this.x,this.t):this.J=new Op,o&&this.start()}start(){var t,e;if(((t=this.st)==null?void 0:t.flushInterval)!==void 0&&(this.xt=setInterval(()=>{var n;(n=this.st)==null||n.flush()},this.st.flushInterval*1e3)),this.ai=setInterval(async()=>{var n;try{await this.flush()}catch(r){(n=this.t)==null||n.debug(`Flush failed: ${r}`)}},this.e.flushInterval*1e3),this.S){let n=this.S.createInitEvent();this.he(n),this.de=setInterval(()=>{let r=this.S.createStatsEventAndReset(this.Et,this.Dt,this.le);this.Et=0,this.Dt=0,this.he(r)},this.e.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}he(t){this.ue.sendEventData(On.DiagnosticEvent,t)}close(){clearInterval(this.ai),this.xt&&clearInterval(this.xt),this.de&&clearInterval(this.de)}async flush(){var t;if(this.kt)throw new _S("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.");let e=this.at;if(this.at=[],zS(this.J))this.J.getSummaries().forEach(n=>{Object.keys(n.features).length&&e.push(n)});else{let n=this.J.getSummary();Object.keys(n.features).length&&e.push(n)}e.length&&(this.le=e.length,(t=this.t)==null||t.debug("Flushing %d events",e.length),await this.et(e))}sendEvent(t){var e;if(this.kt)return;if(DS(t)){if(Ui(t.samplingRatio)){let a=me(st({},t),{context:t.context?this.x.filter(t.context):void 0});a.samplingRatio===1&&delete a.samplingRatio,this.ot(a)}return}this.J.summarizeEvent(t);let n=Di(t),r=n&&t.trackEvents||!n,i=this.oi(t),o=JS(t),s=(e=this.st)==null?void 0:e.processContext(t.context);s||o||(this.Dt+=1),s&&!o&&this.ot(this.St({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),r&&Ui(t.samplingRatio)&&this.ot(this.St(t,!1)),i&&Ui(t.samplingRatio)&&this.ot(this.St(t,!0))}St(t,e){switch(t.kind){case"feature":{let n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.x.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.prereqOf&&(n.prereqOf=t.prereqOf),t.variation!==void 0&&(n.variation=t.variation),t.version!==void 0&&(n.version=t.version),t.reason&&(n.reason=t.reason),n}case"index":case"identify":{let n={kind:t.kind,creationDate:t.creationDate,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),n}case"custom":{let n={kind:"custom",creationDate:t.creationDate,key:t.key,context:this.x.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.data!==void 0&&(n.data=t.data),t.metricValue!==void 0&&(n.metricValue=t.metricValue),t.url!==void 0&&(n.url=t.url),n}case"click":return{kind:"click",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url,selector:t.selector};case"pageview":return{kind:"pageview",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url};default:return t}}ot(t){var e;this.at.length<this.si?(this.at.push(t),this.bt=!1):(this.bt||(this.bt=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.Et+=1)}oi(t){return Di(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.ce&&t.debugEventsUntilDate>Date.now()}async et(t){let e=await this.ue.sendEventData(On.AnalyticsEvents,t);if(e.status===qe.FailedAndMustShutDown&&(this.kt=!0),e.serverTime&&(this.ce=e.serverTime),e.error)throw e.error}},Gp=class{constructor(t,e,n,r,i=1,o){this.context=t,this.key=e,this.data=n,this.metricValue=r,this.samplingRatio=i,this.url=o,this.kind="custom",this.creationDate=Date.now(),this.context=t}},Pa=class{constructor(t,e,n,r,i,o,s,a,c,l,u,h,p=1){this.withReasons=t,this.context=e,this.key=n,this.samplingRatio=p,this.kind="feature",this.creationDate=Date.now(),this.value=r,this.default=i,o!==void 0&&(this.version=o),s!==void 0&&(this.variation=s),a!==void 0&&(this.trackEvents=a),c!==void 0&&(this.prereqOf=c),l!==void 0&&(this.reason=l),u!==void 0&&(this.debugEventsUntilDate=u),h!==void 0&&(this.excludeFromSummaries=h)}},Lp=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},jS=class{close(){}async flush(){}sendEvent(){}},QS=class{constructor(t){this.Lt=t}evalEvent(t){var e;return new Pa(this.Lt,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.Lt||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new Pa(this.Lt,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new Lp(t,1)}customEvent(t,e,n,r,i=1){return new Gp(e,t,n!=null?n:void 0,r!=null?r:void 0,i)}},Qh="FDv1Fallback";function $S(t){return{ci:t,fe:"",useSelector(e){return this.fe=e,this},processFullTransfer(e){let n=[{event:"server-intent",data:{payloads:[{id:Qh,target:1,intentCode:"xfer-full",reason:"payload-missing"}]}}];Object.entries((e==null?void 0:e.flags)||[]).forEach(([r,i])=>{n.push({event:"put-object",data:{kind:"flag",key:r,version:i.version||1,object:i}})}),Object.entries((e==null?void 0:e.segments)||[]).forEach(([r,i])=>{n.push({event:"put-object",data:{kind:"segment",key:r,version:i.version||1,object:i}})}),n.push({event:"payload-transferred",data:{state:this.fe,version:1,id:Qh}}),this.ci.processEvents(n)}}}var pe={type:"none"};function Xp(t,e){let n="inactive",r,i="partial",o=[];function s(g,S){var T;return(T=t[g])==null?void 0:T.call(t,S)}function a(){n="inactive",r=void 0,i="partial",o=[]}function c(){n="changes",i="partial",o=[]}function l(){o=[]}function u(g){return!g.id||!g.target?pe:{type:"payload",payload:{id:g.id,version:g.target,type:"none",updates:[]}}}function h(g){var S;if(!((S=g.payloads)!=null&&S.length))return{type:"error",kind:"MISSING_PAYLOAD",message:"No payload present in server-intent"};let T=g.payloads[0];switch(T==null?void 0:T.intentCode){case"xfer-full":return n="full",o=[],i="full",r=T.id,pe;case"xfer-changes":return n="changes",o=[],i="partial",r=T.id,pe;case"none":return n="changes",o=[],i="partial",r=T.id,u(T);default:return e==null||e.warn(`Unable to process intent code '${T==null?void 0:T.intentCode}'.`),pe}}function p(g){if(n==="inactive"||!r||!g.kind||!g.key||!g.version||!g.object)return pe;let S=s(g.kind,g.object);return S?(o.push({kind:g.kind,key:g.key,version:g.version,object:S}),pe):(e==null||e.warn(`Unable to process object for kind: '${g.kind}'`),pe)}function f(g){return n==="inactive"||!r||!g.kind||!g.key||!g.version||o.push({kind:g.kind,key:g.key,version:g.version,deleted:!0}),pe}function m(g){if(n==="inactive")return{type:"error",kind:"PROTOCOL_ERROR",message:"A payload transferred has been received without an intent having been established."};if(!r||g.state===null||g.state===void 0||!g.version)return a(),pe;let S={type:"payload",payload:{id:r,version:g.version,state:g.state,type:i,updates:o}};return c(),S}function d(g){return e==null||e.info(`Goodbye was received from the LaunchDarkly connection with reason: ${g.reason}.`),a(),{type:"goodbye",reason:g.reason}}function v(g){return e==null||e.info(`An issue was encountered receiving updates for payload ${r} with reason: ${g.reason}.`),l(),{type:"serverError",id:g.payload_id,reason:g.reason}}return{get state(){return n},processEvent(g){switch(g.event){case"server-intent":return h(g.data);case"put-object":return p(g.data);case"delete-object":return f(g.data);case"payload-transferred":return m(g.data);case"goodbye":return d(g.data);case"error":return v(g.data);case"heart-beat":return pe;default:return{type:"error",kind:"UNKNOWN_EVENT",message:`Received an unknown event of type '${g.event}'`}}},reset(){a()}}}function qS(t){return t==="MISSING_PAYLOAD"||t==="PROTOCOL_ERROR"}var Wp=class{constructor(t,e,n){this.g=e,this.t=n,this.n=[],this.li=Xp(t,n)}addPayloadListener(t){this.n.push(t)}removePayloadListener(t){let e=this.n.indexOf(t,0);e>-1&&this.n.splice(e,1)}processEvents(t){t.forEach(e=>{var n,r;let i=this.li.processEvent(e);switch(i.type){case"payload":this.n.forEach(o=>o(i.payload));break;case"error":qS(i.kind)?(n=this.g)==null||n.call(this,At.InvalidData,i.message):(r=this.t)==null||r.warn(i.message);break}})}},tw=class{constructor(t,e,n,r){this.g=n,this.t=r,this.H(t,"server-intent"),this.H(t,"put-object"),this.H(t,"delete-object"),this.H(t,"payload-transferred"),this.H(t,"goodbye"),this.H(t,"error"),this.Ct=new Wp(e,n,r)}addPayloadListener(t){this.Ct.addPayloadListener(t)}removePayloadListener(t){this.Ct.removePayloadListener(t)}H(t,e){t.addEventListener(e,async n=>{var r,i,o,s,a;if(n!=null&&n.data){(r=this.t)==null||r.debug(`Received ${e} event. Data is ${n.data}`);try{this.Ct.processEvents([{event:e,data:JSON.parse(n.data)}])}catch(c){(i=this.t)==null||i.error(`Stream received data that was unable to be processed in "${e}" message`),(o=this.t)==null||o.debug(`Data follows: ${n.data}`),(s=this.g)==null||s.call(this,At.InvalidData,"Malformed data in EventStream.")}}else(a=this.g)==null||a.call(this,At.Unknown,"Event from EventStream missing data.")})}};function ew(t){if(t){let e=Object.keys(t).find(n=>n.toLowerCase()==="x-ld-envid");if(e)return{environmentId:t[e]}}}var $h="unknown plugin";function Yi(t,e){try{return e.getMetadata().name||$h}catch(n){return t.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),$h}}function nw(t,e,n){let r=[];return n.forEach(i=>{var o;try{let s=(o=i.getHooks)==null?void 0:o.call(i,e);s===void 0?t.error(`Plugin ${Yi(t,i)} returned undefined from getHooks.`):s&&s.length>0&&r.push(...s)}catch(s){t.error(`Exception thrown getting hooks for plugin ${Yi(t,i)}. Unable to get hooks.`)}}),r}function rw(t,e,n,r){r.forEach(i=>{try{i.register(n,e)}catch(o){t.error(`Exception thrown registering plugin ${Yi(t,i)}.`)}})}var de=Object.freeze({__proto__:null,ClientMessages:Np,DiagnosticsManager:MS,ErrorKinds:FS,EventFactoryBase:QS,EventProcessor:BS,FDv1PayloadAdaptor:$S,InputCustomEvent:Gp,InputEvalEvent:Pa,InputIdentifyEvent:Lp,NullEventProcessor:jS,PayloadProcessor:Wp,PayloadStreamReader:tw,canonicalize:Mi,createProtocolHandler:Xp,initMetadataFromHeaders:ew,isLegacyUser:wp,isMultiKind:Sp,isSingleKind:vp,safeGetHooks:nw,safeGetName:Yi,safeRegisterPlugins:rw,shouldSample:Ui}),iw={Initializing:"INITIALIZING",Valid:"VALID",Interrupted:"INTERRUPTED",SetOffline:"SET_OFFLINE",Closed:"CLOSED"};function ow(t){return t>=200&&t<=299}var qh=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}};function tp(t,e,n,r,i,o,s,a,c,l){let u,h="GET",p=st({},o);c&&(h="REPORT",p["content-type"]="application/json",u=t);let f=c?n.pathReport(i,t):n.pathGet(i,t),m=[...s!=null?s:[]];a&&m.push({key:"withReasons",value:"true"}),l&&m.push({key:"h",value:l});let d=GS(e,f,m);return{async requestPayload(){let v;try{let g=await r.fetch(d,{method:h,headers:p,body:u});if(ow(g.status))return await g.text();v=g.status}catch(g){throw new qh(g==null?void 0:g.message)}throw new qh(`Unexpected status code: ${v}`,v)}}}var ep=new Error("Task has already been executed or shed. This is likely an implementation error. The task will not be executed again.");function sw(t,e,n=!1){let r,i=new Promise(a=>{r=(c,l)=>{var u;try{(u=t.after)==null||u.call(t,c,l)}catch(h){e==null||e.error(`Error in after callback: ${h}`)}a(c)}}),o=t.before?t.before():Promise.resolve(void 0),s=!1;return{execute:()=>{s&&(e==null||e.error(ep)),s=!0,o.then(a=>{t.execute(a).then(c=>r({status:"complete",result:c},a)).catch(c=>r({status:"error",error:c},a))}).catch(a=>{e==null||e.error(a),r({status:"error",error:a},void 0)})},shed:()=>{s&&(e==null||e.error(ep)),s=!0,o.then(a=>{r({status:"shed"},a)})},promise:i,sheddable:n}}function aw(t){let e,n=[];function r(){if(!e&&n.length>0){let i=n.shift();e=i.promise.finally(()=>{e=void 0,r()}),i.execute()}}return{execute(i,o=!1){var s,a;let c=sw(i,t,o);return e?((s=n[n.length-1])!=null&&s.sheddable&&((a=n.pop())==null||a.shed()),n.push(c)):(e=c.promise.finally(()=>{e=void 0,r()}),c.execute()),c.promise},pendingCount(){return n.length}}}var lw={logger:G.Object,maxCachedContexts:G.numberWithMin(0),baseUri:G.String,streamUri:G.String,eventsUri:G.String,capacity:G.numberWithMin(1),diagnosticRecordingInterval:G.numberWithMin(2),flushInterval:G.numberWithMin(2),streamInitialReconnectDelay:G.numberWithMin(0),allAttributesPrivate:G.Boolean,debug:G.Boolean,diagnosticOptOut:G.Boolean,withReasons:G.Boolean,sendEvents:G.Boolean,pollInterval:G.numberWithMin(30),useReport:G.Boolean,privateAttributes:G.StringArray,applicationInfo:G.Object,wrapperName:G.String,wrapperVersion:G.String,payloadFilterKey:G.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:G.createTypeArray("Hook[]",{}),inspectors:G.createTypeArray("LDInspection",{}),cleanOldPersistentData:G.Boolean},cw=300,Up="https://clientsdk.launchdarkly.com",Pp="https://clientstream.launchdarkly.com";function uw(t){return t instanceof Tp?t:Ep(t)}var hw=class{constructor(t={},e={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var n,r,i;this.logger=Ep(),this.baseUri=Up,this.eventsUri=Ji.DEFAULT_EVENTS,this.streamUri=Pp,this.maxCachedContexts=5,this.capacity=100,this.diagnosticRecordingInterval=900,this.flushInterval=30,this.streamInitialReconnectDelay=1,this.allAttributesPrivate=!1,this.debug=!1,this.diagnosticOptOut=!1,this.sendEvents=!0,this.sendLDHeaders=!0,this.useReport=!1,this.withReasons=!1,this.privateAttributes=[],this.pollInterval=cw,this.hooks=[],this.inspectors=[],this.logger=uw(t.logger),this.ui(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new Ji(this.streamUri,this.baseUri,this.eventsUri,e.analyticsEventPath,e.diagnosticEventPath,e.includeAuthorizationHeader,t.payloadFilterKey),this.useReport=(n=t.useReport)!=null?n:!1,this.tags=new xS({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(r=e.userAgentHeaderName)!=null?r:"user-agent",this.trackEventModifier=(i=e.trackEventModifier)!=null?i:(o=>o),this.credentialType=e.credentialType,this.getImplementationHooks=e.getImplementationHooks}ui(t){let e=[];return Object.entries(t).forEach(([n,r])=>{let i=lw[n];if(i)if(i.is(r))n==="logger"||(this[n]=r!=null?r:void 0);else{let o=i.getType();if(o==="boolean")e.push(Ue.wrongOptionTypeBoolean(n,typeof r)),this[n]=!!r;else if(o==="boolean | undefined | null")e.push(Ue.wrongOptionTypeBoolean(n,typeof r)),typeof r!="boolean"&&typeof r!="undefined"&&r!==null&&(this[n]=!!r);else if(i instanceof gp&&G.Number.is(r)){let{min:s}=i;e.push(Ue.optionBelowMinimum(n,r,s)),this[n]=s}else e.push(Ue.wrongOptionType(n,i.getType(),typeof r))}else e.push(Ue.unknownOption(n))}),e}};async function Mp(t,e){if(t.digest)return t.digest(e);if(t.asyncDigest)return t.asyncDigest(e);throw new Error("Platform must implement digest or asyncDigest")}var Fp=async(t,{crypto:e,storage:n})=>{let r=await(n==null?void 0:n.get(t));return r||(r=e.randomUUID(),await(n==null?void 0:n.set(t,r))),r};function Ap(t){return async e=>Mp(t.createHash("sha256").update(e),"base64")}var fe=async t=>t;async function gr(t){return(await Promise.all(t.map(e=>e.transform(e.value)))).join("_")}async function pw(t,e){return gr([{value:"LaunchDarkly",transform:fe},{value:e,transform:Ap(t)}])}async function dw(t){return gr([{value:"LaunchDarkly",transform:fe},{value:"AnonymousKeys",transform:fe},{value:t,transform:fe}])}async function fw(t){return gr([{value:"LaunchDarkly",transform:fe},{value:"ContextKeys",transform:fe},{value:t,transform:fe}])}async function mw(t){return gr([{value:t,transform:fe},{value:"ContextIndex",transform:fe}])}async function np(t,e,n){return gr([{value:e,transform:fe},{value:n.canonicalKey,transform:Ap(t)}])}var{isLegacyUser:yw,isSingleKind:Va,isMultiKind:rp}=de,Jp="1.0",gw=t=>{let e=t,{kind:n}=e,r=fp(e,["kind"]);return{kind:"multi",[n]:r}},bw=async({crypto:t,info:e},{applicationInfo:n})=>{var r;let{ld_application:i}=e.platformData(),o=(r=Ja(i))!=null?r:{},s=(n==null?void 0:n.id)||(o==null?void 0:o.id);if(s){let a=(n==null?void 0:n.version)||(o==null?void 0:o.version),c=(n==null?void 0:n.name)||(o==null?void 0:o.name),l=(n==null?void 0:n.versionName)||(o==null?void 0:o.versionName);return o=st(st(st(me(st({},o),{id:s}),a?{version:a}:{}),c?{name:c}:{}),l?{versionName:l}:{}),o.key=await Mp(t.createHash("sha256").update(s),"base64"),o.envAttributesVersion=o.envAttributesVersion||Jp,o}},vw=async t=>{var e,n,r,i;let{ld_device:o,os:s}=t.info.platformData(),a=(e=Ja(o))!=null?e:{},c=(s==null?void 0:s.name)||((n=a.os)==null?void 0:n.name),l=(s==null?void 0:s.version)||((r=a.os)==null?void 0:r.version),u=(i=a.os)==null?void 0:i.family;if((c||l||u)&&(a.os=st(st(st({},c?{name:c}:{}),l?{version:l}:{}),u?{family:u}:{})),Object.keys(a).filter(h=>h!=="key"&&h!=="envAttributesVersion").length){let h=await fw("ld_device");return a.key=await Fp(h,t),a.envAttributesVersion=a.envAttributesVersion||Jp,a}},Sw=async(t,e,n)=>{if(yw(t))return t;let r,i;if(Va(t)&&t.kind!=="ld_application"||rp(t)&&!t.ld_application?r=await bw(e,n):n.logger.warn("Not adding ld_application environment attributes because it already exists."),Va(t)&&t.kind!=="ld_device"||rp(t)&&!t.ld_device?i=await vw(e):n.logger.warn("Not adding ld_device environment attributes because it already exists."),r||i){let o=Va(t)?gw(t):t;return st(st(st({},o),r?{ld_application:r}:{}),i?{ld_device:i}:{})}return t};function ww(){let t,e;return{set(n,r){t=n,e=r},getContext(){return e},getUnwrappedContext(){return t},newIdentificationPromise(){let n,r;return{identifyPromise:new Promise((i,o)=>{n=i,r=o}),identifyResolve:n,identifyReject:r}},hasContext(){return e!==void 0},hasValidContext(){return this.hasContext()&&e.valid}}}var{isLegacyUser:Iw,isMultiKind:Tw,isSingleKind:Ew}=de,Da=async(t,e,n)=>{let{anonymous:r,key:i}=e;if(r&&!i){let o=await dw(t);e.key=await Fp(o,n)}},Rw=async(t,e)=>{await Da(t.kind,t,e)},Cw=async(t,e)=>{let n=t,{kind:r}=n,i=fp(n,["kind"]);return Promise.all(Object.entries(i).map(([o,s])=>Da(o,s,e)))},Zw=async(t,e)=>{await Da("user",t,e)},kw=async(t,e)=>{let n=kp(t);return Ew(n)&&await Rw(n,e),Tw(n)&&await Cw(n,e),Iw(n)&&await Zw(n,e),n},Vw=t=>({customBaseURI:t.serviceEndpoints.polling!==Up,customStreamURI:t.serviceEndpoints.streaming!==Pp,customEventsURI:t.serviceEndpoints.events!==Ji.DEFAULT_EVENTS,eventsCapacity:t.capacity,eventsFlushIntervalMillis:ka(t.flushInterval),reconnectTimeMillis:ka(t.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:ka(t.diagnosticRecordingInterval),allAttributesPrivate:t.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),xw=(t,e,n)=>{if(e.sendEvents&&!e.diagnosticOptOut)return new de.DiagnosticsManager(t,n,Vw(e))};function ip(t,e){return{value:e!=null?e:null,variationIndex:null,reason:{kind:"ERROR",errorKind:t}}}function op(t,e,n){return st({value:t,variationIndex:e!=null?e:null},n!==void 0&&{reason:n})}var Nw=(t,e,n,r,i)=>{if(e.sendEvents)return new de.EventProcessor(me(st({},e),{eventsCapacity:e.capacity}),new NS(t,e,n),r,void 0,i,!1,!0)},sp=class extends de.EventFactoryBase{evalEventClient(t,e,n,r,i,o){let{trackEvents:s,debugEventsUntilDate:a,trackReason:c,flagVersion:l,version:u,variation:h}=r;return super.evalEvent({addExperimentData:c,context:i,debugEventsUntilDate:a,defaultVal:n,flagKey:t,reason:o,trackEvents:!!s,value:e,variation:h,version:l!=null?l:u})}},xa=class Dp{constructor(){this.container={index:new Array}}static fromJson(e){let n=new Dp;try{n.container=JSON.parse(e)}catch(r){}return n}toJson(){return JSON.stringify(this.container)}notice(e,n){let r=this.container.index.find(i=>i.id===e);r===void 0?this.container.index.push({id:e,timestamp:n}):r.timestamp=n}prune(e){let n=Math.max(e,0);return this.container.index.length>n?(this.container.index.sort((r,i)=>r.timestamp-i.timestamp),this.container.index.splice(0,this.container.index.length-n)):[]}},Ow=class{constructor(t,e,n,r,i,o,s=()=>Date.now()){this.p=t,this.It=e,this.hi=n,this.P=r,this.w=i,this.t=o,this.di=s,this.pe=mw(this.It)}async init(t,e){this.w.init(t,e),await this.ge(t)}async upsert(t,e,n){return this.w.upsert(t,e,n)?(await this.ge(t),!0):!1}async loadCached(t){var e,n,r,i;let o=await np(this.p.crypto,this.It,t),s=await((e=this.p.storage)==null?void 0:e.get(o));if(s==null){if(s=await((n=this.p.storage)==null?void 0:n.get(t.canonicalKey)),s==null)return!1;await((r=this.p.storage)==null?void 0:r.set(o,s)),await((i=this.p.storage)==null?void 0:i.clear(t.canonicalKey))}try{let a=JSON.parse(s),c=Object.entries(a).reduce((l,[u,h])=>(l[u]={version:h.version,flag:h},l),{});return this.w.initCached(t,c),this.t.debug("Loaded cached flag evaluations from persistent storage"),!0}catch(a){return this.t.warn(`Could not load cached flag evaluations from persistent storage: ${a.message}`),!1}}async fi(){var t;if(this.B!==void 0)return this.B;let e=await((t=this.p.storage)==null?void 0:t.get(await this.pe));if(!e)return this.B=new xa,this.B;try{this.B=xa.fromJson(e),this.t.debug("Loaded context index from persistent storage")}catch(n){this.t.warn(`Could not load index from persistent storage: ${n.message}`),this.B=new xa}return this.B}async ge(t){var e,n;let r=await this.fi(),i=await np(this.p.crypto,this.It,t);r.notice(i,this.di());let o=r.prune(this.hi);await Promise.all(o.map(async l=>{var u;return(u=this.p.storage)==null?void 0:u.clear(l.id)})),await((e=this.p.storage)==null?void 0:e.set(await this.pe,r.toJson()));let s=this.P.getAll(),a=Object.entries(s).reduce((l,[u,h])=>(h.flag!==null&&h.flag!==void 0&&(l[u]=h.flag),l),{}),c=JSON.stringify(a);await((n=this.p.storage)==null?void 0:n.set(i,c))}};function Gw(){let t={};return{init(e){t=Object.entries(e).reduce((n,[r,i])=>(n[r]=i,n),{})},insertOrUpdate(e,n){t[e]=n},get(e){if(Object.prototype.hasOwnProperty.call(t,e))return t[e]},getAll(){return t}}}function Lw(t,e){let n=[];return Object.entries(t).forEach(([r,i])=>{let o=e[r];(!o||!Wi(i,o))&&n.push(r)}),Object.keys(e).forEach(r=>{t[r]||n.push(r)}),n}function Xw(t,e){let n=t,r=e,i,o=new Array;return{handleFlagChanges(s,a){i?o.forEach(c=>{try{c(i,s,a)}catch(l){}}):r.warn("Received a change event without an active context. Changes will not be propagated.")},init(s,a){i=s;let c=n.getAll();n.init(a);let l=Lw(c,a);l.length>0&&this.handleFlagChanges(l,"init")},initCached(s,a){(i==null?void 0:i.canonicalKey)!==s.canonicalKey&&this.init(s,a)},upsert(s,a,c){if((i==null?void 0:i.canonicalKey)!==s.canonicalKey)return r.warn("Received an update for an inactive context."),!1;let l=n.get(a);return l!==void 0&&l.version>=c.version?!1:(n.insertOrUpdate(a,c),this.handleFlagChanges([a],"patch"),!0)},on(s){o.push(s)},off(s){let a=o.indexOf(s);a>-1&&o.splice(a,1)}}}var Ww=class{constructor(t,e,n,r,i=()=>Date.now()){this.P=Gw(),this.w=Xw(this.P,r),this.Ot=this.pi(t,e,n,r,i)}async pi(t,e,n,r,i=()=>Date.now()){let o=await pw(t.crypto,e);return new Ow(t,o,n,this.P,this.w,r,i)}get(t){return this.r&&Object.prototype.hasOwnProperty.call(this.r,t)?this.At(this.r[t]):this.P.get(t)}getAll(){return this.r?st(st({},this.P.getAll()),Object.entries(this.r).reduce((t,[e,n])=>(t[e]=this.At(n),t),{})):this.P.getAll()}presetFlags(t){this.P.init(t)}setBootstrap(t,e){this.w.init(t,e)}async init(t,e){return(await this.Ot).init(t,e)}async upsert(t,e,n){return(await this.Ot).upsert(t,e,n)}async loadCached(t){return(await this.Ot).loadCached(t)}on(t){this.w.on(t)}off(t){this.w.off(t)}At(t){return{flag:{value:t,version:0},version:0}}setOverride(t,e){this.r||(this.r={}),this.r[t]=e,this.w.handleFlagChanges([t],"override")}removeOverride(t){!this.r||!Object.prototype.hasOwnProperty.call(this.r,t)||(delete this.r[t],Object.keys(this.r).length===0&&(this.r=void 0),this.w.handleFlagChanges([t],"override"))}clearAllOverrides(){if(this.r){let t=st({},this.r);this.r=void 0,this.w.handleFlagChanges(Object.keys(t),"override")}}getAllOverrides(){if(!this.r)return{};let t={};return Object.entries(this.r).forEach(([e,n])=>{t[e]=this.At(n)}),t}getDebugOverride(){return{setOverride:this.setOverride.bind(this),removeOverride:this.removeOverride.bind(this),clearAllOverrides:this.clearAllOverrides.bind(this),getAllOverrides:this.getAllOverrides.bind(this)}}},ap="unknown hook",Yp="beforeEvaluation",Kp="afterEvaluation",Uw="afterTrack";function br(t,e,n,r,i){try{return r()}catch(o){return t==null||t.error(`An error was encountered in "${e}" of the "${n}" hook: ${o}`),i}}function vr(t,e){try{return e.getMetadata().name||ap}catch(n){return t.error("Exception thrown getting metadata for hook. Unable to get hook name."),ap}}function Pw(t,e,n){return e.map(r=>br(t,Yp,vr(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeEvaluation)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Mw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];br(t,Kp,vr(t,s),()=>{var c,l;return(l=(c=s==null?void 0:s.afterEvaluation)==null?void 0:c.call(s,n,a,i))!=null?l:{}},{})}}function Fw(t,e,n){return e.map(r=>br(t,Yp,vr(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeIdentify)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Aw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];br(t,Kp,vr(t,s),()=>{var c,l;return(l=(c=s==null?void 0:s.afterIdentify)==null?void 0:c.call(s,n,a,i))!=null?l:{}},{})}}function Jw(t,e,n){for(let r=e.length-1;r>=0;r-=1){let i=e[r];br(t,Uw,vr(t,i),()=>{var o;return(o=i==null?void 0:i.afterTrack)==null?void 0:o.call(i,n)},void 0)}}var Dw=class{constructor(t,e){this.t=t,this.$=[],this.$.push(...e)}withEvaluation(t,e,n,r){if(this.$.length===0)return r();let i=[...this.$],o={flagKey:t,context:e,defaultValue:n},s=Pw(this.t,i,o),a=r();return Mw(this.t,i,o,s,a),a}identify(t,e){let n=[...this.$],r={context:t,timeout:e},i=Fw(this.t,n,r);return o=>{Aw(this.t,n,r,i,o)}}addHook(t){this.$.push(t)}afterTrack(t){if(this.$.length===0)return;let e=[...this.$];Jw(this.t,e,t)}};function Yw(t){return{getMetadata(){return{name:"LaunchDarkly-Inspector-Adapter"}},afterEvaluation:(e,n,r)=>(t.onFlagUsed(e.flagKey,r,e.context),n),afterIdentify(e,n,r){return t.onIdentityChanged(e.context),n}}}function Kw(t,e){return`an inspector: "${e}" of an invalid type (${t}) was configured`}function _w(t,e){return`an inspector: "${e}" of type: "${t}" generated an exception`}function Hw(t,e){let n=!1,r={method:(...i)=>{try{t.method(...i)}catch(o){n||(n=!0,e.warn(_w(r.type,r.name)))}},type:t.type,name:t.name,synchronous:t.synchronous};return r}var _p="flag-used",Hp="flag-details-changed",zp="flag-detail-changed",Bp="client-identity-changed",zw=[_p,Hp,zp,Bp];function Bw(t,e){let n=zw.includes(t.type)&&t.method&&typeof t.method=="function";return n||e.warn(Kw(t.type,t.name)),n}var jw=class{constructor(t,e){this.z=[];let n=t.filter(r=>Bw(r,e));this.z=n.map(r=>Hw(r,e))}hasInspectors(){return this.z.length!==0}onFlagUsed(t,e,n){this.z.forEach(r=>{r.type===_p&&r.method(t,e,n)})}onFlagsChanged(t){this.z.forEach(e=>{e.type===Hp&&e.method(t)})}onFlagChanged(t,e){this.z.forEach(n=>{n.type===zp&&n.method(t,e)})}onIdentityChanged(t){this.z.forEach(e=>{e.type===Bp&&e.method(t)})}},Qw=class{constructor(t){this.t=t,this.n=new Map}on(t,e){var n,r;if(typeof t!="string"){(n=this.t)==null||n.warn("Only string event names are supported.");return}this.n.has(t)?(r=this.n.get(t))==null||r.push(e):this.n.set(t,[e])}off(t,e){let n=this.n.get(t);if(n){if(e){let r=n.filter(i=>i!==e);r.length===0?this.n.delete(t):this.n.set(t,r);return}this.n.delete(t)}}gi(t,e,...n){var r;try{t(...n)}catch(i){(r=this.t)==null||r.error(`Encountered error invoking handler for "${e}", detail: "${i}"`)}}emit(t,...e){let n=this.n.get(t);n==null||n.forEach(r=>this.gi(r,t,...e))}eventNames(){return[...this.n.keys()]}listenerCount(t){var e,n;return(n=(e=this.n.get(t))==null?void 0:e.length)!=null?n:0}};function $w(t,e,n){let r=e.info.sdkData(),i;n.applicationInfo&&(n.applicationInfo.id&&(i=i!=null?i:{},i.id=n.applicationInfo.id),n.applicationInfo.version&&(i=i!=null?i:{},i.version=n.applicationInfo.version),n.applicationInfo.name&&(i=i!=null?i:{},i.name=n.applicationInfo.name),n.applicationInfo.versionName&&(i=i!=null?i:{},i.versionName=n.applicationInfo.versionName));let o={name:r.userAgentBase,version:r.version};r.wrapperName&&(o.wrapperName=r.wrapperName),r.wrapperVersion&&(o.wrapperVersion=r.wrapperVersion);let s={sdk:o,[n.credentialType]:t};return i&&(s.application=i),s}var{ClientMessages:lp,ErrorKinds:cp}=de,qw=5,tI=class{constructor(t,e,n,r,i,o){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.a=ww(),this.Pt=15,this.T=new sp(!1),this.ct=new sp(!0),this.Tt=!1,this.mi=aw(),!t)throw new Error("You must configure the client with a client-side SDK key");if(!n.encoding)throw new Error("Platform must implement Encoding because btoa is required.");this.e=new hw(r,o),this.logger=this.e.logger,this.me=PS(this.sdkKey,this.platform.info,this.e.tags,this.e.serviceEndpoints.includeAuthorizationHeader,this.e.userAgentHeaderName),this.R=new Ww(this.platform,t,this.e.maxCachedContexts,this.e.logger),this.S=xw(t,this.e,n),this.E=Nw(t,this.e,n,this.me,this.S),this.emitter=new Qw,this.emitter.on("error",(a,c)=>{this.logger.error(`error: ${c}, context: ${JSON.stringify(a)}`)}),this.R.on((a,c,l)=>{this.yi(c,l);let u=xn.toLDContext(a);this.emitter.emit("change",u,c),c.forEach(h=>{this.emitter.emit(`change:${h}`,u)})}),this.dataManager=i(this.R,this.e,this.me,this.emitter,this.S);let s=[...this.e.hooks];if(this.environmentMetadata=$w(this.sdkKey,this.platform,this.e),this.e.getImplementationHooks(this.environmentMetadata).forEach(a=>{s.push(a)}),this.M=new Dw(this.logger,s),this.Y=new jw(this.e.inspectors,this.logger),this.Y.hasInspectors()&&this.M.addHook(Yw(this.Y)),r.cleanOldPersistentData&&o!=null&&o.getLegacyStorageKeys&&this.platform.storage)try{this.logger.debug("Cleaning old persistent data."),Promise.all(o.getLegacyStorageKeys().map(a=>{var c;return(c=this.platform.storage)==null?void 0:c.clear(a)})).catch(a=>{this.logger.error(`Error cleaning old persistent data: ${a}`)}).finally(()=>{this.logger.debug("Cleaned old persistent data.")})}catch(a){this.logger.error(`Error cleaning old persistent data: ${a}`)}}allFlags(){return Object.entries(this.R.getAll()).reduce((t,[e,n])=>(n.flag!==null&&n.flag!==void 0&&!n.flag.deleted&&(t[e]=n.flag.value),t),{})}async close(){var t;await this.flush(),(t=this.E)==null||t.close(),this.dataManager.close(),this.logger.debug("Closed event processor and data source.")}async flush(){var t;try{await((t=this.E)==null?void 0:t.flush()),this.logger.debug("Successfully flushed event processor.")}catch(e){return this.logger.error(`Error flushing event processor: ${e}.`),{error:e,result:!1}}return{result:!0}}getContext(){return this.a.hasContext()?kp(this.a.getUnwrappedContext()):void 0}getInternalContext(){return this.a.getContext()}presetFlags(t){this.R.presetFlags(t)}async identify(t,e){let n=await this.identifyResult(t,e);if(n.status==="error")throw n.error;if(n.status==="timeout"){let r=new Zp(`identify timed out after ${n.timeout} seconds.`);throw this.logger.error(r.message),r}}async identifyResult(t,e){var n,r;let i=(n=e==null?void 0:e.timeout)!=null?n:qw,o=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;i>this.Pt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Pt} seconds. We recommend a timeout of less than ${this.Pt} seconds.`);let s=this.mi.execute({before:async()=>{let c=await kw(t,this.platform);this.autoEnvAttributes===Ai.Enabled&&(c=await Sw(c,this.platform,this.e));let l=xn.fromLDContext(c);if(l.valid){let u=this.M.identify(c,e==null?void 0:e.timeout);return{context:c,checkedContext:l,afterIdentify:u}}return{context:c,checkedContext:l}},execute:async c=>{var l;let{context:u,checkedContext:h}=c;if(!h.valid){let d=new Error("Context was unspecified or had no key");return this.emitter.emit("error",u,d),Promise.reject(d)}this.a.set(u,h),(l=this.E)==null||l.sendEvent(this.T.identifyEvent(h));let{identifyPromise:p,identifyResolve:f,identifyReject:m}=this.a.newIdentificationPromise();return this.logger.debug(`Identifying ${JSON.stringify(h)}`),await this.dataManager.identify(f,m,h,e),p},after:async(c,l)=>{var u,h,p;c.status==="complete"?(u=l==null?void 0:l.afterIdentify)==null||u.call(l,{status:"completed"}):c.status==="shed"?(h=l==null?void 0:l.afterIdentify)==null||h.call(l,{status:"shed"}):c.status==="error"&&((p=l==null?void 0:l.afterIdentify)==null||p.call(l,{status:"error"}))}},(r=e==null?void 0:e.sheddable)!=null?r:!1).then(c=>{if(c.status==="error"){let u={status:"error",error:c.error};return this.maybeSetInitializationResult({status:"failed",error:c.error}),u}if(c.status==="shed")return{status:"shed"};let l={status:"completed"};return this.maybeSetInitializationResult({status:"complete"}),l});if(o)return s;let a=new Promise(c=>{setTimeout(()=>{c({status:"timeout",timeout:i})},i*1e3)});return Promise.race([s,a])}maybeSetInitializationResult(t){this.initializeResult===void 0&&(this.initializeResult=t,this.emitter.emit("ready"),t.status==="complete"&&this.emitter.emit("initialized"),this.initResolve&&(this.initResolve(t),this.initResolve=void 0))}waitForInitialization(t){var e;let n=(e=t==null?void 0:t.timeout)!=null?e:5;return this.initializeResult?Promise.resolve(this.initializeResult):this.initializedPromise?this.promiseWithTimeout(this.initializedPromise,n):(this.initializedPromise||(this.initializedPromise=new Promise(r=>{this.initResolve=r})),this.promiseWithTimeout(this.initializedPromise,n))}promiseWithTimeout(t,e){let n=WS(e,"waitForInitialization");return Promise.race([t.then(r=>(n.cancel(),r)),n.promise.then(()=>({status:"complete"})).catch(()=>({status:"timeout"}))]).catch(r=>{var i;return(i=this.logger)==null||i.error(r.message),{status:"failed",error:r}})}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}track(t,e,n){var r,i;if(!this.a.hasValidContext()){this.logger.warn(lp.MissingContextKeyNoEvent);return}n!==void 0&&!G.Number.is(n)&&((r=this.logger)==null||r.warn(lp.invalidMetricValue(typeof n))),(i=this.E)==null||i.sendEvent(this.e.trackEventModifier(this.T.customEvent(t,this.a.getContext(),e,n))),this.M.afterTrack({key:t,context:this.a.getUnwrappedContext(),data:e,metricValue:n})}lt(t,e,n,r){var i,o,s,a,c;let l=this.a.hasContext();l||(i=this.logger)==null||i.warn("Flag evaluation called before client is fully initialized, data from this evaulation could be stale.");let u=this.a.getContext(),h=this.R.get(t);if(h===void 0||h.flag.deleted){let g=e!=null?e:null;return(o=this.logger)==null||o.warn(`Unknown feature flag "${t}"; returning default value ${g}.`),l&&((s=this.E)==null||s.sendEvent(this.T.unknownFlagEvent(t,g,u))),ip(cp.FlagNotFound,e)}let{reason:p,value:f,variation:m,prerequisites:d}=h.flag;if(r){let[g,S]=r(f);if(!g){l&&((a=this.E)==null||a.sendEvent(n.evalEventClient(t,e,e,h.flag,u,p)));let T=new LS(`Wrong type "${S}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.a.getUnwrappedContext(),T),ip(cp.WrongType,e)}}let v=op(f,m,p);return f==null&&(this.logger.debug("Result value is null. Providing default value."),v.value=e),d==null||d.forEach(g=>{this.lt(g,void 0,this.T)}),l&&((c=this.E)==null||c.sendEvent(n.evalEventClient(t,f,e,h.flag,u,p))),v}variation(t,e){let{value:n}=this.M.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.lt(t,e,this.T));return n}variationDetail(t,e){return this.M.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.lt(t,e,this.ct))}G(t,e,n,r){return this.M.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.lt(t,e,n,r))}boolVariation(t,e){return this.G(t,e,this.T,n=>[G.Boolean.is(n),G.Boolean.getType()]).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.G(t,e,this.T,n=>[G.Number.is(n),G.Number.getType()]).value}stringVariation(t,e){return this.G(t,e,this.T,n=>[G.String.is(n),G.String.getType()]).value}boolVariationDetail(t,e){return this.G(t,e,this.ct,n=>[G.Boolean.is(n),G.Boolean.getType()])}numberVariationDetail(t,e){return this.G(t,e,this.ct,n=>[G.Number.is(n),G.Number.getType()])}stringVariationDetail(t,e){return this.G(t,e,this.ct,n=>[G.String.is(n),G.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.M.addHook(t)}setEventSendingEnabled(t,e){var n,r,i,o;this.Tt!==t&&(this.Tt=t,t?(this.logger.debug("Starting event processor"),(n=this.E)==null||n.start()):e?((r=this.logger)==null||r.debug("Flushing event processor before disabling."),this.flush().then(()=>{var s,a;this.Tt||((s=this.logger)==null||s.debug("Stopping event processor."),(a=this.E)==null||a.close())})):((i=this.logger)==null||i.debug("Stopping event processor."),(o=this.E)==null||o.close()))}sendEvent(t){var e;(e=this.E)==null||e.sendEvent(t)}getDebugOverrides(){var t,e;return(e=(t=this.R).getDebugOverride)==null?void 0:e.call(t)}yi(t,e){if(!this.Y.hasInspectors())return;let n={};t.forEach(r=>{let i=this.R.get(r);if(i!=null&&i.flag&&!i.flag.deleted){let{reason:o,value:s,variation:a}=i.flag;n[r]=op(s,a,o)}else n[r]={value:void 0,variationIndex:null}}),e==="init"?this.Y.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([r,i])=>{this.Y.onFlagChanged(r,i)})}};function eI(t,e,n){n.forEach(r=>{var i;try{(i=r.registerDebug)==null||i.call(r,e)}catch(o){t.error(`Exception thrown registering plugin ${de.safeGetName(t,r)}.`)}})}function jp(t,e){let n=Object.keys(e),r="$flagsState",i="$valid",o=e[r];!o&&n.length&&t.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),e[i]===!1&&t.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");let s={};return n.forEach(a=>{if(a!==r&&a!==i){let c;o&&o[a]?c=st({value:e[a]},o[a]):c={value:e[a],version:0},s[a]={version:c.version,flag:c}}}),s}function nI(t,e,n){return{async handlePut(r,i){n.debug(`Got PUT: ${Object.keys(i)}`);let o=Object.entries(i).reduce((s,[a,c])=>(s[a]={version:c.version,flag:c},s),{});await t.init(r,o),e.requestStateUpdate("VALID")},async handlePatch(r,i){n.debug(`Got PATCH ${JSON.stringify(i,null,2)}`),t.upsert(r,i.key,{version:i.version,flag:i})},async handleDelete(r,i){n.debug(`Got DELETE ${JSON.stringify(i,null,2)}`),t.upsert(r,i.key,{version:i.version,flag:me(st({},i),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})},handleStreamingError(r){e.reportError(r.kind,r.message,r.code,r.recoverable)},handlePollingError(r){e.reportError(r.kind,r.message,r.status,r.recoverable)}}}function rI(t,e=()=>Date.now()){let n="CLOSED",r=e(),i;function o(){return{state:n,stateSince:r,lastError:i}}function s(a,c=!1){let l=a==="INTERRUPTED"&&n==="INITIALIZING"?"INITIALIZING":a,u=n!==l;u&&(n=l,r=e()),(u||c)&&t.emit("dataSourceStatus",o())}return{get status(){return o()},requestStateUpdate(a){s(a)},reportError(a,c,l,u=!1){i={kind:a,message:c,statusCode:l,time:e()},s(u?"INTERRUPTED":"CLOSED",!0)}}}function up(t){t==null||t.debug("Poll completed after the processor was closed. Skipping processing.")}var iI=class{constructor(t,e,n,r,i){this.vi=t,this.wi=e,this.Ei=n,this.g=r,this.t=i,this.u=!1}async ye(){var t,e,n,r,i,o,s;if(this.u)return;let a=h=>{var p,f,m;(p=this.t)==null||p.error("Polling received invalid data"),(f=this.t)==null||f.debug(`Invalid JSON follows: ${h}`),(m=this.g)==null||m.call(this,new Fi(At.InvalidData,"Malformed JSON data in polling response"))};(t=this.t)==null||t.debug("Polling LaunchDarkly for feature flag updates");let c=Date.now();try{let h=await this.vi.requestPayload();try{if(this.u){up(this.t);return}let p=JSON.parse(h);try{(e=this.Ei)==null||e.call(this,p)}catch(f){(n=this.t)==null||n.error(`Exception from data handler: ${f}`)}}catch(p){a(h)}}catch(h){if(this.u){up(this.t);return}let p=h;if(p.status!==void 0&&!Ki(p.status)){(r=this.t)==null||r.error(Gn(h,"polling request")),(i=this.g)==null||i.call(this,new Fi(At.ErrorResponse,p.message,p.status));return}(o=this.t)==null||o.error(Gn(h,"polling request","will retry"))}let l=Date.now()-c,u=Math.max(this.wi*1e3-l,0);(s=this.t)==null||s.debug("Elapsed: %d ms, sleeping for %d ms",l,u),this.Nt=setTimeout(()=>{this.ye()},u)}start(){this.ye()}stop(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0),this.u=!0}close(){this.stop()}},oI=(t,e,n,r)=>{n==null||n.error(`Stream received invalid data in "${t}" message`),n==null||n.debug(`Invalid JSON follows: ${e}`),r==null||r(new Xa(At.InvalidData,"Malformed JSON data in event stream"))};function sI(t,e){e==null||e.debug(`Received ${t} event after processor was closed. Skipping processing.`)}function hp(t){t==null||t.debug("Ping completed after processor was closed. Skipping processing.")}var aI=class{constructor(t,e,n,r,i,o,s,a,c){var l;this.Di=t,this.$t=e,this.n=n,this.V=r,this.bi=o,this.S=s,this.g=a,this.t=c,this.u=!1;let u;e.useReport&&!r.getEventSourceCapabilities().customMethod?u=e.paths.pathPing(i,t):u=e.useReport?e.paths.pathReport(i,t):e.paths.pathGet(i,t);let h=[...(l=e.queryParameters)!=null?l:[]];this.$t.withReasons&&h.push({key:"withReasons",value:"true"}),this.V=r,this.ve=st({},e.baseHeaders),this.t=c,this.ki=OS(e.serviceEndpoints,u,h)}we(){this.ut=Date.now()}Rt(t){this.ut&&this.S&&this.S.recordStreamInit(this.ut,!t,Date.now()-this.ut),this.ut=void 0}xi(t){var e,n,r;return Vp(t)?((r=this.t)==null||r.warn(Gn(t,"streaming request","will retry")),this.Rt(!1),this.we(),!0):(this.Rt(!1),(e=this.g)==null||e.call(this,new Xa(At.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error(Gn(t,"streaming request")),!1)}start(){this.we();let t;this.$t.useReport?(this.ve["content-type"]="application/json",t={method:"REPORT",body:this.Di}):t={};let e=this.V.createEventSource(this.ki,me(st({headers:this.ve},t),{errorFilter:n=>this.xi(n),initialRetryDelayMillis:this.$t.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3}));this.Ee=e,e.onclose=()=>{var n;(n=this.t)==null||n.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var n;(n=this.t)==null||n.info("Opened LaunchDarkly stream connection")},e.onretrying=n=>{var r;(r=this.t)==null||r.info(`Will retry stream connection in ${n.delayMillis} milliseconds`)},this.n.forEach(({deserializeData:n,processJson:r},i)=>{e.addEventListener(i,o=>{var s,a;if(this.u){sI(i,this.t);return}if((s=this.t)==null||s.debug(`Received ${i} event`),o!=null&&o.data){this.Rt(!0);let{data:c}=o,l=n(c);if(!l){oI(i,c,this.t,this.g);return}r(l)}else(a=this.g)==null||a.call(this,new Xa(At.InvalidData,"Unexpected payload from event stream"))})}),e.addEventListener("ping",async()=>{var n,r,i,o,s,a,c;(n=this.t)==null||n.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let l=await this.bi.requestPayload();try{if(this.u){hp(this.t);return}let u=JSON.parse(l);try{(r=this.n.get("put"))==null||r.processJson(u)}catch(h){(i=this.t)==null||i.error(`Exception from data handler: ${h}`)}}catch(u){(o=this.t)==null||o.error("Polling after ping received invalid data"),(s=this.t)==null||s.debug(`Invalid JSON follows: ${l}`),(a=this.g)==null||a.call(this,new Fi(At.InvalidData,"Malformed JSON data in ping polling response"))}}catch(l){if(this.u){hp(this.t);return}let u=l;(c=this.g)==null||c.call(this,new Fi(At.ErrorResponse,u.message,u.status))}})}stop(){var t;(t=this.Ee)==null||t.close(),this.Ee=void 0,this.u=!0}close(){this.stop()}},lI=class{constructor(t,e,n,r,i,o,s,a,c){this.platform=t,this.flagManager=e,this.credential=n,this.config=r,this.getPollingPaths=i,this.getStreamingPaths=o,this.baseHeaders=s,this.emitter=a,this.diagnosticsManager=c,this.closed=!1,this.logger=r.logger,this.dataSourceStatusManager=rI(a),this.K=nI(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.Si=t}createPollingProcessor(t,e,n,r,i){let o=new iI(n,this.config.pollInterval,async s=>{await this.K.handlePut(e,s),r==null||r()},s=>{this.emitter.emit("error",t,s),this.K.handlePollingError(s),i==null||i(s)},this.logger);this.updateProcessor=this.De(o,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,r,i){var o;let s=new aI(JSON.stringify(t),{credential:this.credential,serviceEndpoints:this.config.serviceEndpoints,paths:this.getStreamingPaths(),baseHeaders:this.baseHeaders,initialRetryDelayMillis:this.config.streamInitialReconnectDelay*1e3,withReasons:this.config.withReasons,useReport:this.config.useReport,queryParameters:(o=this.Si)==null?void 0:o.queryParameters},this.createStreamListeners(e,r),this.platform.requests,this.platform.encoding,n,this.diagnosticsManager,a=>{this.emitter.emit("error",t,a),this.K.handleStreamingError(a),i==null||i(a)},this.logger);this.updateProcessor=this.De(s,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async r=>{await this.K.handlePut(t,r),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async r=>{this.K.handlePatch(t,r)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async r=>{this.K.handleDelete(t,r)}}),n}De(t,e){return{start:()=>{e.requestStateUpdate("INITIALIZING"),t.start()},stop:()=>{t.stop(),e.requestStateUpdate("CLOSED")},close:()=>{t.close(),e.requestStateUpdate("CLOSED")}}}close(){var t;(t=this.updateProcessor)==null||t.close(),this.closed=!0}};function _i(){return typeof document!==void 0}function Ya(){return typeof window!==void 0}function Qp(t,e,n){return _i()?(document.addEventListener(t,e,n),()=>{document.removeEventListener(t,e,n)}):()=>{}}function $p(t,e,n){return _i()?(window.addEventListener(t,e,n),()=>{window.removeEventListener(t,e,n)}):()=>{}}function yr(){return Ya()?window.location.href:""}function cI(){return Ya()?window.location.search:""}function uI(){return Ya()?window.location.hash:""}function hI(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function pI(){return _i()?document.visibilityState:"visibile"}function dI(t){if(_i())return document.querySelectorAll(t)}var fI="[BrowserDataManager]",mI=class extends lI{constructor(t,e,n,r,i,o,s,a,c,l){super(t,e,n,r,o,s,a,c,l),this.Ui=i,this.Z=void 0,this.Mt=!1,this.Z=i.streaming}L(t,...e){this.logger.debug(`${fI} ${t}`,...e)}async identify(t,e,n,r){if(this.closed){this.L("Identify called after data manager was closed.");return}this.context=n;let i=r;i!=null&&i.hash?this.setConnectionParams({queryParameters:[{key:"h",value:i.hash}]}):this.setConnectionParams(),this.Ft=i==null?void 0:i.hash,i!=null&&i.bootstrap?this.Li(n,i,t):(await this.flagManager.loadCached(n)&&this.L("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Ci(n,t,e)),this.Ut()}async Ii(t){let e=JSON.stringify(xn.toLDContext(t)),n=tp(e,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ft),r=3,i;for(let o=0;o<=r;o+=1)try{return await n.requestPayload()}catch(s){if(!Vp(s))throw s;i=s,o<r&&(this.L(Gn(s,"initial poll request","will retry")),await xp(1e3))}throw i}async Ci(t,e,n){var r,i;try{this.dataSourceStatusManager.requestStateUpdate(iw.Initializing);let o=await this.Ii(t);try{let s=this.createStreamListeners(t,e).get("put");s.processJson(s.deserializeData(o))}catch(s){this.dataSourceStatusManager.reportError(At.InvalidData,(r=s.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(At.NetworkError,(i=o.message)!=null?i:"unexpected network error",o.status),n(o)}}Li(t,e,n){let{bootstrapParsed:r}=e;r||(r=jp(this.logger,e.bootstrap)),this.flagManager.setBootstrap(t,r),this.L("Identify - Initialization completed from bootstrap"),n()}setForcedStreaming(t){this.Z=t,this.Ut()}setAutomaticStreamingState(t){this.Mt=t,this.Ut()}Ut(){let t=this.Z||this.Mt&&this.Z===void 0;this.L(`Updating streaming state. forced(${this.Z}) automatic(${this.Mt})`),t?this.Oi():this.Ai()}Ai(){var t;this.updateProcessor&&this.L("Stopping update processor."),(t=this.updateProcessor)==null||t.close(),this.updateProcessor=void 0}Oi(){if(this.updateProcessor){this.L("Update processor already active. Not changing state.");return}if(!this.context){this.L("Context not set, not starting update processor.");return}this.L("Starting update processor."),this.Pi(this.context)}Pi(t,e,n){var r;let i=xn.toLDContext(t);(r=this.updateProcessor)==null||r.close();let o=JSON.stringify(xn.toLDContext(t)),s=tp(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ft);this.createStreamingProcessor(i,t,s,e,n),this.updateProcessor.start()}};function yI(t){let e=Qp("visibilitychange",()=>{pI()==="hidden"&&t()}),n=$p("pagehide",t);return()=>{e(),n()}}function Na(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function gI(t,e,n,r){let i=((t.kind==="substring"||t.kind==="regex")&&r.includes("/")?e:e.replace(r,"")).replace(n,"");switch(t.kind){case"exact":return new RegExp(`^${Na(t.url)}/?$`).test(e);case"canonical":return new RegExp(`^${Na(t.url)}/?$`).test(i);case"substring":return new RegExp(`.*${Na(t.substring)}.*$`).test(i);case"regex":return new RegExp(t.pattern).test(i);default:return!1}}function bI(t,e){let n=[];return e.forEach(r=>{let i=t.target,{selector:o}=r,s=dI(o);for(;i&&s!=null&&s.length;){for(let a=0;a<s.length;a+=1)if(i===s[a]){n.push(r);break}i=i.parentNode}}),n}var vI=class{constructor(t,e){let n=t.filter(o=>{var s;return(s=o.urls)==null?void 0:s.some(a=>gI(a,yr(),cI(),uI()))}),r=n.filter(o=>o.kind==="pageview"),i=n.filter(o=>o.kind==="click");if(r.forEach(o=>e(o)),i.length){let o=s=>{bI(s,i).forEach(a=>{e(a)})};this.be=Qp("click",o)}}close(){var t;(t=this.be)==null||t.call(this)}},SI=300,wI=class{constructor(t){this.Vt=yr();let e=()=>{let r=yr();r!==this.Vt&&(this.Vt=r,t())};this.jt=setInterval(e,SI);let n=$p("popstate",e);this.ke=()=>{n()}}close(){var t;this.jt&&clearInterval(this.jt),(t=this.ke)==null||t.call(this)}},II=class{constructor(t,e,n,r,i,o=s=>new wI(s)){this.V=e,this.$i=r,this.Ni=i,this.ht=[],this.Se=!1,this.dt=`${n}/sdk/goals/${t}`,this.xe=o(()=>{this.Bt()})}async initialize(){await this.Ti(),this.Bt()}startTracking(){this.Se=!0,this.Bt()}Bt(){var t;this.Se&&((t=this.Ht)==null||t.close(),this.ht&&this.ht.length&&(this.Ht=new vI(this.ht,e=>{this.Ni(yr(),e)})))}async Ti(){try{let t=await this.V.fetch(this.dt);this.ht=await t.json()}catch(t){this.$i(new Cp(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.xe)==null||t.close(),(e=this.Ht)==null||e.close()}};function TI(t){return t.kind==="click"}var EI=2,qp={fetchGoals:!0,eventUrlTransformer:t=>t,streaming:void 0,plugins:[]},RI={fetchGoals:G.Boolean,eventUrlTransformer:G.Function,streaming:G.Boolean,plugins:G.createTypeArray("LDPlugin",{})};function CI(t){var e;let n=st({},t);return(e=n.flushInterval)!=null||(n.flushInterval=EI),n}function ZI(t){let e=CI(t);return Object.keys(qp).forEach(n=>{delete e[n]}),e}function kI(t,e){let n=st({},qp);return Object.entries(RI).forEach(r=>{let[i,o]=r,s=t[i];s!==void 0&&(o.is(s)?n[i]=s:e.warn(Ue.wrongOptionType(i,o.getType(),typeof s)))}),n}var VI=class{constructor(t,e){switch(this.Ri=t,this.Le=[],e){case"sha1":this.zt="SHA-1";break;case"sha256":this.zt="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.Le.join(""),n=new TextEncoder().encode(e),r=await this.Ri.subtle.digest(this.zt,n);switch(t){case"base64":return btoa(String.fromCharCode(...new Uint8Array(r)));case"hex":return[...new Uint8Array(r)].map(i=>i.toString(16).padStart(2,"0")).join("");default:throw new Error(`Encoding is not supported ${t}`)}}update(t){return this.Le.push(t),this}},xI={start:0,end:3},NI={start:4,end:5},Oa={start:6,end:7},Ga={start:8,end:8},OI={start:9,end:9},GI={start:10,end:15};function LI(){if(crypto&&crypto.getRandomValues){let e=new Uint8Array(16);return crypto.getRandomValues(e),[...e.values()]}let t=[];for(let e=0;e<16;e+=1)t.push(Math.floor(Math.random()*256));return t}function kn(t,e){let n="";for(let r=e.start;r<=e.end;r+=1)n+=t[r].toString(16).padStart(2,"0");return n}function XI(t){return t[Ga.start]=(t[Ga.start]|128)&191,t[Oa.start]=t[Oa.start]&15|64,`${kn(t,xI)}-${kn(t,NI)}-${kn(t,Oa)}-${kn(t,Ga)}${kn(t,OI)}-${kn(t,GI)}`}function WI(){let t=LI();return XI(t)}function UI(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():WI()}var PI=class{createHash(t){return new VI(hI(),t)}randomUUID(){return UI()}};function MI(t){let e=Array.from(t,n=>String.fromCodePoint(n)).join("");return btoa(e)}var FI=class{btoa(t){return MI(new TextEncoder().encode(t))}},AI=class{constructor(t){this.e=t}platformData(){return{name:"JS"}}sdkData(){let t={name:"@launchdarkly/js-client-sdk",version:"4.2.1",userAgentBase:"JSClient"};return this.e.wrapperName&&(t.wrapperName=this.e.wrapperName),this.e.wrapperVersion&&(t.wrapperVersion=this.e.wrapperVersion),t}},JI=class{constructor(t,e){this.dt=t,this.n={},this.I=new wS(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.Ce=e.errorFilter,this.Ie()}Ie(){this._=new EventSource(this.dt),this._.onopen=()=>{var t;this.I.success(),(t=this.onopen)==null||t.call(this)},this._.onerror=t=>{var e;this.Mi(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.n).forEach(([t,e])=>{e.forEach(n=>{var r;(r=this._)==null||r.addEventListener(t,n)})})}addEventListener(t,e){var n,r,i;(r=(n=this.n)[t])!=null||(n[t]=[]),this.n[t].push(e),(i=this._)==null||i.addEventListener(t,e)}close(){var t,e;clearTimeout(this.Gt),this.Gt=void 0,(t=this._)==null||t.close(),(e=this.onclose)==null||e.call(this)}Fi(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.Gt=setTimeout(()=>{this.Ie()},t)}Mi(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.Ce(t))&&this.Fi(this.I.fail())}},DI=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new JI(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function td(){return typeof localStorage!="undefined"}function YI(){if(!td())return[];let t=[];for(let e=0;e<localStorage.length;e+=1){let n=localStorage.key(e);n&&t.push(n)}return t}var KI=class{constructor(t){this.t=t}async clear(t){var e;try{localStorage.removeItem(t)}catch(n){(e=this.t)==null||e.error(`Error clearing key from localStorage: ${t}, reason: ${n}`)}}async get(t){var e;try{let n=localStorage.getItem(t);return n!=null?n:null}catch(n){return(e=this.t)==null||e.error(`Error getting key from localStorage: ${t}, reason: ${n}`),null}}async set(t,e){var n;try{localStorage.setItem(t,e)}catch(r){(n=this.t)==null||n.error(`Error setting key in localStorage: ${t}, reason: ${r}`)}}},_I=class{constructor(t,e){this.encoding=new FI,this.crypto=new PI,this.requests=new DI,td()&&(this.storage=new KI(t)),this.info=new AI(e)}},HI=class extends tI{constructor(t,e,n={},r){var i;let{logger:o,debug:s}=n,a=o!=null?o:new Ma({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:s?"debug":"info"}),c=(i=n.baseUri)!=null?i:"https://clientsdk.launchdarkly.com",l=r!=null?r:new _I(a,n),u=kI(n,a),h=ZI(me(st({},n),{logger:a})),{eventUrlTransformer:p}=u;super(t,e,l,h,(f,m,d,v,g)=>new mI(l,f,t,m,u,()=>({pathGet(S,T){return`/sdk/evalx/${t}/contexts/${jh(T,S)}`},pathReport(S,T){return`/sdk/evalx/${t}/context`},pathPing(S,T){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(S,T){return`/eval/${t}/${jh(T,S)}`},pathReport(S,T){return`/eval/${t}`},pathPing(S,T){return`/ping/${t}`}}),d,v,g),{getLegacyStorageKeys:()=>YI().filter(f=>f.startsWith(`ld:${t}:`)),analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:f=>new de.InputCustomEvent(f.context,f.key,f.data,f.metricValue,f.samplingRatio,p(yr())),getImplementationHooks:f=>de.safeGetHooks(a,f,u.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),this.yo=u.plugins,u.fetchGoals&&(this.Kt=new II(t,l.requests,c,f=>{a.error(f.message)},(f,m)=>{let d=this.getInternalContext();if(!d)return;let v=p(f);TI(m)?this.sendEvent({kind:"click",url:v,samplingRatio:1,key:m.key,creationDate:Date.now(),context:d,selector:m.selector}):this.sendEvent({kind:"pageview",url:v,samplingRatio:1,key:m.key,creationDate:Date.now(),context:d})}),this.Kt.initialize(),u.automaticBackgroundHandling&&yI(()=>this.flush()))}registerPlugins(t){de.safeRegisterPlugins(this.logger,this.environmentMetadata,t,this.yo||[]);let e=this.getDebugOverrides();e&&eI(this.logger,e,this.yo||[])}setInitialContext(t){this.Wt=t}async identify(t,e){return super.identify(t,e)}async identifyResult(t,e){var n;if(!this.X)return this.logger.error("Client must be started before it can identify a context, did you forget to call start()?"),{status:"error",error:new Error("Identify called before start")};let r=st({},e);(e==null?void 0:e.sheddable)===void 0&&(r.sheddable=!0);let i=await super.identifyResult(t,r);return(n=this.Kt)==null||n.startTracking(),i}start(t){var e,n;if(this.initializeResult)return Promise.resolve(this.initializeResult);if(this.X)return this.X;if(!this.Wt)return this.logger.error("Initial context not set"),Promise.resolve({status:"failed",error:new Error("Initial context not set")});let r=me(st({},(e=t==null?void 0:t.identifyOptions)!=null?e:{}),{sheddable:!1});if(t!=null&&t.bootstrap&&!r.bootstrap&&(r.bootstrap=t.bootstrap),r!=null&&r.bootstrap)try{r.bootstrapParsed||(r.bootstrapParsed=jp(this.logger,r.bootstrap)),this.presetFlags(r.bootstrapParsed)}catch(i){this.logger.error("Failed to bootstrap data",i)}return this.initializedPromise||(this.initializedPromise=new Promise(i=>{this.initResolve=i})),this.X=this.promiseWithTimeout(this.initializedPromise,(n=t==null?void 0:t.timeout)!=null?n:5),this.identifyResult(this.Wt,r),this.X}setStreaming(t){this.dataManager.setForcedStreaming(t)}Oe(){let t=this.dataManager,e=this.emitter.eventNames().some(n=>n.startsWith("change:")||n==="change");t.setAutomaticStreamingState(e)}on(t,e){super.on(t,e),this.Oe()}off(t,e){super.off(t,e),this.Oe()}};function zI(t,e,n,r={},i){let o=new HI(t,n,r,i);o.setInitialContext(e);let s={variation:(a,c)=>o.variation(a,c),variationDetail:(a,c)=>o.variationDetail(a,c),boolVariation:(a,c)=>o.boolVariation(a,c),boolVariationDetail:(a,c)=>o.boolVariationDetail(a,c),numberVariation:(a,c)=>o.numberVariation(a,c),numberVariationDetail:(a,c)=>o.numberVariationDetail(a,c),stringVariation:(a,c)=>o.stringVariation(a,c),stringVariationDetail:(a,c)=>o.stringVariationDetail(a,c),jsonVariation:(a,c)=>o.jsonVariation(a,c),jsonVariationDetail:(a,c)=>o.jsonVariationDetail(a,c),track:(a,c,l)=>o.track(a,c,l),on:(a,c)=>o.on(a,c),off:(a,c)=>o.off(a,c),flush:()=>o.flush(),setStreaming:a=>o.setStreaming(a),identify:(a,c)=>o.identifyResult(a,c),getContext:()=>o.getContext(),close:()=>o.close(),allFlags:()=>o.allFlags(),addHook:a=>o.addHook(a),waitForInitialization:a=>o.waitForInitialization(a),logger:o.logger,start:a=>o.start(a)};return o.registerPlugins(s),s}function _F(t){return new Ma(t)}function ed(t,e,n){return zI(t,e,Ai.Disabled,n)}var BI=Object.defineProperty,jI=(t,e,n)=>e in t?BI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Te=(t,e,n)=>jI(t,typeof e!="symbol"?e+"":e,n),QI=(t,e,n)=>new Promise((r,i)=>{var o=c=>{try{a(n.next(c))}catch(l){i(l)}},s=c=>{try{a(n.throw(c))}catch(l){i(l)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(o,s);a((n=n.apply(t,e)).next())}),ke=(t,e,...n)=>{let r=`[@launchdarkly plugins]: (${t}): `;console[e].apply(console,[r,...n]),$I(r,...n)},$I=(t,...e)=>QI(void 0,null,function*(){try{let{LDObserve:n}=yield Promise.resolve().then(()=>rR);n.recordLog(`${t}${e}`,"warn")}catch(n){}}),qI=class{constructor(t,e){Te(this,"debug"),Te(this,"name"),this.debug=t,this.name=e}log(...t){if(this.debug){let e=`[${Date.now()}]`;this.name&&(e+=` - ${this.name}`),console.log.apply(console,[e,...t])}}warn(...t){let e=`[${Date.now()}]`;this.name&&(e+=` - ${this.name}`),console.warn.apply(console,[e,...t])}},vo=class{constructor(){Te(this,"_sdk"),Te(this,"_isLoaded",!1),Te(this,"_callBuffer",[]),Te(this,"_capacity",1e5),Te(this,"_droppedEvents",0),Te(this,"_exceededCapacity",!1),Te(this,"_logger",new qI)}h(e,n){if(this.Nn)try{return this.jn[e](...n)}catch(r){ke(`Error executing buffered call to ${e}:`,"error",r)}else{this.Pr({method:e,args:n});return}}Pr(e){this.wn.length<this.Is?(this.wn.push(e),this.Qn=!1):(this.Qn||(this.Qn=!0,ke("Exceeded event queue capacity. Increase capacity to avoid dropping events.","warn")),this.Ts+=1)}load(e){this.jn=e,this.Nn=!0;for(let{method:n,args:r}of this.wn)try{this.jn[n](...r)}catch(i){ke(`Error executing buffered call to ${n}:`,"error",i)}this.wn=[]}},tT=Object.defineProperty,eT=Object.defineProperties,nT=Object.getOwnPropertyDescriptors,So=Object.getOwnPropertySymbols,Mf=Object.prototype.hasOwnProperty,Ff=Object.prototype.propertyIsEnumerable,Zl=(t,e,n)=>e in t?tT(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,j=(t,e)=>{for(var n in e||(e={}))Mf.call(e,n)&&Zl(t,n,e[n]);if(So)for(var n of So(e))Ff.call(e,n)&&Zl(t,n,e[n]);return t},An=(t,e)=>eT(t,nT(e)),xr=(t,e)=>{var n={};for(var r in t)Mf.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&So)for(var r of So(t))e.indexOf(r)<0&&Ff.call(t,r)&&(n[r]=t[r]);return n},Wr=(t,e,n)=>Zl(t,typeof e!="symbol"?e+"":e,n),Dn=(t,e,n)=>new Promise((r,i)=>{var o=c=>{try{a(n.next(c))}catch(l){i(l)}},s=c=>{try{a(n.throw(c))}catch(l){i(l)}},a=c=>c.done?r(c.value):Promise.resolve(c.value).then(o,s);a((n=n.apply(t,e)).next())});function rT(t,e){for(var n=0;n<e.length;n++){let r=e[n];if(typeof r!="string"&&!Array.isArray(r)){for(let i in r)if(i!=="default"&&!(i in t)){let o=Object.getOwnPropertyDescriptor(r,i);o&&Object.defineProperty(t,i,o.get?o:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}function lo(t,e){throw new Error(e)}function iT(t){return typeof t=="object"&&t!==null}function oT(t,e){throw new Error("Unexpected invariant triggered.")}var sT=/\r\n|[\n\r]/g;function kl(t,e){let n=0,r=1;for(let i of t.body.matchAll(sT)){if(typeof i.index=="number"||oT(),i.index>=e)break;n=i.index+i[0].length,r+=1}return{line:r,column:e+1-n}}function aT(t){return Af(t.source,kl(t.source,t.start))}function Af(t,e){let n=t.locationOffset.column-1,r="".padStart(n)+t.body,i=e.line-1,o=t.locationOffset.line-1,s=e.line+o,a=e.line===1?n:0,c=e.column+a,l=`${t.name}:${s}:${c}
|
|
349
349
|
`,u=r.split(/\r\n|[\n\r]/g),h=u[i];if(h.length>120){let p=Math.floor(c/80),f=c%80,m=[];for(let d=0;d<h.length;d+=80)m.push(h.slice(d,d+80));return l+nd([[`${s} |`,m[0]],...m.slice(1,p+1).map(d=>["|",d]),["|","^".padStart(f)],["|",m[p+1]]])}return l+nd([[`${s-1} |`,u[i-1]],[`${s} |`,h],["|","^".padStart(c)],[`${s+1} |`,u[i+1]]])}function nd(t){let e=t.filter(([r,i])=>i!==void 0),n=Math.max(...e.map(([r])=>r.length));return e.map(([r,i])=>r.padStart(n)+(i?" "+i:"")).join(`
|
|
350
350
|
`)}function lT(t){let e=t[0];return e==null||"kind"in e||"length"in e?{nodes:e,source:t[1],positions:t[2],path:t[3],originalError:t[4],extensions:t[5]}:e}var cT=class Jf extends Error{constructor(e,...n){var r,i,o;let{nodes:s,source:a,positions:c,path:l,originalError:u,extensions:h}=lT(n);super(e),this.name="GraphQLError",this.path=l!=null?l:void 0,this.originalError=u!=null?u:void 0,this.nodes=rd(Array.isArray(s)?s:s?[s]:void 0);let p=rd((r=this.nodes)===null||r===void 0?void 0:r.map(m=>m.loc).filter(m=>m!=null));this.source=a!=null?a:p==null||(i=p[0])===null||i===void 0?void 0:i.source,this.positions=c!=null?c:p==null?void 0:p.map(m=>m.start),this.locations=c&&a?c.map(m=>kl(a,m)):p==null?void 0:p.map(m=>kl(m.source,m.start));let f=iT(u==null?void 0:u.extensions)?u==null?void 0:u.extensions:void 0;this.extensions=(o=h!=null?h:f)!==null&&o!==void 0?o:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),u!=null&&u.stack?Object.defineProperty(this,"stack",{value:u.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,Jf):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let e=this.message;if(this.nodes)for(let n of this.nodes)n.loc&&(e+=`
|
|
351
351
|
|