@launchdarkly/js-client-sdk 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var ht=Object.defineProperty,bi=Object.defineProperties,ki=Object.getOwnPropertyDescriptor,Si=Object.getOwnPropertyDescriptors,xi=Object.getOwnPropertyNames,lt=Object.getOwnPropertySymbols;var Nt=Object.prototype.hasOwnProperty,Ue=Object.prototype.propertyIsEnumerable;var Pe=(i,t,e)=>t in i?ht(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,g=(i,t)=>{for(var e in t||(t={}))Nt.call(t,e)&&Pe(i,e,t[e]);if(lt)for(var e of lt(t))Ue.call(t,e)&&Pe(i,e,t[e]);return i},b=(i,t)=>bi(i,Si(t));var Pt=(i,t)=>{var e={};for(var n in i)Nt.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&lt)for(var n of lt(i))t.indexOf(n)<0&&Ue.call(i,n)&&(e[n]=i[n]);return e};var Li=(i,t)=>{for(var e in t)ht(i,e,{get:t[e],enumerable:!0})},Ci=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of xi(t))!Nt.call(i,s)&&s!==e&&ht(i,s,{get:()=>t[s],enumerable:!(n=ki(t,s))||n.enumerable});return i};var Ai=i=>Ci(ht({},"__esModule",{value:!0}),i);var ss={};Li(ss,{basicLogger:()=>ns,initialize:()=>is});module.exports=Ai(ss);function Oi(i){return`/${i.replace(/~/g,"~0").replace(/\//g,"~1")}`}function Ve(i){return i.indexOf("~")?i.replace(/~1/g,"/").replace(/~0/g,"~"):i}function Ri(i){return(i.startsWith("/")?i.substring(1):i).split("/").map(e=>Ve(e))}function $i(i){return!i.startsWith("/")}function Ti(i){return!i.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var O=class{constructor(t,e=!1){if(e){let n=t;this.l=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?Oi(n):n}else{if(this.redactionName=t,t===""||t==="/"||!Ti(t)){this.isValid=!1,this.l=[];return}$i(t)?this.l=[t]:t.indexOf("/",1)<0?this.l=[Ve(t.slice(1))]:this.l=Ri(t),this.l[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{l: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.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))}};O.InvalidReference=new O("");var jt=class{is(t){if(Array.isArray(t))return!1;let n=typeof t;return n==="function"||n==="object"}getType(){return"factory method or object"}},R=class{constructor(t,e){this.ut=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.ut}},pt=class{constructor(t,e){this.ut=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.ut}},_=class extends R{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},gt=class extends R{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},Bt=class{is(t){return typeof t=="function"}getType(){return"function"}},Kt=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},Ii=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,Vt=class{is(t){return typeof t=="number"||typeof t=="string"&&Ii.test(t)}getType(){return"date"}},_t=class extends gt{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},l=class{static createTypeArray(t,e){return new pt(t,e)}static numberWithMin(t){return new _(t)}static stringMatchingRegex(t){return new gt(t)}};l.String=new R("string","");l.Number=new R("number",0);l.ObjectOrFactory=new jt;l.Object=new R("object",{});l.StringArray=new pt("string[]","");l.Boolean=new R("boolean",!0);l.Function=new Bt;l.Date=new Vt;l.Kind=new _t;l.NullableBoolean=new Kt;function _e(i){return"kind"in i?l.String.is(i.kind)&&i.kind!=="multi":!1}function He(i){return"kind"in i?l.String.is(i.kind)&&i.kind==="multi":!1}function Ge(i){return!("kind"in i)||i.kind===null||i.kind===void 0}var Ht="user";function Fe(i){return i.includes("%")||i.includes(":")?i.replace(/%/g,"%25").replace(/:/g,"%3A"):i}function Mi(i){return i&&l.Object.is(i)}function je(i){return l.Kind.is(i)}function Be(i){return l.String.is(i)&&i!==""}function Ut(i,t=!1){return i?i.map(e=>new O(e,t)):[]}function Ni(i){return i!=null}function Pi(i){let t=b(g({},i.custom||[]),{kind:"user",key:String(i.key)});if(Ni(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.D=!1,this.J=!1,this.Bt=!1,this.S={},this.kind=e,this.valid=t,this.message=n}static m(t,e){return new i(!1,t,e)}static Ee(t,e){if(!(!e||!t.isValid))return t.depth===1&&t.getComponent(0)==="anonymous"?!!(e!=null&&e.anonymous):t.get(e)}Kt(t){if(this.D)return this.S[t];if(this.kind===t)return this.x}static we(t){let e=Object.keys(t).filter(c=>c!=="kind"),n=e.every(je);if(!e.length)return i.m("multi","A multi-kind context must contain at least one kind");if(!n)return i.m("multi","Context contains invalid kinds");let s={},r=!0,a=e.reduce((c,u)=>{var d;let h=t[u];return Mi(h)?(c[u]=h,s[u]=Ut((d=h._meta)==null?void 0:d.privateAttributes)):r=!1,c},{});if(!r)return i.m("multi","Context contained contexts that were not objects");if(!Object.values(a).every(c=>Be(c.key)))return i.m("multi","Context contained invalid keys");if(e.length===1){let c=e[0],u=new i(!0,c);return u.x=b(g({},a[c]),{kind:c}),u.W=s,u.J=c==="user",u}let o=new i(!0,t.kind);return o.S=a,o.W=s,o.D=!0,o}static De(t){var c;let{key:e,kind:n}=t,s=je(n),r=Be(e);if(!s)return i.m(n!=null?n:"unknown","The kind was not valid for the context");if(!r)return i.m(n,"The key for the context was not valid");let a=Ut((c=t._meta)==null?void 0:c.privateAttributes),o=new i(!0,n);return o.J=n==="user",o.x=t,o.W={[n]:a},o}static be(t){if(!(t.key!==void 0&&t.key!==null))return i.m("user","The key for the context was not valid");let n=new i(!0,"user");return n.J=!0,n.Bt=!0,n.x=Pi(t),n.W={user:Ut(t.privateAttributeNames,!0)},n}static fromLDContext(t){return t?_e(t)?i.De(t):He(t)?i.we(t):Ge(t)?i.be(t):i.m("unknown","Context was not of a valid kind"):i.m("unknown","No context specified. Returning default value")}static toLDContext(t){if(!t.valid)return;let e=t.getContexts();if(!t.D)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=Ht){return t.isKind?this.kinds:i.Ee(t,this.Kt(e))}key(t=Ht){var e;return(e=this.Kt(t))==null?void 0:e.key}get isMultiKind(){return this.D}get canonicalKey(){return this.J?this.x.key:this.D?Object.keys(this.S).sort().map(t=>`${t}:${Fe(this.S[t].key)}`).join(":"):`${this.kind}:${Fe(this.x.key)}`}get kinds(){return this.D?Object.keys(this.S):[this.kind]}get kindsAndKeys(){return this.D?Object.entries(this.S).reduce((t,[e,n])=>(t[e]=n.key,t),{}):{[this.kind]:this.x.key}}privateAttributes(t){var e;return((e=this.W)==null?void 0:e[t])||[]}getContexts(){return this.D?Object.entries(this.S):[[this.kind,this.x]]}get legacy(){return this.Bt}};k.UserKind=Ht;var Ui=["key","kind","_meta","anonymous"].map(i=>new O(i,!0)),Fi=["name","ip","firstName","lastName","email","avatar","country"];function ji(i,t){return i.depth===t.length&&t.every((e,n)=>e===i.getComponent(n))}function Bi(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=>ji(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 Gt=class{constructor(t,e){this.ke=t,this.Se=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this.Vt(t,n[0][1],n[0][0],e);let s={kind:"multi"};return n.forEach(([r,a])=>{s[r]=this.Vt(t,a,r,e)}),s}xe(t,e,n,s){return(s?Object.keys(e).map(r=>new O(r,!0)):[...this.Se,...t.privateAttributes(n)]).filter(r=>!Ui.some(a=>a.compare(r)))}Vt(t,e,n,s){let r=this.ke||s&&e.anonymous===!0,{cloned:a,excluded:o}=Bi(e,this.xe(t,e,n,r));return t.legacy&&Fi.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 N=class extends Error{constructor(t,e,n,s=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=s}},x=class extends Error{constructor(t,e,n,s=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=s}},j;(function(i){i[i.Disabled=0]="Disabled",i[i.Enabled=1]="Enabled"})(j||(j={}));var B;(function(i){i[i.AnalyticsEvents=0]="AnalyticsEvents",i[i.DiagnosticEvent=1]="DiagnosticEvent"})(B||(B={}));var M;(function(i){i[i.Succeeded=0]="Succeeded",i[i.Failed=1]="Failed",i[i.FailedAndMustShutDown=2]="FailedAndMustShutDown"})(M||(M={}));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 Ki(i){return typeof i=="symbol"?"NaN":typeof i=="bigint"?`${i}n`:String(Number(i))}function Vi(i){return typeof i=="symbol"?"NaN":typeof i=="bigint"?`${i}n`:String(parseInt(i,10))}function _i(i){return typeof i=="symbol"?"NaN":String(parseFloat(i))}var dt={s:i=>F(i),d:i=>Ki(i),i:i=>Vi(i),f:i=>_i(i),j:i=>F(i),o:i=>F(i),O:i=>F(i),c:()=>""};function qt(...i){var e;let t=i.shift();if(l.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 dt&&i.length){let c=i.shift();n+=(e=dt[o])==null?void 0:e.call(dt,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 Hi=["debug","info","warn","error","none"],P=class i{static get(){return new i({})}constructor(t){var e,n,s;if(this.Le=(n=v[(e=t.level)!=null?e:"info"])!=null?n:v.info,this.Ce=(s=t.name)!=null?s:"LaunchDarkly",this._t=t.formatter,typeof t.destination=="object")this.Ht={[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.Ht={[v.debug]:r,[v.info]:r,[v.warn]:r,[v.error]:r}}}Ae(...t){var e;try{return this._t?(e=this._t)==null?void 0:e.call(this,...t):qt(...t)}catch(n){return qt(...t)}}Oe(t,e){try{t(e)}catch(n){console.error(e)}}y(t,e){var n;if(t>=this.Le){let s=`${Hi[t]}: [${this.Ce}]`;try{let r=(n=this.Ht)==null?void 0:n[t];r?this.Oe(r,`${s} ${this.Ae(...e)}`):console.error(...e)}catch(r){console.error(...e)}}}error(...t){this.y(v.error,t)}warn(...t){this.y(v.warn,t)}info(...t){this.y(v.info,t)}debug(...t){this.y(v.debug,t)}},Gi={error:l.Function,warn:l.Function,info:l.Function,debug:l.Function},H=class{constructor(t,e){Object.entries(Gi).forEach(([n,s])=>{if(!s.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.Re=e}y(t,e){try{this.t[t](...e)}catch(n){this.Re[t](...e)}}error(...t){this.y("error",t)}warn(...t){this.y("warn",t)}info(...t){this.y("info",t)}debug(...t){this.y("debug",t)}},re=i=>{let t=new P({level:"info",destination:console.error,formatter:qt});return i?new H(i,t):t},D=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`}},qi=/^(\w|\.|-)+$/,Ji=l.stringMatchingRegex(qi),Wi={is:(i,t)=>Ji.is(i)?i.length>64?{valid:!1,message:D.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:D.invalidTagValue(t)}},mt=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:u}=Wi.is(o,`application.${a}`);c?a==="versionName"?e["application-version-name"]=[o]:e[`application-${a}`]=[o]:s==null||s.warn(u)}});let r=Object.keys(e);r.length&&(this.value=r.sort().flatMap(a=>e[a].sort().map(o=>`${a}/${o}`)).join(" "))}},yt=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 Ft(i){return i.replace(/\/+$/,"")}function ae(i){return i.replace(/^\/+/,"").replace(/\?$/,"")}var U=class i{constructor(t,e,n=i.DEFAULT_EVENTS,s="/bulk",r="/diagnostic",a=!0,o){this.streaming=Ft(t),this.polling=Ft(e),this.events=Ft(n),this.analyticsEventPath=s,this.diagnosticEventPath=r,this.includeAuthorizationHeader=a,this.payloadFilterKey=o}};U.DEFAULT_EVENTS="https://events.launchdarkly.com";function oe(i,t){if(t.length===0)return i;let e=t.map(({key:n,value:s})=>`${n}=${s}`);return`${i}?${e.join("&")}`}function ce(i,t,e){let n=ae(t),s=[...e];return i.payloadFilterKey&&s.push({key:"filter",value:i.payloadFilterKey}),oe(`${i.streaming}/${n}`,s)}function qe(i,t,e){let n=ae(t),s=[...e];return i.payloadFilterKey&&s.push({key:"filter",value:i.payloadFilterKey}),oe(`${i.polling}/${n}`,s)}function Ke(i,t,e){let n=ae(t);return oe(`${i.events}/${n}`,e)}var G=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},q=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},Jt=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function W(i){return i>=400&&i<500?i===400||i===408||i===429:!0}function zi(i){return i===413?!0:W(i)}function ue(i){return i==null?i:JSON.parse(JSON.stringify(i))}function Dt(i){return Math.trunc(i*1e3)}var Yi=i=>JSON.stringify(i)==="{}",bt=(i,t)=>i&&Object.entries(i).reduce((e,[n,s])=>(s&&!Yi(s)&&!(t!=null&&t.includes(n))&&(e[n]=typeof s=="object"?bt(s,t):s),e),{});function V(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(!V(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(!V(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(!V(i[r],t[r]))return!1}return!0}return i!==i&&t!==t}function Je(i,t,e,n=!0,s="user-agent"){let{userAgentBase:r,version:a,wrapperName:o,wrapperVersion:c}=t.sdkData(),u={[s]:`${r!=null?r:"NodeJSClient"}/${a}`};return n&&(u.authorization=i),o&&(u["x-launchdarkly-wrapper"]=c?`${o}/${c}`:o),e!=null&&e.value&&(u["x-launchdarkly-tags"]=e.value),u}function $(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 le({status:i}){return i?W(i):!0}var he=(i,t)=>t.btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var Xi=async(i=1e3)=>new Promise(t=>{setTimeout(t,i)}),We=(i,t)=>new Promise((e,n)=>{setTimeout(()=>{let s=`${t} timed out after ${i} seconds.`;n(new Jt(s))},i*1e3)}),Wt=class{constructor(t,e,n){this.r=e,this.$e=n,this.lt=[],this.Gt=Date.now(),this.qt=this.Gt,this.Jt={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var n,s,r;let t=this.r.info.sdkData(),e=this.r.info.platformData();return{kind:"diagnostic-init",id:this.Jt,creationDate:this.Gt,sdk:t,configuration:this.$e,platform:g({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.Jt,creationDate:s,dataSinceDate:this.qt,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.lt};return this.lt=[],this.qt=s,r}},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 Zi=zt,vt=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};vt.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var Yt=class{constructor(t,e){let{basicConfiguration:n,platform:s}=t,{serviceEndpoints:{analyticsEventPath:r,diagnosticEventPath:a}}=n,{crypto:o,requests:c}=s;this.Te=g({},e),this.Wt=Ke(n.serviceEndpoints,r,[]),this.Ie=Ke(n.serviceEndpoints,a,[]),this.g=c,this.Me=o}async z(t,e,n,s){let r={status:M.Succeeded},a=b(g({},this.Te),{"content-type":"application/json"});n&&(a["x-launchdarkly-payload-id"]=n,a["x-launchDarkly-event-schema"]="4");let o;try{let{status:c,headers:u}=await this.g.fetch(e,{headers:a,body:JSON.stringify(t),method:"POST",keepalive:!0}),h=Date.parse(u.get("date")||"");if(h&&(r.serverTime=h),c<=204)return r;if(o=new G($({status:c,message:"some events were dropped"},"event posting")),!W(c))return zi(c)?r.status=M.Failed:r.status=M.FailedAndMustShutDown,r.error=o,r}catch(c){o=c}return o&&!s?(r.status=M.Failed,r.error=o,r):(await Xi(),this.z(t,this.Wt,n,!1))}async sendEventData(t,e){let n=t===B.AnalyticsEvents?this.Me.randomUUID():void 0,s=t===B.AnalyticsEvents?this.Wt:this.Ie;return this.z(e,s,n,!0)}};function Xt(i){return i.kind==="feature"}function Qi(i){return i.kind==="identify"}function tn(i){return i.kind==="migration_op"}var Zt=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 en(i){return`${i.key}:${i.variation!==null&&i.variation!==void 0?i.variation:""}:${i.version!==null&&i.version!==void 0?i.version:""}`}var Qt=class{constructor(){this.U=0,this.Y=0,this.X={},this.Z={}}summarizeEvent(t){if(Xt(t)&&!t.excludeFromSummaries){let e=en(t),n=this.X[e],s=this.Z[t.key];s||(s=new Set,this.Z[t.key]=s),t.context.kinds.forEach(r=>s.add(r)),n?n.increment():this.X[e]=new Zt(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.Y&&(this.Y=t.creationDate)}}getSummary(){let t=Object.values(this.X).reduce((e,n)=>{let s=e[n.key];s||(s={default:n.default,counters:[],contextKinds:[...this.Z[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.U,endDate:this.Y,features:t,kind:"summary"}}clearSummary(){this.U=0,this.Y=0,this.X={},this.Z={}}},te=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}};function ft(i){let t=Math.trunc(i);return t===1?!0:t===0?!1:Math.floor(Math.random()*t)===0}var ee=class{constructor(t,e,n,s,r,a=!0){this.n=t,this.Q=s,this.a=r,this.ht=new Qt,this.tt=[],this.zt=0,this.dt=0,this.ft=0,this.pt=!1,this.Yt=0,this.gt=!1,this.mt=null,this.Ne=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.Xt=new Yt(e,n),this.Zt=new Gt(t.allAttributesPrivate,t.privateAttributes.map(o=>new O(o))),a&&this.start()}start(){var t,e;if(((t=this.Q)==null?void 0:t.flushInterval)!==void 0&&(this.mt=setInterval(()=>{var n;(n=this.Q)==null||n.flush()},this.Q.flushInterval*1e3)),this.Pe=setInterval(async()=>{var n;try{await this.flush()}catch(s){(n=this.t)==null||n.debug(`Flush failed: ${s}`)}},this.n.flushInterval*1e3),this.a){let n=this.a.createInitEvent();this.Qt(n),this.te=setInterval(()=>{let s=this.a.createStatsEventAndReset(this.dt,this.ft,this.Yt);this.dt=0,this.ft=0,this.Qt(s)},this.n.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}Qt(t){this.Xt.sendEventData(B.DiagnosticEvent,t)}close(){clearInterval(this.Pe),this.mt&&clearInterval(this.mt),this.te&&clearInterval(this.te)}async flush(){var n;if(this.gt)throw new te("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.tt;this.tt=[];let e=this.ht.getSummary();this.ht.clearSummary(),Object.keys(e.features).length&&t.push(e),t.length&&(this.Yt=t.length,(n=this.t)==null||n.debug("Flushing %d events",t.length),await this.z(t))}sendEvent(t){var c;if(this.gt)return;if(tn(t)){if(ft(t.samplingRatio)){let u=g({},t);u.samplingRatio===1&&delete u.samplingRatio,this.et(u)}return}this.ht.summarizeEvent(t);let e=Xt(t),n=e&&t.trackEvents||!e,s=this.Ue(t),r=Qi(t),a=(c=this.Q)==null?void 0:c.processContext(t.context);a||r||(this.ft+=1),a&&!r&&this.et(this.yt({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),n&&ft(t.samplingRatio)&&this.et(this.yt(t,!1)),s&&ft(t.samplingRatio)&&this.et(this.yt(t,!0))}yt(t,e){switch(t.kind){case"feature":{let n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.Zt.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.Zt.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),n}case"custom":{let n={kind:"custom",creationDate:t.creationDate,key:t.key,contextKeys:t.context.kindsAndKeys};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}}et(t){var e;this.tt.length<this.Ne?(this.tt.push(t),this.pt=!1):(this.pt||(this.pt=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.dt+=1)}Ue(t){return Xt(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.zt&&t.debugEventsUntilDate>Date.now()}async z(t){let e=await this.Xt.sendEventData(B.AnalyticsEvents,t);if(e.status===M.FailedAndMustShutDown&&(this.gt=!0),e.serverTime&&(this.zt=e.serverTime),e.error)throw e.error}},Et=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}},J=class{constructor(t,e,n,s,r,a,o,c,u,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=s,this.default=r,a!==void 0&&(this.version=a),o!==void 0&&(this.variation=o),c!==void 0&&(this.trackEvents=c),u!==void 0&&(this.prereqOf=u),h!==void 0&&(this.reason=h),d!==void 0&&(this.debugEventsUntilDate=d),f!==void 0&&(this.excludeFromSummaries=f)}},wt=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},ie=class{close(){}async flush(){}sendEvent(){}},ne=class{constructor(t){this.vt=t}evalEvent(t){var e;return new J(this.vt,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.vt||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new J(this.vt,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new wt(t,1)}customEvent(t,e,n,s,r=1){return new Et(e,t,n!=null?n:void 0,s!=null?s:void 0,r)}},nn=(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 x(E.InvalidData,"Malformed JSON data in event stream"))},se=class{constructor(t,e,n,s,r,a,o,c=1){this.e=s,this.a=a,this.u=o,this.Fe=c;let{basicConfiguration:u,platform:h}=t,{logger:d}=u,{requests:f}=h;this.A=g({},r),this.t=d,this.g=f,this.Et=ce(u.serviceEndpoints,e,n)}F(){this.v=Date.now()}L(t){this.v&&this.a&&this.a.recordStreamInit(this.v,!t,Date.now()-this.v),this.v=void 0}wt(t){var e,n,s;return le(t)?((s=this.t)==null||s.warn($(t,"streaming request","will retry")),this.L(!1),this.F(),!0):(this.L(!1),(e=this.u)==null||e.call(this,new x(E.ErrorResponse,t.message,t.status)),(n=this.t)==null||n.error($(t,"streaming request")),!1)}start(){this.F();let t=this.g.createEventSource(this.Et,{headers:this.A,errorFilter:e=>this.wt(e),initialRetryDelayMillis:1e3*this.Fe,readTimeoutMillis:5*60*1e3,retryResetIntervalMillis:60*1e3});this.B=t,t.onclose=()=>{var e;(e=this.t)==null||e.info("Closed LaunchDarkly stream connection")},t.onerror=()=>{},t.onopen=()=>{var e;(e=this.t)==null||e.info("Opened LaunchDarkly stream connection")},t.onretrying=e=>{var n;(n=this.t)==null||n.info(`Will retry stream connection in ${e.delayMillis} milliseconds`)},this.e.forEach(({deserializeData:e,processJson:n},s)=>{t.addEventListener(s,r=>{var a,o;if((a=this.t)==null||a.debug(`Received ${s} event`),r!=null&&r.data){this.L(!0);let{data:c}=r,u=e(c);if(!u){nn(s,c,this.t,this.u);return}n(u)}else(o=this.u)==null||o.call(this,new x(E.Unknown,"Unexpected payload from event stream"))})})}stop(){var t;(t=this.B)==null||t.close(),this.B=void 0}close(){this.stop()}},L=Object.freeze({__proto__:null,ClientMessages:vt,DiagnosticsManager:Wt,ErrorKinds:Zi,EventFactoryBase:ne,EventProcessor:ee,InputCustomEvent:Et,InputEvalEvent:J,InputIdentifyEvent:wt,NullEventProcessor:ie,StreamingProcessor:se,isLegacyUser:Ge,isMultiKind:He,isSingleKind:_e,shouldSample:ft});var w;(function(i){i.Initializing="INITIALIZING",i.Valid="VALID",i.Interrupted="INTERRUPTED",i.SetOffline="SET_OFFLINE",i.Closed="CLOSED"})(w||(w={}));function rn(i){return i>=200&&i<=299}var kt=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}},me=class{constructor(t,e,n,s,r){this.g=t,this.je=e,this.A=n,this.Be=s,this.Ke=r}async requestPayload(){let t;try{let e=await this.g.fetch(this.je,{method:this.Be,headers:this.A,body:this.Ke});if(rn(e.status))return await e.text();t=e.status}catch(e){throw new kt(e==null?void 0:e.message)}throw new kt(`Unexpected status code: ${t}`,t)}};function Oe(i,t,e,n,s,r,a,o,c,u){let h,d="GET",f=g({},r);c&&(d="REPORT",f["content-type"]="application/json",h=i);let p=c?e.pathReport(s,i):e.pathGet(s,i),m=[...a!=null?a:[]];o&&m.push({key:"withReasons",value:"true"}),u&&m.push({key:"h",value:u});let y=qe(t,p,m);return new me(n,y,f,d,h)}var an={logger:l.Object,maxCachedContexts:l.numberWithMin(0),baseUri:l.String,streamUri:l.String,eventsUri:l.String,capacity:l.numberWithMin(1),diagnosticRecordingInterval:l.numberWithMin(2),flushInterval:l.numberWithMin(2),streamInitialReconnectDelay:l.numberWithMin(0),allAttributesPrivate:l.Boolean,debug:l.Boolean,diagnosticOptOut:l.Boolean,withReasons:l.Boolean,sendEvents:l.Boolean,pollInterval:l.numberWithMin(30),useReport:l.Boolean,privateAttributes:l.StringArray,applicationInfo:l.Object,wrapperName:l.String,wrapperVersion:l.String,payloadFilterKey:l.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:l.createTypeArray("Hook[]",{}),inspectors:l.createTypeArray("LDInspection",{})},on=60*5,Qe="https://clientsdk.launchdarkly.com",ti="https://clientstream.launchdarkly.com";function cn(i){return i instanceof H?i:re(i)}var ye=class{constructor(t={},e={}){var s,r,a;this.logger=re(),this.baseUri=Qe,this.eventsUri=U.DEFAULT_EVENTS,this.streamUri=ti,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=on,this.hooks=[],this.inspectors=[],this.logger=cn(t.logger),this.Ve(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new U(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 mt({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(r=e.userAgentHeaderName)!=null?r:"user-agent",this.trackEventModifier=(a=e.trackEventModifier)!=null?a:o=>o}Ve(t){let e=[];return Object.entries(t).forEach(([n,s])=>{let r=an[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(D.wrongOptionTypeBoolean(n,typeof s)),this[n]=!!s;else if(a==="boolean | undefined | null")e.push(D.wrongOptionTypeBoolean(n,typeof s)),typeof s!="boolean"&&typeof s!="undefined"&&s!==null&&(this[n]=!!s);else if(r instanceof _&&l.Number.is(s)){let{min:o}=r;e.push(D.optionBelowMinimum(n,s,o)),this[n]=o}else e.push(D.wrongOptionType(n,r.getType(),typeof s))}else e.push(D.unknownOption(n))}),e}};async function ei(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 ii=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 ni(i){return async t=>ei(i.createHash("sha256").update(t),"base64")}var S=async i=>i;async function Y(i){return(await Promise.all(i.map(e=>e.transform(e.value)))).join("_")}async function un(i,t){return Y([{value:"LaunchDarkly",transform:S},{value:t,transform:ni(i)}])}async function ln(i){return Y([{value:"LaunchDarkly",transform:S},{value:"AnonymousKeys",transform:S},{value:i,transform:S}])}async function hn(i){return Y([{value:"LaunchDarkly",transform:S},{value:"ContextKeys",transform:S},{value:i,transform:S}])}async function dn(i){return Y([{value:i,transform:S},{value:"ContextIndex",transform:S}])}async function ze(i,t,e){return Y([{value:t,transform:S},{value:e.canonicalKey,transform:ni(i)}])}var{isLegacyUser:fn,isSingleKind:de,isMultiKind:Ye}=L,si="1.0",pn=i=>{let n=i,{kind:t}=n,e=Pt(n,["kind"]);return{kind:"multi",[t]:e}},gn=async({crypto:i,info:t},{applicationInfo:e})=>{var a;let{ld_application:n}=t.platformData(),s=(a=bt(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),u=(e==null?void 0:e.versionName)||(s==null?void 0:s.versionName);return s=g(g(g(b(g({},s),{id:r}),o?{version:o}:{}),c?{name:c}:{}),u?{versionName:u}:{}),s.key=await ei(i.createHash("sha256").update(r),"base64"),s.envAttributesVersion=s.envAttributesVersion||si,s}},mn=async i=>{var o,c,u,h;let{ld_device:t,os:e}=i.info.platformData(),n=(o=bt(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)||((u=n.os)==null?void 0:u.version),a=(h=n.os)==null?void 0:h.family;if((s||r||a)&&(n.os=g(g(g({},s?{name:s}:{}),r?{version:r}:{}),a?{family:a}:{})),Object.keys(n).filter(d=>d!=="key"&&d!=="envAttributesVersion").length){let d=await hn("ld_device");return n.key=await ii(d,i),n.envAttributesVersion=n.envAttributesVersion||si,n}},yn=async(i,t,e)=>{if(fn(i))return i;let n,s;if(de(i)&&i.kind!=="ld_application"||Ye(i)&&!i.ld_application?n=await gn(t,e):e.logger.warn("Not adding ld_application environment attributes because it already exists."),de(i)&&i.kind!=="ld_device"||Ye(i)&&!i.ld_device?s=await mn(t):e.logger.warn("Not adding ld_device environment attributes because it already exists."),n||s){let r=de(i)?pn(i):i;return g(g(g({},r),n?{ld_application:n}:{}),s?{ld_device:s}:{})}return i},{isLegacyUser:vn,isMultiKind:En,isSingleKind:wn}=L,Re=async(i,t,e)=>{let{anonymous:n,key:s}=t;if(n&&!s){let r=await ln(i);t.key=await ii(r,e)}},Dn=async(i,t)=>{await Re(i.kind,i,t)},bn=async(i,t)=>{let s=i,{kind:e}=s,n=Pt(s,["kind"]);return Promise.all(Object.entries(n).map(([r,a])=>Re(r,a,t)))},kn=async(i,t)=>{await Re("user",i,t)},Sn=async(i,t)=>{let e=ue(i);return wn(e)&&await Dn(e,t),En(e)&&await bn(e,t),vn(e)&&await kn(e,t),e},xn=i=>({customBaseURI:i.serviceEndpoints.polling!==Qe,customStreamURI:i.serviceEndpoints.streaming!==ti,customEventsURI:i.serviceEndpoints.events!==U.DEFAULT_EVENTS,eventsCapacity:i.capacity,eventsFlushIntervalMillis:Dt(i.flushInterval),reconnectTimeMillis:Dt(i.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:Dt(i.diagnosticRecordingInterval),allAttributesPrivate:i.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Ln=(i,t,e)=>{if(t.sendEvents&&!t.diagnosticOptOut)return new L.DiagnosticsManager(i,e,xn(t))};function fe(i,t){return{value:t!=null?t:null,variationIndex:null,reason:{kind:"ERROR",errorKind:i}}}function Xe(i,t,e){return{value:i,variationIndex:t!=null?t:null,reason:e!=null?e:null}}var Cn=(i,t,e,n,s)=>{if(t.sendEvents)return new L.EventProcessor(b(g({},t),{eventsCapacity:t.capacity}),new yt(i,t,e),n,void 0,s,!1)},St=class extends L.EventFactoryBase{evalEventClient(t,e,n,s,r,a){let{trackEvents:o,debugEventsUntilDate:c,trackReason:u,flagVersion:h,version:d,variation:f}=s;return super.evalEvent({addExperimentData:u,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)):[]}},ve=class{constructor(t,e,n,s,r,a,o=()=>Date.now()){this.r=t,this.Dt=e,this._e=n,this.h=s,this.b=r,this.t=a,this.it=o,this.ee=dn(this.Dt)}async init(t,e){this.b.init(t,e),await this.ie(t)}async upsert(t,e,n){return this.b.upsert(t,e,n)?(await this.ie(t),!0):!1}async loadCached(t){var s,r,a,o;let e=await ze(this.r.crypto,this.Dt,t),n=await((s=this.r.storage)==null?void 0:s.get(e));if(n==null){if(n=await((r=this.r.storage)==null?void 0:r.get(t.canonicalKey)),n==null)return!1;await((a=this.r.storage)==null?void 0:a.set(e,n)),await((o=this.r.storage)==null?void 0:o.clear(t.canonicalKey))}try{let c=JSON.parse(n),u=Object.entries(c).reduce((h,[d,f])=>(h[d]={version:f.version,flag:f},h),{});return this.b.initCached(t,u),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 He(){var e;if(this.R!==void 0)return this.R;let t=await((e=this.r.storage)==null?void 0:e.get(await this.ee));if(!t)return this.R=new z,this.R;try{this.R=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.R=new z}return this.R}async ie(t){var c,u;let e=await this.He(),n=await ze(this.r.crypto,this.Dt,t);e.notice(n,this.it());let s=e.prune(this._e);await Promise.all(s.map(async h=>{var d;return(d=this.r.storage)==null?void 0:d.clear(h.id)})),await((c=this.r.storage)==null?void 0:c.set(await this.ee,e.toJson()));let r=this.h.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((u=this.r.storage)==null?void 0:u.set(n,o))}},Ee=class{constructor(){this.K={}}init(t){this.K=Object.entries(t).reduce((e,[n,s])=>(e[n]=s,e),{})}insertOrUpdate(t,e){this.K[t]=e}get(t){if(Object.prototype.hasOwnProperty.call(this.K,t))return this.K[t]}getAll(){return this.K}};function An(i,t){let e=[];return Object.entries(i).forEach(([n,s])=>{let r=t[n];(!r||!V(s,r))&&e.push(n)}),Object.keys(t).forEach(n=>{i[n]||e.push(n)}),e}var we=class{constructor(t,e){this.V=new Array,this.h=t,this.t=e}init(t,e){this.ne=t.canonicalKey;let n=this.h.getAll();this.h.init(e);let s=An(n,e);s.length>0&&this.V.forEach(r=>{try{r(t,s,"init")}catch(a){}})}initCached(t,e){this.ne!==t.canonicalKey&&this.init(t,e)}upsert(t,e,n){if(this.ne!==t.canonicalKey)return this.t.warn("Received an update for an inactive context."),!1;let s=this.h.get(e);return s!==void 0&&s.version>=n.version?!1:(this.h.insertOrUpdate(e,n),this.V.forEach(r=>{try{r(t,[e],"patch")}catch(a){}}),!0)}on(t){this.V.push(t)}off(t){let e=this.V.indexOf(t);e>-1&&this.V.splice(e,1)}},De=class{constructor(t,e,n,s,r=()=>Date.now()){this.h=new Ee,this.b=new we(this.h,s),this.bt=this.Ge(t,e,n,s,r)}async Ge(t,e,n,s,r=()=>Date.now()){let a=await un(t.crypto,e);return new ve(t,a,n,this.h,this.b,s,r)}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.bt).init(t,e)}async upsert(t,e,n){return(await this.bt).upsert(t,e,n)}async loadCached(t){return(await this.bt).loadCached(t)}on(t){this.b.on(t)}off(t){this.b.off(t)}},Ze="unknown hook",ri="beforeEvaluation",ai="afterEvaluation";function Ct(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 At(i,t){try{return t.getMetadata().name||Ze}catch(e){return i.error("Exception thrown getting metadata for hook. Unable to get hook name."),Ze}}function On(i,t,e){return t.map(n=>Ct(i,ri,At(i,n),()=>{var s,r;return(r=(s=n==null?void 0:n.beforeEvaluation)==null?void 0:s.call(n,e,{}))!=null?r:{}},{}))}function Rn(i,t,e,n,s){for(let r=t.length-1;r>=0;r-=1){let a=t[r],o=n[r];Ct(i,ai,At(i,a),()=>{var c,u;return(u=(c=a==null?void 0:a.afterEvaluation)==null?void 0:c.call(a,e,o,s))!=null?u:{}},{})}}function $n(i,t,e){return t.map(n=>Ct(i,ri,At(i,n),()=>{var s,r;return(r=(s=n==null?void 0:n.beforeIdentify)==null?void 0:s.call(n,e,{}))!=null?r:{}},{}))}function Tn(i,t,e,n,s){for(let r=t.length-1;r>=0;r-=1){let a=t[r],o=n[r];Ct(i,ai,At(i,a),()=>{var c,u;return(u=(c=a==null?void 0:a.afterIdentify)==null?void 0:c.call(a,e,o,s))!=null?u:{}},{})}}var be=class{constructor(t,e){this.t=t,this._=[],this._.push(...e)}withEvaluation(t,e,n,s){if(this._.length===0)return s();let r=[...this._],a={flagKey:t,context:e,defaultValue:n},o=On(this.t,r,a),c=s();return Rn(this.t,r,a,o,c),c}identify(t,e){let n=[...this._],s={context:t,timeout:e},r=$n(this.t,n,s);return a=>{Tn(this.t,n,s,r,a)}}addHook(t){this._.push(t)}};function In(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 Mn(i,t){return`an inspector: "${t}" of an invalid type (${i}) was configured`}function Nn(i,t){return`an inspector: "${t}" of type: "${i}" generated an exception`}function Pn(i,t){let e=!1,n={method:(...s)=>{try{i.method(...s)}catch(r){e||(e=!0,t.warn(Nn(n.type,n.name)))}},type:i.type,name:i.name,synchronous:i.synchronous};return n}var oi="flag-used",ci="flag-details-changed",ui="flag-detail-changed",li="client-identity-changed",Un=[oi,ci,ui,li];function Fn(i,t){let e=Un.includes(i.type)&&i.method&&typeof i.method=="function";return e||t.warn(Mn(i.type,i.name)),e}var ke=class{constructor(t,e){this.$=[];let n=t.filter(s=>Fn(s,e));this.$=n.map(s=>Pn(s,e))}hasInspectors(){return this.$.length!==0}onFlagUsed(t,e,n){this.$.forEach(s=>{s.type===oi&&s.method(t,e,n)})}onFlagsChanged(t){this.$.forEach(e=>{e.type===ci&&e.method(t)})}onFlagChanged(t,e){this.$.forEach(n=>{n.type===ui&&n.method(t,e)})}onIdentityChanged(t){this.$.forEach(e=>{e.type===li&&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 s=n.filter(r=>r!==e);s.length===0?this.e.delete(t):this.e.set(t,s);return}this.e.delete(t)}}qe(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.qe(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}},{ClientMessages:pe,ErrorKinds:ge}=L,jn=5,xt=class{constructor(t,e,n,s,r,a){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.kt=15,this.k=new St(!1),this.nt=new St(!0),this.St=!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.n=new ye(s,a),this.logger=this.n.logger,this.se=Je(this.sdkKey,this.platform.info,this.n.tags,this.n.serviceEndpoints.includeAuthorizationHeader,this.n.userAgentHeaderName),this.E=new De(this.platform,t,this.n.maxCachedContexts,this.n.logger),this.a=Ln(t,this.n,n),this.p=Cn(t,this.n,n,this.se,this.a),this.emitter=new Se,this.emitter.on("error",(o,c)=>{this.logger.error(`error: ${c}, context: ${JSON.stringify(o)}`)}),this.E.on((o,c,u)=>{this.Je(c,u);let h=k.toLDContext(o);this.emitter.emit("change",h,c),c.forEach(d=>{this.emitter.emit(`change:${d}`,h)})}),this.dataManager=r(this.E,this.n,this.se,this.emitter,this.a),this.T=new be(this.logger,this.n.hooks),this.H=new ke(this.n.inspectors,this.logger),this.H.hasInspectors()&&this.T.addHook(In(this.H))}allFlags(){return Object.entries(this.E.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,e;await this.flush(),(t=this.p)==null||t.close(),(e=this.yi)==null||e.close(),this.logger.debug("Closed event processor and data source.")}async flush(){var t;try{await((t=this.p)==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.w?ue(this.w):void 0}getInternalContext(){return this.I}We(t,e){let n,s,r=new Promise((c,u)=>{n=c,s=u});if(e)return{identifyPromise:r,identifyResolve:n,identifyReject:s};let a=We(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:jn,s=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;n>this.kt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.kt} seconds. We recommend a timeout of less than ${this.kt} seconds.`);let r=await Sn(t,this.platform);this.autoEnvAttributes===j.Enabled&&(r=await yn(r,this.platform,this.n));let a=k.fromLDContext(r);if(!a.valid){let p=new Error("Context was unspecified or had no key");return this.emitter.emit("error",r,p),Promise.reject(p)}this.w=r,this.I=a,(f=this.p)==null||f.sendEvent(this.k.identifyEvent(this.I));let{identifyPromise:o,identifyResolve:c,identifyReject:u}=this.We(n,s);this.logger.debug(`Identifying ${JSON.stringify(this.I)}`);let h=this.T.identify(r,e==null?void 0:e.timeout);return await this.dataManager.identify(c,u,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 s,r;if(!this.I||!this.I.valid){this.logger.warn(pe.MissingContextKeyNoEvent);return}n!==void 0&&!l.Number.is(n)&&((s=this.logger)==null||s.warn(pe.invalidMetricValue(typeof n))),(r=this.p)==null||r.sendEvent(this.n.trackEventModifier(this.k.customEvent(t,this.I,e,n)))}st(t,e,n,s){var f,p,m;if(!this.w)return this.logger.debug(pe.MissingContextKeyNoEvent),fe(ge.UserNotSpecified,e);let r=k.fromLDContext(this.w),a=this.E.get(t);if(a===void 0||a.flag.deleted){let y=e!=null?e:null,A=new q(`Unknown feature flag "${t}"; returning default value ${y}.`);return this.emitter.emit("error",this.w,A),(f=this.p)==null||f.sendEvent(this.k.unknownFlagEvent(t,y,r)),fe(ge.FlagNotFound,e)}let{reason:o,value:c,variation:u,prerequisites:h}=a.flag;if(s){let[y,A]=s(c);if(!y){(p=this.p)==null||p.sendEvent(n.evalEventClient(t,e,e,a.flag,r,o));let Mt=new q(`Wrong type "${A}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.w,Mt),fe(ge.WrongType,e)}}let d=Xe(c,u,o);return c==null&&(this.logger.debug("Result value is null. Providing default value."),d.value=e),h==null||h.forEach(y=>{this.st(y,void 0,this.k)}),(m=this.p)==null||m.sendEvent(n.evalEventClient(t,c,e,a.flag,r,o)),d}variation(t,e){let{value:n}=this.T.withEvaluation(t,this.w,e,()=>this.st(t,e,this.k));return n}variationDetail(t,e){return this.T.withEvaluation(t,this.w,e,()=>this.st(t,e,this.nt))}M(t,e,n,s){return this.T.withEvaluation(t,this.w,e,()=>this.st(t,e,n,s))}boolVariation(t,e){return this.M(t,e,this.k,n=>[l.Boolean.is(n),l.Boolean.getType()]).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.M(t,e,this.k,n=>[l.Number.is(n),l.Number.getType()]).value}stringVariation(t,e){return this.M(t,e,this.k,n=>[l.String.is(n),l.String.getType()]).value}boolVariationDetail(t,e){return this.M(t,e,this.nt,n=>[l.Boolean.is(n),l.Boolean.getType()])}numberVariationDetail(t,e){return this.M(t,e,this.nt,n=>[l.Number.is(n),l.Number.getType()])}stringVariationDetail(t,e){return this.M(t,e,this.nt,n=>[l.String.is(n),l.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.T.addHook(t)}setEventSendingEnabled(t,e){var n,s,r,a;this.St!==t&&(this.St=t,t?(this.logger.debug("Starting event processor"),(n=this.p)==null||n.start()):e?((s=this.logger)==null||s.debug("Flushing event processor before disabling."),this.flush().then(()=>{var o,c;this.St||((o=this.logger)==null||o.debug("Stopping event processor."),(c=this.p)==null||c.close())})):((r=this.logger)==null||r.debug("Stopping event processor."),(a=this.p)==null||a.close()))}sendEvent(t){var e;(e=this.p)==null||e.sendEvent(t)}Je(t,e){if(!this.H.hasInspectors())return;let n={};t.forEach(s=>{let r=this.E.get(s);if(r!=null&&r.flag&&!r.flag.deleted){let{reason:a,value:o,variation:c}=r.flag;n[s]=Xe(o,c,a)}}),e==="init"?this.H.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([s,r])=>{this.H.onFlagChanged(s,r)})}},xe=class{constructor(t,e,n){this.E=t,this.xt=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.E.init(t,n),this.xt.requestStateUpdate(w.Valid)}async handlePatch(t,e){this.t.debug(`Got PATCH ${JSON.stringify(e,null,2)}`),this.E.upsert(t,e.key,{version:e.version,flag:e})}async handleDelete(t,e){this.t.debug(`Got DELETE ${JSON.stringify(e,null,2)}`),this.E.upsert(t,e.key,{version:e.version,flag:b(g({},e),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})}handleStreamingError(t){this.xt.reportError(t.kind,t.message,t.code,t.recoverable)}handlePollingError(t){this.xt.reportError(t.kind,t.message,t.status,t.recoverable)}},Le=class{constructor(t,e=()=>Date.now()){this.ze=t,this.rt=w.Closed,this.re=e(),this.it=e}get status(){return{state:this.rt,stateSince:this.re,lastError:this.Ye}}ae(t,e=!1){let n=t===w.Interrupted&&this.rt===w.Initializing?w.Initializing:t,s=this.rt!==n;s&&(this.rt=n,this.re=this.it()),(s||e)&&this.ze.emit("dataSourceStatus",this.status)}requestStateUpdate(t){this.ae(t)}reportError(t,e,n,s=!1){let r={kind:t,message:e,statusCode:n,time:this.it()};this.Ye=r,this.ae(s?w.Interrupted:w.Closed,!0)}},Ce=class{constructor(t,e,n,s,r){this.Xe=t,this.Ze=e,this.Qe=n,this.u=s,this.t=r,this.oe=!1}async ce(){var r,a,o,c,u,h,d;if(this.oe)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 N(E.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.Xe.requestPayload();try{let p=JSON.parse(f);try{(a=this.Qe)==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&&!W(p.status)){(c=this.t)==null||c.error($(f,"polling request")),(u=this.u)==null||u.call(this,new N(E.ErrorResponse,p.message,p.status));return}(h=this.t)==null||h.error($(f,"polling request","will retry"))}let n=Date.now()-e,s=Math.max(this.Ze*1e3-n,0);(d=this.t)==null||d.debug("Elapsed: %d ms, sleeping for %d ms",n,s),this.Lt=setTimeout(()=>{this.ce()},s)}start(){this.ce()}stop(){this.Lt&&(clearTimeout(this.Lt),this.Lt=void 0),this.oe=!0}close(){this.stop()}},Bn=(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 x(E.InvalidData,"Malformed JSON data in event stream"))},Ae=class{constructor(t,e,n,s,r,a,o,c,u){var f;this.ti=t,this.Ct=e,this.e=n,this.g=s,this.ei=a,this.a=o,this.u=c,this.t=u;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.Ct.withReasons&&d.push({key:"withReasons",value:"true"}),this.g=s,this.A=g({},e.baseHeaders),this.t=u,this.Et=ce(e.serviceEndpoints,h,d)}F(){this.v=Date.now()}L(t){this.v&&this.a&&this.a.recordStreamInit(this.v,!t,Date.now()-this.v),this.v=void 0}wt(t){var e,n,s;return le(t)?((s=this.t)==null||s.warn($(t,"streaming request","will retry")),this.L(!1),this.F(),!0):(this.L(!1),(e=this.u)==null||e.call(this,new x(E.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error($(t,"streaming request")),!1)}start(){this.F();let t;this.Ct.useReport?(this.A["content-type"]="application/json",t={method:"REPORT",body:this.ti}):t={};let e=this.g.createEventSource(this.Et,b(g({headers:this.A},t),{errorFilter:n=>this.wt(n),initialRetryDelayMillis:this.Ct.initialRetryDelayMillis,readTimeoutMillis:5*60*1e3,retryResetIntervalMillis:60*1e3}));this.B=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.L(!0);let{data:u}=a,h=n(u);if(!h){Bn(r,u,this.t,this.u);return}s(h)}else(c=this.u)==null||c.call(this,new x(E.InvalidData,"Unexpected payload from event stream"))})}),e.addEventListener("ping",async()=>{var n,s,r,a,o,c,u;(n=this.t)==null||n.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let h=await this.ei.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 N(E.InvalidData,"Malformed JSON data in ping polling response"))}}catch(h){let d=h;(u=this.u)==null||u.call(this,new N(E.ErrorResponse,d.message,d.status))}})}stop(){var t;(t=this.B)==null||t.close(),this.B=void 0}close(){this.stop()}},Lt=class{constructor(t,e,n,s,r,a,o,c,u){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=u,this.logger=s.logger,this.dataSourceStatusManager=new Le(c),this.N=new xe(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.ii=t}createPollingProcessor(t,e,n,s,r){let a=new Ce(n,this.config.pollInterval,async o=>{await this.N.handlePut(e,o),s==null||s()},o=>{this.emitter.emit("error",t,o),this.N.handlePollingError(o),r==null||r(o)},this.logger);this.updateProcessor=this.ue(a,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,s,r){var o;let a=new Ae(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.ii)==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.N.handleStreamingError(c),r==null||r(c)},this.logger);this.updateProcessor=this.ue(a,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async s=>{await this.N.handlePut(t,s),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async s=>{this.N.handlePatch(t,s)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async s=>{this.N.handleDelete(t,s)}}),n}ue(t,e){return{start:()=>{e.requestStateUpdate(w.Initializing),t.start()},stop:()=>{t.stop(),e.requestStateUpdate(w.Closed)},close:()=>{t.close(),e.requestStateUpdate(w.Closed)}}}};function Ot(){return typeof document!==void 0}function $e(){return typeof window!==void 0}function Rt(i,t,e){return Ot()?(document.addEventListener(i,t,e),()=>{document.removeEventListener(i,t,e)}):()=>{}}function $t(i,t,e){return Ot()?(window.addEventListener(i,t,e),()=>{window.removeEventListener(i,t,e)}):()=>{}}function C(){return $e()?window.location.href:""}function hi(){return $e()?window.location.search:""}function di(){return $e()?window.location.hash:""}function fi(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function pi(){return Ot()?document.visibilityState:"visibile"}function gi(i){if(Ot())return document.querySelectorAll(i)}function mi(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=g({value:t[o]},r[o]):c={value:t[o],version:0},a[o]={version:c.version,flag:c}}}),a}var Kn="[BrowserDataManager]",X=class extends Lt{constructor(e,n,s,r,a,o,c,u,h,d){super(e,n,s,r,o,c,u,h,d);this.vi=a;this.G=void 0;this.At=!1;this.G=a.streaming}C(e,...n){this.logger.debug(`${Kn} ${e}`,...n)}async identify(e,n,s,r){this.context=s;let a=r;a!=null&&a.hash?this.setConnectionParams({queryParameters:[{key:"h",value:a.hash}]}):this.setConnectionParams(),this.Ot=a==null?void 0:a.hash,a!=null&&a.bootstrap?this.ni(s,a.bootstrap,e):(await this.flagManager.loadCached(s)&&this.C("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.si(s,e,n)),this.Rt()}async si(e,n,s){var r,a;try{this.dataSourceStatusManager.requestStateUpdate(w.Initializing);let o=JSON.stringify(k.toLDContext(e)),u=await Oe(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ot).requestPayload();try{let d=this.createStreamListeners(e,n).get("put");d.processJson(d.deserializeData(u))}catch(h){this.dataSourceStatusManager.reportError(E.InvalidData,(r=h.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(E.NetworkError,(a=o.message)!=null?a:"unexpected network error",o.status),s(o)}}ni(e,n,s){this.flagManager.setBootstrap(e,mi(this.logger,n)),this.C("Identify - Initialization completed from bootstrap"),s()}setForcedStreaming(e){this.G=e,this.Rt()}setAutomaticStreamingState(e){this.At=e,this.Rt()}Rt(){let e=this.G||this.At&&this.G===void 0;this.C(`Updating streaming state. forced(${this.G}) automatic(${this.At})`),e?this.ri():this.ai()}ai(){var e;this.updateProcessor&&this.C("Stopping update processor."),(e=this.updateProcessor)==null||e.close(),this.updateProcessor=void 0}ri(){if(this.updateProcessor){this.C("Update processor already active. Not changing state.");return}if(!this.context){this.C("Context not set, not starting update processor.");return}this.C("Starting update processor."),this.oi(this.context)}oi(e,n,s){var c;let r=k.toLDContext(e);(c=this.updateProcessor)==null||c.close();let a=JSON.stringify(k.toLDContext(e)),o=Oe(a,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ot);this.createStreamingProcessor(r,e,o,n,s),this.updateProcessor.start()}};function yi(i){let e=Rt("visibilitychange",()=>{pi()==="hidden"&&i()}),n=$t("pagehide",i);return()=>{e(),n()}}function Z(i){if(typeof i!="string")throw new TypeError("Expected a string");return i.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function Vn(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(`^${Z(i.url)}/?$`).test(t);case"canonical":return new RegExp(`^${Z(i.url)}/?$`).test(r);case"substring":return new RegExp(`.*${Z(i.substring)}.*$`).test(r);case"regex":return new RegExp(i.pattern).test(r);default:return!1}}function _n(i,t){let e=[];return t.forEach(n=>{let s=i.target,{selector:r}=n,a=gi(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 Q=class{constructor(t,e){let n=t.filter(a=>{var o;return(o=a.urls)==null?void 0:o.some(c=>Vn(c,C(),hi(),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=>{_n(o,r).forEach(c=>{e(c)})};this.le=Rt("click",a)}}close(){var t;(t=this.le)==null||t.call(this)}};var Hn=300,Tt=class{constructor(t){this.$t=C();let e=()=>{let s=C();s!==this.$t&&(this.$t=s,t())};this.Tt=setInterval(e,Hn);let n=$t("popstate",e);this.he=()=>{n()}}close(){var t;this.Tt&&clearInterval(this.Tt),(t=this.he)==null||t.call(this)}};var tt=class{constructor(t,e,n,s,r,a=o=>new Tt(o)){this.g=e;this.li=s;this.ui=r;this.at=[];this.fe=!1;this.ot=`${n}/sdk/goals/${t}`,this.de=a(()=>{this.Mt()})}async initialize(){await this.ci(),this.Mt()}startTracking(){this.fe=!0,this.Mt()}Mt(){var t;this.fe&&((t=this.It)==null||t.close(),this.at&&this.at.length&&(this.It=new Q(this.at,e=>{this.ui(C(),e)})))}async ci(){try{let t=await this.g.fetch(this.ot);this.at=await t.json()}catch(t){this.li(new G(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.de)==null||t.close(),(e=this.It)==null||e.close()}};function vi(i){return i.kind==="click"}var Gn=2,Ei={fetchGoals:!0,eventUrlTransformer:i=>i,streaming:void 0},qn={fetchGoals:l.Boolean,eventUrlTransformer:l.Function,streaming:l.Boolean};function wi(i){let t=g({},i);return Object.keys(Ei).forEach(e=>{delete t[e]}),t}function Jn(i){var t;(t=i.flushInterval)!=null||(i.flushInterval=Gn)}function Te(i,t){let e=g({},Ei);return Jn(e),Object.entries(qn).forEach(n=>{let[s,r]=n,a=i[s];a!==void 0&&(r.is(a)?e[s]=a:t.warn(D.wrongOptionType(s,r.getType(),typeof a)))}),e}var et=class{constructor(t,e){this.hi=t;this.pe=[];switch(e){case"sha1":this.Nt="SHA-1";break;case"sha256":this.Nt="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.pe.join(""),n=new TextEncoder().encode(e),s=await this.hi.subtle.digest(this.Nt,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.pe.push(t),this}};var Wn={start:0,end:3},zn={start:4,end:5},Ie={start:6,end:7},Me={start:8,end:8},Yn={start:9,end:9},Xn={start:10,end:15};function Zn(){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 K(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 Qn(i){return i[Me.start]=(i[Me.start]|128)&191,i[Ie.start]=i[Ie.start]&15|64,`${K(i,Wn)}-${K(i,zn)}-${K(i,Ie)}-${K(i,Me)}${K(i,Yn)}-${K(i,Xn)}`}function ts(){let i=Zn();return Qn(i)}function Ne(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():ts()}var it=class{createHash(t){return new et(fi(),t)}randomUUID(){return Ne()}};function es(i){let t=Array.from(i,e=>String.fromCodePoint(e)).join("");return btoa(t)}var nt=class{btoa(t){return es(new TextEncoder().encode(t))}};var st=class{platformData(){return{name:"JS"}}sdkData(){return{name:"@launchdarkly/js-client-sdk",version:"0.0.0",userAgentBase:"JSClient"}}};var rt=class{constructor(t,e,n=Math.random){this.pi=e;this.fi=n;this.Pt=0;this.Ut=Math.max(1,t),this.ge=Math.ceil(Math.log2(3e4/this.Ut))}q(){let t=Math.min(this.Pt,this.ge),e=this.Ut*2**t;return Math.min(e,3e4)}di(t){return t-Math.trunc(this.fi()*.5*t)}success(t=Date.now()){this.ct=t}fail(t=Date.now()){this.ct!==void 0&&t-this.ct>this.pi&&(this.Pt=0),this.ct=void 0;let e=this.di(this.q());return this.Pt+=1,e}};var at=class{constructor(t,e){this.ot=t;this.e={};this.q=new rt(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.me=e.errorFilter,this.ye()}ye(){this.P=new EventSource(this.ot),this.P.onopen=()=>{var t;this.q.success(),(t=this.onopen)==null||t.call(this)},this.P.onerror=t=>{var e;this.gi(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.e).forEach(([t,e])=>{e.forEach(n=>{var s;(s=this.P)==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.P)==null||r.addEventListener(t,e)}close(){var t,e;clearTimeout(this.Ft),this.Ft=void 0,(t=this.P)==null||t.close(),(e=this.onclose)==null||e.call(this)}mi(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.Ft=setTimeout(()=>{this.ye()},t)}gi(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.me(t))&&this.mi(this.q.fail())}};var ot=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new at(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function Di(){return typeof localStorage!="undefined"}var ct=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 ut=class{constructor(t){this.encoding=new nt;this.info=new st;this.crypto=new it;this.requests=new ot;Di()&&(this.storage=new ct(t))}};var It=class extends xt{constructor(t,e,n={},s){var f;let{logger:r,debug:a}=n,o=r!=null?r:new P({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:a?"debug":"info"}),c=(f=n.baseUri)!=null?f:"https://clientsdk.launchdarkly.com",u=s!=null?s:new ut(o),h=Te(n,o),{eventUrlTransformer:d}=h;super(t,e,u,wi(b(g({},n),{logger:o})),(p,m,y,A,Mt)=>new X(u,p,t,m,h,()=>({pathGet(T,I){return`/sdk/evalx/${t}/contexts/${he(I,T)}`},pathReport(T,I){return`/sdk/evalx/${t}/context`},pathPing(T,I){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(T,I){return`/eval/${t}/${he(I,T)}`},pathReport(T,I){return`/eval/${t}`},pathPing(T,I){return`/ping/${t}`}}),y,A,Mt),{analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:p=>new L.InputCustomEvent(p.context,p.key,p.data,p.metricValue,p.samplingRatio,d(C()))}),this.setEventSendingEnabled(!0,!1),h.fetchGoals&&(this.jt=new tt(t,u.requests,c,p=>{o.error(p.message)},(p,m)=>{let y=this.getInternalContext();if(!y)return;let A=d(p);vi(m)?this.sendEvent({kind:"click",url:A,samplingRatio:1,key:m.key,creationDate:Date.now(),context:y,selector:m.selector}):this.sendEvent({kind:"pageview",url:A,samplingRatio:1,key:m.key,creationDate:Date.now(),context:y})}),this.jt.initialize(),h.automaticBackgroundHandling&&yi(()=>this.flush()))}async identify(t,e){var n;await super.identify(t,e),(n=this.jt)==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()}};function is(i,t){return new It(i,j.Disabled,t)}function ns(i){return new P(i)}0&&(module.exports={basicLogger,initialize});
1
+ "use strict";var ht=Object.defineProperty,bi=Object.defineProperties,ki=Object.getOwnPropertyDescriptor,Si=Object.getOwnPropertyDescriptors,xi=Object.getOwnPropertyNames,lt=Object.getOwnPropertySymbols;var Mt=Object.prototype.hasOwnProperty,Ue=Object.prototype.propertyIsEnumerable;var Pe=(i,t,e)=>t in i?ht(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e,g=(i,t)=>{for(var e in t||(t={}))Mt.call(t,e)&&Pe(i,e,t[e]);if(lt)for(var e of lt(t))Ue.call(t,e)&&Pe(i,e,t[e]);return i},b=(i,t)=>bi(i,Si(t));var Pt=(i,t)=>{var e={};for(var n in i)Mt.call(i,n)&&t.indexOf(n)<0&&(e[n]=i[n]);if(i!=null&&lt)for(var n of lt(i))t.indexOf(n)<0&&Ue.call(i,n)&&(e[n]=i[n]);return e};var Li=(i,t)=>{for(var e in t)ht(i,e,{get:t[e],enumerable:!0})},Ai=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of xi(t))!Mt.call(i,s)&&s!==e&&ht(i,s,{get:()=>t[s],enumerable:!(n=ki(t,s))||n.enumerable});return i};var Ci=i=>Ai(ht({},"__esModule",{value:!0}),i);var ss={};Li(ss,{basicLogger:()=>is,initialize:()=>ns});module.exports=Ci(ss);function Oi(i){return`/${i.replace(/~/g,"~0").replace(/\//g,"~1")}`}function _e(i){return i.indexOf("~")?i.replace(/~1/g,"/").replace(/~0/g,"~"):i}function Ri(i){return(i.startsWith("/")?i.substring(1):i).split("/").map(e=>_e(e))}function $i(i){return!i.startsWith("/")}function Ti(i){return!i.match(/\/\/|(^\/.*~[^0|^1])|~$/)}var O=class{constructor(t,e=!1){if(e){let n=t;this.l=[n],this.isValid=n!=="",this.redactionName=n.startsWith("/")?Oi(n):n}else{if(this.redactionName=t,t===""||t==="/"||!Ti(t)){this.isValid=!1,this.l=[];return}$i(t)?this.l=[t]:t.indexOf("/",1)<0?this.l=[_e(t.slice(1))]:this.l=Ri(t),this.l[0]==="_meta"?this.isValid=!1:this.isValid=!0}}get(t){let{l: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.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))}};O.InvalidReference=new O("");var jt=class{is(t){if(Array.isArray(t))return!1;let n=typeof t;return n==="function"||n==="object"}getType(){return"factory method or object"}},R=class{constructor(t,e){this.ut=t,this.typeOf=typeof e}is(t){return Array.isArray(t)?!1:typeof t===this.typeOf}getType(){return this.ut}},pt=class{constructor(t,e){this.ut=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.ut}},K=class extends R{constructor(t){super(`number with minimum value of ${t}`,0),this.min=t}is(t){return typeof t===this.typeOf&&t>=this.min}},gt=class extends R{constructor(t){super(`string matching ${t}`,""),this.expression=t}is(t){return typeof t=="string"&&!!t.match(this.expression)}},Bt=class{is(t){return typeof t=="function"}getType(){return"function"}},Vt=class{is(t){return typeof t=="boolean"||typeof t=="undefined"||t===null}getType(){return"boolean | undefined | null"}},Ii=/^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d\d*)?(Z|[-+]\d\d(:\d\d)?)/,_t=class{is(t){return typeof t=="number"||typeof t=="string"&&Ii.test(t)}getType(){return"date"}},Kt=class extends gt{constructor(){super(/^(\w|\.|-)+$/)}is(t){return super.is(t)&&t!=="kind"}},l=class{static createTypeArray(t,e){return new pt(t,e)}static numberWithMin(t){return new K(t)}static stringMatchingRegex(t){return new gt(t)}};l.String=new R("string","");l.Number=new R("number",0);l.ObjectOrFactory=new jt;l.Object=new R("object",{});l.StringArray=new pt("string[]","");l.Boolean=new R("boolean",!0);l.Function=new Bt;l.Date=new _t;l.Kind=new Kt;l.NullableBoolean=new Vt;function Ke(i){return"kind"in i?l.String.is(i.kind)&&i.kind!=="multi":!1}function He(i){return"kind"in i?l.String.is(i.kind)&&i.kind==="multi":!1}function Ge(i){return!("kind"in i)||i.kind===null||i.kind===void 0}var Ht="user";function Fe(i){return i.includes("%")||i.includes(":")?i.replace(/%/g,"%25").replace(/:/g,"%3A"):i}function Ni(i){return i&&l.Object.is(i)}function je(i){return l.Kind.is(i)}function Be(i){return l.String.is(i)&&i!==""}function Ut(i,t=!1){return i?i.map(e=>new O(e,t)):[]}function Mi(i){return i!=null}function Pi(i){let t=b(g({},i.custom||[]),{kind:"user",key:String(i.key)});if(Mi(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.D=!1,this.J=!1,this.Bt=!1,this.S={},this.kind=e,this.valid=t,this.message=n}static m(t,e){return new i(!1,t,e)}static Ee(t,e){if(!(!e||!t.isValid))return t.depth===1&&t.getComponent(0)==="anonymous"?!!(e!=null&&e.anonymous):t.get(e)}Vt(t){if(this.D)return this.S[t];if(this.kind===t)return this.x}static we(t){let e=Object.keys(t).filter(c=>c!=="kind"),n=e.every(je);if(!e.length)return i.m("multi","A multi-kind context must contain at least one kind");if(!n)return i.m("multi","Context contains invalid kinds");let s={},r=!0,a=e.reduce((c,u)=>{var d;let h=t[u];return Ni(h)?(c[u]=h,s[u]=Ut((d=h._meta)==null?void 0:d.privateAttributes)):r=!1,c},{});if(!r)return i.m("multi","Context contained contexts that were not objects");if(!Object.values(a).every(c=>Be(c.key)))return i.m("multi","Context contained invalid keys");if(e.length===1){let c=e[0],u=new i(!0,c);return u.x=b(g({},a[c]),{kind:c}),u.W=s,u.J=c==="user",u}let o=new i(!0,t.kind);return o.S=a,o.W=s,o.D=!0,o}static De(t){var c;let{key:e,kind:n}=t,s=je(n),r=Be(e);if(!s)return i.m(n!=null?n:"unknown","The kind was not valid for the context");if(!r)return i.m(n,"The key for the context was not valid");let a=Ut((c=t._meta)==null?void 0:c.privateAttributes),o=new i(!0,n);return o.J=n==="user",o.x=t,o.W={[n]:a},o}static be(t){if(!(t.key!==void 0&&t.key!==null))return i.m("user","The key for the context was not valid");let n=new i(!0,"user");return n.J=!0,n.Bt=!0,n.x=Pi(t),n.W={user:Ut(t.privateAttributeNames,!0)},n}static fromLDContext(t){return t?Ke(t)?i.De(t):He(t)?i.we(t):Ge(t)?i.be(t):i.m("unknown","Context was not of a valid kind"):i.m("unknown","No context specified. Returning default value")}static toLDContext(t){if(!t.valid)return;let e=t.getContexts();if(!t.D)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=Ht){return t.isKind?this.kinds:i.Ee(t,this.Vt(e))}key(t=Ht){var e;return(e=this.Vt(t))==null?void 0:e.key}get isMultiKind(){return this.D}get canonicalKey(){return this.J?this.x.key:this.D?Object.keys(this.S).sort().map(t=>`${t}:${Fe(this.S[t].key)}`).join(":"):`${this.kind}:${Fe(this.x.key)}`}get kinds(){return this.D?Object.keys(this.S):[this.kind]}get kindsAndKeys(){return this.D?Object.entries(this.S).reduce((t,[e,n])=>(t[e]=n.key,t),{}):{[this.kind]:this.x.key}}privateAttributes(t){var e;return((e=this.W)==null?void 0:e[t])||[]}getContexts(){return this.D?Object.entries(this.S):[[this.kind,this.x]]}get legacy(){return this.Bt}};k.UserKind=Ht;var Ui=["key","kind","_meta","anonymous"].map(i=>new O(i,!0)),Fi=["name","ip","firstName","lastName","email","avatar","country"];function ji(i,t){return i.depth===t.length&&t.every((e,n)=>e===i.getComponent(n))}function Bi(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=>ji(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 Gt=class{constructor(t,e){this.ke=t,this.Se=e}filter(t,e=!1){let n=t.getContexts();if(n.length===1)return this._t(t,n[0][1],n[0][0],e);let s={kind:"multi"};return n.forEach(([r,a])=>{s[r]=this._t(t,a,r,e)}),s}xe(t,e,n,s){return(s?Object.keys(e).map(r=>new O(r,!0)):[...this.Se,...t.privateAttributes(n)]).filter(r=>!Ui.some(a=>a.compare(r)))}_t(t,e,n,s){let r=this.ke||s&&e.anonymous===!0,{cloned:a,excluded:o}=Bi(e,this.xe(t,e,n,r));return t.legacy&&Fi.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 M=class extends Error{constructor(t,e,n,s=!0){super(e),this.kind=t,this.status=n,this.name="LaunchDarklyPollingError",this.recoverable=s}},x=class extends Error{constructor(t,e,n,s=!0){super(e),this.kind=t,this.code=n,this.name="LaunchDarklyStreamingError",this.recoverable=s}},j;(function(i){i[i.Disabled=0]="Disabled",i[i.Enabled=1]="Enabled"})(j||(j={}));var B;(function(i){i[i.AnalyticsEvents=0]="AnalyticsEvents",i[i.DiagnosticEvent=1]="DiagnosticEvent"})(B||(B={}));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 Vi(i){return typeof i=="symbol"?"NaN":typeof i=="bigint"?`${i}n`:String(Number(i))}function _i(i){return typeof i=="symbol"?"NaN":typeof i=="bigint"?`${i}n`:String(parseInt(i,10))}function Ki(i){return typeof i=="symbol"?"NaN":String(parseFloat(i))}var dt={s:i=>F(i),d:i=>Vi(i),i:i=>_i(i),f:i=>Ki(i),j:i=>F(i),o:i=>F(i),O:i=>F(i),c:()=>""};function qt(...i){var e;let t=i.shift();if(l.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 dt&&i.length){let c=i.shift();n+=(e=dt[o])==null?void 0:e.call(dt,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 Hi=["debug","info","warn","error","none"],P=class i{static get(){return new i({})}constructor(t){var e,n,s;if(this.Le=(n=v[(e=t.level)!=null?e:"info"])!=null?n:v.info,this.Ae=(s=t.name)!=null?s:"LaunchDarkly",this.Kt=t.formatter,typeof t.destination=="object")this.Ht={[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.Ht={[v.debug]:r,[v.info]:r,[v.warn]:r,[v.error]:r}}}Ce(...t){var e;try{return this.Kt?(e=this.Kt)==null?void 0:e.call(this,...t):qt(...t)}catch(n){return qt(...t)}}Oe(t,e){try{t(e)}catch(n){console.error(e)}}y(t,e){var n;if(t>=this.Le){let s=`${Hi[t]}: [${this.Ae}]`;try{let r=(n=this.Ht)==null?void 0:n[t];r?this.Oe(r,`${s} ${this.Ce(...e)}`):console.error(...e)}catch(r){console.error(...e)}}}error(...t){this.y(v.error,t)}warn(...t){this.y(v.warn,t)}info(...t){this.y(v.info,t)}debug(...t){this.y(v.debug,t)}},Gi={error:l.Function,warn:l.Function,info:l.Function,debug:l.Function},H=class{constructor(t,e){Object.entries(Gi).forEach(([n,s])=>{if(!s.is(t[n]))throw new Error(`Provided logger instance must support logger.${n}(...) method`)}),this.t=t,this.Re=e}y(t,e){try{this.t[t](...e)}catch(n){this.Re[t](...e)}}error(...t){this.y("error",t)}warn(...t){this.y("warn",t)}info(...t){this.y("info",t)}debug(...t){this.y("debug",t)}},re=i=>{let t=new P({level:"info",destination:console.error,formatter:qt});return i?new H(i,t):t},D=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`}},qi=/^(\w|\.|-)+$/,Ji=l.stringMatchingRegex(qi),Wi={is:(i,t)=>Ji.is(i)?i.length>64?{valid:!1,message:D.tagValueTooLong(t)}:{valid:!0}:{valid:!1,message:D.invalidTagValue(t)}},mt=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:u}=Wi.is(o,`application.${a}`);c?a==="versionName"?e["application-version-name"]=[o]:e[`application-${a}`]=[o]:s==null||s.warn(u)}});let r=Object.keys(e);r.length&&(this.value=r.sort().flatMap(a=>e[a].sort().map(o=>`${a}/${o}`)).join(" "))}},yt=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 Ft(i){return i.replace(/\/+$/,"")}function ae(i){return i.replace(/^\/+/,"").replace(/\?$/,"")}var U=class i{constructor(t,e,n=i.DEFAULT_EVENTS,s="/bulk",r="/diagnostic",a=!0,o){this.streaming=Ft(t),this.polling=Ft(e),this.events=Ft(n),this.analyticsEventPath=s,this.diagnosticEventPath=r,this.includeAuthorizationHeader=a,this.payloadFilterKey=o}};U.DEFAULT_EVENTS="https://events.launchdarkly.com";function oe(i,t){if(t.length===0)return i;let e=t.map(({key:n,value:s})=>`${n}=${s}`);return`${i}?${e.join("&")}`}function ce(i,t,e){let n=ae(t),s=[...e];return i.payloadFilterKey&&s.push({key:"filter",value:i.payloadFilterKey}),oe(`${i.streaming}/${n}`,s)}function qe(i,t,e){let n=ae(t),s=[...e];return i.payloadFilterKey&&s.push({key:"filter",value:i.payloadFilterKey}),oe(`${i.polling}/${n}`,s)}function Ve(i,t,e){let n=ae(t);return oe(`${i.events}/${n}`,e)}var G=class extends Error{constructor(t){super(t),this.name="LaunchDarklyUnexpectedResponseError"}},q=class extends Error{constructor(t){super(t),this.name="LaunchDarklyClientError"}},Jt=class extends Error{constructor(t){super(t),this.name="LaunchDarklyTimeoutError"}};function W(i){return i>=400&&i<500?i===400||i===408||i===429:!0}function zi(i){return i===413?!0:W(i)}function ue(i){return i==null?i:JSON.parse(JSON.stringify(i))}function Dt(i){return Math.trunc(i*1e3)}var Yi=i=>JSON.stringify(i)==="{}",bt=(i,t)=>i&&Object.entries(i).reduce((e,[n,s])=>(s&&!Yi(s)&&!(t!=null&&t.includes(n))&&(e[n]=typeof s=="object"?bt(s,t):s),e),{});function _(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(!_(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(!_(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(!_(i[r],t[r]))return!1}return!0}return i!==i&&t!==t}function Je(i,t,e,n=!0,s="user-agent"){let{userAgentBase:r,version:a,wrapperName:o,wrapperVersion:c}=t.sdkData(),u={[s]:`${r!=null?r:"NodeJSClient"}/${a}`};return n&&(u.authorization=i),o&&(u["x-launchdarkly-wrapper"]=c?`${o}/${c}`:o),e!=null&&e.value&&(u["x-launchdarkly-tags"]=e.value),u}function $(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 le({status:i}){return i?W(i):!0}var he=(i,t)=>t.btoa(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var Xi=async(i=1e3)=>new Promise(t=>{setTimeout(t,i)}),We=(i,t)=>new Promise((e,n)=>{setTimeout(()=>{let s=`${t} timed out after ${i} seconds.`;n(new Jt(s))},i*1e3)}),Wt=class{constructor(t,e,n){this.r=e,this.$e=n,this.lt=[],this.Gt=Date.now(),this.qt=this.Gt,this.Jt={diagnosticId:e.crypto.randomUUID(),sdkKeySuffix:t.length>6?t.substring(t.length-6):t}}createInitEvent(){var n,s,r;let t=this.r.info.sdkData(),e=this.r.info.platformData();return{kind:"diagnostic-init",id:this.Jt,creationDate:this.Gt,sdk:t,configuration:this.$e,platform:g({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.Jt,creationDate:s,dataSinceDate:this.qt,droppedEvents:t,deduplicatedUsers:e,eventsInLastBatch:n,streamInits:this.lt};return this.lt=[],this.qt=s,r}},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 Zi=zt,vt=class{static invalidMetricValue(t){return`The track function was called with a non-numeric "metricValue" (${t}), only numeric metric values are supported.`}};vt.MissingContextKeyNoEvent="Context was unspecified or had no key; event will not be sent";var Yt=class{constructor(t,e){let{basicConfiguration:n,platform:s}=t,{serviceEndpoints:{analyticsEventPath:r,diagnosticEventPath:a}}=n,{crypto:o,requests:c}=s;this.Te=g({},e),this.Wt=Ve(n.serviceEndpoints,r,[]),this.Ie=Ve(n.serviceEndpoints,a,[]),this.g=c,this.Ne=o}async z(t,e,n,s){let r={status:N.Succeeded},a=b(g({},this.Te),{"content-type":"application/json"});n&&(a["x-launchdarkly-payload-id"]=n,a["x-launchDarkly-event-schema"]="4");let o;try{let{status:c,headers:u}=await this.g.fetch(e,{headers:a,body:JSON.stringify(t),method:"POST",keepalive:!0}),h=Date.parse(u.get("date")||"");if(h&&(r.serverTime=h),c<=204)return r;if(o=new G($({status:c,message:"some events were dropped"},"event posting")),!W(c))return zi(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 Xi(),this.z(t,this.Wt,n,!1))}async sendEventData(t,e){let n=t===B.AnalyticsEvents?this.Ne.randomUUID():void 0,s=t===B.AnalyticsEvents?this.Wt:this.Ie;return this.z(e,s,n,!0)}};function Xt(i){return i.kind==="feature"}function Qi(i){return i.kind==="identify"}function tn(i){return i.kind==="migration_op"}var Zt=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 en(i){return`${i.key}:${i.variation!==null&&i.variation!==void 0?i.variation:""}:${i.version!==null&&i.version!==void 0?i.version:""}`}var Qt=class{constructor(){this.U=0,this.Y=0,this.X={},this.Z={}}summarizeEvent(t){if(Xt(t)&&!t.excludeFromSummaries){let e=en(t),n=this.X[e],s=this.Z[t.key];s||(s=new Set,this.Z[t.key]=s),t.context.kinds.forEach(r=>s.add(r)),n?n.increment():this.X[e]=new Zt(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.Y&&(this.Y=t.creationDate)}}getSummary(){let t=Object.values(this.X).reduce((e,n)=>{let s=e[n.key];s||(s={default:n.default,counters:[],contextKinds:[...this.Z[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.U,endDate:this.Y,features:t,kind:"summary"}}clearSummary(){this.U=0,this.Y=0,this.X={},this.Z={}}},te=class extends Error{constructor(t){super(t),this.name="LaunchDarklyInvalidSDKKeyError"}};function ft(i){let t=Math.trunc(i);return t===1?!0:t===0?!1:Math.floor(Math.random()*t)===0}var ee=class{constructor(t,e,n,s,r,a=!0){this.n=t,this.Q=s,this.a=r,this.ht=new Qt,this.tt=[],this.zt=0,this.dt=0,this.ft=0,this.pt=!1,this.Yt=0,this.gt=!1,this.mt=null,this.Me=t.eventsCapacity,this.t=e.basicConfiguration.logger,this.Xt=new Yt(e,n),this.Zt=new Gt(t.allAttributesPrivate,t.privateAttributes.map(o=>new O(o))),a&&this.start()}start(){var t,e;if(((t=this.Q)==null?void 0:t.flushInterval)!==void 0&&(this.mt=setInterval(()=>{var n;(n=this.Q)==null||n.flush()},this.Q.flushInterval*1e3)),this.Pe=setInterval(async()=>{var n;try{await this.flush()}catch(s){(n=this.t)==null||n.debug(`Flush failed: ${s}`)}},this.n.flushInterval*1e3),this.a){let n=this.a.createInitEvent();this.Qt(n),this.te=setInterval(()=>{let s=this.a.createStatsEventAndReset(this.dt,this.ft,this.Yt);this.dt=0,this.ft=0,this.Qt(s)},this.n.diagnosticRecordingInterval*1e3)}(e=this.t)==null||e.debug("Started EventProcessor.")}Qt(t){this.Xt.sendEventData(B.DiagnosticEvent,t)}close(){clearInterval(this.Pe),this.mt&&clearInterval(this.mt),this.te&&clearInterval(this.te)}async flush(){var n;if(this.gt)throw new te("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.tt;this.tt=[];let e=this.ht.getSummary();this.ht.clearSummary(),Object.keys(e.features).length&&t.push(e),t.length&&(this.Yt=t.length,(n=this.t)==null||n.debug("Flushing %d events",t.length),await this.z(t))}sendEvent(t){var c;if(this.gt)return;if(tn(t)){if(ft(t.samplingRatio)){let u=g({},t);u.samplingRatio===1&&delete u.samplingRatio,this.et(u)}return}this.ht.summarizeEvent(t);let e=Xt(t),n=e&&t.trackEvents||!e,s=this.Ue(t),r=Qi(t),a=(c=this.Q)==null?void 0:c.processContext(t.context);a||r||(this.ft+=1),a&&!r&&this.et(this.yt({kind:"index",creationDate:t.creationDate,context:t.context,samplingRatio:1},!1)),n&&ft(t.samplingRatio)&&this.et(this.yt(t,!1)),s&&ft(t.samplingRatio)&&this.et(this.yt(t,!0))}yt(t,e){switch(t.kind){case"feature":{let n={kind:e?"debug":"feature",creationDate:t.creationDate,context:this.Zt.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.Zt.filter(t.context)};return t.samplingRatio!==1&&(n.samplingRatio=t.samplingRatio),n}case"custom":{let n={kind:"custom",creationDate:t.creationDate,key:t.key,contextKeys:t.context.kindsAndKeys};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}}et(t){var e;this.tt.length<this.Me?(this.tt.push(t),this.pt=!1):(this.pt||(this.pt=!0,(e=this.t)==null||e.warn("Exceeded event queue capacity. Increase capacity to avoid dropping events.")),this.dt+=1)}Ue(t){return Xt(t)&&t.debugEventsUntilDate&&t.debugEventsUntilDate>this.zt&&t.debugEventsUntilDate>Date.now()}async z(t){let e=await this.Xt.sendEventData(B.AnalyticsEvents,t);if(e.status===N.FailedAndMustShutDown&&(this.gt=!0),e.serverTime&&(this.zt=e.serverTime),e.error)throw e.error}},Et=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}},J=class{constructor(t,e,n,s,r,a,o,c,u,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=s,this.default=r,a!==void 0&&(this.version=a),o!==void 0&&(this.variation=o),c!==void 0&&(this.trackEvents=c),u!==void 0&&(this.prereqOf=u),h!==void 0&&(this.reason=h),d!==void 0&&(this.debugEventsUntilDate=d),f!==void 0&&(this.excludeFromSummaries=f)}},wt=class{constructor(t,e=1){this.context=t,this.samplingRatio=e,this.kind="identify",this.creationDate=Date.now()}},ie=class{close(){}async flush(){}sendEvent(){}},ne=class{constructor(t){this.vt=t}evalEvent(t){var e;return new J(this.vt,t.context,t.flagKey,t.value,t.defaultVal,t.version,(e=t.variation)!=null?e:void 0,t.trackEvents||t.addExperimentData,t.prereqOfFlagKey,this.vt||t.addExperimentData?t.reason:void 0,t.debugEventsUntilDate,t.excludeFromSummaries,t.samplingRatio)}unknownFlagEvent(t,e,n){return new J(this.vt,n,t,e,e,void 0,void 0,void 0,void 0,void 0,void 0,void 0,void 0)}identifyEvent(t){return new wt(t,1)}customEvent(t,e,n,s,r=1){return new Et(e,t,n!=null?n:void 0,s!=null?s:void 0,r)}},nn=(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 x(E.InvalidData,"Malformed JSON data in event stream"))},se=class{constructor(t,e,n,s,r,a,o,c=1){this.e=s,this.a=a,this.u=o,this.Fe=c;let{basicConfiguration:u,platform:h}=t,{logger:d}=u,{requests:f}=h;this.C=g({},r),this.t=d,this.g=f,this.Et=ce(u.serviceEndpoints,e,n)}F(){this.v=Date.now()}L(t){this.v&&this.a&&this.a.recordStreamInit(this.v,!t,Date.now()-this.v),this.v=void 0}wt(t){var e,n,s;return le(t)?((s=this.t)==null||s.warn($(t,"streaming request","will retry")),this.L(!1),this.F(),!0):(this.L(!1),(e=this.u)==null||e.call(this,new x(E.ErrorResponse,t.message,t.status)),(n=this.t)==null||n.error($(t,"streaming request")),!1)}start(){this.F();let t=this.g.createEventSource(this.Et,{headers:this.C,errorFilter:e=>this.wt(e),initialRetryDelayMillis:1e3*this.Fe,readTimeoutMillis:5*60*1e3,retryResetIntervalMillis:60*1e3});this.B=t,t.onclose=()=>{var e;(e=this.t)==null||e.info("Closed LaunchDarkly stream connection")},t.onerror=()=>{},t.onopen=()=>{var e;(e=this.t)==null||e.info("Opened LaunchDarkly stream connection")},t.onretrying=e=>{var n;(n=this.t)==null||n.info(`Will retry stream connection in ${e.delayMillis} milliseconds`)},this.e.forEach(({deserializeData:e,processJson:n},s)=>{t.addEventListener(s,r=>{var a,o;if((a=this.t)==null||a.debug(`Received ${s} event`),r!=null&&r.data){this.L(!0);let{data:c}=r,u=e(c);if(!u){nn(s,c,this.t,this.u);return}n(u)}else(o=this.u)==null||o.call(this,new x(E.Unknown,"Unexpected payload from event stream"))})})}stop(){var t;(t=this.B)==null||t.close(),this.B=void 0}close(){this.stop()}},L=Object.freeze({__proto__:null,ClientMessages:vt,DiagnosticsManager:Wt,ErrorKinds:Zi,EventFactoryBase:ne,EventProcessor:ee,InputCustomEvent:Et,InputEvalEvent:J,InputIdentifyEvent:wt,NullEventProcessor:ie,StreamingProcessor:se,isLegacyUser:Ge,isMultiKind:He,isSingleKind:Ke,shouldSample:ft});var w;(function(i){i.Initializing="INITIALIZING",i.Valid="VALID",i.Interrupted="INTERRUPTED",i.SetOffline="SET_OFFLINE",i.Closed="CLOSED"})(w||(w={}));function rn(i){return i>=200&&i<=299}var kt=class extends Error{constructor(t,e){super(t),this.status=e,this.name="LaunchDarklyRequestError"}},me=class{constructor(t,e,n,s,r){this.g=t,this.je=e,this.C=n,this.Be=s,this.Ve=r}async requestPayload(){let t;try{let e=await this.g.fetch(this.je,{method:this.Be,headers:this.C,body:this.Ve});if(rn(e.status))return await e.text();t=e.status}catch(e){throw new kt(e==null?void 0:e.message)}throw new kt(`Unexpected status code: ${t}`,t)}};function Oe(i,t,e,n,s,r,a,o,c,u){let h,d="GET",f=g({},r);c&&(d="REPORT",f["content-type"]="application/json",h=i);let p=c?e.pathReport(s,i):e.pathGet(s,i),m=[...a!=null?a:[]];o&&m.push({key:"withReasons",value:"true"}),u&&m.push({key:"h",value:u});let y=qe(t,p,m);return new me(n,y,f,d,h)}var an={logger:l.Object,maxCachedContexts:l.numberWithMin(0),baseUri:l.String,streamUri:l.String,eventsUri:l.String,capacity:l.numberWithMin(1),diagnosticRecordingInterval:l.numberWithMin(2),flushInterval:l.numberWithMin(2),streamInitialReconnectDelay:l.numberWithMin(0),allAttributesPrivate:l.Boolean,debug:l.Boolean,diagnosticOptOut:l.Boolean,withReasons:l.Boolean,sendEvents:l.Boolean,pollInterval:l.numberWithMin(30),useReport:l.Boolean,privateAttributes:l.StringArray,applicationInfo:l.Object,wrapperName:l.String,wrapperVersion:l.String,payloadFilterKey:l.stringMatchingRegex(/^[a-zA-Z0-9](\w|\.|-)*$/),hooks:l.createTypeArray("Hook[]",{}),inspectors:l.createTypeArray("LDInspection",{})},on=60*5,Qe="https://clientsdk.launchdarkly.com",ti="https://clientstream.launchdarkly.com";function cn(i){return i instanceof H?i:re(i)}var ye=class{constructor(t={},e={}){var s,r,a;this.logger=re(),this.baseUri=Qe,this.eventsUri=U.DEFAULT_EVENTS,this.streamUri=ti,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=on,this.hooks=[],this.inspectors=[],this.logger=cn(t.logger),this._e(t).forEach(o=>this.logger.warn(o)),this.serviceEndpoints=new U(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 mt({application:this.applicationInfo,logger:this.logger}),this.userAgentHeaderName=(r=e.userAgentHeaderName)!=null?r:"user-agent",this.trackEventModifier=(a=e.trackEventModifier)!=null?a:o=>o}_e(t){let e=[];return Object.entries(t).forEach(([n,s])=>{let r=an[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(D.wrongOptionTypeBoolean(n,typeof s)),this[n]=!!s;else if(a==="boolean | undefined | null")e.push(D.wrongOptionTypeBoolean(n,typeof s)),typeof s!="boolean"&&typeof s!="undefined"&&s!==null&&(this[n]=!!s);else if(r instanceof K&&l.Number.is(s)){let{min:o}=r;e.push(D.optionBelowMinimum(n,s,o)),this[n]=o}else e.push(D.wrongOptionType(n,r.getType(),typeof s))}else e.push(D.unknownOption(n))}),e}};async function ei(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 ii=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 ni(i){return async t=>ei(i.createHash("sha256").update(t),"base64")}var S=async i=>i;async function Y(i){return(await Promise.all(i.map(e=>e.transform(e.value)))).join("_")}async function un(i,t){return Y([{value:"LaunchDarkly",transform:S},{value:t,transform:ni(i)}])}async function ln(i){return Y([{value:"LaunchDarkly",transform:S},{value:"AnonymousKeys",transform:S},{value:i,transform:S}])}async function hn(i){return Y([{value:"LaunchDarkly",transform:S},{value:"ContextKeys",transform:S},{value:i,transform:S}])}async function dn(i){return Y([{value:i,transform:S},{value:"ContextIndex",transform:S}])}async function ze(i,t,e){return Y([{value:t,transform:S},{value:e.canonicalKey,transform:ni(i)}])}var{isLegacyUser:fn,isSingleKind:de,isMultiKind:Ye}=L,si="1.0",pn=i=>{let n=i,{kind:t}=n,e=Pt(n,["kind"]);return{kind:"multi",[t]:e}},gn=async({crypto:i,info:t},{applicationInfo:e})=>{var a;let{ld_application:n}=t.platformData(),s=(a=bt(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),u=(e==null?void 0:e.versionName)||(s==null?void 0:s.versionName);return s=g(g(g(b(g({},s),{id:r}),o?{version:o}:{}),c?{name:c}:{}),u?{versionName:u}:{}),s.key=await ei(i.createHash("sha256").update(r),"base64"),s.envAttributesVersion=s.envAttributesVersion||si,s}},mn=async i=>{var o,c,u,h;let{ld_device:t,os:e}=i.info.platformData(),n=(o=bt(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)||((u=n.os)==null?void 0:u.version),a=(h=n.os)==null?void 0:h.family;if((s||r||a)&&(n.os=g(g(g({},s?{name:s}:{}),r?{version:r}:{}),a?{family:a}:{})),Object.keys(n).filter(d=>d!=="key"&&d!=="envAttributesVersion").length){let d=await hn("ld_device");return n.key=await ii(d,i),n.envAttributesVersion=n.envAttributesVersion||si,n}},yn=async(i,t,e)=>{if(fn(i))return i;let n,s;if(de(i)&&i.kind!=="ld_application"||Ye(i)&&!i.ld_application?n=await gn(t,e):e.logger.warn("Not adding ld_application environment attributes because it already exists."),de(i)&&i.kind!=="ld_device"||Ye(i)&&!i.ld_device?s=await mn(t):e.logger.warn("Not adding ld_device environment attributes because it already exists."),n||s){let r=de(i)?pn(i):i;return g(g(g({},r),n?{ld_application:n}:{}),s?{ld_device:s}:{})}return i},{isLegacyUser:vn,isMultiKind:En,isSingleKind:wn}=L,Re=async(i,t,e)=>{let{anonymous:n,key:s}=t;if(n&&!s){let r=await ln(i);t.key=await ii(r,e)}},Dn=async(i,t)=>{await Re(i.kind,i,t)},bn=async(i,t)=>{let s=i,{kind:e}=s,n=Pt(s,["kind"]);return Promise.all(Object.entries(n).map(([r,a])=>Re(r,a,t)))},kn=async(i,t)=>{await Re("user",i,t)},Sn=async(i,t)=>{let e=ue(i);return wn(e)&&await Dn(e,t),En(e)&&await bn(e,t),vn(e)&&await kn(e,t),e},xn=i=>({customBaseURI:i.serviceEndpoints.polling!==Qe,customStreamURI:i.serviceEndpoints.streaming!==ti,customEventsURI:i.serviceEndpoints.events!==U.DEFAULT_EVENTS,eventsCapacity:i.capacity,eventsFlushIntervalMillis:Dt(i.flushInterval),reconnectTimeMillis:Dt(i.streamInitialReconnectDelay),diagnosticRecordingIntervalMillis:Dt(i.diagnosticRecordingInterval),allAttributesPrivate:i.allAttributesPrivate,usingSecureMode:!1,bootstrapMode:!1}),Ln=(i,t,e)=>{if(t.sendEvents&&!t.diagnosticOptOut)return new L.DiagnosticsManager(i,e,xn(t))};function fe(i,t){return{value:t!=null?t:null,variationIndex:null,reason:{kind:"ERROR",errorKind:i}}}function Xe(i,t,e){return{value:i,variationIndex:t!=null?t:null,reason:e!=null?e:null}}var An=(i,t,e,n,s)=>{if(t.sendEvents)return new L.EventProcessor(b(g({},t),{eventsCapacity:t.capacity}),new yt(i,t,e),n,void 0,s,!1)},St=class extends L.EventFactoryBase{evalEventClient(t,e,n,s,r,a){let{trackEvents:o,debugEventsUntilDate:c,trackReason:u,flagVersion:h,version:d,variation:f}=s;return super.evalEvent({addExperimentData:u,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)):[]}},ve=class{constructor(t,e,n,s,r,a,o=()=>Date.now()){this.r=t,this.Dt=e,this.Ke=n,this.h=s,this.b=r,this.t=a,this.it=o,this.ee=dn(this.Dt)}async init(t,e){this.b.init(t,e),await this.ie(t)}async upsert(t,e,n){return this.b.upsert(t,e,n)?(await this.ie(t),!0):!1}async loadCached(t){var s,r,a,o;let e=await ze(this.r.crypto,this.Dt,t),n=await((s=this.r.storage)==null?void 0:s.get(e));if(n==null){if(n=await((r=this.r.storage)==null?void 0:r.get(t.canonicalKey)),n==null)return!1;await((a=this.r.storage)==null?void 0:a.set(e,n)),await((o=this.r.storage)==null?void 0:o.clear(t.canonicalKey))}try{let c=JSON.parse(n),u=Object.entries(c).reduce((h,[d,f])=>(h[d]={version:f.version,flag:f},h),{});return this.b.initCached(t,u),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 He(){var e;if(this.R!==void 0)return this.R;let t=await((e=this.r.storage)==null?void 0:e.get(await this.ee));if(!t)return this.R=new z,this.R;try{this.R=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.R=new z}return this.R}async ie(t){var c,u;let e=await this.He(),n=await ze(this.r.crypto,this.Dt,t);e.notice(n,this.it());let s=e.prune(this.Ke);await Promise.all(s.map(async h=>{var d;return(d=this.r.storage)==null?void 0:d.clear(h.id)})),await((c=this.r.storage)==null?void 0:c.set(await this.ee,e.toJson()));let r=this.h.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((u=this.r.storage)==null?void 0:u.set(n,o))}},Ee=class{constructor(){this.V={}}init(t){this.V=Object.entries(t).reduce((e,[n,s])=>(e[n]=s,e),{})}insertOrUpdate(t,e){this.V[t]=e}get(t){if(Object.prototype.hasOwnProperty.call(this.V,t))return this.V[t]}getAll(){return this.V}};function Cn(i,t){let e=[];return Object.entries(i).forEach(([n,s])=>{let r=t[n];(!r||!_(s,r))&&e.push(n)}),Object.keys(t).forEach(n=>{i[n]||e.push(n)}),e}var we=class{constructor(t,e){this._=new Array,this.h=t,this.t=e}init(t,e){this.ne=t.canonicalKey;let n=this.h.getAll();this.h.init(e);let s=Cn(n,e);s.length>0&&this._.forEach(r=>{try{r(t,s,"init")}catch(a){}})}initCached(t,e){this.ne!==t.canonicalKey&&this.init(t,e)}upsert(t,e,n){if(this.ne!==t.canonicalKey)return this.t.warn("Received an update for an inactive context."),!1;let s=this.h.get(e);return s!==void 0&&s.version>=n.version?!1:(this.h.insertOrUpdate(e,n),this._.forEach(r=>{try{r(t,[e],"patch")}catch(a){}}),!0)}on(t){this._.push(t)}off(t){let e=this._.indexOf(t);e>-1&&this._.splice(e,1)}},De=class{constructor(t,e,n,s,r=()=>Date.now()){this.h=new Ee,this.b=new we(this.h,s),this.bt=this.Ge(t,e,n,s,r)}async Ge(t,e,n,s,r=()=>Date.now()){let a=await un(t.crypto,e);return new ve(t,a,n,this.h,this.b,s,r)}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.bt).init(t,e)}async upsert(t,e,n){return(await this.bt).upsert(t,e,n)}async loadCached(t){return(await this.bt).loadCached(t)}on(t){this.b.on(t)}off(t){this.b.off(t)}},Ze="unknown hook",ri="beforeEvaluation",ai="afterEvaluation";function At(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 Ct(i,t){try{return t.getMetadata().name||Ze}catch(e){return i.error("Exception thrown getting metadata for hook. Unable to get hook name."),Ze}}function On(i,t,e){return t.map(n=>At(i,ri,Ct(i,n),()=>{var s,r;return(r=(s=n==null?void 0:n.beforeEvaluation)==null?void 0:s.call(n,e,{}))!=null?r:{}},{}))}function Rn(i,t,e,n,s){for(let r=t.length-1;r>=0;r-=1){let a=t[r],o=n[r];At(i,ai,Ct(i,a),()=>{var c,u;return(u=(c=a==null?void 0:a.afterEvaluation)==null?void 0:c.call(a,e,o,s))!=null?u:{}},{})}}function $n(i,t,e){return t.map(n=>At(i,ri,Ct(i,n),()=>{var s,r;return(r=(s=n==null?void 0:n.beforeIdentify)==null?void 0:s.call(n,e,{}))!=null?r:{}},{}))}function Tn(i,t,e,n,s){for(let r=t.length-1;r>=0;r-=1){let a=t[r],o=n[r];At(i,ai,Ct(i,a),()=>{var c,u;return(u=(c=a==null?void 0:a.afterIdentify)==null?void 0:c.call(a,e,o,s))!=null?u:{}},{})}}var be=class{constructor(t,e){this.t=t,this.K=[],this.K.push(...e)}withEvaluation(t,e,n,s){if(this.K.length===0)return s();let r=[...this.K],a={flagKey:t,context:e,defaultValue:n},o=On(this.t,r,a),c=s();return Rn(this.t,r,a,o,c),c}identify(t,e){let n=[...this.K],s={context:t,timeout:e},r=$n(this.t,n,s);return a=>{Tn(this.t,n,s,r,a)}}addHook(t){this.K.push(t)}};function In(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 Nn(i,t){return`an inspector: "${t}" of an invalid type (${i}) was configured`}function Mn(i,t){return`an inspector: "${t}" of type: "${i}" generated an exception`}function Pn(i,t){let e=!1,n={method:(...s)=>{try{i.method(...s)}catch(r){e||(e=!0,t.warn(Mn(n.type,n.name)))}},type:i.type,name:i.name,synchronous:i.synchronous};return n}var oi="flag-used",ci="flag-details-changed",ui="flag-detail-changed",li="client-identity-changed",Un=[oi,ci,ui,li];function Fn(i,t){let e=Un.includes(i.type)&&i.method&&typeof i.method=="function";return e||t.warn(Nn(i.type,i.name)),e}var ke=class{constructor(t,e){this.$=[];let n=t.filter(s=>Fn(s,e));this.$=n.map(s=>Pn(s,e))}hasInspectors(){return this.$.length!==0}onFlagUsed(t,e,n){this.$.forEach(s=>{s.type===oi&&s.method(t,e,n)})}onFlagsChanged(t){this.$.forEach(e=>{e.type===ci&&e.method(t)})}onFlagChanged(t,e){this.$.forEach(n=>{n.type===ui&&n.method(t,e)})}onIdentityChanged(t){this.$.forEach(e=>{e.type===li&&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 s=n.filter(r=>r!==e);s.length===0?this.e.delete(t):this.e.set(t,s);return}this.e.delete(t)}}qe(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.qe(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}},{ClientMessages:pe,ErrorKinds:ge}=L,jn=5,xt=class{constructor(t,e,n,s,r,a){if(this.sdkKey=t,this.autoEnvAttributes=e,this.platform=n,this.kt=15,this.k=new St(!1),this.nt=new St(!0),this.St=!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.n=new ye(s,a),this.logger=this.n.logger,this.se=Je(this.sdkKey,this.platform.info,this.n.tags,this.n.serviceEndpoints.includeAuthorizationHeader,this.n.userAgentHeaderName),this.E=new De(this.platform,t,this.n.maxCachedContexts,this.n.logger),this.a=Ln(t,this.n,n),this.p=An(t,this.n,n,this.se,this.a),this.emitter=new Se,this.emitter.on("error",(o,c)=>{this.logger.error(`error: ${c}, context: ${JSON.stringify(o)}`)}),this.E.on((o,c,u)=>{this.Je(c,u);let h=k.toLDContext(o);this.emitter.emit("change",h,c),c.forEach(d=>{this.emitter.emit(`change:${d}`,h)})}),this.dataManager=r(this.E,this.n,this.se,this.emitter,this.a),this.T=new be(this.logger,this.n.hooks),this.H=new ke(this.n.inspectors,this.logger),this.H.hasInspectors()&&this.T.addHook(In(this.H))}allFlags(){return Object.entries(this.E.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,e;await this.flush(),(t=this.p)==null||t.close(),(e=this.yi)==null||e.close(),this.logger.debug("Closed event processor and data source.")}async flush(){var t;try{await((t=this.p)==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.w?ue(this.w):void 0}getInternalContext(){return this.I}We(t,e){let n,s,r=new Promise((c,u)=>{n=c,s=u});if(e)return{identifyPromise:r,identifyResolve:n,identifyReject:s};let a=We(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:jn,s=(e==null?void 0:e.timeout)===void 0&&(e==null?void 0:e.noTimeout)===!0;n>this.kt&&this.logger.warn(`The identify function was called with a timeout greater than ${this.kt} seconds. We recommend a timeout of less than ${this.kt} seconds.`);let r=await Sn(t,this.platform);this.autoEnvAttributes===j.Enabled&&(r=await yn(r,this.platform,this.n));let a=k.fromLDContext(r);if(!a.valid){let p=new Error("Context was unspecified or had no key");return this.emitter.emit("error",r,p),Promise.reject(p)}this.w=r,this.I=a,(f=this.p)==null||f.sendEvent(this.k.identifyEvent(this.I));let{identifyPromise:o,identifyResolve:c,identifyReject:u}=this.We(n,s);this.logger.debug(`Identifying ${JSON.stringify(this.I)}`);let h=this.T.identify(r,e==null?void 0:e.timeout);return await this.dataManager.identify(c,u,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 s,r;if(!this.I||!this.I.valid){this.logger.warn(pe.MissingContextKeyNoEvent);return}n!==void 0&&!l.Number.is(n)&&((s=this.logger)==null||s.warn(pe.invalidMetricValue(typeof n))),(r=this.p)==null||r.sendEvent(this.n.trackEventModifier(this.k.customEvent(t,this.I,e,n)))}st(t,e,n,s){var f,p,m;if(!this.w)return this.logger.debug(pe.MissingContextKeyNoEvent),fe(ge.UserNotSpecified,e);let r=k.fromLDContext(this.w),a=this.E.get(t);if(a===void 0||a.flag.deleted){let y=e!=null?e:null,C=new q(`Unknown feature flag "${t}"; returning default value ${y}.`);return this.emitter.emit("error",this.w,C),(f=this.p)==null||f.sendEvent(this.k.unknownFlagEvent(t,y,r)),fe(ge.FlagNotFound,e)}let{reason:o,value:c,variation:u,prerequisites:h}=a.flag;if(s){let[y,C]=s(c);if(!y){(p=this.p)==null||p.sendEvent(n.evalEventClient(t,e,e,a.flag,r,o));let Nt=new q(`Wrong type "${C}" for feature flag "${t}"; returning default value`);return this.emitter.emit("error",this.w,Nt),fe(ge.WrongType,e)}}let d=Xe(c,u,o);return c==null&&(this.logger.debug("Result value is null. Providing default value."),d.value=e),h==null||h.forEach(y=>{this.st(y,void 0,this.k)}),(m=this.p)==null||m.sendEvent(n.evalEventClient(t,c,e,a.flag,r,o)),d}variation(t,e){let{value:n}=this.T.withEvaluation(t,this.w,e,()=>this.st(t,e,this.k));return n}variationDetail(t,e){return this.T.withEvaluation(t,this.w,e,()=>this.st(t,e,this.nt))}N(t,e,n,s){return this.T.withEvaluation(t,this.w,e,()=>this.st(t,e,n,s))}boolVariation(t,e){return this.N(t,e,this.k,n=>[l.Boolean.is(n),l.Boolean.getType()]).value}jsonVariation(t,e){return this.variation(t,e)}numberVariation(t,e){return this.N(t,e,this.k,n=>[l.Number.is(n),l.Number.getType()]).value}stringVariation(t,e){return this.N(t,e,this.k,n=>[l.String.is(n),l.String.getType()]).value}boolVariationDetail(t,e){return this.N(t,e,this.nt,n=>[l.Boolean.is(n),l.Boolean.getType()])}numberVariationDetail(t,e){return this.N(t,e,this.nt,n=>[l.Number.is(n),l.Number.getType()])}stringVariationDetail(t,e){return this.N(t,e,this.nt,n=>[l.String.is(n),l.String.getType()])}jsonVariationDetail(t,e){return this.variationDetail(t,e)}addHook(t){this.T.addHook(t)}setEventSendingEnabled(t,e){var n,s,r,a;this.St!==t&&(this.St=t,t?(this.logger.debug("Starting event processor"),(n=this.p)==null||n.start()):e?((s=this.logger)==null||s.debug("Flushing event processor before disabling."),this.flush().then(()=>{var o,c;this.St||((o=this.logger)==null||o.debug("Stopping event processor."),(c=this.p)==null||c.close())})):((r=this.logger)==null||r.debug("Stopping event processor."),(a=this.p)==null||a.close()))}sendEvent(t){var e;(e=this.p)==null||e.sendEvent(t)}Je(t,e){if(!this.H.hasInspectors())return;let n={};t.forEach(s=>{let r=this.E.get(s);if(r!=null&&r.flag&&!r.flag.deleted){let{reason:a,value:o,variation:c}=r.flag;n[s]=Xe(o,c,a)}}),e==="init"?this.H.onFlagsChanged(n):e==="patch"&&Object.entries(n).forEach(([s,r])=>{this.H.onFlagChanged(s,r)})}},xe=class{constructor(t,e,n){this.E=t,this.xt=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.E.init(t,n),this.xt.requestStateUpdate(w.Valid)}async handlePatch(t,e){this.t.debug(`Got PATCH ${JSON.stringify(e,null,2)}`),this.E.upsert(t,e.key,{version:e.version,flag:e})}async handleDelete(t,e){this.t.debug(`Got DELETE ${JSON.stringify(e,null,2)}`),this.E.upsert(t,e.key,{version:e.version,flag:b(g({},e),{deleted:!0,flagVersion:0,value:void 0,variation:0,trackEvents:!1})})}handleStreamingError(t){this.xt.reportError(t.kind,t.message,t.code,t.recoverable)}handlePollingError(t){this.xt.reportError(t.kind,t.message,t.status,t.recoverable)}},Le=class{constructor(t,e=()=>Date.now()){this.ze=t,this.rt=w.Closed,this.re=e(),this.it=e}get status(){return{state:this.rt,stateSince:this.re,lastError:this.Ye}}ae(t,e=!1){let n=t===w.Interrupted&&this.rt===w.Initializing?w.Initializing:t,s=this.rt!==n;s&&(this.rt=n,this.re=this.it()),(s||e)&&this.ze.emit("dataSourceStatus",this.status)}requestStateUpdate(t){this.ae(t)}reportError(t,e,n,s=!1){let r={kind:t,message:e,statusCode:n,time:this.it()};this.Ye=r,this.ae(s?w.Interrupted:w.Closed,!0)}},Ae=class{constructor(t,e,n,s,r){this.Xe=t,this.Ze=e,this.Qe=n,this.u=s,this.t=r,this.oe=!1}async ce(){var r,a,o,c,u,h,d;if(this.oe)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 M(E.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.Xe.requestPayload();try{let p=JSON.parse(f);try{(a=this.Qe)==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&&!W(p.status)){(c=this.t)==null||c.error($(f,"polling request")),(u=this.u)==null||u.call(this,new M(E.ErrorResponse,p.message,p.status));return}(h=this.t)==null||h.error($(f,"polling request","will retry"))}let n=Date.now()-e,s=Math.max(this.Ze*1e3-n,0);(d=this.t)==null||d.debug("Elapsed: %d ms, sleeping for %d ms",n,s),this.Lt=setTimeout(()=>{this.ce()},s)}start(){this.ce()}stop(){this.Lt&&(clearTimeout(this.Lt),this.Lt=void 0),this.oe=!0}close(){this.stop()}},Bn=(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 x(E.InvalidData,"Malformed JSON data in event stream"))},Ce=class{constructor(t,e,n,s,r,a,o,c,u){var f;this.ti=t,this.At=e,this.e=n,this.g=s,this.ei=a,this.a=o,this.u=c,this.t=u;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.At.withReasons&&d.push({key:"withReasons",value:"true"}),this.g=s,this.C=g({},e.baseHeaders),this.t=u,this.Et=ce(e.serviceEndpoints,h,d)}F(){this.v=Date.now()}L(t){this.v&&this.a&&this.a.recordStreamInit(this.v,!t,Date.now()-this.v),this.v=void 0}wt(t){var e,n,s;return le(t)?((s=this.t)==null||s.warn($(t,"streaming request","will retry")),this.L(!1),this.F(),!0):(this.L(!1),(e=this.u)==null||e.call(this,new x(E.ErrorResponse,t.message,t.status,!1)),(n=this.t)==null||n.error($(t,"streaming request")),!1)}start(){this.F();let t;this.At.useReport?(this.C["content-type"]="application/json",t={method:"REPORT",body:this.ti}):t={};let e=this.g.createEventSource(this.Et,b(g({headers:this.C},t),{errorFilter:n=>this.wt(n),initialRetryDelayMillis:this.At.initialRetryDelayMillis,readTimeoutMillis:5*60*1e3,retryResetIntervalMillis:60*1e3}));this.B=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.L(!0);let{data:u}=a,h=n(u);if(!h){Bn(r,u,this.t,this.u);return}s(h)}else(c=this.u)==null||c.call(this,new x(E.InvalidData,"Unexpected payload from event stream"))})}),e.addEventListener("ping",async()=>{var n,s,r,a,o,c,u;(n=this.t)==null||n.debug("Got PING, going to poll LaunchDarkly for feature flag updates");try{let h=await this.ei.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 M(E.InvalidData,"Malformed JSON data in ping polling response"))}}catch(h){let d=h;(u=this.u)==null||u.call(this,new M(E.ErrorResponse,d.message,d.status))}})}stop(){var t;(t=this.B)==null||t.close(),this.B=void 0}close(){this.stop()}},Lt=class{constructor(t,e,n,s,r,a,o,c,u){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=u,this.logger=s.logger,this.dataSourceStatusManager=new Le(c),this.M=new xe(e,this.dataSourceStatusManager,this.config.logger)}setConnectionParams(t){this.ii=t}createPollingProcessor(t,e,n,s,r){let a=new Ae(n,this.config.pollInterval,async o=>{await this.M.handlePut(e,o),s==null||s()},o=>{this.emitter.emit("error",t,o),this.M.handlePollingError(o),r==null||r(o)},this.logger);this.updateProcessor=this.ue(a,this.dataSourceStatusManager)}createStreamingProcessor(t,e,n,s,r){var o;let a=new Ce(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.ii)==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.M.handleStreamingError(c),r==null||r(c)},this.logger);this.updateProcessor=this.ue(a,this.dataSourceStatusManager)}createStreamListeners(t,e){let n=new Map;return n.set("put",{deserializeData:JSON.parse,processJson:async s=>{await this.M.handlePut(t,s),e==null||e()}}),n.set("patch",{deserializeData:JSON.parse,processJson:async s=>{this.M.handlePatch(t,s)}}),n.set("delete",{deserializeData:JSON.parse,processJson:async s=>{this.M.handleDelete(t,s)}}),n}ue(t,e){return{start:()=>{e.requestStateUpdate(w.Initializing),t.start()},stop:()=>{t.stop(),e.requestStateUpdate(w.Closed)},close:()=>{t.close(),e.requestStateUpdate(w.Closed)}}}};function Ot(){return typeof document!==void 0}function $e(){return typeof window!==void 0}function Rt(i,t,e){return Ot()?(document.addEventListener(i,t,e),()=>{document.removeEventListener(i,t,e)}):()=>{}}function $t(i,t,e){return Ot()?(window.addEventListener(i,t,e),()=>{window.removeEventListener(i,t,e)}):()=>{}}function A(){return $e()?window.location.href:""}function hi(){return $e()?window.location.search:""}function di(){return $e()?window.location.hash:""}function fi(){if(typeof crypto!==void 0)return crypto;throw Error("Access to a web crypto API is required")}function pi(){return Ot()?document.visibilityState:"visibile"}function gi(i){if(Ot())return document.querySelectorAll(i)}function mi(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=g({value:t[o]},r[o]):c={value:t[o],version:0},a[o]={version:c.version,flag:c}}}),a}var Vn="[BrowserDataManager]",X=class extends Lt{constructor(e,n,s,r,a,o,c,u,h,d){super(e,n,s,r,o,c,u,h,d);this.vi=a;this.G=void 0;this.Ct=!1;this.G=a.streaming}A(e,...n){this.logger.debug(`${Vn} ${e}`,...n)}async identify(e,n,s,r){this.context=s;let a=r;a!=null&&a.hash?this.setConnectionParams({queryParameters:[{key:"h",value:a.hash}]}):this.setConnectionParams(),this.Ot=a==null?void 0:a.hash,a!=null&&a.bootstrap?this.ni(s,a.bootstrap,e):(await this.flagManager.loadCached(s)&&this.A("Identify - Flags loaded from cache. Continuing to initialize via a poll."),await this.si(s,e,n)),this.Rt()}async si(e,n,s){var r,a;try{this.dataSourceStatusManager.requestStateUpdate(w.Initializing);let o=JSON.stringify(k.toLDContext(e)),u=await Oe(o,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ot).requestPayload();try{let d=this.createStreamListeners(e,n).get("put");d.processJson(d.deserializeData(u))}catch(h){this.dataSourceStatusManager.reportError(E.InvalidData,(r=h.message)!=null?r:"Could not parse poll response")}}catch(o){this.dataSourceStatusManager.reportError(E.NetworkError,(a=o.message)!=null?a:"unexpected network error",o.status),s(o)}}ni(e,n,s){this.flagManager.setBootstrap(e,mi(this.logger,n)),this.A("Identify - Initialization completed from bootstrap"),s()}setForcedStreaming(e){this.G=e,this.Rt()}setAutomaticStreamingState(e){this.Ct=e,this.Rt()}Rt(){let e=this.G||this.Ct&&this.G===void 0;this.A(`Updating streaming state. forced(${this.G}) automatic(${this.Ct})`),e?this.ri():this.ai()}ai(){var e;this.updateProcessor&&this.A("Stopping update processor."),(e=this.updateProcessor)==null||e.close(),this.updateProcessor=void 0}ri(){if(this.updateProcessor){this.A("Update processor already active. Not changing state.");return}if(!this.context){this.A("Context not set, not starting update processor.");return}this.A("Starting update processor."),this.oi(this.context)}oi(e,n,s){var c;let r=k.toLDContext(e);(c=this.updateProcessor)==null||c.close();let a=JSON.stringify(k.toLDContext(e)),o=Oe(a,this.config.serviceEndpoints,this.getPollingPaths(),this.platform.requests,this.platform.encoding,this.baseHeaders,[],this.config.withReasons,this.config.useReport,this.Ot);this.createStreamingProcessor(r,e,o,n,s),this.updateProcessor.start()}};function yi(i){let e=Rt("visibilitychange",()=>{pi()==="hidden"&&i()}),n=$t("pagehide",i);return()=>{e(),n()}}function Z(i){if(typeof i!="string")throw new TypeError("Expected a string");return i.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function _n(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(`^${Z(i.url)}/?$`).test(t);case"canonical":return new RegExp(`^${Z(i.url)}/?$`).test(r);case"substring":return new RegExp(`.*${Z(i.substring)}.*$`).test(r);case"regex":return new RegExp(i.pattern).test(r);default:return!1}}function Kn(i,t){let e=[];return t.forEach(n=>{let s=i.target,{selector:r}=n,a=gi(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 Q=class{constructor(t,e){let n=t.filter(a=>{var o;return(o=a.urls)==null?void 0:o.some(c=>_n(c,A(),hi(),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=>{Kn(o,r).forEach(c=>{e(c)})};this.le=Rt("click",a)}}close(){var t;(t=this.le)==null||t.call(this)}};var Hn=300,Tt=class{constructor(t){this.$t=A();let e=()=>{let s=A();s!==this.$t&&(this.$t=s,t())};this.Tt=setInterval(e,Hn);let n=$t("popstate",e);this.he=()=>{n()}}close(){var t;this.Tt&&clearInterval(this.Tt),(t=this.he)==null||t.call(this)}};var tt=class{constructor(t,e,n,s,r,a=o=>new Tt(o)){this.g=e;this.li=s;this.ui=r;this.at=[];this.fe=!1;this.ot=`${n}/sdk/goals/${t}`,this.de=a(()=>{this.Nt()})}async initialize(){await this.ci(),this.Nt()}startTracking(){this.fe=!0,this.Nt()}Nt(){var t;this.fe&&((t=this.It)==null||t.close(),this.at&&this.at.length&&(this.It=new Q(this.at,e=>{this.ui(A(),e)})))}async ci(){try{let t=await this.g.fetch(this.ot);this.at=await t.json()}catch(t){this.li(new G(`Encountered error fetching goals: ${t}`))}}close(){var t,e;(t=this.de)==null||t.close(),(e=this.It)==null||e.close()}};function vi(i){return i.kind==="click"}var Gn=2,Ei={fetchGoals:!0,eventUrlTransformer:i=>i,streaming:void 0},qn={fetchGoals:l.Boolean,eventUrlTransformer:l.Function,streaming:l.Boolean};function wi(i){let t=g({},i);return Object.keys(Ei).forEach(e=>{delete t[e]}),t}function Jn(i){var t;(t=i.flushInterval)!=null||(i.flushInterval=Gn)}function Te(i,t){let e=g({},Ei);return Jn(e),Object.entries(qn).forEach(n=>{let[s,r]=n,a=i[s];a!==void 0&&(r.is(a)?e[s]=a:t.warn(D.wrongOptionType(s,r.getType(),typeof a)))}),e}var et=class{constructor(t,e){this.hi=t;this.pe=[];switch(e){case"sha1":this.Mt="SHA-1";break;case"sha256":this.Mt="SHA-256";break;default:throw new Error(`Algorithm is not supported ${e}`)}}async asyncDigest(t){let e=this.pe.join(""),n=new TextEncoder().encode(e),s=await this.hi.subtle.digest(this.Mt,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.pe.push(t),this}};var Wn={start:0,end:3},zn={start:4,end:5},Ie={start:6,end:7},Ne={start:8,end:8},Yn={start:9,end:9},Xn={start:10,end:15};function Zn(){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 V(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 Qn(i){return i[Ne.start]=(i[Ne.start]|128)&191,i[Ie.start]=i[Ie.start]&15|64,`${V(i,Wn)}-${V(i,zn)}-${V(i,Ie)}-${V(i,Ne)}${V(i,Yn)}-${V(i,Xn)}`}function ts(){let i=Zn();return Qn(i)}function Me(){return typeof crypto!==void 0&&typeof crypto.randomUUID=="function"?crypto.randomUUID():ts()}var it=class{createHash(t){return new et(fi(),t)}randomUUID(){return Me()}};function es(i){let t=Array.from(i,e=>String.fromCodePoint(e)).join("");return btoa(t)}var nt=class{btoa(t){return es(new TextEncoder().encode(t))}};var st=class{platformData(){return{name:"JS"}}sdkData(){return{name:"@launchdarkly/js-client-sdk",version:"0.0.0",userAgentBase:"JSClient"}}};var rt=class{constructor(t,e,n=Math.random){this.pi=e;this.fi=n;this.Pt=0;this.Ut=Math.max(1,t),this.ge=Math.ceil(Math.log2(3e4/this.Ut))}q(){let t=Math.min(this.Pt,this.ge),e=this.Ut*2**t;return Math.min(e,3e4)}di(t){return t-Math.trunc(this.fi()*.5*t)}success(t=Date.now()){this.ct=t}fail(t=Date.now()){this.ct!==void 0&&t-this.ct>this.pi&&(this.Pt=0),this.ct=void 0;let e=this.di(this.q());return this.Pt+=1,e}};var at=class{constructor(t,e){this.ot=t;this.e={};this.q=new rt(e.initialRetryDelayMillis,e.retryResetIntervalMillis),this.me=e.errorFilter,this.ye()}ye(){this.P=new EventSource(this.ot),this.P.onopen=()=>{var t;this.q.success(),(t=this.onopen)==null||t.call(this)},this.P.onerror=t=>{var e;this.gi(t),(e=this.onerror)==null||e.call(this,t)},Object.entries(this.e).forEach(([t,e])=>{e.forEach(n=>{var s;(s=this.P)==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.P)==null||r.addEventListener(t,e)}close(){var t,e;clearTimeout(this.Ft),this.Ft=void 0,(t=this.P)==null||t.close(),(e=this.onclose)==null||e.call(this)}mi(t){var e;(e=this.onretrying)==null||e.call(this,{delayMillis:t}),this.Ft=setTimeout(()=>{this.ye()},t)}gi(t){this.close(),!(t.status&&typeof t.status=="number"&&!this.me(t))&&this.mi(this.q.fail())}};var ot=class{fetch(t,e){return fetch(t,e)}createEventSource(t,e){return new at(t,e)}getEventSourceCapabilities(){return{customMethod:!1,readTimeout:!1,headers:!1}}};function Di(){return typeof localStorage!="undefined"}var ct=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 ut=class{constructor(t){this.encoding=new nt;this.info=new st;this.crypto=new it;this.requests=new ot;Di()&&(this.storage=new ct(t))}};var It=class extends xt{constructor(t,e,n={},s){var f;let{logger:r,debug:a}=n,o=r!=null?r:new P({destination:{debug:console.debug,info:console.info,warn:console.warn,error:console.error},level:a?"debug":"info"}),c=(f=n.baseUri)!=null?f:"https://clientsdk.launchdarkly.com",u=s!=null?s:new ut(o),h=Te(n,o),{eventUrlTransformer:d}=h;super(t,e,u,wi(b(g({},n),{logger:o})),(p,m,y,C,Nt)=>new X(u,p,t,m,h,()=>({pathGet(T,I){return`/sdk/evalx/${t}/contexts/${he(I,T)}`},pathReport(T,I){return`/sdk/evalx/${t}/context`},pathPing(T,I){throw new Error("Ping for polling unsupported.")}}),()=>({pathGet(T,I){return`/eval/${t}/${he(I,T)}`},pathReport(T,I){return`/eval/${t}`},pathPing(T,I){return`/ping/${t}`}}),y,C,Nt),{analyticsEventPath:`/events/bulk/${t}`,diagnosticEventPath:`/events/diagnostic/${t}`,includeAuthorizationHeader:!1,highTimeoutThreshold:5,userAgentHeaderName:"x-launchdarkly-user-agent",trackEventModifier:p=>new L.InputCustomEvent(p.context,p.key,p.data,p.metricValue,p.samplingRatio,d(A()))}),this.setEventSendingEnabled(!0,!1),h.fetchGoals&&(this.jt=new tt(t,u.requests,c,p=>{o.error(p.message)},(p,m)=>{let y=this.getInternalContext();if(!y)return;let C=d(p);vi(m)?this.sendEvent({kind:"click",url:C,samplingRatio:1,key:m.key,creationDate:Date.now(),context:y,selector:m.selector}):this.sendEvent({kind:"pageview",url:C,samplingRatio:1,key:m.key,creationDate:Date.now(),context:y})}),this.jt.initialize(),h.automaticBackgroundHandling&&yi(()=>this.flush()))}async identify(t,e){var n;await super.identify(t,e),(n=this.jt)==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()}};function is(i){return new P(i)}function ns(i,t){return new It(i,j.Disabled,t)}0&&(module.exports={basicLogger,initialize});
package/dist/index.d.cts CHANGED
@@ -1,139 +1,6 @@
1
- import { LDIdentifyOptions, LDOptions, LDClient as LDClient$1, LDContext, BasicLoggerOptions, LDLogger } from '@launchdarkly/js-client-sdk-common';
2
- export { EvaluationSeriesContext, EvaluationSeriesData, Hook, HookMetadata, IdentifySeriesContext, IdentifySeriesData, IdentifySeriesResult, IdentifySeriesStatus, LDContext, LDContextCommon, LDContextMeta, LDEvaluationDetail, LDEvaluationDetailTyped, LDEvaluationReason, LDFlagSet, LDInspection, LDLogLevel, LDLogger, LDMultiKindContext, LDSingleKindContext } from '@launchdarkly/js-client-sdk-common';
3
-
4
- interface BrowserIdentifyOptions extends Omit<LDIdentifyOptions, 'waitForNetworkResults'> {
5
- /**
6
- * The signed context key if you are using [Secure Mode]
7
- * (https://docs.launchdarkly.com/sdk/features/secure-mode#configuring-secure-mode-in-the-javascript-client-side-sdk).
8
- */
9
- hash?: string;
10
- /**
11
- * The initial set of flags to use until the remote set is retrieved.
12
- *
13
- * Bootstrap data can be generated by server SDKs. When bootstrap data is provided the SDK the
14
- * identification operation will complete without waiting for any values from LaunchDarkly and
15
- * the variation calls can be used immediately.
16
- *
17
- * If streaming is activated, either it is configured to always be used, or is activated
18
- * via setStreaming, or via the addition of change handlers, then a streaming connection will
19
- * subsequently be established.
20
- *
21
- * For more information, see the [SDK Reference Guide](https://docs.launchdarkly.com/sdk/features/bootstrapping#javascript).
22
- */
23
- bootstrap?: unknown;
24
- }
25
-
26
- /**
27
- * Initialization options for the LaunchDarkly browser SDK.
28
- */
29
- interface BrowserOptions extends Omit<LDOptions, 'initialConnectionMode'> {
30
- /**
31
- * Whether the client should make a request to LaunchDarkly for Experimentation metrics (goals).
32
- *
33
- * This is true by default, meaning that this request will be made on every page load.
34
- * Set it to false if you are not using Experimentation and want to skip the request.
35
- */
36
- fetchGoals?: boolean;
37
- /**
38
- * A function which, if present, can change the URL in analytics events to something other
39
- * than the actual browser URL. It will be called with the current browser URL as a parameter,
40
- * and returns the value that should be stored in the event's `url` property.
41
- *
42
- * It may be useful to customize the `url` to provide specific meaning, incorporate
43
- * client-side routing concerns, or redact tokens or other info.
44
- */
45
- eventUrlTransformer?: (url: string) => string;
46
- /**
47
- * Whether or not to open a streaming connection to LaunchDarkly for live flag updates.
48
- *
49
- * If this is true, the client will always attempt to maintain a streaming connection; if false,
50
- * it never will. If you leave the value undefined (the default), the client will open a streaming
51
- * connection if you subscribe to `"change"` or `"change:flag-key"` events.
52
- *
53
- * This is equivalent to calling `client.setStreaming()` with the same value.
54
- */
55
- streaming?: boolean;
56
- /**
57
- * Determines if the SDK responds to entering different visibility states, such as foreground and background.
58
- * An example is flushing buffered events when going to the background.
59
- *
60
- * This is true by default. Generally speaking the SDK will be able to most reliably deliver
61
- * events with this setting on.
62
- *
63
- * It may be useful to disable for environments where not all window/document objects are
64
- * available, such as when running the SDK in a browser extension.
65
- */
66
- automaticBackgroundHandling?: boolean;
67
- }
68
-
69
- /**
70
- *
71
- * The LaunchDarkly SDK client object.
72
- *
73
- * Applications should configure the client at page load time and reuse the same instance.
74
- *
75
- * For more information, see the [SDK Reference Guide](https://docs.launchdarkly.com/sdk/client-side/javascript).
76
- */
77
- type LDClient = Omit<LDClient$1, 'setConnectionMode' | 'getConnectionMode' | 'getOffline' | 'identify'> & {
78
- /**
79
- * @ignore
80
- * Implementation Note: We are not supporting dynamically setting the connection mode on the LDClient.
81
- * Implementation Note: The SDK does not support offline mode. Instead bootstrap data can be used.
82
- * Implementation Note: The browser SDK has different identify options, so omits the base implementation
83
- * from the interface.
84
- */
85
- /**
86
- * Specifies whether or not to open a streaming connection to LaunchDarkly for live flag updates.
87
- *
88
- * If this is true, the client will always attempt to maintain a streaming connection; if false,
89
- * it never will. If you leave the value undefined (the default), the client will open a streaming
90
- * connection if you subscribe to `"change"` or `"change:flag-key"` events (see {@link LDClient.on}).
91
- *
92
- * This can also be set as the `streaming` property of {@link LDOptions}.
93
- */
94
- setStreaming(streaming?: boolean): void;
95
- /**
96
- * Identifies a context to LaunchDarkly.
97
- *
98
- * Unlike the server-side SDKs, the client-side JavaScript SDKs maintain a current context state,
99
- * which is set when you call `identify()`.
100
- *
101
- * Changing the current context also causes all feature flag values to be reloaded. Until that has
102
- * finished, calls to {@link variation} will still return flag values for the previous context. You can
103
- * await the Promise to determine when the new flag values are available.
104
- *
105
- * @param context
106
- * The LDContext object.
107
- * @param identifyOptions
108
- * Optional configuration. Please see {@link LDIdentifyOptions}.
109
- * @returns
110
- * A Promise which resolves when the flag values for the specified
111
- * context are available. It rejects when:
112
- *
113
- * 1. The context is unspecified or has no key.
114
- *
115
- * 2. The identify timeout is exceeded. In client SDKs this defaults to 5s.
116
- * You can customize this timeout with {@link LDIdentifyOptions | identifyOptions}.
117
- *
118
- * 3. A network error is encountered during initialization.
119
- *
120
- * @ignore Implementation Note: Browser implementation has different options.
121
- */
122
- identify(context: LDContext, identifyOptions?: BrowserIdentifyOptions): Promise<void>;
123
- };
124
-
125
- /**
126
- * This is the API reference for the LaunchDarkly Client-Side SDK for JavaScript.
127
- *
128
- * This SDK is intended for use in browser environments.
129
- *
130
- * In typical usage, you will call {@link initialize} once at startup time to obtain an instance of
131
- * {@link LDClient}, which provides access to all of the SDK's functionality.
132
- *
133
- * For more information, see the [SDK Reference Guide](https://docs.launchdarkly.com/sdk/client-side/javascript).
134
- *
135
- * @packageDocumentation
136
- */
1
+ import { B as BrowserOptions, L as LDClient } from './common-DPjctgS7.cjs';
2
+ export { a as LDIdentifyOptions, b as basicLogger } from './common-DPjctgS7.cjs';
3
+ export { AutoEnvAttributes, BasicLogger, BasicLoggerOptions, EvaluationSeriesContext, EvaluationSeriesData, Hook, HookMetadata, IdentifySeriesContext, IdentifySeriesData, IdentifySeriesResult, IdentifySeriesStatus, LDContext, LDContextCommon, LDContextMeta, LDEvaluationDetail, LDEvaluationDetailTyped, LDEvaluationReason, LDFlagSet, LDFlagValue, LDInspection, LDLogLevel, LDLogger, LDMultiKindContext, LDSingleKindContext, LDTimeoutError } from '@launchdarkly/js-client-sdk-common';
137
4
 
138
5
  /**
139
6
  * Creates an instance of the LaunchDarkly client.
@@ -152,54 +19,5 @@ type LDClient = Omit<LDClient$1, 'setConnectionMode' | 'getConnectionMode' | 'ge
152
19
  * The new client instance.
153
20
  */
154
21
  declare function initialize(clientSideId: string, options?: BrowserOptions): LDClient;
155
- /**
156
- * Provides a basic {@link LDLogger} implementation.
157
- *
158
- * This logging implementation uses a basic format that includes only the log level
159
- * and the message text. By default this uses log level 'info' and the output is
160
- * written to `console.error`.
161
- *
162
- * To use the logger created by this function, put it into {@link LDOptions.logger}. If
163
- * you do not set {@link LDOptions.logger} to anything, the SDK uses a default logger
164
- * that will log "info" level and higher priorty messages and it will log messages to
165
- * console.info, console.warn, and console.error.
166
- *
167
- * @param options Configuration for the logger. If no options are specified, the
168
- * logger uses `{ level: 'info' }`.
169
- *
170
- * @example
171
- * This example shows how to use `basicLogger` in your SDK options to enable console
172
- * logging only at `warn` and `error` levels.
173
- * ```javascript
174
- * const ldOptions = {
175
- * logger: basicLogger({ level: 'warn' }),
176
- * };
177
- * ```
178
- *
179
- * @example
180
- * This example shows how to use `basicLogger` in your SDK options to cause all
181
- * log output to go to `console.log`
182
- * ```javascript
183
- * const ldOptions = {
184
- * logger: basicLogger({ destination: console.log }),
185
- * };
186
- * ```
187
- *
188
- * * @example
189
- * The configuration also allows you to control the destination for each log level.
190
- * ```javascript
191
- * const ldOptions = {
192
- * logger: basicLogger({
193
- * destination: {
194
- * debug: console.debug,
195
- * info: console.info,
196
- * warn: console.warn,
197
- * error:console.error
198
- * }
199
- * }),
200
- * };
201
- * ```
202
- */
203
- declare function basicLogger(options: BasicLoggerOptions): LDLogger;
204
22
 
205
- export { type LDClient, type BrowserIdentifyOptions as LDIdentifyOptions, type BrowserOptions as LDOptions, basicLogger, initialize };
23
+ export { LDClient, BrowserOptions as LDOptions, initialize };