@launchdarkly/react-sdk 0.1.1 → 0.2.1

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 CHANGED
@@ -1,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.1](https://github.com/launchdarkly/js-core/compare/react-sdk-v0.2.0...react-sdk-v0.2.1) (2026-04-17)
4
+
5
+
6
+ ### Dependencies
7
+
8
+ * The following workspace dependencies were updated
9
+ * dependencies
10
+ * @launchdarkly/js-client-sdk bumped from ^4.5.0 to ^4.6.0
11
+
12
+ ## [0.2.0](https://github.com/launchdarkly/js-core/compare/react-sdk-v0.1.1...react-sdk-v0.2.0) (2026-04-14)
13
+
14
+
15
+ ### Features
16
+
17
+ * adding isomorphic provider to bridge client and server ([#1218](https://github.com/launchdarkly/js-core/issues/1218)) ([d766f39](https://github.com/launchdarkly/js-core/commit/d766f39c0d178cc66c80644c3cecddb6e7131c93))
18
+ * support static client component rendering ([#1227](https://github.com/launchdarkly/js-core/issues/1227)) ([6b3a100](https://github.com/launchdarkly/js-core/commit/6b3a1001844cdeccb378a402283673bf35760369))
19
+
20
+
21
+ ### Bug Fixes
22
+
23
+ * adding wrapper name for react client ([#1199](https://github.com/launchdarkly/js-core/issues/1199)) ([f92a8f9](https://github.com/launchdarkly/js-core/commit/f92a8f9d9b7f15c344745be13ce16d6a03a0c126))
24
+ * **deps:** update dependency next to v16.2.3 [security] ([#1263](https://github.com/launchdarkly/js-core/issues/1263)) ([10f582a](https://github.com/launchdarkly/js-core/commit/10f582a460342f6352735b1cd3f93af1f57ba303))
25
+ * **react-sdk:** double evaluation on client side init ([#1229](https://github.com/launchdarkly/js-core/issues/1229)) ([6a4c42f](https://github.com/launchdarkly/js-core/commit/6a4c42f1bc2e73efa16b1317d10dbc6026d53628))
26
+
27
+
28
+ ### Dependencies
29
+
30
+ * The following workspace dependencies were updated
31
+ * dependencies
32
+ * @launchdarkly/js-client-sdk bumped from ^4.4.1 to ^4.5.0
33
+ * @launchdarkly/js-server-sdk-common bumped from ^2.18.3 to ^2.18.4
34
+
3
35
  ## [0.1.1](https://github.com/launchdarkly/js-core/compare/react-sdk-v0.1.0...react-sdk-v0.1.1) (2026-03-24)
4
36
 
5
37
 
package/README.md CHANGED
@@ -16,6 +16,9 @@
16
16
 
17
17
  ☝️☝️☝️
18
18
 
19
+ ## Getting started
20
+ Refer to the [SDK documentation](https://launchdarkly.com/docs/sdk/client-side/react/react-web#get-started) for instructions on getting started with using the SDK.
21
+
19
22
  ## About LaunchDarkly
20
23
 
21
24
  - LaunchDarkly is a continuous delivery platform that provides feature flags as a service and allows developers to iterate quickly and safely. We allow you to easily flag your features and manage them from the LaunchDarkly dashboard. With LaunchDarkly, you can:
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";var Ei=Object.create;var q=Object.defineProperty,xi=Object.defineProperties,Ci=Object.getOwnPropertyDescriptor,Si=Object.getOwnPropertyDescriptors,Ri=Object.getOwnPropertyNames,At=Object.getOwnPropertySymbols,Oi=Object.getPrototypeOf,Mt=Object.prototype.hasOwnProperty,Ii=Object.prototype.propertyIsEnumerable;var Vt=(t,e,i)=>e in t?q(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,A=(t,e)=>{for(var i in e||(e={}))Mt.call(e,i)&&Vt(t,i,e[i]);if(At)for(var i of At(e))Ii.call(e,i)&&Vt(t,i,e[i]);return t},V=(t,e)=>xi(t,Si(e));var Li=(t,e)=>{for(var i in e)q(t,i,{get:e[i],enumerable:!0})},Ft=(t,e,i,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ri(e))!Mt.call(t,r)&&r!==i&&q(t,r,{get:()=>e[r],enumerable:!(n=Ci(e,r))||n.enumerable});return t};var $i=(t,e,i)=>(i=t!=null?Ei(Oi(t)):{},Ft(e||!t||!t.__esModule?q(i,"default",{value:t,enumerable:!0}):i,t)),Ti=t=>Ft(q({},"__esModule",{value:!0}),t);var qa={};Li(qa,{LDReactContext:()=>R,createClient:()=>ht,createLDReactProvider:()=>li,createLDReactProviderWithClient:()=>jt,initLDReactContext:()=>dt,useBoolVariation:()=>pi,useBoolVariationDetail:()=>wi,useFlags:()=>ci,useInitializationStatus:()=>di,useJsonVariation:()=>yi,useJsonVariationDetail:()=>Di,useLDClient:()=>gi,useNumberVariation:()=>mi,useNumberVariationDetail:()=>ki,useStringVariation:()=>vi,useStringVariationDetail:()=>bi});module.exports=Ti(qa);var Ut=require("react");function dt(){return(0,Ut.createContext)(null)}var R=dt();var H=$i(require("react"),1);var Pi=Object.defineProperty,Ni=Object.defineProperties,ji=Object.getOwnPropertyDescriptors,et=Object.getOwnPropertySymbols,de=Object.prototype.hasOwnProperty,fe=Object.prototype.propertyIsEnumerable,zt=(t,e,i)=>e in t?Pi(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,v=(t,e)=>{for(var i in e||(e={}))de.call(e,i)&&zt(t,i,e[i]);if(et)for(var i of et(e))fe.call(e,i)&&zt(t,i,e[i]);return t},T=(t,e)=>Ni(t,ji(e)),ge=(t,e)=>{var i={};for(var n in t)de.call(t,n)&&e.indexOf(n)<0&&(i[n]=t[n]);if(t!=null&&et)for(var n of et(t))e.indexOf(n)<0&&fe.call(t,n)&&(i[n]=t[n]);return i};function Ai(t){return`/${t.replace(/~/g,"~0").replace(/\//g,"~1")}`}function pe(t){return t.indexOf("~")?t.replace(/~1/g,"/").replace(/~0/g,"~"):t}function Vi(t){return(t.startsWith("/")?t.substring(1):t).split("/").map(e=>pe(e))}function Mi(t){return!t.startsWith("/")}function Fi(t){return!t.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var z=class{constructor(t,e=!1){if(e){let i=t;this.g=[i],this.isValid=i!=="",this.redactionName=i.startsWith("/")?Ai(i):i}else{if(this.redactionName=t,t===""||t==="/"||!Fi(t)){this.isValid=!1,this.g=[];return}Mi(t)?this.g=[t]:t.indexOf("/",1)<0?this.g=[pe(t.slice(1))]:this.g=Vi(t),this.g[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{g:e,isValid:i}=this;if(!i)return;let n=t;for(let r=0;r<e.length;r+=1){let a=e[r];if(n!=null&&Object.prototype.hasOwnProperty.call(n,a)&&typeof n=="object"&&!Array.isArray(n))n=n[a];else return}return n}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,i)=>e===t.getComponent(i))}get components(){return[...this.g]}};z.InvalidReference=new z("");var Ui=class{is(t){if(Array.isArray(t))return!1;let e=typeof t;return e==="function"||e==="object"}getType(){return"factory method or object"}},B=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}},ve=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}},me=class extends B{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},ye=class extends B{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},zi=class{is(t){return typeof t=="function"}getType(){return"function"}},Ki=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},Ji=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,Bi=class{is(t){return typeof t=="number"||typeof t=="string"&&Ji.test(t)}getType(){return"date"}},Hi=class extends ye{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},qi=class{constructor(t){this.Yt=t}is(t){return typeof t=="string"&&this.Yt.includes(t)}getType(){return this.Yt.join(" | ")}};function N(t){return t==null}var d=class{static createTypeArray(t,e){return new ve(t,e)}static numberWithMin(t){return new me(t)}static stringMatchingRegex(t){return new ye(t)}static oneOf(...t){return new qi(t)}};d.String=new B("string","");d.Number=new B("number",0);d.ObjectOrFactory=new Ui;d.Object=new B("object",{});d.StringArray=new ve("string[]","");d.Boolean=new B("boolean",!0);d.Function=new zi;d.Date=new Bi;d.Kind=new Hi;d.NullableBoolean=new Ki;function we(t){return"kind"in t?d.String.is(t.kind)&&t.kind!=="multi":!1}function be(t){return"kind"in t?d.String.is(t.kind)&&t.kind==="multi":!1}function ke(t){return!("kind"in t)||t.kind===null||t.kind===void 0}function it(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(i=>it(i,[...e,t])).map(i=>i===void 0?"null":i).join(",")}]`:`{${Object.keys(t).sort().map(i=>{let n=it(t[i],[...e,t]);if(n!==void 0)return`${JSON.stringify(i)}:${n}`}).filter(i=>i!==void 0).join(",")}}`}var Dt="user";function Kt(t){return t.includes("%")||t.includes(":")?t.replace(/%/g,"%25").replace(/:/g,"%3A"):t}function _i(t){return t&&d.Object.is(t)}function Jt(t){return d.Kind.is(t)}function Bt(t){return d.String.is(t)&&t!==""}function ft(t,e=!1){return t?t.map(i=>new z(i,e)):[]}function Wi(t){return t!=null}function Gi(t){let e=T(v({},t.custom||[]),{kind:"user",key:String(t.key)});if(Wi(t.anonymous)){let i=!!t.anonymous;delete e.anonymous,e.anonymous=i}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 U=class y{constructor(e,i,n){this.P=!1,this.Q=!1,this.Zt=!1,this.$={},this.kind=i,this.valid=e,this.message=n}static D(e,i){return new y(!1,e,i)}static Re(e,i){if(!(!i||!e.isValid))return e.depth===1&&e.getComponent(0)==="anonymous"?!!(i!=null&&i.anonymous):e.get(i)}Xt(e){if(this.P)return this.$[e];if(this.kind===e)return this.v}static Ne(e){let i=Object.keys(e).filter(l=>l!=="kind"),n=i.every(Jt);if(!i.length)return y.D("multi","A multi-kind context must contain at least one kind");if(!n)return y.D("multi","Context contains invalid kinds");let r={},a=!0,o=i.reduce((l,u)=>{var c;let h=e[u];return _i(h)?(l[u]=h,r[u]=ft((c=h._meta)==null?void 0:c.privateAttributes)):a=!1,l},{});if(!a)return y.D("multi","Context contained contexts that were not objects");if(!Object.values(o).every(l=>Bt(l.key)))return y.D("multi","Context contained invalid keys");if(i.length===1){let l=i[0],u=new y(!0,l);return u.v=T(v({},o[l]),{kind:l}),u.tt=r,u.Q=l==="user",u}let s=new y(!0,e.kind);return s.$=o,s.tt=r,s.P=!0,s}static Me(e){var i;let{key:n,kind:r}=e,a=Jt(r),o=Bt(n);if(!a)return y.D(r!=null?r:"unknown","The kind was not valid for the context");if(!o)return y.D(r,"The key for the context was not valid");let s=ft((i=e._meta)==null?void 0:i.privateAttributes),l=new y(!0,r);return l.Q=r==="user",l.v=e,l.tt={[r]:s},l}static Fe(e){if(!(e.key!==void 0&&e.key!==null))return y.D("user","The key for the context was not valid");let i=new y(!0,"user");return i.Q=!0,i.Zt=!0,i.v=Gi(e),i.tt={user:ft(e.privateAttributeNames,!0)},i}static fromLDContext(e){return e?we(e)?y.Me(e):be(e)?y.Ne(e):ke(e)?y.Fe(e):y.D("unknown","Context was not of a valid kind"):y.D("unknown","No context specified. Returning default value")}static toLDContext(e){if(!e.valid)return;let i=e.getContexts();if(!e.P)return i[0][1];let n={kind:"multi"};return i.forEach(r=>{let a=r[0],o=r[1];n[a]=o}),n}valueForKind(e,i=Dt){return e.isKind?this.kinds:y.Re(e,this.Xt(i))}key(e=Dt){var i;return(i=this.Xt(e))==null?void 0:i.key}get isMultiKind(){return this.P}get canonicalKey(){return this.Q?this.v.key:this.P?Object.keys(this.$).sort().map(e=>`${e}:${Kt(this.$[e].key)}`).join(":"):`${this.kind}:${Kt(this.v.key)}`}get kinds(){return this.P?Object.keys(this.$):[this.kind]}get kindsAndKeys(){return this.P?Object.entries(this.$).reduce((e,[i,n])=>(e[i]=n.key,e),{}):{[this.kind]:this.v.key}}privateAttributes(e){var i;return((i=this.tt)==null?void 0:i[e])||[]}getContexts(){return this.P?Object.entries(this.$):[[this.kind,this.v]]}get legacy(){return this.Zt}canonicalUnfilteredJson(){if(this.valid){if(this.gt)return this.gt;try{this.gt=it(y.toLDContext(this))}catch(e){}return this.gt}}};U.UserKind=Dt;var Zi=["key","kind","_meta","anonymous"].map(t=>new z(t,!0)),Yi=["name","ip","firstName","lastName","email","avatar","country"];function Qi(t,e){return t.depth===e.length&&e.every((i,n)=>i===t.getComponent(n))}function Xi(t,e){let i=[],n={},r=[];for(i.push(...Object.keys(t).map(a=>({key:a,ptr:[a],source:t,parent:n,visited:[t]})));i.length;){let a=i.pop(),o=e.find(s=>Qi(s,a.ptr));if(o)r.push(o.redactionName);else{let s=a.source[a.key];s===null?a.parent[a.key]=s:Array.isArray(s)?a.parent[a.key]=[...s]:typeof s=="object"?a.visited.includes(s)||(a.parent[a.key]={},i.push(...Object.keys(s).map(l=>({key:l,ptr:[...a.ptr,l],source:s,parent:a.parent[a.key],visited:[...a.visited,s]})))):a.parent[a.key]=s}}return{cloned:n,excluded:r.sort()}}var tn=class{constructor(t,e){this.Ue=t,this.je=e}filter(t,e=!1){let i=t.getContexts();if(i.length===1)return this.Qt(t,i[0][1],i[0][0],e);let n={kind:"multi"};return i.forEach(([r,a])=>{n[r]=this.Qt(t,a,r,e)}),n}p(t,e,i,n){return(n?Object.keys(e).map(r=>new z(r,!0)):[...this.je,...t.privateAttributes(i)]).filter(r=>!Zi.some(a=>a.compare(r)))}Qt(t,e,i,n){let r=this.Ue||n&&e.anonymous===!0,{cloned:a,excluded:o}=Xi(e,this.p(t,e,i,r));return t.legacy&&Yi.forEach(s=>{s in a&&(a[s]=String(a[s]))}),o.length&&(a._meta||(a._meta={}),a._meta.redactedAttributes=o),a._meta&&(delete a._meta.privateAttributes,Object.keys(a._meta).length===0&&delete a._meta),a}},Ht=30*1e3,en=.5,nn=class{constructor(t,e,i=Math.random){this.Ve=e,this.He=i,this.yt=0,this.te=Math.max(1,t),this.ze=Math.ceil(Math.log2(Ht/this.te))}C(){let t=Math.min(this.yt,this.ze),e=this.te*2**t;return Math.min(e,Ht)}Be(t){return t-Math.trunc(this.He()*en*t)}success(t=Date.now()){this.vt=t}fail(t=Date.now()){this.vt!==void 0&&t-this.vt>this.Ve&&(this.yt=0),this.vt=void 0;let e=this.Be(this.C());return this.yt+=1,e}},qt;(function(t){t[t.Valid=0]="Valid",t[t.Initializing=1]="Initializing",t[t.Interrupted=2]="Interrupted",t[t.Closed=3]="Closed"})(qt||(qt={}));var nt=class extends Error{constructor(t,e,i,n=!0){super(e),this.kind=t,this.status=i,this.name="LaunchDarklyPollingError",this.recoverable=n}},Et=class extends Error{constructor(t,e,i,n=!0){super(e),this.kind=t,this.code=i,this.name="LaunchDarklyStreamingError",this.recoverable=n}},Ga=120*1e3,Za=300*1e3,E;(function(t){t.Unknown="UNKNOWN",t.NetworkError="NETWORK_ERROR",t.ErrorResponse="ERROR_RESPONSE",t.InvalidData="INVALID_DATA"})(E||(E={}));var rt;(function(t){t[t.Disabled=0]="Disabled",t[t.Enabled=1]="Enabled"})(rt||(rt={}));var K;(function(t){t[t.AnalyticsEvents=0]="AnalyticsEvents",t[t.DiagnosticEvent=1]="DiagnosticEvent"})(K||(K={}));var j;(function(t){t[t.Succeeded=0]="Succeeded",t[t.Failed=1]="Failed",t[t.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(j||(j={}));function F(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 rn(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(Number(t))}function an(t){return typeof t=="symbol"?"NaN":typeof t=="bigint"?`${t}n`:String(parseInt(t,10))}function sn(t){return typeof t=="symbol"?"NaN":String(parseFloat(t))}var gt={s:t=>F(t),d:t=>rn(t),i:t=>an(t),f:t=>sn(t),j:t=>F(t),o:t=>F(t),O:t=>F(t),c:()=>""};function xt(...t){var e;let i=t.shift();if(d.String.is(i)){let n="",r=0;for(;r<i.length;){let a=i.charAt(r);if(a==="%"){if(r+1<i.length){let o=i.charAt(r+1);if(o in gt&&t.length){let s=t.shift();n+=(e=gt[o])==null?void 0:e.call(gt,s)}else o==="%"?n+="%":n+=`%${o}`;r+=2}}else n+=a,r+=1}return t.length&&(n.length&&(n+=" "),n+=t.map(F).join(" ")),n}return t.map(F).join(" ")}var b;(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"})(b||(b={}));var on=["debug","info","warn","error","none"],De=class Ee{static get(){return new Ee({})}constructor(e){var i,n,r;if(this.Xe=(n=b[(i=e.level)!=null?i:"info"])!=null?n:b.info,this.Qe=(r=e.name)!=null?r:"LaunchDarkly",this.se=e.formatter,typeof e.destination=="object")this.ae={[b.debug]:e.destination.debug,[b.info]:e.destination.info,[b.warn]:e.destination.warn,[b.error]:e.destination.error};else if(typeof e.destination=="function"){let{destination:a}=e;this.ae={[b.debug]:a,[b.info]:a,[b.warn]:a,[b.error]:a}}}tn(...e){var i;try{return this.se?(i=this.se)==null?void 0:i.call(this,...e):xt(...e)}catch(n){return xt(...e)}}en(e,i){try{e(i)}catch(n){console.error(i)}}k(e,i){var n;if(e>=this.Xe){let r=`${on[e]}: [${this.Qe}]`;try{let a=(n=this.ae)==null?void 0:n[e];a?this.en(a,`${r} ${this.tn(...i)}`):console.error(...i)}catch(a){console.error(...i)}}}error(...e){this.k(b.error,e)}warn(...e){this.k(b.warn,e)}info(...e){this.k(b.info,e)}debug(...e){this.k(b.debug,e)}},ln={error:d.Function,warn:d.Function,info:d.Function,debug:d.Function},xe=class{constructor(t,e){Object.entries(ln).forEach(([i,n])=>{if(!n.is(t[i]))throw new Error(`Provided logger instance must support logger.${i}(...) method`)}),this.t=t,this.nn=e}k(t,e){try{this.t[t](...e)}catch(i){this.nn[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)}},Ce=t=>{let e=new De({level:"info",destination:console.error,formatter:xt});return t?new xe(t,e):e},k=class{static deprecated(t,e){return`"${t}" is deprecated, please use "${e}"`}static optionBelowMinimum(t,e,i){return`Config option "${t}" had invalid value of ${e}, using minimum of ${i} instead`}static unknownOption(t){return`Ignoring unknown config option "${t}"`}static wrongOptionType(t,e,i){return`Config option "${t}" should be of type ${e}, got ${i}, 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`}},un=/^(\w|\.|-)+$/,cn=d.stringMatchingRegex(un),hn={is:(t,e)=>cn.is(t)?t.length>64?{valid:!1,message:k.tagValueTooLong(e)}:{valid:!0}:{valid:!1,message:k.invalidTagValue(e)}},dn=class{constructor(t){let e={},i=t==null?void 0:t.application,n=t==null?void 0:t.logger;i&&Object.entries(i).forEach(([a,o])=>{if(o!=null){let{valid:s,message:l}=hn.is(o,`application.${a}`);s?a==="versionName"?e["application-version-name"]=[o]:e[`application-${a}`]=[o]:n==null||n.warn(l)}});let r=Object.keys(e);r.length&&(this.value=r.sort().flatMap(a=>e[a].sort().map(o=>`${a}/${o}`)).join(" "))}},fn=class{constructor(t,e,i){this.platform=i,this.basicConfiguration={tags:e.tags,logger:e.logger,offline:e.offline,serviceEndpoints:e.serviceEndpoints,sdkKey:t}}};function pt(t){return t.replace(/\/+$/,"")}function Ot(t){return t.replace(/^\/+/,"").replace(/\?$/,"")}var at=class Se{constructor(e,i,n=Se.DEFAULT_EVENTS,r="/bulk",a="/diagnostic",o=!0,s){this.streaming=pt(e),this.polling=pt(i),this.events=pt(n),this.analyticsEventPath=r,this.diagnosticEventPath=a,this.includeAuthorizationHeader=o,this.payloadFilterKey=s}};at.DEFAULT_EVENTS="https://events.launchdarkly.com";function It(t,e=[]){if(e.length===0)return t;let i=e.map(({key:n,value:r})=>`${n}=${r}`);return`${t}?${i.join("&")}`}function gn(t,e,i){let n=Ot(e),r=[...i];return t.payloadFilterKey&&r.push({key:"filter",value:t.payloadFilterKey}),It(`${t.streaming}/${n}`,r)}function pn(t,e,i=[]){let n=Ot(e),r=[...i];return t.payloadFilterKey&&r.push({key:"filter",value:t.payloadFilterKey}),It(`${t.polling}/${n}`,r)}function _t(t,e,i=[]){let n=Ot(e);return It(`${t.events}/${n}`,i)}var Re=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},vn=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},Oe=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function lt(t){return t>=400&&t<500?t===400||t===408||t===429:!0}function mn(t){return t===413?!0:lt(t)}function yn(t,e){let i,n;return{promise:new Promise((r,a)=>{n=r,i=setTimeout(()=>{let o=`${e} timed out after ${t} seconds.`;a(new Oe(o))},t*1e3)}),cancel:()=>{n(),clearTimeout(i)}}}function Ie(t){return t==null?t:JSON.parse(JSON.stringify(t))}function vt(t){return Math.trunc(t*1e3)}var wn=t=>JSON.stringify(t)==="{}",Lt=(t,e)=>t&&Object.entries(t).reduce((i,[n,r])=>(r&&!wn(r)&&!(e!=null&&e.includes(n))&&(i[n]=typeof r=="object"?Lt(r,e):r),i),{});function X(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(t.constructor!==e.constructor)return!1;var i,n,r;if(Array.isArray(t)){if(i=t.length,i!=e.length)return!1;for(n=i;n--!==0;)if(!X(t[n],e[n]))return!1;return!0}if(t instanceof Map&&e instanceof Map){if(t.size!==e.size)return!1;for(n of t.entries())if(!e.has(n[0]))return!1;for(n of t.entries())if(!X(n[1],e.get(n[0])))return!1;return!0}if(t instanceof Set&&e instanceof Set){if(t.size!==e.size)return!1;for(n of t.entries())if(!e.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(e)){if(i=t.length,i!=e.length)return!1;for(n=i;n--!==0;)if(t[n]!==e[n])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(r=Object.keys(t),i=r.length,i!==Object.keys(e).length)return!1;for(n=i;n--!==0;)if(!Object.prototype.hasOwnProperty.call(e,r[n]))return!1;for(n=i;n--!==0;){var a=r[n];if(!X(t[a],e[a]))return!1}return!0}return t!==t&&e!==e}function bn(t,e,i,n=!0,r="user-agent"){let{userAgentBase:a,version:o,wrapperName:s,wrapperVersion:l}=e.sdkData(),u={[r]:`${a!=null?a:"NodeJSClient"}/${o}`};return n&&(u.authorization=t),s&&(u["x-launchdarkly-wrapper"]=l?`${s}/${l}`:s),i!=null&&i.value&&(u["x-launchdarkly-tags"]=i.value),u}function J(t,e,i){let n;t.status?n=`error ${t.status}${t.status===401?" (invalid SDK key)":""}`:n=`I/O error (${t.message||"unknown error"})`;let r=i!=null?i:"giving up permanently";return`Received ${n} for ${e} - ${r}`}function Le({status:t}){return t?lt(t):!0}var Wt=(t,e)=>e.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),$e=async(t=1e3)=>new Promise(e=>{setTimeout(e,t)}),kn=class{constructor(t,e,i){this.a=e,this.rn=i,this.bt=[],this.oe=Date.now(),this.ce=this.oe,this.ue={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var t,e,i;let n=this.a.info.sdkData(),r=this.a.info.platformData();return{kind:"diagnostic-init",id:this.ue,creationDate:this.oe,sdk:n,configuration:this.rn,platform:v({name:r.name,osArch:(t=r.os)==null?void 0:t.arch,osName:(e=r.os)==null?void 0:e.name,osVersion:(i=r.os)==null?void 0:i.version},r.additional||{})}}recordStreamInit(t,e,i){let n={timestamp:t,failed:e,durationMillis:i};this.bt.push(n)}createStatsEventAndReset(t,e,i){let n=Date.now(),r={kind:"diagnostic",id:this.ue,creationDate:n,dataSinceDate:this.ce,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:i,streamInits:this.bt};return this.bt=[],this.ce=n,r}},Ct;(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"})(Ct||(Ct={}));var Dn=Ct,Te=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};Te.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var En=class{constructor(t,e){let{basicConfiguration:i,platform:n}=t,{serviceEndpoints:{analyticsEventPath:r,diagnosticEventPath:a}}=i,{crypto:o,requests:s}=n;this.sn=v({},e),this.le=_t(i.serviceEndpoints,r,[]),this.an=_t(i.serviceEndpoints,a,[]),this._=s,this.cn=o}async et(t,e,i,n){let r={status:j.Succeeded},a=T(v({},this.sn),{"content-type":"application/json"});i&&(a["x-launchdarkly-payload-id"]=i,a["x-launchDarkly-event-schema"]="4");let o;try{let{status:s,headers:l}=await this._.fetch(e,{headers:a,body:JSON.stringify(t),compressBodyIfPossible:!0,method:"POST",keepalive:!0}),u=Date.parse(l.get("date")||"");if(u&&(r.serverTime=u),s<=204)return r;if(o=new Re(J({status:s,message:"some events were dropped"},"event posting")),!lt(s))return mn(s)?r.status=j.Failed:r.status=j.FailedAndMustShutDown,r.error=o,r}catch(s){o=s}return o&&!n?(r.status=j.Failed,r.error=o,r):(await $e(),this.et(t,this.le,i,!1))}async sendEventData(t,e){let i=t===K.AnalyticsEvents?this.cn.randomUUID():void 0,n=t===K.AnalyticsEvents?this.le:this.an;return this.et(e,n,i,!0)}};function st(t){return t.kind==="feature"}function xn(t){return t.kind==="identify"}function Cn(t){return t.kind==="migration_op"}var Sn=class{constructor(t,e,i,n,r,a){this.count=t,this.key=e,this.value=i,this.version=r,this.variation=a,this.default=n}increment(){this.count+=1}};function Rn(t){return`${t.key}:${t.variation!==null&&t.variation!==void 0?t.variation:""}:${t.version!==null&&t.version!==void 0?t.version:""}`}var Pe=class{constructor(t=!1,e){this.un=t,this.S=e,this.q=0,this.nt=0,this.it={},this.rt={}}summarizeEvent(t){if(st(t)&&!t.excludeFromSummaries){this.v||(this.v=t.context);let e=Rn(t),i=this.it[e],n=this.rt[t.key];n||(n=new Set,this.rt[t.key]=n),t.context.kinds.forEach(r=>n.add(r)),i?i.increment():this.it[e]=new Sn(1,t.key,t.value,t.default,t.version,t.variation),(this.q===0||t.creationDate<this.q)&&(this.q=t.creationDate),t.creationDate>this.nt&&(this.nt=t.creationDate)}}getSummary(){var t;let e=Object.values(this.it).reduce((n,r)=>{let a=n[r.key];a||(a={default:r.default,counters:[],contextKinds:[...this.rt[r.key]]},n[r.key]=a);let o={value:r.value,count:r.count};return r.variation!==void 0&&r.variation!==null&&(o.variation=r.variation),r.version!==void 0&&r.version!==null?o.version=r.version:o.unknown=!0,a.counters.push(o),n},{}),i={startDate:this.q,endDate:this.nt,features:e,kind:"summary",context:this.v!==void 0&&this.un?(t=this.S)==null?void 0:t.filter(this.v):void 0};return this.ln(),i}ln(){this.q=0,this.nt=0,this.it={},this.rt={}}},On=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}},In=class{constructor(t,e){this.S=t,this.t=e,this.W={}}summarizeEvent(t){var e;if(st(t)){let i=t.context.canonicalUnfilteredJson();if(!i){t.context.valid&&((e=this.t)==null||e.error("Unable to serialize context, likely the context contains a cycle."));return}let n=this.W[i];n||(this.W[i]=new Pe(!0,this.S),n=this.W[i]),n.summarizeEvent(t)}}getSummaries(){let t=this.W;return this.W={},Object.values(t).map(e=>e.getSummary())}};function tt(t){let e=Math.trunc(t);return e===1?!0:e===0?!1:Math.floor(Math.random()*e)===0}function Ln(t){return t.getSummaries!==void 0}var $n=class{constructor(t,e,i,n,r,a=!0,o=!1){this.e=t,this.st=n,this.x=r,this.at=[],this.de=0,this.Dt=0,this.kt=0,this.St=!1,this.he=0,this.xt=!1,this.Lt=null,this.dn=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.fe=new En(e,i),this.S=new tn(t.allAttributesPrivate,t.privateAttributes.map(s=>new z(s))),o?this.J=new In(this.S,this.t):this.J=new Pe,a&&this.start()}start(){var t,e;if(((t=this.st)==null?void 0:t.flushInterval)!==void 0&&(this.Lt=setInterval(()=>{var i;(i=this.st)==null||i.flush()},this.st.flushInterval*1e3)),this.hn=setInterval(async()=>{var i;try{await this.flush()}catch(n){(i=this.t)==null||i.debug(`Flush failed: ${n}`)}},this.e.flushInterval*1e3),this.x){let i=this.x.createInitEvent();this.pe(i),this.me=setInterval(()=>{let n=this.x.createStatsEventAndReset(this.Dt,this.kt,this.he);this.Dt=0,this.kt=0,this.pe(n)},this.e.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}pe(t){this.fe.sendEventData(K.DiagnosticEvent,t)}close(){clearInterval(this.hn),this.Lt&&clearInterval(this.Lt),this.me&&clearInterval(this.me)}async flush(){var t;if(this.xt)throw new On("Events cannot be posted because a permanent error has been encountered. This is most likely an invalid SDK key. The specific error information is logged independently.");let e=this.at;if(this.at=[],Ln(this.J))this.J.getSummaries().forEach(i=>{Object.keys(i.features).length&&e.push(i)});else{let i=this.J.getSummary();Object.keys(i.features).length&&e.push(i)}e.length&&(this.he=e.length,(t=this.t)==null||t.debug("Flushing %d events",e.length),await this.et(e))}sendEvent(t){var e;if(this.xt)return;if(Cn(t)){if(tt(t.samplingRatio)){let s=T(v({},t),{context:t.context?this.S.filter(t.context):void 0});s.samplingRatio===1&&delete s.samplingRatio,this.ot(s)}return}this.J.summarizeEvent(t);let i=st(t),n=i&&t.trackEvents||!i,r=this.fn(t),a=xn(t),o=(e=this.st)==null?void 0:e.processContext(t.context);o||a||(this.kt+=1),o&&!a&&this.ot(this.Ot({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),n&&tt(t.samplingRatio)&&this.ot(this.Ot(t,!1)),r&&tt(t.samplingRatio)&&this.ot(this.Ot(t,!0))}Ot(t,e){switch(t.kind){case"feature":{let i={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.S.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return t.samplingRatio!==1&&(i.samplingRatio=t.samplingRatio),t.prereqOf&&(i.prereqOf=t.prereqOf),t.variation!==void 0&&(i.variation=t.variation),t.version!==void 0&&(i.version=t.version),t.reason&&(i.reason=t.reason),i}case"index":case"identify":{let i={kind:t.kind,creationDate:t.creationDate,context:this.S.filter(t.context)};return t.samplingRatio!==1&&(i.samplingRatio=t.samplingRatio),i}case"custom":{let i={kind:"custom",creationDate:t.creationDate,key:t.key,context:this.S.filter(t.context)};return t.samplingRatio!==1&&(i.samplingRatio=t.samplingRatio),t.data!==void 0&&(i.data=t.data),t.metricValue!==void 0&&(i.metricValue=t.metricValue),t.url!==void 0&&(i.url=t.url),i}case"click":return{kind:"click",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url,selector:t.selector};case"pageview":return{kind:"pageview",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url};default:return t}}ot(t){var e;this.at.length<this.dn?(this.at.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.Dt+=1)}fn(t){return st(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.de&&t.debugEventsUntilDate>Date.now()}async et(t){let e=await this.fe.sendEventData(K.AnalyticsEvents,t);if(e.status===j.FailedAndMustShutDown&&(this.xt=!0),e.serverTime&&(this.de=e.serverTime),e.error)throw e.error}},Ne=class{constructor(t,e,i,n,r=1,a){this.context=t,this.key=e,this.data=i,this.metricValue=n,this.samplingRatio=r,this.url=a,this.kind="custom",this.creationDate=Date.now(),this.context=t}},St=class{constructor(t,e,i,n,r,a,o,s,l,u,c,h,g=1){this.withReasons=t,this.context=e,this.key=i,this.samplingRatio=g,this.kind="feature",this.creationDate=Date.now(),this.value=n,this.default=r,a!==void 0&&(this.version=a),o!==void 0&&(this.variation=o),s!==void 0&&(this.trackEvents=s),l!==void 0&&(this.prereqOf=l),u!==void 0&&(this.reason=u),c!==void 0&&(this.debugEventsUntilDate=c),h!==void 0&&(this.excludeFromSummaries=h)}},je=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},Tn=class{close(){}async flush(){}sendEvent(){}},Pn=class{constructor(t){this.Pt=t}evalEvent(t){var e;return new St(this.Pt,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.Pt||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,i){return new St(this.Pt,i,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new je(t,1)}customEvent(t,e,i,n,r=1){return new Ne(e,t,i!=null?i:void 0,n!=null?n:void 0,r)}},Gt="FDv1Fallback";function Nn(t){return{pn:t,ge:"",useSelector(e){return this.ge=e,this},processFullTransfer(e){let i=[{event:"server-intent",data:{payloads:[{id:Gt,target:1,intentCode:"xfer-full",reason:"payload-missing"}]}}];Object.entries((e==null?void 0:e.flags)||[]).forEach(([n,r])=>{i.push({event:"put-object",data:{kind:"flag",key:n,version:r.version||1,object:r}})}),Object.entries((e==null?void 0:e.segments)||[]).forEach(([n,r])=>{i.push({event:"put-object",data:{kind:"segment",key:n,version:r.version||1,object:r}})}),i.push({event:"payload-transferred",data:{state:this.ge,version:1,id:Gt}}),this.pn.processEvents(i)}}}var S={type:"none"};function Ae(t,e){let i="inactive",n,r="partial",a=[];function o(f,x){var C;return(C=t[f])==null?void 0:C.call(t,x)}function s(){i="inactive",n=void 0,r="partial",a=[]}function l(){i="changes",r="partial",a=[]}function u(){a=[]}function c(f){return!f.id||N(f.target)?(e==null||e.warn(`Ignoring 'none' intent with missing fields: id=${f.id}, target=${f.target}`),S):{type:"payload",payload:{id:f.id,version:f.target,type:"none",updates:[]}}}function h(f){var x;if(!((x=f.payloads)!=null&&x.length))return{type:"error",kind:"MISSING_PAYLOAD",message:"No payload present in server-intent"};let C=f.payloads[0];switch(C==null?void 0:C.intentCode){case"xfer-full":return i="full",a=[],r="full",n=C.id,S;case"xfer-changes":return i="changes",a=[],r="partial",n=C.id,S;case"none":return i="changes",a=[],r="partial",n=C.id,c(C);default:return e==null||e.warn(`Unable to process intent code '${C==null?void 0:C.intentCode}'.`),S}}function g(f){if(i==="inactive"||!n)return e==null||e.warn("Received put-object before server-intent was established. Ignoring."),S;if(!f.kind||!f.key||N(f.version)||!f.object)return e==null||e.warn(`Ignoring put-object with missing fields: kind=${f.kind}, key=${f.key}, version=${f.version}`),S;let x=o(f.kind,f.object);return x?(a.push({kind:f.kind,key:f.key,version:f.version,object:x}),S):(e==null||e.warn(`Unable to process object for kind: '${f.kind}'`),S)}function p(f){return i==="inactive"||!n?(e==null||e.warn("Received delete-object before server-intent was established. Ignoring."),S):!f.kind||!f.key||N(f.version)?(e==null||e.warn(`Ignoring delete-object with missing fields: kind=${f.kind}, key=${f.key}, version=${f.version}`),S):(a.push({kind:f.kind,key:f.key,version:f.version,deleted:!0}),S)}function m(f){if(i==="inactive")return{type:"error",kind:"PROTOCOL_ERROR",message:"A payload transferred has been received without an intent having been established."};if(!n||N(f.state)||N(f.version))return e==null||e.warn(`Ignoring payload-transferred with missing fields: state=${f.state}, version=${f.version}`),s(),S;let x={type:"payload",payload:{id:n,version:f.version,state:f.state,type:r,updates:a}};return l(),x}function w(f){return e==null||e.info(`Goodbye was received from the LaunchDarkly connection with reason: ${f.reason}.`),s(),{type:"goodbye",reason:f.reason}}function D(f){return e==null||e.info(`An issue was encountered receiving updates for payload ${n} with reason: ${f.reason}.`),u(),{type:"serverError",id:f.payload_id,reason:f.reason}}return{get state(){return i},processEvent(f){switch(f.event){case"server-intent":return h(f.data);case"put-object":return g(f.data);case"delete-object":return p(f.data);case"payload-transferred":return m(f.data);case"goodbye":return w(f.data);case"error":return D(f.data);case"heart-beat":return S;default:return{type:"error",kind:"UNKNOWN_EVENT",message:`Received an unknown event of type '${f.event}'`}}},reset(){s()}}}function jn(t){return t==="MISSING_PAYLOAD"||t==="PROTOCOL_ERROR"}var Ve=class{constructor(t,e,i){this.m=e,this.t=i,this.n=[],this.mn=Ae(t,i)}addPayloadListener(t){this.n.push(t)}removePayloadListener(t){let e=this.n.indexOf(t,0);e>-1&&this.n.splice(e,1)}processEvents(t){t.forEach(e=>{var i,n;let r=this.mn.processEvent(e);switch(r.type){case"payload":this.n.forEach(a=>a(r.payload));break;case"error":jn(r.kind)?(i=this.m)==null||i.call(this,E.InvalidData,r.message):(n=this.t)==null||n.warn(r.message);break}})}},An=class{constructor(t,e,i,n){this.m=i,this.t=n,this.V(t,"server-intent"),this.V(t,"put-object"),this.V(t,"delete-object"),this.V(t,"payload-transferred"),this.V(t,"goodbye"),this.V(t,"error"),this.Ct=new Ve(e,i,n)}addPayloadListener(t){this.Ct.addPayloadListener(t)}removePayloadListener(t){this.Ct.removePayloadListener(t)}V(t,e){t.addEventListener(e,async i=>{var n,r,a,o,s;if(i!=null&&i.data){(n=this.t)==null||n.debug(`Received ${e} event. Data is ${i.data}`);try{this.Ct.processEvents([{event:e,data:JSON.parse(i.data)}])}catch(l){(r=this.t)==null||r.error(`Stream received data that was unable to be processed in "${e}" message`),(a=this.t)==null||a.debug(`Data follows: ${i.data}`),(o=this.m)==null||o.call(this,E.InvalidData,"Malformed data in EventStream.")}}else(s=this.m)==null||s.call(this,E.Unknown,"Event from EventStream missing data.")})}};function Vn(t){if(t){let e=Object.keys(t).find(i=>i.toLowerCase()==="x-ld-envid");if(e)return{environmentId:t[e]}}}var Zt="unknown plugin";function ot(t,e){try{return e.getMetadata().name||Zt}catch(i){return t.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),Zt}}function Mn(t,e,i){let n=[];return i.forEach(r=>{var a;try{let o=(a=r.getHooks)==null?void 0:a.call(r,e);o===void 0?t.error(`Plugin ${ot(t,r)} returned undefined from getHooks.`):o&&o.length>0&&n.push(...o)}catch(o){t.error(`Exception thrown getting hooks for plugin ${ot(t,r)}. Unable to get hooks.`)}}),n}function Fn(t,e,i,n){n.forEach(r=>{try{r.register(i,e)}catch(a){t.error(`Exception thrown registering plugin ${ot(t,r)}.`)}})}var L=Object.freeze({__proto__:null,ClientMessages:Te,DiagnosticsManager:kn,ErrorKinds:Dn,EventFactoryBase:Pn,EventProcessor:$n,FDv1PayloadAdaptor:Nn,InputCustomEvent:Ne,InputEvalEvent:St,InputIdentifyEvent:je,NullEventProcessor:Tn,PayloadProcessor:Ve,PayloadStreamReader:An,canonicalize:it,createProtocolHandler:Ae,initMetadataFromHeaders:Vn,isLegacyUser:ke,isMultiKind:be,isSingleKind:we,safeGetHooks:Mn,safeGetName:ot,safeRegisterPlugins:Fn,shouldSample:tt}),Yt={Initializing:"INITIALIZING",Valid:"VALID",Interrupted:"INTERRUPTED",SetOffline:"SET_OFFLINE",Closed:"CLOSED"};function Un(t){return t>=200&&t<=299}var Qt=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}};function Xt(t,e,i,n,r,a,o,s,l,u){let c,h="GET",g=v({},a);l&&(h="REPORT",g["content-type"]="application/json",c=t);let p=l?i.pathReport(r,t):i.pathGet(r,t),m=[...o!=null?o:[]];s&&m.push({key:"withReasons",value:"true"}),u&&m.push({key:"h",value:u});let w=pn(e,p,m);return{async requestPayload(){let D;try{let f=await n.fetch(w,{method:h,headers:g,body:c});if(Un(f.status))return await f.text();D=f.status}catch(f){throw new Qt(f==null?void 0:f.message)}throw new Qt(`Unexpected status code: ${D}`,D)}}}var te=new Error("Task has already been executed or shed. This is likely an implementation error. The task will not be executed again.");function zn(t,e,i=!1){let n,r=new Promise(s=>{n=(l,u)=>{var c;try{(c=t.after)==null||c.call(t,l,u)}catch(h){e==null||e.error(`Error in after callback: ${h}`)}s(l)}}),a=t.before?t.before():Promise.resolve(void 0),o=!1;return{execute:()=>{o&&(e==null||e.error(te)),o=!0,a.then(s=>{t.execute(s).then(l=>n({status:"complete",result:l},s)).catch(l=>n({status:"error",error:l},s))}).catch(s=>{e==null||e.error(s),n({status:"error",error:s},void 0)})},shed:()=>{o&&(e==null||e.error(te)),o=!0,a.then(s=>{n({status:"shed"},s)})},promise:r,sheddable:i}}function Kn(t){let e,i=[];function n(){if(!e&&i.length>0){let r=i.shift();e=r.promise.finally(()=>{e=void 0,n()}),r.execute()}}return{execute(r,a=!1){var o,s;let l=zn(r,t,a);return e?((o=i[i.length-1])!=null&&o.sheddable&&((s=i.pop())==null||s.shed()),i.push(l)):(e=l.promise.finally(()=>{e=void 0,n()}),l.execute()),l.promise},pendingCount(){return i.length}}}function Me(t){return"validate"in t}function ut(t,e,i,n,r){let a=v({},i);return N(t)?a:d.Object.is(t)?(Object.entries(t).forEach(([o,s])=>{let l=e[o],u=r?`${r}.${o}`:o;if(!l){n==null||n.warn(k.unknownOption(u));return}if(N(s))return;if(Me(l)){let h=l.validate(s,u,n,i[o]);h!==void 0&&(a[o]=h.value);return}if(l.is(s)){a[o]=s;return}let c=l.getType();c==="boolean"?(n==null||n.warn(k.wrongOptionTypeBoolean(u,typeof s)),a[o]=!!s):c==="boolean | undefined | null"?(n==null||n.warn(k.wrongOptionTypeBoolean(u,typeof s)),typeof s!="boolean"&&typeof s!="undefined"&&s!==null&&(a[o]=!!s)):l instanceof me&&d.Number.is(s)?(n==null||n.warn(k.optionBelowMinimum(u,s,l.min)),a[o]=l.min):n==null||n.warn(k.wrongOptionType(u,c,typeof s))}),a):(n==null||n.warn(k.wrongOptionType(r!=null?r:"config","object",typeof t)),a)}function W(t,e){return{is:i=>d.Object.is(i),getType:()=>"object",validate(i,n,r,a){if(!d.Object.is(i)){r==null||r.warn(k.wrongOptionType(n,"object",typeof i));return}let o=e!=null?e:d.Object.is(a)?a:{},s=ut(i,t,o,r,n);return Object.keys(s).length>0?{value:s}:void 0}}}function Fe(t,e){return{is:i=>Array.isArray(i),getType:()=>"array",validate(i,n,r){if(!Array.isArray(i)){r==null||r.warn(k.wrongOptionType(n,"array",typeof i));return}let a=[];return i.forEach((o,s)=>{let l=`${n}[${s}]`;if(N(o)||!d.Object.is(o)){r==null||r.warn(k.wrongOptionType(l,"object",typeof o));return}let u=o,c=u[t],h=typeof c=="string"?e[c]:void 0;if(!h){let g=Object.keys(e).join(" | "),p=typeof c=="string"?c:typeof c;r==null||r.warn(k.wrongOptionType(`${l}.${t}`,g,p));return}a.push(ut(u,h,{},r,l))}),{value:a}}}}function Jn(...t){return{is:e=>t.some(i=>i.is(e)),getType:()=>t.map(e=>e.getType()).join(" | "),validate(e,i,n,r){let a=t.find(o=>o.is(e));if(a)return Me(a)?a.validate(e,i,n,r):{value:e};n==null||n.warn(k.wrongOptionType(i,this.getType(),typeof e))}}}function Bn(t,e){return{is:i=>d.Object.is(i),getType:()=>"object",validate(i,n,r,a){if(N(i))return;if(!d.Object.is(i)){r==null||r.warn(k.wrongOptionType(n,"object",typeof i));return}let o=i,s={},l={};Object.keys(o).forEach(c=>{t.is(c)?(s[c]=o[c],l[c]=e):r==null||r.warn(k.wrongOptionType(n,t.getType(),c))});let u=d.Object.is(a)?a:{};return{value:ut(s,l,u,r,n)}}}}var $t=d.oneOf("cache","polling","streaming"),Rt=d.oneOf("streaming","polling","offline","one-shot","background"),Ue={pollingBaseUri:d.String,streamingBaseUri:d.String},Hn={type:$t},ze={type:$t,pollInterval:d.numberWithMin(30),endpoints:W(Ue)},Ke={type:$t,initialReconnectDelay:d.numberWithMin(1),endpoints:W(Ue)},qn=Fe("type",{cache:Hn,polling:ze,streaming:Ke}),_n=Fe("type",{polling:ze,streaming:Ke}),Wn={initializers:qn,synchronizers:_n},Gn=Bn(Rt,W(Wn)),Zn={lifecycle:d.Boolean,network:d.Boolean},Yn={initialConnectionMode:Rt,backgroundConnectionMode:Rt,automaticModeSwitching:Jn(d.Boolean,W(Zn)),connectionModes:Gn},Qn={initialConnectionMode:"one-shot",backgroundConnectionMode:void 0,automaticModeSwitching:!1};function Xn(t){return{logger:d.Object,maxCachedContexts:d.numberWithMin(0),baseUri:d.String,streamUri:d.String,eventsUri:d.String,capacity:d.numberWithMin(1),diagnosticRecordingInterval:d.numberWithMin(2),flushInterval:d.numberWithMin(2),streamInitialReconnectDelay:d.numberWithMin(0),allAttributesPrivate:d.Boolean,debug:d.Boolean,diagnosticOptOut:d.Boolean,withReasons:d.Boolean,sendEvents:d.Boolean,pollInterval:d.numberWithMin(30),useReport:d.Boolean,privateAttributes:d.StringArray,disableCache:d.Boolean,applicationInfo:d.Object,wrapperName:d.String,wrapperVersion:d.String,payloadFilterKey:d.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:d.createTypeArray("Hook[]",{}),inspectors:d.createTypeArray("LDInspection",{}),cleanOldPersistentData:d.Boolean,dataSystem:t!=null&&t.dataSystemDefaults?W(Yn,t.dataSystemDefaults):d.Object}}var tr=300,Je="https://clientsdk.launchdarkly.com",Be="https://clientstream.launchdarkly.com";function er(t){return t instanceof xe?t:Ce(t)}var ir=class{constructor(t={},e={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var i,n,r;this.logger=Ce(),this.baseUri=Je,this.eventsUri=at.DEFAULT_EVENTS,this.streamUri=Be,this.maxCachedContexts=5,this.disableCache=!1,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=tr,this.hooks=[],this.inspectors=[],this.logger=er(t.logger);let a=Xn({dataSystemDefaults:e.dataSystemDefaults}),o=ut(t,a,{},this.logger);Object.entries(o).forEach(([s,l])=>{s!=="logger"&&(this[s]=l)}),this.serviceEndpoints=new at(this.streamUri,this.baseUri,this.eventsUri,e.analyticsEventPath,e.diagnosticEventPath,e.includeAuthorizationHeader,t.payloadFilterKey),this.useReport=(i=t.useReport)!=null?i:!1,this.tags=new dn({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(n=e.userAgentHeaderName)!=null?n:"user-agent",this.trackEventModifier=(r=e.trackEventModifier)!=null?r:(s=>s),this.credentialType=e.credentialType,this.getImplementationHooks=e.getImplementationHooks}};async function Tt(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 He=async(t,{crypto:e,storage:i})=>{let n=await(i==null?void 0:i.get(t));return n||(n=e.randomUUID(),await(i==null?void 0:i.set(t,n))),n};function qe(t){return async e=>Tt(t.createHash("sha256").update(e),"base64")}var $=async t=>t;async function G(t){return(await Promise.all(t.map(e=>e.transform(e.value)))).join("_")}async function nr(t,e){return G([{value:"LaunchDarkly",transform:$},{value:e,transform:qe(t)}])}async function rr(t){return G([{value:"LaunchDarkly",transform:$},{value:"AnonymousKeys",transform:$},{value:t,transform:$}])}async function ar(t){return G([{value:"LaunchDarkly",transform:$},{value:"ContextKeys",transform:$},{value:t,transform:$}])}async function sr(t){return G([{value:t,transform:$},{value:"ContextIndex",transform:$}])}async function _e(t,e,i){return G([{value:e,transform:$},{value:i.canonicalKey,transform:qe(t)}])}var{isLegacyUser:or,isSingleKind:mt,isMultiKind:ee}=L,We="1.0",lr=t=>{let e=t,{kind:i}=e,n=ge(e,["kind"]);return{kind:"multi",[i]:n}},ur=async({crypto:t,info:e},{applicationInfo:i})=>{var n;let{ld_application:r}=e.platformData(),a=(n=Lt(r))!=null?n:{},o=(i==null?void 0:i.id)||(a==null?void 0:a.id);if(o){let s=(i==null?void 0:i.version)||(a==null?void 0:a.version),l=(i==null?void 0:i.name)||(a==null?void 0:a.name),u=(i==null?void 0:i.versionName)||(a==null?void 0:a.versionName);return a=v(v(v(T(v({},a),{id:o}),s?{version:s}:{}),l?{name:l}:{}),u?{versionName:u}:{}),a.key=await Tt(t.createHash("sha256").update(o),"base64"),a.envAttributesVersion=a.envAttributesVersion||We,a}},cr=async t=>{var e,i,n,r;let{ld_device:a,os:o}=t.info.platformData(),s=(e=Lt(a))!=null?e:{},l=(o==null?void 0:o.name)||((i=s.os)==null?void 0:i.name),u=(o==null?void 0:o.version)||((n=s.os)==null?void 0:n.version),c=(r=s.os)==null?void 0:r.family;if((l||u||c)&&(s.os=v(v(v({},l?{name:l}:{}),u?{version:u}:{}),c?{family:c}:{})),Object.keys(s).filter(h=>h!=="key"&&h!=="envAttributesVersion").length){let h=await ar("ld_device");return s.key=await He(h,t),s.envAttributesVersion=s.envAttributesVersion||We,s}},hr=async(t,e,i)=>{if(or(t))return t;let n,r;if(mt(t)&&t.kind!=="ld_application"||ee(t)&&!t.ld_application?n=await ur(e,i):i.logger.warn("Not adding ld_application environment attributes because it already exists."),mt(t)&&t.kind!=="ld_device"||ee(t)&&!t.ld_device?r=await cr(e):i.logger.warn("Not adding ld_device environment attributes because it already exists."),n||r){let a=mt(t)?lr(t):t;return v(v(v({},a),n?{ld_application:n}:{}),r?{ld_device:r}:{})}return t};function dr(){let t,e;return{set(i,n){t=i,e=n},getContext(){return e},getUnwrappedContext(){return t},newIdentificationPromise(){let i,n;return{identifyPromise:new Promise((r,a)=>{i=r,n=a}),identifyResolve:i,identifyReject:n}},hasContext(){return e!==void 0},hasValidContext(){return this.hasContext()&&e.valid}}}var{isLegacyUser:fr,isMultiKind:gr,isSingleKind:pr}=L,Pt=async(t,e,i)=>{let{anonymous:n,key:r}=e;if(n&&!r){let a=await rr(t);e.key=await He(a,i)}},vr=async(t,e)=>{await Pt(t.kind,t,e)},mr=async(t,e)=>{let i=t,{kind:n}=i,r=ge(i,["kind"]);return Promise.all(Object.entries(r).map(([a,o])=>Pt(a,o,e)))},yr=async(t,e)=>{await Pt("user",t,e)},wr=async(t,e)=>{let i=Ie(t);return pr(i)&&await vr(i,e),gr(i)&&await mr(i,e),fr(i)&&await yr(i,e),i},br=t=>({customBaseURI:t.serviceEndpoints.polling!==Je,customStreamURI:t.serviceEndpoints.streaming!==Be,customEventsURI:t.serviceEndpoints.events!==at.DEFAULT_EVENTS,eventsCapacity:t.capacity,eventsFlushIntervalMillis:vt(t.flushInterval),reconnectTimeMillis:vt(t.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:vt(t.diagnosticRecordingInterval),allAttributesPrivate:t.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),kr=(t,e,i)=>{if(e.sendEvents&&!e.diagnosticOptOut)return new L.DiagnosticsManager(t,i,br(e))};function ie(t,e){return{value:e!=null?e:null,variationIndex:null,reason:{kind:"ERROR",errorKind:t}}}function ne(t,e,i){return v({value:t,variationIndex:e!=null?e:null},i!==void 0&&{reason:i})}var Dr=(t,e,i,n,r)=>{if(e.sendEvents)return new L.EventProcessor(T(v({},e),{eventsCapacity:e.capacity}),new fn(t,e,i),n,void 0,r,!1,!0)},re=class extends L.EventFactoryBase{evalEventClient(t,e,i,n,r,a){let{trackEvents:o,debugEventsUntilDate:s,trackReason:l,flagVersion:u,version:c,variation:h}=n;return super.evalEvent({addExperimentData:l,context:r,debugEventsUntilDate:s,defaultVal:i,flagKey:t,reason:a,trackEvents:!!o,value:e,variation:h,version:u!=null?u:c})}},ae="_freshness";async function Er(t,e){let i=e.canonicalUnfilteredJson();if(i)return Tt(t.createHash("sha256").update(i),"base64")}function xr(t){return t!==null&&typeof t=="object"&&typeof t.version=="number"}async function Cr(t,e,i,n,r){let a=await _e(e,i,n),o=await t.get(a),s=!1;if(o==null){if(o=await t.get(n.canonicalKey),o==null)return;s=!0}try{let l=JSON.parse(o);if(l===null||typeof l!="object"){r==null||r.warn("Cached flag data is not a valid object");return}let u=Object.entries(l),c=u.find(([,h])=>!xr(h));if(c){r==null||r.warn(`Discarding cached flags due to invalid entry: ${c[0]}`);return}return{flags:u.reduce((h,[g,p])=>(h[g]=p,h),{}),storageKey:a,fromLegacyKey:s}}catch(l){r==null||r.warn(`Could not parse cached flag evaluations from persistent storage: ${l.message}`);return}}var yt=class Ge{constructor(){this.container={index:new Array}}static fromJson(e){let i=new Ge;try{i.container=JSON.parse(e)}catch(n){}return i}toJson(){return JSON.stringify(this.container)}notice(e,i){let n=this.container.index.find(r=>r.id===e);n===void 0?this.container.index.push({id:e,timestamp:i}):n.timestamp=i}prune(e){let i=Math.max(e,0);return this.container.index.length>i?(this.container.index.sort((n,r)=>n.timestamp-r.timestamp),this.container.index.splice(0,this.container.index.length-i)):[]}},Sr=class{constructor(t,e,i,n,r,a,o,s=()=>Date.now()){this.a=t,this.It=e,this.ct=i,this.ye=n,this.A=r,this.y=a,this.t=o,this.gn=s,this.ve=sr(this.It)}async init(t,e){this.y.init(t,e),await this.At(t)}async upsert(t,e,i){return this.y.upsert(t,e,i)?(await this.At(t),!0):!1}async applyChanges(t,e,i){this.y.applyChanges(t,e,i),await this.At(t)}async loadCached(t){if(this.ye||this.ct<=0||!this.a.storage)return!1;let e=await Cr(this.a.storage,this.a.crypto,this.It,t,this.t);if(!e)return!1;e.fromLegacyKey&&(await this.a.storage.set(e.storageKey,JSON.stringify(e.flags)),await this.a.storage.clear(t.canonicalKey));let i=Object.entries(e.flags).reduce((n,[r,a])=>(n[r]={version:a.version,flag:a},n),{});return this.y.initCached(t,i),this.t.debug("Loaded cached flag evaluations from persistent storage"),!0}async yn(t,e,i){var n;let r=await Er(this.a.crypto,e);if(r===void 0){this.t.error("Could not serialize context for freshness tracking");return}let a={timestamp:i,contextHash:r};await((n=this.a.storage)==null?void 0:n.set(`${t}${ae}`,JSON.stringify(a)))}async vn(){var t;if(this.H!==void 0)return this.H;let e=await((t=this.a.storage)==null?void 0:t.get(await this.ve));if(!e)return this.H=new yt,this.H;try{this.H=yt.fromJson(e),this.t.debug("Loaded context index from persistent storage")}catch(i){this.t.warn(`Could not load index from persistent storage: ${i.message}`),this.H=new yt}return this.H}async At(t){var e,i;if(this.ye)return;let n=this.gn(),r=await this.vn(),a=await _e(this.a.crypto,this.It,t);this.ct>0&&r.notice(a,n);let o=r.prune(this.ct),s=this.ct<=0||o.some(h=>h.id===a);if(await Promise.all(o.flatMap(h=>{var g,p;return[(g=this.a.storage)==null?void 0:g.clear(h.id),(p=this.a.storage)==null?void 0:p.clear(`${h.id}${ae}`)]})),await((e=this.a.storage)==null?void 0:e.set(await this.ve,r.toJson())),s)return;let l=this.A.getAll(),u=Object.entries(l).reduce((h,[g,p])=>(p.flag!==null&&p.flag!==void 0&&(h[g]=p.flag),h),{}),c=JSON.stringify(u);await((i=this.a.storage)==null?void 0:i.set(a,c));try{await this.yn(a,t,n)}catch(h){this.t.warn(`Failed to store freshness data: ${h.message}`)}}};function Rr(){let t={};return{init(e){t=Object.entries(e).reduce((i,[n,r])=>(i[n]=r,i),{})},insertOrUpdate(e,i){t[e]=i},get(e){if(Object.prototype.hasOwnProperty.call(t,e))return t[e]},getAll(){return t},applyChanges(e,i){i==="full"?this.init(e):i==="partial"&&Object.entries(e).forEach(([n,r])=>{t[n]=r})}}}function se(t,e){let i=[];return Object.entries(t).forEach(([n,r])=>{let a=e[n];(!a||!X(r,a))&&i.push(n)}),Object.keys(e).forEach(n=>{t[n]||i.push(n)}),i}function Or(t,e){let i=t,n=e,r,a=new Array;return{handleFlagChanges(o,s){r?a.forEach(l=>{try{l(r,o,s)}catch(u){}}):n.warn("Received a change event without an active context. Changes will not be propagated.")},init(o,s){r=o;let l=i.getAll();i.init(s);let u=se(l,s);u.length>0&&this.handleFlagChanges(u,"init")},initCached(o,s){(r==null?void 0:r.canonicalKey)!==o.canonicalKey&&this.init(o,s)},applyChanges(o,s,l){r=o;let u=i.getAll();if(i.applyChanges(s,l),l==="full"){let c=se(u,s);c.length>0&&this.handleFlagChanges(c,"init")}else if(l==="partial"){let c=Object.keys(s);c.length>0&&this.handleFlagChanges(c,"patch")}},upsert(o,s,l){if((r==null?void 0:r.canonicalKey)!==o.canonicalKey)return n.warn("Received an update for an inactive context."),!1;let u=i.get(s);return u!==void 0&&u.version>=l.version?!1:(i.insertOrUpdate(s,l),this.handleFlagChanges([s],"patch"),!0)},on(o){a.push(o)},off(o){let s=a.indexOf(o);s>-1&&a.splice(s,1)}}}var Ir=class{constructor(t,e,i,n,r,a=()=>Date.now()){this.A=Rr(),this.y=Or(this.A,r),this.ut=this.wn(t,e,i,n,r,a)}async wn(t,e,i,n,r,a=()=>Date.now()){let o=await nr(t.crypto,e);return new Sr(t,o,i,n,this.A,this.y,r,a)}get(t){return this.r&&Object.prototype.hasOwnProperty.call(this.r,t)?this.Tt(this.r[t]):this.A.get(t)}getAll(){return this.r?v(v({},this.A.getAll()),Object.entries(this.r).reduce((t,[e,i])=>(t[e]=this.Tt(i),t),{})):this.A.getAll()}presetFlags(t){this.A.init(t)}setBootstrap(t,e){this.y.init(t,e)}async init(t,e){return(await this.ut).init(t,e)}async upsert(t,e,i){return(await this.ut).upsert(t,e,i)}async loadCached(t){return(await this.ut).loadCached(t)}async applyChanges(t,e,i){return(await this.ut).applyChanges(t,e,i)}on(t){this.y.on(t)}off(t){this.y.off(t)}Tt(t){return{flag:{value:t,version:0},version:0}}setOverride(t,e){this.r||(this.r={}),this.r[t]=e,this.y.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.y.handleFlagChanges([t],"override"))}clearAllOverrides(){if(this.r){let t=v({},this.r);this.r=void 0,this.y.handleFlagChanges(Object.keys(t),"override")}}getAllOverrides(){if(!this.r)return{};let t={};return Object.entries(this.r).forEach(([e,i])=>{t[e]=this.Tt(i)}),t}getDebugOverride(){return{setOverride:this.setOverride.bind(this),removeOverride:this.removeOverride.bind(this),clearAllOverrides:this.clearAllOverrides.bind(this),getAllOverrides:this.getAllOverrides.bind(this)}}},oe="unknown hook",Ze="beforeEvaluation",Ye="afterEvaluation",Lr="afterTrack";function Z(t,e,i,n,r){try{return n()}catch(a){return t==null||t.error(`An error was encountered in "${e}" of the "${i}" hook: ${a}`),r}}function Y(t,e){try{return e.getMetadata().name||oe}catch(i){return t.error("Exception thrown getting metadata for hook. Unable to get hook name."),oe}}function $r(t,e,i){return e.map(n=>Z(t,Ze,Y(t,n),()=>{var r,a;return(a=(r=n==null?void 0:n.beforeEvaluation)==null?void 0:r.call(n,i,{}))!=null?a:{}},{}))}function Tr(t,e,i,n,r){for(let a=e.length-1;a>=0;a-=1){let o=e[a],s=n[a];Z(t,Ye,Y(t,o),()=>{var l,u;return(u=(l=o==null?void 0:o.afterEvaluation)==null?void 0:l.call(o,i,s,r))!=null?u:{}},{})}}function Pr(t,e,i){return e.map(n=>Z(t,Ze,Y(t,n),()=>{var r,a;return(a=(r=n==null?void 0:n.beforeIdentify)==null?void 0:r.call(n,i,{}))!=null?a:{}},{}))}function Nr(t,e,i,n,r){for(let a=e.length-1;a>=0;a-=1){let o=e[a],s=n[a];Z(t,Ye,Y(t,o),()=>{var l,u;return(u=(l=o==null?void 0:o.afterIdentify)==null?void 0:l.call(o,i,s,r))!=null?u:{}},{})}}function jr(t,e,i){for(let n=e.length-1;n>=0;n-=1){let r=e[n];Z(t,Lr,Y(t,r),()=>{var a;return(a=r==null?void 0:r.afterTrack)==null?void 0:a.call(r,i)},void 0)}}var Ar=class{constructor(t,e){this.t=t,this.R=[],this.R.push(...e)}withEvaluation(t,e,i,n){if(this.R.length===0)return n();let r=[...this.R],a={flagKey:t,context:e,defaultValue:i},o=$r(this.t,r,a),s=n();return Tr(this.t,r,a,o,s),s}identify(t,e){let i=[...this.R],n={context:t,timeout:e},r=Pr(this.t,i,n);return a=>{Nr(this.t,i,n,r,a)}}addHook(t){this.R.push(t)}afterTrack(t){if(this.R.length===0)return;let e=[...this.R];jr(this.t,e,t)}};function Vr(t){return{getMetadata(){return{name:"LaunchDarkly-Inspector-Adapter"}},afterEvaluation:(e,i,n)=>(t.onFlagUsed(e.flagKey,n,e.context),i),afterIdentify(e,i,n){return t.onIdentityChanged(e.context),i}}}function Mr(t,e){return`an inspector: "${e}" of an invalid type (${t}) was configured`}function Fr(t,e){return`an inspector: "${e}" of type: "${t}" generated an exception`}function Ur(t,e){let i=!1,n={method:(...r)=>{try{t.method(...r)}catch(a){i||(i=!0,e.warn(Fr(n.type,n.name)))}},type:t.type,name:t.name,synchronous:t.synchronous};return n}var Qe="flag-used",Xe="flag-details-changed",ti="flag-detail-changed",ei="client-identity-changed",zr=[Qe,Xe,ti,ei];function Kr(t,e){let i=zr.includes(t.type)&&t.method&&typeof t.method=="function";return i||e.warn(Mr(t.type,t.name)),i}var Jr=class{constructor(t,e){this.z=[];let i=t.filter(n=>Kr(n,e));this.z=i.map(n=>Ur(n,e))}hasInspectors(){return this.z.length!==0}onFlagUsed(t,e,i){this.z.forEach(n=>{n.type===Qe&&n.method(t,e,i)})}onFlagsChanged(t){this.z.forEach(e=>{e.type===Xe&&e.method(t)})}onFlagChanged(t,e){this.z.forEach(i=>{i.type===ti&&i.method(t,e)})}onIdentityChanged(t){this.z.forEach(e=>{e.type===ei&&e.method(t)})}},Br=class{constructor(t){this.t=t,this.n=new Map}on(t,e){var i,n;if(typeof t!="string"){(i=this.t)==null||i.warn("Only string event names are supported.");return}this.n.has(t)?(n=this.n.get(t))==null||n.push(e):this.n.set(t,[e])}off(t,e){let i=this.n.get(t);if(i){if(e){let n=i.filter(r=>r!==e);n.length===0?this.n.delete(t):this.n.set(t,n);return}this.n.delete(t)}}En(t,e,...i){var n;try{t(...i)}catch(r){(n=this.t)==null||n.error(`Encountered error invoking handler for "${e}", detail: "${r}"`)}}emit(t,...e){let i=this.n.get(t);i==null||i.forEach(n=>this.En(n,t,...e))}eventNames(){return[...this.n.keys()]}listenerCount(t){var e,i;return(i=(e=this.n.get(t))==null?void 0:e.length)!=null?i:0}};function Hr(t,e,i){let n=e.info.sdkData(),r;i.applicationInfo&&(i.applicationInfo.id&&(r=r!=null?r:{},r.id=i.applicationInfo.id),i.applicationInfo.version&&(r=r!=null?r:{},r.version=i.applicationInfo.version),i.applicationInfo.name&&(r=r!=null?r:{},r.name=i.applicationInfo.name),i.applicationInfo.versionName&&(r=r!=null?r:{},r.versionName=i.applicationInfo.versionName));let a={name:n.userAgentBase,version:n.version};n.wrapperName&&(a.wrapperName=n.wrapperName),n.wrapperVersion&&(a.wrapperVersion=n.wrapperVersion);let o={sdk:a,[i.credentialType]:t};return r&&(o.application=r),o}var{ClientMessages:le,ErrorKinds:ue}=L,qr=5,_r=class{constructor(t,e,i,n,r,a){var o;if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=i,this.u=dr(),this.$t=15,this.T=new re(!1),this.lt=new re(!0),this.Rt=!1,this.bn=Kn(),!t)throw new Error("You must configure the client with a client-side SDK key");if(!i.encoding)throw new Error("Platform must implement Encoding because btoa is required.");this.e=new ir(n,a),this.logger=this.e.logger,this.we=bn(this.sdkKey,this.platform.info,this.e.tags,this.e.serviceEndpoints.includeAuthorizationHeader,this.e.userAgentHeaderName),this.N=new Ir(this.platform,t,this.e.maxCachedContexts,(o=this.e.disableCache)!=null?o:!1,this.e.logger),this.x=kr(t,this.e,i),this.E=Dr(t,this.e,i,this.we,this.x),this.emitter=new Br,this.emitter.on("error",(l,u)=>{this.logger.error(`error: ${u}, context: ${JSON.stringify(l)}`)}),this.N.on((l,u,c)=>{this.Dn(u,c);let h=U.toLDContext(l);this.emitter.emit("change",h,u),u.forEach(g=>{this.emitter.emit(`change:${g}`,h)})}),this.dataManager=r(this.N,this.e,this.we,this.emitter,this.x);let s=[...this.e.hooks];if(this.environmentMetadata=Hr(this.sdkKey,this.platform,this.e),this.e.getImplementationHooks(this.environmentMetadata).forEach(l=>{s.push(l)}),this.M=new Ar(this.logger,s),this.Y=new Jr(this.e.inspectors,this.logger),this.Y.hasInspectors()&&this.M.addHook(Vr(this.Y)),n.cleanOldPersistentData&&a!=null&&a.getLegacyStorageKeys&&this.platform.storage)try{this.logger.debug("Cleaning old persistent data."),Promise.all(a.getLegacyStorageKeys().map(l=>{var u;return(u=this.platform.storage)==null?void 0:u.clear(l)})).catch(l=>{this.logger.error(`Error cleaning old persistent data: ${l}`)}).finally(()=>{this.logger.debug("Cleaned old persistent data.")})}catch(l){this.logger.error(`Error cleaning old persistent data: ${l}`)}}allFlags(){return Object.entries(this.N.getAll()).reduce((t,[e,i])=>(i.flag!==null&&i.flag!==void 0&&!i.flag.deleted&&(t[e]=i.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.u.hasContext()?Ie(this.u.getUnwrappedContext()):void 0}getInternalContext(){return this.u.getContext()}presetFlags(t){this.N.presetFlags(t)}async identify(t,e){let i=await this.identifyResult(t,e);if(i.status==="error")throw i.error;if(i.status==="timeout"){let n=new Oe(`identify timed out after ${i.timeout} seconds.`);throw this.logger.error(n.message),n}}async identifyResult(t,e){var i,n;let r=(i=e==null?void 0:e.timeout)!=null?i:qr,a=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;r>this.$t&&this.logger.warn(`The identify function was called with a timeout greater than ${this.$t} seconds. We recommend a timeout of less than ${this.$t} seconds.`);let o=this.bn.execute({before:async()=>{let l=await wr(t,this.platform);this.autoEnvAttributes===rt.Enabled&&(l=await hr(l,this.platform,this.e));let u=U.fromLDContext(l);if(u.valid){let c=this.M.identify(l,e==null?void 0:e.timeout);return{context:l,checkedContext:u,afterIdentify:c}}return{context:l,checkedContext:u}},execute:async l=>{var u;let{context:c,checkedContext:h}=l;if(!h.valid){let w=new Error("Context was unspecified or had no key");return this.emitter.emit("error",c,w),Promise.reject(w)}this.u.set(c,h),(u=this.E)==null||u.sendEvent(this.T.identifyEvent(h));let{identifyPromise:g,identifyResolve:p,identifyReject:m}=this.u.newIdentificationPromise();return this.logger.debug(`Identifying ${JSON.stringify(h)}`),await this.dataManager.identify(p,m,h,e),g},after:async(l,u)=>{var c,h,g;l.status==="complete"?(c=u==null?void 0:u.afterIdentify)==null||c.call(u,{status:"completed"}):l.status==="shed"?(h=u==null?void 0:u.afterIdentify)==null||h.call(u,{status:"shed"}):l.status==="error"&&((g=u==null?void 0:u.afterIdentify)==null||g.call(u,{status:"error"}))}},(n=e==null?void 0:e.sheddable)!=null?n:!1).then(l=>{if(l.status==="error"){let c={status:"error",error:l.error};return this.maybeSetInitializationResult({status:"failed",error:l.error}),c}if(l.status==="shed")return{status:"shed"};let u={status:"completed"};return this.maybeSetInitializationResult({status:"complete"}),u});if(a)return o;let s=new Promise(l=>{setTimeout(()=>{l({status:"timeout",timeout:r})},r*1e3)});return Promise.race([o,s])}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 i=(e=t==null?void 0:t.timeout)!=null?e:5;return this.initializeResult?Promise.resolve(this.initializeResult):this.initializedPromise?this.promiseWithTimeout(this.initializedPromise,i):(this.initializedPromise||(this.initializedPromise=new Promise(n=>{this.initResolve=n})),this.promiseWithTimeout(this.initializedPromise,i))}promiseWithTimeout(t,e){let i=yn(e,"waitForInitialization");return Promise.race([t.then(n=>(i.cancel(),n)),i.promise.then(()=>({status:"complete"})).catch(()=>({status:"timeout"}))]).catch(n=>{var r;return(r=this.logger)==null||r.error(n.message),{status:"failed",error:n}})}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}track(t,e,i){var n,r;if(!this.u.hasValidContext()){this.logger.warn(le.MissingContextKeyNoEvent);return}i!==void 0&&!d.Number.is(i)&&((n=this.logger)==null||n.warn(le.invalidMetricValue(typeof i))),(r=this.E)==null||r.sendEvent(this.e.trackEventModifier(this.T.customEvent(t,this.u.getContext(),e,i))),this.M.afterTrack({key:t,context:this.u.getUnwrappedContext(),data:e,metricValue:i})}dt(t,e,i,n){var r,a,o,s,l;let u=this.u.hasContext();u||(r=this.logger)==null||r.warn("Flag evaluation called before client is fully initialized, data from this evaulation could be stale.");let c=this.u.getContext(),h=this.N.get(t);if(h===void 0||h.flag.deleted){let f=e!=null?e:null;return(a=this.logger)==null||a.warn(`Unknown feature flag "${t}"; returning default value ${f}.`),u&&((o=this.E)==null||o.sendEvent(this.T.unknownFlagEvent(t,f,c))),ie(ue.FlagNotFound,e)}let{reason:g,value:p,variation:m,prerequisites:w}=h.flag;if(n){let[f,x]=n(p);if(!f){u&&((s=this.E)==null||s.sendEvent(i.evalEventClient(t,e,e,h.flag,c,g)));let C=new vn(`Wrong type "${x}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.u.getUnwrappedContext(),C),ie(ue.WrongType,e)}}let D=ne(p,m,g);return p==null&&(this.logger.debug("Result value is null. Providing default value."),D.value=e),w==null||w.forEach(f=>{this.dt(f,void 0,this.T)}),u&&((l=this.E)==null||l.sendEvent(i.evalEventClient(t,p,e,h.flag,c,g))),D}variation(t,e){let{value:i}=this.M.withEvaluation(t,this.u.getUnwrappedContext(),e,()=>this.dt(t,e,this.T));return i}variationDetail(t,e){return this.M.withEvaluation(t,this.u.getUnwrappedContext(),e,()=>this.dt(t,e,this.lt))}B(t,e,i,n){return this.M.withEvaluation(t,this.u.getUnwrappedContext(),e,()=>this.dt(t,e,i,n))}boolVariation(t,e){return this.B(t,e,this.T,i=>[d.Boolean.is(i),d.Boolean.getType()]).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.B(t,e,this.T,i=>[d.Number.is(i),d.Number.getType()]).value}stringVariation(t,e){return this.B(t,e,this.T,i=>[d.String.is(i),d.String.getType()]).value}boolVariationDetail(t,e){return this.B(t,e,this.lt,i=>[d.Boolean.is(i),d.Boolean.getType()])}numberVariationDetail(t,e){return this.B(t,e,this.lt,i=>[d.Number.is(i),d.Number.getType()])}stringVariationDetail(t,e){return this.B(t,e,this.lt,i=>[d.String.is(i),d.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.M.addHook(t)}setEventSendingEnabled(t,e){var i,n,r,a;this.Rt!==t&&(this.Rt=t,t?(this.logger.debug("Starting event processor"),(i=this.E)==null||i.start()):e?((n=this.logger)==null||n.debug("Flushing event processor before disabling."),this.flush().then(()=>{var o,s;this.Rt||((o=this.logger)==null||o.debug("Stopping event processor."),(s=this.E)==null||s.close())})):((r=this.logger)==null||r.debug("Stopping event processor."),(a=this.E)==null||a.close()))}sendEvent(t){var e;(e=this.E)==null||e.sendEvent(t)}getDebugOverrides(){var t,e;return(e=(t=this.N).getDebugOverride)==null?void 0:e.call(t)}Dn(t,e){if(!this.Y.hasInspectors())return;let i={};t.forEach(n=>{let r=this.N.get(n);if(r!=null&&r.flag&&!r.flag.deleted){let{reason:a,value:o,variation:s}=r.flag;i[n]=ne(o,s,a)}else i[n]={value:void 0,variationIndex:null}}),e==="init"?this.Y.onFlagsChanged(i):e==="patch"&&Object.entries(i).forEach(([n,r])=>{this.Y.onFlagChanged(n,r)})}};function Wr(t,e,i){i.forEach(n=>{var r;try{(r=n.registerDebug)==null||r.call(n,e)}catch(a){t.error(`Exception thrown registering plugin ${L.safeGetName(t,n)}.`)}})}function ii(t,e){let i=Object.keys(e),n="$flagsState",r="$valid",a=e[n];!a&&i.length&&t.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),e[r]===!1&&t.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");let o={};return i.forEach(s=>{if(s!==n&&s!==r){let l;a&&a[s]?l=v({value:e[s]},a[s]):l={value:e[s],version:0},o[s]={version:l.version,flag:l}}}),o}function Gr(t){return{polling:()=>({pathGet(e,i){return`/sdk/evalx/${t}/contexts/${Wt(i,e)}`},pathReport(e,i){return`/sdk/evalx/${t}/context`},pathPost(e,i){throw new Error("Post for FDv1 unsupported.")},pathPing(e,i){throw new Error("Ping for polling unsupported.")}}),streaming:()=>({pathGet(e,i){return`/eval/${t}/${Wt(i,e)}`},pathReport(e,i){return`/eval/${t}`},pathPost(e,i){throw new Error("Post for FDv1 unsupported.")},pathPing(e,i){return`/ping/${t}`}})}}function Zr(t,e,i){return{async handlePut(n,r){i.debug(`Got PUT: ${Object.keys(r)}`);let a=Object.entries(r).reduce((o,[s,l])=>(o[s]={version:l.version,flag:l},o),{});await t.init(n,a),e.requestStateUpdate("VALID")},async handlePatch(n,r){i.debug(`Got PATCH ${JSON.stringify(r,null,2)}`),t.upsert(n,r.key,{version:r.version,flag:r})},async handleDelete(n,r){i.debug(`Got DELETE ${JSON.stringify(r,null,2)}`),t.upsert(n,r.key,{version:r.version,flag:T(v({},r),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})},handleStreamingError(n){e.reportError(n.kind,n.message,n.code,n.recoverable)},handlePollingError(n){e.reportError(n.kind,n.message,n.status,n.recoverable)}}}function Yr(t,e=()=>Date.now()){let i="CLOSED",n=e(),r;function a(){return{state:i,stateSince:n,lastError:r}}function o(s,l=!1){let u=s==="INTERRUPTED"&&i==="INITIALIZING"?"INITIALIZING":s,c=i!==u;c&&(i=u,n=e()),(c||l)&&t.emit("dataSourceStatus",a())}return{get status(){return a()},requestStateUpdate(s){o(s)},reportError(s,l,u,c=!1){r={kind:s,message:l,statusCode:u,time:e()},o(c?"INTERRUPTED":"CLOSED",!0)}}}function ce(t){t==null||t.debug("Poll completed after the processor was closed. Skipping processing.")}var Qr=class{constructor(t,e,i,n,r){this.kn=t,this.Sn=e,this.xn=i,this.m=n,this.t=r,this.h=!1}async Ee(){var t,e,i,n,r,a,o;if(this.h)return;let s=h=>{var g,p,m;(g=this.t)==null||g.error("Polling received invalid data"),(p=this.t)==null||p.debug(`Invalid JSON follows: ${h}`),(m=this.m)==null||m.call(this,new nt(E.InvalidData,"Malformed JSON data in polling response"))};(t=this.t)==null||t.debug("Polling LaunchDarkly for feature flag updates");let l=Date.now();try{let h=await this.kn.requestPayload();try{if(this.h){ce(this.t);return}let g=JSON.parse(h);try{(e=this.xn)==null||e.call(this,g)}catch(p){(i=this.t)==null||i.error(`Exception from data handler: ${p}`)}}catch(g){s(h)}}catch(h){if(this.h){ce(this.t);return}let g=h;if(g.status!==void 0&&!lt(g.status)){(n=this.t)==null||n.error(J(h,"polling request")),(r=this.m)==null||r.call(this,new nt(E.ErrorResponse,g.message,g.status));return}(a=this.t)==null||a.error(J(h,"polling request","will retry"))}let u=Date.now()-l,c=Math.max(this.Sn*1e3-u,0);(o=this.t)==null||o.debug("Elapsed: %d ms, sleeping for %d ms",u,c),this.Nt=setTimeout(()=>{this.Ee()},c)}start(){this.Ee()}stop(){this.Nt&&(clearTimeout(this.Nt),this.Nt=void 0),this.h=!0}close(){this.stop()}},Xr=(t,e,i,n)=>{i==null||i.error(`Stream received invalid data in "${t}" message`),i==null||i.debug(`Invalid JSON follows: ${e}`),n==null||n(new Et(E.InvalidData,"Malformed JSON data in event stream"))};function ta(t,e){e==null||e.debug(`Received ${t} event after processor was closed. Skipping processing.`)}function he(t){t==null||t.debug("Ping completed after processor was closed. Skipping processing.")}var ea=class{constructor(t,e,i,n,r,a,o,s,l){var u;this.Ln=t,this.Mt=e,this.n=i,this._=n,this.On=a,this.x=o,this.m=s,this.t=l,this.h=!1;let c;e.useReport&&!n.getEventSourceCapabilities().customMethod?c=e.paths.pathPing(r,t):c=e.useReport?e.paths.pathReport(r,t):e.paths.pathGet(r,t);let h=[...(u=e.queryParameters)!=null?u:[]];this.Mt.withReasons&&h.push({key:"withReasons",value:"true"}),this._=n,this.be=v({},e.baseHeaders),this.t=l,this.Pn=gn(e.serviceEndpoints,c,h)}De(){this.ht=Date.now()}Ft(t){this.ht&&this.x&&this.x.recordStreamInit(this.ht,!t,Date.now()-this.ht),this.ht=void 0}Cn(t){var e,i,n;return Le(t)?((n=this.t)==null||n.warn(J(t,"streaming request","will retry")),this.Ft(!1),this.De(),!0):(this.Ft(!1),(e=this.m)==null||e.call(this,new Et(E.ErrorResponse,t.message,t.status,!1)),(i=this.t)==null||i.error(J(t,"streaming request")),!1)}start(){this.De();let t;this.Mt.useReport?(this.be["content-type"]="application/json",t={method:"REPORT",body:this.Ln}):t={};let e=this._.createEventSource(this.Pn,T(v({headers:this.be},t),{errorFilter:i=>this.Cn(i),initialRetryDelayMillis:this.Mt.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3}));this.ke=e,e.onclose=()=>{var i;(i=this.t)==null||i.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var i;(i=this.t)==null||i.info("Opened LaunchDarkly stream connection")},e.onretrying=i=>{var n;(n=this.t)==null||n.info(`Will retry stream connection in ${i.delayMillis} milliseconds`)},this.n.forEach(({deserializeData:i,processJson:n},r)=>{e.addEventListener(r,a=>{var o,s;if(this.h){ta(r,this.t);return}if((o=this.t)==null||o.debug(`Received ${r} event`),a!=null&&a.data){this.Ft(!0);let{data:l}=a,u=i(l);if(!u){Xr(r,l,this.t,this.m);return}n(u)}else(s=this.m)==null||s.call(this,new Et(E.InvalidData,"Unexpected payload from event stream"))})}),e.addEventListener("ping",async()=>{var i,n,r,a,o,s,l;(i=this.t)==null||i.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let u=await this.On.requestPayload();try{if(this.h){he(this.t);return}let c=JSON.parse(u);try{(n=this.n.get("put"))==null||n.processJson(c)}catch(h){(r=this.t)==null||r.error(`Exception from data handler: ${h}`)}}catch(c){(a=this.t)==null||a.error("Polling after ping received invalid data"),(o=this.t)==null||o.debug(`Invalid JSON follows: ${u}`),(s=this.m)==null||s.call(this,new nt(E.InvalidData,"Malformed JSON data in ping polling response"))}}catch(u){if(this.h){he(this.t);return}let c=u;(l=this.m)==null||l.call(this,new nt(E.ErrorResponse,c.message,c.status))}})}stop(){var t;(t=this.ke)==null||t.close(),this.ke=void 0,this.h=!0}close(){this.stop()}},ia=class{constructor(t,e,i,n,r,a,o,s,l){this.platform=t,this.flagManager=e,this.credential=i,this.config=n,this.getPollingPaths=r,this.getStreamingPaths=a,this.baseHeaders=o,this.emitter=s,this.diagnosticsManager=l,this.closed=!1,this.logger=n.logger,this.dataSourceStatusManager=Yr(s),this.G=Zr(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.In=t}createPollingProcessor(t,e,i,n,r){let a=new Qr(i,this.config.pollInterval,async o=>{await this.G.handlePut(e,o),n==null||n()},o=>{this.emitter.emit("error",t,o),this.G.handlePollingError(o),r==null||r(o)},this.logger);this.updateProcessor=this.Se(a,this.dataSourceStatusManager)}createStreamingProcessor(t,e,i,n,r){var a;let o=new ea(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:(a=this.In)==null?void 0:a.queryParameters},this.createStreamListeners(e,n),this.platform.requests,this.platform.encoding,i,this.diagnosticsManager,s=>{this.emitter.emit("error",t,s),this.G.handleStreamingError(s),r==null||r(s)},this.logger);this.updateProcessor=this.Se(o,this.dataSourceStatusManager)}createStreamListeners(t,e){let i=new Map;return i.set("put",{deserializeData:JSON.parse,processJson:async n=>{await this.G.handlePut(t,n),e==null||e()}}),i.set("patch",{deserializeData:JSON.parse,processJson:async n=>{this.G.handlePatch(t,n)}}),i.set("delete",{deserializeData:JSON.parse,processJson:async n=>{this.G.handleDelete(t,n)}}),i}Se(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 ct(){return typeof document!==void 0}function Nt(){return typeof window!==void 0}function ni(t,e,i){return ct()?(document.addEventListener(t,e,i),()=>{document.removeEventListener(t,e,i)}):()=>{}}function ri(t,e,i){return ct()?(window.addEventListener(t,e,i),()=>{window.removeEventListener(t,e,i)}):()=>{}}function _(){return Nt()?window.location.href:""}function na(){return Nt()?window.location.search:""}function ra(){return Nt()?window.location.hash:""}function aa(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function sa(){return ct()?document.visibilityState:"visibile"}function oa(t){if(ct())return document.querySelectorAll(t)}var la="[BrowserDataManager]",ua=class extends ia{constructor(t,e,i,n,r,a,o,s,l,u){super(t,e,i,n,a,o,s,l,u),this.Hn=r,this.Z=void 0,this.Ut=!1,this.Z=r.streaming}L(t,...e){this.logger.debug(`${la} ${t}`,...e)}async identify(t,e,i,n){if(this.closed){this.L("Identify called after data manager was closed.");return}this.context=i;let r=n;r!=null&&r.hash?this.setConnectionParams({queryParameters:[{key:"h",value:r.hash}]}):this.setConnectionParams(),this.jt=r==null?void 0:r.hash,r!=null&&r.bootstrap?this.An(i,r,t):(await this.flagManager.loadCached(i)&&this.L("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Tn(i,t,e)),this.xe(),this.l()}async $n(t){let e=JSON.stringify(U.toLDContext(t)),i=Xt(e,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.jt),n=3,r;for(let a=0;a<=n;a+=1)try{return await i.requestPayload()}catch(o){if(!Le(o))throw o;r=o,a<n&&(this.L(J(o,"initial poll request","will retry")),await $e(1e3))}throw r}async Tn(t,e,i){var n,r;try{this.dataSourceStatusManager.requestStateUpdate(Yt.Initializing);let a=await this.$n(t);try{let o=this.createStreamListeners(t,e).get("put");o.processJson(o.deserializeData(a))}catch(o){this.dataSourceStatusManager.reportError(E.InvalidData,(n=o.message)!=null?n:"Could not parse poll response")}}catch(a){this.dataSourceStatusManager.reportError(E.NetworkError,(r=a.message)!=null?r:"unexpected network error",a.status),i(a)}}An(t,e,i){let{bootstrapParsed:n}=e;n||(n=ii(this.logger,e.bootstrap)),this.flagManager.setBootstrap(t,n),this.dataSourceStatusManager.requestStateUpdate(Yt.Valid),this.L("Identify - Initialization completed from bootstrap"),i()}setForcedStreaming(t){this.Z=t,this.l()}setAutomaticStreamingState(t){this.Ut=t,this.l()}l(){let t=this.Z||this.Ut&&this.Z===void 0;this.L(`Updating streaming state. forced(${this.Z}) automatic(${this.Ut})`),t?this.Rn():this.xe()}xe(){var t;this.updateProcessor&&this.L("Stopping update processor."),(t=this.updateProcessor)==null||t.close(),this.updateProcessor=void 0}Rn(){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.Nn(this.context)}Nn(t,e,i){var n;let r=U.toLDContext(t);(n=this.updateProcessor)==null||n.close();let a=JSON.stringify(U.toLDContext(t)),o=Xt(a,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.jt);this.createStreamingProcessor(r,t,o,e,i),this.updateProcessor.start()}};function ca(t){let e=ni("visibilitychange",()=>{sa()==="hidden"&&t()}),i=ri("pagehide",t);return()=>{e(),i()}}function wt(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function ha(t,e,i,n){let r=((t.kind==="substring"||t.kind==="regex")&&n.includes("/")?e:e.replace(n,"")).replace(i,"");switch(t.kind){case"exact":return new RegExp(`^${wt(t.url)}/?$`).test(e);case"canonical":return new RegExp(`^${wt(t.url)}/?$`).test(r);case"substring":return new RegExp(`.*${wt(t.substring)}.*$`).test(r);case"regex":return new RegExp(t.pattern).test(r);default:return!1}}function da(t,e){let i=[];return e.forEach(n=>{let r=t.target,{selector:a}=n,o=oa(a);for(;r&&o!=null&&o.length;){for(let s=0;s<o.length;s+=1)if(r===o[s]){i.push(n);break}r=r.parentNode}}),i}var fa=class{constructor(t,e){let i=t.filter(a=>{var o;return(o=a.urls)==null?void 0:o.some(s=>ha(s,_(),na(),ra()))}),n=i.filter(a=>a.kind==="pageview"),r=i.filter(a=>a.kind==="click");if(n.forEach(a=>e(a)),r.length){let a=o=>{da(o,r).forEach(s=>{e(s)})};this.Le=ni("click",a)}}close(){var t;(t=this.Le)==null||t.call(this)}},ga=300,pa=class{constructor(t){this.Vt=_();let e=()=>{let n=_();n!==this.Vt&&(this.Vt=n,t())};this.Ht=setInterval(e,ga);let i=ri("popstate",e);this.Oe=()=>{i()}}close(){var t;this.Ht&&clearInterval(this.Ht),(t=this.Oe)==null||t.call(this)}},va=class{constructor(t,e,i,n,r,a=o=>new pa(o)){this._=e,this.Un=n,this.Fn=r,this.ft=[],this.Ce=!1,this.pt=`${i}/sdk/goals/${t}`,this.Pe=a(()=>{this.Bt()})}async initialize(){await this.Mn(),this.Bt()}startTracking(){this.Ce=!0,this.Bt()}Bt(){var t;this.Ce&&((t=this.zt)==null||t.close(),this.ft&&this.ft.length&&(this.zt=new fa(this.ft,e=>{this.Fn(_(),e)})))}async Mn(){try{let t=await this._.fetch(this.pt);this.ft=await t.json()}catch(t){this.Un(new Re(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.Pe)==null||t.close(),(e=this.zt)==null||e.close()}};function ma(t){return t.kind==="click"}var ya=2,ai={fetchGoals:!0,eventUrlTransformer:t=>t,streaming:void 0,plugins:[]},wa={fetchGoals:d.Boolean,eventUrlTransformer:d.Function,streaming:d.Boolean,plugins:d.createTypeArray("LDPlugin",{})};function ba(t){var e;let i=v({},t);return(e=i.flushInterval)!=null||(i.flushInterval=ya),i}function ka(t){let e=ba(t);return Object.keys(ai).forEach(i=>{delete e[i]}),e}function Da(t,e){let i=v({},ai);return Object.entries(wa).forEach(n=>{let[r,a]=n,o=t[r];o!==void 0&&(a.is(o)?i[r]=o:e.warn(k.wrongOptionType(r,a.getType(),typeof o)))}),i}var Ea=class{constructor(t,e){switch(this.jn=t,this.Ie=[],e){case"sha1":this.Gt="SHA-1";break;case"sha256":this.Gt="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.Ie.join(""),i=new TextEncoder().encode(e),n=await this.jn.subtle.digest(this.Gt,i);switch(t){case"base64":return btoa(String.fromCharCode(...new Uint8Array(n)));case"hex":return[...new Uint8Array(n)].map(r=>r.toString(16).padStart(2,"0")).join("");default:throw new Error(`Encoding is not supported ${t}`)}}update(t){return this.Ie.push(t),this}},xa={start:0,end:3},Ca={start:4,end:5},bt={start:6,end:7},kt={start:8,end:8},Sa={start:9,end:9},Ra={start:10,end:15};function Oa(){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 M(t,e){let i="";for(let n=e.start;n<=e.end;n+=1)i+=t[n].toString(16).padStart(2,"0");return i}function Ia(t){return t[kt.start]=(t[kt.start]|128)&191,t[bt.start]=t[bt.start]&15|64,`${M(t,xa)}-${M(t,Ca)}-${M(t,bt)}-${M(t,kt)}${M(t,Sa)}-${M(t,Ra)}`}function La(){let t=Oa();return Ia(t)}function $a(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():La()}var Ta=class{createHash(t){return new Ea(aa(),t)}randomUUID(){return $a()}};function Pa(t){let e=Array.from(t,i=>String.fromCodePoint(i)).join("");return btoa(e)}var Na=class{btoa(t){return Pa(new TextEncoder().encode(t))}},ja=class{constructor(t){this.e=t}platformData(){return{name:"JS"}}sdkData(){let t={name:"@launchdarkly/js-client-sdk",version:"4.4.1",userAgentBase:"JSClient"};return this.e.wrapperName&&(t.wrapperName=this.e.wrapperName),this.e.wrapperVersion&&(t.wrapperVersion=this.e.wrapperVersion),t}},Aa=class{constructor(t,e){this.pt=t,this.n={},this.C=new nn(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.Ae=e.errorFilter,this.Te()}Te(){this.K=new EventSource(this.pt),this.K.onopen=()=>{var t;this.C.success(),(t=this.onopen)==null||t.call(this)},this.K.onerror=t=>{var e;this.w(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.n).forEach(([t,e])=>{e.forEach(i=>{var n;(n=this.K)==null||n.addEventListener(t,i)})})}addEventListener(t,e){var i,n,r;(n=(i=this.n)[t])!=null||(i[t]=[]),this.n[t].push(e),(r=this.K)==null||r.addEventListener(t,e)}close(){var t,e;clearTimeout(this.Kt),this.Kt=void 0,(t=this.K)==null||t.close(),(e=this.onclose)==null||e.call(this)}Vn(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.Kt=setTimeout(()=>{this.Te()},t)}w(t){this.close(),!(typeof t.status=="number"&&!this.Ae(t))&&this.Vn(this.C.fail())}},Va=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new Aa(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function si(){return typeof localStorage!="undefined"}function Ma(){if(!si())return[];let t=[];for(let e=0;e<localStorage.length;e+=1){let i=localStorage.key(e);i&&t.push(i)}return t}var Fa=class{constructor(t){this.t=t}async clear(t){var e;try{localStorage.removeItem(t)}catch(i){(e=this.t)==null||e.error(`Error clearing key from localStorage: ${t}, reason: ${i}`)}}async get(t){var e;try{let i=localStorage.getItem(t);return i!=null?i:null}catch(i){return(e=this.t)==null||e.error(`Error getting key from localStorage: ${t}, reason: ${i}`),null}}async set(t,e){var i;try{localStorage.setItem(t,e)}catch(n){(i=this.t)==null||i.error(`Error setting key in localStorage: ${t}, reason: ${n}`)}}},Ua=class{constructor(t,e){this.encoding=new Na,this.crypto=new Ta,this.requests=new Va,si()&&(this.storage=new Fa(t)),this.info=new ja(e)}},za=class extends _r{constructor(t,e,i={},n){var r;let{logger:a,debug:o}=i,s=a!=null?a:new De({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:o?"debug":"info"}),l=(r=i.baseUri)!=null?r:"https://clientsdk.launchdarkly.com",u=n!=null?n:new Ua(s,i),c=Da(i,s),h=ka(T(v({},i),{logger:s})),{eventUrlTransformer:g}=c,p=Gr(t);super(t,e,u,h,(m,w,D,f,x)=>new ua(u,m,t,w,c,p.polling,p.streaming,D,f,x),{getLegacyStorageKeys:()=>Ma().filter(m=>m.startsWith(`ld:${t}:`)),analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",dataSystemDefaults:Qn,trackEventModifier:m=>new L.InputCustomEvent(m.context,m.key,m.data,m.metricValue,m.samplingRatio,g(_())),getImplementationHooks:m=>L.safeGetHooks(s,m,c.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),this.Wt=c.plugins,c.fetchGoals&&(this.qt=new va(t,u.requests,l,m=>{s.error(m.message)},(m,w)=>{let D=this.getInternalContext();if(!D)return;let f=g(m);ma(w)?this.sendEvent({kind:"click",url:f,samplingRatio:1,key:w.key,creationDate:Date.now(),context:D,selector:w.selector}):this.sendEvent({kind:"pageview",url:f,samplingRatio:1,key:w.key,creationDate:Date.now(),context:D})}),this.qt.initialize(),c.automaticBackgroundHandling&&ca(()=>this.flush()))}registerPlugins(t){L.safeRegisterPlugins(this.logger,this.environmentMetadata,t,this.Wt||[]);let e=this.getDebugOverrides();e&&Wr(this.logger,e,this.Wt||[])}setInitialContext(t){this.Jt=t}async identify(t,e){return super.identify(t,e)}async identifyResult(t,e){var i;if(!this.X)return this.logger.error("Client must be started before it can identify a context, did you forget to call start()?"),{status:"error",error:new Error("Identify called before start")};let n=v({},e);(e==null?void 0:e.sheddable)===void 0&&(n.sheddable=!0);let r=await super.identifyResult(t,n);return(i=this.qt)==null||i.startTracking(),r}start(t){var e,i;if(this.initializeResult)return Promise.resolve(this.initializeResult);if(this.X)return this.X;if(!this.Jt)return this.logger.error("Initial context not set"),Promise.resolve({status:"failed",error:new Error("Initial context not set")});let n=T(v({},(e=t==null?void 0:t.identifyOptions)!=null?e:{}),{sheddable:!1});if(t!=null&&t.bootstrap&&!n.bootstrap&&(n.bootstrap=t.bootstrap),n!=null&&n.bootstrap)try{n.bootstrapParsed||(n.bootstrapParsed=ii(this.logger,n.bootstrap)),this.presetFlags(n.bootstrapParsed)}catch(r){this.logger.error("Failed to bootstrap data",r)}return this.initializedPromise||(this.initializedPromise=new Promise(r=>{this.initResolve=r})),this.X=this.promiseWithTimeout(this.initializedPromise,(i=t==null?void 0:t.timeout)!=null?i:5),this.identifyResult(this.Jt,n),this.X}setStreaming(t){this.dataManager.setForcedStreaming(t)}$e(){let t=this.dataManager,e=this.emitter.eventNames().some(i=>i.startsWith("change:")||i==="change");t.setAutomaticStreamingState(e)}on(t,e){super.on(t,e),this.$e()}off(t,e){super.off(t,e),this.$e()}};function Ka(t,e,i,n={},r){let a=new za(t,i,n,r);a.setInitialContext(e);let o={variation:(s,l)=>a.variation(s,l),variationDetail:(s,l)=>a.variationDetail(s,l),boolVariation:(s,l)=>a.boolVariation(s,l),boolVariationDetail:(s,l)=>a.boolVariationDetail(s,l),numberVariation:(s,l)=>a.numberVariation(s,l),numberVariationDetail:(s,l)=>a.numberVariationDetail(s,l),stringVariation:(s,l)=>a.stringVariation(s,l),stringVariationDetail:(s,l)=>a.stringVariationDetail(s,l),jsonVariation:(s,l)=>a.jsonVariation(s,l),jsonVariationDetail:(s,l)=>a.jsonVariationDetail(s,l),track:(s,l,u)=>a.track(s,l,u),on:(s,l)=>a.on(s,l),off:(s,l)=>a.off(s,l),flush:()=>a.flush(),setStreaming:s=>a.setStreaming(s),identify:(s,l)=>a.identifyResult(s,l),getContext:()=>a.getContext(),close:()=>a.close(),allFlags:()=>a.allFlags(),addHook:s=>a.addHook(s),waitForInitialization:s=>a.waitForInitialization(s),logger:a.logger,start:s=>a.start(s)};return a.registerPlugins(o),o}function oi(t,e,i){return Ka(t,e,rt.Disabled,i)}function Ja(){return typeof window=="undefined"}function Q(t){return{value:t,kind:"NO Evaluation Reason"}}function Ba(){return{allFlags:()=>({}),boolVariation:(t,e)=>e,boolVariationDetail:(t,e)=>Q(e),close:()=>Promise.resolve(),flush:()=>Promise.resolve({result:!0}),getContext:()=>{},getInitializationState:()=>"unknown",getInitializationError:()=>{},identify:()=>Promise.resolve({status:"completed"}),jsonVariation:(t,e)=>e,jsonVariationDetail:(t,e)=>Q(e),logger:{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},numberVariation:(t,e)=>e,numberVariationDetail:(t,e)=>Q(e),off:()=>{},on:()=>{},onContextChange:()=>()=>{},onInitializationStatusChange:()=>()=>{},setStreaming:()=>{},start:()=>Promise.resolve({status:"failed",error:new Error("Server-side client cannot be used to start")}),stringVariation:(t,e)=>e,stringVariationDetail:(t,e)=>Q(e),track:()=>{},variation:(t,e)=>e!=null?e:null,variationDetail:(t,e)=>{let i=e!=null?e:null;return Q(i)},waitForInitialization:()=>Promise.resolve({status:"failed",error:new Error("Server-side client cannot be used to wait for initialization")}),addHook:()=>{},shouldUseCamelCaseFlagKeys:()=>!0}}function ht(t,e,i){var u;if(Ja())return Ba();let n=(u=i==null?void 0:i.useCamelCaseFlagKeys)!=null?u:!0,r=oi(t,e,i),a="unknown",o=new Set,s=new Set,l;return V(A({},r),{start:c=>a!=="unknown"?r.start(c):(a="initializing",r.start(c).then(h=>(a=h.status,l=h,s.forEach(g=>g(h)),h))),identify:(...c)=>r.identify(...c).then(h=>{if(h.status==="completed"){let g=r.getContext();g&&o.forEach(p=>p(g))}return h}),getInitializationState:()=>a,getInitializationError:()=>(l==null?void 0:l.status)==="failed"?l.error:void 0,onContextChange:c=>(o.add(c),()=>{o.delete(c)}),onInitializationStatusChange:c=>(l&&c(l),s.add(c),()=>{s.delete(c)}),shouldUseCamelCaseFlagKeys:()=>n})}function jt(t,e){var r;let i=(r=e==null?void 0:e.Provider)!=null?r:R.Provider;return({children:a})=>{var l;let[o,s]=(0,H.useState)({client:t,context:(l=t.getContext())!=null?l:void 0,initializedState:t.getInitializationState(),error:t.getInitializationError()});return(0,H.useEffect)(()=>{let u=!0,c=t.onInitializationStatusChange(g=>{u&&s(p=>p.initializedState===g.status?p:V(A({},p),{initializedState:g.status,error:g.status==="failed"?g.error:void 0}))}),h=t.onContextChange(g=>{u&&s(p=>V(A({},p),{context:g}))});return()=>{u=!1,c(),h()}},[]),H.default.createElement(i,{value:o},a)}}function li(t,e,i){let{deferInitialization:n,startOptions:r,reactContext:a,ldOptions:o,bootstrap:s}=i!=null?i:{},l=ht(t,e,o);if(!n){let u=s?V(A({},r),{bootstrap:s}):r;l.start(u)}return jt(l,a)}var O=require("react");function ui(t){return t.replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[-._\s]+/).filter(Boolean).map((e,i)=>{let n=e.toLowerCase();return i===0?n:n.charAt(0).toUpperCase()+n.slice(1)}).join("")}function Ha(t,e){let i=new Map,n=t.shouldUseCamelCaseFlagKeys(),r={},a={};return Object.keys(e).filter(o=>o.indexOf("$")!==0).forEach(o=>{if(n){let s=ui(o);r[s]=e[o],a[s]=o}else r[o]=e[o]}),new Proxy(r,{get(o,s,l){var g;let u=Reflect.get(o,s,l);if(typeof s=="symbol"||!Object.prototype.hasOwnProperty.call(o,s))return u;if(u===void 0)return;if(i.has(s))return i.get(s);let c=n&&(g=a[s])!=null?g:s,h=t.variation(c,u);return i.set(s,h),h}})}function ci(t){let{client:e,context:i}=(0,O.useContext)(t!=null?t:R);(0,O.useEffect)(()=>{e.logger.warn("[LaunchDarkly] useFlags is deprecated and will be removed in a future major version.")},[]);let[n,r]=(0,O.useState)(()=>e.allFlags()),a=(0,O.useRef)(!1);return(0,O.useEffect)(()=>{a.current&&r(e.allFlags()),a.current=!0;let o=()=>r(e.allFlags());return e.on("change",o),()=>e.off("change",o)},[e,i]),(0,O.useMemo)(()=>Ha(e,n),[e,n,i])}var hi=require("react");function di(t){let{initializedState:e,error:i}=(0,hi.useContext)(t!=null?t:R);return e==="failed"?{status:"failed",error:i}:{status:e}}var fi=require("react");function gi(t){let{client:e}=(0,fi.useContext)(t!=null?t:R);return e}var P=require("react");function I(t,e,i,n){let{client:r,context:a}=(0,P.useContext)(n!=null?n:R),o=(0,P.useRef)(e);o.current=e;let s=(0,P.useRef)(i);s.current=i;let l=(0,P.useRef)(!1),[u,c]=(0,P.useState)(()=>i(r,t,e));return(0,P.useEffect)(()=>{l.current&&c(s.current(r,t,o.current)),l.current=!0;let h=()=>c(s.current(r,t,o.current));return r.on(`change:${t}`,h),()=>r.off(`change:${t}`,h)},[r,t,a]),u}function pi(t,e,i){return I(t,e,(n,r,a)=>n.boolVariation(r,a),i)}function vi(t,e,i){return I(t,e,(n,r,a)=>n.stringVariation(r,a),i)}function mi(t,e,i){return I(t,e,(n,r,a)=>n.numberVariation(r,a),i)}function yi(t,e,i){return I(t,e,(n,r,a)=>n.jsonVariation(r,a),i)}function wi(t,e,i){return I(t,e,(n,r,a)=>n.boolVariationDetail(r,a),i)}function bi(t,e,i){return I(t,e,(n,r,a)=>n.stringVariationDetail(r,a),i)}function ki(t,e,i){return I(t,e,(n,r,a)=>n.numberVariationDetail(r,a),i)}function Di(t,e,i){return I(t,e,(n,r,a)=>n.jsonVariationDetail(r,a),i)}0&&(module.exports={LDReactContext,createClient,createLDReactProvider,createLDReactProviderWithClient,initLDReactContext,useBoolVariation,useBoolVariationDetail,useFlags,useInitializationStatus,useJsonVariation,useJsonVariationDetail,useLDClient,useNumberVariation,useNumberVariationDetail,useStringVariation,useStringVariationDetail});
2
+ "use strict";var ti=Object.create;var Se=Object.defineProperty,ri=Object.defineProperties,ni=Object.getOwnPropertyDescriptor,ii=Object.getOwnPropertyDescriptors,ai=Object.getOwnPropertyNames,Ne=Object.getOwnPropertySymbols,si=Object.getPrototypeOf,it=Object.prototype.hasOwnProperty,Jt=Object.prototype.propertyIsEnumerable;var Ht=(e,t,r)=>t in e?Se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,J=(e,t)=>{for(var r in t||(t={}))it.call(t,r)&&Ht(e,r,t[r]);if(Ne)for(var r of Ne(t))Jt.call(t,r)&&Ht(e,r,t[r]);return e},ne=(e,t)=>ri(e,ii(t));var Gt=(e,t)=>{var r={};for(var n in e)it.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&Ne)for(var n of Ne(e))t.indexOf(n)<0&&Jt.call(e,n)&&(r[n]=e[n]);return r};var oi=(e,t)=>{for(var r in t)Se(e,r,{get:t[r],enumerable:!0})},_t=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ai(t))!it.call(e,i)&&i!==r&&Se(e,i,{get:()=>t[i],enumerable:!(n=ni(t,i))||n.enumerable});return e};var Wt=(e,t,r)=>(r=e!=null?ti(si(e)):{},_t(t||!e||!e.__esModule?Se(r,"default",{value:e,enumerable:!0}):r,e)),li=e=>_t(Se({},"__esModule",{value:!0}),e);var _o={};oi(_o,{LDIsomorphicClientProvider:()=>Tn,LDReactContext:()=>U,createClient:()=>Ye,createLDReactProvider:()=>Qe,createLDReactProviderWithClient:()=>Le,initLDReactContext:()=>at,useBoolVariation:()=>zn,useBoolVariationDetail:()=>Bn,useFlags:()=>Fn,useInitializationStatus:()=>An,useJsonVariation:()=>Kn,useJsonVariationDetail:()=>Gn,useLDClient:()=>Vn,useNumberVariation:()=>qn,useNumberVariationDetail:()=>Jn,useStringVariation:()=>Un,useStringVariationDetail:()=>Hn});module.exports=li(_o);var Zt=require("react");function at(){return(0,Zt.createContext)(null)}var U=at();var De=Wt(require("react"),1);var ui=Object.defineProperty,ci=Object.defineProperties,di=Object.getOwnPropertyDescriptors,ze=Object.getOwnPropertySymbols,Rr=Object.prototype.hasOwnProperty,Ir=Object.prototype.propertyIsEnumerable,Yt=(e,t,r)=>t in e?ui(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,E=(e,t)=>{for(var r in t||(t={}))Rr.call(t,r)&&Yt(e,r,t[r]);if(ze)for(var r of ze(t))Ir.call(t,r)&&Yt(e,r,t[r]);return e},V=(e,t)=>ci(e,di(t)),St=(e,t)=>{var r={};for(var n in e)Rr.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&ze)for(var n of ze(e))t.indexOf(n)<0&&Ir.call(e,n)&&(r[n]=e[n]);return r};function hi(e){return`/${e.replace(/~/g,"~0").replace(/\//g,"~1")}`}function Or(e){return e.indexOf("~")?e.replace(/~1/g,"/").replace(/~0/g,"~"):e}function fi(e){return(e.startsWith("/")?e.substring(1):e).split("/").map(t=>Or(t))}function gi(e){return!e.startsWith("/")}function pi(e){return!e.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var ye=class{constructor(e,t=!1){if(t){let r=e;this.y=[r],this.isValid=r!=="",this.redactionName=r.startsWith("/")?hi(r):r}else{if(this.redactionName=e,e===""||e==="/"||!pi(e)){this.isValid=!1,this.y=[];return}gi(e)?this.y=[e]:e.indexOf("/",1)<0?this.y=[Or(e.slice(1))]:this.y=fi(e),this.y[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(e){let{y:t,isValid:r}=this;if(!r)return;let n=e;for(let i=0;i<t.length;i+=1){let a=t[i];if(n!=null&&Object.prototype.hasOwnProperty.call(n,a)&&typeof n=="object"&&!Array.isArray(n))n=n[a];else return}return n}getComponent(e){return this.y[e]}get depth(){return this.y.length}get isKind(){return this.y.length===1&&this.y[0]==="kind"}compare(e){return this.depth===e.depth&&this.y.every((t,r)=>t===e.getComponent(r))}get components(){return[...this.y]}};ye.InvalidReference=new ye("");var vi=class{is(e){if(Array.isArray(e))return!1;let t=typeof e;return t==="function"||t==="object"}getType(){return"factory method or object"}},ke=class{constructor(e,t){this.pt=e,this.typeOf=typeof t}is(e){return Array.isArray(e)?!1:typeof e===this.typeOf}getType(){return this.pt}},Pr=class{constructor(e,t){this.pt=e,this.typeOf=typeof t}is(e){return Array.isArray(e)?e.length>0?e.every(t=>typeof t===this.typeOf):!0:!1}getType(){return this.pt}},$r=class extends ke{constructor(e){super(`number with minimum value of ${e}`,0),this.min=e}is(e){return typeof e===this.typeOf&&e>=this.min}},Lr=class extends ke{constructor(e){super(`string matching ${e}`,""),this.expression=e}is(e){return typeof e=="string"&&!!e.match(this.expression)}},mi=class{is(e){return typeof e=="function"}getType(){return"function"}},yi=class{is(e){return typeof e=="boolean"||typeof e=="undefined"||e===null}getType(){return"boolean | undefined | null"}},wi=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,bi=class{is(e){return typeof e=="number"||typeof e=="string"&&wi.test(e)}getType(){return"date"}},ki=class extends Lr{constructor(){super(/^(\w|\.|-)+$/)}is(e){return super.is(e)&&e!=="kind"}},Ei=class{constructor(e){this.Yt=e}is(e){return typeof e=="string"&&this.Yt.includes(e)}getType(){return this.Yt.join(" | ")}};function ie(e){return e==null}var p=class{static createTypeArray(e,t){return new Pr(e,t)}static numberWithMin(e){return new $r(e)}static stringMatchingRegex(e){return new Lr(e)}static oneOf(...e){return new Ei(e)}};p.String=new ke("string","");p.Number=new ke("number",0);p.ObjectOrFactory=new vi;p.Object=new ke("object",{});p.StringArray=new Pr("string[]","");p.Boolean=new ke("boolean",!0);p.Function=new mi;p.Date=new bi;p.Kind=new ki;p.NullableBoolean=new yi;function Tr(e){return"kind"in e?p.String.is(e.kind)&&e.kind!=="multi":!1}function Mr(e){return"kind"in e?p.String.is(e.kind)&&e.kind==="multi":!1}function Fr(e){return!("kind"in e)||e.kind===null||e.kind===void 0}function Ue(e,t=[]){if(e===null||typeof e!="object")return JSON.stringify(e);if(t.includes(e))throw new Error("Cycle detected");return Array.isArray(e)?`[${e.map(r=>Ue(r,[...t,e])).map(r=>r===void 0?"null":r).join(",")}]`:`{${Object.keys(e).sort().map(r=>{let n=Ue(e[r],[...t,e]);if(n!==void 0)return`${JSON.stringify(r)}:${n}`}).filter(r=>r!==void 0).join(",")}}`}var vt="user";function Qt(e){return e.includes("%")||e.includes(":")?e.replace(/%/g,"%25").replace(/:/g,"%3A"):e}function Di(e){return e&&p.Object.is(e)}function Xt(e){return p.Kind.is(e)}function er(e){return p.String.is(e)&&e!==""}function st(e,t=!1){return e?e.map(r=>new ye(r,t)):[]}function Ci(e){return e!=null}function xi(e){let t=V(E({},e.custom||[]),{kind:"user",key:String(e.key)});if(Ci(e.anonymous)){let r=!!e.anonymous;delete t.anonymous,t.anonymous=r}return e.name!==null&&e.name!==void 0&&(t.name=e.name),e.ip!==null&&e.ip!==void 0&&(t.ip=e.ip),e.firstName!==null&&e.firstName!==void 0&&(t.firstName=e.firstName),e.lastName!==null&&e.lastName!==void 0&&(t.lastName=e.lastName),e.email!==null&&e.email!==void 0&&(t.email=e.email),e.avatar!==null&&e.avatar!==void 0&&(t.avatar=e.avatar),e.country!==null&&e.country!==void 0&&(t.country=e.country),e.privateAttributeNames!==null&&e.privateAttributeNames!==void 0&&(t._meta={privateAttributes:e.privateAttributeNames}),t}var de=class L{constructor(t,r,n){this.I=!1,this.Q=!1,this.Zt=!1,this.M={},this.kind=r,this.valid=t,this.message=n}static D(t,r){return new L(!1,t,r)}static $e(t,r){if(!(!r||!t.isValid))return t.depth===1&&t.getComponent(0)==="anonymous"?!!(r!=null&&r.anonymous):t.get(r)}Xt(t){if(this.I)return this.M[t];if(this.kind===t)return this.v}static Re(t){let r=Object.keys(t).filter(l=>l!=="kind"),n=r.every(Xt);if(!r.length)return L.D("multi","A multi-kind context must contain at least one kind");if(!n)return L.D("multi","Context contains invalid kinds");let i={},a=!0,s=r.reduce((l,u)=>{var d;let c=t[u];return Di(c)?(l[u]=c,i[u]=st((d=c._meta)==null?void 0:d.privateAttributes)):a=!1,l},{});if(!a)return L.D("multi","Context contained contexts that were not objects");if(!Object.values(s).every(l=>er(l.key)))return L.D("multi","Context contained invalid keys");if(r.length===1){let l=r[0],u=new L(!0,l);return u.v=V(E({},s[l]),{kind:l}),u.tt=i,u.Q=l==="user",u}let o=new L(!0,t.kind);return o.M=s,o.tt=i,o.I=!0,o}static Ne(t){var r;let{key:n,kind:i}=t,a=Xt(i),s=er(n);if(!a)return L.D(i!=null?i:"unknown","The kind was not valid for the context");if(!s)return L.D(i,"The key for the context was not valid");let o=st((r=t._meta)==null?void 0:r.privateAttributes),l=new L(!0,i);return l.Q=i==="user",l.v=t,l.tt={[i]:o},l}static Ue(t){if(!(t.key!==void 0&&t.key!==null))return L.D("user","The key for the context was not valid");let r=new L(!0,"user");return r.Q=!0,r.Zt=!0,r.v=xi(t),r.tt={user:st(t.privateAttributeNames,!0)},r}static fromLDContext(t){return t?Tr(t)?L.Ne(t):Mr(t)?L.Re(t):Fr(t)?L.Ue(t):L.D("unknown","Context was not of a valid kind"):L.D("unknown","No context specified. Returning default value")}static toLDContext(t){if(!t.valid)return;let r=t.getContexts();if(!t.I)return r[0][1];let n={kind:"multi"};return r.forEach(i=>{let a=i[0],s=i[1];n[a]=s}),n}valueForKind(t,r=vt){return t.isKind?this.kinds:L.$e(t,this.Xt(r))}key(t=vt){var r;return(r=this.Xt(t))==null?void 0:r.key}get isMultiKind(){return this.I}get canonicalKey(){return this.Q?this.v.key:this.I?Object.keys(this.M).sort().map(t=>`${t}:${Qt(this.M[t].key)}`).join(":"):`${this.kind}:${Qt(this.v.key)}`}get kinds(){return this.I?Object.keys(this.M):[this.kind]}get kindsAndKeys(){return this.I?Object.entries(this.M).reduce((t,[r,n])=>(t[r]=n.key,t),{}):{[this.kind]:this.v.key}}privateAttributes(t){var r;return((r=this.tt)==null?void 0:r[t])||[]}getContexts(){return this.I?Object.entries(this.M):[[this.kind,this.v]]}get legacy(){return this.Zt}canonicalUnfilteredJson(){if(this.valid){if(this.mt)return this.mt;try{this.mt=Ue(L.toLDContext(this))}catch(t){}return this.mt}}};de.UserKind=vt;var Si=["key","kind","_meta","anonymous"].map(e=>new ye(e,!0)),Ri=["name","ip","firstName","lastName","email","avatar","country"];function Ii(e,t){return e.depth===t.length&&t.every((r,n)=>r===e.getComponent(n))}function Oi(e,t){let r=[],n={},i=[];for(r.push(...Object.keys(e).map(a=>({key:a,ptr:[a],source:e,parent:n,visited:[e]})));r.length;){let a=r.pop(),s=t.find(o=>Ii(o,a.ptr));if(s)i.push(s.redactionName);else{let o=a.source[a.key];o===null?a.parent[a.key]=o:Array.isArray(o)?a.parent[a.key]=[...o]:typeof o=="object"?a.visited.includes(o)||(a.parent[a.key]={},r.push(...Object.keys(o).map(l=>({key:l,ptr:[...a.ptr,l],source:o,parent:a.parent[a.key],visited:[...a.visited,o]})))):a.parent[a.key]=o}}return{cloned:n,excluded:i.sort()}}var Pi=class{constructor(e,t){this.ze=e,this.je=t}filter(e,t=!1){let r=e.getContexts();if(r.length===1)return this.Qt(e,r[0][1],r[0][0],t);let n={kind:"multi"};return r.forEach(([i,a])=>{n[i]=this.Qt(e,a,i,t)}),n}p(e,t,r,n){return(n?Object.keys(t).map(i=>new ye(i,!0)):[...this.je,...e.privateAttributes(r)]).filter(i=>!Si.some(a=>a.compare(i)))}Qt(e,t,r,n){let i=this.ze||n&&t.anonymous===!0,{cloned:a,excluded:s}=Oi(t,this.p(e,t,r,i));return e.legacy&&Ri.forEach(o=>{o in a&&(a[o]=String(a[o]))}),s.length&&(a._meta||(a._meta={}),a._meta.redactedAttributes=s),a._meta&&(delete a._meta.privateAttributes,Object.keys(a._meta).length===0&&delete a._meta),a}},tr=30*1e3,$i=.5,Li=class{constructor(e,t,r=Math.random){this.Ve=t,this.Be=r,this.yt=0,this.te=Math.max(1,e),this.He=Math.ceil(Math.log2(tr/this.te))}x(){let e=Math.min(this.yt,this.He),t=this.te*2**e;return Math.min(t,tr)}qe(e){return e-Math.trunc(this.Be()*$i*e)}success(e=Date.now()){this.gt=e}fail(e=Date.now()){this.gt!==void 0&&e-this.gt>this.Ve&&(this.yt=0),this.gt=void 0;let t=this.qe(this.x());return this.yt+=1,t}},rr;(function(e){e[e.Valid=0]="Valid",e[e.Initializing=1]="Initializing",e[e.Interrupted=2]="Interrupted",e[e.Closed=3]="Closed"})(rr||(rr={}));var qe=class extends Error{constructor(e,t,r,n=!0){super(t),this.kind=e,this.status=r,this.name="LaunchDarklyPollingError",this.recoverable=n}},mt=class extends Error{constructor(e,t,r,n=!0){super(t),this.kind=e,this.code=r,this.name="LaunchDarklyStreamingError",this.recoverable=n}},Yo=120*1e3,Qo=300*1e3,T;(function(e){e.Unknown="UNKNOWN",e.NetworkError="NETWORK_ERROR",e.ErrorResponse="ERROR_RESPONSE",e.InvalidData="INVALID_DATA"})(T||(T={}));var Ke;(function(e){e[e.Disabled=0]="Disabled",e[e.Enabled=1]="Enabled"})(Ke||(Ke={}));var we;(function(e){e[e.AnalyticsEvents=0]="AnalyticsEvents",e[e.DiagnosticEvent=1]="DiagnosticEvent"})(we||(we={}));var ce;(function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed",e[e.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(ce||(ce={}));function ve(e){if(typeof e=="string")return e;if(e===void 0)return"undefined";if(e===null)return"null";if(Object.prototype.hasOwnProperty.call(e,"toString"))try{return e.toString()}catch(t){}if(typeof e=="bigint")return`${e}n`;try{return JSON.stringify(e)}catch(t){return t instanceof TypeError&&t.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}function Ti(e){return typeof e=="symbol"?"NaN":typeof e=="bigint"?`${e}n`:String(Number(e))}function Mi(e){return typeof e=="symbol"?"NaN":typeof e=="bigint"?`${e}n`:String(parseInt(e,10))}function Fi(e){return typeof e=="symbol"?"NaN":String(parseFloat(e))}var ot={s:e=>ve(e),d:e=>Ti(e),i:e=>Mi(e),f:e=>Fi(e),j:e=>ve(e),o:e=>ve(e),O:e=>ve(e),c:()=>""};function yt(...e){var t;let r=e.shift();if(p.String.is(r)){let n="",i=0;for(;i<r.length;){let a=r.charAt(i);if(a==="%"){if(i+1<r.length){let s=r.charAt(i+1);if(s in ot&&e.length){let o=e.shift();n+=(t=ot[s])==null?void 0:t.call(ot,o)}else s==="%"?n+="%":n+=`%${s}`;i+=2}}else n+=a,i+=1}return e.length&&(n.length&&(n+=" "),n+=e.map(ve).join(" ")),n}return e.map(ve).join(" ")}var M;(function(e){e[e.debug=0]="debug",e[e.info=1]="info",e[e.warn=2]="warn",e[e.error=3]="error",e[e.none=4]="none"})(M||(M={}));var Ni=["debug","info","warn","error","none"],Nr=class Ar{static get(){return new Ar({})}constructor(t){var r,n,i;if(this.Qe=(n=M[(r=t.level)!=null?r:"info"])!=null?n:M.info,this.tn=(i=t.name)!=null?i:"LaunchDarkly",this.se=t.formatter,typeof t.destination=="object")this.ae={[M.debug]:t.destination.debug,[M.info]:t.destination.info,[M.warn]:t.destination.warn,[M.error]:t.destination.error};else if(typeof t.destination=="function"){let{destination:a}=t;this.ae={[M.debug]:a,[M.info]:a,[M.warn]:a,[M.error]:a}}}en(...t){var r;try{return this.se?(r=this.se)==null?void 0:r.call(this,...t):yt(...t)}catch(n){return yt(...t)}}nn(t,r){try{t(r)}catch(n){console.error(r)}}S(t,r){var n;if(t>=this.Qe){let i=`${Ni[t]}: [${this.tn}]`;try{let a=(n=this.ae)==null?void 0:n[t];a?this.nn(a,`${i} ${this.en(...r)}`):console.error(...r)}catch(a){console.error(...r)}}}error(...t){this.S(M.error,t)}warn(...t){this.S(M.warn,t)}info(...t){this.S(M.info,t)}debug(...t){this.S(M.debug,t)}},Ai={error:p.Function,warn:p.Function,info:p.Function,debug:p.Function},jr=class{constructor(e,t){Object.entries(Ai).forEach(([r,n])=>{if(!n.is(e[r]))throw new Error(`Provided logger instance must support logger.${r}(...) method`)}),this.t=e,this.rn=t}S(e,t){try{this.t[e](...t)}catch(r){this.rn[e](...t)}}error(...e){this.S("error",e)}warn(...e){this.S("warn",e)}info(...e){this.S("info",e)}debug(...e){this.S("debug",e)}},Vr=e=>{let t=new Nr({level:"info",destination:console.error,formatter:yt});return e?new jr(e,t):t},F=class{static deprecated(e,t){return`"${e}" is deprecated, please use "${t}"`}static optionBelowMinimum(e,t,r){return`Config option "${e}" had invalid value of ${t}, using minimum of ${r} instead`}static unknownOption(e){return`Ignoring unknown config option "${e}"`}static wrongOptionType(e,t,r){return`Config option "${e}" should be of type ${t}, got ${r}, using default value`}static wrongOptionTypeBoolean(e,t){return`Config option "${e}" should be a boolean, got ${t}, converting to boolean`}static invalidTagValue(e){return`Config option "${e}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(e){return`Value of "${e}" was longer than 64 characters and was discarded.`}static partialEndpoint(e){return`You have set custom uris without specifying the ${e} URI; connections may not work properly`}},ji=/^(\w|\.|-)+$/,Vi=p.stringMatchingRegex(ji),zi={is:(e,t)=>Vi.is(e)?e.length>64?{valid:!1,message:F.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:F.invalidTagValue(t)}},Ui=class{constructor(e){let t={},r=e==null?void 0:e.application,n=e==null?void 0:e.logger;r&&Object.entries(r).forEach(([a,s])=>{if(s!=null){let{valid:o,message:l}=zi.is(s,`application.${a}`);o?a==="versionName"?t["application-version-name"]=[s]:t[`application-${a}`]=[s]:n==null||n.warn(l)}});let i=Object.keys(t);i.length&&(this.value=i.sort().flatMap(a=>t[a].sort().map(s=>`${a}/${s}`)).join(" "))}},qi=class{constructor(e,t,r){this.platform=r,this.basicConfiguration={tags:t.tags,logger:t.logger,offline:t.offline,serviceEndpoints:t.serviceEndpoints,sdkKey:e}}};function lt(e){return e.replace(/\/+$/,"")}function Rt(e){return e.replace(/^\/+/,"").replace(/\?$/,"")}var be=class zr{constructor(t,r,n=zr.DEFAULT_EVENTS,i="/bulk",a="/diagnostic",s=!0,o){this.streaming=lt(t),this.polling=lt(r),this.events=lt(n),this.analyticsEventPath=i,this.diagnosticEventPath=a,this.includeAuthorizationHeader=s,this.payloadFilterKey=o}};be.DEFAULT_EVENTS="https://events.launchdarkly.com";function It(e,t=[]){if(t.length===0)return e;let r=t.map(({key:n,value:i})=>`${n}=${i}`);return`${e}?${r.join("&")}`}function Ur(e,t,r){let n=Rt(t),i=[...r];return e.payloadFilterKey&&i.push({key:"filter",value:e.payloadFilterKey}),It(`${e.streaming}/${n}`,i)}function qr(e,t,r=[]){let n=Rt(t),i=[...r];return e.payloadFilterKey&&i.push({key:"filter",value:e.payloadFilterKey}),It(`${e.polling}/${n}`,i)}function nr(e,t,r=[]){let n=Rt(t);return It(`${e.events}/${n}`,r)}var Kr=class extends Error{constructor(e){super(e),this.name="LaunchDarklyUnexpectedResponseError"}},Ki=class extends Error{constructor(e){super(e),this.name="LaunchDarklyClientError"}},Br=class extends Error{constructor(e){super(e),this.name="LaunchDarklyTimeoutError"}};function Ee(e){return e>=400&&e<500?e===400||e===408||e===429:!0}function Bi(e){return e===413?!0:Ee(e)}function Hr(e,t){let r,n;return{promise:new Promise((i,a)=>{n=i,r=setTimeout(()=>{let s=`${t} timed out after ${e} seconds.`;a(new Br(s))},e*1e3)}),cancel:()=>{n(),clearTimeout(r)}}}function Jr(e){return e==null?e:JSON.parse(JSON.stringify(e))}function ut(e){return Math.trunc(e*1e3)}var Hi=e=>JSON.stringify(e)==="{}",Ot=(e,t)=>e&&Object.entries(e).reduce((r,[n,i])=>(i&&!Hi(i)&&!(t!=null&&t.includes(n))&&(r[n]=typeof i=="object"?Ot(i,t):i),r),{});function Ae(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var r,n,i;if(Array.isArray(e)){if(r=e.length,r!=t.length)return!1;for(n=r;n--!==0;)if(!Ae(e[n],t[n]))return!1;return!0}if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(n of e.entries())if(!t.has(n[0]))return!1;for(n of e.entries())if(!Ae(n[1],t.get(n[0])))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(n of e.entries())if(!t.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(e)&&ArrayBuffer.isView(t)){if(r=e.length,r!=t.length)return!1;for(n=r;n--!==0;)if(e[n]!==t[n])return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(i=Object.keys(e),r=i.length,r!==Object.keys(t).length)return!1;for(n=r;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,i[n]))return!1;for(n=r;n--!==0;){var a=i[n];if(!Ae(e[a],t[a]))return!1}return!0}return e!==e&&t!==t}function Ji(e,t,r,n=!0,i="user-agent"){let{userAgentBase:a,version:s,wrapperName:o,wrapperVersion:l}=t.sdkData(),u={[i]:`${a!=null?a:"NodeJSClient"}/${s}`};return n&&(u.authorization=e),o&&(u["x-launchdarkly-wrapper"]=l?`${o}/${l}`:o),r!=null&&r.value&&(u["x-launchdarkly-tags"]=r.value),u}function X(e,t,r){let n;e.status?n=`error ${e.status}${e.status===401?" (invalid SDK key)":""}`:n=`I/O error (${e.message||"unknown error"})`;let i=r!=null?r:"giving up permanently";return`Received ${n} for ${t} - ${i}`}function Pt({status:e}){return e?Ee(e):!0}var Be=(e,t)=>t.btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""),$t=async(e=1e3)=>new Promise(t=>{setTimeout(t,e)}),Gi=class{constructor(e,t,r){this.a=t,this.sn=r,this.Et=[],this.oe=Date.now(),this.ce=this.oe,this.ue={diagnosticId:t.crypto.randomUUID(),sdkKeySuffix:e.length>6?e.substring(e.length-6):e}}createInitEvent(){var e,t,r;let n=this.a.info.sdkData(),i=this.a.info.platformData();return{kind:"diagnostic-init",id:this.ue,creationDate:this.oe,sdk:n,configuration:this.sn,platform:E({name:i.name,osArch:(e=i.os)==null?void 0:e.arch,osName:(t=i.os)==null?void 0:t.name,osVersion:(r=i.os)==null?void 0:r.version},i.additional||{})}}recordStreamInit(e,t,r){let n={timestamp:e,failed:t,durationMillis:r};this.Et.push(n)}createStatsEventAndReset(e,t,r){let n=Date.now(),i={kind:"diagnostic",id:this.ue,creationDate:n,dataSinceDate:this.ce,droppedEvents:e,deduplicatedUsers:t,eventsInLastBatch:r,streamInits:this.Et};return this.Et=[],this.ce=n,i}},wt;(function(e){e.MalformedFlag="MALFORMED_FLAG",e.UserNotSpecified="USER_NOT_SPECIFIED",e.FlagNotFound="FLAG_NOT_FOUND",e.ClientNotReady="CLIENT_NOT_READY",e.WrongType="WRONG_TYPE"})(wt||(wt={}));var _i=wt,Gr=class{static invalidMetricValue(e){return`The track function was called with a non-numeric "metricValue" (${e}), only numeric metric values are supported.`}};Gr.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var Wi=class{constructor(e,t){let{basicConfiguration:r,platform:n}=e,{serviceEndpoints:{analyticsEventPath:i,diagnosticEventPath:a}}=r,{crypto:s,requests:o}=n;this.an=E({},t),this.le=nr(r.serviceEndpoints,i,[]),this.cn=nr(r.serviceEndpoints,a,[]),this.z=o,this.un=s}async et(e,t,r,n){let i={status:ce.Succeeded},a=V(E({},this.an),{"content-type":"application/json"});r&&(a["x-launchdarkly-payload-id"]=r,a["x-launchDarkly-event-schema"]="4");let s;try{let{status:o,headers:l}=await this.z.fetch(t,{headers:a,body:JSON.stringify(e),compressBodyIfPossible:!0,method:"POST",keepalive:!0}),u=Date.parse(l.get("date")||"");if(u&&(i.serverTime=u),o<=204)return i;if(s=new Kr(X({status:o,message:"some events were dropped"},"event posting")),!Ee(o))return Bi(o)?i.status=ce.Failed:i.status=ce.FailedAndMustShutDown,i.error=s,i}catch(o){s=o}return s&&!n?(i.status=ce.Failed,i.error=s,i):(await $t(),this.et(e,this.le,r,!1))}async sendEventData(e,t){let r=e===we.AnalyticsEvents?this.un.randomUUID():void 0,n=e===we.AnalyticsEvents?this.le:this.cn;return this.et(t,n,r,!0)}};function He(e){return e.kind==="feature"}function Zi(e){return e.kind==="identify"}function Yi(e){return e.kind==="migration_op"}var Qi=class{constructor(e,t,r,n,i,a){this.count=e,this.key=t,this.value=r,this.version=i,this.variation=a,this.default=n}increment(){this.count+=1}};function Xi(e){return`${e.key}:${e.variation!==null&&e.variation!==void 0?e.variation:""}:${e.version!==null&&e.version!==void 0?e.version:""}`}var _r=class{constructor(e=!1,t){this.ln=e,this.k=t,this.K=0,this.nt=0,this.it={},this.rt={}}summarizeEvent(e){if(He(e)&&!e.excludeFromSummaries){this.v||(this.v=e.context);let t=Xi(e),r=this.it[t],n=this.rt[e.key];n||(n=new Set,this.rt[e.key]=n),e.context.kinds.forEach(i=>n.add(i)),r?r.increment():this.it[t]=new Qi(1,e.key,e.value,e.default,e.version,e.variation),(this.K===0||e.creationDate<this.K)&&(this.K=e.creationDate),e.creationDate>this.nt&&(this.nt=e.creationDate)}}getSummary(){var e;let t=Object.values(this.it).reduce((n,i)=>{let a=n[i.key];a||(a={default:i.default,counters:[],contextKinds:[...this.rt[i.key]]},n[i.key]=a);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,a.counters.push(s),n},{}),r={startDate:this.K,endDate:this.nt,features:t,kind:"summary",context:this.v!==void 0&&this.ln?(e=this.k)==null?void 0:e.filter(this.v):void 0};return this.dn(),r}dn(){this.K=0,this.nt=0,this.it={},this.rt={}}},ea=class extends Error{constructor(e){super(e),this.name="LaunchDarklyInvalidSDKKeyError"}},ta=class{constructor(e,t){this.k=e,this.t=t,this.J={}}summarizeEvent(e){var t;if(He(e)){let r=e.context.canonicalUnfilteredJson();if(!r){e.context.valid&&((t=this.t)==null||t.error("Unable to serialize context, likely the context contains a cycle."));return}let n=this.J[r];n||(this.J[r]=new _r(!0,this.k),n=this.J[r]),n.summarizeEvent(e)}}getSummaries(){let e=this.J;return this.J={},Object.values(e).map(t=>t.getSummary())}};function je(e){let t=Math.trunc(e);return t===1?!0:t===0?!1:Math.floor(Math.random()*t)===0}function ra(e){return e.getSummaries!==void 0}var na=class{constructor(e,t,r,n,i,a=!0,s=!1){this.e=e,this.st=n,this.C=i,this.at=[],this.de=0,this.bt=0,this.Dt=0,this.St=!1,this.he=0,this.kt=!1,this.Ct=null,this.hn=e.eventsCapacity,this.t=t.basicConfiguration.logger,this.fe=new Wi(t,r),this.k=new Pi(e.allAttributesPrivate,e.privateAttributes.map(o=>new ye(o))),s?this.W=new ta(this.k,this.t):this.W=new _r,a&&this.start()}start(){var e,t;if(((e=this.st)==null?void 0:e.flushInterval)!==void 0&&(this.Ct=setInterval(()=>{var r;(r=this.st)==null||r.flush()},this.st.flushInterval*1e3)),this.fn=setInterval(async()=>{var r;try{await this.flush()}catch(n){(r=this.t)==null||r.debug(`Flush failed: ${n}`)}},this.e.flushInterval*1e3),this.C){let r=this.C.createInitEvent();this.pe(r),this.me=setInterval(()=>{let n=this.C.createStatsEventAndReset(this.bt,this.Dt,this.he);this.bt=0,this.Dt=0,this.pe(n)},this.e.diagnosticRecordingInterval*1e3)}(t=this.t)==null||t.debug("Started EventProcessor.")}pe(e){this.fe.sendEventData(we.DiagnosticEvent,e)}close(){clearInterval(this.fn),this.Ct&&clearInterval(this.Ct),this.me&&clearInterval(this.me)}async flush(){var e;if(this.kt)throw new ea("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 t=this.at;if(this.at=[],ra(this.W))this.W.getSummaries().forEach(r=>{Object.keys(r.features).length&&t.push(r)});else{let r=this.W.getSummary();Object.keys(r.features).length&&t.push(r)}t.length&&(this.he=t.length,(e=this.t)==null||e.debug("Flushing %d events",t.length),await this.et(t))}sendEvent(e){var t;if(this.kt)return;if(Yi(e)){if(je(e.samplingRatio)){let o=V(E({},e),{context:e.context?this.k.filter(e.context):void 0});o.samplingRatio===1&&delete o.samplingRatio,this.ot(o)}return}this.W.summarizeEvent(e);let r=He(e),n=r&&e.trackEvents||!r,i=this.pn(e),a=Zi(e),s=(t=this.st)==null?void 0:t.processContext(e.context);s||a||(this.Dt+=1),s&&!a&&this.ot(this.Pt({kind:"index",creationDate:e.creationDate,context:e.context,samplingRatio:1},!1)),n&&je(e.samplingRatio)&&this.ot(this.Pt(e,!1)),i&&je(e.samplingRatio)&&this.ot(this.Pt(e,!0))}Pt(e,t){switch(e.kind){case"feature":{let r={kind:t?"debug":"feature",creationDate:e.creationDate,context:this.k.filter(e.context,!t),key:e.key,value:e.value,default:e.default};return e.samplingRatio!==1&&(r.samplingRatio=e.samplingRatio),e.prereqOf&&(r.prereqOf=e.prereqOf),e.variation!==void 0&&(r.variation=e.variation),e.version!==void 0&&(r.version=e.version),e.reason&&(r.reason=e.reason),r}case"index":case"identify":{let r={kind:e.kind,creationDate:e.creationDate,context:this.k.filter(e.context)};return e.samplingRatio!==1&&(r.samplingRatio=e.samplingRatio),r}case"custom":{let r={kind:"custom",creationDate:e.creationDate,key:e.key,context:this.k.filter(e.context)};return e.samplingRatio!==1&&(r.samplingRatio=e.samplingRatio),e.data!==void 0&&(r.data=e.data),e.metricValue!==void 0&&(r.metricValue=e.metricValue),e.url!==void 0&&(r.url=e.url),r}case"click":return{kind:"click",creationDate:e.creationDate,contextKeys:e.context.kindsAndKeys,key:e.key,url:e.url,selector:e.selector};case"pageview":return{kind:"pageview",creationDate:e.creationDate,contextKeys:e.context.kindsAndKeys,key:e.key,url:e.url};default:return e}}ot(e){var t;this.at.length<this.hn?(this.at.push(e),this.St=!1):(this.St||(this.St=!0,(t=this.t)==null||t.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.bt+=1)}pn(e){return He(e)&&e.debugEventsUntilDate&&e.debugEventsUntilDate>this.de&&e.debugEventsUntilDate>Date.now()}async et(e){let t=await this.fe.sendEventData(we.AnalyticsEvents,e);if(t.status===ce.FailedAndMustShutDown&&(this.kt=!0),t.serverTime&&(this.de=t.serverTime),t.error)throw t.error}},Wr=class{constructor(e,t,r,n,i=1,a){this.context=e,this.key=t,this.data=r,this.metricValue=n,this.samplingRatio=i,this.url=a,this.kind="custom",this.creationDate=Date.now(),this.context=e}},bt=class{constructor(e,t,r,n,i,a,s,o,l,u,d,c,h=1){this.withReasons=e,this.context=t,this.key=r,this.samplingRatio=h,this.kind="feature",this.creationDate=Date.now(),this.value=n,this.default=i,a!==void 0&&(this.version=a),s!==void 0&&(this.variation=s),o!==void 0&&(this.trackEvents=o),l!==void 0&&(this.prereqOf=l),u!==void 0&&(this.reason=u),d!==void 0&&(this.debugEventsUntilDate=d),c!==void 0&&(this.excludeFromSummaries=c)}},Zr=class{constructor(e,t=1){this.context=e,this.samplingRatio=t,this.kind="identify",this.creationDate=Date.now()}},ia=class{close(){}async flush(){}sendEvent(){}},aa=class{constructor(e){this.It=e}evalEvent(e){var t;return new bt(this.It,e.context,e.flagKey,e.value,e.defaultVal,e.version,(t=e.variation)!=null?t:void 0,e.trackEvents||e.addExperimentData,e.prereqOfFlagKey,this.It||e.addExperimentData?e.reason:void 0,e.debugEventsUntilDate,e.excludeFromSummaries,e.samplingRatio)}unknownFlagEvent(e,t,r){return new bt(this.It,r,e,t,t,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(e){return new Zr(e,1)}customEvent(e,t,r,n,i=1){return new Wr(t,e,r!=null?r:void 0,n!=null?n:void 0,i)}},ir="FDv1Fallback";function sa(e){return{mn:e,ye:"",useSelector(t){return this.ye=t,this},processFullTransfer(t){let r=[{event:"server-intent",data:{payloads:[{id:ir,target:1,intentCode:"xfer-full",reason:"payload-missing"}]}}];Object.entries((t==null?void 0:t.flags)||[]).forEach(([n,i])=>{r.push({event:"put-object",data:{kind:"flag",key:n,version:i.version||1,object:i}})}),Object.entries((t==null?void 0:t.segments)||[]).forEach(([n,i])=>{r.push({event:"put-object",data:{kind:"segment",key:n,version:i.version||1,object:i}})}),r.push({event:"payload-transferred",data:{state:this.ye,version:1,id:ir}}),this.mn.processEvents(r)}}}var j={type:"none"};function Yr(e,t){let r="inactive",n="partial",i=[];function a(f,v){var m;return(m=e[f])==null?void 0:m.call(e,v)}function s(){r="inactive",n="partial",i=[]}function o(){r="changes",n="partial",i=[]}function l(){i=[]}function u(f){return ie(f.target)?(t==null||t.warn(`Ignoring 'none' intent with missing fields: target=${f.target}`),j):{type:"payload",payload:{version:f.target,type:"none",updates:[]}}}function d(f){var v;if(!((v=f.payloads)!=null&&v.length))return{type:"error",kind:"MISSING_PAYLOAD",message:"No payload present in server-intent"};let m=f.payloads[0];switch(m==null?void 0:m.intentCode){case"xfer-full":return r="full",i=[],n="full",j;case"xfer-changes":return r="changes",i=[],n="partial",j;case"none":return r="changes",i=[],n="partial",u(m);default:return t==null||t.warn(`Unable to process intent code '${m==null?void 0:m.intentCode}'.`),j}}function c(f){if(r==="inactive")return t==null||t.warn("Received put-object before server-intent was established. Ignoring."),j;if(!f.kind||!f.key||ie(f.version)||!f.object)return t==null||t.warn(`Ignoring put-object with missing fields: kind=${f.kind}, key=${f.key}, version=${f.version}`),j;let v=a(f.kind,f.object);return v?(i.push({kind:f.kind,key:f.key,version:f.version,object:v}),j):(t==null||t.warn(`Unable to process object for kind: '${f.kind}'`),j)}function h(f){return r==="inactive"?(t==null||t.warn("Received delete-object before server-intent was established. Ignoring."),j):!f.kind||!f.key||ie(f.version)?(t==null||t.warn(`Ignoring delete-object with missing fields: kind=${f.kind}, key=${f.key}, version=${f.version}`),j):(i.push({kind:f.kind,key:f.key,version:f.version,deleted:!0}),j)}function g(f){if(r==="inactive")return{type:"error",kind:"PROTOCOL_ERROR",message:"A payload transferred has been received without an intent having been established."};if(ie(f.state)||ie(f.version))return t==null||t.warn(`Ignoring payload-transferred with missing fields: state=${f.state}, version=${f.version}`),s(),j;let v={type:"payload",payload:{version:f.version,state:f.state,type:n,updates:i}};return o(),v}function y(f){return t==null||t.info(`Goodbye was received from the LaunchDarkly connection with reason: ${f.reason}.`),s(),{type:"goodbye",reason:f.reason}}function C(f){return t==null||t.info(`An issue was encountered receiving updates with reason: ${f.reason}.`),l(),{type:"serverError",id:f.payload_id,reason:f.reason}}return{get state(){return r},processEvent(f){switch(f.event){case"server-intent":return d(f.data);case"put-object":return c(f.data);case"delete-object":return h(f.data);case"payload-transferred":return g(f.data);case"goodbye":return y(f.data);case"error":return C(f.data);case"heart-beat":return j;default:return{type:"error",kind:"UNKNOWN_EVENT",message:`Received an unknown event of type '${f.event}'`}}},reset(){s()}}}function oa(e){return e==="MISSING_PAYLOAD"||e==="PROTOCOL_ERROR"}var Qr=class{constructor(e,t,r){this.m=t,this.t=r,this.n=[],this.yn=Yr(e,r)}addPayloadListener(e){this.n.push(e)}removePayloadListener(e){let t=this.n.indexOf(e,0);t>-1&&this.n.splice(t,1)}processEvents(e){e.forEach(t=>{var r,n;let i=this.yn.processEvent(t);switch(i.type){case"payload":this.n.forEach(a=>a(i.payload));break;case"error":oa(i.kind)?(r=this.m)==null||r.call(this,T.InvalidData,i.message):(n=this.t)==null||n.warn(i.message);break}})}},la=class{constructor(e,t,r,n){this.m=r,this.t=n,this._(e,"server-intent"),this._(e,"put-object"),this._(e,"delete-object"),this._(e,"payload-transferred"),this._(e,"goodbye"),this._(e,"error"),this.xt=new Qr(t,r,n)}addPayloadListener(e){this.xt.addPayloadListener(e)}removePayloadListener(e){this.xt.removePayloadListener(e)}_(e,t){e.addEventListener(t,async r=>{var n,i,a,s,o;if(r!=null&&r.data){(n=this.t)==null||n.debug(`Received ${t} event. Data is ${r.data}`);try{this.xt.processEvents([{event:t,data:JSON.parse(r.data)}])}catch(l){(i=this.t)==null||i.error(`Stream received data that was unable to be processed in "${t}" message`),(a=this.t)==null||a.debug(`Data follows: ${r.data}`),(s=this.m)==null||s.call(this,T.InvalidData,"Malformed data in EventStream.")}}else(o=this.m)==null||o.call(this,T.Unknown,"Event from EventStream missing data.")})}};function ua(e){if(e){let t=Object.keys(e).find(r=>r.toLowerCase()==="x-ld-envid");if(t)return{environmentId:e[t]}}}var ar="unknown plugin";function Je(e,t){try{return t.getMetadata().name||ar}catch(r){return e.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),ar}}function ca(e,t,r){let n=[];return r.forEach(i=>{var a;try{let s=(a=i.getHooks)==null?void 0:a.call(i,t);s===void 0?e.error(`Plugin ${Je(e,i)} returned undefined from getHooks.`):s&&s.length>0&&n.push(...s)}catch(s){e.error(`Exception thrown getting hooks for plugin ${Je(e,i)}. Unable to get hooks.`)}}),n}function da(e,t,r,n){n.forEach(i=>{try{i.register(r,t)}catch(a){e.error(`Exception thrown registering plugin ${Je(e,i)}.`)}})}var K=Object.freeze({__proto__:null,ClientMessages:Gr,DiagnosticsManager:Gi,ErrorKinds:_i,EventFactoryBase:aa,EventProcessor:na,FDv1PayloadAdaptor:sa,InputCustomEvent:Wr,InputEvalEvent:bt,InputIdentifyEvent:Zr,NullEventProcessor:ia,PayloadProcessor:Qr,PayloadStreamReader:la,canonicalize:Ue,createProtocolHandler:Yr,initMetadataFromHeaders:ua,isLegacyUser:Fr,isMultiKind:Mr,isSingleKind:Tr,safeGetHooks:ca,safeGetName:Je,safeRegisterPlugins:da,shouldSample:je}),sr={Initializing:"INITIALIZING",Valid:"VALID",Interrupted:"INTERRUPTED",SetOffline:"SET_OFFLINE",Closed:"CLOSED"};function ha(e){return e>=200&&e<=299}var or=class extends Error{constructor(e,t){super(e),this.status=t,this.name="LaunchDarklyRequestError"}};function kt(e,t,r,n,i,a,s,o,l,u){let d,c="GET",h=E({},a);l&&(c="REPORT",h["content-type"]="application/json",d=e);let g=l?r.pathReport(i,e):r.pathGet(i,e),y=[...s!=null?s:[]];o&&y.push({key:"withReasons",value:"true"}),u&&y.push({key:"h",value:u});let C=qr(t,g,y);return{async requestPayload(){let f;try{let v=await n.fetch(C,{method:c,headers:h,body:d});if(ha(v.status))return await v.text();f=v.status}catch(v){throw new or(v==null?void 0:v.message)}throw new or(`Unexpected status code: ${f}`,f)}}}var lr=new Error("Task has already been executed or shed. This is likely an implementation error. The task will not be executed again.");function fa(e,t,r=!1){let n,i=new Promise(o=>{n=(l,u)=>{var d;try{(d=e.after)==null||d.call(e,l,u)}catch(c){t==null||t.error(`Error in after callback: ${c}`)}o(l)}}),a=e.before?e.before():Promise.resolve(void 0),s=!1;return{execute:()=>{s&&(t==null||t.error(lr)),s=!0,a.then(o=>{e.execute(o).then(l=>n({status:"complete",result:l},o)).catch(l=>n({status:"error",error:l},o))}).catch(o=>{t==null||t.error(o),n({status:"error",error:o},void 0)})},shed:()=>{s&&(t==null||t.error(lr)),s=!0,a.then(o=>{n({status:"shed"},o)})},promise:i,sheddable:r}}function ga(e){let t,r=[];function n(){if(!t&&r.length>0){let i=r.shift();t=i.promise.finally(()=>{t=void 0,n()}),i.execute()}}return{execute(i,a=!1){var s,o;let l=fa(i,e,a);return t?((s=r[r.length-1])!=null&&s.sheddable&&((o=r.pop())==null||o.shed()),r.push(l)):(t=l.promise.finally(()=>{t=void 0,n()}),l.execute()),l.promise},pendingCount(){return r.length}}}function Xr(e){return"validate"in e}function _e(e,t,r,n,i){let a=E({},r);return ie(e)?a:p.Object.is(e)?(Object.entries(e).forEach(([s,o])=>{let l=t[s],u=i?`${i}.${s}`:s;if(!l){n==null||n.warn(F.unknownOption(u));return}if(ie(o))return;if(Xr(l)){let c=l.validate(o,u,n,r[s]);c!==void 0&&(a[s]=c.value);return}if(l.is(o)){a[s]=o;return}let d=l.getType();d==="boolean"?(n==null||n.warn(F.wrongOptionTypeBoolean(u,typeof o)),a[s]=!!o):d==="boolean | undefined | null"?(n==null||n.warn(F.wrongOptionTypeBoolean(u,typeof o)),typeof o!="boolean"&&typeof o!="undefined"&&o!==null&&(a[s]=!!o)):l instanceof $r&&p.Number.is(o)?(n==null||n.warn(F.optionBelowMinimum(u,o,l.min)),a[s]=l.min):n==null||n.warn(F.wrongOptionType(u,d,typeof o))}),a):(n==null||n.warn(F.wrongOptionType(i!=null?i:"config","object",typeof e)),a)}function se(e,t){var r;let n=t==null?void 0:t.defaults;return{is:(r=t==null?void 0:t.is)!=null?r:(i=>p.Object.is(i)),getType:()=>"object",validate(i,a,s,o){if(!p.Object.is(i)){s==null||s.warn(F.wrongOptionType(a,"object",typeof i));return}let l=n!=null?n:p.Object.is(o)?o:{},u=_e(i,e,l,s,a);return Object.keys(u).length>0?{value:u}:void 0}}}function en(e,t){return{is:r=>Array.isArray(r),getType:()=>"array",validate(r,n,i){if(!Array.isArray(r)){i==null||i.warn(F.wrongOptionType(n,"array",typeof r));return}let a=[];return r.forEach((s,o)=>{let l=`${n}[${o}]`;if(ie(s)||!p.Object.is(s)){i==null||i.warn(F.wrongOptionType(l,"object",typeof s));return}let u=s,d=u[e],c=typeof d=="string"?t[d]:void 0;if(!c){let h=Object.keys(t).join(" | "),g=typeof d=="string"?d:typeof d;i==null||i.warn(F.wrongOptionType(`${l}.${e}`,h,g));return}a.push(_e(u,c,{},i,l))}),{value:a}}}}function pa(...e){return{is:t=>e.some(r=>r.is(t)),getType:()=>e.map(t=>t.getType()).join(" | "),validate(t,r,n,i){let a=e.find(s=>s.is(t));if(a)return Xr(a)?a.validate(t,r,n,i):{value:t};n==null||n.warn(F.wrongOptionType(r,this.getType(),typeof t))}}}function va(e,t,r){let n=r==null?void 0:r.defaults;return{is:i=>p.Object.is(i),getType:()=>"object",validate(i,a,s,o){if(ie(i))return;if(!p.Object.is(i)){s==null||s.warn(F.wrongOptionType(a,"object",typeof i));return}let l=i,u={},d={};Object.keys(l).forEach(h=>{e.is(h)?(u[h]=l[h],d[h]=t):s==null||s.warn(F.wrongOptionType(a,e.getType(),h))});let c=n!=null?n:p.Object.is(o)?o:{};return{value:_e(u,d,c,s,a)}}}}var ur=300,cr=3600,Lt=p.oneOf("cache","polling","streaming"),Tt=p.oneOf("streaming","polling","offline","one-shot","background"),Mt={pollingBaseUri:p.String,streamingBaseUri:p.String},ma={type:Lt},tn={type:Lt,pollInterval:p.numberWithMin(30),endpoints:se(Mt)},rn={type:Lt,initialReconnectDelay:p.numberWithMin(1),endpoints:se(Mt)},ya=en("type",{cache:ma,polling:tn,streaming:rn}),wa=en("type",{polling:tn,streaming:rn}),ba={pollInterval:p.numberWithMin(30),endpoints:se(Mt)},ka={initializers:ya,synchronizers:wa,fdv1Fallback:se(ba)},Ve={streaming:{initializers:[{type:"cache"},{type:"polling"}],synchronizers:[{type:"streaming"},{type:"polling"}],fdv1Fallback:{pollInterval:ur}},polling:{initializers:[{type:"cache"}],synchronizers:[{type:"polling"}],fdv1Fallback:{pollInterval:ur}},offline:{initializers:[{type:"cache"}],synchronizers:[]},"one-shot":{initializers:[{type:"cache"},{type:"polling"},{type:"streaming"}],synchronizers:[]},background:{initializers:[{type:"cache"}],synchronizers:[{type:"polling",pollInterval:cr}],fdv1Fallback:{pollInterval:cr}}},Ea=va(Tt,se(ka));function dr(e,t){return p.Object.is(e)&&e.type===t}var Da={type:p.oneOf("automatic"),lifecycle:p.Boolean,network:p.Boolean},Ca={type:p.oneOf("manual"),initialConnectionMode:Tt},xa={backgroundConnectionMode:Tt,automaticModeSwitching:pa(p.Boolean,se(Da,{is:e=>dr(e,"automatic")}),se(Ca,{is:e=>dr(e,"manual")})),connectionModes:Ea},hr={foregroundConnectionMode:"one-shot",backgroundConnectionMode:void 0,automaticModeSwitching:!1};function Sa(e){return typeof e=="object"&&e!==null&&"type"in e&&e.type==="manual"}function Ra(e,t){var r;return Sa(e.automaticModeSwitching)?e.automaticModeSwitching.initialConnectionMode:(r=e.foregroundConnectionMode)!=null?r:t.foregroundConnectionMode}function Ia(e){return{logger:p.Object,maxCachedContexts:p.numberWithMin(0),baseUri:p.String,streamUri:p.String,eventsUri:p.String,capacity:p.numberWithMin(1),diagnosticRecordingInterval:p.numberWithMin(2),flushInterval:p.numberWithMin(2),streamInitialReconnectDelay:p.numberWithMin(0),allAttributesPrivate:p.Boolean,debug:p.Boolean,diagnosticOptOut:p.Boolean,withReasons:p.Boolean,sendEvents:p.Boolean,pollInterval:p.numberWithMin(30),useReport:p.Boolean,privateAttributes:p.StringArray,disableCache:p.Boolean,applicationInfo:p.Object,wrapperName:p.String,wrapperVersion:p.String,payloadFilterKey:p.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:p.createTypeArray("Hook[]",{}),inspectors:p.createTypeArray("LDInspection",{}),cleanOldPersistentData:p.Boolean,dataSystem:e!=null&&e.dataSystemDefaults?se(xa,{defaults:V(E({},e.dataSystemDefaults),{connectionModes:Ve})}):p.Object}}var Oa=300,nn="https://clientsdk.launchdarkly.com",an="https://clientstream.launchdarkly.com";function Pa(e){return e instanceof jr?e:Vr(e)}var $a=class{constructor(e={},t={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var r,n,i;this.logger=Vr(),this.baseUri=nn,this.eventsUri=be.DEFAULT_EVENTS,this.streamUri=an,this.maxCachedContexts=5,this.disableCache=!1,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=Oa,this.hooks=[],this.inspectors=[],this.logger=Pa(e.logger);let a=Ia({dataSystemDefaults:t.dataSystemDefaults}),s=_e(e,a,{},this.logger);Object.entries(s).forEach(([o,l])=>{o!=="logger"&&(this[o]=l)}),this.serviceEndpoints=new be(this.streamUri,this.baseUri,this.eventsUri,t.analyticsEventPath,t.diagnosticEventPath,t.includeAuthorizationHeader,e.payloadFilterKey),this.useReport=(r=e.useReport)!=null?r:!1,this.tags=new Ui({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(n=t.userAgentHeaderName)!=null?n:"user-agent",this.trackEventModifier=(i=t.trackEventModifier)!=null?i:(o=>o),this.credentialType=t.credentialType,this.getImplementationHooks=t.getImplementationHooks}};async function Ft(e,t){if(e.digest)return e.digest(t);if(e.asyncDigest)return e.asyncDigest(t);throw new Error("Platform must implement digest or asyncDigest")}var sn=async(e,{crypto:t,storage:r})=>{let n=await(r==null?void 0:r.get(e));return n||(n=t.randomUUID(),await(r==null?void 0:r.set(e,n))),n};function on(e){return async t=>Ft(e.createHash("sha256").update(t),"base64")}var Q=async e=>e;async function Oe(e){return(await Promise.all(e.map(t=>t.transform(t.value)))).join("_")}async function ln(e,t){return Oe([{value:"LaunchDarkly",transform:Q},{value:t,transform:on(e)}])}async function La(e){return Oe([{value:"LaunchDarkly",transform:Q},{value:"AnonymousKeys",transform:Q},{value:e,transform:Q}])}async function Ta(e){return Oe([{value:"LaunchDarkly",transform:Q},{value:"ContextKeys",transform:Q},{value:e,transform:Q}])}async function Ma(e){return Oe([{value:e,transform:Q},{value:"ContextIndex",transform:Q}])}async function Nt(e,t,r){return Oe([{value:t,transform:Q},{value:r.canonicalKey,transform:on(e)}])}var{isLegacyUser:Fa,isSingleKind:ct,isMultiKind:fr}=K,un="1.0",Na=e=>{let t=e,{kind:r}=t,n=St(t,["kind"]);return{kind:"multi",[r]:n}},Aa=async({crypto:e,info:t},{applicationInfo:r})=>{var n;let{ld_application:i}=t.platformData(),a=(n=Ot(i))!=null?n:{},s=(r==null?void 0:r.id)||(a==null?void 0:a.id);if(s){let o=(r==null?void 0:r.version)||(a==null?void 0:a.version),l=(r==null?void 0:r.name)||(a==null?void 0:a.name),u=(r==null?void 0:r.versionName)||(a==null?void 0:a.versionName);return a=E(E(E(V(E({},a),{id:s}),o?{version:o}:{}),l?{name:l}:{}),u?{versionName:u}:{}),a.key=await Ft(e.createHash("sha256").update(s),"base64"),a.envAttributesVersion=a.envAttributesVersion||un,a}},ja=async e=>{var t,r,n,i;let{ld_device:a,os:s}=e.info.platformData(),o=(t=Ot(a))!=null?t:{},l=(s==null?void 0:s.name)||((r=o.os)==null?void 0:r.name),u=(s==null?void 0:s.version)||((n=o.os)==null?void 0:n.version),d=(i=o.os)==null?void 0:i.family;if((l||u||d)&&(o.os=E(E(E({},l?{name:l}:{}),u?{version:u}:{}),d?{family:d}:{})),Object.keys(o).filter(c=>c!=="key"&&c!=="envAttributesVersion").length){let c=await Ta("ld_device");return o.key=await sn(c,e),o.envAttributesVersion=o.envAttributesVersion||un,o}},Va=async(e,t,r)=>{if(Fa(e))return e;let n,i;if(ct(e)&&e.kind!=="ld_application"||fr(e)&&!e.ld_application?n=await Aa(t,r):r.logger.warn("Not adding ld_application environment attributes because it already exists."),ct(e)&&e.kind!=="ld_device"||fr(e)&&!e.ld_device?i=await ja(t):r.logger.warn("Not adding ld_device environment attributes because it already exists."),n||i){let a=ct(e)?Na(e):e;return E(E(E({},a),n?{ld_application:n}:{}),i?{ld_device:i}:{})}return e};function za(){let e,t;return{set(r,n){e=r,t=n},getContext(){return t},getUnwrappedContext(){return e},newIdentificationPromise(){let r,n;return{identifyPromise:new Promise((i,a)=>{r=i,n=a}),identifyResolve:r,identifyReject:n}},hasContext(){return t!==void 0},hasValidContext(){return this.hasContext()&&t.valid}}}var{isLegacyUser:Ua,isMultiKind:qa,isSingleKind:Ka}=K,At=async(e,t,r)=>{let{anonymous:n,key:i}=t;if(n&&!i){let a=await La(e);t.key=await sn(a,r)}},Ba=async(e,t)=>{await At(e.kind,e,t)},Ha=async(e,t)=>{let r=e,{kind:n}=r,i=St(r,["kind"]);return Promise.all(Object.entries(i).map(([a,s])=>At(a,s,t)))},Ja=async(e,t)=>{await At("user",e,t)},Ga=async(e,t)=>{let r=Jr(e);return Ka(r)&&await Ba(r,t),qa(r)&&await Ha(r,t),Ua(r)&&await Ja(r,t),r},_a=e=>({customBaseURI:e.serviceEndpoints.polling!==nn,customStreamURI:e.serviceEndpoints.streaming!==an,customEventsURI:e.serviceEndpoints.events!==be.DEFAULT_EVENTS,eventsCapacity:e.capacity,eventsFlushIntervalMillis:ut(e.flushInterval),reconnectTimeMillis:ut(e.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:ut(e.diagnosticRecordingInterval),allAttributesPrivate:e.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Wa=(e,t,r)=>{if(t.sendEvents&&!t.diagnosticOptOut)return new K.DiagnosticsManager(e,r,_a(t))};function gr(e,t){return{value:t!=null?t:null,variationIndex:null,reason:{kind:"ERROR",errorKind:e}}}function pr(e,t,r){return E({value:e,variationIndex:t!=null?t:null},r!==void 0&&{reason:r})}var Za=(e,t,r,n,i)=>{if(t.sendEvents)return new K.EventProcessor(V(E({},t),{eventsCapacity:t.capacity}),new qi(e,t,r),n,void 0,i,!1,!0)},vr=class extends K.EventFactoryBase{evalEventClient(e,t,r,n,i,a){let{trackEvents:s,debugEventsUntilDate:o,trackReason:l,flagVersion:u,version:d,variation:c}=n;return super.evalEvent({addExperimentData:l,context:i,debugEventsUntilDate:o,defaultVal:r,flagKey:e,reason:a,trackEvents:!!s,value:t,variation:c,version:u!=null?u:d})}};function cn(e,t){let r=Object.keys(t),n="$flagsState",i="$valid",a=t[n];!a&&r.length&&e.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),t[i]===!1&&e.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");let s={};return r.forEach(o=>{if(o!==n&&o!==i){let l;a&&a[o]?l=E({value:t[o]},a[o]):l={value:t[o],version:0},s[o]={version:l.version,flag:l}}}),s}var Et="_freshness";async function dn(e,t){let r=t.canonicalUnfilteredJson();if(r)return Ft(e.createHash("sha256").update(r),"base64")}async function Ya(e,t,r,n,i){let a=await Nt(t,r,n),s=await e.get(`${a}${Et}`);if(s!=null)try{let o=JSON.parse(s),l=await dn(t,n);return l===void 0||o.contextHash!==l?void 0:typeof o.timestamp=="number"&&!Number.isNaN(o.timestamp)?o.timestamp:void 0}catch(o){i==null||i.warn(`Could not read freshness data from persistent storage: ${o.message}`);return}}function Qa(e){return e!==null&&typeof e=="object"&&typeof e.version=="number"}async function hn(e,t,r,n,i){let a=await Nt(t,r,n),s=await e.get(a),o=!1;if(s==null){if(s=await e.get(n.canonicalKey),s==null)return;o=!0}try{let l=JSON.parse(s);if(l===null||typeof l!="object"){i==null||i.warn("Cached flag data is not a valid object");return}let u=Object.entries(l),d=u.find(([,c])=>!Qa(c));if(d){i==null||i.warn(`Discarding cached flags due to invalid entry: ${d[0]}`);return}return{flags:u.reduce((c,[h,g])=>(c[h]=g,c),{}),storageKey:a,fromLegacyKey:o}}catch(l){i==null||i.warn(`Could not parse cached flag evaluations from persistent storage: ${l.message}`);return}}var dt=class fn{constructor(){this.container={index:new Array}}static fromJson(t){let r=new fn;try{r.container=JSON.parse(t)}catch(n){}return r}toJson(){return JSON.stringify(this.container)}notice(t,r){let n=this.container.index.find(i=>i.id===t);n===void 0?this.container.index.push({id:t,timestamp:r}):n.timestamp=r}prune(t){let r=Math.max(t,0);return this.container.index.length>r?(this.container.index.sort((n,i)=>n.timestamp-i.timestamp),this.container.index.splice(0,this.container.index.length-r)):[]}},Xa=class{constructor(e,t,r,n,i,a,s,o=()=>Date.now()){this.a=e,this.Lt=t,this.ct=r,this.ge=n,this.A=i,this.g=a,this.t=s,this.gn=o,this.ve=Ma(this.Lt)}async init(e,t){this.g.init(e,t),await this.Ot(e)}async upsert(e,t,r){return this.g.upsert(e,t,r)?(await this.Ot(e),!0):!1}async applyChanges(e,t,r){this.g.applyChanges(e,t,r),await this.Ot(e)}async loadCached(e){if(this.ge||this.ct<=0||!this.a.storage)return!1;let t=await hn(this.a.storage,this.a.crypto,this.Lt,e,this.t);if(!t)return!1;t.fromLegacyKey&&(await this.a.storage.set(t.storageKey,JSON.stringify(t.flags)),await this.a.storage.clear(e.canonicalKey));let r=Object.entries(t.flags).reduce((n,[i,a])=>(n[i]={version:a.version,flag:a},n),{});return this.g.initCached(e,r),this.t.debug("Loaded cached flag evaluations from persistent storage"),!0}async vn(e,t,r){var n;let i=await dn(this.a.crypto,t);if(i===void 0){this.t.error("Could not serialize context for freshness tracking");return}let a={timestamp:r,contextHash:i};await((n=this.a.storage)==null?void 0:n.set(`${e}${Et}`,JSON.stringify(a)))}async wn(){var e;if(this.V!==void 0)return this.V;let t=await((e=this.a.storage)==null?void 0:e.get(await this.ve));if(!t)return this.V=new dt,this.V;try{this.V=dt.fromJson(t),this.t.debug("Loaded context index from persistent storage")}catch(r){this.t.warn(`Could not load index from persistent storage: ${r.message}`),this.V=new dt}return this.V}async Ot(e){var t,r;if(this.ge)return;let n=this.gn(),i=await this.wn(),a=await Nt(this.a.crypto,this.Lt,e);this.ct>0&&i.notice(a,n);let s=i.prune(this.ct),o=this.ct<=0||s.some(c=>c.id===a);if(await Promise.all(s.flatMap(c=>{var h,g;return[(h=this.a.storage)==null?void 0:h.clear(c.id),(g=this.a.storage)==null?void 0:g.clear(`${c.id}${Et}`)]})),await((t=this.a.storage)==null?void 0:t.set(await this.ve,i.toJson())),o)return;let l=this.A.getAll(),u=Object.entries(l).reduce((c,[h,g])=>(g.flag!==null&&g.flag!==void 0&&(c[h]=g.flag),c),{}),d=JSON.stringify(u);await((r=this.a.storage)==null?void 0:r.set(a,d));try{await this.vn(a,e,n)}catch(c){this.t.warn(`Failed to store freshness data: ${c.message}`)}}};function es(){let e={};return{init(t){e=Object.entries(t).reduce((r,[n,i])=>(r[n]=i,r),{})},insertOrUpdate(t,r){e[t]=r},get(t){if(Object.prototype.hasOwnProperty.call(e,t))return e[t]},getAll(){return e},applyChanges(t,r){r==="full"?this.init(t):r==="partial"&&Object.entries(t).forEach(([n,i])=>{e[n]=i})}}}function mr(e,t){let r=[];return Object.entries(e).forEach(([n,i])=>{let a=t[n];(!a||!Ae(i,a))&&r.push(n)}),Object.keys(t).forEach(n=>{e[n]||r.push(n)}),r}function ts(e,t){let r=e,n=t,i,a=new Array;return{handleFlagChanges(s,o){i?a.forEach(l=>{try{l(i,s,o)}catch(u){}}):n.warn("Received a change event without an active context. Changes will not be propagated.")},init(s,o){i=s;let l=r.getAll();r.init(o);let u=mr(l,o);u.length>0&&this.handleFlagChanges(u,"init")},initCached(s,o){(i==null?void 0:i.canonicalKey)!==s.canonicalKey&&this.init(s,o)},applyChanges(s,o,l){i=s;let u=r.getAll();if(r.applyChanges(o,l),l==="full"){let d=mr(u,o);d.length>0&&this.handleFlagChanges(d,"init")}else if(l==="partial"){let d=Object.keys(o);d.length>0&&this.handleFlagChanges(d,"patch")}},upsert(s,o,l){if((i==null?void 0:i.canonicalKey)!==s.canonicalKey)return n.warn("Received an update for an inactive context."),!1;let u=r.get(o);return u!==void 0&&u.version>=l.version?!1:(r.insertOrUpdate(o,l),this.handleFlagChanges([o],"patch"),!0)},on(s){a.push(s)},off(s){let o=a.indexOf(s);o>-1&&a.splice(o,1)}}}var rs=class{constructor(e,t,r,n,i,a=()=>Date.now()){this.A=es(),this.g=ts(this.A,i),this.ut=this.En(e,t,r,n,i,a)}async En(e,t,r,n,i,a=()=>Date.now()){let s=await ln(e.crypto,t);return new Xa(e,s,r,n,this.A,this.g,i,a)}get(e){return this.r&&Object.prototype.hasOwnProperty.call(this.r,e)?this.At(this.r[e]):this.A.get(e)}getAll(){return this.r?E(E({},this.A.getAll()),Object.entries(this.r).reduce((e,[t,r])=>(e[t]=this.At(r),e),{})):this.A.getAll()}presetFlags(e){this.A.init(e)}setBootstrap(e,t){this.g.init(e,t)}async init(e,t){return(await this.ut).init(e,t)}async upsert(e,t,r){return(await this.ut).upsert(e,t,r)}async loadCached(e){return(await this.ut).loadCached(e)}async applyChanges(e,t,r){return(await this.ut).applyChanges(e,t,r)}on(e){this.g.on(e)}off(e){this.g.off(e)}At(e){return{flag:{value:e,version:0},version:0}}setOverride(e,t){this.r||(this.r={}),this.r[e]=t,this.g.handleFlagChanges([e],"override")}removeOverride(e){!this.r||!Object.prototype.hasOwnProperty.call(this.r,e)||(delete this.r[e],Object.keys(this.r).length===0&&(this.r=void 0),this.g.handleFlagChanges([e],"override"))}clearAllOverrides(){if(this.r){let e=E({},this.r);this.r=void 0,this.g.handleFlagChanges(Object.keys(e),"override")}}getAllOverrides(){if(!this.r)return{};let e={};return Object.entries(this.r).forEach(([t,r])=>{e[t]=this.At(r)}),e}getDebugOverride(){return{setOverride:this.setOverride.bind(this),removeOverride:this.removeOverride.bind(this),clearAllOverrides:this.clearAllOverrides.bind(this),getAllOverrides:this.getAllOverrides.bind(this)}}},yr="unknown hook",gn="beforeEvaluation",pn="afterEvaluation",ns="afterTrack";function Pe(e,t,r,n,i){try{return n()}catch(a){return e==null||e.error(`An error was encountered in "${t}" of the "${r}" hook: ${a}`),i}}function $e(e,t){try{return t.getMetadata().name||yr}catch(r){return e.error("Exception thrown getting metadata for hook. Unable to get hook name."),yr}}function is(e,t,r){return t.map(n=>Pe(e,gn,$e(e,n),()=>{var i,a;return(a=(i=n==null?void 0:n.beforeEvaluation)==null?void 0:i.call(n,r,{}))!=null?a:{}},{}))}function as(e,t,r,n,i){for(let a=t.length-1;a>=0;a-=1){let s=t[a],o=n[a];Pe(e,pn,$e(e,s),()=>{var l,u;return(u=(l=s==null?void 0:s.afterEvaluation)==null?void 0:l.call(s,r,o,i))!=null?u:{}},{})}}function ss(e,t,r){return t.map(n=>Pe(e,gn,$e(e,n),()=>{var i,a;return(a=(i=n==null?void 0:n.beforeIdentify)==null?void 0:i.call(n,r,{}))!=null?a:{}},{}))}function os(e,t,r,n,i){for(let a=t.length-1;a>=0;a-=1){let s=t[a],o=n[a];Pe(e,pn,$e(e,s),()=>{var l,u;return(u=(l=s==null?void 0:s.afterIdentify)==null?void 0:l.call(s,r,o,i))!=null?u:{}},{})}}function ls(e,t,r){for(let n=t.length-1;n>=0;n-=1){let i=t[n];Pe(e,ns,$e(e,i),()=>{var a;return(a=i==null?void 0:i.afterTrack)==null?void 0:a.call(i,r)},void 0)}}var us=class{constructor(e,t){this.t=e,this.F=[],this.F.push(...t)}withEvaluation(e,t,r,n){if(this.F.length===0)return n();let i=[...this.F],a={flagKey:e,context:t,defaultValue:r},s=is(this.t,i,a),o=n();return as(this.t,i,a,s,o),o}identify(e,t){let r=[...this.F],n={context:e,timeout:t},i=ss(this.t,r,n);return a=>{os(this.t,r,n,i,a)}}addHook(e){this.F.push(e)}afterTrack(e){if(this.F.length===0)return;let t=[...this.F];ls(this.t,t,e)}};function cs(e){return{getMetadata(){return{name:"LaunchDarkly-Inspector-Adapter"}},afterEvaluation:(t,r,n)=>(e.onFlagUsed(t.flagKey,n,t.context),r),afterIdentify(t,r,n){return e.onIdentityChanged(t.context),r}}}function ds(e,t){return`an inspector: "${t}" of an invalid type (${e}) was configured`}function hs(e,t){return`an inspector: "${t}" of type: "${e}" generated an exception`}function fs(e,t){let r=!1,n={method:(...i)=>{try{e.method(...i)}catch(a){r||(r=!0,t.warn(hs(n.type,n.name)))}},type:e.type,name:e.name,synchronous:e.synchronous};return n}var vn="flag-used",mn="flag-details-changed",yn="flag-detail-changed",wn="client-identity-changed",gs=[vn,mn,yn,wn];function ps(e,t){let r=gs.includes(e.type)&&e.method&&typeof e.method=="function";return r||t.warn(ds(e.type,e.name)),r}var vs=class{constructor(e,t){this.B=[];let r=e.filter(n=>ps(n,t));this.B=r.map(n=>fs(n,t))}hasInspectors(){return this.B.length!==0}onFlagUsed(e,t,r){this.B.forEach(n=>{n.type===vn&&n.method(e,t,r)})}onFlagsChanged(e){this.B.forEach(t=>{t.type===mn&&t.method(e)})}onFlagChanged(e,t){this.B.forEach(r=>{r.type===yn&&r.method(e,t)})}onIdentityChanged(e){this.B.forEach(t=>{t.type===wn&&t.method(e)})}},ms=class{constructor(e){this.t=e,this.n=new Map}on(e,t){var r,n;if(typeof e!="string"){(r=this.t)==null||r.warn("Only string event names are supported.");return}this.n.has(e)?(n=this.n.get(e))==null||n.push(t):this.n.set(e,[t])}off(e,t){let r=this.n.get(e);if(r){if(t){let n=r.filter(i=>i!==t);n.length===0?this.n.delete(e):this.n.set(e,n);return}this.n.delete(e)}}bn(e,t,...r){var n;try{e(...r)}catch(i){(n=this.t)==null||n.error(`Encountered error invoking handler for "${t}", detail: "${i}"`)}}emit(e,...t){let r=this.n.get(e);r==null||r.forEach(n=>this.bn(n,e,...t))}eventNames(){return[...this.n.keys()]}listenerCount(e){var t,r;return(r=(t=this.n.get(e))==null?void 0:t.length)!=null?r:0}};function ys(e,t,r){let n=t.info.sdkData(),i;r.applicationInfo&&(r.applicationInfo.id&&(i=i!=null?i:{},i.id=r.applicationInfo.id),r.applicationInfo.version&&(i=i!=null?i:{},i.version=r.applicationInfo.version),r.applicationInfo.name&&(i=i!=null?i:{},i.name=r.applicationInfo.name),r.applicationInfo.versionName&&(i=i!=null?i:{},i.versionName=r.applicationInfo.versionName));let a={name:n.userAgentBase,version:n.version};n.wrapperName&&(a.wrapperName=n.wrapperName),n.wrapperVersion&&(a.wrapperVersion=n.wrapperVersion);let s={sdk:a,[r.credentialType]:e};return i&&(s.application=i),s}var{ClientMessages:wr,ErrorKinds:br}=K,ws=5,bs=class{constructor(e,t,r,n,i,a){var s,o;if(this.sdkKey=e,this.autoEnvAttributes=t,this.platform=r,this.u=za(),this.Tt=15,this.T=new vr(!1),this.lt=new vr(!0),this.Mt=!1,this.Dn=ga(),this.we=!1,!e)throw new Error("You must configure the client with a client-side SDK key");if(!r.encoding)throw new Error("Platform must implement Encoding because btoa is required.");this.e=new $a(n,a),this.logger=this.e.logger,this.we=(s=a==null?void 0:a.requiresStart)!=null?s:!1,this.initialContext=a==null?void 0:a.initialContext,this.Ee=Ji(this.sdkKey,this.platform.info,this.e.tags,this.e.serviceEndpoints.includeAuthorizationHeader,this.e.userAgentHeaderName),this.$=new rs(this.platform,e,this.e.maxCachedContexts,(o=this.e.disableCache)!=null?o:!1,this.e.logger),this.C=Wa(e,this.e,r),this.E=Za(e,this.e,r,this.Ee,this.C),this.emitter=new ms,this.emitter.on("error",(u,d)=>{this.logger.error(`error: ${d}, context: ${JSON.stringify(u)}`)}),this.$.on((u,d,c)=>{this.Sn(d,c);let h=de.toLDContext(u);this.emitter.emit("change",h,d),d.forEach(g=>{this.emitter.emit(`change:${g}`,h)})}),this.dataManager=i(this.$,this.e,this.Ee,this.emitter,this.C),this.isFDv2=!!this.e.dataSystem,this.dataSystemConfig=this.e.dataSystem;let l=[...this.e.hooks];if(this.environmentMetadata=ys(this.sdkKey,this.platform,this.e),this.e.getImplementationHooks(this.environmentMetadata).forEach(u=>{l.push(u)}),this.R=new us(this.logger,l),this.Y=new vs(this.e.inspectors,this.logger),this.Y.hasInspectors()&&this.R.addHook(cs(this.Y)),n.cleanOldPersistentData&&a!=null&&a.getLegacyStorageKeys&&this.platform.storage)try{this.logger.debug("Cleaning old persistent data."),Promise.all(a.getLegacyStorageKeys().map(u=>{var d;return(d=this.platform.storage)==null?void 0:d.clear(u)})).catch(u=>{this.logger.error(`Error cleaning old persistent data: ${u}`)}).finally(()=>{this.logger.debug("Cleaned old persistent data.")})}catch(u){this.logger.error(`Error cleaning old persistent data: ${u}`)}}allFlags(){return Object.entries(this.$.getAll()).reduce((e,[t,r])=>(r.flag!==null&&r.flag!==void 0&&!r.flag.deleted&&(e[t]=r.flag.value),e),{})}async close(){var e;await this.flush(),(e=this.E)==null||e.close(),this.dataManager.close(),this.logger.debug("Closed event processor and data source.")}async flush(){var e;try{await((e=this.E)==null?void 0:e.flush()),this.logger.debug("Successfully flushed event processor.")}catch(t){return this.logger.error(`Error flushing event processor: ${t}.`),{error:t,result:!1}}return{result:!0}}getContext(){return this.u.hasContext()?Jr(this.u.getUnwrappedContext()):void 0}getInternalContext(){return this.u.getContext()}presetFlags(e){this.$.presetFlags(e)}start(e){var t,r;if(this.initializeResult)return Promise.resolve(this.initializeResult);if(this.startPromise)return this.startPromise;if(!this.initialContext)return this.logger.error("Initial context not set"),Promise.resolve({status:"failed",error:new Error("Initial context not set")});let n=V(E({},(t=e==null?void 0:e.identifyOptions)!=null?t:{}),{sheddable:!1});if(e!=null&&e.bootstrap&&!n.bootstrap&&(n.bootstrap=e.bootstrap),n.bootstrap)try{n.bootstrapParsed||(n.bootstrapParsed=cn(this.logger,n.bootstrap)),n.bootstrapParsed&&this.presetFlags(n.bootstrapParsed)}catch(i){this.logger.error("Failed to bootstrap data",i)}return this.initializedPromise||(this.initializedPromise=new Promise(i=>{this.initResolve=i})),this.startPromise=this.Ft(this.initializedPromise,(r=e==null?void 0:e.timeout)!=null?r:5,"start"),this.identifyResult(this.initialContext,n),this.startPromise}async identify(e,t){let r=await this.identifyResult(e,t);if(r.status==="error")throw r.error;if(r.status==="timeout"){let n=new Br(`identify timed out after ${r.timeout} seconds.`);throw this.logger.error(n.message),n}}async identifyResult(e,t){var r,n;if(this.we&&!this.startPromise)return this.logger.error("The client must be started before a context can be identified. Call start() prior to identifying a context."),{status:"error",error:new Error("Identify called before start")};let i=(r=t==null?void 0:t.timeout)!=null?r:ws,a=(t==null?void 0:t.timeout)===void 0&&(t==null?void 0:t.noTimeout)===!0;i>this.Tt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Tt} seconds. We recommend a timeout of less than ${this.Tt} seconds.`);let s=this.Dn.execute({before:async()=>{let l=await Ga(e,this.platform);this.autoEnvAttributes===Ke.Enabled&&(l=await Va(l,this.platform,this.e));let u=de.fromLDContext(l);if(u.valid){let d=this.R.identify(l,t==null?void 0:t.timeout);return{context:l,checkedContext:u,afterIdentify:d}}return{context:l,checkedContext:u}},execute:async l=>{var u;let{context:d,checkedContext:c}=l;if(!c.valid){let C=new Error("Context was unspecified or had no key");return this.emitter.emit("error",d,C),Promise.reject(C)}this.u.set(d,c),(u=this.E)==null||u.sendEvent(this.T.identifyEvent(c));let{identifyPromise:h,identifyResolve:g,identifyReject:y}=this.u.newIdentificationPromise();return this.logger.debug(`Identifying ${JSON.stringify(c)}`),await this.dataManager.identify(g,y,c,t),h},after:async(l,u)=>{var d,c,h;l.status==="complete"?(d=u==null?void 0:u.afterIdentify)==null||d.call(u,{status:"completed"}):l.status==="shed"?(c=u==null?void 0:u.afterIdentify)==null||c.call(u,{status:"shed"}):l.status==="error"&&((h=u==null?void 0:u.afterIdentify)==null||h.call(u,{status:"error"}))}},(n=t==null?void 0:t.sheddable)!=null?n:!1).then(l=>{if(l.status==="error"){let d={status:"error",error:l.error};return this.maybeSetInitializationResult({status:"failed",error:l.error}),d}if(l.status==="shed")return{status:"shed"};let u={status:"completed"};return this.maybeSetInitializationResult({status:"complete"}),u});if(a)return s;let o=new Promise(l=>{setTimeout(()=>{l({status:"timeout",timeout:i})},i*1e3)});return Promise.race([s,o])}maybeSetInitializationResult(e){this.initializeResult===void 0&&(this.initializeResult=e,this.emitter.emit("ready"),e.status==="complete"&&this.emitter.emit("initialized"),this.initResolve&&(this.initResolve(e),this.initResolve=void 0))}waitForInitialization(e){var t;let r=(t=e==null?void 0:e.timeout)!=null?t:5;return this.initializeResult?Promise.resolve(this.initializeResult):this.initializedPromise?this.Ft(this.initializedPromise,r):(this.initializedPromise||(this.initializedPromise=new Promise(n=>{this.initResolve=n})),this.Ft(this.initializedPromise,r))}Ft(e,t,r="waitForInitialization"){let n=Hr(t,r);return Promise.race([e.then(i=>(n.cancel(),i)),n.promise.then(()=>({status:"complete"})).catch(()=>({status:"timeout"}))]).catch(i=>{var a;return(a=this.logger)==null||a.error(i.message),{status:"failed",error:i}})}on(e,t){this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t)}track(e,t,r){var n,i;if(!this.u.hasValidContext()){this.logger.warn(wr.MissingContextKeyNoEvent);return}r!==void 0&&!p.Number.is(r)&&((n=this.logger)==null||n.warn(wr.invalidMetricValue(typeof r))),(i=this.E)==null||i.sendEvent(this.e.trackEventModifier(this.T.customEvent(e,this.u.getContext(),t,r))),this.R.afterTrack({key:e,context:this.u.getUnwrappedContext(),data:t,metricValue:r})}dt(e,t,r,n){var i,a,s,o,l;let u=this.u.hasContext();u||(i=this.logger)==null||i.warn("Flag evaluation called before client is fully initialized, data from this evaulation could be stale.");let d=this.u.getContext(),c=this.$.get(e);if(c===void 0||c.flag.deleted){let v=t!=null?t:null;return(a=this.logger)==null||a.warn(`Unknown feature flag "${e}"; returning default value ${v}.`),u&&((s=this.E)==null||s.sendEvent(this.T.unknownFlagEvent(e,v,d))),gr(br.FlagNotFound,t)}let{reason:h,value:g,variation:y,prerequisites:C}=c.flag;if(n){let[v,m]=n(g);if(!v){u&&((o=this.E)==null||o.sendEvent(r.evalEventClient(e,t,t,c.flag,d,h)));let R=new Ki(`Wrong type "${m}" for feature flag "${e}"; returning default value`);return this.emitter.emit("error",this.u.getUnwrappedContext(),R),gr(br.WrongType,t)}}let f=pr(g,y,h);return g==null&&(this.logger.debug("Result value is null. Providing default value."),f.value=t),C==null||C.forEach(v=>{this.dt(v,void 0,this.T)}),u&&((l=this.E)==null||l.sendEvent(r.evalEventClient(e,g,t,c.flag,d,h))),f}variation(e,t){let{value:r}=this.R.withEvaluation(e,this.u.getUnwrappedContext(),t,()=>this.dt(e,t,this.T));return r}variationDetail(e,t){return this.R.withEvaluation(e,this.u.getUnwrappedContext(),t,()=>this.dt(e,t,this.lt))}H(e,t,r,n){return this.R.withEvaluation(e,this.u.getUnwrappedContext(),t,()=>this.dt(e,t,r,n))}boolVariation(e,t){return this.H(e,t,this.T,r=>[p.Boolean.is(r),p.Boolean.getType()]).value}jsonVariation(e,t){return this.variation(e,t)}numberVariation(e,t){return this.H(e,t,this.T,r=>[p.Number.is(r),p.Number.getType()]).value}stringVariation(e,t){return this.H(e,t,this.T,r=>[p.String.is(r),p.String.getType()]).value}boolVariationDetail(e,t){return this.H(e,t,this.lt,r=>[p.Boolean.is(r),p.Boolean.getType()])}numberVariationDetail(e,t){return this.H(e,t,this.lt,r=>[p.Number.is(r),p.Number.getType()])}stringVariationDetail(e,t){return this.H(e,t,this.lt,r=>[p.String.is(r),p.String.getType()])}jsonVariationDetail(e,t){return this.variationDetail(e,t)}addHook(e){this.R.addHook(e)}setEventSendingEnabled(e,t){var r,n,i,a;this.Mt!==e&&(this.Mt=e,e?(this.logger.debug("Starting event processor"),(r=this.E)==null||r.start()):t?((n=this.logger)==null||n.debug("Flushing event processor before disabling."),this.flush().then(()=>{var s,o;this.Mt||((s=this.logger)==null||s.debug("Stopping event processor."),(o=this.E)==null||o.close())})):((i=this.logger)==null||i.debug("Stopping event processor."),(a=this.E)==null||a.close()))}sendEvent(e){var t;(t=this.E)==null||t.sendEvent(e)}getDebugOverrides(){var e,t;return(t=(e=this.$).getDebugOverride)==null?void 0:t.call(e)}Sn(e,t){if(!this.Y.hasInspectors())return;let r={};e.forEach(n=>{let i=this.$.get(n);if(i!=null&&i.flag&&!i.flag.deleted){let{reason:a,value:s,variation:o}=i.flag;r[n]=pr(s,o,a)}else r[n]={value:void 0,variationIndex:null}}),t==="init"?this.Y.onFlagsChanged(r):t==="patch"&&Object.entries(r).forEach(([n,i])=>{this.Y.onFlagChanged(n,i)})}};function ks(e,t,r){r.forEach(n=>{var i;try{(i=n.registerDebug)==null||i.call(n,t)}catch(a){e.error(`Exception thrown registering plugin ${K.safeGetName(e,n)}.`)}})}function kr(e){return{polling:()=>({pathGet(t,r){return`/sdk/evalx/${e}/contexts/${Be(r,t)}`},pathReport(t,r){return`/sdk/evalx/${e}/context`},pathPost(t,r){throw new Error("Post for FDv1 unsupported.")},pathPing(t,r){throw new Error("Ping for polling unsupported.")}}),streaming:()=>({pathGet(t,r){return`/eval/${e}/${Be(r,t)}`},pathReport(t,r){return`/eval/${e}`},pathPost(t,r){throw new Error("Post for FDv1 unsupported.")},pathPing(t,r){return`/ping/${e}`}})}}function Es(){return{polling:()=>({pathGet(e,t){return`/sdk/poll/eval/${Be(t,e)}`},pathReport(e,t){throw new Error("Report for FDv2 unsupported.")},pathPost(e,t){return"/sdk/poll/eval"},pathPing(e,t){throw new Error("Ping for polling unsupported.")}}),streaming:()=>({pathGet(e,t){return`/sdk/stream/eval/${Be(t,e)}`},pathReport(e,t){throw new Error("Report for FDv2 unsupported.")},pathPost(e,t){return"/sdk/stream/eval"},pathPing(e,t){throw new Error("Ping for streaming unsupported.")}})}}function Ds(e,t,r){return{async handlePut(n,i){r.debug(`Got PUT: ${Object.keys(i)}`);let a=Object.entries(i).reduce((s,[o,l])=>(s[o]={version:l.version,flag:l},s),{});await e.init(n,a),t.requestStateUpdate("VALID")},async handlePatch(n,i){r.debug(`Got PATCH ${JSON.stringify(i,null,2)}`),e.upsert(n,i.key,{version:i.version,flag:i})},async handleDelete(n,i){r.debug(`Got DELETE ${JSON.stringify(i,null,2)}`),e.upsert(n,i.key,{version:i.version,flag:V(E({},i),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})},handleStreamingError(n){t.reportError(n.kind,n.message,n.code,n.recoverable)},handlePollingError(n){t.reportError(n.kind,n.message,n.status,n.recoverable)}}}function bn(e,t=()=>Date.now()){let r="CLOSED",n=t(),i;function a(){return{state:r,stateSince:n,lastError:i}}function s(o,l=!1){let u=o==="INTERRUPTED"&&r==="INITIALIZING"?"INITIALIZING":o,d=r!==u;d&&(r=u,n=t()),(d||l)&&e.emit("dataSourceStatus",a())}return{get status(){return a()},requestStateUpdate(o){s(o)},reportError(o,l,u,d=!1){i={kind:o,message:l,statusCode:u,time:t()},s(d?"INTERRUPTED":"CLOSED",!0)}}}function Er(e){e==null||e.debug("Poll completed after the processor was closed. Skipping processing.")}var Cs=class{constructor(e,t,r,n,i){this.kn=e,this.Cn=t,this.Pn=r,this.m=n,this.t=i,this.h=!1}async be(){var e,t,r,n,i,a,s;if(this.h)return;let o=c=>{var h,g,y;(h=this.t)==null||h.error("Polling received invalid data"),(g=this.t)==null||g.debug(`Invalid JSON follows: ${c}`),(y=this.m)==null||y.call(this,new qe(T.InvalidData,"Malformed JSON data in polling response"))};(e=this.t)==null||e.debug("Polling LaunchDarkly for feature flag updates");let l=Date.now();try{let c=await this.kn.requestPayload();try{if(this.h){Er(this.t);return}let h=JSON.parse(c);try{(t=this.Pn)==null||t.call(this,h)}catch(g){(r=this.t)==null||r.error(`Exception from data handler: ${g}`)}}catch(h){o(c)}}catch(c){if(this.h){Er(this.t);return}let h=c;if(h.status!==void 0&&!Ee(h.status)){(n=this.t)==null||n.error(X(c,"polling request")),(i=this.m)==null||i.call(this,new qe(T.ErrorResponse,h.message,h.status));return}(a=this.t)==null||a.error(X(c,"polling request","will retry"))}let u=Date.now()-l,d=Math.max(this.Cn*1e3-u,0);(s=this.t)==null||s.debug("Elapsed: %d ms, sleeping for %d ms",u,d),this.$t=setTimeout(()=>{this.be()},d)}start(){this.be()}stop(){this.$t&&(clearTimeout(this.$t),this.$t=void 0),this.h=!0}close(){this.stop()}},xs=(e,t,r,n)=>{r==null||r.error(`Stream received invalid data in "${e}" message`),r==null||r.debug(`Invalid JSON follows: ${t}`),n==null||n(new mt(T.InvalidData,"Malformed JSON data in event stream"))};function Ss(e,t){t==null||t.debug(`Received ${e} event after processor was closed. Skipping processing.`)}function Dr(e){e==null||e.debug("Ping completed after processor was closed. Skipping processing.")}var Rs=class{constructor(e,t,r,n,i,a,s,o,l){var u;this.In=e,this.Rt=t,this.n=r,this.z=n,this.xn=a,this.C=s,this.m=o,this.t=l,this.h=!1;let d;t.useReport&&!n.getEventSourceCapabilities().customMethod?d=t.paths.pathPing(i,e):d=t.useReport?t.paths.pathReport(i,e):t.paths.pathGet(i,e);let c=[...(u=t.queryParameters)!=null?u:[]];this.Rt.withReasons&&c.push({key:"withReasons",value:"true"}),this.z=n,this.De=E({},t.baseHeaders),this.t=l,this.Ln=Ur(t.serviceEndpoints,d,c)}Se(){this.ht=Date.now()}Nt(e){this.ht&&this.C&&this.C.recordStreamInit(this.ht,!e,Date.now()-this.ht),this.ht=void 0}On(e){var t,r,n;return Pt(e)?((n=this.t)==null||n.warn(X(e,"streaming request","will retry")),this.Nt(!1),this.Se(),!0):(this.Nt(!1),(t=this.m)==null||t.call(this,new mt(T.ErrorResponse,e.message,e.status,!1)),(r=this.t)==null||r.error(X(e,"streaming request")),!1)}start(){this.Se();let e;this.Rt.useReport?(this.De["content-type"]="application/json",e={method:"REPORT",body:this.In}):e={};let t=this.z.createEventSource(this.Ln,V(E({headers:this.De},e),{errorFilter:r=>this.On(r),initialRetryDelayMillis:this.Rt.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3}));this.ke=t,t.onclose=()=>{var r;(r=this.t)==null||r.info("Closed LaunchDarkly stream connection")},t.onerror=()=>{},t.onopen=()=>{var r;(r=this.t)==null||r.info("Opened LaunchDarkly stream connection")},t.onretrying=r=>{var n;(n=this.t)==null||n.info(`Will retry stream connection in ${r.delayMillis} milliseconds`)},this.n.forEach(({deserializeData:r,processJson:n},i)=>{t.addEventListener(i,a=>{var s,o;if(this.h){Ss(i,this.t);return}if((s=this.t)==null||s.debug(`Received ${i} event`),a!=null&&a.data){this.Nt(!0);let{data:l}=a,u=r(l);if(!u){xs(i,l,this.t,this.m);return}n(u)}else(o=this.m)==null||o.call(this,new mt(T.InvalidData,"Unexpected payload from event stream"))})}),t.addEventListener("ping",async()=>{var r,n,i,a,s,o,l;(r=this.t)==null||r.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let u=await this.xn.requestPayload();try{if(this.h){Dr(this.t);return}let d=JSON.parse(u);try{(n=this.n.get("put"))==null||n.processJson(d)}catch(c){(i=this.t)==null||i.error(`Exception from data handler: ${c}`)}}catch(d){(a=this.t)==null||a.error("Polling after ping received invalid data"),(s=this.t)==null||s.debug(`Invalid JSON follows: ${u}`),(o=this.m)==null||o.call(this,new qe(T.InvalidData,"Malformed JSON data in ping polling response"))}}catch(u){if(this.h){Dr(this.t);return}let d=u;(l=this.m)==null||l.call(this,new qe(T.ErrorResponse,d.message,d.status))}})}stop(){var e;(e=this.ke)==null||e.close(),this.ke=void 0,this.h=!0}close(){this.stop()}},Is=class{constructor(e,t,r,n,i,a,s,o,l){this.platform=e,this.flagManager=t,this.credential=r,this.config=n,this.getPollingPaths=i,this.getStreamingPaths=a,this.baseHeaders=s,this.emitter=o,this.diagnosticsManager=l,this.closed=!1,this.logger=n.logger,this.dataSourceStatusManager=bn(o),this.q=Ds(t,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(e){this.An=e}createPollingProcessor(e,t,r,n,i){let a=new Cs(r,this.config.pollInterval,async s=>{await this.q.handlePut(t,s),n==null||n()},s=>{this.emitter.emit("error",e,s),this.q.handlePollingError(s),i==null||i(s)},this.logger);this.updateProcessor=this.Ce(a,this.dataSourceStatusManager)}createStreamingProcessor(e,t,r,n,i){var a;let s=new Rs(JSON.stringify(e),{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:(a=this.An)==null?void 0:a.queryParameters},this.createStreamListeners(t,n),this.platform.requests,this.platform.encoding,r,this.diagnosticsManager,o=>{this.emitter.emit("error",e,o),this.q.handleStreamingError(o),i==null||i(o)},this.logger);this.updateProcessor=this.Ce(s,this.dataSourceStatusManager)}createStreamListeners(e,t){let r=new Map;return r.set("put",{deserializeData:JSON.parse,processJson:async n=>{await this.q.handlePut(e,n),t==null||t()}}),r.set("patch",{deserializeData:JSON.parse,processJson:async n=>{this.q.handlePatch(e,n)}}),r.set("delete",{deserializeData:JSON.parse,processJson:async n=>{this.q.handleDelete(e,n)}}),r}Ce(e,t){return{start:()=>{t.requestStateUpdate("INITIALIZING"),e.start()},stop:()=>{e.stop(),t.requestStateUpdate("CLOSED")},close:()=>{e.close(),t.requestStateUpdate("CLOSED")}}}close(){var e;(e=this.updateProcessor)==null||e.close(),this.closed=!0}};function Os(e,t){return Object.entries(e).every(([r,n])=>n===void 0||t[r]===n)}var Ps={foreground:"foregroundMode",background:"backgroundMode"};function $s(e,t){let r=e.find(n=>Os(n.conditions,t));if(r){let{mode:n}=r;return typeof n=="object"?t[Ps[n.configured]]:n}return t.foregroundMode}var Ls=[{conditions:{networkAvailable:!1},mode:"offline"},{conditions:{},mode:{configured:"foreground"}}];function he(e,t,r,n){return{type:"changeSet",payload:e,fdv1Fallback:t,environmentId:r,freshness:n}}function A(e,t){return{type:"status",state:"interrupted",errorInfo:e,fdv1Fallback:t}}function ee(){return{type:"status",state:"shutdown",fdv1Fallback:!1}}function Re(e,t){return{type:"status",state:"terminal_error",errorInfo:e,fdv1Fallback:t}}function kn(e,t){return{type:"status",state:"goodbye",reason:e,fdv1Fallback:t}}function me(e){return{kind:T.ErrorResponse,message:`Unexpected status code: ${e}`,statusCode:e,time:Date.now()}}function Ge(e){return{kind:T.NetworkError,message:e,time:Date.now()}}function fe(e){return{kind:T.InvalidData,message:e,time:Date.now()}}function Dt(e){return{kind:T.Unknown,message:e,time:Date.now()}}function Ts(e){let t=e,{version:r}=t;return St(t,["version"])}async function Ms(e){let{storage:t,crypto:r,environmentNamespace:n,context:i,logger:a}=e;if(!t)return a==null||a.debug("No storage available for cache initializer"),he({version:0,type:"none",updates:[]},!1);let s=await hn(t,r,n,i,a);if(!s)return a==null||a.debug("Cache miss for context"),he({version:0,type:"none",updates:[]},!1);let o={version:0,type:"full",updates:Object.entries(s.flags).map(([u,d])=>({kind:"flag-eval",key:u,version:d.version,object:Ts(d)}))},l=await Ya(t,r,n,i,a);return a==null||a.debug("Loaded cached flag evaluations via cache initializer"),he(o,!1,void 0,l)}function Fs(e){return t=>{let r,n=new Promise(i=>{r=i});return{async run(){return Promise.race([n,Ms(e)])},close(){r==null||r(ee()),r=void 0}}}}function En(e,t,r,n,i,a,s,o){let l=E({},a),u,d="GET",c;return o?(d="POST",l["content-type"]="application/json",u=e,c=r.pathPost(i,e)):c=r.pathGet(i,e),{async poll(h){let g=[...s!=null?s:[]];h&&g.push({key:"basis",value:h});let y=qr(t,c,g),C=await n.fetch(y,{method:d,headers:l,body:u}),f=C.status===304?null:await C.text();return{status:C.status,headers:C.headers,body:f}}}}function Dn(e){return e}function Ns(e){if(e.deleted)return{version:e.version,flag:{version:e.version,deleted:!0,value:void 0,trackEvents:!1}};let t=e.object;return{version:e.version,flag:V(E({},t),{version:e.version})}}function As(e){let t={};return e.forEach(r=>{r.kind==="flag-eval"&&(t[r.key]=Ns(r))}),t}function js(e){let t=e.get("x-ld-fd-fallback");return t!==null&&t.toLowerCase()==="true"}function Vs(e){var t;return(t=e.get("x-ld-envid"))!=null?t:void 0}function zs(e,t,r,n){let i=K.createProtocolHandler({"flag-eval":Dn},n),a;if(e.forEach(o=>{if(a)return;let l=i.processEvent(o);switch(l.type){case"payload":a=he(l.payload,t,r);break;case"goodbye":a=kn(l.reason,t);break;case"serverError":{let u=Dt(l.reason);n==null||n.error(`Server error during polling: ${l.reason}`),a=A(u,t);break}case"error":{if(l.kind==="MISSING_PAYLOAD"||l.kind==="PROTOCOL_ERROR"){let u=fe(l.message);n==null||n.warn(`Protocol error during polling: ${l.message}`),a=A(u,t)}else n==null||n.warn(l.message);break}}}),a)return a;let s=Dt("Unexpected end of polling response");return n==null||n.error("Unexpected end of polling response"),A(s,t)}async function jt(e,t,r){var n;let i=!1,a;try{let s=await e.poll(t);if(i=js(s.headers),a=Vs(s.headers),s.status===304)return he({version:0,type:"none",updates:[]},i,a);if(s.status<200||s.status>=300){let l=me(s.status);return r==null||r.error(`Polling request failed with HTTP error: ${s.status}`),s.status<=0||Ee(s.status)?A(l,i):Re(l,i)}if(!s.body){let l=fe("Empty response body");return r==null||r.error("Polling request received empty response body"),A(l,i)}let o;try{o=JSON.parse(s.body)}catch(l){let u=fe("Malformed JSON data in polling response");return r==null||r.error("Polling request received malformed data"),A(u,i)}if(!Array.isArray(o.events)){let l=fe("Invalid polling response: missing or invalid events array");return r==null||r.error("Polling response does not contain a valid events array"),A(l,i)}return zs(o.events,i,a,r)}catch(s){let o=(n=s==null?void 0:s.message)!=null?n:String(s);r==null||r.error(`Polling request failed with network error: ${o}`);let l=Ge(o);return A(l,i)}}var ht=Symbol("shutdown");function Us(e,t,r){let n,i=new Promise(a=>{n=a});return{async run(){let a=r(),s;for(let l=0;l<=3;l+=1){let u=await Promise.race([i,jt(e,a,t)]);if(u===ht)return ee();if(u.type==="changeSet"||u.state!=="interrupted")return u;if(s=u,l<3&&(t==null||t.warn(`Recoverable polling error (attempt ${l+1}/4), retrying in 1000ms...`),await Promise.race([i,$t(1e3)])===ht))return ee()}let o=s;return Re(o.errorInfo,o.fdv1Fallback)},close(){n==null||n(ht),n=void 0}}}function Vt(){let e=[],t=[];return{put(r){let n=t.shift();n?n(r):e.push(r)},take(){return e.length>0?Promise.resolve(e.shift()):new Promise(r=>{t.push(r)})}}}function qs(e,t,r,n){let i=Vt(),a,s=new Promise(d=>{a=d}),o,l=!1;async function u(){if(l)return;let d=Date.now();try{let c=await jt(e,r(),t);if(l)return;let h=!1;if(c.type==="status")switch(c.state){case"terminal_error":l=!0,h=!0;break;case"interrupted":case"goodbye":break;case"shutdown":break;default:break}h?(a==null||a(c),a=void 0):i.put(c)}catch(c){t==null||t.debug(`Polling error: ${c}`)}if(!l){let c=Date.now()-d,h=Math.min(Math.max(n-c,0),n);o=setTimeout(()=>{u()},h)}}return u(),{async next(){return Promise.race([s,i.take()])},close(){l=!0,o!==void 0&&(clearTimeout(o),o=void 0),a==null||a(ee()),a=void 0}}}function Ct(e,t){var r,n;let i=(r=t==null?void 0:t.isFDv1Fallback)!=null?r:!1,a=(n=t==null?void 0:t.initialState)!=null?n:i?"blocked":"available";return{factory:e,isFDv1Fallback:i,state:a}}function Ks(e,t,r){let n,i=-1,a=-1,s=!1;function o(){n&&(n.close(),n=void 0)}function l(){return t.findIndex(u=>u.state==="available")}return{get isShutdown(){return s},getNextInitializerAndSetActive(){if(s||(i+=1,i>=e.length))return;o();let u=e[i](r);return n=u,u},getNextAvailableSynchronizerAndSetActive(){if(s||t.length===0)return;let u=0;for(;u<t.length;){a+=1,a>=t.length&&(a=0);let d=t[a];if(d.state==="available"){o();let c=d.factory(r);return n=c,c}u+=1}},blockCurrentSynchronizer(){a>=0&&a<t.length&&(t[a].state="blocked")},resetSourceIndex(){a=-1},fdv1Fallback(){t.forEach(u=>{u.state=u.isFDv1Fallback?"available":"blocked"}),a=-1},isPrimeSynchronizer(){return a===l()},getAvailableSynchronizerCount(){return t.filter(u=>u.state==="available").length},hasFDv1Fallback(){return t.some(u=>u.isFDv1Fallback)},close(){s=!0,o()}}}var Bs=["server-intent","put-object","delete-object","payload-transferred","goodbye","error","heart-beat"];function Hs(e){let t=Vt(),r=K.createProtocolHandler({"flag-eval":Dn},e.logger),n=E({},e.headers);function i(){var f;let v=[...e.parameters],m=(f=e.selectorGetter)==null?void 0:f.call(e);return m&&v.push({key:"basis",value:encodeURIComponent(m)}),Ur(e.serviceEndpoints,e.streamUriPath,v)}let a,s,o=!1,l=!1,u=!1;function d(){s=Date.now()}function c(f){s&&e.diagnosticsManager&&e.diagnosticsManager.recordStreamInit(s,!f,Date.now()-s),s=void 0}function h(f){switch(f.type){case"payload":c(!0),t.put(he(f.payload,o));break;case"goodbye":t.put(kn(f.reason,o));break;case"serverError":t.put(A(Dt(f.reason),o));break;case"error":(f.kind==="MISSING_PAYLOAD"||f.kind==="PROTOCOL_ERROR")&&t.put(A(fe(f.message),o));break}}function g(f){var v,m,R,D,I,w;return((v=f.headers)==null?void 0:v["x-ld-fd-fallback"])==="true"?(o=!0,c(!1),t.put(Re(me((m=f.status)!=null?m:0),!0)),!1):Pt(f)?((I=e.logger)==null||I.warn(X(f,"streaming request","will retry")),c(!1),d(),t.put(A(me((w=f.status)!=null?w:0),o)),!0):((R=e.logger)==null||R.error(X(f,"streaming request")),c(!1),t.put(Re(me((D=f.status)!=null?D:0),o)),!1)}function y(f){Bs.forEach(v=>{f.addEventListener(v,m=>{var R,D,I,w,x;if(u){(R=e.logger)==null||R.debug(`Received ${v} event after processor was closed. Skipping.`);return}if(!(m!=null&&m.data)){v!=="error"&&((D=e.logger)==null||D.warn(`Event from EventStream missing data for "${v}".`));return}(I=e.logger)==null||I.debug(`Received ${v} event`);let b;try{b=JSON.parse(m.data)}catch(B){(w=e.logger)==null||w.error(`Stream received data that was unable to be parsed in "${v}" message`),(x=e.logger)==null||x.debug(`Data follows: ${m.data}`),t.put(A(fe("Malformed JSON in EventStream"),o));return}let $=r.processEvent({event:v,data:b});h($)})})}function C(f){f.addEventListener("ping",async()=>{var v,m,R,D,I,w,x;if(u){(v=e.logger)==null||v.debug("Ping received after processor was closed. Skipping.");return}if((m=e.logger)==null||m.debug("Got PING, going to poll LaunchDarkly for feature flag updates"),!e.pingHandler){(R=e.logger)==null||R.warn("Ping event received but no ping handler configured.");return}try{let b=await e.pingHandler.handlePing();if(u){(D=e.logger)==null||D.debug("Ping completed after processor was closed. Skipping processing.");return}t.put(b)}catch(b){if(u)return;(w=e.logger)==null||w.error(`Error handling ping: ${(I=b==null?void 0:b.message)!=null?I:b}`),t.put(A(Ge((x=b==null?void 0:b.message)!=null?x:"Error during ping poll"),o))}})}return{start(){if(l||u)return;l=!0,d();let f=e.requests.createEventSource(i(),{headers:n,errorFilter:v=>g(v),initialRetryDelayMillis:e.initialRetryDelayMillis,readTimeoutMillis:300*1e3,retryResetIntervalMillis:60*1e3,urlBuilder:i});a=f,y(f),C(f),f.onclose=()=>{var v;(v=e.logger)==null||v.info("Closed LaunchDarkly stream connection")},f.onerror=v=>{var m;u||v&&typeof v.status=="number"||t.put(A(Ge((m=v==null?void 0:v.message)!=null?m:"IO Error"),o))},f.onopen=()=>{var v;(v=e.logger)==null||v.info("Opened LaunchDarkly stream connection"),r.reset()},f.onretrying=v=>{var m;(m=e.logger)==null||m.info(`Will retry stream connection in ${v.delayMillis} milliseconds`)}},close(){u||(u=!0,a==null||a.close(),a=void 0,t.put(ee()))},takeResult(){return t.take()}}}function Js(e){let t=!1,r,n=new Promise(i=>{r=i});return{run(){return t?Promise.resolve(ee()):(e.start(),Promise.race([e.takeResult().then(i=>(e.close(),i)),n]))},close(){t||(t=!0,e.close(),r==null||r(ee()),r=void 0)}}}function Gs(e){let t=!1,r=!1,n,i=new Promise(a=>{n=a});return{next(){return r?Promise.resolve(ee()):(t||(t=!0,e.start()),Promise.race([e.takeResult(),i]))},close(){r||(r=!0,e.close(),n==null||n(ee()),n=void 0)}}}function _s(e,t,r){return{handlePing:()=>jt(e,t(),r)}}function Cn(e,t){var r,n;return!(t!=null&&t.pollingBaseUri)&&!(t!=null&&t.streamingBaseUri)?e.serviceEndpoints:new be((r=t.streamingBaseUri)!=null?r:e.serviceEndpoints.streaming,(n=t.pollingBaseUri)!=null?n:e.serviceEndpoints.polling,e.serviceEndpoints.events,e.serviceEndpoints.analyticsEventPath,e.serviceEndpoints.diagnosticEventPath,e.serviceEndpoints.includeAuthorizationHeader,e.serviceEndpoints.payloadFilterKey)}function xt(e,t){if(!(t!=null&&t.pollingBaseUri))return e.requestor;let r=Cn(e,t);return En(e.plainContextString,r,e.polling.paths,e.requests,e.encoding,e.baseHeaders,e.queryParams)}function Cr(e,t,r){var n;let i=Cn(t,e.endpoints),a=xt(t,e.endpoints),s=t.streaming.paths.pathGet(t.encoding,t.plainContextString);return Hs({requests:t.requests,serviceEndpoints:i,streamUriPath:s,parameters:t.queryParams,selectorGetter:r,headers:t.baseHeaders,initialRetryDelayMillis:((n=e.initialReconnectDelay)!=null?n:t.streaming.initialReconnectDelaySeconds)*1e3,logger:t.logger,pingHandler:_s(a,r,t.logger)})}function Ws(){return{createInitializerFactory(e,t){switch(e.type){case"polling":{let r=xt(t,e.endpoints);return n=>Us(r,t.logger,n)}case"streaming":return r=>Js(Cr(e,t,r));case"cache":return Fs({storage:t.storage,crypto:t.crypto,environmentNamespace:t.environmentNamespace,context:t.context,logger:t.logger});default:return}},createSynchronizerSlot(e,t){var r;switch(e.type){case"polling":{let n=((r=e.pollInterval)!=null?r:t.polling.intervalSeconds)*1e3,i=xt(t,e.endpoints);return Ct(a=>qs(i,t.logger,a,n))}case"streaming":return Ct(n=>Gs(Cr(e,t,n)));default:return}}}}function Zs(e){return{version:1,type:"full",updates:Object.entries(e).map(([t,r])=>{var n;return{kind:"flag",key:t,version:(n=r.version)!=null?n:1,object:r}})}}function Ys(e,t,r){let n=Vt(),i,a=new Promise(c=>{i=c}),s,o=!1,l=!1;function u(c){if(!o){let h=Date.now()-c,g=Math.min(Math.max(t-h,0),t);s=setTimeout(d,g)}}async function d(){if(o)return;r==null||r.debug("Polling FDv1 endpoint for feature flag updates");let c=Date.now();try{let h=await e.requestPayload();if(o)return;let g;try{let y=JSON.parse(h);g=Zs(y)}catch(y){r==null||r.error("FDv1 polling received malformed data"),n.put({type:"status",state:"interrupted",errorInfo:fe("Malformed data in FDv1 polling response"),fdv1Fallback:!1}),u(c);return}n.put(he(g,!1))}catch(h){if(o)return;let g=h;if(g.status!==void 0&&!Ee(g.status)){r==null||r.error(X(h,"FDv1 polling request")),o=!0,i==null||i(Re(me(g.status),!1)),i=void 0;return}r==null||r.warn(X(h,"FDv1 polling request","will retry")),n.put({type:"status",state:"interrupted",errorInfo:g.status?me(g.status):Ge(g.message),fdv1Fallback:!1})}u(c)}return{next(){return l||(l=!0,d()),Promise.race([a,n.take()])},close(){o=!0,s!==void 0&&(clearTimeout(s),s=void 0),i==null||i(ee()),i=void 0}}}var xn=120*1e3,Sn=300*1e3;function Qs(e,t,r){let n=Hr(e/1e3,r);return{promise:n.promise.then(()=>new Promise(()=>{}),()=>t),cancel:n.cancel}}function Rn(e,t,r){let n,i,a=!1,s=new Promise(u=>{n=u});function o(){!i&&!a&&(i=Qs(e,t,`${t} condition`),i.promise.then(u=>{i=void 0,n==null||n(u)}))}function l(){i==null||i.cancel(),i=void 0}return r||o(),{promise:s,inform(u){a||r==null||r(u,{start:o,cancel:l})},close(){a=!0,l()}}}function xr(e){return Rn(e,"fallback",(t,{start:r,cancel:n})=>{t.type==="changeSet"?n():t.type==="status"&&t.state==="interrupted"&&r()})}function Xs(e){return Rn(e,"recovery")}function Sr(e){return{promise:e.length===0?void 0:Promise.race(e.map(t=>t.promise)),inform(t){e.forEach(r=>r.inform(t))},close(){e.forEach(t=>t.close())}}}function eo(e,t,r=xn,n=Sn){return e<=1?Sr([]):Sr(t?[xr(r)]:[xr(r),Xs(n)])}function to(e){let{initializerFactories:t,synchronizerSlots:r,dataCallback:n,statusManager:i,selectorGetter:a,logger:s,fallbackTimeoutMs:o=xn,recoveryTimeoutMs:l=Sn}=e,u=!1,d=!1,c=!1,h,g,y=Ks(t,r,a);function C(){u||(u=!0,h==null||h(),h=void 0,g=void 0)}function f(w){n(w.payload),i.requestStateUpdate("VALID")}function v(w){w.errorInfo&&i.reportError(w.errorInfo.kind,w.errorInfo.message,w.errorInfo.statusCode,w.state==="interrupted")}function m(w){return w.fdv1Fallback&&y.hasFDv1Fallback()?(y.fdv1Fallback(),!0):!1}async function R(){for(var w,x;!d;){let b=y.getNextInitializerAndSetActive();if(b===void 0)break;let $=await b.run();if(d)return;if($.type==="changeSet"&&$.payload.type!=="none"){if(f($),m($)){c=!0;break}if($.payload.state){C();return}c=!0}else if($.type==="status"){switch($.state){case"interrupted":case"terminal_error":s==null||s.warn(`Initializer failed: ${(x=(w=$.errorInfo)==null?void 0:w.message)!=null?x:"unknown error"}`),v($);break;case"shutdown":return}m($)}}c&&C()}async function D(){for(var w,x,b,$;!d;){let B=y.getNextAvailableSynchronizerAndSetActive();if(B===void 0){u||(g==null||g(new Error("All data sources exhausted without receiving data.")),h=void 0,g=void 0);return}let N=eo(y.getAvailableSynchronizerCount(),y.isPrimeSynchronizer(),o,l);N.promise&&(s==null||s.debug("Fallback condition active for current synchronizer."));let re=!0;try{for(;!d&&re;){let oe=[B.next().then(O=>({source:"sync",value:O}))];N.promise!==void 0&&oe.push(N.promise.then(O=>({source:"condition",value:O})));let le=await Promise.race(oe);if(d)return;if(le.source==="condition"){let O=le.value;O==="fallback"?s==null||s.warn("Fallback condition fired, moving to next synchronizer."):O==="recovery"&&(s==null||s.info("Recovery condition fired, resetting to primary synchronizer."),y.resetSourceIndex()),re=!1}else{let O=le.value;if(N.inform(O),O.type==="changeSet")f(O),u||C();else if(O.type==="status")switch(O.state){case"interrupted":s==null||s.warn(`Synchronizer interrupted: ${(x=(w=O.errorInfo)==null?void 0:w.message)!=null?x:"unknown error"}`),v(O);break;case"terminal_error":s==null||s.error(`Synchronizer terminal error: ${($=(b=O.errorInfo)==null?void 0:b.message)!=null?$:"unknown error"}`),v(O),y.blockCurrentSynchronizer(),re=!1;break;case"shutdown":return;case"goodbye":break;default:break}m(O)&&(re=!1)}}}finally{N.close()}}}async function I(){if(t.length===0&&r.length===0){i.requestStateUpdate("VALID"),C();return}await R(),d||await D()}return{start(){return new Promise((w,x)=>{h=w,g=x,i.requestStateUpdate("INITIALIZING"),I().then(()=>{u||(g==null||g(new Error("Data source closed before initialization completed.")),h=void 0,g=void 0)}).catch(b=>{u?s==null||s.error(`Orchestration error: ${b}`):(g==null||g(b instanceof Error?b:new Error(String(b))),h=void 0,g=void 0)})})},close(){d=!0,y.close()}}}var ro=1e3;function no(e){let{initialState:t,onReconcile:r,debounceMs:n=ro}=e,{networkState:i,lifecycleState:a,requestedMode:s}=t,o,l=!1;function u(){return{networkState:i,lifecycleState:a,requestedMode:s}}function d(){l||(o!==void 0&&clearTimeout(o),o=setTimeout(()=>{o=void 0,l||r(u())},n))}return{setNetworkState(c){i!==c&&(i=c,d())},setLifecycleState(c){a!==c&&(a=c,d())},setRequestedMode(c){s!==c&&(s=c,d())},close(){l=!0,o!==void 0&&(clearTimeout(o),o=void 0)}}}var q="[FDv2DataManagerBase]";function io(e){var t;let{platform:r,flagManager:n,config:i,baseHeaders:a,emitter:s,transitionTable:o,foregroundMode:l,backgroundMode:u,modeTable:d,sourceFactoryProvider:c,buildQueryParams:h,fdv1Endpoints:g,fallbackTimeoutMs:y,recoveryTimeoutMs:C}=e,{logger:f}=i,v=bn(s),m=Es(),R=(t=i.dataSystem)!=null&&t.connectionModes?E(E({},d),i.dataSystem.connectionModes):d,D,I=l,w=l,x,b,$,B,N=!1,re=!1,oe=!1,le,O,tt,Ut=!1,z,ae,Te="available",Ce="foreground";function qt(k){return R[k]}function _n(){return{lifecycle:Ce,networkAvailable:Te==="available",foregroundMode:w,backgroundMode:u!=null?u:"offline"}}function Kt(){return O!==void 0?O:$s(o,_n())}function Bt(){return tt===!0?"streaming":tt===!1?l==="streaming"?"one-shot":l:Ut?"streaming":l}function rt(){w=Bt(),b==null||b.setRequestedMode(w)}function Wn(k,S,W){var H,Z,Y,Me,xe;let Fe=[];W&&k.initializers.filter(P=>!(re&&P.type==="cache")).forEach(P=>{let ue=c.createInitializerFactory(P,S);ue?Fe.push(ue):f.warn(`${q} Unsupported initializer type '${P.type}'. It will be skipped.`)});let ge=[];if(k.synchronizers.forEach(P=>{let ue=c.createSynchronizerSlot(P,S);ue?ge.push(ue):f.warn(`${q} Unsupported synchronizer type '${P.type}'. It will be skipped.`)}),g&&ge.length>0){let P=k.fdv1Fallback,ue=((H=P==null?void 0:P.pollInterval)!=null?H:i.pollInterval)*1e3,Qn=(Z=P==null?void 0:P.endpoints)!=null&&Z.pollingBaseUri||(Y=P==null?void 0:P.endpoints)!=null&&Y.streamingBaseUri?new be((Me=P.endpoints.streamingBaseUri)!=null?Me:S.serviceEndpoints.streaming,(xe=P.endpoints.pollingBaseUri)!=null?xe:S.serviceEndpoints.polling,S.serviceEndpoints.events,S.serviceEndpoints.analyticsEventPath,S.serviceEndpoints.diagnosticEventPath,S.serviceEndpoints.includeAuthorizationHeader,S.serviceEndpoints.payloadFilterKey):S.serviceEndpoints,Xn=()=>kt(S.plainContextString,Qn,g.polling(),S.requests,S.encoding,S.baseHeaders,S.queryParams,i.withReasons,i.useReport),ei=()=>Ys(Xn(),ue,f);ge.push(Ct(ei,{isFDv1Fallback:!0}))}return{initializerFactories:Fe,synchronizerSlots:ge}}function Zn(k){var S;f.debug(`${q} dataCallback: type=${k.type}, updates=${k.updates.length}, state=${k.state}`),D=k.state;let W=$;if(!W){f.warn(`${q} dataCallback called without an identified context.`);return}let H=As((S=k.updates)!=null?S:[]);n.applyChanges(W,H,k.type).catch(Z=>{f.warn(`${q} Failed to persist flag cache: ${Z}`)})}function nt(k,S){if(!B){f.warn(`${q} Cannot create data source without factory context.`);return}let W=qt(k),{initializerFactories:H,synchronizerSlots:Z}=Wn(W,B,S);if(I=k,H.length===0&&Z.length===0){f.debug(`${q} Mode '${k}' has no sources. No data source created.`),!N&&z&&(N=!0,z(),z=void 0,ae=void 0);return}x=to({initializerFactories:H,synchronizerSlots:Z,dataCallback:Zn,statusManager:v,selectorGetter:()=>D,logger:f,fallbackTimeoutMs:y,recoveryTimeoutMs:C}),x.start().then(()=>{N=!0,z&&(z(),z=void 0,ae=void 0)}).catch(Y=>{ae&&(ae(Y instanceof Error?Y:new Error(String(Y))),z=void 0,ae=void 0)})}function Yn(k){if(oe||!B)return;Te=k.networkState,Ce=k.lifecycleState,w=k.requestedMode;let S=Kt();if(S===I){f.debug(`${q} Reconcile: mode unchanged (${S}). No action.`);return}f.debug(`${q} Reconcile: mode switching from '${I}' to '${S}'.`),x==null||x.close(),x=void 0,nt(S,!D)}return{get configuredForegroundMode(){return l},async identify(k,S,W,H){if(oe){f.debug(`${q} Identify called after close.`);return}x==null||x.close(),x=void 0,b==null||b.close(),b=void 0,D=void 0,N=!1,re=!1,$=W,z=k,ae=S;let Z=JSON.stringify(de.toLDContext(W)),Y=h(H);i.withReasons&&Y.push({key:"withReasons",value:"true"});let Me=m.streaming(),xe=m.polling(),Fe=En(Z,i.serviceEndpoints,xe,r.requests,r.encoding,a,Y),ge=await ln(r.crypto,e.credential);if(oe){f.debug(`${q} Identify aborted: closed during async setup.`);return}B={requestor:Fe,requests:r.requests,encoding:r.encoding,serviceEndpoints:i.serviceEndpoints,baseHeaders:a,queryParams:Y,plainContextString:Z,logger:f,polling:{paths:xe,intervalSeconds:i.pollInterval},streaming:{paths:Me,initialReconnectDelaySeconds:i.streamInitialReconnectDelay},storage:r.storage,crypto:r.crypto,environmentNamespace:ge,context:W},w=Bt();let P=Kt();f.debug(`${q} Identify: initial mode resolved to '${P}'.`),re=(H==null?void 0:H.bootstrap)!==void 0,re?(N=!0,v.requestStateUpdate("VALID"),z==null||z(),z=void 0,ae=void 0,qt(P).synchronizers.length>0&&nt(P,!1)):nt(P,!0),b=no({initialState:{networkState:Te,lifecycleState:Ce,requestedMode:w},onReconcile:Yn})},close(){oe=!0,x==null||x.close(),x=void 0,b==null||b.close(),b=void 0,z=void 0,ae=void 0},setNetworkState(k){Te=k,b==null||b.setNetworkState(k)},setLifecycleState(k){k==="background"&&Ce!=="background"&&(le==null||le()),Ce=k,b==null||b.setLifecycleState(k)},setConnectionMode(k){O=k,k!==void 0?b==null||b.setRequestedMode(k):rt()},getCurrentMode(){return I},setFlushCallback(k){le=k},setForcedStreaming(k){tt=k,rt()},setAutomaticStreamingState(k){Ut=k,rt()}}}function We(){return typeof document!==void 0}function zt(){return typeof window!==void 0}function In(e,t,r){return We()?(document.addEventListener(e,t,r),()=>{document.removeEventListener(e,t,r)}):()=>{}}function On(e,t,r){return We()?(window.addEventListener(e,t,r),()=>{window.removeEventListener(e,t,r)}):()=>{}}function Ie(){return zt()?window.location.href:""}function ao(){return zt()?window.location.search:""}function so(){return zt()?window.location.hash:""}function oo(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function lo(){return We()?document.visibilityState:"visibile"}function uo(e){if(We())return document.querySelectorAll(e)}var co="[BrowserDataManager]",ho=class extends Is{constructor(e,t,r,n,i,a,s,o,l,u){super(e,t,r,n,a,s,o,l,u),this.Bn=i,this.Z=void 0,this.Ut=!1,this.Z=i.streaming}P(e,...t){this.logger.debug(`${co} ${e}`,...t)}async identify(e,t,r,n){if(this.closed){this.P("Identify called after data manager was closed.");return}this.context=r;let i=n;i!=null&&i.hash?this.setConnectionParams({queryParameters:[{key:"h",value:i.hash}]}):this.setConnectionParams(),this.zt=i==null?void 0:i.hash,i!=null&&i.bootstrap?this.Tn(r,i,e):(await this.flagManager.loadCached(r)&&this.P("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Mn(r,e,t)),this.Pe(),this.jt()}async Fn(e){let t=JSON.stringify(de.toLDContext(e)),r=kt(t,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.zt),n=3,i;for(let a=0;a<=n;a+=1)try{return await r.requestPayload()}catch(s){if(!Pt(s))throw s;i=s,a<n&&(this.P(X(s,"initial poll request","will retry")),await $t(1e3))}throw i}async Mn(e,t,r){var n,i;try{this.dataSourceStatusManager.requestStateUpdate(sr.Initializing);let a=await this.Fn(e);try{let s=this.createStreamListeners(e,t).get("put");s.processJson(s.deserializeData(a))}catch(s){this.dataSourceStatusManager.reportError(T.InvalidData,(n=s.message)!=null?n:"Could not parse poll response")}}catch(a){this.dataSourceStatusManager.reportError(T.NetworkError,(i=a.message)!=null?i:"unexpected network error",a.status),r(a)}}Tn(e,t,r){let{bootstrapParsed:n}=t;n||(n=cn(this.logger,t.bootstrap)),this.flagManager.setBootstrap(e,n),this.dataSourceStatusManager.requestStateUpdate(sr.Valid),this.P("Identify - Initialization completed from bootstrap"),r()}setForcedStreaming(e){this.Z=e,this.jt()}setAutomaticStreamingState(e){this.Ut=e,this.jt()}jt(){let e=this.Z||this.Ut&&this.Z===void 0;this.P(`Updating streaming state. forced(${this.Z}) automatic(${this.Ut})`),e?this.$n():this.Pe()}Pe(){var e;this.updateProcessor&&this.P("Stopping update processor."),(e=this.updateProcessor)==null||e.close(),this.updateProcessor=void 0}$n(){if(this.updateProcessor){this.P("Update processor already active. Not changing state.");return}if(!this.context){this.P("Context not set, not starting update processor.");return}this.P("Starting update processor."),this.Rn(this.context)}Rn(e,t,r){var n;let i=de.toLDContext(e);(n=this.updateProcessor)==null||n.close();let a=JSON.stringify(de.toLDContext(e)),s=kt(a,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.zt);this.createStreamingProcessor(i,e,s,t,r),this.updateProcessor.start()}};function fo(e){let t=In("visibilitychange",()=>{lo()==="hidden"&&e()}),r=On("pagehide",e);return()=>{t(),r()}}function ft(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function go(e,t,r,n){let i=((e.kind==="substring"||e.kind==="regex")&&n.includes("/")?t:t.replace(n,"")).replace(r,"");switch(e.kind){case"exact":return new RegExp(`^${ft(e.url)}/?$`).test(t);case"canonical":return new RegExp(`^${ft(e.url)}/?$`).test(i);case"substring":return new RegExp(`.*${ft(e.substring)}.*$`).test(i);case"regex":return new RegExp(e.pattern).test(i);default:return!1}}function po(e,t){let r=[];return t.forEach(n=>{let i=e.target,{selector:a}=n,s=uo(a);for(;i&&s!=null&&s.length;){for(let o=0;o<s.length;o+=1)if(i===s[o]){r.push(n);break}i=i.parentNode}}),r}var vo=class{constructor(e,t){let r=e.filter(a=>{var s;return(s=a.urls)==null?void 0:s.some(o=>go(o,Ie(),ao(),so()))}),n=r.filter(a=>a.kind==="pageview"),i=r.filter(a=>a.kind==="click");if(n.forEach(a=>t(a)),i.length){let a=s=>{po(s,i).forEach(o=>{t(o)})};this.Ie=In("click",a)}}close(){var e;(e=this.Ie)==null||e.call(this)}},mo=300,yo=class{constructor(e){this.l=Ie();let t=()=>{let n=Ie();n!==this.l&&(this.l=n,e())};this.Vt=setInterval(t,mo);let r=On("popstate",t);this.xe=()=>{r()}}close(){var e;this.Vt&&clearInterval(this.Vt),(e=this.xe)==null||e.call(this)}},wo=class{constructor(e,t,r,n,i,a=s=>new yo(s)){this.z=t,this.zn=n,this.Un=i,this.ft=[],this.Oe=!1,this.X=`${r}/sdk/goals/${e}`,this.Le=a(()=>{this.Ht()})}async initialize(){await this.Nn(),this.Ht()}startTracking(){this.Oe=!0,this.Ht()}Ht(){var e;this.Oe&&((e=this.Bt)==null||e.close(),this.ft&&this.ft.length&&(this.Bt=new vo(this.ft,t=>{this.Un(Ie(),t)})))}async Nn(){try{let e=await this.z.fetch(this.X);this.ft=await e.json()}catch(e){this.zn(new Kr(`Encountered error fetching goals: ${e}`))}}close(){var e,t;(e=this.Le)==null||e.close(),(t=this.Bt)==null||t.close()}};function bo(e){return e.kind==="click"}var ko=2,Pn={fetchGoals:!0,eventUrlTransformer:e=>e,streaming:void 0,plugins:[]},Eo={fetchGoals:p.Boolean,eventUrlTransformer:p.Function,streaming:p.Boolean,plugins:p.createTypeArray("LDPlugin",{})};function Do(e){var t;let r=E({},e);return(t=r.flushInterval)!=null||(r.flushInterval=ko),r}function Co(e){let t=Do(e);return Object.keys(Pn).forEach(r=>{delete t[r]}),t}function xo(e,t){let r=E({},Pn);return Object.entries(Eo).forEach(n=>{let[i,a]=n,s=e[i];s!==void 0&&(a.is(s)?r[i]=s:t.warn(F.wrongOptionType(i,a.getType(),typeof s)))}),r}var So=class{constructor(e,t){switch(this.jn=e,this.Ae=[],t){case"sha1":this.qt="SHA-1";break;case"sha256":this.qt="SHA-256";break;default:throw new Error(`Algorithm is not supported ${t}`)}}async asyncDigest(e){let t=this.Ae.join(""),r=new TextEncoder().encode(t),n=await this.jn.subtle.digest(this.qt,r);switch(e){case"base64":return btoa(String.fromCharCode(...new Uint8Array(n)));case"hex":return[...new Uint8Array(n)].map(i=>i.toString(16).padStart(2,"0")).join("");default:throw new Error(`Encoding is not supported ${e}`)}}update(e){return this.Ae.push(e),this}},Ro={start:0,end:3},Io={start:4,end:5},gt={start:6,end:7},pt={start:8,end:8},Oo={start:9,end:9},Po={start:10,end:15};function $o(){if(crypto&&crypto.getRandomValues){let t=new Uint8Array(16);return crypto.getRandomValues(t),[...t.values()]}let e=[];for(let t=0;t<16;t+=1)e.push(Math.floor(Math.random()*256));return e}function pe(e,t){let r="";for(let n=t.start;n<=t.end;n+=1)r+=e[n].toString(16).padStart(2,"0");return r}function Lo(e){return e[pt.start]=(e[pt.start]|128)&191,e[gt.start]=e[gt.start]&15|64,`${pe(e,Ro)}-${pe(e,Io)}-${pe(e,gt)}-${pe(e,pt)}${pe(e,Oo)}-${pe(e,Po)}`}function To(){let e=$o();return Lo(e)}function Mo(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():To()}var Fo=class{createHash(e){return new So(oo(),e)}randomUUID(){return Mo()}};function No(e){let t=Array.from(e,r=>String.fromCodePoint(r)).join("");return btoa(t)}var Ao=class{btoa(e){return No(new TextEncoder().encode(e))}},jo=class{constructor(e){this.e=e}platformData(){return{name:"JS"}}sdkData(){let e={name:"@launchdarkly/js-client-sdk",version:"4.6.0",userAgentBase:"JSClient"};return this.e.wrapperName&&(e.wrapperName=this.e.wrapperName),this.e.wrapperVersion&&(e.wrapperVersion=this.e.wrapperVersion),e}},Vo=class{constructor(e,t){this.X=e,this.n={},this.x=new Li(t.initialRetryDelayMillis,t.retryResetIntervalMillis),this.Te=t.errorFilter,this.Gt=t.urlBuilder,this.Me()}Me(){this.Gt&&(this.X=this.Gt()),this.G=new EventSource(this.X),this.G.onopen=()=>{var e;this.x.success(),(e=this.onopen)==null||e.call(this)},this.G.onerror=e=>{var t;e instanceof MessageEvent||(this.w(e),(t=this.onerror)==null||t.call(this,e))},Object.entries(this.n).forEach(([e,t])=>{t.forEach(r=>{var n;(n=this.G)==null||n.addEventListener(e,r)})})}addEventListener(e,t){var r,n,i;(n=(r=this.n)[e])!=null||(r[e]=[]),this.n[e].push(t),(i=this.G)==null||i.addEventListener(e,t)}close(){var e,t;clearTimeout(this.Kt),this.Kt=void 0,(e=this.G)==null||e.close(),(t=this.onclose)==null||t.call(this)}Vn(e){var t;(t=this.onretrying)==null||t.call(this,{delayMillis:e}),this.Kt=setTimeout(()=>{this.Me()},e)}w(e){this.close(),!(typeof e.status=="number"&&!this.Te(e))&&this.Vn(this.x.fail())}},zo=class{fetch(e,t){return fetch(e,t)}createEventSource(e,t){return new Vo(e,t)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function $n(){return typeof localStorage!="undefined"}function Uo(){if(!$n())return[];let e=[];for(let t=0;t<localStorage.length;t+=1){let r=localStorage.key(t);r&&e.push(r)}return e}var qo=class{constructor(e){this.t=e}async clear(e){var t;try{localStorage.removeItem(e)}catch(r){(t=this.t)==null||t.error(`Error clearing key from localStorage: ${e}, reason: ${r}`)}}async get(e){var t;try{let r=localStorage.getItem(e);return r!=null?r:null}catch(r){return(t=this.t)==null||t.error(`Error getting key from localStorage: ${e}, reason: ${r}`),null}}async set(e,t){var r;try{localStorage.setItem(e,t)}catch(n){(r=this.t)==null||r.error(`Error setting key in localStorage: ${e}, reason: ${n}`)}}},Ko=class{constructor(e,t){this.encoding=new Ao,this.crypto=new Fo,this.requests=new zo,$n()&&(this.storage=new qo(e)),this.info=new jo(t)}},Bo=class extends bs{constructor(e,t,r,n={},i){var a,s,o,l,u;let{logger:d,debug:c}=n,h=d!=null?d:new Nr({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:c?"debug":"info"}),g=(a=n.baseUri)!=null?a:"https://clientsdk.launchdarkly.com",y=i!=null?i:new Ko(h,n),C=xo(n,h),f=Co(V(E({},n),{logger:h})),{eventUrlTransformer:v}=C,m=kr(e),R=(D,I,w,x,b)=>I.dataSystem?io({platform:y,flagManager:D,credential:e,config:I,baseHeaders:w,emitter:x,transitionTable:Ls,foregroundMode:Ra(I.dataSystem,hr),backgroundMode:void 0,modeTable:Ve,sourceFactoryProvider:Ws(),fdv1Endpoints:kr(e),buildQueryParams:$=>{let B=[{key:"auth",value:e}],N=$;return N!=null&&N.hash&&B.push({key:"h",value:N.hash}),B}}):new ho(y,D,e,I,C,m.polling,m.streaming,w,x,b);super(e,r,y,f,R,{getLegacyStorageKeys:()=>Uo().filter(D=>D.startsWith(`ld:${e}:`)),analyticsEventPath:`/events/bulk/${e}`,diagnosticEventPath:`/events/diagnostic/${e}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",dataSystemDefaults:hr,trackEventModifier:D=>new K.InputCustomEvent(D.context,D.key,D.data,D.metricValue,D.samplingRatio,v(Ie())),getImplementationHooks:D=>K.safeGetHooks(h,D,C.plugins),credentialType:"clientSideId",requiresStart:!0,initialContext:t}),this.setEventSendingEnabled(!0,!1),C.streaming!==void 0&&((o=(s=this.dataManager).setForcedStreaming)==null||o.call(s,C.streaming)),(u=(l=this.dataManager).setFlushCallback)==null||u.call(l,()=>this.flush()),this.Wt=C.plugins,C.fetchGoals&&(this.Jt=new wo(e,y.requests,g,D=>{h.error(D.message)},(D,I)=>{let w=this.getInternalContext();if(!w)return;let x=v(D);bo(I)?this.sendEvent({kind:"click",url:x,samplingRatio:1,key:I.key,creationDate:Date.now(),context:w,selector:I.selector}):this.sendEvent({kind:"pageview",url:x,samplingRatio:1,key:I.key,creationDate:Date.now(),context:w})}),this.Jt.initialize(),C.automaticBackgroundHandling&&fo(()=>this.flush()))}registerPlugins(e){K.safeRegisterPlugins(this.logger,this.environmentMetadata,e,this.Wt||[]);let t=this.getDebugOverrides();t&&ks(this.logger,t,this.Wt||[])}async identify(e,t){return super.identify(e,t)}async identifyResult(e,t){var r;let n=(t==null?void 0:t.sheddable)===void 0?V(E({},t),{sheddable:!0}):t,i=await super.identifyResult(e,n);return this.startPromise&&((r=this.Jt)==null||r.startTracking()),i}setConnectionMode(e){if(!this.dataManager.setConnectionMode){this.logger.warn("setConnectionMode requires the FDv2 data system (dataSystem option). The call has no effect without it.");return}if(e!==void 0&&!(e in Ve)){this.logger.warn(`setConnectionMode called with invalid mode '${e}'. Valid modes: ${Object.keys(Ve).join(", ")}.`);return}this.dataManager.setConnectionMode(e)}setStreaming(e){var t,r;(r=(t=this.dataManager).setForcedStreaming)==null||r.call(t,e)}Fe(){var e,t;let r=this.emitter.eventNames().some(n=>n.startsWith("change:")||n==="change");(t=(e=this.dataManager).setAutomaticStreamingState)==null||t.call(e,r)}on(e,t){super.on(e,t),this.Fe()}off(e,t){super.off(e,t),this.Fe()}};function Ho(e,t,r,n={},i){let a=new Bo(e,t,r,n,i),s={variation:(o,l)=>a.variation(o,l),variationDetail:(o,l)=>a.variationDetail(o,l),boolVariation:(o,l)=>a.boolVariation(o,l),boolVariationDetail:(o,l)=>a.boolVariationDetail(o,l),numberVariation:(o,l)=>a.numberVariation(o,l),numberVariationDetail:(o,l)=>a.numberVariationDetail(o,l),stringVariation:(o,l)=>a.stringVariation(o,l),stringVariationDetail:(o,l)=>a.stringVariationDetail(o,l),jsonVariation:(o,l)=>a.jsonVariation(o,l),jsonVariationDetail:(o,l)=>a.jsonVariationDetail(o,l),track:(o,l,u)=>a.track(o,l,u),on:(o,l)=>a.on(o,l),off:(o,l)=>a.off(o,l),flush:()=>a.flush(),setConnectionMode:o=>a.setConnectionMode(o),setStreaming:o=>a.setStreaming(o),identify:(o,l)=>a.identifyResult(o,l),getContext:()=>a.getContext(),close:()=>a.close(),allFlags:()=>a.allFlags(),addHook:o=>a.addHook(o),waitForInitialization:o=>a.waitForInitialization(o),logger:a.logger,start:o=>a.start(o)};return a.registerPlugins(s),s}function Ln(e,t,r){return Ho(e,t,Ke.Disabled,r)}function Jo(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!t.startsWith("$")))}function Ze(e){let t=Jo(e!=null?e:{}),r=e!==void 0;function n(h,g,y){return h in t&&y(t[h])?t[h]:g}function i(h,g){return h in t?t[h]:g}function a(h,g,y){return{value:y?n(h,g,y):i(h,g),variationIndex:null,reason:null}}let s=h=>typeof h=="boolean",o=h=>typeof h=="number",l=h=>typeof h=="string",u=()=>{},d=()=>u,c=()=>Promise.resolve();return{allFlags:()=>J({},t),getContext:()=>{},getInitializationState:()=>"initializing",getInitializationError:()=>{},isReady:()=>r,boolVariation:(h,g)=>n(h,g,s),numberVariation:(h,g)=>n(h,g,o),stringVariation:(h,g)=>n(h,g,l),jsonVariation:(h,g)=>i(h,g),boolVariationDetail:(h,g)=>a(h,g,s),numberVariationDetail:(h,g)=>a(h,g,o),stringVariationDetail:(h,g)=>a(h,g,l),jsonVariationDetail:(h,g)=>a(h,g),variation:(h,g)=>i(h,g),variationDetail:(h,g)=>a(h,g),on:u,off:u,onContextChange:d,onInitializationStatusChange:d,shouldUseCamelCaseFlagKeys:()=>!0,close:c,flush:c,identify:c,track:u,addHook:u,waitForInitialization:c,setStreaming:u,start:c,logger:{debug:u,info:u,warn:u,error:u}}}function Ye(e,t,r={}){var f,v;if(typeof window=="undefined")return Ze();let C=r,{useCamelCaseFlagKeys:n=!0}=C,i=Gt(C,["useCamelCaseFlagKeys"]),a=ne(J({},i),{wrapperName:(f=i==null?void 0:i.wrapperName)!=null?f:"react-client-sdk",wrapperVersion:(v=i==null?void 0:i.wrapperVersion)!=null?v:"0.2.1"}),s=Ln(e,t,a),o="initializing",l=!1,u=!1,d=!1,c=new Set,h=new Set,g;function y(){let m=s.getContext();m&&c.forEach(R=>R(m))}return ne(J({},s),{start:m=>u?s.start(m):(u=!0,m!=null&&m.bootstrap&&(l=!0),s.start(m).then(R=>(o=R.status,g=R,d||(d=!0,y()),h.forEach(D=>D(R)),R))),identify:(m,R)=>s.identify(m,R).then(D=>(D.status==="completed"&&y(),D)),getInitializationState:()=>o,getInitializationError:()=>(g==null?void 0:g.status)==="failed"?g.error:void 0,onContextChange:m=>(c.add(m),()=>{c.delete(m)}),onInitializationStatusChange:m=>(g&&m(g),h.add(m),()=>{h.delete(m)}),isReady:()=>o!=="initializing"||l,shouldUseCamelCaseFlagKeys:()=>n})}function Le(e,t){var i;let r=(i=t==null?void 0:t.Provider)!=null?i:U.Provider;return({children:a})=>{var l;let[s,o]=(0,De.useState)({client:e,context:(l=e.getContext())!=null?l:void 0,initializedState:e.getInitializationState(),error:e.getInitializationError()});return(0,De.useEffect)(()=>{let u=!0,d=e.onInitializationStatusChange(h=>{u&&o(g=>g.initializedState===h.status?g:ne(J({},g),{initializedState:h.status,error:h.status==="failed"?h.error:void 0}))}),c=e.onContextChange(h=>{u&&o(g=>ne(J({},g),{context:h}))});return()=>{u=!1,d(),c()}},[]),De.default.createElement(r,{value:s},a)}}function Qe(e,t,r){let{deferInitialization:n,startOptions:i,reactContext:a,ldOptions:s,bootstrap:o}=r!=null?r:{},l=Ye(e,t,s);if(!n){let u=o?ne(J({},i),{bootstrap:o}):i;l.start(u)}return Le(l,a)}var Xe=Wt(require("react"),1);function Tn({clientSideId:e,context:t,bootstrap:r,options:n,reactContext:i,children:a}){let s=(0,Xe.useRef)(null);s.current===null&&(typeof window=="undefined"?s.current=Le(Ze(r),i):s.current=Qe(e,t,ne(J({},n),{bootstrap:r,reactContext:i})));let o=s.current;return Xe.default.createElement(o,null,a)}var G=require("react");function Mn(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[-._\s]+/).filter(Boolean).map((t,r)=>{let n=t.toLowerCase();return r===0?n:n.charAt(0).toUpperCase()+n.slice(1)}).join("")}function Go(e,t){let r=new Map,n=e.shouldUseCamelCaseFlagKeys(),i={},a={};return Object.keys(t).filter(s=>s.indexOf("$")!==0).forEach(s=>{if(n){let o=Mn(s);i[o]=t[s],a[o]=s}else i[s]=t[s]}),new Proxy(i,{get(s,o,l){var h;let u=Reflect.get(s,o,l);if(typeof o=="symbol"||!Object.prototype.hasOwnProperty.call(s,o))return u;if(u===void 0)return;if(r.has(o))return r.get(o);let d=n&&(h=a[o])!=null?h:o,c=e.variation(d,u);return r.set(o,c),c}})}function Fn(e){let{client:t,context:r}=(0,G.useContext)(e!=null?e:U);(0,G.useEffect)(()=>{t.logger.warn("[LaunchDarkly] useFlags is deprecated and will be removed in a future major version.")},[]);let[n,i]=(0,G.useState)(()=>t.allFlags()),a=(0,G.useRef)(!1);return(0,G.useEffect)(()=>{a.current&&i(t.allFlags()),a.current=!0;let s=()=>i(t.allFlags());return t.on("change",s),()=>t.off("change",s)},[t,r]),(0,G.useMemo)(()=>Go(t,n),[t,n,r])}var Nn=require("react");function An(e){let{initializedState:t,error:r}=(0,Nn.useContext)(e!=null?e:U);return t==="failed"?{status:"failed",error:r}:{status:t}}var jn=require("react");function Vn(e){let{client:t}=(0,jn.useContext)(e!=null?e:U);return t}var te=require("react");function _(e,t,r,n,i){let{client:a,context:s}=(0,te.useContext)(n!=null?n:U),o=a.isReady(),l=(0,te.useRef)(t),u=(0,te.useRef)(r);l.current=t,u.current=r;let d=(0,te.useRef)(!1),[c,h]=(0,te.useState)(()=>o?r(a,e,t):i?i(t):t);return(0,te.useEffect)(()=>{d.current&&o&&h(u.current(a,e,l.current)),d.current=!0;let g=()=>h(u.current(a,e,l.current));return a.on(`change:${e}`,g),()=>a.off(`change:${e}`,g)},[a,e,s,o]),c}function zn(e,t,r){return _(e,t,(n,i,a)=>n.boolVariation(i,a),r)}function Un(e,t,r){return _(e,t,(n,i,a)=>n.stringVariation(i,a),r)}function qn(e,t,r){return _(e,t,(n,i,a)=>n.numberVariation(i,a),r)}function Kn(e,t,r){return _(e,t,(n,i,a)=>n.jsonVariation(i,a),r)}function et(e){return{value:e,variationIndex:null,reason:{kind:"ERROR",errorKind:"CLIENT_NOT_READY"}}}function Bn(e,t,r){return _(e,t,(n,i,a)=>n.boolVariationDetail(i,a),r,et)}function Hn(e,t,r){return _(e,t,(n,i,a)=>n.stringVariationDetail(i,a),r,et)}function Jn(e,t,r){return _(e,t,(n,i,a)=>n.numberVariationDetail(i,a),r,et)}function Gn(e,t,r){return _(e,t,(n,i,a)=>n.jsonVariationDetail(i,a),r,et)}0&&(module.exports={LDIsomorphicClientProvider,LDReactContext,createClient,createLDReactProvider,createLDReactProviderWithClient,initLDReactContext,useBoolVariation,useBoolVariationDetail,useFlags,useInitializationStatus,useJsonVariation,useJsonVariationDetail,useLDClient,useNumberVariation,useNumberVariationDetail,useStringVariation,useStringVariationDetail});