@launchdarkly/browser 0.1.3 → 0.1.4
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/dist/metafile-cjs.json +1 -1
- package/dist/metafile-esm.json +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:xe.Initialize,sessionSecureID:this.sessionData.sessionSecureID,backend:this.pn,debug:!!this.debugOptions.clientInteractions,recordingStartTime:this.Bn}});for(let b of this.xn)b.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.ko||(this.pushPayloadTimerId=setTimeout(()=>{this.Ls()},ng)),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=(b,I)=>{I&&this.logger.log("received isCheckout emit",{event:b}),this.events.push(b)};f.bind(this);let m=!!this.Sn;this.Sn&&(this.Sn(),this.Sn=void 0);let[d,v]=gF(this.privacySetting);this.Sn=Oe({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:b=>!this.options.recordCrossOriginIframe,inlineImages:this.inlineImages,inlineVideos:this.inlineVideos,collectFonts:this.inlineImages,inlineStylesheet:this.inlineStylesheet,plugins:[zX()],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.ml(),document.referrer&&(window&&document.referrer.includes(window.location.origin)||(this.addCustomEvent("Referrer",document.referrer),this.addProperties({referrer:document.referrer},{type:"session"}))),this.yl(),this.ready=!0,this.state="Recording",this.manualStopped=!1}catch(u){Ht("initializeSession _setupWindowListeners","warn",u)}})}Xs(e){return Dt(this,null,function*(){if(this.manualStopped){this.logger.log("Ignoring visibility event due to manual stop.");return}new Date().getTime()-this.Gs<pX||(this.Gs=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)))})}fl(){return Dt(this,null,function*(){this.logger.log("highlight in cross-origin iframe is waiting "),yield new Promise(e=>{let n=r=>{if(r.data.highlight===pb){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:db},"*"),window.removeEventListener("message",n),e()}};window.addEventListener("message",n)})})}ml(){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:pb,projectID:this.sessionData.projectID,sessionSecureID:this.sessionData.sessionSecureID},"*")})},ng),window.addEventListener("message",e=>{e.data.highlight===db&&this.logger.log("highlight got response from initialized iframe")})}yl(){var e;try{let r=this;this.enableSegmentIntegration&&this.listeners.push(wF(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(yF(o=>{this.reloaded?(this.addCustomEvent("Reload",o),this.reloaded=!1,r.addProperties({reload:!0},{type:"session"})):this.addCustomEvent("Navigate",o)})),this.listeners.push(FX(o=>{this.addCustomEvent("Viewport",o)})),this.listeners.push(bF((o,s)=>{let a=null,c=null;if(s&&s.target){let l=s.target;a=PX(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(vF(o=>{o&&this.addCustomEvent("Focus",o)})),this.sessionShortcut&&TF(this.sessionShortcut,()=>{window.open(this.getCurrentSessionURLWithTimestamp(),"_blank")}),this.Ns||((e=window.electron)!=null&&e.ipcRenderer?(window.electron.ipcRenderer.on("highlight.run",({visible:o})=>{this.Xs(!o)}),this.logger.log("Set up Electron highlight.run events.")):(SF(o=>this.Xs(o)),this.logger.log("Set up document visibility listener.")),this.Ns=!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",""),ai(this.sessionData.sessionSecureID),Sn(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",""),ai(this.sessionData.sessionSecureID),Sn(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://${ig}/${n}/sessions/${r}?ts=${i}`}getCurrentSessionURL(){let e=this.sessionData.projectID,n=this.sessionData.sessionSecureID;return e&&n?`https://${ig}/${e}/sessions/${n}`:null}snapshot(e){return Dt(this,null,function*(){yield Oe.snapshotCanvas(e)})}addSessionFeedback({timestamp:e,verbatim:n,user_email:r,user_name:i}){var o;this.zn.postMessage({message:{type:xe.Feedback,verbatim:n,timestamp:e,userName:i||this.sessionData.userIdentifier,userEmail:r||((o=this.sessionData.userObject)==null?void 0:o.name)}})}Ls(){return Dt(this,null,function*(){var e;try{this.state==="Recording"&&this.listeners&&this.sessionData.sessionStartTime&&Date.now()-this.sessionData.sessionStartTime>hX&&(this.logger.log("Resetting session",{start:this.sessionData.sessionStartTime}),yield this.Os({}));let n;((e=this.options)==null?void 0:e.sendMode)==="local"&&(n=r=>Dt(this,null,function*(){let i=new Blob([JSON.stringify({query:Vb(Xb),variables:r})],{type:"application/json"});return yield window.fetch(`${this.pn}`,{method:"POST",body:i}),0})),yield this.gl({sendFn:n}),this.hasPushedData=!0,this.sessionData.lastPushTime=Date.now(),Sn(this.sessionData)}catch(n){Ht("_save","warn",n)}this.state==="Recording"&&(this.pushPayloadTimerId&&(clearTimeout(this.pushPayloadTimerId),this.pushPayloadTimerId=void 0),this.pushPayloadTimerId=setTimeout(()=>{this.Ls()},uX))})}addCustomEvent(e,n){if(this.state==="NotRecording"){let r,i=()=>{clearInterval(r),this.state==="Recording"&&this.events.length>0?cb(e,n):r=setTimeout(i,500)};r=setTimeout(i,500)}else this.state==="Recording"&&(this.events.length>0||this.hasPushedData)&&cb(e,n)}gl(e){return Dt(this,arguments,function*({sendFn:n}){let r=[...this.events],{bytes:i,time:o}=this.enableCanvasRecording?rg.canvas:rg.normal;this.br>=i&&new Date().getTime()-this.xo>=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=OF();n?yield n({session_secure_id:this.sessionData.sessionSecureID,payload_id:(this.sessionData.payloadID++).toString(),events:{events:r},messages:DL({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:xe.AsyncEvents,id:this.sessionData.payloadID++,events:r,messages:[],errors:[],resourcesString:JSON.stringify({resources:[]}),webSocketEventsString:JSON.stringify({webSocketEvents:[]}),hasSessionUnloaded:this.hasSessionUnloaded,highlightLogs:s}}),Sn(this.sessionData),this.events=this.events.slice(r.length),GF(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.xo}),Oe.takeFullSnapshot(),this.br=0,this.xo=new Date().getTime()}register(e,n){this.xn.push(new uu(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=Cs(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(yX);if(r&&(e=r==null?void 0:r.groups)!=null&&e.domain){let i=(n=r.groups.domain)!=null?n:"";return`https://${fX[i]}${mX}`}return dX}},Ri=class extends AX{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=Yt(z({},n),{organizationID:e,firstloadVersion:MF,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 rh(f),n!=null&&n.manualStart||this.record.start(),wn.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&&UF(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&&WF(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=XX(n.context),f=WX(n.context);(h=this.record)==null||h.identify(typeof f=="string"?f:(u=(l=f.user)==null?void 0:l.toString())!=null?u:p,Yt(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,$0=Object.defineProperties,q0=Object.getOwnPropertyDescriptors,Ui=Object.getOwnPropertySymbols,hp=Object.prototype.hasOwnProperty,pp=Object.prototype.propertyIsEnumerable,Jh=(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={}))hp.call(e,n)&&Jh(t,n,e[n]);if(Ui)for(var n of Ui(e))pp.call(e,n)&&Jh(t,n,e[n]);return t},fe=(t,e)=>$0(t,q0(e)),dp=(t,e)=>{var n={};for(var r in t)hp.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&Ui)for(var r of Ui(t))e.indexOf(r)<0&&pp.call(t,r)&&(n[r]=t[r]);return n};function tS(t){return`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`}function fp(t){return t.indexOf("~")?t.replace(/~1/g,"/").replace(/~0/g,"~"):t}function eS(t){return(t.startsWith("/")?t.substring(1):t).split("/").map(e=>fp(e))}function nS(t){return!t.startsWith("/")}function rS(t){return!t.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var xn=class{constructor(t,e=!1){if(e){let n=t;this.g=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?tS(n):n}else{if(this.redactionName=t,t===""||t==="/"||!rS(t)){this.isValid=!1,this.g=[];return}nS(t)?this.g=[t]:t.indexOf("/",1)<0?this.g=[fp(t.slice(1))]:this.g=eS(t),this.g[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{g: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.g[t]}get depth(){return this.g.length}get isKind(){return this.g.length===1&&this.g[0]==="kind"}compare(t){return this.depth===t.depth&&this.g.every((e,n)=>e===t.getComponent(n))}get components(){return[...this.g]}};xn.InvalidReference=new xn("");var iS=class{is(t){if(Array.isArray(t))return!1;let e=typeof t;return e==="function"||e==="object"}getType(){return"factory method or object"}},Gn=class{constructor(t,e){this.mt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.mt}},mp=class{constructor(t,e){this.mt=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.mt}},yp=class extends Gn{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},gp=class extends Gn{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},oS=class{is(t){return typeof t=="function"}getType(){return"function"}},sS=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},aS=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,lS=class{is(t){return typeof t=="number"||typeof t=="string"&&aS.test(t)}getType(){return"date"}},cS=class extends gp{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},G=class{static createTypeArray(t,e){return new mp(t,e)}static numberWithMin(t){return new yp(t)}static stringMatchingRegex(t){return new gp(t)}};G.String=new Gn("string","");G.Number=new Gn("number",0);G.ObjectOrFactory=new iS;G.Object=new Gn("object",{});G.StringArray=new mp("string[]","");G.Boolean=new Gn("boolean",!0);G.Function=new oS;G.Date=new lS;G.Kind=new cS;G.NullableBoolean=new sS;function bp(t){return"kind"in t?G.String.is(t.kind)&&t.kind!=="multi":!1}function vp(t){return"kind"in t?G.String.is(t.kind)&&t.kind==="multi":!1}function Sp(t){return!("kind"in t)||t.kind===null||t.kind===void 0}function Pi(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=>Pi(n,[...e,t])).map(n=>n===void 0?"null":n).join(",")}]`:`{${Object.keys(t).sort().map(n=>{let r=Pi(t[n],[...e,t]);if(r!==void 0)return`${JSON.stringify(n)}:${r}`}).filter(n=>n!==void 0).join(",")}}`}var Ga="user";function Dh(t){return t.includes("%")||t.includes(":")?t.replace(/%/g,"%25").replace(/:/g,"%3A"):t}function uS(t){return t&&G.Object.is(t)}function Yh(t){return G.Kind.is(t)}function Kh(t){return G.String.is(t)&&t!==""}function Ea(t,e=!1){return t?t.map(n=>new xn(n,e)):[]}function hS(t){return t!=null}function pS(t){let e=fe(st({},t.custom||[]),{kind:"user",key:String(t.key)});if(hS(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 Vn=class wt{constructor(e,n,r){this.C=!1,this.it=!1,this.Xt=!1,this.$={},this.kind=n,this.valid=e,this.message=r}static b(e,n){return new wt(!1,e,n)}static Re(e,n){if(!(!n||!e.isValid))return e.depth===1&&e.getComponent(0)==="anonymous"?!!(n!=null&&n.anonymous):e.get(n)}Qt(e){if(this.C)return this.$[e];if(this.kind===e)return this.y}static Me(e){let n=Object.keys(e).filter(c=>c!=="kind"),r=n.every(Yh);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 uS(h)?(c[l]=h,i[l]=Ea((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=>Kh(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=fe(st({},s[c]),{kind:c}),l.nt=i,l.it=c==="user",l}let a=new wt(!0,e.kind);return a.$=s,a.nt=i,a.C=!0,a}static Fe(e){var n;let{key:r,kind:i}=e,o=Yh(i),s=Kh(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=Ea((n=e._meta)==null?void 0:n.privateAttributes),c=new wt(!0,i);return c.it=i==="user",c.y=e,c.nt={[i]:a},c}static Ue(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.it=!0,n.Xt=!0,n.y=pS(e),n.nt={user:Ea(e.privateAttributeNames,!0)},n}static fromLDContext(e){return e?bp(e)?wt.Fe(e):vp(e)?wt.Me(e):Sp(e)?wt.Ue(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=Ga){return e.isKind?this.kinds:wt.Re(e,this.Qt(n))}key(e=Ga){var n;return(n=this.Qt(e))==null?void 0:n.key}get isMultiKind(){return this.C}get canonicalKey(){return this.it?this.y.key:this.C?Object.keys(this.$).sort().map(e=>`${e}:${Dh(this.$[e].key)}`).join(":"):`${this.kind}:${Dh(this.y.key)}`}get kinds(){return this.C?Object.keys(this.$):[this.kind]}get kindsAndKeys(){return this.C?Object.entries(this.$).reduce((e,[n,r])=>(e[n]=r.key,e),{}):{[this.kind]:this.y.key}}privateAttributes(e){var n;return((n=this.nt)==null?void 0:n[e])||[]}getContexts(){return this.C?Object.entries(this.$):[[this.kind,this.y]]}get legacy(){return this.Xt}canonicalUnfilteredJson(){if(this.valid){if(this.yt)return this.yt;try{this.yt=Pi(wt.toLDContext(this))}catch(e){}return this.yt}}};Vn.UserKind=Ga;var dS=["key","kind","_meta","anonymous"].map(t=>new xn(t,!0)),fS=["name","ip","firstName","lastName","email","avatar","country"];function mS(t,e){return t.depth===e.length&&e.every((n,r)=>n===t.getComponent(r))}function yS(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=>mS(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 gS=class{constructor(t,e){this.Ve=t,this.je=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.te(t,n[0][1],n[0][0],e);let r={kind:"multi"};return n.forEach(([i,o])=>{r[i]=this.te(t,o,i,e)}),r}He(t,e,n,r){return(r?Object.keys(e).map(i=>new xn(i,!0)):[...this.je,...t.privateAttributes(n)]).filter(i=>!dS.some(o=>o.compare(i)))}te(t,e,n,r){let i=this.Ve||r&&e.anonymous===!0,{cloned:o,excluded:s}=yS(e,this.He(t,e,n,i));return t.legacy&&fS.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}},_h=30*1e3,bS=.5,vS=class{constructor(t,e,n=Math.random){this.Be=e,this.ze=n,this.vt=0,this.ee=Math.max(1,t),this.Ge=Math.ceil(Math.log2(_h/this.ee))}I(){let t=Math.min(this.vt,this.Ge),e=this.ee*2**t;return Math.min(e,_h)}Ke(t){return t-Math.trunc(this.ze()*bS*t)}success(t=Date.now()){this.wt=t}fail(t=Date.now()){this.wt!==void 0&&t-this.wt>this.Be&&(this.vt=0),this.wt=void 0;let e=this.Ke(this.I());return this.vt+=1,e}},Hh;(function(t){t[t.Valid=0]="Valid",t[t.Initializing=1]="Initializing",t[t.Interrupted=2]="Interrupted",t[t.Closed=3]="Closed"})(Hh||(Hh={}));var Mi=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=r}},La=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=r}},AF=120*1e3,JF=300*1e3,Kt;(function(t){t.Unknown="UNKNOWN",t.NetworkError="NETWORK_ERROR",t.ErrorResponse="ERROR_RESPONSE",t.InvalidData="INVALID_DATA"})(Kt||(Kt={}));var Fi;(function(t){t[t.Disabled=0]="Disabled",t[t.Enabled=1]="Enabled"})(Fi||(Fi={}));var Nn;(function(t){t[t.AnalyticsEvents=0]="AnalyticsEvents",t[t.DiagnosticEvent=1]="DiagnosticEvent"})(Nn||(Nn={}));var $e;(function(t){t[t.Succeeded=0]="Succeeded",t[t.Failed=1]="Failed",t[t.FailedAndMustShutDown=2]="FailedAndMustShutDown"})($e||($e={}));function kn(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 SS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(Number(t))}function wS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(parseInt(t,10))}function IS(t){return typeof t=="symbol"?"NaN":String(parseFloat(t))}var Ra={s:t=>kn(t),d:t=>SS(t),i:t=>wS(t),f:t=>IS(t),j:t=>kn(t),o:t=>kn(t),O:t=>kn(t),c:()=>""};function Xa(...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 Ra&&t.length){let a=t.shift();r+=(e=Ra[s])==null?void 0:e.call(Ra,a)}else s==="%"?r+="%":r+=`%${s}`;i+=2}}else r+=o,i+=1}return t.length&&(r.length&&(r+=" "),r+=t.map(kn).join(" ")),r}return t.map(kn).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 TS=["debug","info","warn","error","none"],Pa=class wp{static get(){return new wp({})}constructor(e){var n,r,i;if(this.Qe=(r=Vt[(n=e.level)!=null?n:"info"])!=null?r:Vt.info,this.ti=(i=e.name)!=null?i:"LaunchDarkly",this.ae=e.formatter,typeof e.destination=="object")this.oe={[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.oe={[Vt.debug]:o,[Vt.info]:o,[Vt.warn]:o,[Vt.error]:o}}}ei(...e){var n;try{return this.ae?(n=this.ae)==null?void 0:n.call(this,...e):Xa(...e)}catch(r){return Xa(...e)}}ii(e,n){try{e(n)}catch(r){console.error(n)}}k(e,n){var r;if(e>=this.Qe){let i=`${TS[e]}: [${this.ti}]`;try{let o=(r=this.oe)==null?void 0:r[e];o?this.ii(o,`${i} ${this.ei(...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)}},ES={error:G.Function,warn:G.Function,info:G.Function,debug:G.Function},Ip=class{constructor(t,e){Object.entries(ES).forEach(([n,r])=>{if(!r.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.ni=e}k(t,e){try{this.t[t](...e)}catch(n){this.ni[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)}},Tp=t=>{let e=new Pa({level:"info",destination:console.error,formatter:Xa});return t?new Ip(t,e):e},We=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`}},RS=/^(\w|\.|-)+$/,CS=G.stringMatchingRegex(RS),ZS={is:(t,e)=>CS.is(t)?t.length>64?{valid:!1,message:We.tagValueTooLong(e)}:{valid:!0}:{valid:!1,message:We.invalidTagValue(e)}},kS=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}=ZS.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(" "))}},VS=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 Ca(t){return t.replace(/\/+$/,"")}function Ma(t){return t.replace(/^\/+/,"").replace(/\?$/,"")}var Ai=class Ep{constructor(e,n,r=Ep.DEFAULT_EVENTS,i="/bulk",o="/diagnostic",s=!0,a){this.streaming=Ca(e),this.polling=Ca(n),this.events=Ca(r),this.analyticsEventPath=i,this.diagnosticEventPath=o,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}};Ai.DEFAULT_EVENTS="https://events.launchdarkly.com";function Fa(t,e=[]){if(e.length===0)return t;let n=e.map(({key:r,value:i})=>`${r}=${i}`);return`${t}?${n.join("&")}`}function xS(t,e,n){let r=Ma(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Fa(`${t.streaming}/${r}`,i)}function NS(t,e,n=[]){let r=Ma(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Fa(`${t.polling}/${r}`,i)}function zh(t,e,n=[]){let r=Ma(e);return Fa(`${t.events}/${r}`,n)}var Rp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},OS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},Cp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function Yi(t){return t>=400&&t<500?t===400||t===408||t===429:!0}function GS(t){return t===413?!0:Yi(t)}function LS(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 Cp(s))},t*1e3)}),cancel:()=>{r(),clearTimeout(n)}}}function Zp(t){return t==null?t:JSON.parse(JSON.stringify(t))}function Za(t){return Math.trunc(t*1e3)}var XS=t=>JSON.stringify(t)==="{}",Aa=(t,e)=>t&&Object.entries(t).reduce((n,[r,i])=>(i&&!XS(i)&&!(e!=null&&e.includes(r))&&(n[r]=typeof i=="object"?Aa(i,e):i),n),{});function Xi(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(!Xi(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(!Xi(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(!Xi(t[o],e[o]))return!1}return!0}return t!==t&&e!==e}function WS(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 On(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 kp({status:t}){return t?Yi(t):!0}var Bh=(t,e)=>e.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Vp=async(t=1e3)=>new Promise(e=>{setTimeout(e,t)}),US=class{constructor(t,e,n){this.p=e,this.si=n,this.bt=[],this.ce=Date.now(),this.le=this.ce,this.ue={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.ue,creationDate:this.ce,sdk:r,configuration:this.si,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.bt.push(r)}createStatsEventAndReset(t,e,n){let r=Date.now(),i={kind:"diagnostic",id:this.ue,creationDate:r,dataSinceDate:this.le,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.bt};return this.bt=[],this.le=r,i}},Wa;(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"})(Wa||(Wa={}));var PS=Wa,xp=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};xp.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var MS=class{constructor(t,e){let{basicConfiguration:n,platform:r}=t,{serviceEndpoints:{analyticsEventPath:i,diagnosticEventPath:o}}=n,{crypto:s,requests:a}=r;this.ri=st({},e),this.he=zh(n.serviceEndpoints,i,[]),this.ai=zh(n.serviceEndpoints,o,[]),this.H=a,this.oi=s}async st(t,e,n,r){let i={status:$e.Succeeded},o=fe(st({},this.ri),{"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.H.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 Rp(On({status:a,message:"some events were dropped"},"event posting")),!Yi(a))return GS(a)?i.status=$e.Failed:i.status=$e.FailedAndMustShutDown,i.error=s,i}catch(a){s=a}return s&&!r?(i.status=$e.Failed,i.error=s,i):(await Vp(),this.st(t,this.he,n,!1))}async sendEventData(t,e){let n=t===Nn.AnalyticsEvents?this.oi.randomUUID():void 0,r=t===Nn.AnalyticsEvents?this.he:this.ai;return this.st(e,r,n,!0)}};function Ji(t){return t.kind==="feature"}function FS(t){return t.kind==="identify"}function AS(t){return t.kind==="migration_op"}var JS=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 DS(t){return`${t.key}:${t.variation!==null&&t.variation!==void 0?t.variation:""}:${t.version!==null&&t.version!==void 0?t.version:""}`}var Np=class{constructor(t=!1,e){this.ci=t,this.x=e,this.Y=0,this.rt=0,this.at={},this.ot={}}summarizeEvent(t){if(Ji(t)&&!t.excludeFromSummaries){this.y||(this.y=t.context);let e=DS(t),n=this.at[e],r=this.ot[t.key];r||(r=new Set,this.ot[t.key]=r),t.context.kinds.forEach(i=>r.add(i)),n?n.increment():this.at[e]=new JS(1,t.key,t.value,t.default,t.version,t.variation),(this.Y===0||t.creationDate<this.Y)&&(this.Y=t.creationDate),t.creationDate>this.rt&&(this.rt=t.creationDate)}}getSummary(){var t;let e=Object.values(this.at).reduce((r,i)=>{let o=r[i.key];o||(o={default:i.default,counters:[],contextKinds:[...this.ot[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.Y,endDate:this.rt,features:e,kind:"summary",context:this.y!==void 0&&this.ci?(t=this.x)==null?void 0:t.filter(this.y):void 0};return this.li(),n}li(){this.Y=0,this.rt=0,this.at={},this.ot={}}},YS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}},KS=class{constructor(t,e){this.x=t,this.t=e,this.Z={}}summarizeEvent(t){var e;if(Ji(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.Z[n];r||(this.Z[n]=new Np(!0,this.x),r=this.Z[n]),r.summarizeEvent(t)}}getSummaries(){let t=this.Z;return this.Z={},Object.values(t).map(e=>e.getSummary())}};function Wi(t){let e=Math.trunc(t);return e===1?!0:e===0?!1:Math.floor(Math.random()*e)===0}function _S(t){return t.getSummaries!==void 0}var HS=class{constructor(t,e,n,r,i,o=!0,s=!1){this.e=t,this.ct=r,this.S=i,this.lt=[],this.de=0,this.kt=0,this.xt=0,this.St=!1,this.fe=0,this.Lt=!1,this.Ct=null,this.ui=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.pe=new MS(e,n),this.x=new gS(t.allAttributesPrivate,t.privateAttributes.map(a=>new xn(a))),s?this.X=new KS(this.x,this.t):this.X=new Np,o&&this.start()}start(){var t,e;if(((t=this.ct)==null?void 0:t.flushInterval)!==void 0&&(this.Ct=setInterval(()=>{var n;(n=this.ct)==null||n.flush()},this.ct.flushInterval*1e3)),this.hi=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.ge(n),this.me=setInterval(()=>{let r=this.S.createStatsEventAndReset(this.kt,this.xt,this.fe);this.kt=0,this.xt=0,this.ge(r)},this.e.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}ge(t){this.pe.sendEventData(Nn.DiagnosticEvent,t)}close(){clearInterval(this.hi),this.Ct&&clearInterval(this.Ct),this.me&&clearInterval(this.me)}async flush(){var t;if(this.Lt)throw new YS("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.lt;if(this.lt=[],_S(this.X))this.X.getSummaries().forEach(n=>{Object.keys(n.features).length&&e.push(n)});else{let n=this.X.getSummary();Object.keys(n.features).length&&e.push(n)}e.length&&(this.fe=e.length,(t=this.t)==null||t.debug("Flushing %d events",e.length),await this.st(e))}sendEvent(t){var e;if(this.Lt)return;if(AS(t)){if(Wi(t.samplingRatio)){let a=fe(st({},t),{context:t.context?this.x.filter(t.context):void 0});a.samplingRatio===1&&delete a.samplingRatio,this.ut(a)}return}this.X.summarizeEvent(t);let n=Ji(t),r=n&&t.trackEvents||!n,i=this.di(t),o=FS(t),s=(e=this.ct)==null?void 0:e.processContext(t.context);s||o||(this.xt+=1),s&&!o&&this.ut(this.It({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),r&&Wi(t.samplingRatio)&&this.ut(this.It(t,!1)),i&&Wi(t.samplingRatio)&&this.ut(this.It(t,!0))}It(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}}ut(t){var e;this.lt.length<this.ui?(this.lt.push(t),this.St=!1):(this.St||(this.St=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.kt+=1)}di(t){return Ji(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.de&&t.debugEventsUntilDate>Date.now()}async st(t){let e=await this.pe.sendEventData(Nn.AnalyticsEvents,t);if(e.status===$e.FailedAndMustShutDown&&(this.Lt=!0),e.serverTime&&(this.de=e.serverTime),e.error)throw e.error}},Op=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}},Ua=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)}},Gp=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},zS=class{close(){}async flush(){}sendEvent(){}},BS=class{constructor(t){this.At=t}evalEvent(t){var e;return new Ua(this.At,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.At||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new Ua(this.At,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new Gp(t,1)}customEvent(t,e,n,r,i=1){return new Op(e,t,n!=null?n:void 0,r!=null?r:void 0,i)}},jh="FDv1Fallback";function jS(t){return{fi:t,ye:"",useSelector(e){return this.ye=e,this},processFullTransfer(e){let n=[{event:"server-intent",data:{payloads:[{id:jh,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.ye,version:1,id:jh}}),this.fi.processEvents(n)}}}var Lp=class{constructor(t,e,n){this.pi=t,this.m=e,this.t=n,this.n=[],this.N=void 0,this.B=!1,this.z=[],this.gi=r=>{var i;if(this.Pt(),!r.payloads.length)return;let o=r.payloads[0];switch(o==null?void 0:o.intentCode){case"xfer-full":this.B=!0;break;case"xfer-changes":this.B=!1;break;case"none":this.B=!1,this.mi(o);break;default:(i=this.t)==null||i.warn(`Unable to process intent code '${o==null?void 0:o.intentCode}'.`);return}this.N=o==null?void 0:o.id},this.yi=r=>{var i;if(!this.N||!r.kind||!r.key||!r.version||!r.object)return;let o=this.vi(r.kind,r.object);if(!o){(i=this.t)==null||i.warn(`Unable to process object for kind: '${r.kind}'`);return}this.z.push({kind:r.kind,key:r.key,version:r.version,object:o})},this.wi=r=>{!this.N||!r.kind||!r.key||!r.version||this.z.push({kind:r.kind,key:r.key,version:r.version,deleted:!0})},this.mi=r=>{if(!r.id||!r.target)return;let i={id:r.id,version:r.target,basis:!1,updates:[]};this.n.forEach(o=>o(i)),this.ve()},this.Ei=r=>{if(!this.N||r.state===null||r.state===void 0||!r.version){this.Pt();return}let i={id:this.N,version:r.version,state:r.state,basis:this.B,updates:this.z};this.n.forEach(o=>o(i)),this.ve()},this.Di=r=>{var i;(i=this.t)==null||i.info(`Goodbye was received from the LaunchDarkly connection with reason: ${r.reason}.`),this.Pt()},this.bi=r=>{var i;(i=this.t)==null||i.info(`An issue was encountered receiving updates for payload ${this.N} with reason: ${r.reason}.`),this.ki()}}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=>{switch(e.event){case"server-intent":{this.gi(e.data);break}case"put-object":{this.yi(e.data);break}case"delete-object":{this.wi(e.data);break}case"payload-transferred":{this.Ei(e.data);break}case"goodbye":{this.Di(e.data);break}case"error":{this.bi(e.data);break}}})}vi(t,e){var n,r;return(r=(n=this.pi)[t])==null?void 0:r.call(n,e)}ve(){this.B=!1,this.z=[]}ki(){this.z=[]}Pt(){this.N=void 0,this.B=!1,this.z=[]}},QS=class{constructor(t,e,n,r){this.m=n,this.t=r,this.G(t,"server-intent"),this.G(t,"put-object"),this.G(t,"delete-object"),this.G(t,"payload-transferred"),this.G(t,"goodbye"),this.G(t,"error"),this.Ot=new Lp(e,n,r)}addPayloadListener(t){this.Ot.addPayloadListener(t)}removePayloadListener(t){this.Ot.removePayloadListener(t)}G(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.Ot.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.m)==null||s.call(this,Kt.InvalidData,"Malformed data in EventStream.")}}else(a=this.m)==null||a.call(this,Kt.Unknown,"Event from EventStream missing data.")})}};function $S(t){if(t){let e=Object.keys(t).find(n=>n.toLowerCase()==="x-ld-envid");if(e)return{environmentId:t[e]}}}var Qh="unknown plugin";function Di(t,e){try{return e.getMetadata().name||Qh}catch(n){return t.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),Qh}}function qS(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 ${Di(t,i)} returned undefined from getHooks.`):s&&s.length>0&&r.push(...s)}catch(s){t.error(`Exception thrown getting hooks for plugin ${Di(t,i)}. Unable to get hooks.`)}}),r}function tw(t,e,n,r){r.forEach(i=>{try{i.register(n,e)}catch(o){t.error(`Exception thrown registering plugin ${Di(t,i)}.`)}})}var pe=Object.freeze({__proto__:null,ClientMessages:xp,DiagnosticsManager:US,ErrorKinds:PS,EventFactoryBase:BS,EventProcessor:HS,FDv1PayloadAdaptor:jS,InputCustomEvent:Op,InputEvalEvent:Ua,InputIdentifyEvent:Gp,NullEventProcessor:zS,PayloadProcessor:Lp,PayloadStreamReader:QS,canonicalize:Pi,initMetadataFromHeaders:$S,isLegacyUser:Sp,isMultiKind:vp,isSingleKind:bp,safeGetHooks:qS,safeGetName:Di,safeRegisterPlugins:tw,shouldSample:Wi}),ew={Initializing:"INITIALIZING",Valid:"VALID",Interrupted:"INTERRUPTED",SetOffline:"SET_OFFLINE",Closed:"CLOSED"};function nw(t){return t>=200&&t<=299}var $h=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}};function qh(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=NS(e,f,m);return{async requestPayload(){let v;try{let b=await r.fetch(d,{method:h,headers:p,body:u});if(nw(b.status))return await b.text();v=b.status}catch(b){throw new $h(b==null?void 0:b.message)}throw new $h(`Unexpected status code: ${v}`,v)}}}var tp=new Error("Task has already been executed or shed. This is likely an implementation error. The task will not be executed again.");function rw(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(tp)),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(tp)),s=!0,o.then(a=>{r({status:"shed"},a)})},promise:i,sheddable:n}}function iw(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=rw(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 ow={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},sw=300,Xp="https://clientsdk.launchdarkly.com",Wp="https://clientstream.launchdarkly.com";function aw(t){return t instanceof Ip?t:Tp(t)}var lw=class{constructor(t={},e={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var n,r,i;this.logger=Tp(),this.baseUri=Xp,this.eventsUri=Ai.DEFAULT_EVENTS,this.streamUri=Wp,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=sw,this.hooks=[],this.inspectors=[],this.logger=aw(t.logger),this.xi(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new Ai(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 kS({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}xi(t){let e=[];return Object.entries(t).forEach(([n,r])=>{let i=ow[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(We.wrongOptionTypeBoolean(n,typeof r)),this[n]=!!r;else if(o==="boolean | undefined | null")e.push(We.wrongOptionTypeBoolean(n,typeof r)),typeof r!="boolean"&&typeof r!="undefined"&&r!==null&&(this[n]=!!r);else if(i instanceof yp&&G.Number.is(r)){let{min:s}=i;e.push(We.optionBelowMinimum(n,r,s)),this[n]=s}else e.push(We.wrongOptionType(n,i.getType(),typeof r))}else e.push(We.unknownOption(n))}),e}};async function Up(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 Pp=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 Mp(t){return async e=>Up(t.createHash("sha256").update(e),"base64")}var de=async t=>t;async function yr(t){return(await Promise.all(t.map(e=>e.transform(e.value)))).join("_")}async function cw(t,e){return yr([{value:"LaunchDarkly",transform:de},{value:e,transform:Mp(t)}])}async function uw(t){return yr([{value:"LaunchDarkly",transform:de},{value:"AnonymousKeys",transform:de},{value:t,transform:de}])}async function hw(t){return yr([{value:"LaunchDarkly",transform:de},{value:"ContextKeys",transform:de},{value:t,transform:de}])}async function pw(t){return yr([{value:t,transform:de},{value:"ContextIndex",transform:de}])}async function ep(t,e,n){return yr([{value:e,transform:de},{value:n.canonicalKey,transform:Mp(t)}])}var{isLegacyUser:dw,isSingleKind:ka,isMultiKind:np}=pe,Fp="1.0",fw=t=>{let e=t,{kind:n}=e,r=dp(e,["kind"]);return{kind:"multi",[n]:r}},mw=async({crypto:t,info:e},{applicationInfo:n})=>{var r;let{ld_application:i}=e.platformData(),o=(r=Aa(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(fe(st({},o),{id:s}),a?{version:a}:{}),c?{name:c}:{}),l?{versionName:l}:{}),o.key=await Up(t.createHash("sha256").update(s),"base64"),o.envAttributesVersion=o.envAttributesVersion||Fp,o}},yw=async t=>{var e,n,r,i;let{ld_device:o,os:s}=t.info.platformData(),a=(e=Aa(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 hw("ld_device");return a.key=await Pp(h,t),a.envAttributesVersion=a.envAttributesVersion||Fp,a}},gw=async(t,e,n)=>{if(dw(t))return t;let r,i;if(ka(t)&&t.kind!=="ld_application"||np(t)&&!t.ld_application?r=await mw(e,n):n.logger.warn("Not adding ld_application environment attributes because it already exists."),ka(t)&&t.kind!=="ld_device"||np(t)&&!t.ld_device?i=await yw(e):n.logger.warn("Not adding ld_device environment attributes because it already exists."),r||i){let o=ka(t)?fw(t):t;return st(st(st({},o),r?{ld_application:r}:{}),i?{ld_device:i}:{})}return t};function bw(){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:vw,isMultiKind:Sw,isSingleKind:ww}=pe,Ja=async(t,e,n)=>{let{anonymous:r,key:i}=e;if(r&&!i){let o=await uw(t);e.key=await Pp(o,n)}},Iw=async(t,e)=>{await Ja(t.kind,t,e)},Tw=async(t,e)=>{let n=t,{kind:r}=n,i=dp(n,["kind"]);return Promise.all(Object.entries(i).map(([o,s])=>Ja(o,s,e)))},Ew=async(t,e)=>{await Ja("user",t,e)},Rw=async(t,e)=>{let n=Zp(t);return ww(n)&&await Iw(n,e),Sw(n)&&await Tw(n,e),vw(n)&&await Ew(n,e),n},Cw=t=>({customBaseURI:t.serviceEndpoints.polling!==Xp,customStreamURI:t.serviceEndpoints.streaming!==Wp,customEventsURI:t.serviceEndpoints.events!==Ai.DEFAULT_EVENTS,eventsCapacity:t.capacity,eventsFlushIntervalMillis:Za(t.flushInterval),reconnectTimeMillis:Za(t.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:Za(t.diagnosticRecordingInterval),allAttributesPrivate:t.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Zw=(t,e,n)=>{if(e.sendEvents&&!e.diagnosticOptOut)return new pe.DiagnosticsManager(t,n,Cw(e))};function rp(t,e){return{value:e!=null?e:null,variationIndex:null,reason:{kind:"ERROR",errorKind:t}}}function ip(t,e,n){return st({value:t,variationIndex:e!=null?e:null},n!==void 0&&{reason:n})}var kw=(t,e,n,r,i)=>{if(e.sendEvents)return new pe.EventProcessor(fe(st({},e),{eventsCapacity:e.capacity}),new VS(t,e,n),r,void 0,i,!1,!0)},op=class extends pe.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})}},Va=class Ap{constructor(){this.container={index:new Array}}static fromJson(e){let n=new Ap;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)):[]}},Vw=class{constructor(t,e,n,r,i,o,s=()=>Date.now()){this.p=t,this.Tt=e,this.Si=n,this.P=r,this.w=i,this.t=o,this.Li=s,this.we=pw(this.Tt)}async init(t,e){this.w.init(t,e),await this.Ee(t)}async upsert(t,e,n){return this.w.upsert(t,e,n)?(await this.Ee(t),!0):!1}async loadCached(t){var e,n,r,i;let o=await ep(this.p.crypto,this.Tt,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 Ci(){var t;if(this.K!==void 0)return this.K;let e=await((t=this.p.storage)==null?void 0:t.get(await this.we));if(!e)return this.K=new Va,this.K;try{this.K=Va.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.K=new Va}return this.K}async Ee(t){var e,n;let r=await this.Ci(),i=await ep(this.p.crypto,this.Tt,t);r.notice(i,this.Li());let o=r.prune(this.Si);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.we,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 xw(){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 Nw(t,e){let n=[];return Object.entries(t).forEach(([r,i])=>{let o=e[r];(!o||!Xi(i,o))&&n.push(r)}),Object.keys(e).forEach(r=>{t[r]||n.push(r)}),n}function Ow(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=Nw(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 Gw=class{constructor(t,e,n,r,i=()=>Date.now()){this.P=xw(),this.w=Ow(this.P,r),this.$t=this.Ii(t,e,n,r,i)}async Ii(t,e,n,r,i=()=>Date.now()){let o=await cw(t.crypto,e);return new Vw(t,o,n,this.P,this.w,r,i)}get(t){return this.r&&Object.prototype.hasOwnProperty.call(this.r,t)?this.Nt(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.Nt(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.$t).init(t,e)}async upsert(t,e,n){return(await this.$t).upsert(t,e,n)}async loadCached(t){return(await this.$t).loadCached(t)}on(t){this.w.on(t)}off(t){this.w.off(t)}Nt(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.Nt(n)}),t}getDebugOverride(){return{setOverride:this.setOverride.bind(this),removeOverride:this.removeOverride.bind(this),clearAllOverrides:this.clearAllOverrides.bind(this),getAllOverrides:this.getAllOverrides.bind(this)}}},sp="unknown hook",Jp="beforeEvaluation",Dp="afterEvaluation",Lw="afterTrack";function gr(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 br(t,e){try{return e.getMetadata().name||sp}catch(n){return t.error("Exception thrown getting metadata for hook. Unable to get hook name."),sp}}function Xw(t,e,n){return e.map(r=>gr(t,Jp,br(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeEvaluation)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Ww(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];gr(t,Dp,br(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 Uw(t,e,n){return e.map(r=>gr(t,Jp,br(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeIdentify)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Pw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];gr(t,Dp,br(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 Mw(t,e,n){for(let r=e.length-1;r>=0;r-=1){let i=e[r];gr(t,Lw,br(t,i),()=>{var o;return(o=i==null?void 0:i.afterTrack)==null?void 0:o.call(i,n)},void 0)}}var Fw=class{constructor(t,e){this.t=t,this.R=[],this.R.push(...e)}withEvaluation(t,e,n,r){if(this.R.length===0)return r();let i=[...this.R],o={flagKey:t,context:e,defaultValue:n},s=Xw(this.t,i,o),a=r();return Ww(this.t,i,o,s,a),a}identify(t,e){let n=[...this.R],r={context:t,timeout:e},i=Uw(this.t,n,r);return o=>{Pw(this.t,n,r,i,o)}}addHook(t){this.R.push(t)}afterTrack(t){if(this.R.length===0)return;let e=[...this.R];Mw(this.t,e,t)}};function Aw(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 Jw(t,e){return`an inspector: "${e}" of an invalid type (${t}) was configured`}function Dw(t,e){return`an inspector: "${e}" of type: "${t}" generated an exception`}function Yw(t,e){let n=!1,r={method:(...i)=>{try{t.method(...i)}catch(o){n||(n=!0,e.warn(Dw(r.type,r.name)))}},type:t.type,name:t.name,synchronous:t.synchronous};return r}var Yp="flag-used",Kp="flag-details-changed",_p="flag-detail-changed",Hp="client-identity-changed",Kw=[Yp,Kp,_p,Hp];function _w(t,e){let n=Kw.includes(t.type)&&t.method&&typeof t.method=="function";return n||e.warn(Jw(t.type,t.name)),n}var Hw=class{constructor(t,e){this.W=[];let n=t.filter(r=>_w(r,e));this.W=n.map(r=>Yw(r,e))}hasInspectors(){return this.W.length!==0}onFlagUsed(t,e,n){this.W.forEach(r=>{r.type===Yp&&r.method(t,e,n)})}onFlagsChanged(t){this.W.forEach(e=>{e.type===Kp&&e.method(t)})}onFlagChanged(t,e){this.W.forEach(n=>{n.type===_p&&n.method(t,e)})}onIdentityChanged(t){this.W.forEach(e=>{e.type===Hp&&e.method(t)})}},zw=class{constructor(t){this.t=t,this.n=new Map}on(t,e){var n;this.n.has(t)?(n=this.n.get(t))==null||n.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)}}Ai(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.Ai(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 Bw(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:ap,ErrorKinds:lp}=pe,jw=5,Qw=class{constructor(t,e,n,r,i,o){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.a=bw(),this.Rt=15,this.T=new op(!1),this.ht=new op(!0),this.Mt=!1,this.Pi=iw(),!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 lw(r,o),this.logger=this.e.logger,this.De=WS(this.sdkKey,this.platform.info,this.e.tags,this.e.serviceEndpoints.includeAuthorizationHeader,this.e.userAgentHeaderName),this.M=new Gw(this.platform,t,this.e.maxCachedContexts,this.e.logger),this.S=Zw(t,this.e,n),this.E=kw(t,this.e,n,this.De,this.S),this.emitter=new zw,this.emitter.on("error",(a,c)=>{this.logger.error(`error: ${c}, context: ${JSON.stringify(a)}`)}),this.M.on((a,c,l)=>{this.Oi(c,l);let u=Vn.toLDContext(a);this.emitter.emit("change",u,c),c.forEach(h=>{this.emitter.emit(`change:${h}`,u)})}),this.dataManager=i(this.M,this.e,this.De,this.emitter,this.S);let s=[...this.e.hooks];if(this.environmentMetadata=Bw(this.sdkKey,this.platform,this.e),this.e.getImplementationHooks(this.environmentMetadata).forEach(a=>{s.push(a)}),this.F=new Fw(this.logger,s),this.Q=new Hw(this.e.inspectors,this.logger),this.Q.hasInspectors()&&this.F.addHook(Aw(this.Q)),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.M.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()?Zp(this.a.getUnwrappedContext()):void 0}getInternalContext(){return this.a.getContext()}presetFlags(t){this.M.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 Cp(`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:jw,o=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;i>this.Rt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Rt} seconds. We recommend a timeout of less than ${this.Rt} seconds.`);let s=this.Pi.execute({before:async()=>{let c=await Rw(t,this.platform);this.autoEnvAttributes===Fi.Enabled&&(c=await gw(c,this.platform,this.e));let l=Vn.fromLDContext(c);if(l.valid){let u=this.F.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=LS(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(ap.MissingContextKeyNoEvent);return}n!==void 0&&!G.Number.is(n)&&((r=this.logger)==null||r.warn(ap.invalidMetricValue(typeof n))),(i=this.E)==null||i.sendEvent(this.e.trackEventModifier(this.T.customEvent(t,this.a.getContext(),e,n))),this.F.afterTrack({key:t,context:this.a.getUnwrappedContext(),data:e,metricValue:n})}dt(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.M.get(t);if(h===void 0||h.flag.deleted){let b=e!=null?e:null;return(o=this.logger)==null||o.warn(`Unknown feature flag "${t}"; returning default value ${b}.`),l&&((s=this.E)==null||s.sendEvent(this.T.unknownFlagEvent(t,b,u))),rp(lp.FlagNotFound,e)}let{reason:p,value:f,variation:m,prerequisites:d}=h.flag;if(r){let[b,I]=r(f);if(!b){l&&((a=this.E)==null||a.sendEvent(n.evalEventClient(t,e,e,h.flag,u,p)));let R=new OS(`Wrong type "${I}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.a.getUnwrappedContext(),R),rp(lp.WrongType,e)}}let v=ip(f,m,p);return f==null&&(this.logger.debug("Result value is null. Providing default value."),v.value=e),d==null||d.forEach(b=>{this.dt(b,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.F.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.dt(t,e,this.T));return n}variationDetail(t,e){return this.F.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.dt(t,e,this.ht))}_(t,e,n,r){return this.F.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.dt(t,e,n,r))}boolVariation(t,e){return this._(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._(t,e,this.T,n=>[G.Number.is(n),G.Number.getType()]).value}stringVariation(t,e){return this._(t,e,this.T,n=>[G.String.is(n),G.String.getType()]).value}boolVariationDetail(t,e){return this._(t,e,this.ht,n=>[G.Boolean.is(n),G.Boolean.getType()])}numberVariationDetail(t,e){return this._(t,e,this.ht,n=>[G.Number.is(n),G.Number.getType()])}stringVariationDetail(t,e){return this._(t,e,this.ht,n=>[G.String.is(n),G.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.F.addHook(t)}setEventSendingEnabled(t,e){var n,r,i,o;this.Mt!==t&&(this.Mt=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.Mt||((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.M).getDebugOverride)==null?void 0:e.call(t)}Oi(t,e){if(!this.Q.hasInspectors())return;let n={};t.forEach(r=>{let i=this.M.get(r);if(i!=null&&i.flag&&!i.flag.deleted){let{reason:o,value:s,variation:a}=i.flag;n[r]=ip(s,a,o)}else n[r]={value:void 0,variationIndex:null}}),e==="init"?this.Q.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([r,i])=>{this.Q.onFlagChanged(r,i)})}};function $w(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 ${pe.safeGetName(t,r)}.`)}})}function qw(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:fe(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 tI(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 cp(t){t==null||t.debug("Poll completed after the processor was closed. Skipping processing.")}var eI=class{constructor(t,e,n,r,i){this.Ti=t,this.$i=e,this.Ni=n,this.m=r,this.t=i,this.u=!1}async be(){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.m)==null||m.call(this,new Mi(Kt.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.Ti.requestPayload();try{if(this.u){cp(this.t);return}let p=JSON.parse(h);try{(e=this.Ni)==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){cp(this.t);return}let p=h;if(p.status!==void 0&&!Yi(p.status)){(r=this.t)==null||r.error(On(h,"polling request")),(i=this.m)==null||i.call(this,new Mi(Kt.ErrorResponse,p.message,p.status));return}(o=this.t)==null||o.error(On(h,"polling request","will retry"))}let l=Date.now()-c,u=Math.max(this.$i*1e3-l,0);(s=this.t)==null||s.debug("Elapsed: %d ms, sleeping for %d ms",l,u),this.Ft=setTimeout(()=>{this.be()},u)}start(){this.be()}stop(){this.Ft&&(clearTimeout(this.Ft),this.Ft=void 0),this.u=!0}close(){this.stop()}},nI=(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 La(Kt.InvalidData,"Malformed JSON data in event stream"))};function rI(t,e){e==null||e.debug(`Received ${t} event after processor was closed. Skipping processing.`)}function up(t){t==null||t.debug("Ping completed after processor was closed. Skipping processing.")}var iI=class{constructor(t,e,n,r,i,o,s,a,c){var l;this.Ri=t,this.Ut=e,this.n=n,this.H=r,this.Mi=o,this.S=s,this.m=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.Ut.withReasons&&h.push({key:"withReasons",value:"true"}),this.H=r,this.ke=st({},e.baseHeaders),this.t=c,this.Fi=xS(e.serviceEndpoints,u,h)}xe(){this.ft=Date.now()}Vt(t){this.ft&&this.S&&this.S.recordStreamInit(this.ft,!t,Date.now()-this.ft),this.ft=void 0}Ui(t){var e,n,r;return kp(t)?((r=this.t)==null||r.warn(On(t,"streaming request","will retry")),this.Vt(!1),this.xe(),!0):(this.Vt(!1),(e=this.m)==null||e.call(this,new La(Kt.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error(On(t,"streaming request")),!1)}start(){this.xe();let t;this.Ut.useReport?(this.ke["content-type"]="application/json",t={method:"REPORT",body:this.Ri}):t={};let e=this.H.createEventSource(this.Fi,fe(st({headers:this.ke},t),{errorFilter:n=>this.Ui(n),initialRetryDelayMillis:this.Ut.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3}));this.Se=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){rI(i,this.t);return}if((s=this.t)==null||s.debug(`Received ${i} event`),o!=null&&o.data){this.Vt(!0);let{data:c}=o,l=n(c);if(!l){nI(i,c,this.t,this.m);return}r(l)}else(a=this.m)==null||a.call(this,new La(Kt.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.Mi.requestPayload();try{if(this.u){up(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.m)==null||a.call(this,new Mi(Kt.InvalidData,"Malformed JSON data in ping polling response"))}}catch(l){if(this.u){up(this.t);return}let u=l;(c=this.m)==null||c.call(this,new Mi(Kt.ErrorResponse,u.message,u.status))}})}stop(){var t;(t=this.Se)==null||t.close(),this.Se=void 0,this.u=!0}close(){this.stop()}},oI=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=tI(a),this.q=qw(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.Vi=t}createPollingProcessor(t,e,n,r,i){let o=new eI(n,this.config.pollInterval,async s=>{await this.q.handlePut(e,s),r==null||r()},s=>{this.emitter.emit("error",t,s),this.q.handlePollingError(s),i==null||i(s)},this.logger);this.updateProcessor=this.Le(o,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,r,i){var o;let s=new iI(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.Vi)==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.q.handleStreamingError(a),i==null||i(a)},this.logger);this.updateProcessor=this.Le(s,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async r=>{await this.q.handlePut(t,r),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async r=>{this.q.handlePatch(t,r)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async r=>{this.q.handleDelete(t,r)}}),n}Le(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 zp(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 Ki(){return typeof document!==void 0}function Da(){return typeof window!==void 0}function Bp(t,e,n){return Ki()?(document.addEventListener(t,e,n),()=>{document.removeEventListener(t,e,n)}):()=>{}}function jp(t,e,n){return Ki()?(window.addEventListener(t,e,n),()=>{window.removeEventListener(t,e,n)}):()=>{}}function mr(){return Da()?window.location.href:""}function sI(){return Da()?window.location.search:""}function aI(){return Da()?window.location.hash:""}function lI(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function cI(){return Ki()?document.visibilityState:"visibile"}function uI(t){if(Ki())return document.querySelectorAll(t)}var hI="[BrowserDataManager]",pI=class extends oI{constructor(t,e,n,r,i,o,s,a,c,l){super(t,e,n,r,o,s,a,c,l),this.Xi=i,this.tt=void 0,this.jt=!1,this.tt=i.streaming}L(t,...e){this.logger.debug(`${hI} ${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.Ht=i==null?void 0:i.hash,i!=null&&i.bootstrap?this.ji(n,i,t):(await this.flagManager.loadCached(n)&&this.L("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Hi(n,t,e)),this.Bt()}async Bi(t){let e=JSON.stringify(Vn.toLDContext(t)),n=qh(e,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ht),r=3,i;for(let o=0;o<=r;o+=1)try{return await n.requestPayload()}catch(s){if(!kp(s))throw s;i=s,o<r&&(this.L(On(s,"initial poll request","will retry")),await Vp(1e3))}throw i}async Hi(t,e,n){var r,i;try{this.dataSourceStatusManager.requestStateUpdate(ew.Initializing);let o=await this.Bi(t);try{let s=this.createStreamListeners(t,e).get("put");s.processJson(s.deserializeData(o))}catch(s){this.dataSourceStatusManager.reportError(Kt.InvalidData,(r=s.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(Kt.NetworkError,(i=o.message)!=null?i:"unexpected network error",o.status),n(o)}}ji(t,e,n){let{bootstrapParsed:r}=e;r||(r=zp(this.logger,e.bootstrap)),this.flagManager.setBootstrap(t,r),this.L("Identify - Initialization completed from bootstrap"),n()}setForcedStreaming(t){this.tt=t,this.Bt()}setAutomaticStreamingState(t){this.jt=t,this.Bt()}Bt(){let t=this.tt||this.jt&&this.tt===void 0;this.L(`Updating streaming state. forced(${this.tt}) automatic(${this.jt})`),t?this.zi():this.Gi()}Gi(){var t;this.updateProcessor&&this.L("Stopping update processor."),(t=this.updateProcessor)==null||t.close(),this.updateProcessor=void 0}zi(){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.Ki(this.context)}Ki(t,e,n){var r;let i=Vn.toLDContext(t);(r=this.updateProcessor)==null||r.close();let o=JSON.stringify(Vn.toLDContext(t)),s=qh(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ht);this.createStreamingProcessor(i,t,s,e,n),this.updateProcessor.start()}};function dI(t){let e=Bp("visibilitychange",()=>{cI()==="hidden"&&t()}),n=jp("pagehide",t);return()=>{e(),n()}}function xa(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function fI(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(`^${xa(t.url)}/?$`).test(e);case"canonical":return new RegExp(`^${xa(t.url)}/?$`).test(i);case"substring":return new RegExp(`.*${xa(t.substring)}.*$`).test(i);case"regex":return new RegExp(t.pattern).test(i);default:return!1}}function mI(t,e){let n=[];return e.forEach(r=>{let i=t.target,{selector:o}=r,s=uI(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 yI=class{constructor(t,e){let n=t.filter(o=>{var s;return(s=o.urls)==null?void 0:s.some(a=>fI(a,mr(),sI(),aI()))}),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=>{mI(s,i).forEach(a=>{e(a)})};this.Ce=Bp("click",o)}}close(){var t;(t=this.Ce)==null||t.call(this)}},gI=300,bI=class{constructor(t){this.zt=mr();let e=()=>{let r=mr();r!==this.zt&&(this.zt=r,t())};this.Gt=setInterval(e,gI);let n=jp("popstate",e);this.Ie=()=>{n()}}close(){var t;this.Gt&&clearInterval(this.Gt),(t=this.Ie)==null||t.call(this)}},vI=class{constructor(t,e,n,r,i,o=s=>new bI(s)){this.H=e,this.qi=r,this.Pr=i,this.pt=[],this.Pe=!1,this.gt=`${n}/sdk/goals/${t}`,this.Ae=o(()=>{this.Wt()})}async initialize(){await this.Wi(),this.Wt()}startTracking(){this.Pe=!0,this.Wt()}Wt(){var t;this.Pe&&((t=this.Kt)==null||t.close(),this.pt&&this.pt.length&&(this.Kt=new yI(this.pt,e=>{this.Pr(mr(),e)})))}async Wi(){try{let t=await this.H.fetch(this.gt);this.pt=await t.json()}catch(t){this.qi(new Rp(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.Ae)==null||t.close(),(e=this.Kt)==null||e.close()}};function SI(t){return t.kind==="click"}var wI=2,Qp={fetchGoals:!0,eventUrlTransformer:t=>t,streaming:void 0,plugins:[]},II={fetchGoals:G.Boolean,eventUrlTransformer:G.Function,streaming:G.Boolean,plugins:G.createTypeArray("LDPlugin",{})};function TI(t){var e;let n=st({},t);return(e=n.flushInterval)!=null||(n.flushInterval=wI),n}function EI(t){let e=TI(t);return Object.keys(Qp).forEach(n=>{delete e[n]}),e}function RI(t,e){let n=st({},Qp);return Object.entries(II).forEach(r=>{let[i,o]=r,s=t[i];s!==void 0&&(o.is(s)?n[i]=s:e.warn(We.wrongOptionType(i,o.getType(),typeof s)))}),n}var CI=class{constructor(t,e){switch(this.Ji=t,this.Oe=[],e){case"sha1":this.No="SHA-1";break;case"sha256":this.No="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.Oe.join(""),n=new TextEncoder().encode(e),r=await this.Ji.subtle.digest(this.No,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.Oe.push(t),this}},ZI={start:0,end:3},kI={start:4,end:5},Na={start:6,end:7},Oa={start:8,end:8},VI={start:9,end:9},xI={start:10,end:15};function NI(){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 Zn(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 OI(t){return t[Oa.start]=(t[Oa.start]|128)&191,t[Na.start]=t[Na.start]&15|64,`${Zn(t,ZI)}-${Zn(t,kI)}-${Zn(t,Na)}-${Zn(t,Oa)}${Zn(t,VI)}-${Zn(t,xI)}`}function GI(){let t=NI();return OI(t)}function LI(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():GI()}var XI=class{createHash(t){return new CI(lI(),t)}randomUUID(){return LI()}};function WI(t){let e=Array.from(t,n=>String.fromCodePoint(n)).join("");return btoa(e)}var UI=class{btoa(t){return WI(new TextEncoder().encode(t))}},PI=class{constructor(t){this.e=t}platformData(){return{name:"JS"}}sdkData(){let t={name:"@launchdarkly/js-client-sdk",version:"0.13.1",userAgentBase:"JSClient"};return this.e.wrapperName&&(t.wrapperName=this.e.wrapperName),this.e.wrapperVersion&&(t.wrapperVersion=this.e.wrapperVersion),t}},MI=class{constructor(t,e){this.gt=t,this.n={},this.I=new vS(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.Te=e.errorFilter,this.$e()}$e(){this.J=new EventSource(this.gt),this.J.onopen=()=>{var t;this.I.success(),(t=this.onopen)==null||t.call(this)},this.J.onerror=t=>{var e;this.Yi(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.n).forEach(([t,e])=>{e.forEach(n=>{var r;(r=this.J)==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.J)==null||i.addEventListener(t,e)}close(){var t,e;clearTimeout(this.qt),this.qt=void 0,(t=this.J)==null||t.close(),(e=this.onclose)==null||e.call(this)}Zi(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.qt=setTimeout(()=>{this.$e()},t)}Yi(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.Te(t))&&this.Zi(this.I.fail())}},FI=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new MI(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function $p(){return typeof localStorage!="undefined"}function AI(){if(!$p())return[];let t=[];for(let e=0;e<localStorage.length;e+=1){let n=localStorage.key(e);n&&t.push(n)}return t}var JI=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}`)}}},DI=class{constructor(t,e){this.encoding=new UI,this.crypto=new XI,this.requests=new FI,$p()&&(this.storage=new JI(t)),this.info=new PI(e)}},YI=class extends Qw{constructor(t,e,n={},r){var i;let{logger:o,debug:s}=n,a=o!=null?o:new Pa({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 DI(a,n),u=RI(n,a),h=EI(fe(st({},n),{logger:a})),{eventUrlTransformer:p}=u;super(t,e,l,h,(f,m,d,v,b)=>new pI(l,f,t,m,u,()=>({pathGet(I,R){return`/sdk/evalx/${t}/contexts/${Bh(R,I)}`},pathReport(I,R){return`/sdk/evalx/${t}/context`},pathPing(I,R){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(I,R){return`/eval/${t}/${Bh(R,I)}`},pathReport(I,R){return`/eval/${t}`},pathPing(I,R){return`/ping/${t}`}}),d,v,b),{getLegacyStorageKeys:()=>AI().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 pe.InputCustomEvent(f.context,f.key,f.data,f.metricValue,f.samplingRatio,p(mr())),getImplementationHooks:f=>pe.safeGetHooks(a,f,u.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),this.Yt=u.plugins,u.fetchGoals&&(this.Jt=new vI(t,l.requests,c,f=>{a.error(f.message)},(f,m)=>{let d=this.getInternalContext();if(!d)return;let v=p(f);SI(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.Jt.initialize(),u.automaticBackgroundHandling&&dI(()=>this.flush()))}registerPlugins(t){pe.safeRegisterPlugins(this.logger,this.environmentMetadata,t,this.Yt||[]);let e=this.getDebugOverrides();e&&$w(this.logger,e,this.Yt||[])}setInitialContext(t){this.Zt=t}async identify(t,e){return super.identify(t,e)}async identifyResult(t,e){var n;if(!this.et)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.Jt)==null||n.startTracking(),i}start(t){var e,n;if(this.initializeResult)return Promise.resolve(this.initializeResult);if(this.et)return this.et;if(!this.Zt)return this.logger.error("Initial context not set"),Promise.resolve({status:"failed",error:new Error("Initial context not set")});let r=fe(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=zp(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.et=this.promiseWithTimeout(this.initializedPromise,(n=t==null?void 0:t.timeout)!=null?n:5),this.identifyResult(this.Zt,r),this.et}setStreaming(t){this.dataManager.setForcedStreaming(t)}Ne(){this.dataManager.setAutomaticStreamingState(!!this.emitter.listenerCount("change"))}on(t,e){super.on(t,e),this.Ne()}off(t,e){super.off(t,e),this.Ne()}};function KI(t,e,n,r={},i){let o=new YI(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 DF(t){return new Pa(t)}function qp(t,e,n){return KI(t,e,Fi.Disabled,n)}var _I=Object.defineProperty,HI=(t,e,n)=>e in t?_I(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ie=(t,e,n)=>HI(t,typeof e!="symbol"?e+"":e,n),zI=(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())}),Ze=(t,e,...n)=>{let r=`[@launchdarkly plugins]: (${t}): `;console[e].apply(console,[r,...n]),BI(r,...n)},BI=(t,...e)=>zI(void 0,null,function*(){try{let{LDObserve:n}=yield Promise.resolve().then(()=>tR);n.recordLog(`${t}${e}`,"warn")}catch(n){}}),jI=class{constructor(t,e){Ie(this,"debug"),Ie(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])}},bo=class{constructor(){Ie(this,"_sdk"),Ie(this,"_isLoaded",!1),Ie(this,"_callBuffer",[]),Ie(this,"_capacity",1e5),Ie(this,"_droppedEvents",0),Ie(this,"_exceededCapacity",!1),Ie(this,"_logger",new jI)}h(e,n){if(this.Nn)try{return this.jn[e](...n)}catch(r){Ze(`Error executing buffered call to ${e}:`,"error",r)}else{this.Mr({method:e,args:n});return}}Mr(e){this.wn.length<this.Ws?(this.wn.push(e),this.Qn=!1):(this.Qn||(this.Qn=!0,Ze("Exceeded event queue capacity. Increase capacity to avoid dropping events.","warn")),this.Us+=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){Ze(`Error executing buffered call to ${n}:`,"error",i)}this.wn=[]}},QI=Object.defineProperty,$I=Object.defineProperties,qI=Object.getOwnPropertyDescriptors,vo=Object.getOwnPropertySymbols,Uf=Object.prototype.hasOwnProperty,Pf=Object.prototype.propertyIsEnumerable,Cl=(t,e,n)=>e in t?QI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,j=(t,e)=>{for(var n in e||(e={}))Uf.call(e,n)&&Cl(t,n,e[n]);if(vo)for(var n of vo(e))Pf.call(e,n)&&Cl(t,n,e[n]);return t},Fn=(t,e)=>$I(t,qI(e)),Vr=(t,e)=>{var n={};for(var r in t)Uf.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&vo)for(var r of vo(t))e.indexOf(r)<0&&Pf.call(t,r)&&(n[r]=t[r]);return n},Xr=(t,e,n)=>Cl(t,typeof e!="symbol"?e+"":e,n),Jn=(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 tT(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 ao(t,e){throw new Error(e)}function eT(t){return typeof t=="object"&&t!==null}function nT(t,e){throw new Error("Unexpected invariant triggered.")}var rT=/\r\n|[\n\r]/g;function Zl(t,e){let n=0,r=1;for(let i of t.body.matchAll(rT)){if(typeof i.index=="number"||nT(),i.index>=e)break;n=i.index+i[0].length,r+=1}return{line:r,column:e+1-n}}function iT(t){return Mf(t.source,Zl(t.source,t.start))}function Mf(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=OF();n?yield n({session_secure_id:this.sessionData.sessionSecureID,payload_id:(this.sessionData.payloadID++).toString(),events:{events:r},messages:DL({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:xe.AsyncEvents,id:this.sessionData.payloadID++,events:r,messages:[],errors:[],resourcesString:JSON.stringify({resources:[]}),webSocketEventsString:JSON.stringify({webSocketEvents:[]}),hasSessionUnloaded:this.hasSessionUnloaded,highlightLogs:s}}),Sn(this.sessionData),this.events=this.events.slice(r.length),GF(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.xo}),Oe.takeFullSnapshot(),this.br=0,this.xo=new Date().getTime()}register(e,n){this.xn.push(new uu(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=Cs(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(yX);if(r&&(e=r==null?void 0:r.groups)!=null&&e.domain){let i=(n=r.groups.domain)!=null?n:"";return`https://${fX[i]}${mX}`}return dX}},Ri=class extends AX{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=Yt(z({},n),{organizationID:e,firstloadVersion:MF,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 rh(f),n!=null&&n.manualStart||this.record.start(),wn.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&&UF(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&&WF(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=XX(n.context),f=WX(n.context);(h=this.record)==null||h.identify(typeof f=="string"?f:(u=(l=f.user)==null?void 0:l.toString())!=null?u:p,Yt(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,$0=Object.defineProperties,q0=Object.getOwnPropertyDescriptors,Ui=Object.getOwnPropertySymbols,hp=Object.prototype.hasOwnProperty,pp=Object.prototype.propertyIsEnumerable,Jh=(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={}))hp.call(e,n)&&Jh(t,n,e[n]);if(Ui)for(var n of Ui(e))pp.call(e,n)&&Jh(t,n,e[n]);return t},fe=(t,e)=>$0(t,q0(e)),dp=(t,e)=>{var n={};for(var r in t)hp.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&Ui)for(var r of Ui(t))e.indexOf(r)<0&&pp.call(t,r)&&(n[r]=t[r]);return n};function tS(t){return`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`}function fp(t){return t.indexOf("~")?t.replace(/~1/g,"/").replace(/~0/g,"~"):t}function eS(t){return(t.startsWith("/")?t.substring(1):t).split("/").map(e=>fp(e))}function nS(t){return!t.startsWith("/")}function rS(t){return!t.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var xn=class{constructor(t,e=!1){if(e){let n=t;this.g=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?tS(n):n}else{if(this.redactionName=t,t===""||t==="/"||!rS(t)){this.isValid=!1,this.g=[];return}nS(t)?this.g=[t]:t.indexOf("/",1)<0?this.g=[fp(t.slice(1))]:this.g=eS(t),this.g[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{g: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.g[t]}get depth(){return this.g.length}get isKind(){return this.g.length===1&&this.g[0]==="kind"}compare(t){return this.depth===t.depth&&this.g.every((e,n)=>e===t.getComponent(n))}get components(){return[...this.g]}};xn.InvalidReference=new xn("");var iS=class{is(t){if(Array.isArray(t))return!1;let e=typeof t;return e==="function"||e==="object"}getType(){return"factory method or object"}},Gn=class{constructor(t,e){this.mt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.mt}},mp=class{constructor(t,e){this.mt=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.mt}},yp=class extends Gn{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},gp=class extends Gn{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},oS=class{is(t){return typeof t=="function"}getType(){return"function"}},sS=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},aS=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,lS=class{is(t){return typeof t=="number"||typeof t=="string"&&aS.test(t)}getType(){return"date"}},cS=class extends gp{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},G=class{static createTypeArray(t,e){return new mp(t,e)}static numberWithMin(t){return new yp(t)}static stringMatchingRegex(t){return new gp(t)}};G.String=new Gn("string","");G.Number=new Gn("number",0);G.ObjectOrFactory=new iS;G.Object=new Gn("object",{});G.StringArray=new mp("string[]","");G.Boolean=new Gn("boolean",!0);G.Function=new oS;G.Date=new lS;G.Kind=new cS;G.NullableBoolean=new sS;function bp(t){return"kind"in t?G.String.is(t.kind)&&t.kind!=="multi":!1}function vp(t){return"kind"in t?G.String.is(t.kind)&&t.kind==="multi":!1}function Sp(t){return!("kind"in t)||t.kind===null||t.kind===void 0}function Pi(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=>Pi(n,[...e,t])).map(n=>n===void 0?"null":n).join(",")}]`:`{${Object.keys(t).sort().map(n=>{let r=Pi(t[n],[...e,t]);if(r!==void 0)return`${JSON.stringify(n)}:${r}`}).filter(n=>n!==void 0).join(",")}}`}var Ga="user";function Dh(t){return t.includes("%")||t.includes(":")?t.replace(/%/g,"%25").replace(/:/g,"%3A"):t}function uS(t){return t&&G.Object.is(t)}function Yh(t){return G.Kind.is(t)}function Kh(t){return G.String.is(t)&&t!==""}function Ea(t,e=!1){return t?t.map(n=>new xn(n,e)):[]}function hS(t){return t!=null}function pS(t){let e=fe(st({},t.custom||[]),{kind:"user",key:String(t.key)});if(hS(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 Vn=class wt{constructor(e,n,r){this.C=!1,this.it=!1,this.Xt=!1,this.$={},this.kind=n,this.valid=e,this.message=r}static b(e,n){return new wt(!1,e,n)}static Re(e,n){if(!(!n||!e.isValid))return e.depth===1&&e.getComponent(0)==="anonymous"?!!(n!=null&&n.anonymous):e.get(n)}Qt(e){if(this.C)return this.$[e];if(this.kind===e)return this.y}static Me(e){let n=Object.keys(e).filter(c=>c!=="kind"),r=n.every(Yh);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 uS(h)?(c[l]=h,i[l]=Ea((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=>Kh(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=fe(st({},s[c]),{kind:c}),l.nt=i,l.it=c==="user",l}let a=new wt(!0,e.kind);return a.$=s,a.nt=i,a.C=!0,a}static Fe(e){var n;let{key:r,kind:i}=e,o=Yh(i),s=Kh(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=Ea((n=e._meta)==null?void 0:n.privateAttributes),c=new wt(!0,i);return c.it=i==="user",c.y=e,c.nt={[i]:a},c}static Ue(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.it=!0,n.Xt=!0,n.y=pS(e),n.nt={user:Ea(e.privateAttributeNames,!0)},n}static fromLDContext(e){return e?bp(e)?wt.Fe(e):vp(e)?wt.Me(e):Sp(e)?wt.Ue(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=Ga){return e.isKind?this.kinds:wt.Re(e,this.Qt(n))}key(e=Ga){var n;return(n=this.Qt(e))==null?void 0:n.key}get isMultiKind(){return this.C}get canonicalKey(){return this.it?this.y.key:this.C?Object.keys(this.$).sort().map(e=>`${e}:${Dh(this.$[e].key)}`).join(":"):`${this.kind}:${Dh(this.y.key)}`}get kinds(){return this.C?Object.keys(this.$):[this.kind]}get kindsAndKeys(){return this.C?Object.entries(this.$).reduce((e,[n,r])=>(e[n]=r.key,e),{}):{[this.kind]:this.y.key}}privateAttributes(e){var n;return((n=this.nt)==null?void 0:n[e])||[]}getContexts(){return this.C?Object.entries(this.$):[[this.kind,this.y]]}get legacy(){return this.Xt}canonicalUnfilteredJson(){if(this.valid){if(this.yt)return this.yt;try{this.yt=Pi(wt.toLDContext(this))}catch(e){}return this.yt}}};Vn.UserKind=Ga;var dS=["key","kind","_meta","anonymous"].map(t=>new xn(t,!0)),fS=["name","ip","firstName","lastName","email","avatar","country"];function mS(t,e){return t.depth===e.length&&e.every((n,r)=>n===t.getComponent(r))}function yS(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=>mS(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 gS=class{constructor(t,e){this.Ve=t,this.je=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.te(t,n[0][1],n[0][0],e);let r={kind:"multi"};return n.forEach(([i,o])=>{r[i]=this.te(t,o,i,e)}),r}He(t,e,n,r){return(r?Object.keys(e).map(i=>new xn(i,!0)):[...this.je,...t.privateAttributes(n)]).filter(i=>!dS.some(o=>o.compare(i)))}te(t,e,n,r){let i=this.Ve||r&&e.anonymous===!0,{cloned:o,excluded:s}=yS(e,this.He(t,e,n,i));return t.legacy&&fS.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}},_h=30*1e3,bS=.5,vS=class{constructor(t,e,n=Math.random){this.Be=e,this.ze=n,this.vt=0,this.ee=Math.max(1,t),this.Ge=Math.ceil(Math.log2(_h/this.ee))}I(){let t=Math.min(this.vt,this.Ge),e=this.ee*2**t;return Math.min(e,_h)}Ke(t){return t-Math.trunc(this.ze()*bS*t)}success(t=Date.now()){this.wt=t}fail(t=Date.now()){this.wt!==void 0&&t-this.wt>this.Be&&(this.vt=0),this.wt=void 0;let e=this.Ke(this.I());return this.vt+=1,e}},Hh;(function(t){t[t.Valid=0]="Valid",t[t.Initializing=1]="Initializing",t[t.Interrupted=2]="Interrupted",t[t.Closed=3]="Closed"})(Hh||(Hh={}));var Mi=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=r}},La=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=r}},AF=120*1e3,JF=300*1e3,Kt;(function(t){t.Unknown="UNKNOWN",t.NetworkError="NETWORK_ERROR",t.ErrorResponse="ERROR_RESPONSE",t.InvalidData="INVALID_DATA"})(Kt||(Kt={}));var Fi;(function(t){t[t.Disabled=0]="Disabled",t[t.Enabled=1]="Enabled"})(Fi||(Fi={}));var Nn;(function(t){t[t.AnalyticsEvents=0]="AnalyticsEvents",t[t.DiagnosticEvent=1]="DiagnosticEvent"})(Nn||(Nn={}));var $e;(function(t){t[t.Succeeded=0]="Succeeded",t[t.Failed=1]="Failed",t[t.FailedAndMustShutDown=2]="FailedAndMustShutDown"})($e||($e={}));function kn(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 SS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(Number(t))}function wS(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(parseInt(t,10))}function IS(t){return typeof t=="symbol"?"NaN":String(parseFloat(t))}var Ra={s:t=>kn(t),d:t=>SS(t),i:t=>wS(t),f:t=>IS(t),j:t=>kn(t),o:t=>kn(t),O:t=>kn(t),c:()=>""};function Xa(...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 Ra&&t.length){let a=t.shift();r+=(e=Ra[s])==null?void 0:e.call(Ra,a)}else s==="%"?r+="%":r+=`%${s}`;i+=2}}else r+=o,i+=1}return t.length&&(r.length&&(r+=" "),r+=t.map(kn).join(" ")),r}return t.map(kn).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 TS=["debug","info","warn","error","none"],Pa=class wp{static get(){return new wp({})}constructor(e){var n,r,i;if(this.Qe=(r=Vt[(n=e.level)!=null?n:"info"])!=null?r:Vt.info,this.ti=(i=e.name)!=null?i:"LaunchDarkly",this.ae=e.formatter,typeof e.destination=="object")this.oe={[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.oe={[Vt.debug]:o,[Vt.info]:o,[Vt.warn]:o,[Vt.error]:o}}}ei(...e){var n;try{return this.ae?(n=this.ae)==null?void 0:n.call(this,...e):Xa(...e)}catch(r){return Xa(...e)}}ii(e,n){try{e(n)}catch(r){console.error(n)}}k(e,n){var r;if(e>=this.Qe){let i=`${TS[e]}: [${this.ti}]`;try{let o=(r=this.oe)==null?void 0:r[e];o?this.ii(o,`${i} ${this.ei(...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)}},ES={error:G.Function,warn:G.Function,info:G.Function,debug:G.Function},Ip=class{constructor(t,e){Object.entries(ES).forEach(([n,r])=>{if(!r.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.ni=e}k(t,e){try{this.t[t](...e)}catch(n){this.ni[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)}},Tp=t=>{let e=new Pa({level:"info",destination:console.error,formatter:Xa});return t?new Ip(t,e):e},We=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`}},RS=/^(\w|\.|-)+$/,CS=G.stringMatchingRegex(RS),ZS={is:(t,e)=>CS.is(t)?t.length>64?{valid:!1,message:We.tagValueTooLong(e)}:{valid:!0}:{valid:!1,message:We.invalidTagValue(e)}},kS=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}=ZS.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(" "))}},VS=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 Ca(t){return t.replace(/\/+$/,"")}function Ma(t){return t.replace(/^\/+/,"").replace(/\?$/,"")}var Ai=class Ep{constructor(e,n,r=Ep.DEFAULT_EVENTS,i="/bulk",o="/diagnostic",s=!0,a){this.streaming=Ca(e),this.polling=Ca(n),this.events=Ca(r),this.analyticsEventPath=i,this.diagnosticEventPath=o,this.includeAuthorizationHeader=s,this.payloadFilterKey=a}};Ai.DEFAULT_EVENTS="https://events.launchdarkly.com";function Fa(t,e=[]){if(e.length===0)return t;let n=e.map(({key:r,value:i})=>`${r}=${i}`);return`${t}?${n.join("&")}`}function xS(t,e,n){let r=Ma(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Fa(`${t.streaming}/${r}`,i)}function NS(t,e,n=[]){let r=Ma(e),i=[...n];return t.payloadFilterKey&&i.push({key:"filter",value:t.payloadFilterKey}),Fa(`${t.polling}/${r}`,i)}function zh(t,e,n=[]){let r=Ma(e);return Fa(`${t.events}/${r}`,n)}var Rp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},OS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},Cp=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function Yi(t){return t>=400&&t<500?t===400||t===408||t===429:!0}function GS(t){return t===413?!0:Yi(t)}function LS(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 Cp(s))},t*1e3)}),cancel:()=>{r(),clearTimeout(n)}}}function Zp(t){return t==null?t:JSON.parse(JSON.stringify(t))}function Za(t){return Math.trunc(t*1e3)}var XS=t=>JSON.stringify(t)==="{}",Aa=(t,e)=>t&&Object.entries(t).reduce((n,[r,i])=>(i&&!XS(i)&&!(e!=null&&e.includes(r))&&(n[r]=typeof i=="object"?Aa(i,e):i),n),{});function Xi(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(!Xi(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(!Xi(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(!Xi(t[o],e[o]))return!1}return!0}return t!==t&&e!==e}function WS(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 On(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 kp({status:t}){return t?Yi(t):!0}var Bh=(t,e)=>e.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),Vp=async(t=1e3)=>new Promise(e=>{setTimeout(e,t)}),US=class{constructor(t,e,n){this.p=e,this.si=n,this.bt=[],this.ce=Date.now(),this.le=this.ce,this.ue={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.ue,creationDate:this.ce,sdk:r,configuration:this.si,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.bt.push(r)}createStatsEventAndReset(t,e,n){let r=Date.now(),i={kind:"diagnostic",id:this.ue,creationDate:r,dataSinceDate:this.le,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.bt};return this.bt=[],this.le=r,i}},Wa;(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"})(Wa||(Wa={}));var PS=Wa,xp=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};xp.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var MS=class{constructor(t,e){let{basicConfiguration:n,platform:r}=t,{serviceEndpoints:{analyticsEventPath:i,diagnosticEventPath:o}}=n,{crypto:s,requests:a}=r;this.ri=st({},e),this.he=zh(n.serviceEndpoints,i,[]),this.ai=zh(n.serviceEndpoints,o,[]),this.H=a,this.oi=s}async st(t,e,n,r){let i={status:$e.Succeeded},o=fe(st({},this.ri),{"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.H.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 Rp(On({status:a,message:"some events were dropped"},"event posting")),!Yi(a))return GS(a)?i.status=$e.Failed:i.status=$e.FailedAndMustShutDown,i.error=s,i}catch(a){s=a}return s&&!r?(i.status=$e.Failed,i.error=s,i):(await Vp(),this.st(t,this.he,n,!1))}async sendEventData(t,e){let n=t===Nn.AnalyticsEvents?this.oi.randomUUID():void 0,r=t===Nn.AnalyticsEvents?this.he:this.ai;return this.st(e,r,n,!0)}};function Ji(t){return t.kind==="feature"}function FS(t){return t.kind==="identify"}function AS(t){return t.kind==="migration_op"}var JS=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 DS(t){return`${t.key}:${t.variation!==null&&t.variation!==void 0?t.variation:""}:${t.version!==null&&t.version!==void 0?t.version:""}`}var Np=class{constructor(t=!1,e){this.ci=t,this.x=e,this.Y=0,this.rt=0,this.at={},this.ot={}}summarizeEvent(t){if(Ji(t)&&!t.excludeFromSummaries){this.y||(this.y=t.context);let e=DS(t),n=this.at[e],r=this.ot[t.key];r||(r=new Set,this.ot[t.key]=r),t.context.kinds.forEach(i=>r.add(i)),n?n.increment():this.at[e]=new JS(1,t.key,t.value,t.default,t.version,t.variation),(this.Y===0||t.creationDate<this.Y)&&(this.Y=t.creationDate),t.creationDate>this.rt&&(this.rt=t.creationDate)}}getSummary(){var t;let e=Object.values(this.at).reduce((r,i)=>{let o=r[i.key];o||(o={default:i.default,counters:[],contextKinds:[...this.ot[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.Y,endDate:this.rt,features:e,kind:"summary",context:this.y!==void 0&&this.ci?(t=this.x)==null?void 0:t.filter(this.y):void 0};return this.li(),n}li(){this.Y=0,this.rt=0,this.at={},this.ot={}}},YS=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}},KS=class{constructor(t,e){this.x=t,this.t=e,this.Z={}}summarizeEvent(t){var e;if(Ji(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.Z[n];r||(this.Z[n]=new Np(!0,this.x),r=this.Z[n]),r.summarizeEvent(t)}}getSummaries(){let t=this.Z;return this.Z={},Object.values(t).map(e=>e.getSummary())}};function Wi(t){let e=Math.trunc(t);return e===1?!0:e===0?!1:Math.floor(Math.random()*e)===0}function _S(t){return t.getSummaries!==void 0}var HS=class{constructor(t,e,n,r,i,o=!0,s=!1){this.e=t,this.ct=r,this.S=i,this.lt=[],this.de=0,this.kt=0,this.xt=0,this.St=!1,this.fe=0,this.Lt=!1,this.Ct=null,this.ui=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.pe=new MS(e,n),this.x=new gS(t.allAttributesPrivate,t.privateAttributes.map(a=>new xn(a))),s?this.X=new KS(this.x,this.t):this.X=new Np,o&&this.start()}start(){var t,e;if(((t=this.ct)==null?void 0:t.flushInterval)!==void 0&&(this.Ct=setInterval(()=>{var n;(n=this.ct)==null||n.flush()},this.ct.flushInterval*1e3)),this.hi=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.ge(n),this.me=setInterval(()=>{let r=this.S.createStatsEventAndReset(this.kt,this.xt,this.fe);this.kt=0,this.xt=0,this.ge(r)},this.e.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}ge(t){this.pe.sendEventData(Nn.DiagnosticEvent,t)}close(){clearInterval(this.hi),this.Ct&&clearInterval(this.Ct),this.me&&clearInterval(this.me)}async flush(){var t;if(this.Lt)throw new YS("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.lt;if(this.lt=[],_S(this.X))this.X.getSummaries().forEach(n=>{Object.keys(n.features).length&&e.push(n)});else{let n=this.X.getSummary();Object.keys(n.features).length&&e.push(n)}e.length&&(this.fe=e.length,(t=this.t)==null||t.debug("Flushing %d events",e.length),await this.st(e))}sendEvent(t){var e;if(this.Lt)return;if(AS(t)){if(Wi(t.samplingRatio)){let a=fe(st({},t),{context:t.context?this.x.filter(t.context):void 0});a.samplingRatio===1&&delete a.samplingRatio,this.ut(a)}return}this.X.summarizeEvent(t);let n=Ji(t),r=n&&t.trackEvents||!n,i=this.di(t),o=FS(t),s=(e=this.ct)==null?void 0:e.processContext(t.context);s||o||(this.xt+=1),s&&!o&&this.ut(this.It({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),r&&Wi(t.samplingRatio)&&this.ut(this.It(t,!1)),i&&Wi(t.samplingRatio)&&this.ut(this.It(t,!0))}It(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}}ut(t){var e;this.lt.length<this.ui?(this.lt.push(t),this.St=!1):(this.St||(this.St=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.kt+=1)}di(t){return Ji(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.de&&t.debugEventsUntilDate>Date.now()}async st(t){let e=await this.pe.sendEventData(Nn.AnalyticsEvents,t);if(e.status===$e.FailedAndMustShutDown&&(this.Lt=!0),e.serverTime&&(this.de=e.serverTime),e.error)throw e.error}},Op=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}},Ua=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)}},Gp=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},zS=class{close(){}async flush(){}sendEvent(){}},BS=class{constructor(t){this.At=t}evalEvent(t){var e;return new Ua(this.At,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.At||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new Ua(this.At,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new Gp(t,1)}customEvent(t,e,n,r,i=1){return new Op(e,t,n!=null?n:void 0,r!=null?r:void 0,i)}},jh="FDv1Fallback";function jS(t){return{fi:t,ye:"",useSelector(e){return this.ye=e,this},processFullTransfer(e){let n=[{event:"server-intent",data:{payloads:[{id:jh,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.ye,version:1,id:jh}}),this.fi.processEvents(n)}}}var Lp=class{constructor(t,e,n){this.pi=t,this.m=e,this.t=n,this.n=[],this.N=void 0,this.B=!1,this.z=[],this.gi=r=>{var i;if(this.Pt(),!r.payloads.length)return;let o=r.payloads[0];switch(o==null?void 0:o.intentCode){case"xfer-full":this.B=!0;break;case"xfer-changes":this.B=!1;break;case"none":this.B=!1,this.mi(o);break;default:(i=this.t)==null||i.warn(`Unable to process intent code '${o==null?void 0:o.intentCode}'.`);return}this.N=o==null?void 0:o.id},this.yi=r=>{var i;if(!this.N||!r.kind||!r.key||!r.version||!r.object)return;let o=this.vi(r.kind,r.object);if(!o){(i=this.t)==null||i.warn(`Unable to process object for kind: '${r.kind}'`);return}this.z.push({kind:r.kind,key:r.key,version:r.version,object:o})},this.wi=r=>{!this.N||!r.kind||!r.key||!r.version||this.z.push({kind:r.kind,key:r.key,version:r.version,deleted:!0})},this.mi=r=>{if(!r.id||!r.target)return;let i={id:r.id,version:r.target,basis:!1,updates:[]};this.n.forEach(o=>o(i)),this.ve()},this.Ei=r=>{if(!this.N||r.state===null||r.state===void 0||!r.version){this.Pt();return}let i={id:this.N,version:r.version,state:r.state,basis:this.B,updates:this.z};this.n.forEach(o=>o(i)),this.ve()},this.Di=r=>{var i;(i=this.t)==null||i.info(`Goodbye was received from the LaunchDarkly connection with reason: ${r.reason}.`),this.Pt()},this.bi=r=>{var i;(i=this.t)==null||i.info(`An issue was encountered receiving updates for payload ${this.N} with reason: ${r.reason}.`),this.ki()}}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=>{switch(e.event){case"server-intent":{this.gi(e.data);break}case"put-object":{this.yi(e.data);break}case"delete-object":{this.wi(e.data);break}case"payload-transferred":{this.Ei(e.data);break}case"goodbye":{this.Di(e.data);break}case"error":{this.bi(e.data);break}}})}vi(t,e){var n,r;return(r=(n=this.pi)[t])==null?void 0:r.call(n,e)}ve(){this.B=!1,this.z=[]}ki(){this.z=[]}Pt(){this.N=void 0,this.B=!1,this.z=[]}},QS=class{constructor(t,e,n,r){this.m=n,this.t=r,this.G(t,"server-intent"),this.G(t,"put-object"),this.G(t,"delete-object"),this.G(t,"payload-transferred"),this.G(t,"goodbye"),this.G(t,"error"),this.Ot=new Lp(e,n,r)}addPayloadListener(t){this.Ot.addPayloadListener(t)}removePayloadListener(t){this.Ot.removePayloadListener(t)}G(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.Ot.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.m)==null||s.call(this,Kt.InvalidData,"Malformed data in EventStream.")}}else(a=this.m)==null||a.call(this,Kt.Unknown,"Event from EventStream missing data.")})}};function $S(t){if(t){let e=Object.keys(t).find(n=>n.toLowerCase()==="x-ld-envid");if(e)return{environmentId:t[e]}}}var Qh="unknown plugin";function Di(t,e){try{return e.getMetadata().name||Qh}catch(n){return t.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),Qh}}function qS(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 ${Di(t,i)} returned undefined from getHooks.`):s&&s.length>0&&r.push(...s)}catch(s){t.error(`Exception thrown getting hooks for plugin ${Di(t,i)}. Unable to get hooks.`)}}),r}function tw(t,e,n,r){r.forEach(i=>{try{i.register(n,e)}catch(o){t.error(`Exception thrown registering plugin ${Di(t,i)}.`)}})}var pe=Object.freeze({__proto__:null,ClientMessages:xp,DiagnosticsManager:US,ErrorKinds:PS,EventFactoryBase:BS,EventProcessor:HS,FDv1PayloadAdaptor:jS,InputCustomEvent:Op,InputEvalEvent:Ua,InputIdentifyEvent:Gp,NullEventProcessor:zS,PayloadProcessor:Lp,PayloadStreamReader:QS,canonicalize:Pi,initMetadataFromHeaders:$S,isLegacyUser:Sp,isMultiKind:vp,isSingleKind:bp,safeGetHooks:qS,safeGetName:Di,safeRegisterPlugins:tw,shouldSample:Wi}),ew={Initializing:"INITIALIZING",Valid:"VALID",Interrupted:"INTERRUPTED",SetOffline:"SET_OFFLINE",Closed:"CLOSED"};function nw(t){return t>=200&&t<=299}var $h=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}};function qh(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=NS(e,f,m);return{async requestPayload(){let v;try{let b=await r.fetch(d,{method:h,headers:p,body:u});if(nw(b.status))return await b.text();v=b.status}catch(b){throw new $h(b==null?void 0:b.message)}throw new $h(`Unexpected status code: ${v}`,v)}}}var tp=new Error("Task has already been executed or shed. This is likely an implementation error. The task will not be executed again.");function rw(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(tp)),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(tp)),s=!0,o.then(a=>{r({status:"shed"},a)})},promise:i,sheddable:n}}function iw(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=rw(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 ow={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},sw=300,Xp="https://clientsdk.launchdarkly.com",Wp="https://clientstream.launchdarkly.com";function aw(t){return t instanceof Ip?t:Tp(t)}var lw=class{constructor(t={},e={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var n,r,i;this.logger=Tp(),this.baseUri=Xp,this.eventsUri=Ai.DEFAULT_EVENTS,this.streamUri=Wp,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=sw,this.hooks=[],this.inspectors=[],this.logger=aw(t.logger),this.xi(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new Ai(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 kS({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}xi(t){let e=[];return Object.entries(t).forEach(([n,r])=>{let i=ow[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(We.wrongOptionTypeBoolean(n,typeof r)),this[n]=!!r;else if(o==="boolean | undefined | null")e.push(We.wrongOptionTypeBoolean(n,typeof r)),typeof r!="boolean"&&typeof r!="undefined"&&r!==null&&(this[n]=!!r);else if(i instanceof yp&&G.Number.is(r)){let{min:s}=i;e.push(We.optionBelowMinimum(n,r,s)),this[n]=s}else e.push(We.wrongOptionType(n,i.getType(),typeof r))}else e.push(We.unknownOption(n))}),e}};async function Up(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 Pp=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 Mp(t){return async e=>Up(t.createHash("sha256").update(e),"base64")}var de=async t=>t;async function yr(t){return(await Promise.all(t.map(e=>e.transform(e.value)))).join("_")}async function cw(t,e){return yr([{value:"LaunchDarkly",transform:de},{value:e,transform:Mp(t)}])}async function uw(t){return yr([{value:"LaunchDarkly",transform:de},{value:"AnonymousKeys",transform:de},{value:t,transform:de}])}async function hw(t){return yr([{value:"LaunchDarkly",transform:de},{value:"ContextKeys",transform:de},{value:t,transform:de}])}async function pw(t){return yr([{value:t,transform:de},{value:"ContextIndex",transform:de}])}async function ep(t,e,n){return yr([{value:e,transform:de},{value:n.canonicalKey,transform:Mp(t)}])}var{isLegacyUser:dw,isSingleKind:ka,isMultiKind:np}=pe,Fp="1.0",fw=t=>{let e=t,{kind:n}=e,r=dp(e,["kind"]);return{kind:"multi",[n]:r}},mw=async({crypto:t,info:e},{applicationInfo:n})=>{var r;let{ld_application:i}=e.platformData(),o=(r=Aa(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(fe(st({},o),{id:s}),a?{version:a}:{}),c?{name:c}:{}),l?{versionName:l}:{}),o.key=await Up(t.createHash("sha256").update(s),"base64"),o.envAttributesVersion=o.envAttributesVersion||Fp,o}},yw=async t=>{var e,n,r,i;let{ld_device:o,os:s}=t.info.platformData(),a=(e=Aa(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 hw("ld_device");return a.key=await Pp(h,t),a.envAttributesVersion=a.envAttributesVersion||Fp,a}},gw=async(t,e,n)=>{if(dw(t))return t;let r,i;if(ka(t)&&t.kind!=="ld_application"||np(t)&&!t.ld_application?r=await mw(e,n):n.logger.warn("Not adding ld_application environment attributes because it already exists."),ka(t)&&t.kind!=="ld_device"||np(t)&&!t.ld_device?i=await yw(e):n.logger.warn("Not adding ld_device environment attributes because it already exists."),r||i){let o=ka(t)?fw(t):t;return st(st(st({},o),r?{ld_application:r}:{}),i?{ld_device:i}:{})}return t};function bw(){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:vw,isMultiKind:Sw,isSingleKind:ww}=pe,Ja=async(t,e,n)=>{let{anonymous:r,key:i}=e;if(r&&!i){let o=await uw(t);e.key=await Pp(o,n)}},Iw=async(t,e)=>{await Ja(t.kind,t,e)},Tw=async(t,e)=>{let n=t,{kind:r}=n,i=dp(n,["kind"]);return Promise.all(Object.entries(i).map(([o,s])=>Ja(o,s,e)))},Ew=async(t,e)=>{await Ja("user",t,e)},Rw=async(t,e)=>{let n=Zp(t);return ww(n)&&await Iw(n,e),Sw(n)&&await Tw(n,e),vw(n)&&await Ew(n,e),n},Cw=t=>({customBaseURI:t.serviceEndpoints.polling!==Xp,customStreamURI:t.serviceEndpoints.streaming!==Wp,customEventsURI:t.serviceEndpoints.events!==Ai.DEFAULT_EVENTS,eventsCapacity:t.capacity,eventsFlushIntervalMillis:Za(t.flushInterval),reconnectTimeMillis:Za(t.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:Za(t.diagnosticRecordingInterval),allAttributesPrivate:t.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Zw=(t,e,n)=>{if(e.sendEvents&&!e.diagnosticOptOut)return new pe.DiagnosticsManager(t,n,Cw(e))};function rp(t,e){return{value:e!=null?e:null,variationIndex:null,reason:{kind:"ERROR",errorKind:t}}}function ip(t,e,n){return st({value:t,variationIndex:e!=null?e:null},n!==void 0&&{reason:n})}var kw=(t,e,n,r,i)=>{if(e.sendEvents)return new pe.EventProcessor(fe(st({},e),{eventsCapacity:e.capacity}),new VS(t,e,n),r,void 0,i,!1,!0)},op=class extends pe.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})}},Va=class Ap{constructor(){this.container={index:new Array}}static fromJson(e){let n=new Ap;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)):[]}},Vw=class{constructor(t,e,n,r,i,o,s=()=>Date.now()){this.p=t,this.Tt=e,this.Si=n,this.P=r,this.w=i,this.t=o,this.Li=s,this.we=pw(this.Tt)}async init(t,e){this.w.init(t,e),await this.Ee(t)}async upsert(t,e,n){return this.w.upsert(t,e,n)?(await this.Ee(t),!0):!1}async loadCached(t){var e,n,r,i;let o=await ep(this.p.crypto,this.Tt,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 Ci(){var t;if(this.K!==void 0)return this.K;let e=await((t=this.p.storage)==null?void 0:t.get(await this.we));if(!e)return this.K=new Va,this.K;try{this.K=Va.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.K=new Va}return this.K}async Ee(t){var e,n;let r=await this.Ci(),i=await ep(this.p.crypto,this.Tt,t);r.notice(i,this.Li());let o=r.prune(this.Si);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.we,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 xw(){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 Nw(t,e){let n=[];return Object.entries(t).forEach(([r,i])=>{let o=e[r];(!o||!Xi(i,o))&&n.push(r)}),Object.keys(e).forEach(r=>{t[r]||n.push(r)}),n}function Ow(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=Nw(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 Gw=class{constructor(t,e,n,r,i=()=>Date.now()){this.P=xw(),this.w=Ow(this.P,r),this.$t=this.Ii(t,e,n,r,i)}async Ii(t,e,n,r,i=()=>Date.now()){let o=await cw(t.crypto,e);return new Vw(t,o,n,this.P,this.w,r,i)}get(t){return this.r&&Object.prototype.hasOwnProperty.call(this.r,t)?this.Nt(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.Nt(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.$t).init(t,e)}async upsert(t,e,n){return(await this.$t).upsert(t,e,n)}async loadCached(t){return(await this.$t).loadCached(t)}on(t){this.w.on(t)}off(t){this.w.off(t)}Nt(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.Nt(n)}),t}getDebugOverride(){return{setOverride:this.setOverride.bind(this),removeOverride:this.removeOverride.bind(this),clearAllOverrides:this.clearAllOverrides.bind(this),getAllOverrides:this.getAllOverrides.bind(this)}}},sp="unknown hook",Jp="beforeEvaluation",Dp="afterEvaluation",Lw="afterTrack";function gr(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 br(t,e){try{return e.getMetadata().name||sp}catch(n){return t.error("Exception thrown getting metadata for hook. Unable to get hook name."),sp}}function Xw(t,e,n){return e.map(r=>gr(t,Jp,br(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeEvaluation)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Ww(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];gr(t,Dp,br(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 Uw(t,e,n){return e.map(r=>gr(t,Jp,br(t,r),()=>{var i,o;return(o=(i=r==null?void 0:r.beforeIdentify)==null?void 0:i.call(r,n,{}))!=null?o:{}},{}))}function Pw(t,e,n,r,i){for(let o=e.length-1;o>=0;o-=1){let s=e[o],a=r[o];gr(t,Dp,br(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 Mw(t,e,n){for(let r=e.length-1;r>=0;r-=1){let i=e[r];gr(t,Lw,br(t,i),()=>{var o;return(o=i==null?void 0:i.afterTrack)==null?void 0:o.call(i,n)},void 0)}}var Fw=class{constructor(t,e){this.t=t,this.R=[],this.R.push(...e)}withEvaluation(t,e,n,r){if(this.R.length===0)return r();let i=[...this.R],o={flagKey:t,context:e,defaultValue:n},s=Xw(this.t,i,o),a=r();return Ww(this.t,i,o,s,a),a}identify(t,e){let n=[...this.R],r={context:t,timeout:e},i=Uw(this.t,n,r);return o=>{Pw(this.t,n,r,i,o)}}addHook(t){this.R.push(t)}afterTrack(t){if(this.R.length===0)return;let e=[...this.R];Mw(this.t,e,t)}};function Aw(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 Jw(t,e){return`an inspector: "${e}" of an invalid type (${t}) was configured`}function Dw(t,e){return`an inspector: "${e}" of type: "${t}" generated an exception`}function Yw(t,e){let n=!1,r={method:(...i)=>{try{t.method(...i)}catch(o){n||(n=!0,e.warn(Dw(r.type,r.name)))}},type:t.type,name:t.name,synchronous:t.synchronous};return r}var Yp="flag-used",Kp="flag-details-changed",_p="flag-detail-changed",Hp="client-identity-changed",Kw=[Yp,Kp,_p,Hp];function _w(t,e){let n=Kw.includes(t.type)&&t.method&&typeof t.method=="function";return n||e.warn(Jw(t.type,t.name)),n}var Hw=class{constructor(t,e){this.W=[];let n=t.filter(r=>_w(r,e));this.W=n.map(r=>Yw(r,e))}hasInspectors(){return this.W.length!==0}onFlagUsed(t,e,n){this.W.forEach(r=>{r.type===Yp&&r.method(t,e,n)})}onFlagsChanged(t){this.W.forEach(e=>{e.type===Kp&&e.method(t)})}onFlagChanged(t,e){this.W.forEach(n=>{n.type===_p&&n.method(t,e)})}onIdentityChanged(t){this.W.forEach(e=>{e.type===Hp&&e.method(t)})}},zw=class{constructor(t){this.t=t,this.n=new Map}on(t,e){var n;this.n.has(t)?(n=this.n.get(t))==null||n.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)}}Ai(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.Ai(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 Bw(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:ap,ErrorKinds:lp}=pe,jw=5,Qw=class{constructor(t,e,n,r,i,o){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.a=bw(),this.Rt=15,this.T=new op(!1),this.ht=new op(!0),this.Mt=!1,this.Pi=iw(),!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 lw(r,o),this.logger=this.e.logger,this.De=WS(this.sdkKey,this.platform.info,this.e.tags,this.e.serviceEndpoints.includeAuthorizationHeader,this.e.userAgentHeaderName),this.M=new Gw(this.platform,t,this.e.maxCachedContexts,this.e.logger),this.S=Zw(t,this.e,n),this.E=kw(t,this.e,n,this.De,this.S),this.emitter=new zw,this.emitter.on("error",(a,c)=>{this.logger.error(`error: ${c}, context: ${JSON.stringify(a)}`)}),this.M.on((a,c,l)=>{this.Oi(c,l);let u=Vn.toLDContext(a);this.emitter.emit("change",u,c),c.forEach(h=>{this.emitter.emit(`change:${h}`,u)})}),this.dataManager=i(this.M,this.e,this.De,this.emitter,this.S);let s=[...this.e.hooks];if(this.environmentMetadata=Bw(this.sdkKey,this.platform,this.e),this.e.getImplementationHooks(this.environmentMetadata).forEach(a=>{s.push(a)}),this.F=new Fw(this.logger,s),this.Q=new Hw(this.e.inspectors,this.logger),this.Q.hasInspectors()&&this.F.addHook(Aw(this.Q)),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.M.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()?Zp(this.a.getUnwrappedContext()):void 0}getInternalContext(){return this.a.getContext()}presetFlags(t){this.M.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 Cp(`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:jw,o=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;i>this.Rt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Rt} seconds. We recommend a timeout of less than ${this.Rt} seconds.`);let s=this.Pi.execute({before:async()=>{let c=await Rw(t,this.platform);this.autoEnvAttributes===Fi.Enabled&&(c=await gw(c,this.platform,this.e));let l=Vn.fromLDContext(c);if(l.valid){let u=this.F.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=LS(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(ap.MissingContextKeyNoEvent);return}n!==void 0&&!G.Number.is(n)&&((r=this.logger)==null||r.warn(ap.invalidMetricValue(typeof n))),(i=this.E)==null||i.sendEvent(this.e.trackEventModifier(this.T.customEvent(t,this.a.getContext(),e,n))),this.F.afterTrack({key:t,context:this.a.getUnwrappedContext(),data:e,metricValue:n})}dt(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.M.get(t);if(h===void 0||h.flag.deleted){let b=e!=null?e:null;return(o=this.logger)==null||o.warn(`Unknown feature flag "${t}"; returning default value ${b}.`),l&&((s=this.E)==null||s.sendEvent(this.T.unknownFlagEvent(t,b,u))),rp(lp.FlagNotFound,e)}let{reason:p,value:f,variation:m,prerequisites:d}=h.flag;if(r){let[b,I]=r(f);if(!b){l&&((a=this.E)==null||a.sendEvent(n.evalEventClient(t,e,e,h.flag,u,p)));let R=new OS(`Wrong type "${I}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.a.getUnwrappedContext(),R),rp(lp.WrongType,e)}}let v=ip(f,m,p);return f==null&&(this.logger.debug("Result value is null. Providing default value."),v.value=e),d==null||d.forEach(b=>{this.dt(b,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.F.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.dt(t,e,this.T));return n}variationDetail(t,e){return this.F.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.dt(t,e,this.ht))}_(t,e,n,r){return this.F.withEvaluation(t,this.a.getUnwrappedContext(),e,()=>this.dt(t,e,n,r))}boolVariation(t,e){return this._(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._(t,e,this.T,n=>[G.Number.is(n),G.Number.getType()]).value}stringVariation(t,e){return this._(t,e,this.T,n=>[G.String.is(n),G.String.getType()]).value}boolVariationDetail(t,e){return this._(t,e,this.ht,n=>[G.Boolean.is(n),G.Boolean.getType()])}numberVariationDetail(t,e){return this._(t,e,this.ht,n=>[G.Number.is(n),G.Number.getType()])}stringVariationDetail(t,e){return this._(t,e,this.ht,n=>[G.String.is(n),G.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.F.addHook(t)}setEventSendingEnabled(t,e){var n,r,i,o;this.Mt!==t&&(this.Mt=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.Mt||((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.M).getDebugOverride)==null?void 0:e.call(t)}Oi(t,e){if(!this.Q.hasInspectors())return;let n={};t.forEach(r=>{let i=this.M.get(r);if(i!=null&&i.flag&&!i.flag.deleted){let{reason:o,value:s,variation:a}=i.flag;n[r]=ip(s,a,o)}else n[r]={value:void 0,variationIndex:null}}),e==="init"?this.Q.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([r,i])=>{this.Q.onFlagChanged(r,i)})}};function $w(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 ${pe.safeGetName(t,r)}.`)}})}function qw(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:fe(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 tI(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 cp(t){t==null||t.debug("Poll completed after the processor was closed. Skipping processing.")}var eI=class{constructor(t,e,n,r,i){this.Ti=t,this.$i=e,this.Ni=n,this.m=r,this.t=i,this.u=!1}async be(){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.m)==null||m.call(this,new Mi(Kt.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.Ti.requestPayload();try{if(this.u){cp(this.t);return}let p=JSON.parse(h);try{(e=this.Ni)==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){cp(this.t);return}let p=h;if(p.status!==void 0&&!Yi(p.status)){(r=this.t)==null||r.error(On(h,"polling request")),(i=this.m)==null||i.call(this,new Mi(Kt.ErrorResponse,p.message,p.status));return}(o=this.t)==null||o.error(On(h,"polling request","will retry"))}let l=Date.now()-c,u=Math.max(this.$i*1e3-l,0);(s=this.t)==null||s.debug("Elapsed: %d ms, sleeping for %d ms",l,u),this.Ft=setTimeout(()=>{this.be()},u)}start(){this.be()}stop(){this.Ft&&(clearTimeout(this.Ft),this.Ft=void 0),this.u=!0}close(){this.stop()}},nI=(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 La(Kt.InvalidData,"Malformed JSON data in event stream"))};function rI(t,e){e==null||e.debug(`Received ${t} event after processor was closed. Skipping processing.`)}function up(t){t==null||t.debug("Ping completed after processor was closed. Skipping processing.")}var iI=class{constructor(t,e,n,r,i,o,s,a,c){var l;this.Ri=t,this.Ut=e,this.n=n,this.H=r,this.Mi=o,this.S=s,this.m=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.Ut.withReasons&&h.push({key:"withReasons",value:"true"}),this.H=r,this.ke=st({},e.baseHeaders),this.t=c,this.Fi=xS(e.serviceEndpoints,u,h)}xe(){this.ft=Date.now()}Vt(t){this.ft&&this.S&&this.S.recordStreamInit(this.ft,!t,Date.now()-this.ft),this.ft=void 0}Ui(t){var e,n,r;return kp(t)?((r=this.t)==null||r.warn(On(t,"streaming request","will retry")),this.Vt(!1),this.xe(),!0):(this.Vt(!1),(e=this.m)==null||e.call(this,new La(Kt.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error(On(t,"streaming request")),!1)}start(){this.xe();let t;this.Ut.useReport?(this.ke["content-type"]="application/json",t={method:"REPORT",body:this.Ri}):t={};let e=this.H.createEventSource(this.Fi,fe(st({headers:this.ke},t),{errorFilter:n=>this.Ui(n),initialRetryDelayMillis:this.Ut.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3}));this.Se=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){rI(i,this.t);return}if((s=this.t)==null||s.debug(`Received ${i} event`),o!=null&&o.data){this.Vt(!0);let{data:c}=o,l=n(c);if(!l){nI(i,c,this.t,this.m);return}r(l)}else(a=this.m)==null||a.call(this,new La(Kt.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.Mi.requestPayload();try{if(this.u){up(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.m)==null||a.call(this,new Mi(Kt.InvalidData,"Malformed JSON data in ping polling response"))}}catch(l){if(this.u){up(this.t);return}let u=l;(c=this.m)==null||c.call(this,new Mi(Kt.ErrorResponse,u.message,u.status))}})}stop(){var t;(t=this.Se)==null||t.close(),this.Se=void 0,this.u=!0}close(){this.stop()}},oI=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=tI(a),this.q=qw(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.Vi=t}createPollingProcessor(t,e,n,r,i){let o=new eI(n,this.config.pollInterval,async s=>{await this.q.handlePut(e,s),r==null||r()},s=>{this.emitter.emit("error",t,s),this.q.handlePollingError(s),i==null||i(s)},this.logger);this.updateProcessor=this.Le(o,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,r,i){var o;let s=new iI(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.Vi)==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.q.handleStreamingError(a),i==null||i(a)},this.logger);this.updateProcessor=this.Le(s,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async r=>{await this.q.handlePut(t,r),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async r=>{this.q.handlePatch(t,r)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async r=>{this.q.handleDelete(t,r)}}),n}Le(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 zp(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 Ki(){return typeof document!==void 0}function Da(){return typeof window!==void 0}function Bp(t,e,n){return Ki()?(document.addEventListener(t,e,n),()=>{document.removeEventListener(t,e,n)}):()=>{}}function jp(t,e,n){return Ki()?(window.addEventListener(t,e,n),()=>{window.removeEventListener(t,e,n)}):()=>{}}function mr(){return Da()?window.location.href:""}function sI(){return Da()?window.location.search:""}function aI(){return Da()?window.location.hash:""}function lI(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function cI(){return Ki()?document.visibilityState:"visibile"}function uI(t){if(Ki())return document.querySelectorAll(t)}var hI="[BrowserDataManager]",pI=class extends oI{constructor(t,e,n,r,i,o,s,a,c,l){super(t,e,n,r,o,s,a,c,l),this.Xi=i,this.tt=void 0,this.jt=!1,this.tt=i.streaming}L(t,...e){this.logger.debug(`${hI} ${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.Ht=i==null?void 0:i.hash,i!=null&&i.bootstrap?this.ji(n,i,t):(await this.flagManager.loadCached(n)&&this.L("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Hi(n,t,e)),this.Bt()}async Bi(t){let e=JSON.stringify(Vn.toLDContext(t)),n=qh(e,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ht),r=3,i;for(let o=0;o<=r;o+=1)try{return await n.requestPayload()}catch(s){if(!kp(s))throw s;i=s,o<r&&(this.L(On(s,"initial poll request","will retry")),await Vp(1e3))}throw i}async Hi(t,e,n){var r,i;try{this.dataSourceStatusManager.requestStateUpdate(ew.Initializing);let o=await this.Bi(t);try{let s=this.createStreamListeners(t,e).get("put");s.processJson(s.deserializeData(o))}catch(s){this.dataSourceStatusManager.reportError(Kt.InvalidData,(r=s.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(Kt.NetworkError,(i=o.message)!=null?i:"unexpected network error",o.status),n(o)}}ji(t,e,n){let{bootstrapParsed:r}=e;r||(r=zp(this.logger,e.bootstrap)),this.flagManager.setBootstrap(t,r),this.L("Identify - Initialization completed from bootstrap"),n()}setForcedStreaming(t){this.tt=t,this.Bt()}setAutomaticStreamingState(t){this.jt=t,this.Bt()}Bt(){let t=this.tt||this.jt&&this.tt===void 0;this.L(`Updating streaming state. forced(${this.tt}) automatic(${this.jt})`),t?this.zi():this.Gi()}Gi(){var t;this.updateProcessor&&this.L("Stopping update processor."),(t=this.updateProcessor)==null||t.close(),this.updateProcessor=void 0}zi(){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.Ki(this.context)}Ki(t,e,n){var r;let i=Vn.toLDContext(t);(r=this.updateProcessor)==null||r.close();let o=JSON.stringify(Vn.toLDContext(t)),s=qh(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ht);this.createStreamingProcessor(i,t,s,e,n),this.updateProcessor.start()}};function dI(t){let e=Bp("visibilitychange",()=>{cI()==="hidden"&&t()}),n=jp("pagehide",t);return()=>{e(),n()}}function xa(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function fI(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(`^${xa(t.url)}/?$`).test(e);case"canonical":return new RegExp(`^${xa(t.url)}/?$`).test(i);case"substring":return new RegExp(`.*${xa(t.substring)}.*$`).test(i);case"regex":return new RegExp(t.pattern).test(i);default:return!1}}function mI(t,e){let n=[];return e.forEach(r=>{let i=t.target,{selector:o}=r,s=uI(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 yI=class{constructor(t,e){let n=t.filter(o=>{var s;return(s=o.urls)==null?void 0:s.some(a=>fI(a,mr(),sI(),aI()))}),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=>{mI(s,i).forEach(a=>{e(a)})};this.Ce=Bp("click",o)}}close(){var t;(t=this.Ce)==null||t.call(this)}},gI=300,bI=class{constructor(t){this.zt=mr();let e=()=>{let r=mr();r!==this.zt&&(this.zt=r,t())};this.Gt=setInterval(e,gI);let n=jp("popstate",e);this.Ie=()=>{n()}}close(){var t;this.Gt&&clearInterval(this.Gt),(t=this.Ie)==null||t.call(this)}},vI=class{constructor(t,e,n,r,i,o=s=>new bI(s)){this.H=e,this.qi=r,this.Pr=i,this.pt=[],this.Pe=!1,this.gt=`${n}/sdk/goals/${t}`,this.Ae=o(()=>{this.Wt()})}async initialize(){await this.Wi(),this.Wt()}startTracking(){this.Pe=!0,this.Wt()}Wt(){var t;this.Pe&&((t=this.Kt)==null||t.close(),this.pt&&this.pt.length&&(this.Kt=new yI(this.pt,e=>{this.Pr(mr(),e)})))}async Wi(){try{let t=await this.H.fetch(this.gt);this.pt=await t.json()}catch(t){this.qi(new Rp(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.Ae)==null||t.close(),(e=this.Kt)==null||e.close()}};function SI(t){return t.kind==="click"}var wI=2,Qp={fetchGoals:!0,eventUrlTransformer:t=>t,streaming:void 0,plugins:[]},II={fetchGoals:G.Boolean,eventUrlTransformer:G.Function,streaming:G.Boolean,plugins:G.createTypeArray("LDPlugin",{})};function TI(t){var e;let n=st({},t);return(e=n.flushInterval)!=null||(n.flushInterval=wI),n}function EI(t){let e=TI(t);return Object.keys(Qp).forEach(n=>{delete e[n]}),e}function RI(t,e){let n=st({},Qp);return Object.entries(II).forEach(r=>{let[i,o]=r,s=t[i];s!==void 0&&(o.is(s)?n[i]=s:e.warn(We.wrongOptionType(i,o.getType(),typeof s)))}),n}var CI=class{constructor(t,e){switch(this.Ji=t,this.Oe=[],e){case"sha1":this.No="SHA-1";break;case"sha256":this.No="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.Oe.join(""),n=new TextEncoder().encode(e),r=await this.Ji.subtle.digest(this.No,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.Oe.push(t),this}},ZI={start:0,end:3},kI={start:4,end:5},Na={start:6,end:7},Oa={start:8,end:8},VI={start:9,end:9},xI={start:10,end:15};function NI(){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 Zn(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 OI(t){return t[Oa.start]=(t[Oa.start]|128)&191,t[Na.start]=t[Na.start]&15|64,`${Zn(t,ZI)}-${Zn(t,kI)}-${Zn(t,Na)}-${Zn(t,Oa)}${Zn(t,VI)}-${Zn(t,xI)}`}function GI(){let t=NI();return OI(t)}function LI(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():GI()}var XI=class{createHash(t){return new CI(lI(),t)}randomUUID(){return LI()}};function WI(t){let e=Array.from(t,n=>String.fromCodePoint(n)).join("");return btoa(e)}var UI=class{btoa(t){return WI(new TextEncoder().encode(t))}},PI=class{constructor(t){this.e=t}platformData(){return{name:"JS"}}sdkData(){let t={name:"@launchdarkly/js-client-sdk",version:"4.0.0",userAgentBase:"JSClient"};return this.e.wrapperName&&(t.wrapperName=this.e.wrapperName),this.e.wrapperVersion&&(t.wrapperVersion=this.e.wrapperVersion),t}},MI=class{constructor(t,e){this.gt=t,this.n={},this.I=new vS(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.Te=e.errorFilter,this.$e()}$e(){this.J=new EventSource(this.gt),this.J.onopen=()=>{var t;this.I.success(),(t=this.onopen)==null||t.call(this)},this.J.onerror=t=>{var e;this.Yi(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.n).forEach(([t,e])=>{e.forEach(n=>{var r;(r=this.J)==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.J)==null||i.addEventListener(t,e)}close(){var t,e;clearTimeout(this.qt),this.qt=void 0,(t=this.J)==null||t.close(),(e=this.onclose)==null||e.call(this)}Zi(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.qt=setTimeout(()=>{this.$e()},t)}Yi(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.Te(t))&&this.Zi(this.I.fail())}},FI=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new MI(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function $p(){return typeof localStorage!="undefined"}function AI(){if(!$p())return[];let t=[];for(let e=0;e<localStorage.length;e+=1){let n=localStorage.key(e);n&&t.push(n)}return t}var JI=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}`)}}},DI=class{constructor(t,e){this.encoding=new UI,this.crypto=new XI,this.requests=new FI,$p()&&(this.storage=new JI(t)),this.info=new PI(e)}},YI=class extends Qw{constructor(t,e,n={},r){var i;let{logger:o,debug:s}=n,a=o!=null?o:new Pa({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 DI(a,n),u=RI(n,a),h=EI(fe(st({},n),{logger:a})),{eventUrlTransformer:p}=u;super(t,e,l,h,(f,m,d,v,b)=>new pI(l,f,t,m,u,()=>({pathGet(I,R){return`/sdk/evalx/${t}/contexts/${Bh(R,I)}`},pathReport(I,R){return`/sdk/evalx/${t}/context`},pathPing(I,R){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(I,R){return`/eval/${t}/${Bh(R,I)}`},pathReport(I,R){return`/eval/${t}`},pathPing(I,R){return`/ping/${t}`}}),d,v,b),{getLegacyStorageKeys:()=>AI().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 pe.InputCustomEvent(f.context,f.key,f.data,f.metricValue,f.samplingRatio,p(mr())),getImplementationHooks:f=>pe.safeGetHooks(a,f,u.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),this.Yt=u.plugins,u.fetchGoals&&(this.Jt=new vI(t,l.requests,c,f=>{a.error(f.message)},(f,m)=>{let d=this.getInternalContext();if(!d)return;let v=p(f);SI(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.Jt.initialize(),u.automaticBackgroundHandling&&dI(()=>this.flush()))}registerPlugins(t){pe.safeRegisterPlugins(this.logger,this.environmentMetadata,t,this.Yt||[]);let e=this.getDebugOverrides();e&&$w(this.logger,e,this.Yt||[])}setInitialContext(t){this.Zt=t}async identify(t,e){return super.identify(t,e)}async identifyResult(t,e){var n;if(!this.et)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.Jt)==null||n.startTracking(),i}start(t){var e,n;if(this.initializeResult)return Promise.resolve(this.initializeResult);if(this.et)return this.et;if(!this.Zt)return this.logger.error("Initial context not set"),Promise.resolve({status:"failed",error:new Error("Initial context not set")});let r=fe(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=zp(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.et=this.promiseWithTimeout(this.initializedPromise,(n=t==null?void 0:t.timeout)!=null?n:5),this.identifyResult(this.Zt,r),this.et}setStreaming(t){this.dataManager.setForcedStreaming(t)}Ne(){this.dataManager.setAutomaticStreamingState(!!this.emitter.listenerCount("change"))}on(t,e){super.on(t,e),this.Ne()}off(t,e){super.off(t,e),this.Ne()}};function KI(t,e,n,r={},i){let o=new YI(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 DF(t){return new Pa(t)}function qp(t,e,n){return KI(t,e,Fi.Disabled,n)}var _I=Object.defineProperty,HI=(t,e,n)=>e in t?_I(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ie=(t,e,n)=>HI(t,typeof e!="symbol"?e+"":e,n),zI=(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())}),Ze=(t,e,...n)=>{let r=`[@launchdarkly plugins]: (${t}): `;console[e].apply(console,[r,...n]),BI(r,...n)},BI=(t,...e)=>zI(void 0,null,function*(){try{let{LDObserve:n}=yield Promise.resolve().then(()=>tR);n.recordLog(`${t}${e}`,"warn")}catch(n){}}),jI=class{constructor(t,e){Ie(this,"debug"),Ie(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])}},bo=class{constructor(){Ie(this,"_sdk"),Ie(this,"_isLoaded",!1),Ie(this,"_callBuffer",[]),Ie(this,"_capacity",1e5),Ie(this,"_droppedEvents",0),Ie(this,"_exceededCapacity",!1),Ie(this,"_logger",new jI)}h(e,n){if(this.Nn)try{return this.jn[e](...n)}catch(r){Ze(`Error executing buffered call to ${e}:`,"error",r)}else{this.Mr({method:e,args:n});return}}Mr(e){this.wn.length<this.Ws?(this.wn.push(e),this.Qn=!1):(this.Qn||(this.Qn=!0,Ze("Exceeded event queue capacity. Increase capacity to avoid dropping events.","warn")),this.Us+=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){Ze(`Error executing buffered call to ${n}:`,"error",i)}this.wn=[]}},QI=Object.defineProperty,$I=Object.defineProperties,qI=Object.getOwnPropertyDescriptors,vo=Object.getOwnPropertySymbols,Uf=Object.prototype.hasOwnProperty,Pf=Object.prototype.propertyIsEnumerable,Cl=(t,e,n)=>e in t?QI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,j=(t,e)=>{for(var n in e||(e={}))Uf.call(e,n)&&Cl(t,n,e[n]);if(vo)for(var n of vo(e))Pf.call(e,n)&&Cl(t,n,e[n]);return t},Fn=(t,e)=>$I(t,qI(e)),Vr=(t,e)=>{var n={};for(var r in t)Uf.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&vo)for(var r of vo(t))e.indexOf(r)<0&&Pf.call(t,r)&&(n[r]=t[r]);return n},Xr=(t,e,n)=>Cl(t,typeof e!="symbol"?e+"":e,n),Jn=(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 tT(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 ao(t,e){throw new Error(e)}function eT(t){return typeof t=="object"&&t!==null}function nT(t,e){throw new Error("Unexpected invariant triggered.")}var rT=/\r\n|[\n\r]/g;function Zl(t,e){let n=0,r=1;for(let i of t.body.matchAll(rT)){if(typeof i.index=="number"||nT(),i.index>=e)break;n=i.index+i[0].length,r+=1}return{line:r,column:e+1-n}}function iT(t){return Mf(t.source,Zl(t.source,t.start))}function Mf(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+td([[`${s} |`,m[0]],...m.slice(1,p+1).map(d=>["|",d]),["|","^".padStart(f)],["|",m[p+1]]])}return l+td([[`${s-1} |`,u[i-1]],[`${s} |`,h],["|","^".padStart(c)],[`${s+1} |`,u[i+1]]])}function td(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 oT(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 sT=class Ff extends Error{constructor(e,...n){var r,i,o;let{nodes:s,source:a,positions:c,path:l,originalError:u,extensions:h}=oT(n);super(e),this.name="GraphQLError",this.path=l!=null?l:void 0,this.originalError=u!=null?u:void 0,this.nodes=ed(Array.isArray(s)?s:s?[s]:void 0);let p=ed((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=>Zl(a,m)):p==null?void 0:p.map(m=>Zl(m.source,m.start));let f=eT(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,Ff):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
|
|