@launchdarkly/js-client-sdk 0.5.2 → 0.6.0

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/compat.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var pt=Object.defineProperty,Ai=Object.defineProperties,Oi=Object.getOwnPropertyDescriptor,Ti=Object.getOwnPropertyDescriptors,$i=Object.getOwnPropertyNames,gt=Object.getOwnPropertySymbols;var Vt=Object.prototype.hasOwnProperty,Ue=Object.prototype.propertyIsEnumerable;var Fe=(i,t,e)=>t in i?pt(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,g=(i,t)=>{for(var e in t||(t={}))Vt.call(t,e)&&Fe(i,e,t[e]);if(gt)for(var e of gt(t))Ue.call(t,e)&&Fe(i,e,t[e]);return i},D=(i,t)=>Ai(i,Ti(t));var jt=(i,t)=>{var e={};for(var n in i)Vt.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&gt)for(var n of gt(i))t.indexOf(n)<0&&Ue.call(i,n)&&(e[n]=i[n]);return e};var Ni=(i,t)=>{for(var e in t)pt(i,e,{get:t[e],enumerable:!0})},Ri=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of $i(t))!Vt.call(i,r)&&r!==e&&pt(i,r,{get:()=>t[r],enumerable:!(n=Oi(t,r))||n.enumerable});return i};var Ii=i=>Ri(pt({},"__esModule",{value:!0}),i);var lr={};Ni(lr,{basicLogger:()=>or,initialize:()=>cr});module.exports=Ii(lr);function Pi(i){return`/${i.replace(/~/g,"~0").replace(/\//g,"~1")}`}function _e(i){return i.indexOf("~")?i.replace(/~1/g,"/").replace(/~0/g,"~"):i}function Mi(i){return(i.startsWith("/")?i.substring(1):i).split("/").map(e=>_e(e))}function Fi(i){return!i.startsWith("/")}function Ui(i){return!i.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var A=class{constructor(t,e=!1){if(e){let n=t;this.l=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?Pi(n):n}else{if(this.redactionName=t,t===""||t==="/"||!Ui(t)){this.isValid=!1,this.l=[];return}Fi(t)?this.l=[t]:t.indexOf("/",1)<0?this.l=[_e(t.slice(1))]:this.l=Mi(t),this.l[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{l:e,isValid:n}=this;if(!n)return;let r=t;for(let s=0;s<e.length;s+=1){let a=e[s];if(r!=null&&Object.prototype.hasOwnProperty.call(r,a)&&typeof r=="object"&&!Array.isArray(r))r=r[a];else return}return r}getComponent(t){return this.l[t]}get depth(){return this.l.length}get isKind(){return this.l.length===1&&this.l[0]==="kind"}compare(t){return this.depth===t.depth&&this.l.every((e,n)=>e===t.getComponent(n))}};A.InvalidReference=new A("");var _t=class{is(t){if(Array.isArray(t))return!1;let n=typeof t;return n==="function"||n==="object"}getType(){return"factory method or object"}},O=class{constructor(t,e){this.pt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.pt}},vt=class{constructor(t,e){this.pt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?t.length>0?t.every(e=>typeof e===this.typeOf):!0:!1}getType(){return this.pt}},G=class extends O{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},Et=class extends O{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},Kt=class{is(t){return typeof t=="function"}getType(){return"function"}},Gt=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},Vi=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,qt=class{is(t){return typeof t=="number"||typeof t=="string"&&Vi.test(t)}getType(){return"date"}},Jt=class extends Et{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},u=class{static createTypeArray(t,e){return new vt(t,e)}static numberWithMin(t){return new G(t)}static stringMatchingRegex(t){return new Et(t)}};u.String=new O("string","");u.Number=new O("number",0);u.ObjectOrFactory=new _t;u.Object=new O("object",{});u.StringArray=new vt("string[]","");u.Boolean=new O("boolean",!0);u.Function=new Kt;u.Date=new qt;u.Kind=new Jt;u.NullableBoolean=new Gt;function Ke(i){return"kind"in i?u.String.is(i.kind)&&i.kind!=="multi":!1}function Ge(i){return"kind"in i?u.String.is(i.kind)&&i.kind==="multi":!1}function qe(i){return!("kind"in i)||i.kind===null||i.kind===void 0}var zt="user";function Ve(i){return i.includes("%")||i.includes(":")?i.replace(/%/g,"%25").replace(/:/g,"%3A"):i}function ji(i){return i&&u.Object.is(i)}function je(i){return u.Kind.is(i)}function Be(i){return u.String.is(i)&&i!==""}function Bt(i,t=!1){return i?i.map(e=>new A(e,t)):[]}function Bi(i){return i!=null}function Hi(i){let t=D(g({},i.custom||[]),{kind:"user",key:String(i.key)});if(Bi(i.anonymous)){let e=!!i.anonymous;delete t.anonymous,t.anonymous=e}return i.name!==null&&i.name!==void 0&&(t.name=i.name),i.ip!==null&&i.ip!==void 0&&(t.ip=i.ip),i.firstName!==null&&i.firstName!==void 0&&(t.firstName=i.firstName),i.lastName!==null&&i.lastName!==void 0&&(t.lastName=i.lastName),i.email!==null&&i.email!==void 0&&(t.email=i.email),i.avatar!==null&&i.avatar!==void 0&&(t.avatar=i.avatar),i.country!==null&&i.country!==void 0&&(t.country=i.country),i.privateAttributeNames!==null&&i.privateAttributeNames!==void 0&&(t._meta={privateAttributes:i.privateAttributeNames}),t}var k=class i{constructor(t,e,n){this.w=!1,this.W=!1,this.Jt=!1,this.L={},this.kind=e,this.valid=t,this.message=n}static p(t,e){return new i(!1,t,e)}static $e(t,e){if(!(!e||!t.isValid))return t.depth===1&&t.getComponent(0)==="anonymous"?!!(e!=null&&e.anonymous):t.get(e)}zt(t){if(this.w)return this.L[t];if(this.kind===t)return this.C}static Ne(t){let e=Object.keys(t).filter(c=>c!=="kind"),n=e.every(je);if(!e.length)return i.p("multi","A multi-kind context must contain at least one kind");if(!n)return i.p("multi","Context contains invalid kinds");let r={},s=!0,a=e.reduce((c,l)=>{var d;let h=t[l];return ji(h)?(c[l]=h,r[l]=Bt((d=h._meta)==null?void 0:d.privateAttributes)):s=!1,c},{});if(!s)return i.p("multi","Context contained contexts that were not objects");if(!Object.values(a).every(c=>Be(c.key)))return i.p("multi","Context contained invalid keys");if(e.length===1){let c=e[0],l=new i(!0,c);return l.C=D(g({},a[c]),{kind:c}),l.Y=r,l.W=c==="user",l}let o=new i(!0,t.kind);return o.L=a,o.Y=r,o.w=!0,o}static Re(t){var c;let{key:e,kind:n}=t,r=je(n),s=Be(e);if(!r)return i.p(n!=null?n:"unknown","The kind was not valid for the context");if(!s)return i.p(n,"The key for the context was not valid");let a=Bt((c=t._meta)==null?void 0:c.privateAttributes),o=new i(!0,n);return o.W=n==="user",o.C=t,o.Y={[n]:a},o}static Ie(t){if(!(t.key!==void 0&&t.key!==null))return i.p("user","The key for the context was not valid");let n=new i(!0,"user");return n.W=!0,n.Jt=!0,n.C=Hi(t),n.Y={user:Bt(t.privateAttributeNames,!0)},n}static fromLDContext(t){return t?Ke(t)?i.Re(t):Ge(t)?i.Ne(t):qe(t)?i.Ie(t):i.p("unknown","Context was not of a valid kind"):i.p("unknown","No context specified. Returning default value")}static toLDContext(t){if(!t.valid)return;let e=t.getContexts();if(!t.w)return e[0][1];let n={kind:"multi"};return e.forEach(r=>{let s=r[0],a=r[1];n[s]=a}),n}valueForKind(t,e=zt){return t.isKind?this.kinds:i.$e(t,this.zt(e))}key(t=zt){var e;return(e=this.zt(t))==null?void 0:e.key}get isMultiKind(){return this.w}get canonicalKey(){return this.W?this.C.key:this.w?Object.keys(this.L).sort().map(t=>`${t}:${Ve(this.L[t].key)}`).join(":"):`${this.kind}:${Ve(this.C.key)}`}get kinds(){return this.w?Object.keys(this.L):[this.kind]}get kindsAndKeys(){return this.w?Object.entries(this.L).reduce((t,[e,n])=>(t[e]=n.key,t),{}):{[this.kind]:this.C.key}}privateAttributes(t){var e;return((e=this.Y)==null?void 0:e[t])||[]}getContexts(){return this.w?Object.entries(this.L):[[this.kind,this.C]]}get legacy(){return this.Jt}};k.UserKind=zt;var _i=["key","kind","_meta","anonymous"].map(i=>new A(i,!0)),Ki=["name","ip","firstName","lastName","email","avatar","country"];function Gi(i,t){return i.depth===t.length&&t.every((e,n)=>e===i.getComponent(n))}function qi(i,t){let e=[],n={},r=[];for(e.push(...Object.keys(i).map(s=>({key:s,ptr:[s],source:i,parent:n,visited:[i]})));e.length;){let s=e.pop(),a=t.find(o=>Gi(o,s.ptr));if(a)r.push(a.redactionName);else{let o=s.source[s.key];o===null?s.parent[s.key]=o:Array.isArray(o)?s.parent[s.key]=[...o]:typeof o=="object"?s.visited.includes(o)||(s.parent[s.key]={},e.push(...Object.keys(o).map(c=>({key:c,ptr:[...s.ptr,c],source:o,parent:s.parent[s.key],visited:[...s.visited,o]})))):s.parent[s.key]=o}}return{cloned:n,excluded:r.sort()}}var Wt=class{constructor(t,e){this.Pe=t,this.Me=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.Wt(t,n[0][1],n[0][0],e);let r={kind:"multi"};return n.forEach(([s,a])=>{r[s]=this.Wt(t,a,s,e)}),r}Fe(t,e,n,r){return(r?Object.keys(e).map(s=>new A(s,!0)):[...this.Me,...t.privateAttributes(n)]).filter(s=>!_i.some(a=>a.compare(s)))}Wt(t,e,n,r){let s=this.Pe||r&&e.anonymous===!0,{cloned:a,excluded:o}=qi(e,this.Fe(t,e,n,s));return t.legacy&&Ki.forEach(c=>{c in a&&(a[c]=String(a[c]))}),o.length&&(a._meta||(a._meta={}),a._meta.redactedAttributes=o),a._meta&&(delete a._meta.privateAttributes,Object.keys(a._meta).length===0&&delete a._meta),a}},E;(function(i){i.Unknown="UNKNOWN",i.NetworkError="NETWORK_ERROR",i.ErrorResponse="ERROR_RESPONSE",i.InvalidData="INVALID_DATA"})(E||(E={}));var R=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=r}},U=class extends Error{constructor(t,e,n,r=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=r}},V;(function(i){i[i.Disabled=0]="Disabled",i[i.Enabled=1]="Enabled"})(V||(V={}));var j;(function(i){i[i.AnalyticsEvents=0]="AnalyticsEvents",i[i.DiagnosticEvent=1]="DiagnosticEvent"})(j||(j={}));var N;(function(i){i[i.Succeeded=0]="Succeeded",i[i.Failed=1]="Failed",i[i.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(N||(N={}));function F(i){if(typeof i=="string")return i;if(i===void 0)return"undefined";if(i===null)return"null";if(Object.prototype.hasOwnProperty.call(i,"toString"))try{return i.toString()}catch(t){}if(typeof i=="bigint")return`${i}n`;try{return JSON.stringify(i)}catch(t){return t instanceof TypeError&&t.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}function Ji(i){return typeof i=="symbol"?"NaN":typeof i=="bigint"?`${i}n`:String(Number(i))}function zi(i){return typeof i=="symbol"?"NaN":typeof i=="bigint"?`${i}n`:String(parseInt(i,10))}function Wi(i){return typeof i=="symbol"?"NaN":String(parseFloat(i))}var mt={s:i=>F(i),d:i=>Ji(i),i:i=>zi(i),f:i=>Wi(i),j:i=>F(i),o:i=>F(i),O:i=>F(i),c:()=>""};function Yt(...i){var e;let t=i.shift();if(u.String.is(t)){let n="",r=0;for(;r<t.length;){let s=t.charAt(r);if(s==="%"){if(r+1<t.length){let o=t.charAt(r+1);if(o in mt&&i.length){let c=i.shift();n+=(e=mt[o])==null?void 0:e.call(mt,c)}else o==="%"?n+="%":n+=`%${o}`;r+=2}}else n+=s,r+=1}return i.length&&(n.length&&(n+=" "),n+=i.map(F).join(" ")),n}return i.map(F).join(" ")}var v;(function(i){i[i.debug=0]="debug",i[i.info=1]="info",i[i.warn=2]="warn",i[i.error=3]="error",i[i.none=4]="none"})(v||(v={}));var Yi=["debug","info","warn","error","none"],I=class i{static get(){return new i({})}constructor(t){var e,n,r;if(this.Ue=(n=v[(e=t.level)!=null?e:"info"])!=null?n:v.info,this.Ve=(r=t.name)!=null?r:"LaunchDarkly",this.Yt=t.formatter,typeof t.destination=="object")this.Xt={[v.debug]:t.destination.debug,[v.info]:t.destination.info,[v.warn]:t.destination.warn,[v.error]:t.destination.error};else if(typeof t.destination=="function"){let{destination:s}=t;this.Xt={[v.debug]:s,[v.info]:s,[v.warn]:s,[v.error]:s}}}je(...t){var e;try{return this.Yt?(e=this.Yt)==null?void 0:e.call(this,...t):Yt(...t)}catch(n){return Yt(...t)}}Be(t,e){try{t(e)}catch(n){console.error(e)}}m(t,e){var n;if(t>=this.Ue){let r=`${Yi[t]}: [${this.Ve}]`;try{let s=(n=this.Xt)==null?void 0:n[t];s?this.Be(s,`${r} ${this.je(...e)}`):console.error(...e)}catch(s){console.error(...e)}}}error(...t){this.m(v.error,t)}warn(...t){this.m(v.warn,t)}info(...t){this.m(v.info,t)}debug(...t){this.m(v.debug,t)}},Xi={error:u.Function,warn:u.Function,info:u.Function,debug:u.Function},q=class{constructor(t,e){Object.entries(Xi).forEach(([n,r])=>{if(!r.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.He=e}m(t,e){try{this.t[t](...e)}catch(n){this.He[t](...e)}}error(...t){this.m("error",t)}warn(...t){this.m("warn",t)}info(...t){this.m("info",t)}debug(...t){this.m("debug",t)}},ce=i=>{let t=new I({level:"info",destination:console.error,formatter:Yt});return i?new q(i,t):t},b=class{static deprecated(t,e){return`"${t}" is deprecated, please use "${e}"`}static optionBelowMinimum(t,e,n){return`Config option "${t}" had invalid value of ${e}, using minimum of ${n} instead`}static unknownOption(t){return`Ignoring unknown config option "${t}"`}static wrongOptionType(t,e,n){return`Config option "${t}" should be of type ${e}, got ${n}, using default value`}static wrongOptionTypeBoolean(t,e){return`Config option "${t}" should be a boolean, got ${e}, converting to boolean`}static invalidTagValue(t){return`Config option "${t}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(t){return`Value of "${t}" was longer than 64 characters and was discarded.`}static partialEndpoint(t){return`You have set custom uris without specifying the ${t} URI; connections may not work properly`}},Zi=/^(\w|\.|-)+$/,Qi=u.stringMatchingRegex(Zi),tn={is:(i,t)=>Qi.is(i)?i.length>64?{valid:!1,message:b.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:b.invalidTagValue(t)}},wt=class{constructor(t){let e={},n=t==null?void 0:t.application,r=t==null?void 0:t.logger;n&&Object.entries(n).forEach(([a,o])=>{if(o!=null){let{valid:c,message:l}=tn.is(o,`application.${a}`);c?a==="versionName"?e["application-version-name"]=[o]:e[`application-${a}`]=[o]:r==null||r.warn(l)}});let s=Object.keys(e);s.length&&(this.value=s.sort().flatMap(a=>e[a].sort().map(o=>`${a}/${o}`)).join(" "))}},Dt=class{constructor(t,e,n){this.platform=n,this.basicConfiguration={tags:e.tags,logger:e.logger,offline:e.offline,serviceEndpoints:e.serviceEndpoints,sdkKey:t}}};function Ht(i){return i.replace(/\/+$/,"")}function le(i){return i.replace(/^\/+/,"").replace(/\?$/,"")}var P=class i{constructor(t,e,n=i.DEFAULT_EVENTS,r="/bulk",s="/diagnostic",a=!0,o){this.streaming=Ht(t),this.polling=Ht(e),this.events=Ht(n),this.analyticsEventPath=r,this.diagnosticEventPath=s,this.includeAuthorizationHeader=a,this.payloadFilterKey=o}};P.DEFAULT_EVENTS="https://events.launchdarkly.com";function ue(i,t){if(t.length===0)return i;let e=t.map(({key:n,value:r})=>`${n}=${r}`);return`${i}?${e.join("&")}`}function Je(i,t,e){let n=le(t),r=[...e];return i.payloadFilterKey&&r.push({key:"filter",value:i.payloadFilterKey}),ue(`${i.streaming}/${n}`,r)}function ze(i,t,e){let n=le(t),r=[...e];return i.payloadFilterKey&&r.push({key:"filter",value:i.payloadFilterKey}),ue(`${i.polling}/${n}`,r)}function He(i,t,e){let n=le(t);return ue(`${i.events}/${n}`,e)}var J=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},z=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},B=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function Y(i){return i>=400&&i<500?i===400||i===408||i===429:!0}function en(i){return i===413?!0:Y(i)}function We(i,t){let e,n;return{promise:new Promise((s,a)=>{n=s,e=setTimeout(()=>{let o=`${t} timed out after ${i} seconds.`;a(new B(o))},i*1e3)}),cancel:()=>{n(),clearTimeout(e)}}}function he(i){return i==null?i:JSON.parse(JSON.stringify(i))}function St(i){return Math.trunc(i*1e3)}var nn=i=>JSON.stringify(i)==="{}",Lt=(i,t)=>i&&Object.entries(i).reduce((e,[n,r])=>(r&&!nn(r)&&!(t!=null&&t.includes(n))&&(e[n]=typeof r=="object"?Lt(r,t):r),e),{});function K(i,t){if(i===t)return!0;if(i&&t&&typeof i=="object"&&typeof t=="object"){if(i.constructor!==t.constructor)return!1;var e,n,r;if(Array.isArray(i)){if(e=i.length,e!=t.length)return!1;for(n=e;n--!==0;)if(!K(i[n],t[n]))return!1;return!0}if(i instanceof Map&&t instanceof Map){if(i.size!==t.size)return!1;for(n of i.entries())if(!t.has(n[0]))return!1;for(n of i.entries())if(!K(n[1],t.get(n[0])))return!1;return!0}if(i instanceof Set&&t instanceof Set){if(i.size!==t.size)return!1;for(n of i.entries())if(!t.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(i)&&ArrayBuffer.isView(t)){if(e=i.length,e!=t.length)return!1;for(n=e;n--!==0;)if(i[n]!==t[n])return!1;return!0}if(i.constructor===RegExp)return i.source===t.source&&i.flags===t.flags;if(i.valueOf!==Object.prototype.valueOf)return i.valueOf()===t.valueOf();if(i.toString!==Object.prototype.toString)return i.toString()===t.toString();if(r=Object.keys(i),e=r.length,e!==Object.keys(t).length)return!1;for(n=e;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,r[n]))return!1;for(n=e;n--!==0;){var s=r[n];if(!K(i[s],t[s]))return!1}return!0}return i!==i&&t!==t}function Ye(i,t,e,n=!0,r="user-agent"){let{userAgentBase:s,version:a,wrapperName:o,wrapperVersion:c}=t.sdkData(),l={[r]:`${s!=null?s:"NodeJSClient"}/${a}`};return n&&(l.authorization=i),o&&(l["x-launchdarkly-wrapper"]=c?`${o}/${c}`:o),e!=null&&e.value&&(l["x-launchdarkly-tags"]=e.value),l}function H(i,t,e){let n;i.status?n=`error ${i.status}${i.status===401?" (invalid SDK key)":""}`:n=`I/O error (${i.message||"unknown error"})`;let r=e!=null?e:"giving up permanently";return`Received ${n} for ${t} - ${r}`}function Xe({status:i}){return i?Y(i):!0}var de=(i,t)=>t.btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var rn=async(i=1e3)=>new Promise(t=>{setTimeout(t,i)}),Ze=(i,t)=>new Promise((e,n)=>{setTimeout(()=>{let r=`${t} timed out after ${i} seconds.`;n(new B(r))},i*1e3)}),Xt=class{constructor(t,e,n){this.a=e,this._e=n,this.mt=[],this.Zt=Date.now(),this.Qt=this.Zt,this.te={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var n,r,s;let t=this.a.info.sdkData(),e=this.a.info.platformData();return{kind:"diagnostic-init",id:this.te,creationDate:this.Zt,sdk:t,configuration:this._e,platform:g({name:e.name,osArch:(n=e.os)==null?void 0:n.arch,osName:(r=e.os)==null?void 0:r.name,osVersion:(s=e.os)==null?void 0:s.version},e.additional||{})}}recordStreamInit(t,e,n){let r={timestamp:t,failed:e,durationMillis:n};this.mt.push(r)}createStatsEventAndReset(t,e,n){let r=Date.now(),s={kind:"diagnostic",id:this.te,creationDate:r,dataSinceDate:this.Qt,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.mt};return this.mt=[],this.Qt=r,s}},Zt;(function(i){i.MalformedFlag="MALFORMED_FLAG",i.UserNotSpecified="USER_NOT_SPECIFIED",i.FlagNotFound="FLAG_NOT_FOUND",i.ClientNotReady="CLIENT_NOT_READY",i.WrongType="WRONG_TYPE"})(Zt||(Zt={}));var sn=Zt,bt=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};bt.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var Qt=class{constructor(t,e){let{basicConfiguration:n,platform:r}=t,{serviceEndpoints:{analyticsEventPath:s,diagnosticEventPath:a}}=n,{crypto:o,requests:c}=r;this.Ke=g({},e),this.ee=He(n.serviceEndpoints,s,[]),this.Ge=He(n.serviceEndpoints,a,[]),this.D=c,this.qe=o}async X(t,e,n,r){let s={status:N.Succeeded},a=D(g({},this.Ke),{"content-type":"application/json"});n&&(a["x-launchdarkly-payload-id"]=n,a["x-launchDarkly-event-schema"]="4");let o;try{let{status:c,headers:l}=await this.D.fetch(e,{headers:a,body:JSON.stringify(t),compressBodyIfPossible:!0,method:"POST",keepalive:!0}),h=Date.parse(l.get("date")||"");if(h&&(s.serverTime=h),c<=204)return s;if(o=new J(H({status:c,message:"some events were dropped"},"event posting")),!Y(c))return en(c)?s.status=N.Failed:s.status=N.FailedAndMustShutDown,s.error=o,s}catch(c){o=c}return o&&!r?(s.status=N.Failed,s.error=o,s):(await rn(),this.X(t,this.ee,n,!1))}async sendEventData(t,e){let n=t===j.AnalyticsEvents?this.qe.randomUUID():void 0,r=t===j.AnalyticsEvents?this.ee:this.Ge;return this.X(e,r,n,!0)}};function te(i){return i.kind==="feature"}function an(i){return i.kind==="identify"}function on(i){return i.kind==="migration_op"}var ee=class{constructor(t,e,n,r,s,a){this.count=t,this.key=e,this.value=n,this.version=s,this.variation=a,this.default=r}increment(){this.count+=1}};function cn(i){return`${i.key}:${i.variation!==null&&i.variation!==void 0?i.variation:""}:${i.version!==null&&i.version!==void 0?i.version:""}`}var ie=class{constructor(){this.U=0,this.Z=0,this.Q={},this.tt={}}summarizeEvent(t){if(te(t)&&!t.excludeFromSummaries){let e=cn(t),n=this.Q[e],r=this.tt[t.key];r||(r=new Set,this.tt[t.key]=r),t.context.kinds.forEach(s=>r.add(s)),n?n.increment():this.Q[e]=new ee(1,t.key,t.value,t.default,t.version,t.variation),(this.U===0||t.creationDate<this.U)&&(this.U=t.creationDate),t.creationDate>this.Z&&(this.Z=t.creationDate)}}getSummary(){let t=Object.values(this.Q).reduce((e,n)=>{let r=e[n.key];r||(r={default:n.default,counters:[],contextKinds:[...this.tt[n.key]]},e[n.key]=r);let s={value:n.value,count:n.count};return n.variation!==void 0&&n.variation!==null&&(s.variation=n.variation),n.version!==void 0&&n.version!==null?s.version=n.version:s.unknown=!0,r.counters.push(s),e},{});return{startDate:this.U,endDate:this.Z,features:t,kind:"summary"}}clearSummary(){this.U=0,this.Z=0,this.Q={},this.tt={}}},ne=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}};function yt(i){let t=Math.trunc(i);return t===1?!0:t===0?!1:Math.floor(Math.random()*t)===0}var re=class{constructor(t,e,n,r,s,a=!0){this.r=t,this.et=r,this.y=s,this.yt=new ie,this.it=[],this.ie=0,this.vt=0,this.Et=0,this.wt=!1,this.ne=0,this.Dt=!1,this.bt=null,this.Je=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.re=new Qt(e,n),this.nt=new Wt(t.allAttributesPrivate,t.privateAttributes.map(o=>new A(o))),a&&this.start()}start(){var t,e;if(((t=this.et)==null?void 0:t.flushInterval)!==void 0&&(this.bt=setInterval(()=>{var n;(n=this.et)==null||n.flush()},this.et.flushInterval*1e3)),this.ze=setInterval(async()=>{var n;try{await this.flush()}catch(r){(n=this.t)==null||n.debug(`Flush failed: ${r}`)}},this.r.flushInterval*1e3),this.y){let n=this.y.createInitEvent();this.se(n),this.ae=setInterval(()=>{let r=this.y.createStatsEventAndReset(this.vt,this.Et,this.ne);this.vt=0,this.Et=0,this.se(r)},this.r.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}se(t){this.re.sendEventData(j.DiagnosticEvent,t)}close(){clearInterval(this.ze),this.bt&&clearInterval(this.bt),this.ae&&clearInterval(this.ae)}async flush(){var n;if(this.Dt)throw new ne("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.it;this.it=[];let e=this.yt.getSummary();this.yt.clearSummary(),Object.keys(e.features).length&&t.push(e),t.length&&(this.ne=t.length,(n=this.t)==null||n.debug("Flushing %d events",t.length),await this.X(t))}sendEvent(t){var c;if(this.Dt)return;if(on(t)){if(yt(t.samplingRatio)){let l=D(g({},t),{context:t.context?this.nt.filter(t.context):void 0});l.samplingRatio===1&&delete l.samplingRatio,this.rt(l)}return}this.yt.summarizeEvent(t);let e=te(t),n=e&&t.trackEvents||!e,r=this.We(t),s=an(t),a=(c=this.et)==null?void 0:c.processContext(t.context);a||s||(this.Et+=1),a&&!s&&this.rt(this.kt({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),n&&yt(t.samplingRatio)&&this.rt(this.kt(t,!1)),r&&yt(t.samplingRatio)&&this.rt(this.kt(t,!0))}kt(t,e){switch(t.kind){case"feature":{let n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.nt.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.prereqOf&&(n.prereqOf=t.prereqOf),t.variation!==void 0&&(n.variation=t.variation),t.version!==void 0&&(n.version=t.version),t.reason&&(n.reason=t.reason),n}case"index":case"identify":{let n={kind:t.kind,creationDate:t.creationDate,context:this.nt.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),n}case"custom":{let n={kind:"custom",creationDate:t.creationDate,key:t.key,context:this.nt.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.data!==void 0&&(n.data=t.data),t.metricValue!==void 0&&(n.metricValue=t.metricValue),t.url!==void 0&&(n.url=t.url),n}case"click":return{kind:"click",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url,selector:t.selector};case"pageview":return{kind:"pageview",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url};default:return t}}rt(t){var e;this.it.length<this.Je?(this.it.push(t),this.wt=!1):(this.wt||(this.wt=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.vt+=1)}We(t){return te(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.ie&&t.debugEventsUntilDate>Date.now()}async X(t){let e=await this.re.sendEventData(j.AnalyticsEvents,t);if(e.status===N.FailedAndMustShutDown&&(this.Dt=!0),e.serverTime&&(this.ie=e.serverTime),e.error)throw e.error}},kt=class{constructor(t,e,n,r,s=1,a){this.context=t,this.key=e,this.data=n,this.metricValue=r,this.samplingRatio=s,this.url=a,this.kind="custom",this.creationDate=Date.now(),this.context=t}},W=class{constructor(t,e,n,r,s,a,o,c,l,h,d,f,p=1){this.withReasons=t,this.context=e,this.key=n,this.samplingRatio=p,this.kind="feature",this.creationDate=Date.now(),this.value=r,this.default=s,a!==void 0&&(this.version=a),o!==void 0&&(this.variation=o),c!==void 0&&(this.trackEvents=c),l!==void 0&&(this.prereqOf=l),h!==void 0&&(this.reason=h),d!==void 0&&(this.debugEventsUntilDate=d),f!==void 0&&(this.excludeFromSummaries=f)}},xt=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},se=class{close(){}async flush(){}sendEvent(){}},ae=class{constructor(t){this.xt=t}evalEvent(t){var e;return new W(this.xt,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.xt||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new W(this.xt,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new xt(t,1)}customEvent(t,e,n,r,s=1){return new kt(e,t,n!=null?n:void 0,r!=null?r:void 0,s)}},oe=class{constructor(t,e,n,r){this.Ye=e,this.u=n,this.t=r,this.e=[],this.A=void 0,this.V=void 0,this.st=[],this.Xe=s=>{if(this.B(),!s.payloads.length)return;let a=s.payloads[0];switch(a==null?void 0:a.code){case"xfer-full":this.V=!0;break;case"xfer-changes":case"none":this.V=!1;break;default:return}this.A=a==null?void 0:a.id},this.Ze=s=>{var o;if(!this.A||!s.kind||!s.key||!s.version||!s.object)return;let a=this.Qe(s.kind,s.object);if(!a){(o=this.t)==null||o.warn(`Unable to prcoess object for kind: '${s.kind}'`);return}this.st.push({kind:s.kind,key:s.key,version:s.version,object:a})},this.ti=s=>{!this.A||!s.kind||!s.key||!s.version||this.st.push({kind:s.kind,key:s.key,version:s.version,deleted:!0})},this.ei=s=>{if(!this.A||!s.state||!s.version||this.V===void 0){this.B();return}let a={id:this.A,version:s.version,state:s.state,basis:this.V,updates:this.st};this.e.forEach(o=>o(a)),this.B()},this.ii=s=>{var a;(a=this.t)==null||a.info(`Goodbye was received from the LaunchDarkly connection with reason: ${s.reason}.`),this.B()},this.ni=s=>{var a;(a=this.t)==null||a.info(`An issue was encountered receiving updates for payload ${this.A} with reason: ${s.reason}. Automatic retry will occur.`),this.B()},this.T(t,"server-intent",this.Xe),this.T(t,"put-object",this.Ze),this.T(t,"delete-object",this.ti),this.T(t,"payload-transferred",this.ei),this.T(t,"goodbye",this.ii),this.T(t,"error",this.ni)}addPayloadListener(t){this.e.push(t)}removePayloadListener(t){let e=this.e.indexOf(t,0);e>-1&&this.e.splice(e,1)}T(t,e,n){t.addEventListener(e,async r=>{var s,a,o,c,l;if(r!=null&&r.data){(s=this.t)==null||s.debug(`Received ${e} event. Data is ${r.data}`);try{n(JSON.parse(r.data))}catch(h){(a=this.t)==null||a.error(`Stream received data that was unable to be processed in "${e}" message`),(o=this.t)==null||o.debug(`Data follows: ${r.data}`),(c=this.u)==null||c.call(this,E.InvalidData,"Malformed data in event stream")}}else(l=this.u)==null||l.call(this,E.Unknown,"Unexpected message from event stream")})}Qe(t,e){var n,r;return(r=(n=this.Ye)[t])==null?void 0:r.call(n,e)}B(){this.A=void 0,this.V=void 0,this.st=[]}},L=Object.freeze({__proto__:null,ClientMessages:bt,DiagnosticsManager:Xt,ErrorKinds:sn,EventFactoryBase:ae,EventProcessor:re,InputCustomEvent:kt,InputEvalEvent:W,InputIdentifyEvent:xt,NullEventProcessor:se,PayloadReader:oe,isLegacyUser:qe,isMultiKind:Ge,isSingleKind:Ke,shouldSample:yt});var w;(function(i){i.Initializing="INITIALIZING",i.Valid="VALID",i.Interrupted="INTERRUPTED",i.SetOffline="SET_OFFLINE",i.Closed="CLOSED"})(w||(w={}));function un(i){return i>=200&&i<=299}var Ct=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}},ye=class{constructor(t,e,n,r,s){this.D=t,this.ri=e,this.at=n,this.si=r,this.ai=s}async requestPayload(){let t;try{let e=await this.D.fetch(this.ri,{method:this.si,headers:this.at,body:this.ai});if(un(e.status))return await e.text();t=e.status}catch(e){throw new Ct(e==null?void 0:e.message)}throw new Ct(`Unexpected status code: ${t}`,t)}};function Te(i,t,e,n,r,s,a,o,c,l){let h,d="GET",f=g({},s);c&&(d="REPORT",f["content-type"]="application/json",h=i);let p=c?e.pathReport(r,i):e.pathGet(r,i),m=[...a!=null?a:[]];o&&m.push({key:"withReasons",value:"true"}),l&&m.push({key:"h",value:l});let y=ze(t,p,m);return new ye(n,y,f,d,h)}var hn={logger:u.Object,maxCachedContexts:u.numberWithMin(0),baseUri:u.String,streamUri:u.String,eventsUri:u.String,capacity:u.numberWithMin(1),diagnosticRecordingInterval:u.numberWithMin(2),flushInterval:u.numberWithMin(2),streamInitialReconnectDelay:u.numberWithMin(0),allAttributesPrivate:u.Boolean,debug:u.Boolean,diagnosticOptOut:u.Boolean,withReasons:u.Boolean,sendEvents:u.Boolean,pollInterval:u.numberWithMin(30),useReport:u.Boolean,privateAttributes:u.StringArray,applicationInfo:u.Object,wrapperName:u.String,wrapperVersion:u.String,payloadFilterKey:u.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:u.createTypeArray("Hook[]",{}),inspectors:u.createTypeArray("LDInspection",{})},dn=60*5,ni="https://clientsdk.launchdarkly.com",ri="https://clientstream.launchdarkly.com";function fn(i){return i instanceof q?i:ce(i)}var ve=class{constructor(t={},e={}){var r,s,a;this.logger=ce(),this.baseUri=ni,this.eventsUri=P.DEFAULT_EVENTS,this.streamUri=ri,this.maxCachedContexts=5,this.capacity=100,this.diagnosticRecordingInterval=900,this.flushInterval=30,this.streamInitialReconnectDelay=1,this.allAttributesPrivate=!1,this.debug=!1,this.diagnosticOptOut=!1,this.sendEvents=!0,this.sendLDHeaders=!0,this.useReport=!1,this.withReasons=!1,this.privateAttributes=[],this.pollInterval=dn,this.hooks=[],this.inspectors=[],this.logger=fn(t.logger),this.oi(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new P(this.streamUri,this.baseUri,this.eventsUri,e.analyticsEventPath,e.diagnosticEventPath,e.includeAuthorizationHeader,t.payloadFilterKey),this.useReport=(r=t.useReport)!=null?r:!1,this.tags=new wt({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(s=e.userAgentHeaderName)!=null?s:"user-agent",this.trackEventModifier=(a=e.trackEventModifier)!=null?a:o=>o}oi(t){let e=[];return Object.entries(t).forEach(([n,r])=>{let s=hn[n];if(s)if(s.is(r))n==="logger"||(this[n]=r!=null?r:void 0);else{let a=s.getType();if(a==="boolean")e.push(b.wrongOptionTypeBoolean(n,typeof r)),this[n]=!!r;else if(a==="boolean | undefined | null")e.push(b.wrongOptionTypeBoolean(n,typeof r)),typeof r!="boolean"&&typeof r!="undefined"&&r!==null&&(this[n]=!!r);else if(s instanceof G&&u.Number.is(r)){let{min:o}=s;e.push(b.optionBelowMinimum(n,r,o)),this[n]=o}else e.push(b.wrongOptionType(n,s.getType(),typeof r))}else e.push(b.unknownOption(n))}),e}};async function si(i,t){if(i.digest)return i.digest(t);if(i.asyncDigest)return i.asyncDigest(t);throw new Error("Platform must implement digest or asyncDigest")}var ai=async(i,{crypto:t,storage:e})=>{let n=await(e==null?void 0:e.get(i));return n||(n=t.randomUUID(),await(e==null?void 0:e.set(i,n))),n};function oi(i){return async t=>si(i.createHash("sha256").update(t),"base64")}var x=async i=>i;async function Z(i){return(await Promise.all(i.map(e=>e.transform(e.value)))).join("_")}async function gn(i,t){return Z([{value:"LaunchDarkly",transform:x},{value:t,transform:oi(i)}])}async function pn(i){return Z([{value:"LaunchDarkly",transform:x},{value:"AnonymousKeys",transform:x},{value:i,transform:x}])}async function mn(i){return Z([{value:"LaunchDarkly",transform:x},{value:"ContextKeys",transform:x},{value:i,transform:x}])}async function yn(i){return Z([{value:i,transform:x},{value:"ContextIndex",transform:x}])}async function Qe(i,t,e){return Z([{value:t,transform:x},{value:e.canonicalKey,transform:oi(i)}])}var{isLegacyUser:vn,isSingleKind:fe,isMultiKind:ti}=L,ci="1.0",En=i=>{let n=i,{kind:t}=n,e=jt(n,["kind"]);return{kind:"multi",[t]:e}},wn=async({crypto:i,info:t},{applicationInfo:e})=>{var a;let{ld_application:n}=t.platformData(),r=(a=Lt(n))!=null?a:{},s=(e==null?void 0:e.id)||(r==null?void 0:r.id);if(s){let o=(e==null?void 0:e.version)||(r==null?void 0:r.version),c=(e==null?void 0:e.name)||(r==null?void 0:r.name),l=(e==null?void 0:e.versionName)||(r==null?void 0:r.versionName);return r=g(g(g(D(g({},r),{id:s}),o?{version:o}:{}),c?{name:c}:{}),l?{versionName:l}:{}),r.key=await si(i.createHash("sha256").update(s),"base64"),r.envAttributesVersion=r.envAttributesVersion||ci,r}},Dn=async i=>{var o,c,l,h;let{ld_device:t,os:e}=i.info.platformData(),n=(o=Lt(t))!=null?o:{},r=(e==null?void 0:e.name)||((c=n.os)==null?void 0:c.name),s=(e==null?void 0:e.version)||((l=n.os)==null?void 0:l.version),a=(h=n.os)==null?void 0:h.family;if((r||s||a)&&(n.os=g(g(g({},r?{name:r}:{}),s?{version:s}:{}),a?{family:a}:{})),Object.keys(n).filter(d=>d!=="key"&&d!=="envAttributesVersion").length){let d=await mn("ld_device");return n.key=await ai(d,i),n.envAttributesVersion=n.envAttributesVersion||ci,n}},bn=async(i,t,e)=>{if(vn(i))return i;let n,r;if(fe(i)&&i.kind!=="ld_application"||ti(i)&&!i.ld_application?n=await wn(t,e):e.logger.warn("Not adding ld_application environment attributes because it already exists."),fe(i)&&i.kind!=="ld_device"||ti(i)&&!i.ld_device?r=await Dn(t):e.logger.warn("Not adding ld_device environment attributes because it already exists."),n||r){let s=fe(i)?En(i):i;return g(g(g({},s),n?{ld_application:n}:{}),r?{ld_device:r}:{})}return i},{isLegacyUser:kn,isMultiKind:xn,isSingleKind:Sn}=L,$e=async(i,t,e)=>{let{anonymous:n,key:r}=t;if(n&&!r){let s=await pn(i);t.key=await ai(s,e)}},Ln=async(i,t)=>{await $e(i.kind,i,t)},Cn=async(i,t)=>{let r=i,{kind:e}=r,n=jt(r,["kind"]);return Promise.all(Object.entries(n).map(([s,a])=>$e(s,a,t)))},An=async(i,t)=>{await $e("user",i,t)},On=async(i,t)=>{let e=he(i);return Sn(e)&&await Ln(e,t),xn(e)&&await Cn(e,t),kn(e)&&await An(e,t),e},Tn=i=>({customBaseURI:i.serviceEndpoints.polling!==ni,customStreamURI:i.serviceEndpoints.streaming!==ri,customEventsURI:i.serviceEndpoints.events!==P.DEFAULT_EVENTS,eventsCapacity:i.capacity,eventsFlushIntervalMillis:St(i.flushInterval),reconnectTimeMillis:St(i.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:St(i.diagnosticRecordingInterval),allAttributesPrivate:i.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),$n=(i,t,e)=>{if(t.sendEvents&&!t.diagnosticOptOut)return new L.DiagnosticsManager(i,e,Tn(t))};function ge(i,t){return{value:t!=null?t:null,variationIndex:null,reason:{kind:"ERROR",errorKind:i}}}function ei(i,t,e){return{value:i,variationIndex:t!=null?t:null,reason:e!=null?e:null}}var Nn=(i,t,e,n,r)=>{if(t.sendEvents)return new L.EventProcessor(D(g({},t),{eventsCapacity:t.capacity}),new Dt(i,t,e),n,void 0,r,!1)},At=class extends L.EventFactoryBase{evalEventClient(t,e,n,r,s,a){let{trackEvents:o,debugEventsUntilDate:c,trackReason:l,flagVersion:h,version:d,variation:f}=r;return super.evalEvent({addExperimentData:l,context:s,debugEventsUntilDate:c,defaultVal:n,flagKey:t,reason:a,trackEvents:!!o,value:e,variation:f,version:h!=null?h:d})}},X=class i{constructor(){this.container={index:new Array}}static fromJson(t){let e=new i;try{e.container=JSON.parse(t)}catch(n){}return e}toJson(){return JSON.stringify(this.container)}notice(t,e){let n=this.container.index.find(r=>r.id===t);n===void 0?this.container.index.push({id:t,timestamp:e}):n.timestamp=e}prune(t){let e=Math.max(t,0);return this.container.index.length>e?(this.container.index.sort((n,r)=>n.timestamp-r.timestamp),this.container.index.splice(0,this.container.index.length-e)):[]}},Ee=class{constructor(t,e,n,r,s,a,o=()=>Date.now()){this.a=t,this.St=e,this.ci=n,this.h=r,this.b=s,this.t=a,this.ot=o,this.oe=yn(this.St)}async init(t,e){this.b.init(t,e),await this.ce(t)}async upsert(t,e,n){return this.b.upsert(t,e,n)?(await this.ce(t),!0):!1}async loadCached(t){var r,s,a,o;let e=await Qe(this.a.crypto,this.St,t),n=await((r=this.a.storage)==null?void 0:r.get(e));if(n==null){if(n=await((s=this.a.storage)==null?void 0:s.get(t.canonicalKey)),n==null)return!1;await((a=this.a.storage)==null?void 0:a.set(e,n)),await((o=this.a.storage)==null?void 0:o.clear(t.canonicalKey))}try{let c=JSON.parse(n),l=Object.entries(c).reduce((h,[d,f])=>(h[d]={version:f.version,flag:f},h),{});return this.b.initCached(t,l),this.t.debug("Loaded cached flag evaluations from persistent storage"),!0}catch(c){return this.t.warn(`Could not load cached flag evaluations from persistent storage: ${c.message}`),!1}}async li(){var e;if(this.$!==void 0)return this.$;let t=await((e=this.a.storage)==null?void 0:e.get(await this.oe));if(!t)return this.$=new X,this.$;try{this.$=X.fromJson(t),this.t.debug("Loaded context index from persistent storage")}catch(n){this.t.warn(`Could not load index from persistent storage: ${n.message}`),this.$=new X}return this.$}async ce(t){var c,l;let e=await this.li(),n=await Qe(this.a.crypto,this.St,t);e.notice(n,this.ot());let r=e.prune(this.ci);await Promise.all(r.map(async h=>{var d;return(d=this.a.storage)==null?void 0:d.clear(h.id)})),await((c=this.a.storage)==null?void 0:c.set(await this.oe,e.toJson()));let s=this.h.getAll(),a=Object.entries(s).reduce((h,[d,f])=>(f.flag!==null&&f.flag!==void 0&&(h[d]=f.flag),h),{}),o=JSON.stringify(a);await((l=this.a.storage)==null?void 0:l.set(n,o))}},we=class{constructor(){this.H={}}init(t){this.H=Object.entries(t).reduce((e,[n,r])=>(e[n]=r,e),{})}insertOrUpdate(t,e){this.H[t]=e}get(t){if(Object.prototype.hasOwnProperty.call(this.H,t))return this.H[t]}getAll(){return this.H}};function Rn(i,t){let e=[];return Object.entries(i).forEach(([n,r])=>{let s=t[n];(!s||!K(r,s))&&e.push(n)}),Object.keys(t).forEach(n=>{i[n]||e.push(n)}),e}var De=class{constructor(t,e){this._=new Array,this.h=t,this.t=e}init(t,e){this.le=t.canonicalKey;let n=this.h.getAll();this.h.init(e);let r=Rn(n,e);r.length>0&&this._.forEach(s=>{try{s(t,r,"init")}catch(a){}})}initCached(t,e){this.le!==t.canonicalKey&&this.init(t,e)}upsert(t,e,n){if(this.le!==t.canonicalKey)return this.t.warn("Received an update for an inactive context."),!1;let r=this.h.get(e);return r!==void 0&&r.version>=n.version?!1:(this.h.insertOrUpdate(e,n),this._.forEach(s=>{try{s(t,[e],"patch")}catch(a){}}),!0)}on(t){this._.push(t)}off(t){let e=this._.indexOf(t);e>-1&&this._.splice(e,1)}},be=class{constructor(t,e,n,r,s=()=>Date.now()){this.h=new we,this.b=new De(this.h,r),this.Lt=this.ui(t,e,n,r,s)}async ui(t,e,n,r,s=()=>Date.now()){let a=await gn(t.crypto,e);return new Ee(t,a,n,this.h,this.b,r,s)}get(t){return this.h.get(t)}getAll(){return this.h.getAll()}setBootstrap(t,e){this.b.init(t,e)}async init(t,e){return(await this.Lt).init(t,e)}async upsert(t,e,n){return(await this.Lt).upsert(t,e,n)}async loadCached(t){return(await this.Lt).loadCached(t)}on(t){this.b.on(t)}off(t){this.b.off(t)}},ii="unknown hook",li="beforeEvaluation",ui="afterEvaluation";function $t(i,t,e,n,r){try{return n()}catch(s){return i==null||i.error(`An error was encountered in "${t}" of the "${e}" hook: ${s}`),r}}function Nt(i,t){try{return t.getMetadata().name||ii}catch(e){return i.error("Exception thrown getting metadata for hook. Unable to get hook name."),ii}}function In(i,t,e){return t.map(n=>$t(i,li,Nt(i,n),()=>{var r,s;return(s=(r=n==null?void 0:n.beforeEvaluation)==null?void 0:r.call(n,e,{}))!=null?s:{}},{}))}function Pn(i,t,e,n,r){for(let s=t.length-1;s>=0;s-=1){let a=t[s],o=n[s];$t(i,ui,Nt(i,a),()=>{var c,l;return(l=(c=a==null?void 0:a.afterEvaluation)==null?void 0:c.call(a,e,o,r))!=null?l:{}},{})}}function Mn(i,t,e){return t.map(n=>$t(i,li,Nt(i,n),()=>{var r,s;return(s=(r=n==null?void 0:n.beforeIdentify)==null?void 0:r.call(n,e,{}))!=null?s:{}},{}))}function Fn(i,t,e,n,r){for(let s=t.length-1;s>=0;s-=1){let a=t[s],o=n[s];$t(i,ui,Nt(i,a),()=>{var c,l;return(l=(c=a==null?void 0:a.afterIdentify)==null?void 0:c.call(a,e,o,r))!=null?l:{}},{})}}var ke=class{constructor(t,e){this.t=t,this.K=[],this.K.push(...e)}withEvaluation(t,e,n,r){if(this.K.length===0)return r();let s=[...this.K],a={flagKey:t,context:e,defaultValue:n},o=In(this.t,s,a),c=r();return Pn(this.t,s,a,o,c),c}identify(t,e){let n=[...this.K],r={context:t,timeout:e},s=Mn(this.t,n,r);return a=>{Fn(this.t,n,r,s,a)}}addHook(t){this.K.push(t)}};function Un(i){return{getMetadata(){return{name:"LaunchDarkly-Inspector-Adapter"}},afterEvaluation:(t,e,n)=>(i.onFlagUsed(t.flagKey,n,t.context),e),afterIdentify(t,e,n){return i.onIdentityChanged(t.context),e}}}function Vn(i,t){return`an inspector: "${t}" of an invalid type (${i}) was configured`}function jn(i,t){return`an inspector: "${t}" of type: "${i}" generated an exception`}function Bn(i,t){let e=!1,n={method:(...r)=>{try{i.method(...r)}catch(s){e||(e=!0,t.warn(jn(n.type,n.name)))}},type:i.type,name:i.name,synchronous:i.synchronous};return n}var hi="flag-used",di="flag-details-changed",fi="flag-detail-changed",gi="client-identity-changed",Hn=[hi,di,fi,gi];function _n(i,t){let e=Hn.includes(i.type)&&i.method&&typeof i.method=="function";return e||t.warn(Vn(i.type,i.name)),e}var xe=class{constructor(t,e){this.N=[];let n=t.filter(r=>_n(r,e));this.N=n.map(r=>Bn(r,e))}hasInspectors(){return this.N.length!==0}onFlagUsed(t,e,n){this.N.forEach(r=>{r.type===hi&&r.method(t,e,n)})}onFlagsChanged(t){this.N.forEach(e=>{e.type===di&&e.method(t)})}onFlagChanged(t,e){this.N.forEach(n=>{n.type===fi&&n.method(t,e)})}onIdentityChanged(t){this.N.forEach(e=>{e.type===gi&&e.method(t)})}},Se=class{constructor(t){this.t=t,this.e=new Map}on(t,e){var n;this.e.has(t)?(n=this.e.get(t))==null||n.push(e):this.e.set(t,[e])}off(t,e){let n=this.e.get(t);if(n){if(e){let r=n.filter(s=>s!==e);r.length===0?this.e.delete(t):this.e.set(t,r);return}this.e.delete(t)}}Ct(t,e,...n){var r;try{t(...n)}catch(s){(r=this.t)==null||r.error(`Encountered error invoking handler for "${e}", detail: "${s}"`)}}emit(t,...e){let n=this.e.get(t);n==null||n.forEach(r=>this.Ct(r,t,...e))}eventNames(){return[...this.e.keys()]}listenerCount(t){var e,n;return(n=(e=this.e.get(t))==null?void 0:e.length)!=null?n:0}},{ClientMessages:pe,ErrorKinds:me}=L,Kn=5,Ot=class{constructor(t,e,n,r,s,a){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.At=15,this.k=new At(!1),this.ct=new At(!0),this.Ot=!1,!t)throw new Error("You must configure the client with a client-side SDK key");if(!n.encoding)throw new Error("Platform must implement Encoding because btoa is required.");this.r=new ve(r,a),this.logger=this.r.logger,this.ue=Ye(this.sdkKey,this.platform.info,this.r.tags,this.r.serviceEndpoints.includeAuthorizationHeader,this.r.userAgentHeaderName),this.v=new be(this.platform,t,this.r.maxCachedContexts,this.r.logger),this.y=$n(t,this.r,n),this.g=Nn(t,this.r,n,this.ue,this.y),this.emitter=new Se,this.emitter.on("error",(o,c)=>{this.logger.error(`error: ${c}, context: ${JSON.stringify(o)}`)}),this.v.on((o,c,l)=>{this.hi(c,l);let h=k.toLDContext(o);this.emitter.emit("change",h,c),c.forEach(d=>{this.emitter.emit(`change:${d}`,h)})}),this.dataManager=s(this.v,this.r,this.ue,this.emitter,this.y),this.R=new ke(this.logger,this.r.hooks),this.G=new xe(this.r.inspectors,this.logger),this.G.hasInspectors()&&this.R.addHook(Un(this.G))}allFlags(){return Object.entries(this.v.getAll()).reduce((e,[n,r])=>(r.flag!==null&&r.flag!==void 0&&!r.flag.deleted&&(e[n]=r.flag.value),e),{})}async close(){var t;await this.flush(),(t=this.g)==null||t.close(),this.dataManager.close(),this.logger.debug("Closed event processor and data source.")}async flush(){var t;try{await((t=this.g)==null?void 0:t.flush()),this.logger.debug("Successfully flushed event processor.")}catch(e){return this.logger.error(`Error flushing event processor: ${e}.`),{error:e,result:!1}}return{result:!0}}getContext(){return this.E?he(this.E):void 0}getInternalContext(){return this.I}di(t,e){let n,r,s=new Promise((c,l)=>{n=c,r=l});if(e)return{identifyPromise:s,identifyResolve:n,identifyReject:r};let a=Ze(t,"identify");return{identifyPromise:Promise.race([a,s]).catch(c=>{throw c.message.includes("timed out")&&this.logger.error(`identify error: ${c}`),c}),identifyResolve:n,identifyReject:r}}async identify(t,e){var d,f;let n=(d=e==null?void 0:e.timeout)!=null?d:Kn,r=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;n>this.At&&this.logger.warn(`The identify function was called with a timeout greater than ${this.At} seconds. We recommend a timeout of less than ${this.At} seconds.`);let s=await On(t,this.platform);this.autoEnvAttributes===V.Enabled&&(s=await bn(s,this.platform,this.r));let a=k.fromLDContext(s);if(!a.valid){let p=new Error("Context was unspecified or had no key");return this.emitter.emit("error",s,p),Promise.reject(p)}this.E=s,this.I=a,(f=this.g)==null||f.sendEvent(this.k.identifyEvent(this.I));let{identifyPromise:o,identifyResolve:c,identifyReject:l}=this.di(n,r);this.logger.debug(`Identifying ${JSON.stringify(this.I)}`);let h=this.R.identify(s,e==null?void 0:e.timeout);return await this.dataManager.identify(c,l,a,e),o.then(p=>(h({status:"completed"}),p),p=>{throw h({status:"error"}),p})}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}track(t,e,n){var r,s;if(!this.I||!this.I.valid){this.logger.warn(pe.MissingContextKeyNoEvent);return}n!==void 0&&!u.Number.is(n)&&((r=this.logger)==null||r.warn(pe.invalidMetricValue(typeof n))),(s=this.g)==null||s.sendEvent(this.r.trackEventModifier(this.k.customEvent(t,this.I,e,n)))}lt(t,e,n,r){var f,p,m;if(!this.E)return this.logger.debug(pe.MissingContextKeyNoEvent),ge(me.UserNotSpecified,e);let s=k.fromLDContext(this.E),a=this.v.get(t);if(a===void 0||a.flag.deleted){let y=e!=null?e:null,S=new z(`Unknown feature flag "${t}"; returning default value ${y}.`);return this.emitter.emit("error",this.E,S),(f=this.g)==null||f.sendEvent(this.k.unknownFlagEvent(t,y,s)),ge(me.FlagNotFound,e)}let{reason:o,value:c,variation:l,prerequisites:h}=a.flag;if(r){let[y,S]=r(c);if(!y){(p=this.g)==null||p.sendEvent(n.evalEventClient(t,e,e,a.flag,s,o));let M=new z(`Wrong type "${S}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.E,M),ge(me.WrongType,e)}}let d=ei(c,l,o);return c==null&&(this.logger.debug("Result value is null. Providing default value."),d.value=e),h==null||h.forEach(y=>{this.lt(y,void 0,this.k)}),(m=this.g)==null||m.sendEvent(n.evalEventClient(t,c,e,a.flag,s,o)),d}variation(t,e){let{value:n}=this.R.withEvaluation(t,this.E,e,()=>this.lt(t,e,this.k));return n}variationDetail(t,e){return this.R.withEvaluation(t,this.E,e,()=>this.lt(t,e,this.ct))}P(t,e,n,r){return this.R.withEvaluation(t,this.E,e,()=>this.lt(t,e,n,r))}boolVariation(t,e){return this.P(t,e,this.k,n=>[u.Boolean.is(n),u.Boolean.getType()]).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.P(t,e,this.k,n=>[u.Number.is(n),u.Number.getType()]).value}stringVariation(t,e){return this.P(t,e,this.k,n=>[u.String.is(n),u.String.getType()]).value}boolVariationDetail(t,e){return this.P(t,e,this.ct,n=>[u.Boolean.is(n),u.Boolean.getType()])}numberVariationDetail(t,e){return this.P(t,e,this.ct,n=>[u.Number.is(n),u.Number.getType()])}stringVariationDetail(t,e){return this.P(t,e,this.ct,n=>[u.String.is(n),u.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.R.addHook(t)}setEventSendingEnabled(t,e){var n,r,s,a;this.Ot!==t&&(this.Ot=t,t?(this.logger.debug("Starting event processor"),(n=this.g)==null||n.start()):e?((r=this.logger)==null||r.debug("Flushing event processor before disabling."),this.flush().then(()=>{var o,c;this.Ot||((o=this.logger)==null||o.debug("Stopping event processor."),(c=this.g)==null||c.close())})):((s=this.logger)==null||s.debug("Stopping event processor."),(a=this.g)==null||a.close()))}sendEvent(t){var e;(e=this.g)==null||e.sendEvent(t)}hi(t,e){if(!this.G.hasInspectors())return;let n={};t.forEach(r=>{let s=this.v.get(r);if(s!=null&&s.flag&&!s.flag.deleted){let{reason:a,value:o,variation:c}=s.flag;n[r]=ei(o,c,a)}else n[r]={value:void 0,reason:null,variationIndex:null}}),e==="init"?this.G.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([r,s])=>{this.G.onFlagChanged(r,s)})}},Le=class{constructor(t,e,n){this.v=t,this.Tt=e,this.t=n}async handlePut(t,e){this.t.debug(`Got PUT: ${Object.keys(e)}`);let n=Object.entries(e).reduce((r,[s,a])=>(r[s]={version:a.version,flag:a},r),{});await this.v.init(t,n),this.Tt.requestStateUpdate(w.Valid)}async handlePatch(t,e){this.t.debug(`Got PATCH ${JSON.stringify(e,null,2)}`),this.v.upsert(t,e.key,{version:e.version,flag:e})}async handleDelete(t,e){this.t.debug(`Got DELETE ${JSON.stringify(e,null,2)}`),this.v.upsert(t,e.key,{version:e.version,flag:D(g({},e),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})}handleStreamingError(t){this.Tt.reportError(t.kind,t.message,t.code,t.recoverable)}handlePollingError(t){this.Tt.reportError(t.kind,t.message,t.status,t.recoverable)}},Ce=class{constructor(t,e=()=>Date.now()){this.x=t,this.ut=w.Closed,this.he=e(),this.ot=e}get status(){return{state:this.ut,stateSince:this.he,lastError:this.fi}}de(t,e=!1){let n=t===w.Interrupted&&this.ut===w.Initializing?w.Initializing:t,r=this.ut!==n;r&&(this.ut=n,this.he=this.ot()),(r||e)&&this.x.emit("dataSourceStatus",this.status)}requestStateUpdate(t){this.de(t)}reportError(t,e,n,r=!1){let s={kind:t,message:e,statusCode:n,time:this.ot()};this.fi=s,this.de(r?w.Interrupted:w.Closed,!0)}},Ae=class{constructor(t,e,n,r,s){this.gi=t,this.pi=e,this.mi=n,this.u=r,this.t=s,this.fe=!1}async ge(){var s,a,o,c,l,h,d;if(this.fe)return;let t=f=>{var p,m,y;(p=this.t)==null||p.error("Polling received invalid data"),(m=this.t)==null||m.debug(`Invalid JSON follows: ${f}`),(y=this.u)==null||y.call(this,new R(E.InvalidData,"Malformed JSON data in polling response"))};(s=this.t)==null||s.debug("Polling LaunchDarkly for feature flag updates");let e=Date.now();try{let f=await this.gi.requestPayload();try{let p=JSON.parse(f);try{(a=this.mi)==null||a.call(this,p)}catch(m){(o=this.t)==null||o.error(`Exception from data handler: ${m}`)}}catch(p){t(f)}}catch(f){let p=f;if(p.status!==void 0&&!Y(p.status)){(c=this.t)==null||c.error(H(f,"polling request")),(l=this.u)==null||l.call(this,new R(E.ErrorResponse,p.message,p.status));return}(h=this.t)==null||h.error(H(f,"polling request","will retry"))}let n=Date.now()-e,r=Math.max(this.pi*1e3-n,0);(d=this.t)==null||d.debug("Elapsed: %d ms, sleeping for %d ms",n,r),this.$t=setTimeout(()=>{this.ge()},r)}start(){this.ge()}stop(){this.$t&&(clearTimeout(this.$t),this.$t=void 0),this.fe=!0}close(){this.stop()}},Gn=(i,t,e,n)=>{e==null||e.error(`Stream received invalid data in "${i}" message`),e==null||e.debug(`Invalid JSON follows: ${t}`),n==null||n(new U(E.InvalidData,"Malformed JSON data in event stream"))},Oe=class{constructor(t,e,n,r,s,a,o,c,l){var f;this.yi=t,this.Nt=e,this.e=n,this.D=r,this.vi=a,this.y=o,this.u=c,this.t=l;let h;e.useReport&&!r.getEventSourceCapabilities().customMethod?h=e.paths.pathPing(s,t):h=e.useReport?e.paths.pathReport(s,t):e.paths.pathGet(s,t);let d=[...(f=e.queryParameters)!=null?f:[]];this.Nt.withReasons&&d.push({key:"withReasons",value:"true"}),this.D=r,this.at=g({},e.baseHeaders),this.t=l,this.Ei=Je(e.serviceEndpoints,h,d)}pe(){this.ht=Date.now()}Rt(t){this.ht&&this.y&&this.y.recordStreamInit(this.ht,!t,Date.now()-this.ht),this.ht=void 0}wi(t){var e,n,r;return Xe(t)?((r=this.t)==null||r.warn(H(t,"streaming request","will retry")),this.Rt(!1),this.pe(),!0):(this.Rt(!1),(e=this.u)==null||e.call(this,new U(E.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error(H(t,"streaming request")),!1)}start(){this.pe();let t;this.Nt.useReport?(this.at["content-type"]="application/json",t={method:"REPORT",body:this.yi}):t={};let e=this.D.createEventSource(this.Ei,D(g({headers:this.at},t),{errorFilter:n=>this.wi(n),initialRetryDelayMillis:this.Nt.initialRetryDelayMillis,readTimeoutMillis:5*60*1e3,retryResetIntervalMillis:60*1e3}));this.me=e,e.onclose=()=>{var n;(n=this.t)==null||n.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var n;(n=this.t)==null||n.info("Opened LaunchDarkly stream connection")},e.onretrying=n=>{var r;(r=this.t)==null||r.info(`Will retry stream connection in ${n.delayMillis} milliseconds`)},this.e.forEach(({deserializeData:n,processJson:r},s)=>{e.addEventListener(s,a=>{var o,c;if((o=this.t)==null||o.debug(`Received ${s} event`),a!=null&&a.data){this.Rt(!0);let{data:l}=a,h=n(l);if(!h){Gn(s,l,this.t,this.u);return}r(h)}else(c=this.u)==null||c.call(this,new U(E.InvalidData,"Unexpected payload from event stream"))})}),e.addEventListener("ping",async()=>{var n,r,s,a,o,c,l;(n=this.t)==null||n.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let h=await this.vi.requestPayload();try{let d=JSON.parse(h);try{(r=this.e.get("put"))==null||r.processJson(d)}catch(f){(s=this.t)==null||s.error(`Exception from data handler: ${f}`)}}catch(d){(a=this.t)==null||a.error("Polling after ping received invalid data"),(o=this.t)==null||o.debug(`Invalid JSON follows: ${h}`),(c=this.u)==null||c.call(this,new R(E.InvalidData,"Malformed JSON data in ping polling response"))}}catch(h){let d=h;(l=this.u)==null||l.call(this,new R(E.ErrorResponse,d.message,d.status))}})}stop(){var t;(t=this.me)==null||t.close(),this.me=void 0}close(){this.stop()}},Tt=class{constructor(t,e,n,r,s,a,o,c,l){this.platform=t,this.flagManager=e,this.credential=n,this.config=r,this.getPollingPaths=s,this.getStreamingPaths=a,this.baseHeaders=o,this.emitter=c,this.diagnosticsManager=l,this.closed=!1,this.logger=r.logger,this.dataSourceStatusManager=new Ce(c),this.M=new Le(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.Di=t}createPollingProcessor(t,e,n,r,s){let a=new Ae(n,this.config.pollInterval,async o=>{await this.M.handlePut(e,o),r==null||r()},o=>{this.emitter.emit("error",t,o),this.M.handlePollingError(o),s==null||s(o)},this.logger);this.updateProcessor=this.ye(a,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,r,s){var o;let a=new Oe(JSON.stringify(t),{credential:this.credential,serviceEndpoints:this.config.serviceEndpoints,paths:this.getStreamingPaths(),baseHeaders:this.baseHeaders,initialRetryDelayMillis:this.config.streamInitialReconnectDelay*1e3,withReasons:this.config.withReasons,useReport:this.config.useReport,queryParameters:(o=this.Di)==null?void 0:o.queryParameters},this.createStreamListeners(e,r),this.platform.requests,this.platform.encoding,n,this.diagnosticsManager,c=>{this.emitter.emit("error",t,c),this.M.handleStreamingError(c),s==null||s(c)},this.logger);this.updateProcessor=this.ye(a,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async r=>{await this.M.handlePut(t,r),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async r=>{this.M.handlePatch(t,r)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async r=>{this.M.handleDelete(t,r)}}),n}ye(t,e){return{start:()=>{e.requestStateUpdate(w.Initializing),t.start()},stop:()=>{t.stop(),e.requestStateUpdate(w.Closed)},close:()=>{t.close(),e.requestStateUpdate(w.Closed)}}}close(){var t;(t=this.updateProcessor)==null||t.close(),this.closed=!0}};function Rt(){return typeof document!==void 0}function Ne(){return typeof window!==void 0}function It(i,t,e){return Rt()?(document.addEventListener(i,t,e),()=>{document.removeEventListener(i,t,e)}):()=>{}}function Pt(i,t,e){return Rt()?(window.addEventListener(i,t,e),()=>{window.removeEventListener(i,t,e)}):()=>{}}function C(){return Ne()?window.location.href:""}function pi(){return Ne()?window.location.search:""}function mi(){return Ne()?window.location.hash:""}function yi(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function vi(){return Rt()?document.visibilityState:"visibile"}function Ei(i){if(Rt())return document.querySelectorAll(i)}function wi(i,t){let e=Object.keys(t),n="$flagsState",r="$valid",s=t[n];!s&&e.length&&i.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),t[r]===!1&&i.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");let a={};return e.forEach(o=>{if(o!==n&&o!==r){let c;s&&s[o]?c=g({value:t[o]},s[o]):c={value:t[o],version:0},a[o]={version:c.version,flag:c}}}),a}var qn="[BrowserDataManager]",Q=class extends Tt{constructor(e,n,r,s,a,o,c,l,h,d){super(e,n,r,s,o,c,l,h,d);this.Fi=a;this.q=void 0;this.It=!1;this.q=a.streaming}S(e,...n){this.logger.debug(`${qn} ${e}`,...n)}async identify(e,n,r,s){if(this.closed){this.S("Identify called after data manager was closed.");return}this.context=r;let a=s;a!=null&&a.hash?this.setConnectionParams({queryParameters:[{key:"h",value:a.hash}]}):this.setConnectionParams(),this.Pt=a==null?void 0:a.hash,a!=null&&a.bootstrap?this.bi(r,a.bootstrap,e):(await this.flagManager.loadCached(r)&&this.S("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.ki(r,e,n)),this.Mt()}async ki(e,n,r){var s,a;try{this.dataSourceStatusManager.requestStateUpdate(w.Initializing);let o=JSON.stringify(k.toLDContext(e)),l=await Te(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Pt).requestPayload();try{let d=this.createStreamListeners(e,n).get("put");d.processJson(d.deserializeData(l))}catch(h){this.dataSourceStatusManager.reportError(E.InvalidData,(s=h.message)!=null?s:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(E.NetworkError,(a=o.message)!=null?a:"unexpected network error",o.status),r(o)}}bi(e,n,r){this.flagManager.setBootstrap(e,wi(this.logger,n)),this.S("Identify - Initialization completed from bootstrap"),r()}setForcedStreaming(e){this.q=e,this.Mt()}setAutomaticStreamingState(e){this.It=e,this.Mt()}Mt(){let e=this.q||this.It&&this.q===void 0;this.S(`Updating streaming state. forced(${this.q}) automatic(${this.It})`),e?this.xi():this.Si()}Si(){var e;this.updateProcessor&&this.S("Stopping update processor."),(e=this.updateProcessor)==null||e.close(),this.updateProcessor=void 0}xi(){if(this.updateProcessor){this.S("Update processor already active. Not changing state.");return}if(!this.context){this.S("Context not set, not starting update processor.");return}this.S("Starting update processor."),this.Li(this.context)}Li(e,n,r){var c;let s=k.toLDContext(e);(c=this.updateProcessor)==null||c.close();let a=JSON.stringify(k.toLDContext(e)),o=Te(a,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Pt);this.createStreamingProcessor(s,e,o,n,r),this.updateProcessor.start()}};function Di(i){let e=It("visibilitychange",()=>{vi()==="hidden"&&i()}),n=Pt("pagehide",i);return()=>{e(),n()}}function tt(i){if(typeof i!="string")throw new TypeError("Expected a string");return i.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Jn(i,t,e,n){let s=((i.kind==="substring"||i.kind==="regex")&&n.includes("/")?t:t.replace(n,"")).replace(e,"");switch(i.kind){case"exact":return new RegExp(`^${tt(i.url)}/?$`).test(t);case"canonical":return new RegExp(`^${tt(i.url)}/?$`).test(s);case"substring":return new RegExp(`.*${tt(i.substring)}.*$`).test(s);case"regex":return new RegExp(i.pattern).test(s);default:return!1}}function zn(i,t){let e=[];return t.forEach(n=>{let r=i.target,{selector:s}=n,a=Ei(s);for(;r&&(a!=null&&a.length);){for(let o=0;o<a.length;o+=1)if(r===a[o]){e.push(n);break}r=r.parentNode}}),e}var et=class{constructor(t,e){let n=t.filter(a=>{var o;return(o=a.urls)==null?void 0:o.some(c=>Jn(c,C(),pi(),mi()))}),r=n.filter(a=>a.kind==="pageview"),s=n.filter(a=>a.kind==="click");if(r.forEach(a=>e(a)),s.length){let a=o=>{zn(o,s).forEach(c=>{e(c)})};this.ve=It("click",a)}}close(){var t;(t=this.ve)==null||t.call(this)}};var Wn=300,Mt=class{constructor(t){this.Ft=C();let e=()=>{let r=C();r!==this.Ft&&(this.Ft=r,t())};this.Ut=setInterval(e,Wn);let n=Pt("popstate",e);this.Ee=()=>{n()}}close(){var t;this.Ut&&clearInterval(this.Ut),(t=this.Ee)==null||t.call(this)}};var it=class{constructor(t,e,n,r,s,a=o=>new Mt(o)){this.D=e;this.Oi=r;this.Ai=s;this.dt=[];this.De=!1;this.ft=`${n}/sdk/goals/${t}`,this.we=a(()=>{this.jt()})}async initialize(){await this.Ci(),this.jt()}startTracking(){this.De=!0,this.jt()}jt(){var t;this.De&&((t=this.Vt)==null||t.close(),this.dt&&this.dt.length&&(this.Vt=new et(this.dt,e=>{this.Ai(C(),e)})))}async Ci(){try{let t=await this.D.fetch(this.ft);this.dt=await t.json()}catch(t){this.Oi(new J(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.we)==null||t.close(),(e=this.Vt)==null||e.close()}};function bi(i){return i.kind==="click"}var Yn=2,ki={fetchGoals:!0,eventUrlTransformer:i=>i,streaming:void 0},Xn={fetchGoals:u.Boolean,eventUrlTransformer:u.Function,streaming:u.Boolean};function Zn(i){var e;let t=g({},i);return(e=t.flushInterval)!=null||(t.flushInterval=Yn),t}function xi(i){let t=Zn(i);return Object.keys(ki).forEach(e=>{delete t[e]}),t}function Re(i,t){let e=g({},ki);return Object.entries(Xn).forEach(n=>{let[r,s]=n,a=i[r];a!==void 0&&(s.is(a)?e[r]=a:t.warn(b.wrongOptionType(r,s.getType(),typeof a)))}),e}var nt=class{constructor(t,e){this.Ti=t;this.be=[];switch(e){case"sha1":this.Bt="SHA-1";break;case"sha256":this.Bt="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.be.join(""),n=new TextEncoder().encode(e),r=await this.Ti.subtle.digest(this.Bt,n);switch(t){case"base64":return btoa(String.fromCharCode(...new Uint8Array(r)));case"hex":return[...new Uint8Array(r)].map(s=>s.toString(16).padStart(2,"0")).join("");default:throw new Error(`Encoding is not supported ${t}`)}}update(t){return this.be.push(t),this}};var Qn={start:0,end:3},tr={start:4,end:5},Ie={start:6,end:7},Pe={start:8,end:8},er={start:9,end:9},ir={start:10,end:15};function nr(){if(crypto&&crypto.getRandomValues){let t=new Uint8Array(16);return crypto.getRandomValues(t),[...t.values()]}let i=[];for(let t=0;t<16;t+=1)i.push(Math.floor(Math.random()*256));return i}function _(i,t){let e="";for(let n=t.start;n<=t.end;n+=1)e+=i[n].toString(16).padStart(2,"0");return e}function rr(i){return i[Pe.start]=(i[Pe.start]|128)&191,i[Ie.start]=i[Ie.start]&15|64,`${_(i,Qn)}-${_(i,tr)}-${_(i,Ie)}-${_(i,Pe)}${_(i,er)}-${_(i,ir)}`}function sr(){let i=nr();return rr(i)}function Me(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():sr()}var rt=class{createHash(t){return new nt(yi(),t)}randomUUID(){return Me()}};function ar(i){let t=Array.from(i,e=>String.fromCodePoint(e)).join("");return btoa(t)}var st=class{btoa(t){return ar(new TextEncoder().encode(t))}};var at=class{platformData(){return{name:"JS"}}sdkData(){return{name:"@launchdarkly/js-client-sdk",version:"0.0.0",userAgentBase:"JSClient"}}};var ot=class{constructor(t,e,n=Math.random){this.Ri=e;this.Ni=n;this.Ht=0;this._t=Math.max(1,t),this.ke=Math.ceil(Math.log2(3e4/this._t))}J(){let t=Math.min(this.Ht,this.ke),e=this._t*2**t;return Math.min(e,3e4)}$i(t){return t-Math.trunc(this.Ni()*.5*t)}success(t=Date.now()){this.gt=t}fail(t=Date.now()){this.gt!==void 0&&t-this.gt>this.Ri&&(this.Ht=0),this.gt=void 0;let e=this.$i(this.J());return this.Ht+=1,e}};var ct=class{constructor(t,e){this.ft=t;this.e={};this.J=new ot(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.xe=e.errorFilter,this.Se()}Se(){this.F=new EventSource(this.ft),this.F.onopen=()=>{var t;this.J.success(),(t=this.onopen)==null||t.call(this)},this.F.onerror=t=>{var e;this.Ii(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.e).forEach(([t,e])=>{e.forEach(n=>{var r;(r=this.F)==null||r.addEventListener(t,n)})})}addEventListener(t,e){var n,r,s;(r=(n=this.e)[t])!=null||(n[t]=[]),this.e[t].push(e),(s=this.F)==null||s.addEventListener(t,e)}close(){var t,e;clearTimeout(this.Kt),this.Kt=void 0,(t=this.F)==null||t.close(),(e=this.onclose)==null||e.call(this)}Pi(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.Kt=setTimeout(()=>{this.Se()},t)}Ii(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.xe(t))&&this.Pi(this.J.fail())}};var lt=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new ct(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function Si(){return typeof localStorage!="undefined"}var ut=class{constructor(t){this.t=t}async clear(t){var e;try{localStorage.removeItem(t)}catch(n){(e=this.t)==null||e.error(`Error clearing key from localStorage: ${t}, reason: ${n}`)}}async get(t){var e;try{let n=localStorage.getItem(t);return n!=null?n:null}catch(n){return(e=this.t)==null||e.error(`Error getting key from localStorage: ${t}, reason: ${n}`),null}}async set(t,e){var n;try{localStorage.setItem(t,e)}catch(r){(n=this.t)==null||n.error(`Error setting key in localStorage: ${t}, reason: ${r}`)}}};var ht=class{constructor(t){this.encoding=new st;this.info=new at;this.crypto=new rt;this.requests=new lt;Si()&&(this.storage=new ut(t))}};var Ft=class extends Ot{constructor(t,e,n={},r){var p;let{logger:s,debug:a}=n,o=s!=null?s:new I({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:a?"debug":"info"}),c=(p=n.baseUri)!=null?p:"https://clientsdk.launchdarkly.com",l=r!=null?r:new ht(o),h=Re(n,o),d=xi(D(g({},n),{logger:o})),{eventUrlTransformer:f}=h;super(t,e,l,d,(m,y,S,M,Ci)=>new Q(l,m,t,y,h,()=>({pathGet(T,$){return`/sdk/evalx/${t}/contexts/${de($,T)}`},pathReport(T,$){return`/sdk/evalx/${t}/context`},pathPing(T,$){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(T,$){return`/eval/${t}/${de($,T)}`},pathReport(T,$){return`/eval/${t}`},pathPing(T,$){return`/ping/${t}`}}),S,M,Ci),{analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:m=>new L.InputCustomEvent(m.context,m.key,m.data,m.metricValue,m.samplingRatio,f(C()))}),this.setEventSendingEnabled(!0,!1),h.fetchGoals&&(this.Gt=new it(t,l.requests,c,m=>{o.error(m.message)},(m,y)=>{let S=this.getInternalContext();if(!S)return;let M=f(m);bi(y)?this.sendEvent({kind:"click",url:M,samplingRatio:1,key:y.key,creationDate:Date.now(),context:S,selector:y.selector}):this.sendEvent({kind:"pageview",url:M,samplingRatio:1,key:y.key,creationDate:Date.now(),context:S})}),this.Gt.initialize(),h.automaticBackgroundHandling&&Di(()=>this.flush()))}async identify(t,e){var n;await super.identify(t,e),(n=this.Gt)==null||n.startTracking()}setStreaming(t){this.dataManager.setForcedStreaming(t)}Le(){this.dataManager.setAutomaticStreamingState(!!this.emitter.listenerCount("change"))}on(t,e){super.on(t,e),this.Le()}off(t,e){super.off(t,e),this.Le()}};var Li=["ready","failed","initialized"],dt=class{constructor(t){this.n=t;this.e=new Map}on(t,e){var n;Li.includes(t)?this.e.has(t)?(n=this.e.get(t))==null||n.push(e):this.e.set(t,[e]):this.n.on(t,e)}off(t,e){if(Li.includes(t)){let n=this.e.get(t);if(!n)return;if(e){let r=n.filter(s=>s!==e);r.length===0?this.e.delete(t):this.e.set(t,r);return}this.e.delete(t)}else this.n.off(t,e)}Ct(t,e,...n){try{t(...n)}catch(r){this.n.logger.error(`Encountered error invoking handler for "${e}", detail: "${r}"`)}}emit(t,...e){let n=this.e.get(t);n==null||n.forEach(r=>this.Ct(r,t,...e))}eventNames(){return[...this.e.keys()]}listenerCount(t){var e,n;return(n=(e=this.e.get(t))==null?void 0:e.length)!=null?n:0}};function Ut(i,t){let e=i.then(n=>(t&&setTimeout(()=>{t(null,n)},0),n),n=>{if(t)setTimeout(()=>{t(n,null)},0);else return Promise.reject(n)});return t?void 0:e}var ft=class{constructor(t,e,n){this.qt="initializing";let r=n==null?void 0:n.bootstrap,s=n==null?void 0:n.hash,a=g({},n);delete a.bootstrap,delete a.hash,this.n=new Ft(t,V.Disabled,n),this.x=new dt(this.n),this.logger=this.n.logger,this.Mi(e,r,s)}async Mi(t,e,n){var r,s;try{await this.n.identify(t,{noTimeout:!0,bootstrap:e,hash:n}),this.qt="success",(r=this.Ce)==null||r.call(this),this.x.emit("initialized")}catch(a){this.Oe=a,this.qt="failure",(s=this.Ae)==null||s.call(this,a),this.x.emit("failed",a)}this.x.emit("ready")}allFlags(){return this.n.allFlags()}boolVariation(t,e){return this.n.boolVariation(t,e)}boolVariationDetail(t,e){return this.n.boolVariationDetail(t,e)}jsonVariation(t,e){return this.n.jsonVariation(t,e)}jsonVariationDetail(t,e){return this.n.jsonVariationDetail(t,e)}numberVariation(t,e){return this.n.numberVariation(t,e)}numberVariationDetail(t,e){return this.n.numberVariationDetail(t,e)}off(t,e){this.x.off(t,e)}on(t,e){this.x.on(t,e)}stringVariation(t,e){return this.n.stringVariation(t,e)}stringVariationDetail(t,e){return this.n.stringVariationDetail(t,e)}track(t,e,n){this.n.track(t,e,n)}variation(t,e){return this.n.variation(t,e)}variationDetail(t,e){return this.n.variationDetail(t,e)}addHook(t){this.n.addHook(t)}setStreaming(t){this.n.setStreaming(t)}identify(t,e,n){return Ut(this.n.identify(t,{hash:e}).then(()=>this.allFlags()),n)}close(t){return Ut(this.n.close().then(),t)}flush(t){return Ut(this.n.flush().then(()=>{}),t)}getContext(){return this.n.getContext()}waitForInitialization(t){var e;if(this.z)return this.Te(this.z,t);switch(this.qt){case"success":return Promise.resolve();case"failure":return Promise.reject(this.Oe);case"initializing":break;default:throw new Error("Unexpected initialization state. This represents an implementation error in the SDK.")}return t===void 0&&((e=this.logger)==null||e.warn("The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied.")),this.z||(this.z=new Promise((n,r)=>{this.Ce=n,this.Ae=r})),this.Te(this.z,t)}async waitUntilReady(){try{await this.waitForInitialization()}catch(t){}}Te(t,e){if(e){let n=We(e,"waitForInitialization");return Promise.race([t.then(()=>n.cancel()),n.promise]).catch(r=>{var s;throw r instanceof B&&((s=this.logger)==null||s.error(r.message)),r})}return t}};function or(i){return new I(i)}function cr(i,t,e){return new ft(i,t,e)}0&&(module.exports={basicLogger,initialize});
1
+ "use strict";var mt=Object.defineProperty,Oi=Object.defineProperties,$i=Object.getOwnPropertyDescriptor,Mi=Object.getOwnPropertyDescriptors,Ri=Object.getOwnPropertyNames,gt=Object.getOwnPropertySymbols;var Ht=Object.prototype.hasOwnProperty,je=Object.prototype.propertyIsEnumerable;var Ve=(i,t,e)=>t in i?mt(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,p=(i,t)=>{for(var e in t||(t={}))Ht.call(t,e)&&Ve(i,e,t[e]);if(gt)for(var e of gt(t))je.call(t,e)&&Ve(i,e,t[e]);return i},D=(i,t)=>Oi(i,Mi(t));var Bt=(i,t)=>{var e={};for(var n in i)Ht.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&gt)for(var n of gt(i))t.indexOf(n)<0&&je.call(i,n)&&(e[n]=i[n]);return e};var Fi=(i,t)=>{for(var e in t)mt(i,e,{get:t[e],enumerable:!0})},Ui=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ri(t))!Ht.call(i,s)&&s!==e&&mt(i,s,{get:()=>t[s],enumerable:!(n=$i(t,s))||n.enumerable});return i};var Vi=i=>Ui(mt({},"__esModule",{value:!0}),i);var Ds={};Fi(Ds,{basicLogger:()=>ws,initialize:()=>Es});module.exports=Vi(Ds);function ji(i){return`/${i.replace(/~/g,"~0").replace(/\//g,"~1")}`}function Je(i){return i.indexOf("~")?i.replace(/~1/g,"/").replace(/~0/g,"~"):i}function Hi(i){return(i.startsWith("/")?i.substring(1):i).split("/").map(e=>Je(e))}function Bi(i){return!i.startsWith("/")}function _i(i){return!i.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var T=class{constructor(t,e=!1){if(e){let n=t;this.h=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?ji(n):n}else{if(this.redactionName=t,t===""||t==="/"||!_i(t)){this.isValid=!1,this.h=[];return}Bi(t)?this.h=[t]:t.indexOf("/",1)<0?this.h=[Je(t.slice(1))]:this.h=Hi(t),this.h[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{h:e,isValid:n}=this;if(!n)return;let s=t;for(let r=0;r<e.length;r+=1){let a=e[r];if(s!=null&&Object.prototype.hasOwnProperty.call(s,a)&&typeof s=="object"&&!Array.isArray(s))s=s[a];else return}return s}getComponent(t){return this.h[t]}get depth(){return this.h.length}get isKind(){return this.h.length===1&&this.h[0]==="kind"}compare(t){return this.depth===t.depth&&this.h.every((e,n)=>e===t.getComponent(n))}};T.InvalidReference=new T("");var Gt=class{is(t){if(Array.isArray(t))return!1;let n=typeof t;return n==="function"||n==="object"}getType(){return"factory method or object"}},A=class{constructor(t,e){this.Dt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.Dt}},wt=class{constructor(t,e){this.Dt=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?t.length>0?t.every(e=>typeof e===this.typeOf):!0:!1}getType(){return this.Dt}},G=class extends A{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},Et=class extends A{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},zt=class{is(t){return typeof t=="function"}getType(){return"function"}},qt=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},Ki=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,Jt=class{is(t){return typeof t=="number"||typeof t=="string"&&Ki.test(t)}getType(){return"date"}},Wt=class extends Et{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},u=class{static createTypeArray(t,e){return new wt(t,e)}static numberWithMin(t){return new G(t)}static stringMatchingRegex(t){return new Et(t)}};u.String=new A("string","");u.Number=new A("number",0);u.ObjectOrFactory=new Gt;u.Object=new A("object",{});u.StringArray=new wt("string[]","");u.Boolean=new A("boolean",!0);u.Function=new zt;u.Date=new Jt;u.Kind=new Wt;u.NullableBoolean=new qt;function We(i){return"kind"in i?u.String.is(i.kind)&&i.kind!=="multi":!1}function Ye(i){return"kind"in i?u.String.is(i.kind)&&i.kind==="multi":!1}function Ze(i){return!("kind"in i)||i.kind===null||i.kind===void 0}var Yt="user";function He(i){return i.includes("%")||i.includes(":")?i.replace(/%/g,"%25").replace(/:/g,"%3A"):i}function Gi(i){return i&&u.Object.is(i)}function Be(i){return u.Kind.is(i)}function _e(i){return u.String.is(i)&&i!==""}function _t(i,t=!1){return i?i.map(e=>new T(e,t)):[]}function zi(i){return i!=null}function qi(i){let t=D(p({},i.custom||[]),{kind:"user",key:String(i.key)});if(zi(i.anonymous)){let e=!!i.anonymous;delete t.anonymous,t.anonymous=e}return i.name!==null&&i.name!==void 0&&(t.name=i.name),i.ip!==null&&i.ip!==void 0&&(t.ip=i.ip),i.firstName!==null&&i.firstName!==void 0&&(t.firstName=i.firstName),i.lastName!==null&&i.lastName!==void 0&&(t.lastName=i.lastName),i.email!==null&&i.email!==void 0&&(t.email=i.email),i.avatar!==null&&i.avatar!==void 0&&(t.avatar=i.avatar),i.country!==null&&i.country!==void 0&&(t.country=i.country),i.privateAttributeNames!==null&&i.privateAttributeNames!==void 0&&(t._meta={privateAttributes:i.privateAttributeNames}),t}var k=class i{constructor(t,e,n){this.k=!1,this.nt=!1,this.ne=!1,this.P={},this.kind=e,this.valid=t,this.message=n}static w(t,e){return new i(!1,t,e)}static Ke(t,e){if(!(!e||!t.isValid))return t.depth===1&&t.getComponent(0)==="anonymous"?!!(e!=null&&e.anonymous):t.get(e)}se(t){if(this.k)return this.P[t];if(this.kind===t)return this.N}static Ge(t){let e=Object.keys(t).filter(c=>c!=="kind"),n=e.every(Be);if(!e.length)return i.w("multi","A multi-kind context must contain at least one kind");if(!n)return i.w("multi","Context contains invalid kinds");let s={},r=!0,a=e.reduce((c,l)=>{var d;let h=t[l];return Gi(h)?(c[l]=h,s[l]=_t((d=h._meta)==null?void 0:d.privateAttributes)):r=!1,c},{});if(!r)return i.w("multi","Context contained contexts that were not objects");if(!Object.values(a).every(c=>_e(c.key)))return i.w("multi","Context contained invalid keys");if(e.length===1){let c=e[0],l=new i(!0,c);return l.N=D(p({},a[c]),{kind:c}),l.st=s,l.nt=c==="user",l}let o=new i(!0,t.kind);return o.P=a,o.st=s,o.k=!0,o}static ze(t){var c;let{key:e,kind:n}=t,s=Be(n),r=_e(e);if(!s)return i.w(n!=null?n:"unknown","The kind was not valid for the context");if(!r)return i.w(n,"The key for the context was not valid");let a=_t((c=t._meta)==null?void 0:c.privateAttributes),o=new i(!0,n);return o.nt=n==="user",o.N=t,o.st={[n]:a},o}static qe(t){if(!(t.key!==void 0&&t.key!==null))return i.w("user","The key for the context was not valid");let n=new i(!0,"user");return n.nt=!0,n.ne=!0,n.N=qi(t),n.st={user:_t(t.privateAttributeNames,!0)},n}static fromLDContext(t){return t?We(t)?i.ze(t):Ye(t)?i.Ge(t):Ze(t)?i.qe(t):i.w("unknown","Context was not of a valid kind"):i.w("unknown","No context specified. Returning default value")}static toLDContext(t){if(!t.valid)return;let e=t.getContexts();if(!t.k)return e[0][1];let n={kind:"multi"};return e.forEach(s=>{let r=s[0],a=s[1];n[r]=a}),n}valueForKind(t,e=Yt){return t.isKind?this.kinds:i.Ke(t,this.se(e))}key(t=Yt){var e;return(e=this.se(t))==null?void 0:e.key}get isMultiKind(){return this.k}get canonicalKey(){return this.nt?this.N.key:this.k?Object.keys(this.P).sort().map(t=>`${t}:${He(this.P[t].key)}`).join(":"):`${this.kind}:${He(this.N.key)}`}get kinds(){return this.k?Object.keys(this.P):[this.kind]}get kindsAndKeys(){return this.k?Object.entries(this.P).reduce((t,[e,n])=>(t[e]=n.key,t),{}):{[this.kind]:this.N.key}}privateAttributes(t){var e;return((e=this.st)==null?void 0:e[t])||[]}getContexts(){return this.k?Object.entries(this.P):[[this.kind,this.N]]}get legacy(){return this.ne}};k.UserKind=Yt;var Ji=["key","kind","_meta","anonymous"].map(i=>new T(i,!0)),Wi=["name","ip","firstName","lastName","email","avatar","country"];function Yi(i,t){return i.depth===t.length&&t.every((e,n)=>e===i.getComponent(n))}function Zi(i,t){let e=[],n={},s=[];for(e.push(...Object.keys(i).map(r=>({key:r,ptr:[r],source:i,parent:n,visited:[i]})));e.length;){let r=e.pop(),a=t.find(o=>Yi(o,r.ptr));if(a)s.push(a.redactionName);else{let o=r.source[r.key];o===null?r.parent[r.key]=o:Array.isArray(o)?r.parent[r.key]=[...o]:typeof o=="object"?r.visited.includes(o)||(r.parent[r.key]={},e.push(...Object.keys(o).map(c=>({key:c,ptr:[...r.ptr,c],source:o,parent:r.parent[r.key],visited:[...r.visited,o]})))):r.parent[r.key]=o}}return{cloned:n,excluded:s.sort()}}var Zt=class{constructor(t,e){this.Je=t,this.We=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.re(t,n[0][1],n[0][0],e);let s={kind:"multi"};return n.forEach(([r,a])=>{s[r]=this.re(t,a,r,e)}),s}Ye(t,e,n,s){return(s?Object.keys(e).map(r=>new T(r,!0)):[...this.We,...t.privateAttributes(n)]).filter(r=>!Ji.some(a=>a.compare(r)))}re(t,e,n,s){let r=this.Je||s&&e.anonymous===!0,{cloned:a,excluded:o}=Zi(e,this.Ye(t,e,n,r));return t.legacy&&Wi.forEach(c=>{c in a&&(a[c]=String(a[c]))}),o.length&&(a._meta||(a._meta={}),a._meta.redactedAttributes=o),a._meta&&(delete a._meta.privateAttributes,Object.keys(a._meta).length===0&&delete a._meta),a}},Ke=30*1e3,Xi=.5,Dt=class{constructor(t,e,n=Math.random){this.Ze=e,this.Xe=n,this.bt=0,this.ae=Math.max(1,t),this.Qe=Math.ceil(Math.log2(Ke/this.ae))}x(){let t=Math.min(this.bt,this.Qe),e=this.ae*2**t;return Math.min(e,Ke)}ti(t){return t-Math.trunc(this.Xe()*Xi*t)}success(t=Date.now()){this.kt=t}fail(t=Date.now()){this.kt!==void 0&&t-this.kt>this.Ze&&(this.bt=0),this.kt=void 0;let e=this.ti(this.x());return this.bt+=1,e}};var Ge;(function(i){i[i.Valid=0]="Valid",i[i.Initializing=1]="Initializing",i[i.Interrupted=2]="Interrupted",i[i.Closed=3]="Closed"})(Ge||(Ge={}));var ks=2*60*1e3,xs=5*60*1e3;var w;(function(i){i.Unknown="UNKNOWN",i.NetworkError="NETWORK_ERROR",i.ErrorResponse="ERROR_RESPONSE",i.InvalidData="INVALID_DATA"})(w||(w={}));var O=class extends Error{constructor(t,e,n,s=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=s}},U=class extends Error{constructor(t,e,n,s=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=s}},V;(function(i){i[i.Disabled=0]="Disabled",i[i.Enabled=1]="Enabled"})(V||(V={}));var j;(function(i){i[i.AnalyticsEvents=0]="AnalyticsEvents",i[i.DiagnosticEvent=1]="DiagnosticEvent"})(j||(j={}));var N;(function(i){i[i.Succeeded=0]="Succeeded",i[i.Failed=1]="Failed",i[i.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(N||(N={}));function F(i){if(typeof i=="string")return i;if(i===void 0)return"undefined";if(i===null)return"null";if(Object.prototype.hasOwnProperty.call(i,"toString"))try{return i.toString()}catch(t){}if(typeof i=="bigint")return`${i}n`;try{return JSON.stringify(i)}catch(t){return t instanceof TypeError&&t.message.indexOf("circular")>=0?"[Circular]":"[Not Stringifiable]"}}function Qi(i){return typeof i=="symbol"?"NaN":typeof i=="bigint"?`${i}n`:String(Number(i))}function tn(i){return typeof i=="symbol"?"NaN":typeof i=="bigint"?`${i}n`:String(parseInt(i,10))}function en(i){return typeof i=="symbol"?"NaN":String(parseFloat(i))}var yt={s:i=>F(i),d:i=>Qi(i),i:i=>tn(i),f:i=>en(i),j:i=>F(i),o:i=>F(i),O:i=>F(i),c:()=>""};function Xt(...i){var e;let t=i.shift();if(u.String.is(t)){let n="",s=0;for(;s<t.length;){let r=t.charAt(s);if(r==="%"){if(s+1<t.length){let o=t.charAt(s+1);if(o in yt&&i.length){let c=i.shift();n+=(e=yt[o])==null?void 0:e.call(yt,c)}else o==="%"?n+="%":n+=`%${o}`;s+=2}}else n+=r,s+=1}return i.length&&(n.length&&(n+=" "),n+=i.map(F).join(" ")),n}return i.map(F).join(" ")}var v;(function(i){i[i.debug=0]="debug",i[i.info=1]="info",i[i.warn=2]="warn",i[i.error=3]="error",i[i.none=4]="none"})(v||(v={}));var nn=["debug","info","warn","error","none"],$=class i{static get(){return new i({})}constructor(t){var e,n,s;if(this.ci=(n=v[(e=t.level)!=null?e:"info"])!=null?n:v.info,this.li=(s=t.name)!=null?s:"LaunchDarkly",this.ue=t.formatter,typeof t.destination=="object")this.he={[v.debug]:t.destination.debug,[v.info]:t.destination.info,[v.warn]:t.destination.warn,[v.error]:t.destination.error};else if(typeof t.destination=="function"){let{destination:r}=t;this.he={[v.debug]:r,[v.info]:r,[v.warn]:r,[v.error]:r}}}ui(...t){var e;try{return this.ue?(e=this.ue)==null?void 0:e.call(this,...t):Xt(...t)}catch(n){return Xt(...t)}}hi(t,e){try{t(e)}catch(n){console.error(e)}}E(t,e){var n;if(t>=this.ci){let s=`${nn[t]}: [${this.li}]`;try{let r=(n=this.he)==null?void 0:n[t];r?this.hi(r,`${s} ${this.ui(...e)}`):console.error(...e)}catch(r){console.error(...e)}}}error(...t){this.E(v.error,t)}warn(...t){this.E(v.warn,t)}info(...t){this.E(v.info,t)}debug(...t){this.E(v.debug,t)}},sn={error:u.Function,warn:u.Function,info:u.Function,debug:u.Function},z=class{constructor(t,e){Object.entries(sn).forEach(([n,s])=>{if(!s.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.di=e}E(t,e){try{this.t[t](...e)}catch(n){this.di[t](...e)}}error(...t){this.E("error",t)}warn(...t){this.E("warn",t)}info(...t){this.E("info",t)}debug(...t){this.E("debug",t)}},ue=i=>{let t=new $({level:"info",destination:console.error,formatter:Xt});return i?new z(i,t):t},b=class{static deprecated(t,e){return`"${t}" is deprecated, please use "${e}"`}static optionBelowMinimum(t,e,n){return`Config option "${t}" had invalid value of ${e}, using minimum of ${n} instead`}static unknownOption(t){return`Ignoring unknown config option "${t}"`}static wrongOptionType(t,e,n){return`Config option "${t}" should be of type ${e}, got ${n}, using default value`}static wrongOptionTypeBoolean(t,e){return`Config option "${t}" should be a boolean, got ${e}, converting to boolean`}static invalidTagValue(t){return`Config option "${t}" must only contain letters, numbers, ., _ or -.`}static tagValueTooLong(t){return`Value of "${t}" was longer than 64 characters and was discarded.`}static partialEndpoint(t){return`You have set custom uris without specifying the ${t} URI; connections may not work properly`}},rn=/^(\w|\.|-)+$/,an=u.stringMatchingRegex(rn),on={is:(i,t)=>an.is(i)?i.length>64?{valid:!1,message:b.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:b.invalidTagValue(t)}},bt=class{constructor(t){let e={},n=t==null?void 0:t.application,s=t==null?void 0:t.logger;n&&Object.entries(n).forEach(([a,o])=>{if(o!=null){let{valid:c,message:l}=on.is(o,`application.${a}`);c?a==="versionName"?e["application-version-name"]=[o]:e[`application-${a}`]=[o]:s==null||s.warn(l)}});let r=Object.keys(e);r.length&&(this.value=r.sort().flatMap(a=>e[a].sort().map(o=>`${a}/${o}`)).join(" "))}},kt=class{constructor(t,e,n){this.platform=n,this.basicConfiguration={tags:e.tags,logger:e.logger,offline:e.offline,serviceEndpoints:e.serviceEndpoints,sdkKey:t}}};function Kt(i){return i.replace(/\/+$/,"")}function he(i){return i.replace(/^\/+/,"").replace(/\?$/,"")}var M=class i{constructor(t,e,n=i.DEFAULT_EVENTS,s="/bulk",r="/diagnostic",a=!0,o){this.streaming=Kt(t),this.polling=Kt(e),this.events=Kt(n),this.analyticsEventPath=s,this.diagnosticEventPath=r,this.includeAuthorizationHeader=a,this.payloadFilterKey=o}};M.DEFAULT_EVENTS="https://events.launchdarkly.com";function de(i,t){if(t.length===0)return i;let e=t.map(({key:n,value:s})=>`${n}=${s}`);return`${i}?${e.join("&")}`}function Xe(i,t,e){let n=he(t),s=[...e];return i.payloadFilterKey&&s.push({key:"filter",value:i.payloadFilterKey}),de(`${i.streaming}/${n}`,s)}function Qe(i,t,e){let n=he(t),s=[...e];return i.payloadFilterKey&&s.push({key:"filter",value:i.payloadFilterKey}),de(`${i.polling}/${n}`,s)}function ze(i,t,e){let n=he(t);return de(`${i.events}/${n}`,e)}var q=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},J=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},H=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function Y(i){return i>=400&&i<500?i===400||i===408||i===429:!0}function cn(i){return i===413?!0:Y(i)}function ti(i,t){let e,n;return{promise:new Promise((r,a)=>{n=r,e=setTimeout(()=>{let o=`${t} timed out after ${i} seconds.`;a(new H(o))},i*1e3)}),cancel:()=>{n(),clearTimeout(e)}}}function fe(i){return i==null?i:JSON.parse(JSON.stringify(i))}function At(i){return Math.trunc(i*1e3)}var ln=i=>JSON.stringify(i)==="{}",It=(i,t)=>i&&Object.entries(i).reduce((e,[n,s])=>(s&&!ln(s)&&!(t!=null&&t.includes(n))&&(e[n]=typeof s=="object"?It(s,t):s),e),{});function K(i,t){if(i===t)return!0;if(i&&t&&typeof i=="object"&&typeof t=="object"){if(i.constructor!==t.constructor)return!1;var e,n,s;if(Array.isArray(i)){if(e=i.length,e!=t.length)return!1;for(n=e;n--!==0;)if(!K(i[n],t[n]))return!1;return!0}if(i instanceof Map&&t instanceof Map){if(i.size!==t.size)return!1;for(n of i.entries())if(!t.has(n[0]))return!1;for(n of i.entries())if(!K(n[1],t.get(n[0])))return!1;return!0}if(i instanceof Set&&t instanceof Set){if(i.size!==t.size)return!1;for(n of i.entries())if(!t.has(n[0]))return!1;return!0}if(ArrayBuffer.isView(i)&&ArrayBuffer.isView(t)){if(e=i.length,e!=t.length)return!1;for(n=e;n--!==0;)if(i[n]!==t[n])return!1;return!0}if(i.constructor===RegExp)return i.source===t.source&&i.flags===t.flags;if(i.valueOf!==Object.prototype.valueOf)return i.valueOf()===t.valueOf();if(i.toString!==Object.prototype.toString)return i.toString()===t.toString();if(s=Object.keys(i),e=s.length,e!==Object.keys(t).length)return!1;for(n=e;n--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[n]))return!1;for(n=e;n--!==0;){var r=s[n];if(!K(i[r],t[r]))return!1}return!0}return i!==i&&t!==t}function ei(i,t,e,n=!0,s="user-agent"){let{userAgentBase:r,version:a,wrapperName:o,wrapperVersion:c}=t.sdkData(),l={[s]:`${r!=null?r:"NodeJSClient"}/${a}`};return n&&(l.authorization=i),o&&(l["x-launchdarkly-wrapper"]=c?`${o}/${c}`:o),e!=null&&e.value&&(l["x-launchdarkly-tags"]=e.value),l}function B(i,t,e){let n;i.status?n=`error ${i.status}${i.status===401?" (invalid SDK key)":""}`:n=`I/O error (${i.message||"unknown error"})`;let s=e!=null?e:"giving up permanently";return`Received ${n} for ${t} - ${s}`}function ii({status:i}){return i?Y(i):!0}var pe=(i,t)=>t.btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var un=async(i=1e3)=>new Promise(t=>{setTimeout(t,i)}),ni=(i,t)=>new Promise((e,n)=>{setTimeout(()=>{let s=`${t} timed out after ${i} seconds.`;n(new H(s))},i*1e3)}),Qt=class{constructor(t,e,n){this.l=e,this.fi=n,this.Lt=[],this.de=Date.now(),this.fe=this.de,this.pe={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var n,s,r;let t=this.l.info.sdkData(),e=this.l.info.platformData();return{kind:"diagnostic-init",id:this.pe,creationDate:this.de,sdk:t,configuration:this.fi,platform:p({name:e.name,osArch:(n=e.os)==null?void 0:n.arch,osName:(s=e.os)==null?void 0:s.name,osVersion:(r=e.os)==null?void 0:r.version},e.additional||{})}}recordStreamInit(t,e,n){let s={timestamp:t,failed:e,durationMillis:n};this.Lt.push(s)}createStatsEventAndReset(t,e,n){let s=Date.now(),r={kind:"diagnostic",id:this.pe,creationDate:s,dataSinceDate:this.fe,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.Lt};return this.Lt=[],this.fe=s,r}},te;(function(i){i.MalformedFlag="MALFORMED_FLAG",i.UserNotSpecified="USER_NOT_SPECIFIED",i.FlagNotFound="FLAG_NOT_FOUND",i.ClientNotReady="CLIENT_NOT_READY",i.WrongType="WRONG_TYPE"})(te||(te={}));var hn=te,xt=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};xt.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var ee=class{constructor(t,e){let{basicConfiguration:n,platform:s}=t,{serviceEndpoints:{analyticsEventPath:r,diagnosticEventPath:a}}=n,{crypto:o,requests:c}=s;this.pi=p({},e),this.ge=ze(n.serviceEndpoints,r,[]),this.gi=ze(n.serviceEndpoints,a,[]),this.L=c,this.mi=o}async rt(t,e,n,s){let r={status:N.Succeeded},a=D(p({},this.pi),{"content-type":"application/json"});n&&(a["x-launchdarkly-payload-id"]=n,a["x-launchDarkly-event-schema"]="4");let o;try{let{status:c,headers:l}=await this.L.fetch(e,{headers:a,body:JSON.stringify(t),compressBodyIfPossible:!0,method:"POST",keepalive:!0}),h=Date.parse(l.get("date")||"");if(h&&(r.serverTime=h),c<=204)return r;if(o=new q(B({status:c,message:"some events were dropped"},"event posting")),!Y(c))return cn(c)?r.status=N.Failed:r.status=N.FailedAndMustShutDown,r.error=o,r}catch(c){o=c}return o&&!s?(r.status=N.Failed,r.error=o,r):(await un(),this.rt(t,this.ge,n,!1))}async sendEventData(t,e){let n=t===j.AnalyticsEvents?this.mi.randomUUID():void 0,s=t===j.AnalyticsEvents?this.ge:this.gi;return this.rt(e,s,n,!0)}};function ie(i){return i.kind==="feature"}function dn(i){return i.kind==="identify"}function fn(i){return i.kind==="migration_op"}var ne=class{constructor(t,e,n,s,r,a){this.count=t,this.key=e,this.value=n,this.version=r,this.variation=a,this.default=s}increment(){this.count+=1}};function pn(i){return`${i.key}:${i.variation!==null&&i.variation!==void 0?i.variation:""}:${i.version!==null&&i.version!==void 0?i.version:""}`}var se=class{constructor(){this.Z=0,this.at=0,this.ot={},this.ct={}}summarizeEvent(t){if(ie(t)&&!t.excludeFromSummaries){let e=pn(t),n=this.ot[e],s=this.ct[t.key];s||(s=new Set,this.ct[t.key]=s),t.context.kinds.forEach(r=>s.add(r)),n?n.increment():this.ot[e]=new ne(1,t.key,t.value,t.default,t.version,t.variation),(this.Z===0||t.creationDate<this.Z)&&(this.Z=t.creationDate),t.creationDate>this.at&&(this.at=t.creationDate)}}getSummary(){let t=Object.values(this.ot).reduce((e,n)=>{let s=e[n.key];s||(s={default:n.default,counters:[],contextKinds:[...this.ct[n.key]]},e[n.key]=s);let r={value:n.value,count:n.count};return n.variation!==void 0&&n.variation!==null&&(r.variation=n.variation),n.version!==void 0&&n.version!==null?r.version=n.version:r.unknown=!0,s.counters.push(r),e},{});return{startDate:this.Z,endDate:this.at,features:t,kind:"summary"}}clearSummary(){this.Z=0,this.at=0,this.ot={},this.ct={}}},re=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}};function vt(i){let t=Math.trunc(i);return t===1?!0:t===0?!1:Math.floor(Math.random()*t)===0}var ae=class{constructor(t,e,n,s,r,a=!0){this.r=t,this.lt=s,this.D=r,this.Ct=new se,this.ut=[],this.me=0,this.Tt=0,this.At=0,this.It=!1,this.ye=0,this.Pt=!1,this.Nt=null,this.yi=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.ve=new ee(e,n),this.ht=new Zt(t.allAttributesPrivate,t.privateAttributes.map(o=>new T(o))),a&&this.start()}start(){var t,e;if(((t=this.lt)==null?void 0:t.flushInterval)!==void 0&&(this.Nt=setInterval(()=>{var n;(n=this.lt)==null||n.flush()},this.lt.flushInterval*1e3)),this.vi=setInterval(async()=>{var n;try{await this.flush()}catch(s){(n=this.t)==null||n.debug(`Flush failed: ${s}`)}},this.r.flushInterval*1e3),this.D){let n=this.D.createInitEvent();this.we(n),this.Ee=setInterval(()=>{let s=this.D.createStatsEventAndReset(this.Tt,this.At,this.ye);this.Tt=0,this.At=0,this.we(s)},this.r.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}we(t){this.ve.sendEventData(j.DiagnosticEvent,t)}close(){clearInterval(this.vi),this.Nt&&clearInterval(this.Nt),this.Ee&&clearInterval(this.Ee)}async flush(){var n;if(this.Pt)throw new re("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.ut;this.ut=[];let e=this.Ct.getSummary();this.Ct.clearSummary(),Object.keys(e.features).length&&t.push(e),t.length&&(this.ye=t.length,(n=this.t)==null||n.debug("Flushing %d events",t.length),await this.rt(t))}sendEvent(t){var c;if(this.Pt)return;if(fn(t)){if(vt(t.samplingRatio)){let l=D(p({},t),{context:t.context?this.ht.filter(t.context):void 0});l.samplingRatio===1&&delete l.samplingRatio,this.dt(l)}return}this.Ct.summarizeEvent(t);let e=ie(t),n=e&&t.trackEvents||!e,s=this.wi(t),r=dn(t),a=(c=this.lt)==null?void 0:c.processContext(t.context);a||r||(this.At+=1),a&&!r&&this.dt(this.Ot({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),n&&vt(t.samplingRatio)&&this.dt(this.Ot(t,!1)),s&&vt(t.samplingRatio)&&this.dt(this.Ot(t,!0))}Ot(t,e){switch(t.kind){case"feature":{let n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.ht.filter(t.context,!e),key:t.key,value:t.value,default:t.default};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.prereqOf&&(n.prereqOf=t.prereqOf),t.variation!==void 0&&(n.variation=t.variation),t.version!==void 0&&(n.version=t.version),t.reason&&(n.reason=t.reason),n}case"index":case"identify":{let n={kind:t.kind,creationDate:t.creationDate,context:this.ht.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),n}case"custom":{let n={kind:"custom",creationDate:t.creationDate,key:t.key,context:this.ht.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),t.data!==void 0&&(n.data=t.data),t.metricValue!==void 0&&(n.metricValue=t.metricValue),t.url!==void 0&&(n.url=t.url),n}case"click":return{kind:"click",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url,selector:t.selector};case"pageview":return{kind:"pageview",creationDate:t.creationDate,contextKeys:t.context.kindsAndKeys,key:t.key,url:t.url};default:return t}}dt(t){var e;this.ut.length<this.yi?(this.ut.push(t),this.It=!1):(this.It||(this.It=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.Tt+=1)}wi(t){return ie(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.me&&t.debugEventsUntilDate>Date.now()}async rt(t){let e=await this.ve.sendEventData(j.AnalyticsEvents,t);if(e.status===N.FailedAndMustShutDown&&(this.Pt=!0),e.serverTime&&(this.me=e.serverTime),e.error)throw e.error}},St=class{constructor(t,e,n,s,r=1,a){this.context=t,this.key=e,this.data=n,this.metricValue=s,this.samplingRatio=r,this.url=a,this.kind="custom",this.creationDate=Date.now(),this.context=t}},W=class{constructor(t,e,n,s,r,a,o,c,l,h,d,f,g=1){this.withReasons=t,this.context=e,this.key=n,this.samplingRatio=g,this.kind="feature",this.creationDate=Date.now(),this.value=s,this.default=r,a!==void 0&&(this.version=a),o!==void 0&&(this.variation=o),c!==void 0&&(this.trackEvents=c),l!==void 0&&(this.prereqOf=l),h!==void 0&&(this.reason=h),d!==void 0&&(this.debugEventsUntilDate=d),f!==void 0&&(this.excludeFromSummaries=f)}},Lt=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},oe=class{close(){}async flush(){}sendEvent(){}},ce=class{constructor(t){this.$t=t}evalEvent(t){var e;return new W(this.$t,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.$t||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new W(this.$t,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new Lt(t,1)}customEvent(t,e,n,s,r=1){return new St(e,t,n!=null?n:void 0,s!=null?s:void 0,r)}},Ct=class{constructor(t,e,n){this.Ei=t,this.u=e,this.t=n,this.e=[],this.$=void 0,this.H=!1,this.B=[],this.Di=s=>{if(this.Mt(),!s.payloads.length)return;let r=s.payloads[0];switch(r==null?void 0:r.code){case"xfer-full":this.H=!0;break;case"xfer-changes":this.H=!1;break;case"none":this.H=!1,this.bi(r);break;default:return}this.$=r==null?void 0:r.id},this.ki=s=>{var a;if(!this.$||!s.kind||!s.key||!s.version||!s.object)return;let r=this.xi(s.kind,s.object);if(!r){(a=this.t)==null||a.warn(`Unable to process object for kind: '${s.kind}'`);return}this.B.push({kind:s.kind,key:s.key,version:s.version,object:r})},this.Si=s=>{!this.$||!s.kind||!s.key||!s.version||this.B.push({kind:s.kind,key:s.key,version:s.version,deleted:!0})},this.bi=s=>{if(!s.id||!s.target)return;let r={id:s.id,version:s.target,basis:!1,updates:[]};this.e.forEach(a=>a(r)),this.De()},this.Li=s=>{if(!this.$||!s.state||!s.version){this.Mt();return}let r={id:this.$,version:s.version,state:s.state,basis:this.H,updates:this.B};this.e.forEach(a=>a(r)),this.De()},this.Ci=s=>{var r;(r=this.t)==null||r.info(`Goodbye was received from the LaunchDarkly connection with reason: ${s.reason}.`),this.Mt()},this.Ti=s=>{var r;(r=this.t)==null||r.info(`An issue was encountered receiving updates for payload ${this.$} with reason: ${s.reason}.`),this.Ai()}}addPayloadListener(t){this.e.push(t)}removePayloadListener(t){let e=this.e.indexOf(t,0);e>-1&&this.e.splice(e,1)}processEvents(t){t.forEach(e=>{switch(e.event){case"server-intent":{this.Di(e.data);break}case"put-object":{this.ki(e.data);break}case"delete-object":{this.Si(e.data);break}case"payload-transferred":{this.Li(e.data);break}case"goodbye":{this.Ci(e.data);break}case"error":{this.Ti(e.data);break}}})}xi(t,e){var n,s;return(s=(n=this.Ei)[t])==null?void 0:s.call(n,e)}De(){this.H=!1,this.B=[]}Ai(){this.B=[]}Mt(){this.$=void 0,this.H=!1,this.B=[]}},le=class{constructor(t,e,n,s){this.u=n,this.t=s,this._(t,"server-intent"),this._(t,"put-object"),this._(t,"delete-object"),this._(t,"payload-transferred"),this._(t,"goodbye"),this._(t,"error"),this.Rt=new Ct(e,n,s)}addPayloadListener(t){this.Rt.addPayloadListener(t)}removePayloadListener(t){this.Rt.removePayloadListener(t)}_(t,e){t.addEventListener(e,async n=>{var s,r,a,o,c;if(n!=null&&n.data){(s=this.t)==null||s.debug(`Received ${e} event. Data is ${n.data}`);try{this.Rt.processEvents([{event:e,data:JSON.parse(n.data)}])}catch(l){(r=this.t)==null||r.error(`Stream received data that was unable to be processed in "${e}" message`),(a=this.t)==null||a.debug(`Data follows: ${n.data}`),(o=this.u)==null||o.call(this,w.InvalidData,"Malformed data in EventStream.")}}else(c=this.u)==null||c.call(this,w.Unknown,"Event from EventStream missing data.")})}};function gn(i){if(i){let t=Object.keys(i).find(e=>e.toLowerCase()==="x-ld-envid");if(t)return{environmentId:i[t]}}}var qe="unknown plugin";function Tt(i,t){try{return t.getMetadata().name||qe}catch(e){return i.error("Exception thrown getting metadata for plugin. Unable to get plugin name."),qe}}function mn(i,t,e){let n=[];return e.forEach(s=>{var r;try{let a=(r=s.getHooks)==null?void 0:r.call(s,t);a===void 0?i.error(`Plugin ${Tt(i,s)} returned undefined from getHooks.`):a&&a.length>0&&n.push(...a)}catch(a){i.error(`Exception thrown getting hooks for plugin ${Tt(i,s)}. Unable to get hooks.`)}}),n}function yn(i,t,e,n){n.forEach(s=>{try{s.register(e,t)}catch(r){i.error(`Exception thrown registering plugin ${Tt(i,s)}.`)}})}var x=Object.freeze({__proto__:null,ClientMessages:xt,DiagnosticsManager:Qt,ErrorKinds:hn,EventFactoryBase:ce,EventProcessor:ae,InputCustomEvent:St,InputEvalEvent:W,InputIdentifyEvent:Lt,NullEventProcessor:oe,PayloadProcessor:Ct,PayloadStreamReader:le,initMetadataFromHeaders:gn,isLegacyUser:Ze,isMultiKind:Ye,isSingleKind:We,safeGetHooks:mn,safeGetName:Tt,safeRegisterPlugins:yn,shouldSample:vt});var E;(function(i){i.Initializing="INITIALIZING",i.Valid="VALID",i.Interrupted="INTERRUPTED",i.SetOffline="SET_OFFLINE",i.Closed="CLOSED"})(E||(E={}));function wn(i){return i>=200&&i<=299}var Pt=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}},we=class{constructor(t,e,n,s,r){this.L=t,this.Ii=e,this.ft=n,this.Pi=s,this.Ni=r}async requestPayload(){let t;try{let e=await this.L.fetch(this.Ii,{method:this.Pi,headers:this.ft,body:this.Ni});if(wn(e.status))return await e.text();t=e.status}catch(e){throw new Pt(e==null?void 0:e.message)}throw new Pt(`Unexpected status code: ${t}`,t)}};function Ne(i,t,e,n,s,r,a,o,c,l){let h,d="GET",f=p({},r);c&&(d="REPORT",f["content-type"]="application/json",h=i);let g=c?e.pathReport(s,i):e.pathGet(s,i),m=[...a!=null?a:[]];o&&m.push({key:"withReasons",value:"true"}),l&&m.push({key:"h",value:l});let y=Qe(t,g,m);return new we(n,y,f,d,h)}var En={logger:u.Object,maxCachedContexts:u.numberWithMin(0),baseUri:u.String,streamUri:u.String,eventsUri:u.String,capacity:u.numberWithMin(1),diagnosticRecordingInterval:u.numberWithMin(2),flushInterval:u.numberWithMin(2),streamInitialReconnectDelay:u.numberWithMin(0),allAttributesPrivate:u.Boolean,debug:u.Boolean,diagnosticOptOut:u.Boolean,withReasons:u.Boolean,sendEvents:u.Boolean,pollInterval:u.numberWithMin(30),useReport:u.Boolean,privateAttributes:u.StringArray,applicationInfo:u.Object,wrapperName:u.String,wrapperVersion:u.String,payloadFilterKey:u.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:u.createTypeArray("Hook[]",{}),inspectors:u.createTypeArray("LDInspection",{})},Dn=60*5,ci="https://clientsdk.launchdarkly.com",li="https://clientstream.launchdarkly.com";function bn(i){return i instanceof z?i:ue(i)}var Ee=class{constructor(t={},e={getImplementationHooks:()=>[],credentialType:"mobileKey"}){var s,r,a;this.logger=ue(),this.baseUri=ci,this.eventsUri=M.DEFAULT_EVENTS,this.streamUri=li,this.maxCachedContexts=5,this.capacity=100,this.diagnosticRecordingInterval=900,this.flushInterval=30,this.streamInitialReconnectDelay=1,this.allAttributesPrivate=!1,this.debug=!1,this.diagnosticOptOut=!1,this.sendEvents=!0,this.sendLDHeaders=!0,this.useReport=!1,this.withReasons=!1,this.privateAttributes=[],this.pollInterval=Dn,this.hooks=[],this.inspectors=[],this.logger=bn(t.logger),this.Oi(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new M(this.streamUri,this.baseUri,this.eventsUri,e.analyticsEventPath,e.diagnosticEventPath,e.includeAuthorizationHeader,t.payloadFilterKey),this.useReport=(s=t.useReport)!=null?s:!1,this.tags=new bt({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(r=e.userAgentHeaderName)!=null?r:"user-agent",this.trackEventModifier=(a=e.trackEventModifier)!=null?a:o=>o,this.credentialType=e.credentialType,this.getImplementationHooks=e.getImplementationHooks}Oi(t){let e=[];return Object.entries(t).forEach(([n,s])=>{let r=En[n];if(r)if(r.is(s))n==="logger"||(this[n]=s!=null?s:void 0);else{let a=r.getType();if(a==="boolean")e.push(b.wrongOptionTypeBoolean(n,typeof s)),this[n]=!!s;else if(a==="boolean | undefined | null")e.push(b.wrongOptionTypeBoolean(n,typeof s)),typeof s!="boolean"&&typeof s!="undefined"&&s!==null&&(this[n]=!!s);else if(r instanceof G&&u.Number.is(s)){let{min:o}=r;e.push(b.optionBelowMinimum(n,s,o)),this[n]=o}else e.push(b.wrongOptionType(n,r.getType(),typeof s))}else e.push(b.unknownOption(n))}),e}};async function ui(i,t){if(i.digest)return i.digest(t);if(i.asyncDigest)return i.asyncDigest(t);throw new Error("Platform must implement digest or asyncDigest")}var hi=async(i,{crypto:t,storage:e})=>{let n=await(e==null?void 0:e.get(i));return n||(n=t.randomUUID(),await(e==null?void 0:e.set(i,n))),n};function di(i){return async t=>ui(i.createHash("sha256").update(t),"base64")}var S=async i=>i;async function X(i){return(await Promise.all(i.map(e=>e.transform(e.value)))).join("_")}async function kn(i,t){return X([{value:"LaunchDarkly",transform:S},{value:t,transform:di(i)}])}async function xn(i){return X([{value:"LaunchDarkly",transform:S},{value:"AnonymousKeys",transform:S},{value:i,transform:S}])}async function Sn(i){return X([{value:"LaunchDarkly",transform:S},{value:"ContextKeys",transform:S},{value:i,transform:S}])}async function Ln(i){return X([{value:i,transform:S},{value:"ContextIndex",transform:S}])}async function si(i,t,e){return X([{value:t,transform:S},{value:e.canonicalKey,transform:di(i)}])}var{isLegacyUser:Cn,isSingleKind:ge,isMultiKind:ri}=x,fi="1.0",Tn=i=>{let n=i,{kind:t}=n,e=Bt(n,["kind"]);return{kind:"multi",[t]:e}},An=async({crypto:i,info:t},{applicationInfo:e})=>{var a;let{ld_application:n}=t.platformData(),s=(a=It(n))!=null?a:{},r=(e==null?void 0:e.id)||(s==null?void 0:s.id);if(r){let o=(e==null?void 0:e.version)||(s==null?void 0:s.version),c=(e==null?void 0:e.name)||(s==null?void 0:s.name),l=(e==null?void 0:e.versionName)||(s==null?void 0:s.versionName);return s=p(p(p(D(p({},s),{id:r}),o?{version:o}:{}),c?{name:c}:{}),l?{versionName:l}:{}),s.key=await ui(i.createHash("sha256").update(r),"base64"),s.envAttributesVersion=s.envAttributesVersion||fi,s}},In=async i=>{var o,c,l,h;let{ld_device:t,os:e}=i.info.platformData(),n=(o=It(t))!=null?o:{},s=(e==null?void 0:e.name)||((c=n.os)==null?void 0:c.name),r=(e==null?void 0:e.version)||((l=n.os)==null?void 0:l.version),a=(h=n.os)==null?void 0:h.family;if((s||r||a)&&(n.os=p(p(p({},s?{name:s}:{}),r?{version:r}:{}),a?{family:a}:{})),Object.keys(n).filter(d=>d!=="key"&&d!=="envAttributesVersion").length){let d=await Sn("ld_device");return n.key=await hi(d,i),n.envAttributesVersion=n.envAttributesVersion||fi,n}},Pn=async(i,t,e)=>{if(Cn(i))return i;let n,s;if(ge(i)&&i.kind!=="ld_application"||ri(i)&&!i.ld_application?n=await An(t,e):e.logger.warn("Not adding ld_application environment attributes because it already exists."),ge(i)&&i.kind!=="ld_device"||ri(i)&&!i.ld_device?s=await In(t):e.logger.warn("Not adding ld_device environment attributes because it already exists."),n||s){let r=ge(i)?Tn(i):i;return p(p(p({},r),n?{ld_application:n}:{}),s?{ld_device:s}:{})}return i},{isLegacyUser:Nn,isMultiKind:On,isSingleKind:$n}=x,Oe=async(i,t,e)=>{let{anonymous:n,key:s}=t;if(n&&!s){let r=await xn(i);t.key=await hi(r,e)}},Mn=async(i,t)=>{await Oe(i.kind,i,t)},Rn=async(i,t)=>{let s=i,{kind:e}=s,n=Bt(s,["kind"]);return Promise.all(Object.entries(n).map(([r,a])=>Oe(r,a,t)))},Fn=async(i,t)=>{await Oe("user",i,t)},Un=async(i,t)=>{let e=fe(i);return $n(e)&&await Mn(e,t),On(e)&&await Rn(e,t),Nn(e)&&await Fn(e,t),e},Vn=i=>({customBaseURI:i.serviceEndpoints.polling!==ci,customStreamURI:i.serviceEndpoints.streaming!==li,customEventsURI:i.serviceEndpoints.events!==M.DEFAULT_EVENTS,eventsCapacity:i.capacity,eventsFlushIntervalMillis:At(i.flushInterval),reconnectTimeMillis:At(i.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:At(i.diagnosticRecordingInterval),allAttributesPrivate:i.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),jn=(i,t,e)=>{if(t.sendEvents&&!t.diagnosticOptOut)return new x.DiagnosticsManager(i,e,Vn(t))};function me(i,t){return{value:t!=null?t:null,variationIndex:null,reason:{kind:"ERROR",errorKind:i}}}function ai(i,t,e){return{value:i,variationIndex:t!=null?t:null,reason:e!=null?e:null}}var Hn=(i,t,e,n,s)=>{if(t.sendEvents)return new x.EventProcessor(D(p({},t),{eventsCapacity:t.capacity}),new kt(i,t,e),n,void 0,s,!1)},Nt=class extends x.EventFactoryBase{evalEventClient(t,e,n,s,r,a){let{trackEvents:o,debugEventsUntilDate:c,trackReason:l,flagVersion:h,version:d,variation:f}=s;return super.evalEvent({addExperimentData:l,context:r,debugEventsUntilDate:c,defaultVal:n,flagKey:t,reason:a,trackEvents:!!o,value:e,variation:f,version:h!=null?h:d})}},Z=class i{constructor(){this.container={index:new Array}}static fromJson(t){let e=new i;try{e.container=JSON.parse(t)}catch(n){}return e}toJson(){return JSON.stringify(this.container)}notice(t,e){let n=this.container.index.find(s=>s.id===t);n===void 0?this.container.index.push({id:t,timestamp:e}):n.timestamp=e}prune(t){let e=Math.max(t,0);return this.container.index.length>e?(this.container.index.sort((n,s)=>n.timestamp-s.timestamp),this.container.index.splice(0,this.container.index.length-e)):[]}},De=class{constructor(t,e,n,s,r,a,o=()=>Date.now()){this.l=t,this.Ft=e,this.$i=n,this.m=s,this.C=r,this.t=a,this.pt=o,this.be=Ln(this.Ft)}async init(t,e){this.C.init(t,e),await this.ke(t)}async upsert(t,e,n){return this.C.upsert(t,e,n)?(await this.ke(t),!0):!1}async loadCached(t){var s,r,a,o;let e=await si(this.l.crypto,this.Ft,t),n=await((s=this.l.storage)==null?void 0:s.get(e));if(n==null){if(n=await((r=this.l.storage)==null?void 0:r.get(t.canonicalKey)),n==null)return!1;await((a=this.l.storage)==null?void 0:a.set(e,n)),await((o=this.l.storage)==null?void 0:o.clear(t.canonicalKey))}try{let c=JSON.parse(n),l=Object.entries(c).reduce((h,[d,f])=>(h[d]={version:f.version,flag:f},h),{});return this.C.initCached(t,l),this.t.debug("Loaded cached flag evaluations from persistent storage"),!0}catch(c){return this.t.warn(`Could not load cached flag evaluations from persistent storage: ${c.message}`),!1}}async Mi(){var e;if(this.K!==void 0)return this.K;let t=await((e=this.l.storage)==null?void 0:e.get(await this.be));if(!t)return this.K=new Z,this.K;try{this.K=Z.fromJson(t),this.t.debug("Loaded context index from persistent storage")}catch(n){this.t.warn(`Could not load index from persistent storage: ${n.message}`),this.K=new Z}return this.K}async ke(t){var c,l;let e=await this.Mi(),n=await si(this.l.crypto,this.Ft,t);e.notice(n,this.pt());let s=e.prune(this.$i);await Promise.all(s.map(async h=>{var d;return(d=this.l.storage)==null?void 0:d.clear(h.id)})),await((c=this.l.storage)==null?void 0:c.set(await this.be,e.toJson()));let r=this.m.getAll(),a=Object.entries(r).reduce((h,[d,f])=>(f.flag!==null&&f.flag!==void 0&&(h[d]=f.flag),h),{}),o=JSON.stringify(a);await((l=this.l.storage)==null?void 0:l.set(n,o))}},be=class{constructor(){this.X={}}init(t){this.X=Object.entries(t).reduce((e,[n,s])=>(e[n]=s,e),{})}insertOrUpdate(t,e){this.X[t]=e}get(t){if(Object.prototype.hasOwnProperty.call(this.X,t))return this.X[t]}getAll(){return this.X}};function Bn(i,t){let e=[];return Object.entries(i).forEach(([n,s])=>{let r=t[n];(!r||!K(s,r))&&e.push(n)}),Object.keys(t).forEach(n=>{i[n]||e.push(n)}),e}var ke=class{constructor(t,e){this.Q=new Array,this.m=t,this.t=e}init(t,e){this.xe=t.canonicalKey;let n=this.m.getAll();this.m.init(e);let s=Bn(n,e);s.length>0&&this.Q.forEach(r=>{try{r(t,s,"init")}catch(a){}})}initCached(t,e){this.xe!==t.canonicalKey&&this.init(t,e)}upsert(t,e,n){if(this.xe!==t.canonicalKey)return this.t.warn("Received an update for an inactive context."),!1;let s=this.m.get(e);return s!==void 0&&s.version>=n.version?!1:(this.m.insertOrUpdate(e,n),this.Q.forEach(r=>{try{r(t,[e],"patch")}catch(a){}}),!0)}on(t){this.Q.push(t)}off(t){let e=this.Q.indexOf(t);e>-1&&this.Q.splice(e,1)}},xe=class{constructor(t,e,n,s,r=()=>Date.now()){this.m=new be,this.C=new ke(this.m,s),this.Ut=this.Ri(t,e,n,s,r)}async Ri(t,e,n,s,r=()=>Date.now()){let a=await kn(t.crypto,e);return new De(t,a,n,this.m,this.C,s,r)}get(t){return this.m.get(t)}getAll(){return this.m.getAll()}setBootstrap(t,e){this.C.init(t,e)}async init(t,e){return(await this.Ut).init(t,e)}async upsert(t,e,n){return(await this.Ut).upsert(t,e,n)}async loadCached(t){return(await this.Ut).loadCached(t)}on(t){this.C.on(t)}off(t){this.C.off(t)}},oi="unknown hook",pi="beforeEvaluation",gi="afterEvaluation",_n="afterTrack";function Q(i,t,e,n,s){try{return n()}catch(r){return i==null||i.error(`An error was encountered in "${t}" of the "${e}" hook: ${r}`),s}}function tt(i,t){try{return t.getMetadata().name||oi}catch(e){return i.error("Exception thrown getting metadata for hook. Unable to get hook name."),oi}}function Kn(i,t,e){return t.map(n=>Q(i,pi,tt(i,n),()=>{var s,r;return(r=(s=n==null?void 0:n.beforeEvaluation)==null?void 0:s.call(n,e,{}))!=null?r:{}},{}))}function Gn(i,t,e,n,s){for(let r=t.length-1;r>=0;r-=1){let a=t[r],o=n[r];Q(i,gi,tt(i,a),()=>{var c,l;return(l=(c=a==null?void 0:a.afterEvaluation)==null?void 0:c.call(a,e,o,s))!=null?l:{}},{})}}function zn(i,t,e){return t.map(n=>Q(i,pi,tt(i,n),()=>{var s,r;return(r=(s=n==null?void 0:n.beforeIdentify)==null?void 0:s.call(n,e,{}))!=null?r:{}},{}))}function qn(i,t,e,n,s){for(let r=t.length-1;r>=0;r-=1){let a=t[r],o=n[r];Q(i,gi,tt(i,a),()=>{var c,l;return(l=(c=a==null?void 0:a.afterIdentify)==null?void 0:c.call(a,e,o,s))!=null?l:{}},{})}}function Jn(i,t,e){for(let n=t.length-1;n>=0;n-=1){let s=t[n];Q(i,_n,tt(i,s),()=>{var r;return(r=s==null?void 0:s.afterTrack)==null?void 0:r.call(s,e)},void 0)}}var Se=class{constructor(t,e){this.t=t,this.M=[],this.M.push(...e)}withEvaluation(t,e,n,s){if(this.M.length===0)return s();let r=[...this.M],a={flagKey:t,context:e,defaultValue:n},o=Kn(this.t,r,a),c=s();return Gn(this.t,r,a,o,c),c}identify(t,e){let n=[...this.M],s={context:t,timeout:e},r=zn(this.t,n,s);return a=>{qn(this.t,n,s,r,a)}}addHook(t){this.M.push(t)}afterTrack(t){if(this.M.length===0)return;let e=[...this.M];Jn(this.t,e,t)}};function Wn(i){return{getMetadata(){return{name:"LaunchDarkly-Inspector-Adapter"}},afterEvaluation:(t,e,n)=>(i.onFlagUsed(t.flagKey,n,t.context),e),afterIdentify(t,e,n){return i.onIdentityChanged(t.context),e}}}function Yn(i,t){return`an inspector: "${t}" of an invalid type (${i}) was configured`}function Zn(i,t){return`an inspector: "${t}" of type: "${i}" generated an exception`}function Xn(i,t){let e=!1,n={method:(...s)=>{try{i.method(...s)}catch(r){e||(e=!0,t.warn(Zn(n.type,n.name)))}},type:i.type,name:i.name,synchronous:i.synchronous};return n}var mi="flag-used",yi="flag-details-changed",vi="flag-detail-changed",wi="client-identity-changed",Qn=[mi,yi,vi,wi];function ts(i,t){let e=Qn.includes(i.type)&&i.method&&typeof i.method=="function";return e||t.warn(Yn(i.type,i.name)),e}var Le=class{constructor(t,e){this.G=[];let n=t.filter(s=>ts(s,e));this.G=n.map(s=>Xn(s,e))}hasInspectors(){return this.G.length!==0}onFlagUsed(t,e,n){this.G.forEach(s=>{s.type===mi&&s.method(t,e,n)})}onFlagsChanged(t){this.G.forEach(e=>{e.type===yi&&e.method(t)})}onFlagChanged(t,e){this.G.forEach(n=>{n.type===vi&&n.method(t,e)})}onIdentityChanged(t){this.G.forEach(e=>{e.type===wi&&e.method(t)})}},Ce=class{constructor(t){this.t=t,this.e=new Map}on(t,e){var n;this.e.has(t)?(n=this.e.get(t))==null||n.push(e):this.e.set(t,[e])}off(t,e){let n=this.e.get(t);if(n){if(e){let s=n.filter(r=>r!==e);s.length===0?this.e.delete(t):this.e.set(t,s);return}this.e.delete(t)}}Vt(t,e,...n){var s;try{t(...n)}catch(r){(s=this.t)==null||s.error(`Encountered error invoking handler for "${e}", detail: "${r}"`)}}emit(t,...e){let n=this.e.get(t);n==null||n.forEach(s=>this.Vt(s,t,...e))}eventNames(){return[...this.e.keys()]}listenerCount(t){var e,n;return(n=(e=this.e.get(t))==null?void 0:e.length)!=null?n:0}};function es(i,t,e){let n=t.info.sdkData(),s;e.applicationInfo&&(e.applicationInfo.id&&(s=s!=null?s:{},s.id=e.applicationInfo.id),e.applicationInfo.version&&(s=s!=null?s:{},s.version=e.applicationInfo.version),e.applicationInfo.name&&(s=s!=null?s:{},s.name=e.applicationInfo.name),e.applicationInfo.versionName&&(s=s!=null?s:{},s.versionName=e.applicationInfo.versionName));let r={name:n.userAgentBase,version:n.version};n.wrapperName&&(r.wrapperName=n.wrapperName),n.wrapperVersion&&(r.wrapperVersion=n.wrapperVersion);let a={sdk:r,[e.credentialType]:i};return s&&(a.application=s),a}var{ClientMessages:ye,ErrorKinds:ve}=x,is=5,Ot=class{constructor(t,e,n,s,r,a){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.jt=15,this.T=new Nt(!1),this.gt=new Nt(!0),this.Ht=!1,!t)throw new Error("You must configure the client with a client-side SDK key");if(!n.encoding)throw new Error("Platform must implement Encoding because btoa is required.");this.r=new Ee(s,a),this.logger=this.r.logger,this.Se=ei(this.sdkKey,this.platform.info,this.r.tags,this.r.serviceEndpoints.includeAuthorizationHeader,this.r.userAgentHeaderName),this.b=new xe(this.platform,t,this.r.maxCachedContexts,this.r.logger),this.D=jn(t,this.r,n),this.y=Hn(t,this.r,n,this.Se,this.D),this.emitter=new Ce,this.emitter.on("error",(c,l)=>{this.logger.error(`error: ${l}, context: ${JSON.stringify(c)}`)}),this.b.on((c,l,h)=>{this.Fi(l,h);let d=k.toLDContext(c);this.emitter.emit("change",d,l),l.forEach(f=>{this.emitter.emit(`change:${f}`,d)})}),this.dataManager=r(this.b,this.r,this.Se,this.emitter,this.D);let o=[...this.r.hooks];this.environmentMetadata=es(this.sdkKey,this.platform,this.r),this.r.getImplementationHooks(this.environmentMetadata).forEach(c=>{o.push(c)}),this.R=new Se(this.logger,o),this.tt=new Le(this.r.inspectors,this.logger),this.tt.hasInspectors()&&this.R.addHook(Wn(this.tt))}allFlags(){return Object.entries(this.b.getAll()).reduce((e,[n,s])=>(s.flag!==null&&s.flag!==void 0&&!s.flag.deleted&&(e[n]=s.flag.value),e),{})}async close(){var t;await this.flush(),(t=this.y)==null||t.close(),this.dataManager.close(),this.logger.debug("Closed event processor and data source.")}async flush(){var t;try{await((t=this.y)==null?void 0:t.flush()),this.logger.debug("Successfully flushed event processor.")}catch(e){return this.logger.error(`Error flushing event processor: ${e}.`),{error:e,result:!1}}return{result:!0}}getContext(){return this.v?fe(this.v):void 0}getInternalContext(){return this.z}Ui(t,e){let n,s,r=new Promise((c,l)=>{n=c,s=l});if(e)return{identifyPromise:r,identifyResolve:n,identifyReject:s};let a=ni(t,"identify");return{identifyPromise:Promise.race([a,r]).catch(c=>{throw c.message.includes("timed out")&&this.logger.error(`identify error: ${c}`),c}),identifyResolve:n,identifyReject:s}}async identify(t,e){var d,f;let n=(d=e==null?void 0:e.timeout)!=null?d:is,s=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;n>this.jt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.jt} seconds. We recommend a timeout of less than ${this.jt} seconds.`);let r=await Un(t,this.platform);this.autoEnvAttributes===V.Enabled&&(r=await Pn(r,this.platform,this.r));let a=k.fromLDContext(r);if(!a.valid){let g=new Error("Context was unspecified or had no key");return this.emitter.emit("error",r,g),Promise.reject(g)}this.v=r,this.z=a,(f=this.y)==null||f.sendEvent(this.T.identifyEvent(this.z));let{identifyPromise:o,identifyResolve:c,identifyReject:l}=this.Ui(n,s);this.logger.debug(`Identifying ${JSON.stringify(this.z)}`);let h=this.R.identify(r,e==null?void 0:e.timeout);return await this.dataManager.identify(c,l,a,e),o.then(g=>(h({status:"completed"}),g),g=>{throw h({status:"error"}),g})}on(t,e){this.emitter.on(t,e)}off(t,e){this.emitter.off(t,e)}track(t,e,n){var s,r;if(!this.z||!this.z.valid){this.logger.warn(ye.MissingContextKeyNoEvent);return}n!==void 0&&!u.Number.is(n)&&((s=this.logger)==null||s.warn(ye.invalidMetricValue(typeof n))),(r=this.y)==null||r.sendEvent(this.r.trackEventModifier(this.T.customEvent(t,this.z,e,n))),this.R.afterTrack({key:t,context:this.v,data:e,metricValue:n})}mt(t,e,n,s){var f,g,m;if(!this.v)return this.logger.debug(ye.MissingContextKeyNoEvent),me(ve.UserNotSpecified,e);let r=k.fromLDContext(this.v),a=this.b.get(t);if(a===void 0||a.flag.deleted){let y=e!=null?e:null,L=new J(`Unknown feature flag "${t}"; returning default value ${y}.`);return this.emitter.emit("error",this.v,L),(f=this.y)==null||f.sendEvent(this.T.unknownFlagEvent(t,y,r)),me(ve.FlagNotFound,e)}let{reason:o,value:c,variation:l,prerequisites:h}=a.flag;if(s){let[y,L]=s(c);if(!y){(g=this.y)==null||g.sendEvent(n.evalEventClient(t,e,e,a.flag,r,o));let R=new J(`Wrong type "${L}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.v,R),me(ve.WrongType,e)}}let d=ai(c,l,o);return c==null&&(this.logger.debug("Result value is null. Providing default value."),d.value=e),h==null||h.forEach(y=>{this.mt(y,void 0,this.T)}),(m=this.y)==null||m.sendEvent(n.evalEventClient(t,c,e,a.flag,r,o)),d}variation(t,e){let{value:n}=this.R.withEvaluation(t,this.v,e,()=>this.mt(t,e,this.T));return n}variationDetail(t,e){return this.R.withEvaluation(t,this.v,e,()=>this.mt(t,e,this.gt))}q(t,e,n,s){return this.R.withEvaluation(t,this.v,e,()=>this.mt(t,e,n,s))}boolVariation(t,e){return this.q(t,e,this.T,n=>[u.Boolean.is(n),u.Boolean.getType()]).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.q(t,e,this.T,n=>[u.Number.is(n),u.Number.getType()]).value}stringVariation(t,e){return this.q(t,e,this.T,n=>[u.String.is(n),u.String.getType()]).value}boolVariationDetail(t,e){return this.q(t,e,this.gt,n=>[u.Boolean.is(n),u.Boolean.getType()])}numberVariationDetail(t,e){return this.q(t,e,this.gt,n=>[u.Number.is(n),u.Number.getType()])}stringVariationDetail(t,e){return this.q(t,e,this.gt,n=>[u.String.is(n),u.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.R.addHook(t)}setEventSendingEnabled(t,e){var n,s,r,a;this.Ht!==t&&(this.Ht=t,t?(this.logger.debug("Starting event processor"),(n=this.y)==null||n.start()):e?((s=this.logger)==null||s.debug("Flushing event processor before disabling."),this.flush().then(()=>{var o,c;this.Ht||((o=this.logger)==null||o.debug("Stopping event processor."),(c=this.y)==null||c.close())})):((r=this.logger)==null||r.debug("Stopping event processor."),(a=this.y)==null||a.close()))}sendEvent(t){var e;(e=this.y)==null||e.sendEvent(t)}Fi(t,e){if(!this.tt.hasInspectors())return;let n={};t.forEach(s=>{let r=this.b.get(s);if(r!=null&&r.flag&&!r.flag.deleted){let{reason:a,value:o,variation:c}=r.flag;n[s]=ai(o,c,a)}else n[s]={value:void 0,reason:null,variationIndex:null}}),e==="init"?this.tt.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([s,r])=>{this.tt.onFlagChanged(s,r)})}},Te=class{constructor(t,e,n){this.b=t,this.Bt=e,this.t=n}async handlePut(t,e){this.t.debug(`Got PUT: ${Object.keys(e)}`);let n=Object.entries(e).reduce((s,[r,a])=>(s[r]={version:a.version,flag:a},s),{});await this.b.init(t,n),this.Bt.requestStateUpdate(E.Valid)}async handlePatch(t,e){this.t.debug(`Got PATCH ${JSON.stringify(e,null,2)}`),this.b.upsert(t,e.key,{version:e.version,flag:e})}async handleDelete(t,e){this.t.debug(`Got DELETE ${JSON.stringify(e,null,2)}`),this.b.upsert(t,e.key,{version:e.version,flag:D(p({},e),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})}handleStreamingError(t){this.Bt.reportError(t.kind,t.message,t.code,t.recoverable)}handlePollingError(t){this.Bt.reportError(t.kind,t.message,t.status,t.recoverable)}},Ae=class{constructor(t,e=()=>Date.now()){this.A=t,this.yt=E.Closed,this.Le=e(),this.pt=e}get status(){return{state:this.yt,stateSince:this.Le,lastError:this.Vi}}Ce(t,e=!1){let n=t===E.Interrupted&&this.yt===E.Initializing?E.Initializing:t,s=this.yt!==n;s&&(this.yt=n,this.Le=this.pt()),(s||e)&&this.A.emit("dataSourceStatus",this.status)}requestStateUpdate(t){this.Ce(t)}reportError(t,e,n,s=!1){let r={kind:t,message:e,statusCode:n,time:this.pt()};this.Vi=r,this.Ce(s?E.Interrupted:E.Closed,!0)}},Ie=class{constructor(t,e,n,s,r){this.ji=t,this.Hi=e,this.Bi=n,this.u=s,this.t=r,this.F=!1}async Te(){var r,a,o,c,l,h,d;if(this.F)return;let t=f=>{var g,m,y;(g=this.t)==null||g.error("Polling received invalid data"),(m=this.t)==null||m.debug(`Invalid JSON follows: ${f}`),(y=this.u)==null||y.call(this,new O(w.InvalidData,"Malformed JSON data in polling response"))};(r=this.t)==null||r.debug("Polling LaunchDarkly for feature flag updates");let e=Date.now();try{let f=await this.ji.requestPayload();try{let g=JSON.parse(f);try{(a=this.Bi)==null||a.call(this,g)}catch(m){(o=this.t)==null||o.error(`Exception from data handler: ${m}`)}}catch(g){t(f)}}catch(f){let g=f;if(g.status!==void 0&&!Y(g.status)){(c=this.t)==null||c.error(B(f,"polling request")),(l=this.u)==null||l.call(this,new O(w.ErrorResponse,g.message,g.status));return}(h=this.t)==null||h.error(B(f,"polling request","will retry"))}let n=Date.now()-e,s=Math.max(this.Hi*1e3-n,0);(d=this.t)==null||d.debug("Elapsed: %d ms, sleeping for %d ms",n,s),this._t=setTimeout(()=>{this.Te()},s)}start(){this.Te()}stop(){this._t&&(clearTimeout(this._t),this._t=void 0),this.F=!0}close(){this.stop()}},ns=(i,t,e,n)=>{e==null||e.error(`Stream received invalid data in "${i}" message`),e==null||e.debug(`Invalid JSON follows: ${t}`),n==null||n(new U(w.InvalidData,"Malformed JSON data in event stream"))},Pe=class{constructor(t,e,n,s,r,a,o,c,l){var f;this._i=t,this.Kt=e,this.e=n,this.L=s,this.Ki=a,this.D=o,this.u=c,this.t=l;let h;e.useReport&&!s.getEventSourceCapabilities().customMethod?h=e.paths.pathPing(r,t):h=e.useReport?e.paths.pathReport(r,t):e.paths.pathGet(r,t);let d=[...(f=e.queryParameters)!=null?f:[]];this.Kt.withReasons&&d.push({key:"withReasons",value:"true"}),this.L=s,this.ft=p({},e.baseHeaders),this.t=l,this.Gi=Xe(e.serviceEndpoints,h,d)}Ae(){this.vt=Date.now()}Gt(t){this.vt&&this.D&&this.D.recordStreamInit(this.vt,!t,Date.now()-this.vt),this.vt=void 0}zi(t){var e,n,s;return ii(t)?((s=this.t)==null||s.warn(B(t,"streaming request","will retry")),this.Gt(!1),this.Ae(),!0):(this.Gt(!1),(e=this.u)==null||e.call(this,new U(w.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error(B(t,"streaming request")),!1)}start(){this.Ae();let t;this.Kt.useReport?(this.ft["content-type"]="application/json",t={method:"REPORT",body:this._i}):t={};let e=this.L.createEventSource(this.Gi,D(p({headers:this.ft},t),{errorFilter:n=>this.zi(n),initialRetryDelayMillis:this.Kt.initialRetryDelayMillis,readTimeoutMillis:5*60*1e3,retryResetIntervalMillis:60*1e3}));this.Ie=e,e.onclose=()=>{var n;(n=this.t)==null||n.info("Closed LaunchDarkly stream connection")},e.onerror=()=>{},e.onopen=()=>{var n;(n=this.t)==null||n.info("Opened LaunchDarkly stream connection")},e.onretrying=n=>{var s;(s=this.t)==null||s.info(`Will retry stream connection in ${n.delayMillis} milliseconds`)},this.e.forEach(({deserializeData:n,processJson:s},r)=>{e.addEventListener(r,a=>{var o,c;if((o=this.t)==null||o.debug(`Received ${r} event`),a!=null&&a.data){this.Gt(!0);let{data:l}=a,h=n(l);if(!h){ns(r,l,this.t,this.u);return}s(h)}else(c=this.u)==null||c.call(this,new U(w.InvalidData,"Unexpected payload from event stream"))})}),e.addEventListener("ping",async()=>{var n,s,r,a,o,c,l;(n=this.t)==null||n.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let h=await this.Ki.requestPayload();try{let d=JSON.parse(h);try{(s=this.e.get("put"))==null||s.processJson(d)}catch(f){(r=this.t)==null||r.error(`Exception from data handler: ${f}`)}}catch(d){(a=this.t)==null||a.error("Polling after ping received invalid data"),(o=this.t)==null||o.debug(`Invalid JSON follows: ${h}`),(c=this.u)==null||c.call(this,new O(w.InvalidData,"Malformed JSON data in ping polling response"))}}catch(h){let d=h;(l=this.u)==null||l.call(this,new O(w.ErrorResponse,d.message,d.status))}})}stop(){var t;(t=this.Ie)==null||t.close(),this.Ie=void 0}close(){this.stop()}},$t=class{constructor(t,e,n,s,r,a,o,c,l){this.platform=t,this.flagManager=e,this.credential=n,this.config=s,this.getPollingPaths=r,this.getStreamingPaths=a,this.baseHeaders=o,this.emitter=c,this.diagnosticsManager=l,this.closed=!1,this.logger=s.logger,this.dataSourceStatusManager=new Ae(c),this.J=new Te(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.qi=t}createPollingProcessor(t,e,n,s,r){let a=new Ie(n,this.config.pollInterval,async o=>{await this.J.handlePut(e,o),s==null||s()},o=>{this.emitter.emit("error",t,o),this.J.handlePollingError(o),r==null||r(o)},this.logger);this.updateProcessor=this.Pe(a,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,s,r){var o;let a=new Pe(JSON.stringify(t),{credential:this.credential,serviceEndpoints:this.config.serviceEndpoints,paths:this.getStreamingPaths(),baseHeaders:this.baseHeaders,initialRetryDelayMillis:this.config.streamInitialReconnectDelay*1e3,withReasons:this.config.withReasons,useReport:this.config.useReport,queryParameters:(o=this.qi)==null?void 0:o.queryParameters},this.createStreamListeners(e,s),this.platform.requests,this.platform.encoding,n,this.diagnosticsManager,c=>{this.emitter.emit("error",t,c),this.J.handleStreamingError(c),r==null||r(c)},this.logger);this.updateProcessor=this.Pe(a,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async s=>{await this.J.handlePut(t,s),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async s=>{this.J.handlePatch(t,s)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async s=>{this.J.handleDelete(t,s)}}),n}Pe(t,e){return{start:()=>{e.requestStateUpdate(E.Initializing),t.start()},stop:()=>{t.stop(),e.requestStateUpdate(E.Closed)},close:()=>{t.close(),e.requestStateUpdate(E.Closed)}}}close(){var t;(t=this.updateProcessor)==null||t.close(),this.closed=!0}};function Mt(){return typeof document!==void 0}function $e(){return typeof window!==void 0}function Rt(i,t,e){return Mt()?(document.addEventListener(i,t,e),()=>{document.removeEventListener(i,t,e)}):()=>{}}function Ft(i,t,e){return Mt()?(window.addEventListener(i,t,e),()=>{window.removeEventListener(i,t,e)}):()=>{}}function C(){return $e()?window.location.href:""}function Ei(){return $e()?window.location.search:""}function Di(){return $e()?window.location.hash:""}function bi(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function ki(){return Mt()?document.visibilityState:"visibile"}function xi(i){if(Mt())return document.querySelectorAll(i)}function Si(i,t){let e=Object.keys(t),n="$flagsState",s="$valid",r=t[n];!r&&e.length&&i.warn("LaunchDarkly client was initialized with bootstrap data that did not include flag metadata. Events may not be sent correctly."),t[s]===!1&&i.warn("LaunchDarkly bootstrap data is not available because the back end could not read the flags.");let a={};return e.forEach(o=>{if(o!==n&&o!==s){let c;r&&r[o]?c=p({value:t[o]},r[o]):c={value:t[o],version:0},a[o]={version:c.version,flag:c}}}),a}var ss="[BrowserDataManager]",et=class extends $t{constructor(e,n,s,r,a,o,c,l,h,d){super(e,n,s,r,o,c,l,h,d);this.cn=a;this.et=void 0;this.zt=!1;this.et=a.streaming}I(e,...n){this.logger.debug(`${ss} ${e}`,...n)}async identify(e,n,s,r){if(this.closed){this.I("Identify called after data manager was closed.");return}this.context=s;let a=r;a!=null&&a.hash?this.setConnectionParams({queryParameters:[{key:"h",value:a.hash}]}):this.setConnectionParams(),this.qt=a==null?void 0:a.hash,a!=null&&a.bootstrap?this.Ji(s,a.bootstrap,e):(await this.flagManager.loadCached(s)&&this.I("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.Wi(s,e,n)),this.Jt()}async Wi(e,n,s){var r,a;try{this.dataSourceStatusManager.requestStateUpdate(E.Initializing);let o=JSON.stringify(k.toLDContext(e)),l=await Ne(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.qt).requestPayload();try{let d=this.createStreamListeners(e,n).get("put");d.processJson(d.deserializeData(l))}catch(h){this.dataSourceStatusManager.reportError(w.InvalidData,(r=h.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(w.NetworkError,(a=o.message)!=null?a:"unexpected network error",o.status),s(o)}}Ji(e,n,s){this.flagManager.setBootstrap(e,Si(this.logger,n)),this.I("Identify - Initialization completed from bootstrap"),s()}setForcedStreaming(e){this.et=e,this.Jt()}setAutomaticStreamingState(e){this.zt=e,this.Jt()}Jt(){let e=this.et||this.zt&&this.et===void 0;this.I(`Updating streaming state. forced(${this.et}) automatic(${this.zt})`),e?this.Yi():this.Zi()}Zi(){var e;this.updateProcessor&&this.I("Stopping update processor."),(e=this.updateProcessor)==null||e.close(),this.updateProcessor=void 0}Yi(){if(this.updateProcessor){this.I("Update processor already active. Not changing state.");return}if(!this.context){this.I("Context not set, not starting update processor.");return}this.I("Starting update processor."),this.Xi(this.context)}Xi(e,n,s){var c;let r=k.toLDContext(e);(c=this.updateProcessor)==null||c.close();let a=JSON.stringify(k.toLDContext(e)),o=Ne(a,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.qt);this.createStreamingProcessor(r,e,o,n,s),this.updateProcessor.start()}};function Li(i){let e=Rt("visibilitychange",()=>{ki()==="hidden"&&i()}),n=Ft("pagehide",i);return()=>{e(),n()}}function it(i){if(typeof i!="string")throw new TypeError("Expected a string");return i.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function rs(i,t,e,n){let r=((i.kind==="substring"||i.kind==="regex")&&n.includes("/")?t:t.replace(n,"")).replace(e,"");switch(i.kind){case"exact":return new RegExp(`^${it(i.url)}/?$`).test(t);case"canonical":return new RegExp(`^${it(i.url)}/?$`).test(r);case"substring":return new RegExp(`.*${it(i.substring)}.*$`).test(r);case"regex":return new RegExp(i.pattern).test(r);default:return!1}}function as(i,t){let e=[];return t.forEach(n=>{let s=i.target,{selector:r}=n,a=xi(r);for(;s&&(a!=null&&a.length);){for(let o=0;o<a.length;o+=1)if(s===a[o]){e.push(n);break}s=s.parentNode}}),e}var nt=class{constructor(t,e){let n=t.filter(a=>{var o;return(o=a.urls)==null?void 0:o.some(c=>rs(c,C(),Ei(),Di()))}),s=n.filter(a=>a.kind==="pageview"),r=n.filter(a=>a.kind==="click");if(s.forEach(a=>e(a)),r.length){let a=o=>{as(o,r).forEach(c=>{e(c)})};this.Ne=Rt("click",a)}}close(){var t;(t=this.Ne)==null||t.call(this)}};var os=300,Ut=class{constructor(t){this.Wt=C();let e=()=>{let s=C();s!==this.Wt&&(this.Wt=s,t())};this.Yt=setInterval(e,os);let n=Ft("popstate",e);this.Oe=()=>{n()}}close(){var t;this.Yt&&clearInterval(this.Yt),(t=this.Oe)==null||t.call(this)}};var st=class{constructor(t,e,n,s,r,a=o=>new Ut(o)){this.L=e;this.en=s;this.tn=r;this.wt=[];this.Me=!1;this.Et=`${n}/sdk/goals/${t}`,this.$e=a(()=>{this.Xt()})}async initialize(){await this.Qi(),this.Xt()}startTracking(){this.Me=!0,this.Xt()}Xt(){var t;this.Me&&((t=this.Zt)==null||t.close(),this.wt&&this.wt.length&&(this.Zt=new nt(this.wt,e=>{this.tn(C(),e)})))}async Qi(){try{let t=await this.L.fetch(this.Et);this.wt=await t.json()}catch(t){this.en(new q(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.$e)==null||t.close(),(e=this.Zt)==null||e.close()}};function Ci(i){return i.kind==="click"}var cs=2,Ti={fetchGoals:!0,eventUrlTransformer:i=>i,streaming:void 0,plugins:[]},ls={fetchGoals:u.Boolean,eventUrlTransformer:u.Function,streaming:u.Boolean,plugins:u.createTypeArray("LDPlugin",{})};function us(i){var e;let t=p({},i);return(e=t.flushInterval)!=null||(t.flushInterval=cs),t}function Ai(i){let t=us(i);return Object.keys(Ti).forEach(e=>{delete t[e]}),t}function Me(i,t){let e=p({},Ti);return Object.entries(ls).forEach(n=>{let[s,r]=n,a=i[s];a!==void 0&&(r.is(a)?e[s]=a:t.warn(b.wrongOptionType(s,r.getType(),typeof a)))}),e}var rt=class{constructor(t,e){this.nn=t;this.Re=[];switch(e){case"sha1":this.Qt="SHA-1";break;case"sha256":this.Qt="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.Re.join(""),n=new TextEncoder().encode(e),s=await this.nn.subtle.digest(this.Qt,n);switch(t){case"base64":return btoa(String.fromCharCode(...new Uint8Array(s)));case"hex":return[...new Uint8Array(s)].map(r=>r.toString(16).padStart(2,"0")).join("");default:throw new Error(`Encoding is not supported ${t}`)}}update(t){return this.Re.push(t),this}};var hs={start:0,end:3},ds={start:4,end:5},Re={start:6,end:7},Fe={start:8,end:8},fs={start:9,end:9},ps={start:10,end:15};function gs(){if(crypto&&crypto.getRandomValues){let t=new Uint8Array(16);return crypto.getRandomValues(t),[...t.values()]}let i=[];for(let t=0;t<16;t+=1)i.push(Math.floor(Math.random()*256));return i}function _(i,t){let e="";for(let n=t.start;n<=t.end;n+=1)e+=i[n].toString(16).padStart(2,"0");return e}function ms(i){return i[Fe.start]=(i[Fe.start]|128)&191,i[Re.start]=i[Re.start]&15|64,`${_(i,hs)}-${_(i,ds)}-${_(i,Re)}-${_(i,Fe)}${_(i,fs)}-${_(i,ps)}`}function ys(){let i=gs();return ms(i)}function Ue(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():ys()}var at=class{createHash(t){return new rt(bi(),t)}randomUUID(){return Ue()}};function vs(i){let t=Array.from(i,e=>String.fromCodePoint(e)).join("");return btoa(t)}var ot=class{btoa(t){return vs(new TextEncoder().encode(t))}};var ct=class{constructor(t){this.r=t}platformData(){return{name:"JS"}}sdkData(){let t={name:"@launchdarkly/js-client-sdk",version:"0.0.0",userAgentBase:"JSClient"};return this.r.wrapperName&&(t.wrapperName=this.r.wrapperName),this.r.wrapperVersion&&(t.wrapperVersion=this.r.wrapperVersion),t}};var lt=class{constructor(t,e){this.Et=t;this.e={};this.x=new Dt(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.Fe=e.errorFilter,this.Ue()}Ue(){this.W=new EventSource(this.Et),this.W.onopen=()=>{var t;this.x.success(),(t=this.onopen)==null||t.call(this)},this.W.onerror=t=>{var e;this.sn(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.e).forEach(([t,e])=>{e.forEach(n=>{var s;(s=this.W)==null||s.addEventListener(t,n)})})}addEventListener(t,e){var n,s,r;(s=(n=this.e)[t])!=null||(n[t]=[]),this.e[t].push(e),(r=this.W)==null||r.addEventListener(t,e)}close(){var t,e;clearTimeout(this.te),this.te=void 0,(t=this.W)==null||t.close(),(e=this.onclose)==null||e.call(this)}rn(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.te=setTimeout(()=>{this.Ue()},t)}sn(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.Fe(t))&&this.rn(this.x.fail())}};var ut=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new lt(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function Ii(){return typeof localStorage!="undefined"}var ht=class{constructor(t){this.t=t}async clear(t){var e;try{localStorage.removeItem(t)}catch(n){(e=this.t)==null||e.error(`Error clearing key from localStorage: ${t}, reason: ${n}`)}}async get(t){var e;try{let n=localStorage.getItem(t);return n!=null?n:null}catch(n){return(e=this.t)==null||e.error(`Error getting key from localStorage: ${t}, reason: ${n}`),null}}async set(t,e){var n;try{localStorage.setItem(t,e)}catch(s){(n=this.t)==null||n.error(`Error setting key in localStorage: ${t}, reason: ${s}`)}}};var dt=class{constructor(t,e){this.encoding=new ot;this.crypto=new at;this.requests=new ut;Ii()&&(this.storage=new ht(t)),this.info=new ct(e)}};var Vt=class extends Ot{constructor(t,e,n={},s){var g;let{logger:r,debug:a}=n,o=r!=null?r:new $({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:a?"debug":"info"}),c=(g=n.baseUri)!=null?g:"https://clientsdk.launchdarkly.com",l=s!=null?s:new dt(o,n),h=Me(n,o),d=Ai(D(p({},n),{logger:o})),{eventUrlTransformer:f}=h;super(t,e,l,d,(m,y,L,R,Ni)=>new et(l,m,t,y,h,()=>({pathGet(I,P){return`/sdk/evalx/${t}/contexts/${pe(P,I)}`},pathReport(I,P){return`/sdk/evalx/${t}/context`},pathPing(I,P){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(I,P){return`/eval/${t}/${pe(P,I)}`},pathReport(I,P){return`/eval/${t}`},pathPing(I,P){return`/ping/${t}`}}),L,R,Ni),{analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:m=>new x.InputCustomEvent(m.context,m.key,m.data,m.metricValue,m.samplingRatio,f(C())),getImplementationHooks:m=>x.safeGetHooks(o,m,h.plugins),credentialType:"clientSideId"}),this.setEventSendingEnabled(!0,!1),h.fetchGoals&&(this.ee=new st(t,l.requests,c,m=>{o.error(m.message)},(m,y)=>{let L=this.getInternalContext();if(!L)return;let R=f(m);Ci(y)?this.sendEvent({kind:"click",url:R,samplingRatio:1,key:y.key,creationDate:Date.now(),context:L,selector:y.selector}):this.sendEvent({kind:"pageview",url:R,samplingRatio:1,key:y.key,creationDate:Date.now(),context:L})}),this.ee.initialize(),h.automaticBackgroundHandling&&Li(()=>this.flush())),x.safeRegisterPlugins(o,this.environmentMetadata,this,h.plugins)}async identify(t,e){var n;await super.identify(t,e),(n=this.ee)==null||n.startTracking()}setStreaming(t){this.dataManager.setForcedStreaming(t)}Ve(){this.dataManager.setAutomaticStreamingState(!!this.emitter.listenerCount("change"))}on(t,e){super.on(t,e),this.Ve()}off(t,e){super.off(t,e),this.Ve()}};var Pi=["ready","failed","initialized"],ft=class{constructor(t){this.n=t;this.e=new Map}on(t,e){var n;Pi.includes(t)?this.e.has(t)?(n=this.e.get(t))==null||n.push(e):this.e.set(t,[e]):this.n.on(t,e)}off(t,e){if(Pi.includes(t)){let n=this.e.get(t);if(!n)return;if(e){let s=n.filter(r=>r!==e);s.length===0?this.e.delete(t):this.e.set(t,s);return}this.e.delete(t)}else this.n.off(t,e)}Vt(t,e,...n){try{t(...n)}catch(s){this.n.logger.error(`Encountered error invoking handler for "${e}", detail: "${s}"`)}}emit(t,...e){let n=this.e.get(t);n==null||n.forEach(s=>this.Vt(s,t,...e))}eventNames(){return[...this.e.keys()]}listenerCount(t){var e,n;return(n=(e=this.e.get(t))==null?void 0:e.length)!=null?n:0}};function jt(i,t){let e=i.then(n=>(t&&setTimeout(()=>{t(null,n)},0),n),n=>{if(t)setTimeout(()=>{t(n,null)},0);else return Promise.reject(n)});return t?void 0:e}var pt=class{constructor(t,e,n){this.ie="initializing";let s=n==null?void 0:n.bootstrap,r=n==null?void 0:n.hash,a=p({},n);delete a.bootstrap,delete a.hash,this.n=new Vt(t,V.Disabled,n),this.A=new ft(this.n),this.logger=this.n.logger,this.an(e,s,r)}async an(t,e,n){var s,r;try{await this.n.identify(t,{noTimeout:!0,bootstrap:e,hash:n}),this.ie="success",(s=this.je)==null||s.call(this),this.A.emit("initialized")}catch(a){this.Be=a,this.ie="failure",(r=this.He)==null||r.call(this,a),this.A.emit("failed",a)}this.A.emit("ready")}allFlags(){return this.n.allFlags()}boolVariation(t,e){return this.n.boolVariation(t,e)}boolVariationDetail(t,e){return this.n.boolVariationDetail(t,e)}jsonVariation(t,e){return this.n.jsonVariation(t,e)}jsonVariationDetail(t,e){return this.n.jsonVariationDetail(t,e)}numberVariation(t,e){return this.n.numberVariation(t,e)}numberVariationDetail(t,e){return this.n.numberVariationDetail(t,e)}off(t,e){this.A.off(t,e)}on(t,e){this.A.on(t,e)}stringVariation(t,e){return this.n.stringVariation(t,e)}stringVariationDetail(t,e){return this.n.stringVariationDetail(t,e)}track(t,e,n){this.n.track(t,e,n)}variation(t,e){return this.n.variation(t,e)}variationDetail(t,e){return this.n.variationDetail(t,e)}addHook(t){this.n.addHook(t)}setStreaming(t){this.n.setStreaming(t)}identify(t,e,n){return jt(this.n.identify(t,{hash:e}).then(()=>this.allFlags()),n)}close(t){return jt(this.n.close().then(),t)}flush(t){return jt(this.n.flush().then(()=>{}),t)}getContext(){return this.n.getContext()}waitForInitialization(t){var e;if(this.it)return this._e(this.it,t);switch(this.ie){case"success":return Promise.resolve();case"failure":return Promise.reject(this.Be);case"initializing":break;default:throw new Error("Unexpected initialization state. This represents an implementation error in the SDK.")}return t===void 0&&((e=this.logger)==null||e.warn("The waitForInitialization function was called without a timeout specified. In a future version a default timeout will be applied.")),this.it||(this.it=new Promise((n,s)=>{this.je=n,this.He=s})),this._e(this.it,t)}async waitUntilReady(){try{await this.waitForInitialization()}catch(t){}}_e(t,e){if(e){let n=ti(e,"waitForInitialization");return Promise.race([t.then(()=>n.cancel()),n.promise]).catch(s=>{var r;throw s instanceof H&&((r=this.logger)==null||r.error(s.message)),s})}return t}};function ws(i){return new $(i)}function Es(i,t,e){return new pt(i,t,e)}0&&(module.exports={basicLogger,initialize});
2
2
  //# sourceMappingURL=compat.cjs.map