@launchdarkly/react-sdk 0.2.0 → 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/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- "use strict";var ti=Object.create;var xe=Object.defineProperty,ri=Object.defineProperties,ni=Object.getOwnPropertyDescriptor,ii=Object.getOwnPropertyDescriptors,ai=Object.getOwnPropertyNames,Ae=Object.getOwnPropertySymbols,si=Object.getPrototypeOf,at=Object.prototype.hasOwnProperty,Jt=Object.prototype.propertyIsEnumerable;var Ht=(e,t,r)=>t in e?xe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,J=(e,t)=>{for(var r in t||(t={}))at.call(t,r)&&Ht(e,r,t[r]);if(Ae)for(var r of Ae(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)at.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&Ae)for(var n of Ae(e))t.indexOf(n)<0&&Jt.call(e,n)&&(r[n]=e[n]);return r};var oi=(e,t)=>{for(var r in t)xe(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))!at.call(e,i)&&i!==r&&xe(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?xe(r,"default",{value:e,enumerable:!0}):r,e)),li=e=>_t(xe({},"__esModule",{value:!0}),e);var _o={};oi(_o,{LDIsomorphicClientProvider:()=>Tn,LDReactContext:()=>z,createClient:()=>Qe,createLDReactProvider:()=>Xe,createLDReactProviderWithClient:()=>Te,initLDReactContext:()=>st,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 st(){return(0,Zt.createContext)(null)}var z=st();var De=Wt(require("react"),1);var ui=Object.defineProperty,ci=Object.defineProperties,di=Object.getOwnPropertyDescriptors,Ue=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(Ue)for(var r of Ue(t))Ir.call(t,r)&&Yt(e,r,t[r]);return e},K=(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&&Ue)for(var n of Ue(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 me=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]}};me.InvalidReference=new me("");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"}},be=class{constructor(e,t){this.mt=e,this.typeOf=typeof t}is(e){return Array.isArray(e)?!1:typeof e===this.typeOf}getType(){return this.mt}},Pr=class{constructor(e,t){this.mt=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.mt}},$r=class extends be{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 be{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"}},Di=class{constructor(e){this.Zt=e}is(e){return typeof e=="string"&&this.Zt.includes(e)}getType(){return this.Zt.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 Di(e)}};p.String=new be("string","");p.Number=new be("number",0);p.ObjectOrFactory=new vi;p.Object=new be("object",{});p.StringArray=new Pr("string[]","");p.Boolean=new be("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 qe(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=>qe(r,[...t,e])).map(r=>r===void 0?"null":r).join(",")}]`:`{${Object.keys(e).sort().map(r=>{let n=qe(e[r],[...t,e]);if(n!==void 0)return`${JSON.stringify(r)}:${n}`}).filter(r=>r!==void 0).join(",")}}`}var mt="user";function Qt(e){return e.includes("%")||e.includes(":")?e.replace(/%/g,"%25").replace(/:/g,"%3A"):e}function Ei(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 ot(e,t=!1){return e?e.map(r=>new me(r,t)):[]}function Ci(e){return e!=null}function xi(e){let t=K(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.P=!1,this.tt=!1,this.Xt=!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)}Qt(t){if(this.P)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 Ei(c)?(l[u]=c,i[u]=ot((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=K(E({},s[l]),{kind:l}),u.et=i,u.tt=l==="user",u}let o=new L(!0,t.kind);return o.M=s,o.et=i,o.P=!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=ot((r=t._meta)==null?void 0:r.privateAttributes),l=new L(!0,i);return l.tt=i==="user",l.v=t,l.et={[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.tt=!0,r.Xt=!0,r.v=xi(t),r.et={user:ot(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.P)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=mt){return t.isKind?this.kinds:L.$e(t,this.Qt(r))}key(t=mt){var r;return(r=this.Qt(t))==null?void 0:r.key}get isMultiKind(){return this.P}get canonicalKey(){return this.tt?this.v.key:this.P?Object.keys(this.M).sort().map(t=>`${t}:${Qt(this.M[t].key)}`).join(":"):`${this.kind}:${Qt(this.v.key)}`}get kinds(){return this.P?Object.keys(this.M):[this.kind]}get kindsAndKeys(){return this.P?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.et)==null?void 0:r[t])||[]}getContexts(){return this.P?Object.entries(this.M):[[this.kind,this.v]]}get legacy(){return this.Xt}canonicalUnfilteredJson(){if(this.valid){if(this.yt)return this.yt;try{this.yt=qe(L.toLDContext(this))}catch(t){}return this.yt}}};de.UserKind=mt;var Si=["key","kind","_meta","anonymous"].map(e=>new me(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.te(e,r[0][1],r[0][0],t);let n={kind:"multi"};return r.forEach(([i,a])=>{n[i]=this.te(e,a,i,t)}),n}p(e,t,r,n){return(n?Object.keys(t).map(i=>new me(i,!0)):[...this.je,...e.privateAttributes(r)]).filter(i=>!Si.some(a=>a.compare(i)))}te(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.gt=0,this.ee=Math.max(1,e),this.He=Math.ceil(Math.log2(tr/this.ee))}x(){let e=Math.min(this.gt,this.He),t=this.ee*2**e;return Math.min(t,tr)}Ge(e){return e-Math.trunc(this.Be()*$i*e)}success(e=Date.now()){this.vt=e}fail(e=Date.now()){this.vt!==void 0&&e-this.vt>this.Ve&&(this.gt=0),this.vt=void 0;let t=this.Ge(this.x());return this.gt+=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 Ke=class extends Error{constructor(e,t,r,n=!0){super(t),this.kind=e,this.status=r,this.name="LaunchDarklyPollingError",this.recoverable=n}},yt=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 Be;(function(e){e[e.Disabled=0]="Disabled",e[e.Enabled=1]="Enabled"})(Be||(Be={}));var ye;(function(e){e[e.AnalyticsEvents=0]="AnalyticsEvents",e[e.DiagnosticEvent=1]="DiagnosticEvent"})(ye||(ye={}));var ce;(function(e){e[e.Succeeded=0]="Succeeded",e[e.Failed=1]="Failed",e[e.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(ce||(ce={}));function pe(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 lt={s:e=>pe(e),d:e=>Ti(e),i:e=>Mi(e),f:e=>Fi(e),j:e=>pe(e),o:e=>pe(e),O:e=>pe(e),c:()=>""};function wt(...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 lt&&e.length){let o=e.shift();n+=(t=lt[s])==null?void 0:t.call(lt,o)}else s==="%"?n+="%":n+=`%${s}`;i+=2}}else n+=a,i+=1}return e.length&&(n.length&&(n+=" "),n+=e.map(pe).join(" ")),n}return e.map(pe).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.ae=t.formatter,typeof t.destination=="object")this.oe={[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.oe={[M.debug]:a,[M.info]:a,[M.warn]:a,[M.error]:a}}}en(...t){var r;try{return this.ae?(r=this.ae)==null?void 0:r.call(this,...t):wt(...t)}catch(n){return wt(...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.oe)==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:wt});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 ut(e){return e.replace(/\/+$/,"")}function Rt(e){return e.replace(/^\/+/,"").replace(/\?$/,"")}var we=class zr{constructor(t,r,n=zr.DEFAULT_EVENTS,i="/bulk",a="/diagnostic",s=!0,o){this.streaming=ut(t),this.polling=ut(r),this.events=ut(n),this.analyticsEventPath=i,this.diagnosticEventPath=a,this.includeAuthorizationHeader=s,this.payloadFilterKey=o}};we.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 ke(e){return e>=400&&e<500?e===400||e===408||e===429:!0}function Bi(e){return e===413?!0:ke(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 ct(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 je(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(!je(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(!je(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(!je(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?ke(e):!0}var He=(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.bt=[],this.ce=Date.now(),this.ue=this.ce,this.le={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.le,creationDate:this.ce,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.bt.push(n)}createStatsEventAndReset(e,t,r){let n=Date.now(),i={kind:"diagnostic",id:this.le,creationDate:n,dataSinceDate:this.ue,droppedEvents:e,deduplicatedUsers:t,eventsInLastBatch:r,streamInits:this.bt};return this.bt=[],this.ue=n,i}},bt;(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"})(bt||(bt={}));var _i=bt,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.de=nr(r.serviceEndpoints,i,[]),this.cn=nr(r.serviceEndpoints,a,[]),this.z=o,this.un=s}async nt(e,t,r,n){let i={status:ce.Succeeded},a=K(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")),!ke(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.nt(e,this.de,r,!1))}async sendEventData(e,t){let r=e===ye.AnalyticsEvents?this.un.randomUUID():void 0,n=e===ye.AnalyticsEvents?this.de:this.cn;return this.nt(t,n,r,!0)}};function Je(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.it=0,this.rt={},this.st={}}summarizeEvent(e){if(Je(e)&&!e.excludeFromSummaries){this.v||(this.v=e.context);let t=Xi(e),r=this.rt[t],n=this.st[e.key];n||(n=new Set,this.st[e.key]=n),e.context.kinds.forEach(i=>n.add(i)),r?r.increment():this.rt[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.it&&(this.it=e.creationDate)}}getSummary(){var e;let t=Object.values(this.rt).reduce((n,i)=>{let a=n[i.key];a||(a={default:i.default,counters:[],contextKinds:[...this.st[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.it,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.it=0,this.rt={},this.st={}}},ea=class extends Error{constructor(e){super(e),this.name="LaunchDarklyInvalidSDKKeyError"}},ta=class{constructor(e,t){this.k=e,this.t=t,this.W={}}summarizeEvent(e){var t;if(Je(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.W[r];n||(this.W[r]=new _r(!0,this.k),n=this.W[r]),n.summarizeEvent(e)}}getSummaries(){let e=this.W;return this.W={},Object.values(e).map(t=>t.getSummary())}};function Ve(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.at=n,this.I=i,this.ot=[],this.he=0,this.Dt=0,this.St=0,this.kt=!1,this.fe=0,this.It=!1,this.Ct=null,this.hn=e.eventsCapacity,this.t=t.basicConfiguration.logger,this.pe=new Wi(t,r),this.k=new Pi(e.allAttributesPrivate,e.privateAttributes.map(o=>new me(o))),s?this.J=new ta(this.k,this.t):this.J=new _r,a&&this.start()}start(){var e,t;if(((e=this.at)==null?void 0:e.flushInterval)!==void 0&&(this.Ct=setInterval(()=>{var r;(r=this.at)==null||r.flush()},this.at.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.I){let r=this.I.createInitEvent();this.me(r),this.ye=setInterval(()=>{let n=this.I.createStatsEventAndReset(this.Dt,this.St,this.fe);this.Dt=0,this.St=0,this.me(n)},this.e.diagnosticRecordingInterval*1e3)}(t=this.t)==null||t.debug("Started EventProcessor.")}me(e){this.pe.sendEventData(ye.DiagnosticEvent,e)}close(){clearInterval(this.fn),this.Ct&&clearInterval(this.Ct),this.ye&&clearInterval(this.ye)}async flush(){var e;if(this.It)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.ot;if(this.ot=[],ra(this.J))this.J.getSummaries().forEach(r=>{Object.keys(r.features).length&&t.push(r)});else{let r=this.J.getSummary();Object.keys(r.features).length&&t.push(r)}t.length&&(this.fe=t.length,(e=this.t)==null||e.debug("Flushing %d events",t.length),await this.nt(t))}sendEvent(e){var t;if(this.It)return;if(Yi(e)){if(Ve(e.samplingRatio)){let o=K(E({},e),{context:e.context?this.k.filter(e.context):void 0});o.samplingRatio===1&&delete o.samplingRatio,this.ct(o)}return}this.J.summarizeEvent(e);let r=Je(e),n=r&&e.trackEvents||!r,i=this.pn(e),a=Zi(e),s=(t=this.at)==null?void 0:t.processContext(e.context);s||a||(this.St+=1),s&&!a&&this.ct(this.Pt({kind:"index",creationDate:e.creationDate,context:e.context,samplingRatio:1},!1)),n&&Ve(e.samplingRatio)&&this.ct(this.Pt(e,!1)),i&&Ve(e.samplingRatio)&&this.ct(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}}ct(e){var t;this.ot.length<this.hn?(this.ot.push(e),this.kt=!1):(this.kt||(this.kt=!0,(t=this.t)==null||t.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.Dt+=1)}pn(e){return Je(e)&&e.debugEventsUntilDate&&e.debugEventsUntilDate>this.he&&e.debugEventsUntilDate>Date.now()}async nt(e){let t=await this.pe.sendEventData(ye.AnalyticsEvents,e);if(t.status===ce.FailedAndMustShutDown&&(this.It=!0),t.serverTime&&(this.he=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}},kt=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.xt=e}evalEvent(e){var t;return new kt(this.xt,e.context,e.flagKey,e.value,e.defaultVal,e.version,(t=e.variation)!=null?t:void 0,e.trackEvents||e.addExperimentData,e.prereqOfFlagKey,this.xt||e.addExperimentData?e.reason:void 0,e.debugEventsUntilDate,e.excludeFromSummaries,e.samplingRatio)}unknownFlagEvent(e,t,r){return new kt(this.xt,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,ge:"",useSelector(t){return this.ge=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.ge,version:1,id:ir}}),this.mn.processEvents(r)}}}var A={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}`),A):{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",A;case"xfer-changes":return r="changes",i=[],n="partial",A;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}'.`),A}}function c(f){if(r==="inactive")return t==null||t.warn("Received put-object before server-intent was established. Ignoring."),A;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}`),A;let v=a(f.kind,f.object);return v?(i.push({kind:f.kind,key:f.key,version:f.version,object:v}),A):(t==null||t.warn(`Unable to process object for kind: '${f.kind}'`),A)}function h(f){return r==="inactive"?(t==null||t.warn("Received delete-object before server-intent was established. Ignoring."),A):!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}`),A):(i.push({kind:f.kind,key:f.key,version:f.version,deleted:!0}),A)}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(),A;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 x(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 x(f.data);case"heart-beat":return A;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.Lt=new Qr(t,r,n)}addPayloadListener(e){this.Lt.addPayloadListener(e)}removePayloadListener(e){this.Lt.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.Lt.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 Ge(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 ${Ge(e,i)} returned undefined from getHooks.`):s&&s.length>0&&n.push(...s)}catch(s){e.error(`Exception thrown getting hooks for plugin ${Ge(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 ${Ge(e,i)}.`)}})}var q=Object.freeze({__proto__:null,ClientMessages:Gr,DiagnosticsManager:Gi,ErrorKinds:_i,EventFactoryBase:aa,EventProcessor:na,FDv1PayloadAdaptor:sa,InputCustomEvent:Wr,InputEvalEvent:kt,InputIdentifyEvent:Zr,NullEventProcessor:ia,PayloadProcessor:Qr,PayloadStreamReader:la,canonicalize:qe,createProtocolHandler:Yr,initMetadataFromHeaders:ua,isLegacyUser:Fr,isMultiKind:Mr,isSingleKind:Tr,safeGetHooks:ca,safeGetName:Ge,safeRegisterPlugins:da,shouldSample:Ve}),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 Dt(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 x=qr(t,g,y);return{async requestPayload(){let f;try{let v=await n.fetch(x,{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 We(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=We(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(We(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:We(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)},ze={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}}},Da=va(Tt,se(ka));function dr(e,t){return p.Object.is(e)&&e.type===t}var Ea={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(Ea,{is:e=>dr(e,"automatic")}),se(Ca,{is:e=>dr(e,"manual")})),connectionModes:Da},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:K(E({},e.dataSystemDefaults),{connectionModes:ze})}):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=we.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=We(e,a,{},this.logger);Object.entries(s).forEach(([o,l])=>{o!=="logger"&&(this[o]=l)}),this.serviceEndpoints=new we(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:dt,isMultiKind:fr}=q,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(K(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(dt(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."),dt(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=dt(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}=q,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!==we.DEFAULT_EVENTS,eventsCapacity:e.capacity,eventsFlushIntervalMillis:ct(e.flushInterval),reconnectTimeMillis:ct(e.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:ct(e.diagnosticRecordingInterval),allAttributesPrivate:e.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Wa=(e,t,r)=>{if(t.sendEvents&&!t.diagnosticOptOut)return new q.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 q.EventProcessor(K(E({},t),{eventsCapacity:t.capacity}),new qi(e,t,r),n,void 0,i,!1,!0)},vr=class extends q.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})}},Et="_freshness";async function cn(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 cn(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 dn(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 ht=class hn{constructor(){this.container={index:new Array}}static fromJson(t){let r=new hn;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.Ot=t,this.ut=r,this.ve=n,this.T=i,this.g=a,this.t=s,this.gn=o,this.we=Ma(this.Ot)}async init(e,t){this.g.init(e,t),await this.Tt(e)}async upsert(e,t,r){return this.g.upsert(e,t,r)?(await this.Tt(e),!0):!1}async applyChanges(e,t,r){this.g.applyChanges(e,t,r),await this.Tt(e)}async loadCached(e){if(this.ve||this.ut<=0||!this.a.storage)return!1;let t=await dn(this.a.storage,this.a.crypto,this.Ot,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 cn(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.we));if(!t)return this.V=new ht,this.V;try{this.V=ht.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 ht}return this.V}async Tt(e){var t,r;if(this.ve)return;let n=this.gn(),i=await this.wn(),a=await Nt(this.a.crypto,this.Ot,e);this.ut>0&&i.notice(a,n);let s=i.prune(this.ut),o=this.ut<=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.we,i.toJson())),o)return;let l=this.T.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||!je(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.T=es(),this.g=ts(this.T,i),this.lt=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.T,this.g,i,a)}get(e){return this.r&&Object.prototype.hasOwnProperty.call(this.r,e)?this.At(this.r[e]):this.T.get(e)}getAll(){return this.r?E(E({},this.T.getAll()),Object.entries(this.r).reduce((e,[t,r])=>(e[t]=this.At(r),e),{})):this.T.getAll()}presetFlags(e){this.T.init(e)}setBootstrap(e,t){this.g.init(e,t)}async init(e,t){return(await this.lt).init(e,t)}async upsert(e,t,r){return(await this.lt).upsert(e,t,r)}async loadCached(e){return(await this.lt).loadCached(e)}async applyChanges(e,t,r){return(await this.lt).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",fn="beforeEvaluation",gn="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,fn,$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,gn,$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,fn,$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,gn,$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 pn="flag-used",vn="flag-details-changed",mn="flag-detail-changed",yn="client-identity-changed",gs=[pn,vn,mn,yn];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===pn&&n.method(e,t,r)})}onFlagsChanged(e){this.B.forEach(t=>{t.type===vn&&t.method(e)})}onFlagChanged(e,t){this.B.forEach(r=>{r.type===mn&&r.method(e,t)})}onIdentityChanged(e){this.B.forEach(t=>{t.type===yn&&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}=q,ws=5,bs=class{constructor(e,t,r,n,i,a){var s;if(this.sdkKey=e,this.autoEnvAttributes=t,this.platform=r,this.u=za(),this.Mt=15,this.A=new vr(!1),this.dt=new vr(!0),this.Ft=!1,this.Dn=ga(),!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.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,(s=this.e.disableCache)!=null?s:!1,this.e.logger),this.I=Wa(e,this.e,r),this.E=Za(e,this.e,r,this.Ee,this.I),this.emitter=new ms,this.emitter.on("error",(l,u)=>{this.logger.error(`error: ${u}, context: ${JSON.stringify(l)}`)}),this.$.on((l,u,d)=>{this.Sn(u,d);let c=de.toLDContext(l);this.emitter.emit("change",c,u),u.forEach(h=>{this.emitter.emit(`change:${h}`,c)})}),this.dataManager=i(this.$,this.e,this.Ee,this.emitter,this.I);let o=[...this.e.hooks];if(this.environmentMetadata=ys(this.sdkKey,this.platform,this.e),this.e.getImplementationHooks(this.environmentMetadata).forEach(l=>{o.push(l)}),this.R=new us(this.logger,o),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(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.$.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)}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;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.Mt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.Mt} seconds. We recommend a timeout of less than ${this.Mt} seconds.`);let s=this.Dn.execute({before:async()=>{let l=await Ga(e,this.platform);this.autoEnvAttributes===Be.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 x=new Error("Context was unspecified or had no key");return this.emitter.emit("error",d,x),Promise.reject(x)}this.u.set(d,c),(u=this.E)==null||u.sendEvent(this.A.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.promiseWithTimeout(this.initializedPromise,r):(this.initializedPromise||(this.initializedPromise=new Promise(n=>{this.initResolve=n})),this.promiseWithTimeout(this.initializedPromise,r))}promiseWithTimeout(e,t){let r=Hr(t,"waitForInitialization");return Promise.race([e.then(n=>(r.cancel(),n)),r.promise.then(()=>({status:"complete"})).catch(()=>({status:"timeout"}))]).catch(n=>{var i;return(i=this.logger)==null||i.error(n.message),{status:"failed",error:n}})}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.A.customEvent(e,this.u.getContext(),t,r))),this.R.afterTrack({key:e,context:this.u.getUnwrappedContext(),data:t,metricValue:r})}ht(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.A.unknownFlagEvent(e,v,d))),gr(br.FlagNotFound,t)}let{reason:h,value:g,variation:y,prerequisites:x}=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 w=new Ki(`Wrong type "${m}" for feature flag "${e}"; returning default value`);return this.emitter.emit("error",this.u.getUnwrappedContext(),w),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),x==null||x.forEach(v=>{this.ht(v,void 0,this.A)}),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.ht(e,t,this.A));return r}variationDetail(e,t){return this.R.withEvaluation(e,this.u.getUnwrappedContext(),t,()=>this.ht(e,t,this.dt))}H(e,t,r,n){return this.R.withEvaluation(e,this.u.getUnwrappedContext(),t,()=>this.ht(e,t,r,n))}boolVariation(e,t){return this.H(e,t,this.A,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.A,r=>[p.Number.is(r),p.Number.getType()]).value}stringVariation(e,t){return this.H(e,t,this.A,r=>[p.String.is(r),p.String.getType()]).value}boolVariationDetail(e,t){return this.H(e,t,this.dt,r=>[p.Boolean.is(r),p.Boolean.getType()])}numberVariationDetail(e,t){return this.H(e,t,this.dt,r=>[p.Number.is(r),p.Number.getType()])}stringVariationDetail(e,t){return this.H(e,t,this.dt,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.Ft!==e&&(this.Ft=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.Ft||((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 ${q.safeGetName(e,n)}.`)}})}function wn(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}function kr(e){return{polling:()=>({pathGet(t,r){return`/sdk/evalx/${e}/contexts/${He(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}/${He(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 Ds(){return{polling:()=>({pathGet(e,t){return`/sdk/poll/eval/${He(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/${He(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 Es(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:K(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 Dr(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.In=t,this.Cn=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 Ke(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){Dr(this.t);return}let h=JSON.parse(c);try{(t=this.Cn)==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){Dr(this.t);return}let h=c;if(h.status!==void 0&&!ke(h.status)){(n=this.t)==null||n.error(X(c,"polling request")),(i=this.m)==null||i.call(this,new Ke(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.In*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 yt(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 Er(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.Pn=e,this.Rt=t,this.n=r,this.z=n,this.xn=a,this.I=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.ft=Date.now()}Nt(e){this.ft&&this.I&&this.I.recordStreamInit(this.ft,!e,Date.now()-this.ft),this.ft=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 yt(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.Pn}):e={};let t=this.z.createEventSource(this.Ln,K(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 yt(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){Er(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 Ke(T.InvalidData,"Malformed JSON data in ping polling response"))}}catch(u){if(this.h){Er(this.t);return}let d=u;(l=this.m)==null||l.call(this,new Ke(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.G=Es(t,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(e){this.Tn=e}createPollingProcessor(e,t,r,n,i){let a=new Cs(r,this.config.pollInterval,async s=>{await this.G.handlePut(t,s),n==null||n()},s=>{this.emitter.emit("error",e,s),this.G.handlePollingError(s),i==null||i(s)},this.logger);this.updateProcessor=this.Ie(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.Tn)==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.G.handleStreamingError(o),i==null||i(o)},this.logger);this.updateProcessor=this.Ie(s,this.dataSourceStatusManager)}createStreamListeners(e,t){let r=new Map;return r.set("put",{deserializeData:JSON.parse,processJson:async n=>{await this.G.handlePut(e,n),t==null||t()}}),r.set("patch",{deserializeData:JSON.parse,processJson:async n=>{this.G.handlePatch(e,n)}}),r.set("delete",{deserializeData:JSON.parse,processJson:async n=>{this.G.handleDelete(e,n)}}),r}Ie(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 Le(e,t,r,n){return{type:"changeSet",payload:e,fdv1Fallback:t,environmentId:r,freshness:n}}function N(e,t){return{type:"status",state:"interrupted",errorInfo:e,fdv1Fallback:t}}function ee(){return{type:"status",state:"shutdown",fdv1Fallback:!1}}function Se(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 ve(e){return{kind:T.ErrorResponse,message:`Unexpected status code: ${e}`,statusCode:e,time:Date.now()}}function _e(e){return{kind:T.NetworkError,message:e,time:Date.now()}}function he(e){return{kind:T.InvalidData,message:e,time:Date.now()}}function Re(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"),N(Re("No storage available"),!1);let s=await dn(t,r,n,i,a);if(!s)return a==null||a.debug("Cache miss for context"),N(Re("Cache miss"),!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"),Le(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 Dn(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),x=await n.fetch(y,{method:d,headers:l,body:u}),f=x.status===304?null:await x.text();return{status:x.status,headers:x.headers,body:f}}}}function En(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:K(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=q.createProtocolHandler({"flag-eval":En},n),a;if(e.forEach(o=>{if(a)return;let l=i.processEvent(o);switch(l.type){case"payload":a=Le(l.payload,t,r);break;case"goodbye":a=kn(l.reason,t);break;case"serverError":{let u=Re(l.reason);n==null||n.error(`Server error during polling: ${l.reason}`),a=N(u,t);break}case"error":{if(l.kind==="MISSING_PAYLOAD"||l.kind==="PROTOCOL_ERROR"){let u=he(l.message);n==null||n.warn(`Protocol error during polling: ${l.message}`),a=N(u,t)}else n==null||n.warn(l.message);break}}}),a)return a;let s=Re("Unexpected end of polling response");return n==null||n.error("Unexpected end of polling response"),N(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 Le({version:0,type:"none",updates:[]},i,a);if(s.status<200||s.status>=300){let l=ve(s.status);return r==null||r.error(`Polling request failed with HTTP error: ${s.status}`),s.status<=0||ke(s.status)?N(l,i):Se(l,i)}if(!s.body){let l=he("Empty response body");return r==null||r.error("Polling request received empty response body"),N(l,i)}let o;try{o=JSON.parse(s.body)}catch(l){let u=he("Malformed JSON data in polling response");return r==null||r.error("Polling request received malformed data"),N(u,i)}if(!Array.isArray(o.events)){let l=he("Invalid polling response: missing or invalid events array");return r==null||r.error("Polling response does not contain a valid events array"),N(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=_e(o);return N(l,i)}}var ft=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===ft)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)])===ft))return ee()}let o=s;return Se(o.errorInfo,o.fdv1Fallback)},close(){n==null||n(ft),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=q.createProtocolHandler({"flag-eval":En},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(Le(f.payload,o));break;case"goodbye":t.put(kn(f.reason,o));break;case"serverError":t.put(N(Re(f.reason),o));break;case"error":(f.kind==="MISSING_PAYLOAD"||f.kind==="PROTOCOL_ERROR")&&t.put(N(he(f.message),o));break}}function g(f){var v,m,w,C,I,b;return((v=f.headers)==null?void 0:v["x-ld-fd-fallback"])==="true"?(o=!0,c(!1),t.put(Se(ve((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(N(ve((b=f.status)!=null?b:0),o)),!0):((w=e.logger)==null||w.error(X(f,"streaming request")),c(!1),t.put(Se(ve((C=f.status)!=null?C:0),o)),!1)}function y(f){Bs.forEach(v=>{f.addEventListener(v,m=>{var w,C,I,b,S;if(u){(w=e.logger)==null||w.debug(`Received ${v} event after processor was closed. Skipping.`);return}if(!(m!=null&&m.data)){v!=="error"&&((C=e.logger)==null||C.warn(`Event from EventStream missing data for "${v}".`));return}(I=e.logger)==null||I.debug(`Received ${v} event`);let k;try{k=JSON.parse(m.data)}catch(j){(b=e.logger)==null||b.error(`Stream received data that was unable to be parsed in "${v}" message`),(S=e.logger)==null||S.debug(`Data follows: ${m.data}`),t.put(N(he("Malformed JSON in EventStream"),o));return}let $=r.processEvent({event:v,data:k});h($)})})}function x(f){f.addEventListener("ping",async()=>{var v,m,w,C,I,b,S;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){(w=e.logger)==null||w.warn("Ping event received but no ping handler configured.");return}try{let k=await e.pingHandler.handlePing();if(u){(C=e.logger)==null||C.debug("Ping completed after processor was closed. Skipping processing.");return}t.put(k)}catch(k){if(u)return;(b=e.logger)==null||b.error(`Error handling ping: ${(I=k==null?void 0:k.message)!=null?I:k}`),t.put(N(_e((S=k==null?void 0:k.message)!=null?S:"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),x(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(N(_e((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 we((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 Dn(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:he("Malformed data in FDv1 polling response"),fdv1Fallback:!1}),u(c);return}n.put(Le(g,!1))}catch(h){if(o)return;let g=h;if(g.status!==void 0&&!ke(g.status)){r==null||r.error(X(h,"FDv1 polling request")),o=!0,i==null||i(Se(ve(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?ve(g.status):_e(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 x(){u||(u=!0,h==null||h(),h=void 0,g=void 0)}function f(b){n(b.payload),i.requestStateUpdate("VALID")}function v(b){b.errorInfo&&i.reportError(b.errorInfo.kind,b.errorInfo.message,b.errorInfo.statusCode,b.state==="interrupted")}function m(b){return b.fdv1Fallback&&y.hasFDv1Fallback()?(y.fdv1Fallback(),!0):!1}async function w(){for(var b,S;!d;){let k=y.getNextInitializerAndSetActive();if(k===void 0)break;let $=await k.run();if(d)return;if($.type==="changeSet"){if(f($),m($)){c=!0;break}if($.payload.state){x();return}c=!0}else if($.type==="status"){switch($.state){case"interrupted":case"terminal_error":s==null||s.warn(`Initializer failed: ${(S=(b=$.errorInfo)==null?void 0:b.message)!=null?S:"unknown error"}`),v($);break;case"shutdown":return}m($)}}c&&x()}async function C(){for(var b,S,k,$;!d;){let j=y.getNextAvailableSynchronizerAndSetActive();if(j===void 0){u||(g==null||g(new Error("All data sources exhausted without receiving data.")),h=void 0,g=void 0);return}let B=eo(y.getAvailableSynchronizerCount(),y.isPrimeSynchronizer(),o,l);B.promise&&(s==null||s.debug("Fallback condition active for current synchronizer."));let re=!0;try{for(;!d&&re;){let oe=[j.next().then(O=>({source:"sync",value:O}))];B.promise!==void 0&&oe.push(B.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(B.inform(O),O.type==="changeSet")f(O),u||x();else if(O.type==="status")switch(O.state){case"interrupted":s==null||s.warn(`Synchronizer interrupted: ${(S=(b=O.errorInfo)==null?void 0:b.message)!=null?S:"unknown error"}`),v(O);break;case"terminal_error":s==null||s.error(`Synchronizer terminal error: ${($=(k=O.errorInfo)==null?void 0:k.message)!=null?$:"unknown error"}`),v(O),y.blockCurrentSynchronizer(),re=!1;break;case"shutdown":return;case"goodbye":break;default:break}m(O)&&(re=!1)}}}finally{B.close()}}}async function I(){if(t.length===0&&r.length===0){i.requestStateUpdate("VALID"),x();return}await w(),d||await C()}return{start(){return new Promise((b,S)=>{h=b,g=S,i.requestStateUpdate("INITIALIZING"),I().then(()=>{u||(g==null||g(new Error("Data source closed before initialization completed.")),h=void 0,g=void 0)}).catch(k=>{u?s==null||s.error(`Orchestration error: ${k}`):(g==null||g(k instanceof Error?k:new Error(String(k))),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 U="[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:x}=e,{logger:f}=i,v=bn(s),m=Ds(),w=(t=i.dataSystem)!=null&&t.connectionModes?E(E({},d),i.dataSystem.connectionModes):d,C,I=l,b=l,S,k,$,j,B=!1,re=!1,oe=!1,le,O,rt,Ut=!1,V,ae,Me="available",Ee="foreground";function qt(D){return w[D]}function _n(){return{lifecycle:Ee,networkAvailable:Me==="available",foregroundMode:b,backgroundMode:u!=null?u:"offline"}}function Kt(){return O!==void 0?O:$s(o,_n())}function Bt(){return rt===!0?"streaming":rt===!1?l==="streaming"?"one-shot":l:Ut?"streaming":l}function nt(){b=Bt(),k==null||k.setRequestedMode(b)}function Wn(D,R,W){var H,Z,Y,Fe,Ce;let Ne=[];W&&D.initializers.filter(P=>!(re&&P.type==="cache")).forEach(P=>{let ue=c.createInitializerFactory(P,R);ue?Ne.push(ue):f.warn(`${U} Unsupported initializer type '${P.type}'. It will be skipped.`)});let fe=[];if(D.synchronizers.forEach(P=>{let ue=c.createSynchronizerSlot(P,R);ue?fe.push(ue):f.warn(`${U} Unsupported synchronizer type '${P.type}'. It will be skipped.`)}),g&&fe.length>0){let P=D.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 we((Fe=P.endpoints.streamingBaseUri)!=null?Fe:R.serviceEndpoints.streaming,(Ce=P.endpoints.pollingBaseUri)!=null?Ce:R.serviceEndpoints.polling,R.serviceEndpoints.events,R.serviceEndpoints.analyticsEventPath,R.serviceEndpoints.diagnosticEventPath,R.serviceEndpoints.includeAuthorizationHeader,R.serviceEndpoints.payloadFilterKey):R.serviceEndpoints,Xn=()=>Dt(R.plainContextString,Qn,g.polling(),R.requests,R.encoding,R.baseHeaders,R.queryParams,i.withReasons,i.useReport),ei=()=>Ys(Xn(),ue,f);fe.push(Ct(ei,{isFDv1Fallback:!0}))}return{initializerFactories:Ne,synchronizerSlots:fe}}function Zn(D){var R;f.debug(`${U} dataCallback: type=${D.type}, updates=${D.updates.length}, state=${D.state}`),C=D.state;let W=$;if(!W){f.warn(`${U} dataCallback called without an identified context.`);return}let H=As((R=D.updates)!=null?R:[]);n.applyChanges(W,H,D.type).catch(Z=>{f.warn(`${U} Failed to persist flag cache: ${Z}`)})}function it(D,R){if(!j){f.warn(`${U} Cannot create data source without factory context.`);return}let W=qt(D),{initializerFactories:H,synchronizerSlots:Z}=Wn(W,j,R);if(I=D,H.length===0&&Z.length===0){f.debug(`${U} Mode '${D}' has no sources. No data source created.`),!B&&V&&(B=!0,V(),V=void 0,ae=void 0);return}S=to({initializerFactories:H,synchronizerSlots:Z,dataCallback:Zn,statusManager:v,selectorGetter:()=>C,logger:f,fallbackTimeoutMs:y,recoveryTimeoutMs:x}),S.start().then(()=>{B=!0,V&&(V(),V=void 0,ae=void 0)}).catch(Y=>{ae&&(ae(Y instanceof Error?Y:new Error(String(Y))),V=void 0,ae=void 0)})}function Yn(D){if(oe||!j)return;Me=D.networkState,Ee=D.lifecycleState,b=D.requestedMode;let R=Kt();if(R===I){f.debug(`${U} Reconcile: mode unchanged (${R}). No action.`);return}f.debug(`${U} Reconcile: mode switching from '${I}' to '${R}'.`),S==null||S.close(),S=void 0,it(R,!C)}return{get configuredForegroundMode(){return l},async identify(D,R,W,H){if(oe){f.debug(`${U} Identify called after close.`);return}S==null||S.close(),S=void 0,k==null||k.close(),k=void 0,C=void 0,B=!1,re=!1,$=W,V=D,ae=R;let Z=JSON.stringify(de.toLDContext(W)),Y=h(H);i.withReasons&&Y.push({key:"withReasons",value:"true"});let Fe=m.streaming(),Ce=m.polling(),Ne=Dn(Z,i.serviceEndpoints,Ce,r.requests,r.encoding,a,Y),fe=await ln(r.crypto,e.credential);if(oe){f.debug(`${U} Identify aborted: closed during async setup.`);return}j={requestor:Ne,requests:r.requests,encoding:r.encoding,serviceEndpoints:i.serviceEndpoints,baseHeaders:a,queryParams:Y,plainContextString:Z,logger:f,polling:{paths:Ce,intervalSeconds:i.pollInterval},streaming:{paths:Fe,initialReconnectDelaySeconds:i.streamInitialReconnectDelay},storage:r.storage,crypto:r.crypto,environmentNamespace:fe,context:W},b=Bt();let P=Kt();f.debug(`${U} Identify: initial mode resolved to '${P}'.`),re=(H==null?void 0:H.bootstrap)!==void 0,re?(B=!0,v.requestStateUpdate("VALID"),V==null||V(),V=void 0,ae=void 0,qt(P).synchronizers.length>0&&it(P,!1)):it(P,!0),k=no({initialState:{networkState:Me,lifecycleState:Ee,requestedMode:b},onReconcile:Yn})},close(){oe=!0,S==null||S.close(),S=void 0,k==null||k.close(),k=void 0,V=void 0,ae=void 0},setNetworkState(D){Me=D,k==null||k.setNetworkState(D)},setLifecycleState(D){D==="background"&&Ee!=="background"&&(le==null||le()),Ee=D,k==null||k.setLifecycleState(D)},setConnectionMode(D){O=D,D!==void 0?k==null||k.setRequestedMode(D):nt()},getCurrentMode(){return I},setFlushCallback(D){le=D},setForcedStreaming(D){rt=D,nt()},setAutomaticStreamingState(D){Ut=D,nt()}}}function Ze(){return typeof document!==void 0}function zt(){return typeof window!==void 0}function In(e,t,r){return Ze()?(document.addEventListener(e,t,r),()=>{document.removeEventListener(e,t,r)}):()=>{}}function On(e,t,r){return Ze()?(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 Ze()?document.visibilityState:"visibile"}function uo(e){if(Ze())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}C(e,...t){this.logger.debug(`${co} ${e}`,...t)}async identify(e,t,r,n){if(this.closed){this.C("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.An(r,i,e):(await this.flagManager.loadCached(r)&&this.C("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Mn(r,e,t)),this.Ce(),this.jt()}async Fn(e){let t=JSON.stringify(de.toLDContext(e)),r=Dt(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.C(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)}}An(e,t,r){let{bootstrapParsed:n}=t;n||(n=wn(this.logger,t.bootstrap)),this.flagManager.setBootstrap(e,n),this.dataSourceStatusManager.requestStateUpdate(sr.Valid),this.C("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.C(`Updating streaming state. forced(${this.Z}) automatic(${this.Ut})`),e?this.$n():this.Ce()}Ce(){var e;this.updateProcessor&&this.C("Stopping update processor."),(e=this.updateProcessor)==null||e.close(),this.updateProcessor=void 0}$n(){if(this.updateProcessor){this.C("Update processor already active. Not changing state.");return}if(!this.context){this.C("Context not set, not starting update processor.");return}this.C("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=Dt(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 gt(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(`^${gt(e.url)}/?$`).test(t);case"canonical":return new RegExp(`^${gt(e.url)}/?$`).test(i);case"substring":return new RegExp(`.*${gt(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.Pe=In("click",a)}}close(){var e;(e=this.Pe)==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.pt=[],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.pt&&this.pt.length&&(this.Bt=new vo(this.pt,t=>{this.Un(Ie(),t)})))}async Nn(){try{let e=await this.z.fetch(this.X);this.pt=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:[]},Do={fetchGoals:p.Boolean,eventUrlTransformer:p.Function,streaming:p.Boolean,plugins:p.createTypeArray("LDPlugin",{})};function Eo(e){var t;let r=E({},e);return(t=r.flushInterval)!=null||(r.flushInterval=ko),r}function Co(e){let t=Eo(e);return Object.keys(Pn).forEach(r=>{delete t[r]}),t}function xo(e,t){let r=E({},Pn);return Object.entries(Do).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.Te=[],t){case"sha1":this.Gt="SHA-1";break;case"sha256":this.Gt="SHA-256";break;default:throw new Error(`Algorithm is not supported ${t}`)}}async asyncDigest(e){let t=this.Te.join(""),r=new TextEncoder().encode(t),n=await this.jn.subtle.digest(this.Gt,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.Te.push(e),this}},Ro={start:0,end:3},Io={start:4,end:5},pt={start:6,end:7},vt={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 ge(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[vt.start]=(e[vt.start]|128)&191,e[pt.start]=e[pt.start]&15|64,`${ge(e,Ro)}-${ge(e,Io)}-${ge(e,pt)}-${ge(e,vt)}${ge(e,Oo)}-${ge(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.5.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.Ae=t.errorFilter,this.qt=t.urlBuilder,this.Me()}Me(){this.qt&&(this.X=this.qt()),this.q=new EventSource(this.X),this.q.onopen=()=>{var e;this.x.success(),(e=this.onopen)==null||e.call(this)},this.q.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.q)==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.q)==null||i.addEventListener(e,t)}close(){var e,t;clearTimeout(this.Kt),this.Kt=void 0,(e=this.q)==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.Ae(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){var i,a,s,o,l;let{logger:u,debug:d}=r,c=u!=null?u:new Nr({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:d?"debug":"info"}),h=(i=r.baseUri)!=null?i:"https://clientsdk.launchdarkly.com",g=n!=null?n:new Ko(c,r),y=xo(r,c),x=Co(K(E({},r),{logger:c})),{eventUrlTransformer:f}=y,v=kr(e),m=(w,C,I,b,S)=>C.dataSystem?io({platform:g,flagManager:w,credential:e,config:C,baseHeaders:I,emitter:b,transitionTable:Ls,foregroundMode:Ra(C.dataSystem,hr),backgroundMode:void 0,modeTable:ze,sourceFactoryProvider:Ws(),fdv1Endpoints:kr(e),buildQueryParams:k=>{let $=[{key:"auth",value:e}],j=k;return j!=null&&j.hash&&$.push({key:"h",value:j.hash}),$}}):new ho(g,w,e,C,y,v.polling,v.streaming,I,b,S);super(e,t,g,x,m,{getLegacyStorageKeys:()=>Uo().filter(w=>w.startsWith(`ld:${e}:`)),analyticsEventPath:`/events/bulk/${e}`,diagnosticEventPath:`/events/diagnostic/${e}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",dataSystemDefaults:hr,trackEventModifier:w=>new q.InputCustomEvent(w.context,w.key,w.data,w.metricValue,w.samplingRatio,f(Ie())),getImplementationHooks:w=>q.safeGetHooks(c,w,y.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),y.streaming!==void 0&&((s=(a=this.dataManager).setForcedStreaming)==null||s.call(a,y.streaming)),(l=(o=this.dataManager).setFlushCallback)==null||l.call(o,()=>this.flush()),this.Jt=y.plugins,y.fetchGoals&&(this.Wt=new wo(e,g.requests,h,w=>{c.error(w.message)},(w,C)=>{let I=this.getInternalContext();if(!I)return;let b=f(w);bo(C)?this.sendEvent({kind:"click",url:b,samplingRatio:1,key:C.key,creationDate:Date.now(),context:I,selector:C.selector}):this.sendEvent({kind:"pageview",url:b,samplingRatio:1,key:C.key,creationDate:Date.now(),context:I})}),this.Wt.initialize(),y.automaticBackgroundHandling&&fo(()=>this.flush()))}registerPlugins(e){q.safeRegisterPlugins(this.logger,this.environmentMetadata,e,this.Jt||[]);let t=this.getDebugOverrides();t&&ks(this.logger,t,this.Jt||[])}setInitialContext(e){this.Yt=e}async identify(e,t){return super.identify(e,t)}async identifyResult(e,t){var r;if(!this.Q)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=E({},t);(t==null?void 0:t.sheddable)===void 0&&(n.sheddable=!0);let i=await super.identifyResult(e,n);return(r=this.Wt)==null||r.startTracking(),i}start(e){var t,r;if(this.initializeResult)return Promise.resolve(this.initializeResult);if(this.Q)return this.Q;if(!this.Yt)return this.logger.error("Initial context not set"),Promise.resolve({status:"failed",error:new Error("Initial context not set")});let n=K(E({},(t=e==null?void 0:e.identifyOptions)!=null?t:{}),{sheddable:!1});if(e!=null&&e.bootstrap&&!n.bootstrap&&(n.bootstrap=e.bootstrap),n!=null&&n.bootstrap)try{n.bootstrapParsed||(n.bootstrapParsed=wn(this.logger,n.bootstrap)),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.Q=this.promiseWithTimeout(this.initializedPromise,(r=e==null?void 0:e.timeout)!=null?r:5),this.identifyResult(this.Yt,n),this.Q}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 ze)){this.logger.warn(`setConnectionMode called with invalid mode '${e}'. Valid modes: ${Object.keys(ze).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,r,n,i);a.setInitialContext(t);let 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,Be.Disabled,r)}function Jo(e){return Object.fromEntries(Object.entries(e).filter(([t])=>!t.startsWith("$")))}function Ye(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 Qe(e,t,r={}){var f,v;if(typeof window=="undefined")return Ye();let x=r,{useCamelCaseFlagKeys:n=!0}=x,i=Gt(x,["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.0"}),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(w=>w(m))}return ne(J({},s),{start:m=>u?s.start(m):(u=!0,m!=null&&m.bootstrap&&(l=!0),s.start(m).then(w=>(o=w.status,g=w,d||(d=!0,y()),h.forEach(C=>C(w)),w))),identify:(m,w)=>s.identify(m,w).then(C=>(C.status==="completed"&&y(),C)),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 Te(e,t){var i;let r=(i=t==null?void 0:t.Provider)!=null?i:z.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 Xe(e,t,r){let{deferInitialization:n,startOptions:i,reactContext:a,ldOptions:s,bootstrap:o}=r!=null?r:{},l=Qe(e,t,s);if(!n){let u=o?ne(J({},i),{bootstrap:o}):i;l.start(u)}return Te(l,a)}var et=Wt(require("react"),1);function Tn({clientSideId:e,context:t,bootstrap:r,options:n,reactContext:i,children:a}){let s=(0,et.useRef)(null);s.current===null&&(typeof window=="undefined"?s.current=Te(Ye(r),i):s.current=Xe(e,t,ne(J({},n),{bootstrap:r,reactContext:i})));let o=s.current;return et.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:z);(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:z);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:z);return t}var te=require("react");function _(e,t,r,n,i){let{client:a,context:s}=(0,te.useContext)(n!=null?n:z),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 tt(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,tt)}function Hn(e,t,r){return _(e,t,(n,i,a)=>n.stringVariationDetail(i,a),r,tt)}function Jn(e,t,r){return _(e,t,(n,i,a)=>n.numberVariationDetail(i,a),r,tt)}function Gn(e,t,r){return _(e,t,(n,i,a)=>n.jsonVariationDetail(i,a),r,tt)}0&&(module.exports={LDIsomorphicClientProvider,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});