@flagsmith/flagsmith 12.0.0 → 12.0.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/index.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).index={})}(this,(function(t){"use strict";var e={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},n=function(){return n=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},n.apply(this,arguments)};function i(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((i=i.apply(t,e||[])).next())}))}function a(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function o(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var r=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function s(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!r(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function l(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function u(t){return!!t&&"object"==typeof t&&void 0!==t.value}function c(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))}function d(t){return n(n({},t),{identity:t.identity?n(n({},t.identity),{traits:c(t.identity.traits||{})}):void 0})}var h,v;t.FlagSource=void 0,(h=t.FlagSource||(t.FlagSource={})).NONE="NONE",h.DEFAULT_FLAGS="DEFAULT_FLAGS",h.CACHE="CACHE",h.SERVER="SERVER";var g,f=null,p="FLAGSMITH_EVENT",y=p,m="https://edge.api.flagsmith.com/api/v1/",S="flagsmith_value_",C="flagsmith_enabled_",_="flagsmith_trait_",b=function(){function e(e){var i=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var e=i,a=e.api,o=e.evaluationContext;i.log("Get Flags"),i.isLoading=!0,i.loadingState.isFetching||i.setLoadingState(n(n({},i.loadingState),{isFetching:!0}));var r="".concat(i.getContext().identity),u=function(e){var a,o,u,c;if(e&&r==="".concat(i.getContext().identity)){var d=e.flags,h=e.traits,v=e.identifier;i.isLoading=!1;var g={},f={};h=h||[],(d=d||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),h.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),i.oldFlags=n({},i.flags);var p=s(i.oldFlags,g),y=s(null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.traits,f);if((v||Object.keys(f).length)&&(i.evaluationContext.identity=n(n({},i.evaluationContext.identity),{traits:f}),v&&(i.evaluationContext.identity.identifier=v,i.identity=v)),i.flags=g,i.updateStorage(),i._onChange(i.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},i._loadedState(null,t.FlagSource.SERVER)),i.datadogRum)try{if(i.datadogRum.trackTraits){var m={};Object.keys((null===(o=i.evaluationContext.identity)||void 0===o?void 0:o.traits)||{}).map((function(t){m[_+t]=i.getTrait(t)}));var b=n(n(n({},i.datadogRum.client.getUser()),{id:i.datadogRum.client.getUser().id||(null===(u=i.evaluationContext.identity)||void 0===u?void 0:u.identifier)}),m);i.log("Setting Datadog user",b),i.datadogRum.client.setUser(b)}}catch(t){console.error(t)}if(i.dtrum)try{var E={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(i.flags).map((function(t){l(E,S+t,i.getValue(t,{skipAnalytics:!0})),l(E,C+t,i.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=i.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){l(E,_+t,i.getTrait(t))})),i.log("Sending javaLongOrObject traits to dynatrace",E.javaLongOrObject),i.log("Sending date traits to dynatrace",E.date),i.log("Sending shortString traits to dynatrace",E.shortString),i.log("Sending javaDouble to dynatrace",E.javaDouble),i.dtrum.sendSessionProperties(E.javaLongOrObject,E.date,E.shortString,E.javaDouble)}catch(t){console.error(t)}}};return o.identity?Promise.all([o.identity.traits&&Object.keys(o.identity.traits).length||!o.identity.identifier?i.getJSON(a+"identities/","POST",JSON.stringify({identifier:o.identity.identifier,transient:o.identity.transient,traits:Object.entries(o.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(i.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):i.getJSON(a+"identities/?identifier="+encodeURIComponent(o.identity.identifier)+(o.identity.transient?"&transient=true":""))]).then((function(t){return i.evaluationContext.identity=n(n({},i.evaluationContext.identity),{traits:{}}),u(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):i.getJSON(a+"flags/").then((function(t){return u({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=i.api;if(i.evaluationEvent&&i.evaluationContext.environment&&i.evaluationEvent[i.evaluationContext.environment.apiKey])return i.evaluationEvent&&0!==Object.getOwnPropertyNames(i.evaluationEvent).length&&0!==Object.getOwnPropertyNames(i.evaluationEvent[i.evaluationContext.environment.apiKey]).length?i.getJSON(t+"analytics/flags/","POST",JSON.stringify(i.evaluationEvent[i.evaluationContext.environment.apiKey])).then((function(t){if(i.evaluationContext.environment){var e=i.getState();i.evaluationEvent||(i.evaluationEvent={}),i.evaluationEvent[i.evaluationContext.environment.apiKey]={},i.setState(n(n({},e),{evaluationEvent:i.evaluationEvent})),i.updateEventStorage()}})).catch((function(t){i.log("Exception fetching evaluationEvent",t)})):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:t.FlagSource.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.getValue=function(t,e,n){var a=i.flags&&i.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(a&&(o=a.value),(null==e?void 0:e.skipAnalytics)||n||i.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(i.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,n;return(null===(e=i.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=i.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=i.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var e,a,o=d(t);return i.evaluationContext=n(n({},o),{environment:o.environment||i.evaluationContext.environment}),i.identity=null===(a=null===(e=i.getContext())||void 0===e?void 0:e.identity)||void 0===a?void 0:a.identifier,i.initialised?i.getFlags():Promise.resolve()},this.getContext=function(){return i.evaluationContext},this.updateContext=function(t){return i.setContext(n(n({},i.getContext()),t))},this.setTrait=function(t,e){var a;if(i.api)return i.setContext(n(n({},i.evaluationContext),{identity:n(n({},i.evaluationContext.identity),{traits:n(n({},null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.traits),c(Object.fromEntries([[t,e]])))})}))},this.setTraits=function(t){var e;if(i.api)return i.setContext(n(n({},i.evaluationContext),{identity:n(n({},i.evaluationContext.identity),{traits:n(n({},null===(e=i.evaluationContext.identity)||void 0===e?void 0:e.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,a,o="object"==typeof e,r=i.flags&&i.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!r&&o&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!0),(o&&!e.skipAnalytics||!e)&&i.evaluateFlag(t,"ENABLED"),i.sentryClient)try{null===(a=null===(n=i.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===a||a.call(n,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=i.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=i.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var a,o,r,s=i.headers,l={method:e||"GET",body:n,cache:"no-cache",headers:{}};i.evaluationContext.environment&&(l.headers["X-Environment-Key"]=i.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(a=i.applicationMetadata)||void 0===a?void 0:a.name)&&(l.headers["Flagsmith-Application-Name"]=i.applicationMetadata.name),(null===(o=i.applicationMetadata)||void 0===o?void 0:o.version)&&(l.headers["Flagsmith-Application-Version"]=i.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("12.0.0"),s&&Object.assign(l.headers,s),v||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=i.evaluationContext.identity)||void 0===r?void 0:r.identifier);return v(t,l).then((function(n){var a,o,r="".concat(null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.identifier);if(u===r){var s=null===(o=n.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");i.timestamp=l}catch(t){i.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return i.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}i.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(i.datadogRum&&(i.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?i.datadogRum.client.addFeatureFlagEvaluation(S+t,i.getValue(t,{},!0)):i.datadogRum.client.addFeatureFlagEvaluation(C+t,i.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),i.enableAnalytics){if(!i.evaluationEvent||!i.evaluationContext.environment)return;i.evaluationEvent[i.evaluationContext.environment.apiKey]||(i.evaluationEvent[i.evaluationContext.environment.apiKey]={}),void 0===i.evaluationEvent[i.evaluationContext.environment.apiKey][t]&&(i.evaluationEvent[i.evaluationContext.environment.apiKey][t]=0),i.evaluationEvent[i.evaluationContext.environment.apiKey][t]+=1}i.updateEventStorage()},this._onChange=function(t,e,n){var a,o;i.setLoadingState(n),null===(a=i.onChange)||void 0===a||a.call(i,t,e,i.loadingState),null===(o=i._trigger)||void 0===o||o.call(i)},v=e.fetch?e.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!e.browserlessStorage,this.applicationMetadata=e.applicationMetadata,this.log("Constructing flagsmith instance "+e),e.eventSource&&(g=e.eventSource),e.AsyncStorage&&(f=e.AsyncStorage)}return e.prototype.init=function(e){var o,r,l,u;return i(this,void 0,void 0,(function(){var c,h,g,p,S,C,_,b,E,x,O,F,w,j,I,L,A,k,T,N,P,R,K,D,U,G,J,M,V,H,q,B,W,X,Y,$=this;return a(this,(function(z){switch(z.label){case 0:c=d(e.evaluationContext||this.evaluationContext),z.label=1;case 1:if(z.trys.push([1,13,,14]),h=e.AsyncStorage,g=e._trigger,p=e._triggerLoadingState,S=e.angularHttpClient,C=e.api,_=void 0===C?m:C,b=e.applicationMetadata,E=e.cacheFlags,x=e.cacheOptions,O=e.datadogRum,F=e.defaultFlags,w=e.enableAnalytics,j=e.enableDynatrace,I=e.enableLogs,L=e.environmentID,A=e.eventSourceUrl,k=void 0===A?"https://realtime.flagsmith.com/":A,T=e.fetch,N=e.headers,P=e.identity,R=e.onChange,K=e.onError,D=e.preventFetch,U=e.realtime,G=e.sentryClient,J=e.state,M=e.traits,c.environment=L?{apiKey:L}:c.environment,!c.environment||!c.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(c.identity=P||M?{identifier:P,traits:M?Object.fromEntries(Object.entries(M).map((function(t){return[t[0],{value:t[1]}]}))):{}}:c.identity,this.evaluationContext=c,this.api=(Q=_).endsWith("/")?Q:Q+"/",this.headers=N,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=g||this._trigger,this._triggerLoadingState=p||this._triggerLoadingState,this.onError=function(t){$.setLoadingState(n(n({},$.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==K||K(t)},this.enableLogs=I||!1,this.cacheOptions=x?{skipAPI:!!x.skipAPI,ttl:x.ttl||0,storageKey:x.storageKey,loadStale:!!x.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),T&&(v=T),this.enableAnalytics=w||!1,this.flags=Object.assign({},F)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==f&&!!E,this.applicationMetadata=b,y="FLAGSMITH_EVENT_"+c.environment.apiKey,h&&(f=h),U&&"undefined"!=typeof window&&this.setupRealtime(k,c.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=n(n({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(J),this.log("Initialising with properties",e,this),j&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),G&&(this.sentryClient=G),S&&(v=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(S)),f&&this.canUseStorage&&f.getItem(y).then((function(t){try{$.evaluationEvent=JSON.parse(t)||{}}catch(t){$.evaluationEvent={}}$.analyticsInterval=setInterval($.analyticsFlags,$.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),f&&this.canUseStorage&&f.getItem(y,(function(t,e){if(e&&$.evaluationContext.environment){var i=JSON.parse(e);if(i[$.evaluationContext.environment.apiKey]){var a=$.getState();$.log("Retrieved events from cache",e),$.setState(n(n({},a),{evaluationEvent:i[$.evaluationContext.environment.apiKey]}))}}}))),!E)return[3,9];if(!f||!this.canUseStorage)return[3,8];H=function(e,o){return i($,void 0,void 0,(function(){var e,i,r,l,u,c,h,v,g,f,p,y,m,S,C,_,b,E,x,O=this;return a(this,(function(a){switch(a.label){case 0:if(!o)return[3,7];e=null,i=null,a.label=1;case 1:return a.trys.push([1,5,,6]),r=JSON.parse(o),l=!1,u=!1,r&&r.api===this.api&&(null===(f=null===(g=r.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(c=!0,this.evaluationContext.identity&&(null===(m=null===(y=r.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=r.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),c=!1),this.cacheOptions.ttl&&(!r.ts||(new Date).valueOf()-r.ts>this.cacheOptions.ttl)&&(r.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),c=!1):r.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),u=!0,c=!0)),c&&(l=!0,e=s(this.flags,r.flags),this.setState(n(n({},r),{evaluationContext:d(n(n({},r.evaluationContext),{identity:(null===(_=r.evaluationContext)||void 0===_?void 0:_.identity)?n(n({},null===(b=r.evaluationContext)||void 0===b?void 0:b.identity),{traits:n({},M||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),l?(h=!D&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,t.FlagSource.CACHE,h)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&l&&!u&&this.log("Skipping API, using cache"),h&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:a.sent(),a.label=4;case 4:return[3,6];case 5:throw v=a.sent(),this.log("Exception fetching cached logs",v),v;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return a.sent(),[3,10];case 9:if(F)this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(E=this.evaluationContext.identity)||void 0===E?void 0:E.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS))}a.label=10;case 10:return[2]}}))}))},z.label=2;case 2:return z.trys.push([2,7,,8]),f.getItemSync?(q=f.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,f.getItem(this.getStorageKey())];case 4:q=z.sent(),z.label=5;case 5:return[4,H(null,q)];case 6:return z.sent(),[3,8];case 7:if(B=z.sent(),!this.flags||0===Object.keys(this.flags).length)throw B;return Y=B instanceof Error?B:new Error("".concat(B)),null===(o=this.onError)||void 0===o||o.call(this,Y),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return z.sent(),[3,12];case 11:if(F)this._onChange(null,{isFromServer:!1,flagsChanged:s({},F),traitsChanged:s({},null===(r=c.identity)||void 0===r?void 0:r.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else if(this.flags&&(W=null,0===Object.keys(this.flags).length&&(W=V),this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(l=c.identity)||void 0===l?void 0:l.traits)},this._loadedState(W,t.FlagSource.DEFAULT_FLAGS)),W))throw new Error(W);z.label=12;case 12:return[3,14];case 13:throw X=z.sent(),this.log("Error during initialisation ",X),Y=X instanceof Error?X:new Error("".concat(X)),null===(u=this.onError)||void 0===u||u.call(this,Y),X;case 14:return[2]}var Q}))}))},e.prototype.getAllFlags=function(){return this.flags},e.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},e.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},e.prototype.setState=function(e){var n,i;e&&(this.initialised=!0,this.api=e.api||this.api||m,this.flags=e.flags||this.flags,this.evaluationContext=e.evaluationContext||this.evaluationContext,this.evaluationEvent=e.evaluationEvent||this.evaluationEvent,this.identity=null===(i=null===(n=this.getContext())||void 0===n?void 0:n.identity)||void 0===i?void 0:i.identifier,this.log("setState called",this),this.loadingState.source===t.FlagSource.NONE&&this.flags&&Object.keys(this.flags).length>0&&this.setLoadingState(this._loadedState(null,t.FlagSource.SERVER)))},e.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},e.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},e.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},e.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},e.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,o(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},e.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),f.setItem(this.getStorageKey(),t)}},e.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);f.setItem(y,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},e.prototype.setLoadingState=function(t){var e;r(t,this.loadingState)||(this.loadingState=n({},t),this.log("Loading state changed",t),null===(e=this._triggerLoadingState)||void 0===e||e.call(this))},e.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";g?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new g(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},e}();function E(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new b({fetch:e,AsyncStorage:n,eventSource:i})}var x,O=(x=function(t,e){return x=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},x(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}x(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),F=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},w=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},j=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},I=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return O(e,t),e}(Error),L=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new I;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=F(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=F(j([],w(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=j(j([],w(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var A=function(t,e){return e=e||{},new Promise((function(n,i){var a=new XMLHttpRequest,o=[],r=[],s={},l=function(){return{ok:2==(a.status/100|0),statusText:a.statusText,status:a.status,url:a.responseURL,text:function(){return Promise.resolve(a.responseText)},json:function(){return Promise.resolve(a.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([a.response]))},clone:l,headers:{keys:function(){return o},entries:function(){return r},get:function(t){return s[t.toLowerCase()]},has:function(t){return t.toLowerCase()in s}}}};for(var u in a.open(e.method||"get",t,!0),a.onload=function(){a.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(t,e,n){o.push(e=e.toLowerCase()),r.push([e,n]),s[e]=s[e]?s[e]+","+n:n})),n(l())},a.onerror=i,a.withCredentials="include"==e.credentials,e.headers)a.setRequestHeader(u,e.headers[u]);a.send(e.body||null)}))},k=E({AsyncStorage:e,fetch:A,eventSource:L});"undefined"!=typeof window&&(window.flagsmith=k);t.createFlagsmithInstance=function(){return E({AsyncStorage:e,fetch:A,eventSource:L})},t.default=k,Object.defineProperty(t,"__esModule",{value:!0})}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).index={})}(this,(function(t){"use strict";var e={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},n=function(){return n=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},n.apply(this,arguments)};function i(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((i=i.apply(t,e||[])).next())}))}function a(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function o(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var r=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function s(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!r(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function l(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function u(t){return!!t&&"object"==typeof t&&void 0!==t.value}function c(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))}function d(t){return n(n({},t),{identity:t.identity?n(n({},t.identity),{traits:c(t.identity.traits||{})}):void 0})}var h,v;t.FlagSource=void 0,(h=t.FlagSource||(t.FlagSource={})).NONE="NONE",h.DEFAULT_FLAGS="DEFAULT_FLAGS",h.CACHE="CACHE",h.SERVER="SERVER";var g,f=null,p="FLAGSMITH_EVENT",y=p,m="https://edge.api.flagsmith.com/api/v1/",S="flagsmith_value_",C="flagsmith_enabled_",_="flagsmith_trait_",b=function(){function e(e){var i=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var e=i,a=e.api,o=e.evaluationContext;i.log("Get Flags"),i.isLoading=!0,i.loadingState.isFetching||i.setLoadingState(n(n({},i.loadingState),{isFetching:!0}));var r="".concat(i.getContext().identity),u=function(e){var a,o,u,c;if(e&&r==="".concat(i.getContext().identity)){var d=e.flags,h=e.traits,v=e.identifier;i.isLoading=!1;var g={},f={};h=h||[],(d=d||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),h.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),i.oldFlags=n({},i.flags);var p=s(i.oldFlags,g),y=s(null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.traits,f);if((v||Object.keys(f).length)&&(i.evaluationContext.identity=n(n({},i.evaluationContext.identity),{traits:f}),v&&(i.evaluationContext.identity.identifier=v,i.identity=v)),i.flags=g,i.updateStorage(),i._onChange(i.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},i._loadedState(null,t.FlagSource.SERVER)),i.datadogRum)try{if(i.datadogRum.trackTraits){var m={};Object.keys((null===(o=i.evaluationContext.identity)||void 0===o?void 0:o.traits)||{}).map((function(t){m[_+t]=i.getTrait(t)}));var b=n(n(n({},i.datadogRum.client.getUser()),{id:i.datadogRum.client.getUser().id||(null===(u=i.evaluationContext.identity)||void 0===u?void 0:u.identifier)}),m);i.log("Setting Datadog user",b),i.datadogRum.client.setUser(b)}}catch(t){console.error(t)}if(i.dtrum)try{var E={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(i.flags).map((function(t){l(E,S+t,i.getValue(t,{skipAnalytics:!0})),l(E,C+t,i.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=i.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){l(E,_+t,i.getTrait(t))})),i.log("Sending javaLongOrObject traits to dynatrace",E.javaLongOrObject),i.log("Sending date traits to dynatrace",E.date),i.log("Sending shortString traits to dynatrace",E.shortString),i.log("Sending javaDouble to dynatrace",E.javaDouble),i.dtrum.sendSessionProperties(E.javaLongOrObject,E.date,E.shortString,E.javaDouble)}catch(t){console.error(t)}}};return o.identity?Promise.all([o.identity.traits&&Object.keys(o.identity.traits).length||!o.identity.identifier?i.getJSON(a+"identities/","POST",JSON.stringify({identifier:o.identity.identifier,transient:o.identity.transient,traits:Object.entries(o.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(i.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):i.getJSON(a+"identities/?identifier="+encodeURIComponent(o.identity.identifier)+(o.identity.transient?"&transient=true":""))]).then((function(t){return i.evaluationContext.identity=n(n({},i.evaluationContext.identity),{traits:{}}),u(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):i.getJSON(a+"flags/").then((function(t){return u({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=i.api;if(i.evaluationEvent&&i.evaluationContext.environment&&i.evaluationEvent[i.evaluationContext.environment.apiKey])return i.evaluationEvent&&0!==Object.getOwnPropertyNames(i.evaluationEvent).length&&0!==Object.getOwnPropertyNames(i.evaluationEvent[i.evaluationContext.environment.apiKey]).length?i.getJSON(t+"analytics/flags/","POST",JSON.stringify(i.evaluationEvent[i.evaluationContext.environment.apiKey])).then((function(t){if(i.evaluationContext.environment){var e=i.getState();i.evaluationEvent||(i.evaluationEvent={}),i.evaluationEvent[i.evaluationContext.environment.apiKey]={},i.setState(n(n({},e),{evaluationEvent:i.evaluationEvent})),i.updateEventStorage()}})).catch((function(t){i.log("Exception fetching evaluationEvent",t)})):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:t.FlagSource.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.getValue=function(t,e,n){var a=i.flags&&i.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(a&&(o=a.value),(null==e?void 0:e.skipAnalytics)||n||i.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(i.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,n;return(null===(e=i.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=i.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=i.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var e,a,o=d(t);return i.evaluationContext=n(n({},o),{environment:o.environment||i.evaluationContext.environment}),i.identity=null===(a=null===(e=i.getContext())||void 0===e?void 0:e.identity)||void 0===a?void 0:a.identifier,i.initialised?i.getFlags():Promise.resolve()},this.getContext=function(){return i.evaluationContext},this.updateContext=function(t){return i.setContext(n(n({},i.getContext()),t))},this.setTrait=function(t,e){var a;if(i.api)return i.setContext(n(n({},i.evaluationContext),{identity:n(n({},i.evaluationContext.identity),{traits:n(n({},null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.traits),c(Object.fromEntries([[t,e]])))})}))},this.setTraits=function(t){var e;if(i.api)return i.setContext(n(n({},i.evaluationContext),{identity:n(n({},i.evaluationContext.identity),{traits:n(n({},null===(e=i.evaluationContext.identity)||void 0===e?void 0:e.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,a,o="object"==typeof e,r=i.flags&&i.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!r&&o&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!0),(o&&!e.skipAnalytics||!e)&&i.evaluateFlag(t,"ENABLED"),i.sentryClient)try{null===(a=null===(n=i.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===a||a.call(n,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=i.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=i.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var a,o,r,s=i.headers,l={method:e||"GET",body:n,cache:"no-cache",headers:{}};i.evaluationContext.environment&&(l.headers["X-Environment-Key"]=i.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(a=i.applicationMetadata)||void 0===a?void 0:a.name)&&(l.headers["Flagsmith-Application-Name"]=i.applicationMetadata.name),(null===(o=i.applicationMetadata)||void 0===o?void 0:o.version)&&(l.headers["Flagsmith-Application-Version"]=i.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("12.0.1"),s&&Object.assign(l.headers,s),v||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=i.evaluationContext.identity)||void 0===r?void 0:r.identifier);return v(t,l).then((function(n){var a,o,r="".concat(null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.identifier);if(u===r){var s=null===(o=n.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");i.timestamp=l}catch(t){i.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return i.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}i.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(i.datadogRum&&(i.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?i.datadogRum.client.addFeatureFlagEvaluation(S+t,i.getValue(t,{},!0)):i.datadogRum.client.addFeatureFlagEvaluation(C+t,i.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),i.enableAnalytics){if(!i.evaluationEvent||!i.evaluationContext.environment)return;i.evaluationEvent[i.evaluationContext.environment.apiKey]||(i.evaluationEvent[i.evaluationContext.environment.apiKey]={}),void 0===i.evaluationEvent[i.evaluationContext.environment.apiKey][t]&&(i.evaluationEvent[i.evaluationContext.environment.apiKey][t]=0),i.evaluationEvent[i.evaluationContext.environment.apiKey][t]+=1}i.updateEventStorage()},this._onChange=function(t,e,n){var a,o;i.setLoadingState(n),null===(a=i.onChange)||void 0===a||a.call(i,t,e,i.loadingState),null===(o=i._trigger)||void 0===o||o.call(i)},v=e.fetch?e.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!e.browserlessStorage,this.applicationMetadata=e.applicationMetadata,this.log("Constructing flagsmith instance "+e),e.eventSource&&(g=e.eventSource),e.AsyncStorage&&(f=e.AsyncStorage)}return e.prototype.init=function(e){var o,r,l,u;return i(this,void 0,void 0,(function(){var c,h,g,p,S,C,_,b,E,x,O,F,w,j,I,L,A,k,T,N,P,R,K,D,U,G,J,M,V,H,q,B,W,X,Y,$=this;return a(this,(function(z){switch(z.label){case 0:c=d(e.evaluationContext||this.evaluationContext),z.label=1;case 1:if(z.trys.push([1,13,,14]),h=e.AsyncStorage,g=e._trigger,p=e._triggerLoadingState,S=e.angularHttpClient,C=e.api,_=void 0===C?m:C,b=e.applicationMetadata,E=e.cacheFlags,x=e.cacheOptions,O=e.datadogRum,F=e.defaultFlags,w=e.enableAnalytics,j=e.enableDynatrace,I=e.enableLogs,L=e.environmentID,A=e.eventSourceUrl,k=void 0===A?"https://realtime.flagsmith.com/":A,T=e.fetch,N=e.headers,P=e.identity,R=e.onChange,K=e.onError,D=e.preventFetch,U=e.realtime,G=e.sentryClient,J=e.state,M=e.traits,c.environment=L?{apiKey:L}:c.environment,!c.environment||!c.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(c.identity=P||M?{identifier:P,traits:M?Object.fromEntries(Object.entries(M).map((function(t){return[t[0],{value:t[1]}]}))):{}}:c.identity,this.evaluationContext=c,this.api=(Q=_).endsWith("/")?Q:Q+"/",this.headers=N,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=g||this._trigger,this._triggerLoadingState=p||this._triggerLoadingState,this.onError=function(t){$.setLoadingState(n(n({},$.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==K||K(t)},this.enableLogs=I||!1,this.cacheOptions=x?{skipAPI:!!x.skipAPI,ttl:x.ttl||0,storageKey:x.storageKey,loadStale:!!x.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),T&&(v=T),this.enableAnalytics=w||!1,this.flags=Object.assign({},F)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==f&&!!E,this.applicationMetadata=b,y="FLAGSMITH_EVENT_"+c.environment.apiKey,h&&(f=h),U&&"undefined"!=typeof window&&this.setupRealtime(k,c.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=n(n({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(J),this.log("Initialising with properties",e,this),j&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),G&&(this.sentryClient=G),S&&(v=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(S)),f&&this.canUseStorage&&f.getItem(y).then((function(t){try{$.evaluationEvent=JSON.parse(t)||{}}catch(t){$.evaluationEvent={}}$.analyticsInterval=setInterval($.analyticsFlags,$.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),f&&this.canUseStorage&&f.getItem(y,(function(t,e){if(e&&$.evaluationContext.environment){var i=JSON.parse(e);if(i[$.evaluationContext.environment.apiKey]){var a=$.getState();$.log("Retrieved events from cache",e),$.setState(n(n({},a),{evaluationEvent:i[$.evaluationContext.environment.apiKey]}))}}}))),!E)return[3,9];if(!f||!this.canUseStorage)return[3,8];H=function(e,o){return i($,void 0,void 0,(function(){var e,i,r,l,u,c,h,v,g,f,p,y,m,S,C,_,b,E,x,O=this;return a(this,(function(a){switch(a.label){case 0:if(!o)return[3,7];e=null,i=null,a.label=1;case 1:return a.trys.push([1,5,,6]),r=JSON.parse(o),l=!1,u=!1,r&&r.api===this.api&&(null===(f=null===(g=r.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(c=!0,this.evaluationContext.identity&&(null===(m=null===(y=r.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=r.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),c=!1),this.cacheOptions.ttl&&(!r.ts||(new Date).valueOf()-r.ts>this.cacheOptions.ttl)&&(r.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),c=!1):r.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),u=!0,c=!0)),c&&(l=!0,e=s(this.flags,r.flags),this.setState(n(n({},r),{evaluationContext:d(n(n({},r.evaluationContext),{identity:(null===(_=r.evaluationContext)||void 0===_?void 0:_.identity)?n(n({},null===(b=r.evaluationContext)||void 0===b?void 0:b.identity),{traits:n({},M||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),l?(h=!D&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,t.FlagSource.CACHE,h)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&l&&!u&&this.log("Skipping API, using cache"),h&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:a.sent(),a.label=4;case 4:return[3,6];case 5:throw v=a.sent(),this.log("Exception fetching cached logs",v),v;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return a.sent(),[3,10];case 9:if(F)this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(E=this.evaluationContext.identity)||void 0===E?void 0:E.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS))}a.label=10;case 10:return[2]}}))}))},z.label=2;case 2:return z.trys.push([2,7,,8]),f.getItemSync?(q=f.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,f.getItem(this.getStorageKey())];case 4:q=z.sent(),z.label=5;case 5:return[4,H(null,q)];case 6:return z.sent(),[3,8];case 7:if(B=z.sent(),!this.flags||0===Object.keys(this.flags).length)throw B;return Y=B instanceof Error?B:new Error("".concat(B)),null===(o=this.onError)||void 0===o||o.call(this,Y),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return z.sent(),[3,12];case 11:if(F)this._onChange(null,{isFromServer:!1,flagsChanged:s({},F),traitsChanged:s({},null===(r=c.identity)||void 0===r?void 0:r.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else if(this.flags&&(W=null,0===Object.keys(this.flags).length&&(W=V),this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(l=c.identity)||void 0===l?void 0:l.traits)},this._loadedState(W,t.FlagSource.DEFAULT_FLAGS)),W))throw new Error(W);z.label=12;case 12:return[3,14];case 13:throw X=z.sent(),this.log("Error during initialisation ",X),Y=X instanceof Error?X:new Error("".concat(X)),null===(u=this.onError)||void 0===u||u.call(this,Y),X;case 14:return[2]}var Q}))}))},e.prototype.getAllFlags=function(){return this.flags},e.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},e.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},e.prototype.setState=function(e){var n,i;e&&(this.initialised=!0,this.api=e.api||this.api||m,this.flags=e.flags||this.flags,this.evaluationContext=e.evaluationContext||this.evaluationContext,this.evaluationEvent=e.evaluationEvent||this.evaluationEvent,this.identity=null===(i=null===(n=this.getContext())||void 0===n?void 0:n.identity)||void 0===i?void 0:i.identifier,this.log("setState called",this),this.loadingState.source===t.FlagSource.NONE&&this.flags&&Object.keys(this.flags).length>0&&this.setLoadingState(this._loadedState(null,t.FlagSource.SERVER)))},e.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},e.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},e.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},e.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},e.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,o(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},e.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),f.setItem(this.getStorageKey(),t)}},e.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);f.setItem(y,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},e.prototype.setLoadingState=function(t){var e;r(t,this.loadingState)||(this.loadingState=n({},t),this.log("Loading state changed",t),null===(e=this._triggerLoadingState)||void 0===e||e.call(this))},e.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";g?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new g(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},e}();function E(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new b({fetch:e,AsyncStorage:n,eventSource:i})}var x,O=(x=function(t,e){return x=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},x(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}x(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),F=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},w=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},j=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},I=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return O(e,t),e}(Error),L=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new I;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=F(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=F(j([],w(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=j(j([],w(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var A=function(t,e){return e=e||{},new Promise((function(n,i){var a=new XMLHttpRequest,o=[],r=[],s={},l=function(){return{ok:2==(a.status/100|0),statusText:a.statusText,status:a.status,url:a.responseURL,text:function(){return Promise.resolve(a.responseText)},json:function(){return Promise.resolve(a.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([a.response]))},clone:l,headers:{keys:function(){return o},entries:function(){return r},get:function(t){return s[t.toLowerCase()]},has:function(t){return t.toLowerCase()in s}}}};for(var u in a.open(e.method||"get",t,!0),a.onload=function(){a.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(t,e,n){o.push(e=e.toLowerCase()),r.push([e,n]),s[e]=s[e]?s[e]+","+n:n})),n(l())},a.onerror=i,a.withCredentials="include"==e.credentials,e.headers)a.setRequestHeader(u,e.headers[u]);a.send(e.body||null)}))},k=E({AsyncStorage:e,fetch:A,eventSource:L});"undefined"!=typeof window&&(window.flagsmith=k);t.createFlagsmithInstance=function(){return E({AsyncStorage:e,fetch:A,eventSource:L})},t.default=k,Object.defineProperty(t,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=index.js.map
package/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var t={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},e=function(){return e=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},e.apply(this,arguments)};function n(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((i=i.apply(t,e||[])).next())}))}function i(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function a(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var o=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function r(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!o(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function s(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function l(t){return!!t&&"object"==typeof t&&void 0!==t.value}function u(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,l(n)?n:{value:n}]})))}function c(t){return e(e({},t),{identity:t.identity?e(e({},t.identity),{traits:u(t.identity.traits||{})}):void 0})}var h,d;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(h||(h={}));var v,g=null,f="FLAGSMITH_EVENT",p="https://edge.api.flagsmith.com/api/v1/",y=function(){function t(t){var n=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var t=n,i=t.api,a=t.evaluationContext;n.log("Get Flags"),n.isLoading=!0,n.loadingState.isFetching||n.setLoadingState(e(e({},n.loadingState),{isFetching:!0}));var o="".concat(n.getContext().identity),l=function(t){var i,a,l,u;if(t&&o==="".concat(n.getContext().identity)){var c=t.flags,d=t.traits,v=t.identifier;n.isLoading=!1;var g={},f={};d=d||[],(c=c||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),d.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),n.oldFlags=e({},n.flags);var p=r(n.oldFlags,g),y=r(null===(i=n.evaluationContext.identity)||void 0===i?void 0:i.traits,f);if((v||Object.keys(f).length)&&(n.evaluationContext.identity=e(e({},n.evaluationContext.identity),{traits:f}),v&&(n.evaluationContext.identity.identifier=v,n.identity=v)),n.flags=g,n.updateStorage(),n._onChange(n.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},n._loadedState(null,h.SERVER)),n.datadogRum)try{if(n.datadogRum.trackTraits){var m={};Object.keys((null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.traits)||{}).map((function(t){m["flagsmith_trait_"+t]=n.getTrait(t)}));var S=e(e(e({},n.datadogRum.client.getUser()),{id:n.datadogRum.client.getUser().id||(null===(l=n.evaluationContext.identity)||void 0===l?void 0:l.identifier)}),m);n.log("Setting Datadog user",S),n.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(n.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(n.flags).map((function(t){s(C,"flagsmith_value_"+t,n.getValue(t,{skipAnalytics:!0})),s(C,"flagsmith_enabled_"+t,n.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(u=n.evaluationContext.identity)||void 0===u?void 0:u.traits)||{}).map((function(t){s(C,"flagsmith_trait_"+t,n.getTrait(t))})),n.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),n.log("Sending date traits to dynatrace",C.date),n.log("Sending shortString traits to dynatrace",C.shortString),n.log("Sending javaDouble to dynatrace",C.javaDouble),n.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return a.identity?Promise.all([a.identity.traits&&Object.keys(a.identity.traits).length||!a.identity.identifier?n.getJSON(i+"identities/","POST",JSON.stringify({identifier:a.identity.identifier,transient:a.identity.transient,traits:Object.entries(a.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(n.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):n.getJSON(i+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(t){return n.evaluationContext.identity=e(e({},n.evaluationContext.identity),{traits:{}}),l(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):n.getJSON(i+"flags/").then((function(t){return l({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=n.api;if(n.evaluationEvent&&n.evaluationContext.environment&&n.evaluationEvent[n.evaluationContext.environment.apiKey])return n.evaluationEvent&&0!==Object.getOwnPropertyNames(n.evaluationEvent).length&&0!==Object.getOwnPropertyNames(n.evaluationEvent[n.evaluationContext.environment.apiKey]).length?n.getJSON(t+"analytics/flags/","POST",JSON.stringify(n.evaluationEvent[n.evaluationContext.environment.apiKey])).then((function(t){if(n.evaluationContext.environment){var i=n.getState();n.evaluationEvent||(n.evaluationEvent={}),n.evaluationEvent[n.evaluationContext.environment.apiKey]={},n.setState(e(e({},i),{evaluationEvent:n.evaluationEvent})),n.updateEventStorage()}})).catch((function(t){n.log("Exception fetching evaluationEvent",t)})):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:h.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.getValue=function(t,e,i){var a=n.flags&&n.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(a&&(o=a.value),(null==e?void 0:e.skipAnalytics)||i||n.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(n.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,i;return(null===(e=n.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(i=n.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===i?void 0:i.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=n.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var i,a,o=c(t);return n.evaluationContext=e(e({},o),{environment:o.environment||n.evaluationContext.environment}),n.identity=null===(a=null===(i=n.getContext())||void 0===i?void 0:i.identity)||void 0===a?void 0:a.identifier,n.initialised?n.getFlags():Promise.resolve()},this.getContext=function(){return n.evaluationContext},this.updateContext=function(t){return n.setContext(e(e({},n.getContext()),t))},this.setTrait=function(t,i){var a;if(n.api)return n.setContext(e(e({},n.evaluationContext),{identity:e(e({},n.evaluationContext.identity),{traits:e(e({},null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.traits),u(Object.fromEntries([[t,i]])))})}))},this.setTraits=function(t){var i;if(n.api)return n.setContext(e(e({},n.evaluationContext),{identity:e(e({},n.evaluationContext.identity),{traits:e(e({},null===(i=n.evaluationContext.identity)||void 0===i?void 0:i.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,l(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var i,a,o="object"==typeof e,r=n.flags&&n.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!r&&o&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!0),(o&&!e.skipAnalytics||!e)&&n.evaluateFlag(t,"ENABLED"),n.sentryClient)try{null===(a=null===(i=n.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===i?void 0:i.addFeatureFlag)||void 0===a||a.call(i,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=n.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=n.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,i){var a,o,r,s=n.headers,l={method:e||"GET",body:i,cache:"no-cache",headers:{}};n.evaluationContext.environment&&(l.headers["X-Environment-Key"]=n.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(a=n.applicationMetadata)||void 0===a?void 0:a.name)&&(l.headers["Flagsmith-Application-Name"]=n.applicationMetadata.name),(null===(o=n.applicationMetadata)||void 0===o?void 0:o.version)&&(l.headers["Flagsmith-Application-Version"]=n.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("12.0.0"),s&&Object.assign(l.headers,s),d||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=n.evaluationContext.identity)||void 0===r?void 0:r.identifier);return d(t,l).then((function(i){var a,o,r="".concat(null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.identifier);if(u===r){var s=null===(o=i.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");n.timestamp=l}catch(t){n.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return n.log("Fetch response: "+i.status+" "+(e||"GET")+0+t),i.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&i.status&&(e="API Response: ".concat(i.status)),i.status&&i.status>=200&&i.status<300?e:Promise.reject(new Error(e))}))}n.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(n.datadogRum&&(n.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?n.datadogRum.client.addFeatureFlagEvaluation("flagsmith_value_"+t,n.getValue(t,{},!0)):n.datadogRum.client.addFeatureFlagEvaluation("flagsmith_enabled_"+t,n.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),n.enableAnalytics){if(!n.evaluationEvent||!n.evaluationContext.environment)return;n.evaluationEvent[n.evaluationContext.environment.apiKey]||(n.evaluationEvent[n.evaluationContext.environment.apiKey]={}),void 0===n.evaluationEvent[n.evaluationContext.environment.apiKey][t]&&(n.evaluationEvent[n.evaluationContext.environment.apiKey][t]=0),n.evaluationEvent[n.evaluationContext.environment.apiKey][t]+=1}n.updateEventStorage()},this._onChange=function(t,e,i){var a,o;n.setLoadingState(i),null===(a=n.onChange)||void 0===a||a.call(n,t,e,n.loadingState),null===(o=n._trigger)||void 0===o||o.call(n)},d=t.fetch?t.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!t.browserlessStorage,this.applicationMetadata=t.applicationMetadata,this.log("Constructing flagsmith instance "+t),t.eventSource&&(v=t.eventSource),t.AsyncStorage&&(g=t.AsyncStorage)}return t.prototype.init=function(t){var a,o,s,l;return n(this,void 0,void 0,(function(){var u,v,y,m,S,C,_,b,E,x,O,F,w,L,I,j,A,k,T,N,P,R,K,D,U,G,J,M,V,H,q,B,W,X,Y,$=this;return i(this,(function(z){switch(z.label){case 0:u=c(t.evaluationContext||this.evaluationContext),z.label=1;case 1:if(z.trys.push([1,13,,14]),v=t.AsyncStorage,y=t._trigger,m=t._triggerLoadingState,S=t.angularHttpClient,C=t.api,_=void 0===C?p:C,b=t.applicationMetadata,E=t.cacheFlags,x=t.cacheOptions,O=t.datadogRum,F=t.defaultFlags,w=t.enableAnalytics,L=t.enableDynatrace,I=t.enableLogs,j=t.environmentID,A=t.eventSourceUrl,k=void 0===A?"https://realtime.flagsmith.com/":A,T=t.fetch,N=t.headers,P=t.identity,R=t.onChange,K=t.onError,D=t.preventFetch,U=t.realtime,G=t.sentryClient,J=t.state,M=t.traits,u.environment=j?{apiKey:j}:u.environment,!u.environment||!u.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(u.identity=P||M?{identifier:P,traits:M?Object.fromEntries(Object.entries(M).map((function(t){return[t[0],{value:t[1]}]}))):{}}:u.identity,this.evaluationContext=u,this.api=(Q=_).endsWith("/")?Q:Q+"/",this.headers=N,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=y||this._trigger,this._triggerLoadingState=m||this._triggerLoadingState,this.onError=function(t){$.setLoadingState(e(e({},$.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==K||K(t)},this.enableLogs=I||!1,this.cacheOptions=x?{skipAPI:!!x.skipAPI,ttl:x.ttl||0,storageKey:x.storageKey,loadStale:!!x.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),T&&(d=T),this.enableAnalytics=w||!1,this.flags=Object.assign({},F)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==g&&!!E,this.applicationMetadata=b,f="FLAGSMITH_EVENT_"+u.environment.apiKey,v&&(g=v),U&&"undefined"!=typeof window&&this.setupRealtime(k,u.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:h.DEFAULT_FLAGS})),this.setState(J),this.log("Initialising with properties",t,this),L&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),G&&(this.sentryClient=G),S&&(d=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(S)),g&&this.canUseStorage&&g.getItem(f).then((function(t){try{$.evaluationEvent=JSON.parse(t)||{}}catch(t){$.evaluationEvent={}}$.analyticsInterval=setInterval($.analyticsFlags,$.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),g&&this.canUseStorage&&g.getItem(f,(function(t,n){if(n&&$.evaluationContext.environment){var i=JSON.parse(n);if(i[$.evaluationContext.environment.apiKey]){var a=$.getState();$.log("Retrieved events from cache",n),$.setState(e(e({},a),{evaluationEvent:i[$.evaluationContext.environment.apiKey]}))}}}))),!E)return[3,9];if(!g||!this.canUseStorage)return[3,8];H=function(t,a){return n($,void 0,void 0,(function(){var t,n,o,s,l,u,d,v,g,f,p,y,m,S,C,_,b,E,x,O=this;return i(this,(function(i){switch(i.label){case 0:if(!a)return[3,7];t=null,n=null,i.label=1;case 1:return i.trys.push([1,5,,6]),o=JSON.parse(a),s=!1,l=!1,o&&o.api===this.api&&(null===(f=null===(g=o.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(u=!0,this.evaluationContext.identity&&(null===(m=null===(y=o.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=o.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),u=!1),this.cacheOptions.ttl&&(!o.ts||(new Date).valueOf()-o.ts>this.cacheOptions.ttl)&&(o.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),u=!1):o.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),l=!0,u=!0)),u&&(s=!0,t=r(this.flags,o.flags),this.setState(e(e({},o),{evaluationContext:c(e(e({},o.evaluationContext),{identity:(null===(_=o.evaluationContext)||void 0===_?void 0:_.identity)?e(e({},null===(b=o.evaluationContext)||void 0===b?void 0:b.identity),{traits:e({},M||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),s?(d=!D&&(!this.cacheOptions.skipAPI||l),this._onChange(null,{isFromServer:!1,flagsChanged:t,traitsChanged:n},this._loadedState(null,h.CACHE,d)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!l&&this.log("Skipping API, using cache"),d&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:i.sent(),i.label=4;case 4:return[3,6];case 5:throw v=i.sent(),this.log("Exception fetching cached logs",v),v;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(F)this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(E=this.evaluationContext.identity)||void 0===E?void 0:E.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,h.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},z.label=2;case 2:return z.trys.push([2,7,,8]),g.getItemSync?(q=g.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,g.getItem(this.getStorageKey())];case 4:q=z.sent(),z.label=5;case 5:return[4,H(null,q)];case 6:return z.sent(),[3,8];case 7:if(B=z.sent(),!this.flags||0===Object.keys(this.flags).length)throw B;return Y=B instanceof Error?B:new Error("".concat(B)),null===(a=this.onError)||void 0===a||a.call(this,Y),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return z.sent(),[3,12];case 11:if(F)this._onChange(null,{isFromServer:!1,flagsChanged:r({},F),traitsChanged:r({},null===(o=u.identity)||void 0===o?void 0:o.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else if(this.flags&&(W=null,0===Object.keys(this.flags).length&&(W=V),this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(s=u.identity)||void 0===s?void 0:s.traits)},this._loadedState(W,h.DEFAULT_FLAGS)),W))throw new Error(W);z.label=12;case 12:return[3,14];case 13:throw X=z.sent(),this.log("Error during initialisation ",X),Y=X instanceof Error?X:new Error("".concat(X)),null===(l=this.onError)||void 0===l||l.call(this,Y),X;case 14:return[2]}var Q}))}))},t.prototype.getAllFlags=function(){return this.flags},t.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,l(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},t.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},t.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||p,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this),this.loadingState.source===h.NONE&&this.flags&&Object.keys(this.flags).length>0&&this.setLoadingState(this._loadedState(null,h.SERVER)))},t.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},t.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},t.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},t.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,a(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},t.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),g.setItem(this.getStorageKey(),t)}},t.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);g.setItem(f,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},t.prototype.setLoadingState=function(t){var n;o(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(n=this._triggerLoadingState)||void 0===n||n.call(this))},t.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";v?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new v(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},t}();function m(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new y({fetch:e,AsyncStorage:n,eventSource:i})}var S,C=(S=function(t,e){return S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},S(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}S(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),_=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},b=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},E=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},x=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return C(e,t),e}(Error),O=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new x;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=_(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=_(E([],b(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=E(E([],b(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var F=function(t,e){return e=e||{},new Promise((function(n,i){var a=new XMLHttpRequest,o=[],r=[],s={},l=function(){return{ok:2==(a.status/100|0),statusText:a.statusText,status:a.status,url:a.responseURL,text:function(){return Promise.resolve(a.responseText)},json:function(){return Promise.resolve(a.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([a.response]))},clone:l,headers:{keys:function(){return o},entries:function(){return r},get:function(t){return s[t.toLowerCase()]},has:function(t){return t.toLowerCase()in s}}}};for(var u in a.open(e.method||"get",t,!0),a.onload=function(){a.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(t,e,n){o.push(e=e.toLowerCase()),r.push([e,n]),s[e]=s[e]?s[e]+","+n:n})),n(l())},a.onerror=i,a.withCredentials="include"==e.credentials,e.headers)a.setRequestHeader(u,e.headers[u]);a.send(e.body||null)}))},w=m({AsyncStorage:t,fetch:F,eventSource:O});"undefined"!=typeof window&&(window.flagsmith=w);var L=function(){return m({AsyncStorage:t,fetch:F,eventSource:O})};export{h as FlagSource,L as createFlagsmithInstance,w as default};
1
+ var t={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},e=function(){return e=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},e.apply(this,arguments)};function n(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((i=i.apply(t,e||[])).next())}))}function i(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function a(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var o=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function r(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!o(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function s(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function l(t){return!!t&&"object"==typeof t&&void 0!==t.value}function u(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,l(n)?n:{value:n}]})))}function c(t){return e(e({},t),{identity:t.identity?e(e({},t.identity),{traits:u(t.identity.traits||{})}):void 0})}var h,d;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(h||(h={}));var v,g=null,f="FLAGSMITH_EVENT",p="https://edge.api.flagsmith.com/api/v1/",y=function(){function t(t){var n=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var t=n,i=t.api,a=t.evaluationContext;n.log("Get Flags"),n.isLoading=!0,n.loadingState.isFetching||n.setLoadingState(e(e({},n.loadingState),{isFetching:!0}));var o="".concat(n.getContext().identity),l=function(t){var i,a,l,u;if(t&&o==="".concat(n.getContext().identity)){var c=t.flags,d=t.traits,v=t.identifier;n.isLoading=!1;var g={},f={};d=d||[],(c=c||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),d.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),n.oldFlags=e({},n.flags);var p=r(n.oldFlags,g),y=r(null===(i=n.evaluationContext.identity)||void 0===i?void 0:i.traits,f);if((v||Object.keys(f).length)&&(n.evaluationContext.identity=e(e({},n.evaluationContext.identity),{traits:f}),v&&(n.evaluationContext.identity.identifier=v,n.identity=v)),n.flags=g,n.updateStorage(),n._onChange(n.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},n._loadedState(null,h.SERVER)),n.datadogRum)try{if(n.datadogRum.trackTraits){var m={};Object.keys((null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.traits)||{}).map((function(t){m["flagsmith_trait_"+t]=n.getTrait(t)}));var S=e(e(e({},n.datadogRum.client.getUser()),{id:n.datadogRum.client.getUser().id||(null===(l=n.evaluationContext.identity)||void 0===l?void 0:l.identifier)}),m);n.log("Setting Datadog user",S),n.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(n.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(n.flags).map((function(t){s(C,"flagsmith_value_"+t,n.getValue(t,{skipAnalytics:!0})),s(C,"flagsmith_enabled_"+t,n.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(u=n.evaluationContext.identity)||void 0===u?void 0:u.traits)||{}).map((function(t){s(C,"flagsmith_trait_"+t,n.getTrait(t))})),n.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),n.log("Sending date traits to dynatrace",C.date),n.log("Sending shortString traits to dynatrace",C.shortString),n.log("Sending javaDouble to dynatrace",C.javaDouble),n.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return a.identity?Promise.all([a.identity.traits&&Object.keys(a.identity.traits).length||!a.identity.identifier?n.getJSON(i+"identities/","POST",JSON.stringify({identifier:a.identity.identifier,transient:a.identity.transient,traits:Object.entries(a.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(n.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):n.getJSON(i+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(t){return n.evaluationContext.identity=e(e({},n.evaluationContext.identity),{traits:{}}),l(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):n.getJSON(i+"flags/").then((function(t){return l({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=n.api;if(n.evaluationEvent&&n.evaluationContext.environment&&n.evaluationEvent[n.evaluationContext.environment.apiKey])return n.evaluationEvent&&0!==Object.getOwnPropertyNames(n.evaluationEvent).length&&0!==Object.getOwnPropertyNames(n.evaluationEvent[n.evaluationContext.environment.apiKey]).length?n.getJSON(t+"analytics/flags/","POST",JSON.stringify(n.evaluationEvent[n.evaluationContext.environment.apiKey])).then((function(t){if(n.evaluationContext.environment){var i=n.getState();n.evaluationEvent||(n.evaluationEvent={}),n.evaluationEvent[n.evaluationContext.environment.apiKey]={},n.setState(e(e({},i),{evaluationEvent:n.evaluationEvent})),n.updateEventStorage()}})).catch((function(t){n.log("Exception fetching evaluationEvent",t)})):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:h.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.getValue=function(t,e,i){var a=n.flags&&n.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(a&&(o=a.value),(null==e?void 0:e.skipAnalytics)||i||n.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(n.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,i;return(null===(e=n.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(i=n.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===i?void 0:i.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=n.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var i,a,o=c(t);return n.evaluationContext=e(e({},o),{environment:o.environment||n.evaluationContext.environment}),n.identity=null===(a=null===(i=n.getContext())||void 0===i?void 0:i.identity)||void 0===a?void 0:a.identifier,n.initialised?n.getFlags():Promise.resolve()},this.getContext=function(){return n.evaluationContext},this.updateContext=function(t){return n.setContext(e(e({},n.getContext()),t))},this.setTrait=function(t,i){var a;if(n.api)return n.setContext(e(e({},n.evaluationContext),{identity:e(e({},n.evaluationContext.identity),{traits:e(e({},null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.traits),u(Object.fromEntries([[t,i]])))})}))},this.setTraits=function(t){var i;if(n.api)return n.setContext(e(e({},n.evaluationContext),{identity:e(e({},n.evaluationContext.identity),{traits:e(e({},null===(i=n.evaluationContext.identity)||void 0===i?void 0:i.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,l(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var i,a,o="object"==typeof e,r=n.flags&&n.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!r&&o&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!0),(o&&!e.skipAnalytics||!e)&&n.evaluateFlag(t,"ENABLED"),n.sentryClient)try{null===(a=null===(i=n.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===i?void 0:i.addFeatureFlag)||void 0===a||a.call(i,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=n.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=n.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,i){var a,o,r,s=n.headers,l={method:e||"GET",body:i,cache:"no-cache",headers:{}};n.evaluationContext.environment&&(l.headers["X-Environment-Key"]=n.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(a=n.applicationMetadata)||void 0===a?void 0:a.name)&&(l.headers["Flagsmith-Application-Name"]=n.applicationMetadata.name),(null===(o=n.applicationMetadata)||void 0===o?void 0:o.version)&&(l.headers["Flagsmith-Application-Version"]=n.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("12.0.1"),s&&Object.assign(l.headers,s),d||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=n.evaluationContext.identity)||void 0===r?void 0:r.identifier);return d(t,l).then((function(i){var a,o,r="".concat(null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.identifier);if(u===r){var s=null===(o=i.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");n.timestamp=l}catch(t){n.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return n.log("Fetch response: "+i.status+" "+(e||"GET")+0+t),i.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&i.status&&(e="API Response: ".concat(i.status)),i.status&&i.status>=200&&i.status<300?e:Promise.reject(new Error(e))}))}n.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(n.datadogRum&&(n.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?n.datadogRum.client.addFeatureFlagEvaluation("flagsmith_value_"+t,n.getValue(t,{},!0)):n.datadogRum.client.addFeatureFlagEvaluation("flagsmith_enabled_"+t,n.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),n.enableAnalytics){if(!n.evaluationEvent||!n.evaluationContext.environment)return;n.evaluationEvent[n.evaluationContext.environment.apiKey]||(n.evaluationEvent[n.evaluationContext.environment.apiKey]={}),void 0===n.evaluationEvent[n.evaluationContext.environment.apiKey][t]&&(n.evaluationEvent[n.evaluationContext.environment.apiKey][t]=0),n.evaluationEvent[n.evaluationContext.environment.apiKey][t]+=1}n.updateEventStorage()},this._onChange=function(t,e,i){var a,o;n.setLoadingState(i),null===(a=n.onChange)||void 0===a||a.call(n,t,e,n.loadingState),null===(o=n._trigger)||void 0===o||o.call(n)},d=t.fetch?t.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!t.browserlessStorage,this.applicationMetadata=t.applicationMetadata,this.log("Constructing flagsmith instance "+t),t.eventSource&&(v=t.eventSource),t.AsyncStorage&&(g=t.AsyncStorage)}return t.prototype.init=function(t){var a,o,s,l;return n(this,void 0,void 0,(function(){var u,v,y,m,S,C,_,b,E,x,O,F,w,L,I,j,A,k,T,N,P,R,K,D,U,G,J,M,V,H,q,B,W,X,Y,$=this;return i(this,(function(z){switch(z.label){case 0:u=c(t.evaluationContext||this.evaluationContext),z.label=1;case 1:if(z.trys.push([1,13,,14]),v=t.AsyncStorage,y=t._trigger,m=t._triggerLoadingState,S=t.angularHttpClient,C=t.api,_=void 0===C?p:C,b=t.applicationMetadata,E=t.cacheFlags,x=t.cacheOptions,O=t.datadogRum,F=t.defaultFlags,w=t.enableAnalytics,L=t.enableDynatrace,I=t.enableLogs,j=t.environmentID,A=t.eventSourceUrl,k=void 0===A?"https://realtime.flagsmith.com/":A,T=t.fetch,N=t.headers,P=t.identity,R=t.onChange,K=t.onError,D=t.preventFetch,U=t.realtime,G=t.sentryClient,J=t.state,M=t.traits,u.environment=j?{apiKey:j}:u.environment,!u.environment||!u.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(u.identity=P||M?{identifier:P,traits:M?Object.fromEntries(Object.entries(M).map((function(t){return[t[0],{value:t[1]}]}))):{}}:u.identity,this.evaluationContext=u,this.api=(Q=_).endsWith("/")?Q:Q+"/",this.headers=N,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=y||this._trigger,this._triggerLoadingState=m||this._triggerLoadingState,this.onError=function(t){$.setLoadingState(e(e({},$.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==K||K(t)},this.enableLogs=I||!1,this.cacheOptions=x?{skipAPI:!!x.skipAPI,ttl:x.ttl||0,storageKey:x.storageKey,loadStale:!!x.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),T&&(d=T),this.enableAnalytics=w||!1,this.flags=Object.assign({},F)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==g&&!!E,this.applicationMetadata=b,f="FLAGSMITH_EVENT_"+u.environment.apiKey,v&&(g=v),U&&"undefined"!=typeof window&&this.setupRealtime(k,u.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:h.DEFAULT_FLAGS})),this.setState(J),this.log("Initialising with properties",t,this),L&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),G&&(this.sentryClient=G),S&&(d=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(S)),g&&this.canUseStorage&&g.getItem(f).then((function(t){try{$.evaluationEvent=JSON.parse(t)||{}}catch(t){$.evaluationEvent={}}$.analyticsInterval=setInterval($.analyticsFlags,$.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),g&&this.canUseStorage&&g.getItem(f,(function(t,n){if(n&&$.evaluationContext.environment){var i=JSON.parse(n);if(i[$.evaluationContext.environment.apiKey]){var a=$.getState();$.log("Retrieved events from cache",n),$.setState(e(e({},a),{evaluationEvent:i[$.evaluationContext.environment.apiKey]}))}}}))),!E)return[3,9];if(!g||!this.canUseStorage)return[3,8];H=function(t,a){return n($,void 0,void 0,(function(){var t,n,o,s,l,u,d,v,g,f,p,y,m,S,C,_,b,E,x,O=this;return i(this,(function(i){switch(i.label){case 0:if(!a)return[3,7];t=null,n=null,i.label=1;case 1:return i.trys.push([1,5,,6]),o=JSON.parse(a),s=!1,l=!1,o&&o.api===this.api&&(null===(f=null===(g=o.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(u=!0,this.evaluationContext.identity&&(null===(m=null===(y=o.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=o.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),u=!1),this.cacheOptions.ttl&&(!o.ts||(new Date).valueOf()-o.ts>this.cacheOptions.ttl)&&(o.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),u=!1):o.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),l=!0,u=!0)),u&&(s=!0,t=r(this.flags,o.flags),this.setState(e(e({},o),{evaluationContext:c(e(e({},o.evaluationContext),{identity:(null===(_=o.evaluationContext)||void 0===_?void 0:_.identity)?e(e({},null===(b=o.evaluationContext)||void 0===b?void 0:b.identity),{traits:e({},M||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),s?(d=!D&&(!this.cacheOptions.skipAPI||l),this._onChange(null,{isFromServer:!1,flagsChanged:t,traitsChanged:n},this._loadedState(null,h.CACHE,d)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!l&&this.log("Skipping API, using cache"),d&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:i.sent(),i.label=4;case 4:return[3,6];case 5:throw v=i.sent(),this.log("Exception fetching cached logs",v),v;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(F)this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(E=this.evaluationContext.identity)||void 0===E?void 0:E.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,h.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},z.label=2;case 2:return z.trys.push([2,7,,8]),g.getItemSync?(q=g.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,g.getItem(this.getStorageKey())];case 4:q=z.sent(),z.label=5;case 5:return[4,H(null,q)];case 6:return z.sent(),[3,8];case 7:if(B=z.sent(),!this.flags||0===Object.keys(this.flags).length)throw B;return Y=B instanceof Error?B:new Error("".concat(B)),null===(a=this.onError)||void 0===a||a.call(this,Y),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return z.sent(),[3,12];case 11:if(F)this._onChange(null,{isFromServer:!1,flagsChanged:r({},F),traitsChanged:r({},null===(o=u.identity)||void 0===o?void 0:o.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else if(this.flags&&(W=null,0===Object.keys(this.flags).length&&(W=V),this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(s=u.identity)||void 0===s?void 0:s.traits)},this._loadedState(W,h.DEFAULT_FLAGS)),W))throw new Error(W);z.label=12;case 12:return[3,14];case 13:throw X=z.sent(),this.log("Error during initialisation ",X),Y=X instanceof Error?X:new Error("".concat(X)),null===(l=this.onError)||void 0===l||l.call(this,Y),X;case 14:return[2]}var Q}))}))},t.prototype.getAllFlags=function(){return this.flags},t.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,l(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},t.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},t.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||p,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this),this.loadingState.source===h.NONE&&this.flags&&Object.keys(this.flags).length>0&&this.setLoadingState(this._loadedState(null,h.SERVER)))},t.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},t.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},t.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},t.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,a(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},t.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),g.setItem(this.getStorageKey(),t)}},t.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);g.setItem(f,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},t.prototype.setLoadingState=function(t){var n;o(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(n=this._triggerLoadingState)||void 0===n||n.call(this))},t.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";v?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new v(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},t}();function m(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new y({fetch:e,AsyncStorage:n,eventSource:i})}var S,C=(S=function(t,e){return S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},S(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}S(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),_=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},b=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},E=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},x=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return C(e,t),e}(Error),O=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new x;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=_(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=_(E([],b(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=E(E([],b(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var F=function(t,e){return e=e||{},new Promise((function(n,i){var a=new XMLHttpRequest,o=[],r=[],s={},l=function(){return{ok:2==(a.status/100|0),statusText:a.statusText,status:a.status,url:a.responseURL,text:function(){return Promise.resolve(a.responseText)},json:function(){return Promise.resolve(a.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([a.response]))},clone:l,headers:{keys:function(){return o},entries:function(){return r},get:function(t){return s[t.toLowerCase()]},has:function(t){return t.toLowerCase()in s}}}};for(var u in a.open(e.method||"get",t,!0),a.onload=function(){a.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,(function(t,e,n){o.push(e=e.toLowerCase()),r.push([e,n]),s[e]=s[e]?s[e]+","+n:n})),n(l())},a.onerror=i,a.withCredentials="include"==e.credentials,e.headers)a.setRequestHeader(u,e.headers[u]);a.send(e.body||null)}))},w=m({AsyncStorage:t,fetch:F,eventSource:O});"undefined"!=typeof window&&(window.flagsmith=w);var L=function(){return m({AsyncStorage:t,fetch:F,eventSource:O})};export{h as FlagSource,L as createFlagsmithInstance,w as default};
2
2
  //# sourceMappingURL=index.mjs.map
package/isomorphic.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).isomorphic={})}(this,(function(t){"use strict";var e={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},n=function(){return n=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},n.apply(this,arguments)};function i(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((i=i.apply(t,e||[])).next())}))}function a(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function o(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var r=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function s(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!r(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function l(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function u(t){return!!t&&"object"==typeof t&&void 0!==t.value}function c(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))}function d(t){return n(n({},t),{identity:t.identity?n(n({},t.identity),{traits:c(t.identity.traits||{})}):void 0})}var h,v;t.FlagSource=void 0,(h=t.FlagSource||(t.FlagSource={})).NONE="NONE",h.DEFAULT_FLAGS="DEFAULT_FLAGS",h.CACHE="CACHE",h.SERVER="SERVER";var g,f=null,p="FLAGSMITH_EVENT",y=p,m="https://edge.api.flagsmith.com/api/v1/",S="flagsmith_value_",C="flagsmith_enabled_",_="flagsmith_trait_",E=function(){function e(e){var i=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var e=i,a=e.api,o=e.evaluationContext;i.log("Get Flags"),i.isLoading=!0,i.loadingState.isFetching||i.setLoadingState(n(n({},i.loadingState),{isFetching:!0}));var r="".concat(i.getContext().identity),u=function(e){var a,o,u,c;if(e&&r==="".concat(i.getContext().identity)){var d=e.flags,h=e.traits,v=e.identifier;i.isLoading=!1;var g={},f={};h=h||[],(d=d||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),h.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),i.oldFlags=n({},i.flags);var p=s(i.oldFlags,g),y=s(null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.traits,f);if((v||Object.keys(f).length)&&(i.evaluationContext.identity=n(n({},i.evaluationContext.identity),{traits:f}),v&&(i.evaluationContext.identity.identifier=v,i.identity=v)),i.flags=g,i.updateStorage(),i._onChange(i.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},i._loadedState(null,t.FlagSource.SERVER)),i.datadogRum)try{if(i.datadogRum.trackTraits){var m={};Object.keys((null===(o=i.evaluationContext.identity)||void 0===o?void 0:o.traits)||{}).map((function(t){m[_+t]=i.getTrait(t)}));var E=n(n(n({},i.datadogRum.client.getUser()),{id:i.datadogRum.client.getUser().id||(null===(u=i.evaluationContext.identity)||void 0===u?void 0:u.identifier)}),m);i.log("Setting Datadog user",E),i.datadogRum.client.setUser(E)}}catch(t){console.error(t)}if(i.dtrum)try{var b={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(i.flags).map((function(t){l(b,S+t,i.getValue(t,{skipAnalytics:!0})),l(b,C+t,i.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=i.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){l(b,_+t,i.getTrait(t))})),i.log("Sending javaLongOrObject traits to dynatrace",b.javaLongOrObject),i.log("Sending date traits to dynatrace",b.date),i.log("Sending shortString traits to dynatrace",b.shortString),i.log("Sending javaDouble to dynatrace",b.javaDouble),i.dtrum.sendSessionProperties(b.javaLongOrObject,b.date,b.shortString,b.javaDouble)}catch(t){console.error(t)}}};return o.identity?Promise.all([o.identity.traits&&Object.keys(o.identity.traits).length||!o.identity.identifier?i.getJSON(a+"identities/","POST",JSON.stringify({identifier:o.identity.identifier,transient:o.identity.transient,traits:Object.entries(o.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(i.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):i.getJSON(a+"identities/?identifier="+encodeURIComponent(o.identity.identifier)+(o.identity.transient?"&transient=true":""))]).then((function(t){return i.evaluationContext.identity=n(n({},i.evaluationContext.identity),{traits:{}}),u(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):i.getJSON(a+"flags/").then((function(t){return u({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=i.api;if(i.evaluationEvent&&i.evaluationContext.environment&&i.evaluationEvent[i.evaluationContext.environment.apiKey])return i.evaluationEvent&&0!==Object.getOwnPropertyNames(i.evaluationEvent).length&&0!==Object.getOwnPropertyNames(i.evaluationEvent[i.evaluationContext.environment.apiKey]).length?i.getJSON(t+"analytics/flags/","POST",JSON.stringify(i.evaluationEvent[i.evaluationContext.environment.apiKey])).then((function(t){if(i.evaluationContext.environment){var e=i.getState();i.evaluationEvent||(i.evaluationEvent={}),i.evaluationEvent[i.evaluationContext.environment.apiKey]={},i.setState(n(n({},e),{evaluationEvent:i.evaluationEvent})),i.updateEventStorage()}})).catch((function(t){i.log("Exception fetching evaluationEvent",t)})):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:t.FlagSource.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.getValue=function(t,e,n){var a=i.flags&&i.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(a&&(o=a.value),(null==e?void 0:e.skipAnalytics)||n||i.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(i.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,n;return(null===(e=i.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=i.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=i.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var e,a,o=d(t);return i.evaluationContext=n(n({},o),{environment:o.environment||i.evaluationContext.environment}),i.identity=null===(a=null===(e=i.getContext())||void 0===e?void 0:e.identity)||void 0===a?void 0:a.identifier,i.initialised?i.getFlags():Promise.resolve()},this.getContext=function(){return i.evaluationContext},this.updateContext=function(t){return i.setContext(n(n({},i.getContext()),t))},this.setTrait=function(t,e){var a;if(i.api)return i.setContext(n(n({},i.evaluationContext),{identity:n(n({},i.evaluationContext.identity),{traits:n(n({},null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.traits),c(Object.fromEntries([[t,e]])))})}))},this.setTraits=function(t){var e;if(i.api)return i.setContext(n(n({},i.evaluationContext),{identity:n(n({},i.evaluationContext.identity),{traits:n(n({},null===(e=i.evaluationContext.identity)||void 0===e?void 0:e.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,a,o="object"==typeof e,r=i.flags&&i.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!r&&o&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!0),(o&&!e.skipAnalytics||!e)&&i.evaluateFlag(t,"ENABLED"),i.sentryClient)try{null===(a=null===(n=i.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===a||a.call(n,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=i.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=i.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var a,o,r,s=i.headers,l={method:e||"GET",body:n,cache:"no-cache",headers:{}};i.evaluationContext.environment&&(l.headers["X-Environment-Key"]=i.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(a=i.applicationMetadata)||void 0===a?void 0:a.name)&&(l.headers["Flagsmith-Application-Name"]=i.applicationMetadata.name),(null===(o=i.applicationMetadata)||void 0===o?void 0:o.version)&&(l.headers["Flagsmith-Application-Version"]=i.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("12.0.0"),s&&Object.assign(l.headers,s),v||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=i.evaluationContext.identity)||void 0===r?void 0:r.identifier);return v(t,l).then((function(n){var a,o,r="".concat(null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.identifier);if(u===r){var s=null===(o=n.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");i.timestamp=l}catch(t){i.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return i.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}i.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(i.datadogRum&&(i.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?i.datadogRum.client.addFeatureFlagEvaluation(S+t,i.getValue(t,{},!0)):i.datadogRum.client.addFeatureFlagEvaluation(C+t,i.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),i.enableAnalytics){if(!i.evaluationEvent||!i.evaluationContext.environment)return;i.evaluationEvent[i.evaluationContext.environment.apiKey]||(i.evaluationEvent[i.evaluationContext.environment.apiKey]={}),void 0===i.evaluationEvent[i.evaluationContext.environment.apiKey][t]&&(i.evaluationEvent[i.evaluationContext.environment.apiKey][t]=0),i.evaluationEvent[i.evaluationContext.environment.apiKey][t]+=1}i.updateEventStorage()},this._onChange=function(t,e,n){var a,o;i.setLoadingState(n),null===(a=i.onChange)||void 0===a||a.call(i,t,e,i.loadingState),null===(o=i._trigger)||void 0===o||o.call(i)},v=e.fetch?e.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!e.browserlessStorage,this.applicationMetadata=e.applicationMetadata,this.log("Constructing flagsmith instance "+e),e.eventSource&&(g=e.eventSource),e.AsyncStorage&&(f=e.AsyncStorage)}return e.prototype.init=function(e){var o,r,l,u;return i(this,void 0,void 0,(function(){var c,h,g,p,S,C,_,E,b,x,F,O,w,I,j,A,L,k,T,N,P,R,K,D,U,G,J,M,V,H,B,W,q,Y,X,z=this;return a(this,(function(Q){switch(Q.label){case 0:c=d(e.evaluationContext||this.evaluationContext),Q.label=1;case 1:if(Q.trys.push([1,13,,14]),h=e.AsyncStorage,g=e._trigger,p=e._triggerLoadingState,S=e.angularHttpClient,C=e.api,_=void 0===C?m:C,E=e.applicationMetadata,b=e.cacheFlags,x=e.cacheOptions,F=e.datadogRum,O=e.defaultFlags,w=e.enableAnalytics,I=e.enableDynatrace,j=e.enableLogs,A=e.environmentID,L=e.eventSourceUrl,k=void 0===L?"https://realtime.flagsmith.com/":L,T=e.fetch,N=e.headers,P=e.identity,R=e.onChange,K=e.onError,D=e.preventFetch,U=e.realtime,G=e.sentryClient,J=e.state,M=e.traits,c.environment=A?{apiKey:A}:c.environment,!c.environment||!c.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(c.identity=P||M?{identifier:P,traits:M?Object.fromEntries(Object.entries(M).map((function(t){return[t[0],{value:t[1]}]}))):{}}:c.identity,this.evaluationContext=c,this.api=(Z=_).endsWith("/")?Z:Z+"/",this.headers=N,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=g||this._trigger,this._triggerLoadingState=p||this._triggerLoadingState,this.onError=function(t){z.setLoadingState(n(n({},z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==K||K(t)},this.enableLogs=j||!1,this.cacheOptions=x?{skipAPI:!!x.skipAPI,ttl:x.ttl||0,storageKey:x.storageKey,loadStale:!!x.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),T&&(v=T),this.enableAnalytics=w||!1,this.flags=Object.assign({},O)||{},this.datadogRum=F||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==f&&!!b,this.applicationMetadata=E,y="FLAGSMITH_EVENT_"+c.environment.apiKey,h&&(f=h),U&&"undefined"!=typeof window&&this.setupRealtime(k,c.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=n(n({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(J),this.log("Initialising with properties",e,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),G&&(this.sentryClient=G),S&&(v=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(S)),f&&this.canUseStorage&&f.getItem(y).then((function(t){try{z.evaluationEvent=JSON.parse(t)||{}}catch(t){z.evaluationEvent={}}z.analyticsInterval=setInterval(z.analyticsFlags,z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),f&&this.canUseStorage&&f.getItem(y,(function(t,e){if(e&&z.evaluationContext.environment){var i=JSON.parse(e);if(i[z.evaluationContext.environment.apiKey]){var a=z.getState();z.log("Retrieved events from cache",e),z.setState(n(n({},a),{evaluationEvent:i[z.evaluationContext.environment.apiKey]}))}}}))),!b)return[3,9];if(!f||!this.canUseStorage)return[3,8];H=function(e,o){return i(z,void 0,void 0,(function(){var e,i,r,l,u,c,h,v,g,f,p,y,m,S,C,_,E,b,x,F=this;return a(this,(function(a){switch(a.label){case 0:if(!o)return[3,7];e=null,i=null,a.label=1;case 1:return a.trys.push([1,5,,6]),r=JSON.parse(o),l=!1,u=!1,r&&r.api===this.api&&(null===(f=null===(g=r.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(c=!0,this.evaluationContext.identity&&(null===(m=null===(y=r.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=r.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),c=!1),this.cacheOptions.ttl&&(!r.ts||(new Date).valueOf()-r.ts>this.cacheOptions.ttl)&&(r.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),c=!1):r.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),u=!0,c=!0)),c&&(l=!0,e=s(this.flags,r.flags),this.setState(n(n({},r),{evaluationContext:d(n(n({},r.evaluationContext),{identity:(null===(_=r.evaluationContext)||void 0===_?void 0:_.identity)?n(n({},null===(E=r.evaluationContext)||void 0===E?void 0:E.identity),{traits:n({},M||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),l?(h=!D&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,t.FlagSource.CACHE,h)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&l&&!u&&this.log("Skipping API, using cache"),h&&this.getFlags().catch((function(t){var e;null===(e=F.onError)||void 0===e||e.call(F,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:a.sent(),a.label=4;case 4:return[3,6];case 5:throw v=a.sent(),this.log("Exception fetching cached logs",v),v;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return a.sent(),[3,10];case 9:if(O)this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(b=this.evaluationContext.identity)||void 0===b?void 0:b.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS))}a.label=10;case 10:return[2]}}))}))},Q.label=2;case 2:return Q.trys.push([2,7,,8]),f.getItemSync?(B=f.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,f.getItem(this.getStorageKey())];case 4:B=Q.sent(),Q.label=5;case 5:return[4,H(null,B)];case 6:return Q.sent(),[3,8];case 7:if(W=Q.sent(),!this.flags||0===Object.keys(this.flags).length)throw W;return X=W instanceof Error?W:new Error("".concat(W)),null===(o=this.onError)||void 0===o||o.call(this,X),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return Q.sent(),[3,12];case 11:if(O)this._onChange(null,{isFromServer:!1,flagsChanged:s({},O),traitsChanged:s({},null===(r=c.identity)||void 0===r?void 0:r.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else if(this.flags&&(q=null,0===Object.keys(this.flags).length&&(q=V),this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(l=c.identity)||void 0===l?void 0:l.traits)},this._loadedState(q,t.FlagSource.DEFAULT_FLAGS)),q))throw new Error(q);Q.label=12;case 12:return[3,14];case 13:throw Y=Q.sent(),this.log("Error during initialisation ",Y),X=Y instanceof Error?Y:new Error("".concat(Y)),null===(u=this.onError)||void 0===u||u.call(this,X),Y;case 14:return[2]}var Z}))}))},e.prototype.getAllFlags=function(){return this.flags},e.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},e.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},e.prototype.setState=function(e){var n,i;e&&(this.initialised=!0,this.api=e.api||this.api||m,this.flags=e.flags||this.flags,this.evaluationContext=e.evaluationContext||this.evaluationContext,this.evaluationEvent=e.evaluationEvent||this.evaluationEvent,this.identity=null===(i=null===(n=this.getContext())||void 0===n?void 0:n.identity)||void 0===i?void 0:i.identifier,this.log("setState called",this),this.loadingState.source===t.FlagSource.NONE&&this.flags&&Object.keys(this.flags).length>0&&this.setLoadingState(this._loadedState(null,t.FlagSource.SERVER)))},e.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},e.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},e.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},e.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},e.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,o(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},e.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),f.setItem(this.getStorageKey(),t)}},e.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);f.setItem(y,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},e.prototype.setLoadingState=function(t){var e;r(t,this.loadingState)||(this.loadingState=n({},t),this.log("Loading state changed",t),null===(e=this._triggerLoadingState)||void 0===e||e.call(this))},e.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";g?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new g(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},e}();function b(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new E({fetch:e,AsyncStorage:n,eventSource:i})}var x,F=(x=function(t,e){return x=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},x(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}x(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),O=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},w=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},I=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},j=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return F(e,t),e}(Error),A=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new j;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=O(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=O(I([],w(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=I(I([],w(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var L=b({AsyncStorage:e,eventSource:"undefined"!=typeof window?A:null});"undefined"!=typeof window&&(window.flagsmith=L);t.createFlagsmithInstance=function(){return b({AsyncStorage:e,eventSource:"undefined"!=typeof window?A:null})},t.default=L,Object.defineProperty(t,"__esModule",{value:!0})}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).isomorphic={})}(this,(function(t){"use strict";var e={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},n=function(){return n=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},n.apply(this,arguments)};function i(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((i=i.apply(t,e||[])).next())}))}function a(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function o(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var r=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function s(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!r(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function l(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function u(t){return!!t&&"object"==typeof t&&void 0!==t.value}function c(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))}function d(t){return n(n({},t),{identity:t.identity?n(n({},t.identity),{traits:c(t.identity.traits||{})}):void 0})}var h,v;t.FlagSource=void 0,(h=t.FlagSource||(t.FlagSource={})).NONE="NONE",h.DEFAULT_FLAGS="DEFAULT_FLAGS",h.CACHE="CACHE",h.SERVER="SERVER";var g,f=null,p="FLAGSMITH_EVENT",y=p,m="https://edge.api.flagsmith.com/api/v1/",S="flagsmith_value_",C="flagsmith_enabled_",_="flagsmith_trait_",E=function(){function e(e){var i=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var e=i,a=e.api,o=e.evaluationContext;i.log("Get Flags"),i.isLoading=!0,i.loadingState.isFetching||i.setLoadingState(n(n({},i.loadingState),{isFetching:!0}));var r="".concat(i.getContext().identity),u=function(e){var a,o,u,c;if(e&&r==="".concat(i.getContext().identity)){var d=e.flags,h=e.traits,v=e.identifier;i.isLoading=!1;var g={},f={};h=h||[],(d=d||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),h.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),i.oldFlags=n({},i.flags);var p=s(i.oldFlags,g),y=s(null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.traits,f);if((v||Object.keys(f).length)&&(i.evaluationContext.identity=n(n({},i.evaluationContext.identity),{traits:f}),v&&(i.evaluationContext.identity.identifier=v,i.identity=v)),i.flags=g,i.updateStorage(),i._onChange(i.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},i._loadedState(null,t.FlagSource.SERVER)),i.datadogRum)try{if(i.datadogRum.trackTraits){var m={};Object.keys((null===(o=i.evaluationContext.identity)||void 0===o?void 0:o.traits)||{}).map((function(t){m[_+t]=i.getTrait(t)}));var E=n(n(n({},i.datadogRum.client.getUser()),{id:i.datadogRum.client.getUser().id||(null===(u=i.evaluationContext.identity)||void 0===u?void 0:u.identifier)}),m);i.log("Setting Datadog user",E),i.datadogRum.client.setUser(E)}}catch(t){console.error(t)}if(i.dtrum)try{var b={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(i.flags).map((function(t){l(b,S+t,i.getValue(t,{skipAnalytics:!0})),l(b,C+t,i.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=i.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){l(b,_+t,i.getTrait(t))})),i.log("Sending javaLongOrObject traits to dynatrace",b.javaLongOrObject),i.log("Sending date traits to dynatrace",b.date),i.log("Sending shortString traits to dynatrace",b.shortString),i.log("Sending javaDouble to dynatrace",b.javaDouble),i.dtrum.sendSessionProperties(b.javaLongOrObject,b.date,b.shortString,b.javaDouble)}catch(t){console.error(t)}}};return o.identity?Promise.all([o.identity.traits&&Object.keys(o.identity.traits).length||!o.identity.identifier?i.getJSON(a+"identities/","POST",JSON.stringify({identifier:o.identity.identifier,transient:o.identity.transient,traits:Object.entries(o.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(i.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):i.getJSON(a+"identities/?identifier="+encodeURIComponent(o.identity.identifier)+(o.identity.transient?"&transient=true":""))]).then((function(t){return i.evaluationContext.identity=n(n({},i.evaluationContext.identity),{traits:{}}),u(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):i.getJSON(a+"flags/").then((function(t){return u({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=i.api;if(i.evaluationEvent&&i.evaluationContext.environment&&i.evaluationEvent[i.evaluationContext.environment.apiKey])return i.evaluationEvent&&0!==Object.getOwnPropertyNames(i.evaluationEvent).length&&0!==Object.getOwnPropertyNames(i.evaluationEvent[i.evaluationContext.environment.apiKey]).length?i.getJSON(t+"analytics/flags/","POST",JSON.stringify(i.evaluationEvent[i.evaluationContext.environment.apiKey])).then((function(t){if(i.evaluationContext.environment){var e=i.getState();i.evaluationEvent||(i.evaluationEvent={}),i.evaluationEvent[i.evaluationContext.environment.apiKey]={},i.setState(n(n({},e),{evaluationEvent:i.evaluationEvent})),i.updateEventStorage()}})).catch((function(t){i.log("Exception fetching evaluationEvent",t)})):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:t.FlagSource.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.getValue=function(t,e,n){var a=i.flags&&i.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(a&&(o=a.value),(null==e?void 0:e.skipAnalytics)||n||i.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(i.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,n;return(null===(e=i.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=i.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=i.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var e,a,o=d(t);return i.evaluationContext=n(n({},o),{environment:o.environment||i.evaluationContext.environment}),i.identity=null===(a=null===(e=i.getContext())||void 0===e?void 0:e.identity)||void 0===a?void 0:a.identifier,i.initialised?i.getFlags():Promise.resolve()},this.getContext=function(){return i.evaluationContext},this.updateContext=function(t){return i.setContext(n(n({},i.getContext()),t))},this.setTrait=function(t,e){var a;if(i.api)return i.setContext(n(n({},i.evaluationContext),{identity:n(n({},i.evaluationContext.identity),{traits:n(n({},null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.traits),c(Object.fromEntries([[t,e]])))})}))},this.setTraits=function(t){var e;if(i.api)return i.setContext(n(n({},i.evaluationContext),{identity:n(n({},i.evaluationContext.identity),{traits:n(n({},null===(e=i.evaluationContext.identity)||void 0===e?void 0:e.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,a,o="object"==typeof e,r=i.flags&&i.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!r&&o&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!0),(o&&!e.skipAnalytics||!e)&&i.evaluateFlag(t,"ENABLED"),i.sentryClient)try{null===(a=null===(n=i.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===a||a.call(n,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=i.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=i.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var a,o,r,s=i.headers,l={method:e||"GET",body:n,cache:"no-cache",headers:{}};i.evaluationContext.environment&&(l.headers["X-Environment-Key"]=i.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(a=i.applicationMetadata)||void 0===a?void 0:a.name)&&(l.headers["Flagsmith-Application-Name"]=i.applicationMetadata.name),(null===(o=i.applicationMetadata)||void 0===o?void 0:o.version)&&(l.headers["Flagsmith-Application-Version"]=i.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("12.0.1"),s&&Object.assign(l.headers,s),v||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=i.evaluationContext.identity)||void 0===r?void 0:r.identifier);return v(t,l).then((function(n){var a,o,r="".concat(null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.identifier);if(u===r){var s=null===(o=n.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");i.timestamp=l}catch(t){i.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return i.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}i.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(i.datadogRum&&(i.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?i.datadogRum.client.addFeatureFlagEvaluation(S+t,i.getValue(t,{},!0)):i.datadogRum.client.addFeatureFlagEvaluation(C+t,i.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),i.enableAnalytics){if(!i.evaluationEvent||!i.evaluationContext.environment)return;i.evaluationEvent[i.evaluationContext.environment.apiKey]||(i.evaluationEvent[i.evaluationContext.environment.apiKey]={}),void 0===i.evaluationEvent[i.evaluationContext.environment.apiKey][t]&&(i.evaluationEvent[i.evaluationContext.environment.apiKey][t]=0),i.evaluationEvent[i.evaluationContext.environment.apiKey][t]+=1}i.updateEventStorage()},this._onChange=function(t,e,n){var a,o;i.setLoadingState(n),null===(a=i.onChange)||void 0===a||a.call(i,t,e,i.loadingState),null===(o=i._trigger)||void 0===o||o.call(i)},v=e.fetch?e.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!e.browserlessStorage,this.applicationMetadata=e.applicationMetadata,this.log("Constructing flagsmith instance "+e),e.eventSource&&(g=e.eventSource),e.AsyncStorage&&(f=e.AsyncStorage)}return e.prototype.init=function(e){var o,r,l,u;return i(this,void 0,void 0,(function(){var c,h,g,p,S,C,_,E,b,x,F,O,w,I,j,A,L,k,T,N,P,R,K,D,U,G,J,M,V,H,B,W,q,Y,X,z=this;return a(this,(function(Q){switch(Q.label){case 0:c=d(e.evaluationContext||this.evaluationContext),Q.label=1;case 1:if(Q.trys.push([1,13,,14]),h=e.AsyncStorage,g=e._trigger,p=e._triggerLoadingState,S=e.angularHttpClient,C=e.api,_=void 0===C?m:C,E=e.applicationMetadata,b=e.cacheFlags,x=e.cacheOptions,F=e.datadogRum,O=e.defaultFlags,w=e.enableAnalytics,I=e.enableDynatrace,j=e.enableLogs,A=e.environmentID,L=e.eventSourceUrl,k=void 0===L?"https://realtime.flagsmith.com/":L,T=e.fetch,N=e.headers,P=e.identity,R=e.onChange,K=e.onError,D=e.preventFetch,U=e.realtime,G=e.sentryClient,J=e.state,M=e.traits,c.environment=A?{apiKey:A}:c.environment,!c.environment||!c.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(c.identity=P||M?{identifier:P,traits:M?Object.fromEntries(Object.entries(M).map((function(t){return[t[0],{value:t[1]}]}))):{}}:c.identity,this.evaluationContext=c,this.api=(Z=_).endsWith("/")?Z:Z+"/",this.headers=N,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=g||this._trigger,this._triggerLoadingState=p||this._triggerLoadingState,this.onError=function(t){z.setLoadingState(n(n({},z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==K||K(t)},this.enableLogs=j||!1,this.cacheOptions=x?{skipAPI:!!x.skipAPI,ttl:x.ttl||0,storageKey:x.storageKey,loadStale:!!x.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),T&&(v=T),this.enableAnalytics=w||!1,this.flags=Object.assign({},O)||{},this.datadogRum=F||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==f&&!!b,this.applicationMetadata=E,y="FLAGSMITH_EVENT_"+c.environment.apiKey,h&&(f=h),U&&"undefined"!=typeof window&&this.setupRealtime(k,c.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=n(n({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(J),this.log("Initialising with properties",e,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),G&&(this.sentryClient=G),S&&(v=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(S)),f&&this.canUseStorage&&f.getItem(y).then((function(t){try{z.evaluationEvent=JSON.parse(t)||{}}catch(t){z.evaluationEvent={}}z.analyticsInterval=setInterval(z.analyticsFlags,z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),f&&this.canUseStorage&&f.getItem(y,(function(t,e){if(e&&z.evaluationContext.environment){var i=JSON.parse(e);if(i[z.evaluationContext.environment.apiKey]){var a=z.getState();z.log("Retrieved events from cache",e),z.setState(n(n({},a),{evaluationEvent:i[z.evaluationContext.environment.apiKey]}))}}}))),!b)return[3,9];if(!f||!this.canUseStorage)return[3,8];H=function(e,o){return i(z,void 0,void 0,(function(){var e,i,r,l,u,c,h,v,g,f,p,y,m,S,C,_,E,b,x,F=this;return a(this,(function(a){switch(a.label){case 0:if(!o)return[3,7];e=null,i=null,a.label=1;case 1:return a.trys.push([1,5,,6]),r=JSON.parse(o),l=!1,u=!1,r&&r.api===this.api&&(null===(f=null===(g=r.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(c=!0,this.evaluationContext.identity&&(null===(m=null===(y=r.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=r.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),c=!1),this.cacheOptions.ttl&&(!r.ts||(new Date).valueOf()-r.ts>this.cacheOptions.ttl)&&(r.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),c=!1):r.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),u=!0,c=!0)),c&&(l=!0,e=s(this.flags,r.flags),this.setState(n(n({},r),{evaluationContext:d(n(n({},r.evaluationContext),{identity:(null===(_=r.evaluationContext)||void 0===_?void 0:_.identity)?n(n({},null===(E=r.evaluationContext)||void 0===E?void 0:E.identity),{traits:n({},M||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),l?(h=!D&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,t.FlagSource.CACHE,h)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&l&&!u&&this.log("Skipping API, using cache"),h&&this.getFlags().catch((function(t){var e;null===(e=F.onError)||void 0===e||e.call(F,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:a.sent(),a.label=4;case 4:return[3,6];case 5:throw v=a.sent(),this.log("Exception fetching cached logs",v),v;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return a.sent(),[3,10];case 9:if(O)this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(b=this.evaluationContext.identity)||void 0===b?void 0:b.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS))}a.label=10;case 10:return[2]}}))}))},Q.label=2;case 2:return Q.trys.push([2,7,,8]),f.getItemSync?(B=f.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,f.getItem(this.getStorageKey())];case 4:B=Q.sent(),Q.label=5;case 5:return[4,H(null,B)];case 6:return Q.sent(),[3,8];case 7:if(W=Q.sent(),!this.flags||0===Object.keys(this.flags).length)throw W;return X=W instanceof Error?W:new Error("".concat(W)),null===(o=this.onError)||void 0===o||o.call(this,X),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return Q.sent(),[3,12];case 11:if(O)this._onChange(null,{isFromServer:!1,flagsChanged:s({},O),traitsChanged:s({},null===(r=c.identity)||void 0===r?void 0:r.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else if(this.flags&&(q=null,0===Object.keys(this.flags).length&&(q=V),this._onChange(null,{isFromServer:!1,flagsChanged:s({},this.flags),traitsChanged:s({},null===(l=c.identity)||void 0===l?void 0:l.traits)},this._loadedState(q,t.FlagSource.DEFAULT_FLAGS)),q))throw new Error(q);Q.label=12;case 12:return[3,14];case 13:throw Y=Q.sent(),this.log("Error during initialisation ",Y),X=Y instanceof Error?Y:new Error("".concat(Y)),null===(u=this.onError)||void 0===u||u.call(this,X),Y;case 14:return[2]}var Z}))}))},e.prototype.getAllFlags=function(){return this.flags},e.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,u(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},e.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},e.prototype.setState=function(e){var n,i;e&&(this.initialised=!0,this.api=e.api||this.api||m,this.flags=e.flags||this.flags,this.evaluationContext=e.evaluationContext||this.evaluationContext,this.evaluationEvent=e.evaluationEvent||this.evaluationEvent,this.identity=null===(i=null===(n=this.getContext())||void 0===n?void 0:n.identity)||void 0===i?void 0:i.identifier,this.log("setState called",this),this.loadingState.source===t.FlagSource.NONE&&this.flags&&Object.keys(this.flags).length>0&&this.setLoadingState(this._loadedState(null,t.FlagSource.SERVER)))},e.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},e.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},e.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},e.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},e.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,o(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},e.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),f.setItem(this.getStorageKey(),t)}},e.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);f.setItem(y,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},e.prototype.setLoadingState=function(t){var e;r(t,this.loadingState)||(this.loadingState=n({},t),this.log("Loading state changed",t),null===(e=this._triggerLoadingState)||void 0===e||e.call(this))},e.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";g?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new g(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},e}();function b(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new E({fetch:e,AsyncStorage:n,eventSource:i})}var x,F=(x=function(t,e){return x=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},x(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}x(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),O=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},w=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},I=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},j=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return F(e,t),e}(Error),A=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new j;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=O(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=O(I([],w(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=I(I([],w(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var L=b({AsyncStorage:e,eventSource:"undefined"!=typeof window?A:null});"undefined"!=typeof window&&(window.flagsmith=L);t.createFlagsmithInstance=function(){return b({AsyncStorage:e,eventSource:"undefined"!=typeof window?A:null})},t.default=L,Object.defineProperty(t,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=isomorphic.js.map
package/isomorphic.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var t={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},e=function(){return e=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},e.apply(this,arguments)};function n(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((i=i.apply(t,e||[])).next())}))}function i(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function a(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var o=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function r(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!o(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function s(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function l(t){return!!t&&"object"==typeof t&&void 0!==t.value}function u(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,l(n)?n:{value:n}]})))}function c(t){return e(e({},t),{identity:t.identity?e(e({},t.identity),{traits:u(t.identity.traits||{})}):void 0})}var h,d;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(h||(h={}));var v,g=null,f="FLAGSMITH_EVENT",p="https://edge.api.flagsmith.com/api/v1/",y=function(){function t(t){var n=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var t=n,i=t.api,a=t.evaluationContext;n.log("Get Flags"),n.isLoading=!0,n.loadingState.isFetching||n.setLoadingState(e(e({},n.loadingState),{isFetching:!0}));var o="".concat(n.getContext().identity),l=function(t){var i,a,l,u;if(t&&o==="".concat(n.getContext().identity)){var c=t.flags,d=t.traits,v=t.identifier;n.isLoading=!1;var g={},f={};d=d||[],(c=c||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),d.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),n.oldFlags=e({},n.flags);var p=r(n.oldFlags,g),y=r(null===(i=n.evaluationContext.identity)||void 0===i?void 0:i.traits,f);if((v||Object.keys(f).length)&&(n.evaluationContext.identity=e(e({},n.evaluationContext.identity),{traits:f}),v&&(n.evaluationContext.identity.identifier=v,n.identity=v)),n.flags=g,n.updateStorage(),n._onChange(n.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},n._loadedState(null,h.SERVER)),n.datadogRum)try{if(n.datadogRum.trackTraits){var m={};Object.keys((null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.traits)||{}).map((function(t){m["flagsmith_trait_"+t]=n.getTrait(t)}));var S=e(e(e({},n.datadogRum.client.getUser()),{id:n.datadogRum.client.getUser().id||(null===(l=n.evaluationContext.identity)||void 0===l?void 0:l.identifier)}),m);n.log("Setting Datadog user",S),n.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(n.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(n.flags).map((function(t){s(C,"flagsmith_value_"+t,n.getValue(t,{skipAnalytics:!0})),s(C,"flagsmith_enabled_"+t,n.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(u=n.evaluationContext.identity)||void 0===u?void 0:u.traits)||{}).map((function(t){s(C,"flagsmith_trait_"+t,n.getTrait(t))})),n.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),n.log("Sending date traits to dynatrace",C.date),n.log("Sending shortString traits to dynatrace",C.shortString),n.log("Sending javaDouble to dynatrace",C.javaDouble),n.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return a.identity?Promise.all([a.identity.traits&&Object.keys(a.identity.traits).length||!a.identity.identifier?n.getJSON(i+"identities/","POST",JSON.stringify({identifier:a.identity.identifier,transient:a.identity.transient,traits:Object.entries(a.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(n.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):n.getJSON(i+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(t){return n.evaluationContext.identity=e(e({},n.evaluationContext.identity),{traits:{}}),l(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):n.getJSON(i+"flags/").then((function(t){return l({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=n.api;if(n.evaluationEvent&&n.evaluationContext.environment&&n.evaluationEvent[n.evaluationContext.environment.apiKey])return n.evaluationEvent&&0!==Object.getOwnPropertyNames(n.evaluationEvent).length&&0!==Object.getOwnPropertyNames(n.evaluationEvent[n.evaluationContext.environment.apiKey]).length?n.getJSON(t+"analytics/flags/","POST",JSON.stringify(n.evaluationEvent[n.evaluationContext.environment.apiKey])).then((function(t){if(n.evaluationContext.environment){var i=n.getState();n.evaluationEvent||(n.evaluationEvent={}),n.evaluationEvent[n.evaluationContext.environment.apiKey]={},n.setState(e(e({},i),{evaluationEvent:n.evaluationEvent})),n.updateEventStorage()}})).catch((function(t){n.log("Exception fetching evaluationEvent",t)})):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:h.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.getValue=function(t,e,i){var a=n.flags&&n.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(a&&(o=a.value),(null==e?void 0:e.skipAnalytics)||i||n.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(n.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,i;return(null===(e=n.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(i=n.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===i?void 0:i.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=n.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var i,a,o=c(t);return n.evaluationContext=e(e({},o),{environment:o.environment||n.evaluationContext.environment}),n.identity=null===(a=null===(i=n.getContext())||void 0===i?void 0:i.identity)||void 0===a?void 0:a.identifier,n.initialised?n.getFlags():Promise.resolve()},this.getContext=function(){return n.evaluationContext},this.updateContext=function(t){return n.setContext(e(e({},n.getContext()),t))},this.setTrait=function(t,i){var a;if(n.api)return n.setContext(e(e({},n.evaluationContext),{identity:e(e({},n.evaluationContext.identity),{traits:e(e({},null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.traits),u(Object.fromEntries([[t,i]])))})}))},this.setTraits=function(t){var i;if(n.api)return n.setContext(e(e({},n.evaluationContext),{identity:e(e({},n.evaluationContext.identity),{traits:e(e({},null===(i=n.evaluationContext.identity)||void 0===i?void 0:i.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,l(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var i,a,o="object"==typeof e,r=n.flags&&n.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!r&&o&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!0),(o&&!e.skipAnalytics||!e)&&n.evaluateFlag(t,"ENABLED"),n.sentryClient)try{null===(a=null===(i=n.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===i?void 0:i.addFeatureFlag)||void 0===a||a.call(i,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=n.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=n.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,i){var a,o,r,s=n.headers,l={method:e||"GET",body:i,cache:"no-cache",headers:{}};n.evaluationContext.environment&&(l.headers["X-Environment-Key"]=n.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(a=n.applicationMetadata)||void 0===a?void 0:a.name)&&(l.headers["Flagsmith-Application-Name"]=n.applicationMetadata.name),(null===(o=n.applicationMetadata)||void 0===o?void 0:o.version)&&(l.headers["Flagsmith-Application-Version"]=n.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("12.0.0"),s&&Object.assign(l.headers,s),d||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=n.evaluationContext.identity)||void 0===r?void 0:r.identifier);return d(t,l).then((function(i){var a,o,r="".concat(null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.identifier);if(u===r){var s=null===(o=i.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");n.timestamp=l}catch(t){n.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return n.log("Fetch response: "+i.status+" "+(e||"GET")+0+t),i.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&i.status&&(e="API Response: ".concat(i.status)),i.status&&i.status>=200&&i.status<300?e:Promise.reject(new Error(e))}))}n.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(n.datadogRum&&(n.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?n.datadogRum.client.addFeatureFlagEvaluation("flagsmith_value_"+t,n.getValue(t,{},!0)):n.datadogRum.client.addFeatureFlagEvaluation("flagsmith_enabled_"+t,n.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),n.enableAnalytics){if(!n.evaluationEvent||!n.evaluationContext.environment)return;n.evaluationEvent[n.evaluationContext.environment.apiKey]||(n.evaluationEvent[n.evaluationContext.environment.apiKey]={}),void 0===n.evaluationEvent[n.evaluationContext.environment.apiKey][t]&&(n.evaluationEvent[n.evaluationContext.environment.apiKey][t]=0),n.evaluationEvent[n.evaluationContext.environment.apiKey][t]+=1}n.updateEventStorage()},this._onChange=function(t,e,i){var a,o;n.setLoadingState(i),null===(a=n.onChange)||void 0===a||a.call(n,t,e,n.loadingState),null===(o=n._trigger)||void 0===o||o.call(n)},d=t.fetch?t.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!t.browserlessStorage,this.applicationMetadata=t.applicationMetadata,this.log("Constructing flagsmith instance "+t),t.eventSource&&(v=t.eventSource),t.AsyncStorage&&(g=t.AsyncStorage)}return t.prototype.init=function(t){var a,o,s,l;return n(this,void 0,void 0,(function(){var u,v,y,m,S,C,_,E,b,x,O,F,w,I,j,A,L,k,N,T,P,R,K,D,U,G,J,M,V,H,B,W,q,Y,X,z=this;return i(this,(function(Q){switch(Q.label){case 0:u=c(t.evaluationContext||this.evaluationContext),Q.label=1;case 1:if(Q.trys.push([1,13,,14]),v=t.AsyncStorage,y=t._trigger,m=t._triggerLoadingState,S=t.angularHttpClient,C=t.api,_=void 0===C?p:C,E=t.applicationMetadata,b=t.cacheFlags,x=t.cacheOptions,O=t.datadogRum,F=t.defaultFlags,w=t.enableAnalytics,I=t.enableDynatrace,j=t.enableLogs,A=t.environmentID,L=t.eventSourceUrl,k=void 0===L?"https://realtime.flagsmith.com/":L,N=t.fetch,T=t.headers,P=t.identity,R=t.onChange,K=t.onError,D=t.preventFetch,U=t.realtime,G=t.sentryClient,J=t.state,M=t.traits,u.environment=A?{apiKey:A}:u.environment,!u.environment||!u.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(u.identity=P||M?{identifier:P,traits:M?Object.fromEntries(Object.entries(M).map((function(t){return[t[0],{value:t[1]}]}))):{}}:u.identity,this.evaluationContext=u,this.api=(Z=_).endsWith("/")?Z:Z+"/",this.headers=T,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=y||this._trigger,this._triggerLoadingState=m||this._triggerLoadingState,this.onError=function(t){z.setLoadingState(e(e({},z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==K||K(t)},this.enableLogs=j||!1,this.cacheOptions=x?{skipAPI:!!x.skipAPI,ttl:x.ttl||0,storageKey:x.storageKey,loadStale:!!x.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),N&&(d=N),this.enableAnalytics=w||!1,this.flags=Object.assign({},F)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==g&&!!b,this.applicationMetadata=E,f="FLAGSMITH_EVENT_"+u.environment.apiKey,v&&(g=v),U&&"undefined"!=typeof window&&this.setupRealtime(k,u.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:h.DEFAULT_FLAGS})),this.setState(J),this.log("Initialising with properties",t,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),G&&(this.sentryClient=G),S&&(d=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(S)),g&&this.canUseStorage&&g.getItem(f).then((function(t){try{z.evaluationEvent=JSON.parse(t)||{}}catch(t){z.evaluationEvent={}}z.analyticsInterval=setInterval(z.analyticsFlags,z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),g&&this.canUseStorage&&g.getItem(f,(function(t,n){if(n&&z.evaluationContext.environment){var i=JSON.parse(n);if(i[z.evaluationContext.environment.apiKey]){var a=z.getState();z.log("Retrieved events from cache",n),z.setState(e(e({},a),{evaluationEvent:i[z.evaluationContext.environment.apiKey]}))}}}))),!b)return[3,9];if(!g||!this.canUseStorage)return[3,8];H=function(t,a){return n(z,void 0,void 0,(function(){var t,n,o,s,l,u,d,v,g,f,p,y,m,S,C,_,E,b,x,O=this;return i(this,(function(i){switch(i.label){case 0:if(!a)return[3,7];t=null,n=null,i.label=1;case 1:return i.trys.push([1,5,,6]),o=JSON.parse(a),s=!1,l=!1,o&&o.api===this.api&&(null===(f=null===(g=o.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(u=!0,this.evaluationContext.identity&&(null===(m=null===(y=o.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=o.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),u=!1),this.cacheOptions.ttl&&(!o.ts||(new Date).valueOf()-o.ts>this.cacheOptions.ttl)&&(o.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),u=!1):o.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),l=!0,u=!0)),u&&(s=!0,t=r(this.flags,o.flags),this.setState(e(e({},o),{evaluationContext:c(e(e({},o.evaluationContext),{identity:(null===(_=o.evaluationContext)||void 0===_?void 0:_.identity)?e(e({},null===(E=o.evaluationContext)||void 0===E?void 0:E.identity),{traits:e({},M||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),s?(d=!D&&(!this.cacheOptions.skipAPI||l),this._onChange(null,{isFromServer:!1,flagsChanged:t,traitsChanged:n},this._loadedState(null,h.CACHE,d)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!l&&this.log("Skipping API, using cache"),d&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:i.sent(),i.label=4;case 4:return[3,6];case 5:throw v=i.sent(),this.log("Exception fetching cached logs",v),v;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(F)this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(b=this.evaluationContext.identity)||void 0===b?void 0:b.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,h.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},Q.label=2;case 2:return Q.trys.push([2,7,,8]),g.getItemSync?(B=g.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,g.getItem(this.getStorageKey())];case 4:B=Q.sent(),Q.label=5;case 5:return[4,H(null,B)];case 6:return Q.sent(),[3,8];case 7:if(W=Q.sent(),!this.flags||0===Object.keys(this.flags).length)throw W;return X=W instanceof Error?W:new Error("".concat(W)),null===(a=this.onError)||void 0===a||a.call(this,X),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return Q.sent(),[3,12];case 11:if(F)this._onChange(null,{isFromServer:!1,flagsChanged:r({},F),traitsChanged:r({},null===(o=u.identity)||void 0===o?void 0:o.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else if(this.flags&&(q=null,0===Object.keys(this.flags).length&&(q=V),this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(s=u.identity)||void 0===s?void 0:s.traits)},this._loadedState(q,h.DEFAULT_FLAGS)),q))throw new Error(q);Q.label=12;case 12:return[3,14];case 13:throw Y=Q.sent(),this.log("Error during initialisation ",Y),X=Y instanceof Error?Y:new Error("".concat(Y)),null===(l=this.onError)||void 0===l||l.call(this,X),Y;case 14:return[2]}var Z}))}))},t.prototype.getAllFlags=function(){return this.flags},t.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,l(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},t.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},t.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||p,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this),this.loadingState.source===h.NONE&&this.flags&&Object.keys(this.flags).length>0&&this.setLoadingState(this._loadedState(null,h.SERVER)))},t.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},t.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},t.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},t.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,a(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},t.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),g.setItem(this.getStorageKey(),t)}},t.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);g.setItem(f,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},t.prototype.setLoadingState=function(t){var n;o(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(n=this._triggerLoadingState)||void 0===n||n.call(this))},t.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";v?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new v(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},t}();function m(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new y({fetch:e,AsyncStorage:n,eventSource:i})}var S,C=(S=function(t,e){return S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},S(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}S(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),_=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},E=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},b=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},x=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return C(e,t),e}(Error),O=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new x;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=_(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=_(b([],E(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=b(b([],E(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var F=m({AsyncStorage:t,eventSource:"undefined"!=typeof window?O:null});"undefined"!=typeof window&&(window.flagsmith=F);var w=function(){return m({AsyncStorage:t,eventSource:"undefined"!=typeof window?O:null})};export{h as FlagSource,w as createFlagsmithInstance,F as default};
1
+ var t={getItemSync:function(t){try{return localStorage.getItem(t)||null}catch(t){return null}},getItem:function(t,e){var n=this;return new Promise((function(i,a){try{var o=n.getItemSync(t);null==e||e(null,o),i(o)}catch(t){e&&e(t,null),a(t)}}))},setItem:function(t,e,n){return new Promise((function(i,a){try{localStorage.setItem(t,e),n&&n(null,e),i(e)}catch(t){n&&n(t,null),a(t)}}))}},e=function(){return e=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},e.apply(this,arguments)};function n(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((i=i.apply(t,e||[])).next())}))}function i(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function a(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var o=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function r(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!o(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function s(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function l(t){return!!t&&"object"==typeof t&&void 0!==t.value}function u(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,l(n)?n:{value:n}]})))}function c(t){return e(e({},t),{identity:t.identity?e(e({},t.identity),{traits:u(t.identity.traits||{})}):void 0})}var h,d;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(h||(h={}));var v,g=null,f="FLAGSMITH_EVENT",p="https://edge.api.flagsmith.com/api/v1/",y=function(){function t(t){var n=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var t=n,i=t.api,a=t.evaluationContext;n.log("Get Flags"),n.isLoading=!0,n.loadingState.isFetching||n.setLoadingState(e(e({},n.loadingState),{isFetching:!0}));var o="".concat(n.getContext().identity),l=function(t){var i,a,l,u;if(t&&o==="".concat(n.getContext().identity)){var c=t.flags,d=t.traits,v=t.identifier;n.isLoading=!1;var g={},f={};d=d||[],(c=c||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),d.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),n.oldFlags=e({},n.flags);var p=r(n.oldFlags,g),y=r(null===(i=n.evaluationContext.identity)||void 0===i?void 0:i.traits,f);if((v||Object.keys(f).length)&&(n.evaluationContext.identity=e(e({},n.evaluationContext.identity),{traits:f}),v&&(n.evaluationContext.identity.identifier=v,n.identity=v)),n.flags=g,n.updateStorage(),n._onChange(n.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},n._loadedState(null,h.SERVER)),n.datadogRum)try{if(n.datadogRum.trackTraits){var m={};Object.keys((null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.traits)||{}).map((function(t){m["flagsmith_trait_"+t]=n.getTrait(t)}));var S=e(e(e({},n.datadogRum.client.getUser()),{id:n.datadogRum.client.getUser().id||(null===(l=n.evaluationContext.identity)||void 0===l?void 0:l.identifier)}),m);n.log("Setting Datadog user",S),n.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(n.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(n.flags).map((function(t){s(C,"flagsmith_value_"+t,n.getValue(t,{skipAnalytics:!0})),s(C,"flagsmith_enabled_"+t,n.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(u=n.evaluationContext.identity)||void 0===u?void 0:u.traits)||{}).map((function(t){s(C,"flagsmith_trait_"+t,n.getTrait(t))})),n.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),n.log("Sending date traits to dynatrace",C.date),n.log("Sending shortString traits to dynatrace",C.shortString),n.log("Sending javaDouble to dynatrace",C.javaDouble),n.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return a.identity?Promise.all([a.identity.traits&&Object.keys(a.identity.traits).length||!a.identity.identifier?n.getJSON(i+"identities/","POST",JSON.stringify({identifier:a.identity.identifier,transient:a.identity.transient,traits:Object.entries(a.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(n.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):n.getJSON(i+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(t){return n.evaluationContext.identity=e(e({},n.evaluationContext.identity),{traits:{}}),l(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):n.getJSON(i+"flags/").then((function(t){return l({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=n.api;if(n.evaluationEvent&&n.evaluationContext.environment&&n.evaluationEvent[n.evaluationContext.environment.apiKey])return n.evaluationEvent&&0!==Object.getOwnPropertyNames(n.evaluationEvent).length&&0!==Object.getOwnPropertyNames(n.evaluationEvent[n.evaluationContext.environment.apiKey]).length?n.getJSON(t+"analytics/flags/","POST",JSON.stringify(n.evaluationEvent[n.evaluationContext.environment.apiKey])).then((function(t){if(n.evaluationContext.environment){var i=n.getState();n.evaluationEvent||(n.evaluationEvent={}),n.evaluationEvent[n.evaluationContext.environment.apiKey]={},n.setState(e(e({},i),{evaluationEvent:n.evaluationEvent})),n.updateEventStorage()}})).catch((function(t){n.log("Exception fetching evaluationEvent",t)})):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:h.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.getValue=function(t,e,i){var a=n.flags&&n.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(a&&(o=a.value),(null==e?void 0:e.skipAnalytics)||i||n.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(n.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,i;return(null===(e=n.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(i=n.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===i?void 0:i.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=n.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var i,a,o=c(t);return n.evaluationContext=e(e({},o),{environment:o.environment||n.evaluationContext.environment}),n.identity=null===(a=null===(i=n.getContext())||void 0===i?void 0:i.identity)||void 0===a?void 0:a.identifier,n.initialised?n.getFlags():Promise.resolve()},this.getContext=function(){return n.evaluationContext},this.updateContext=function(t){return n.setContext(e(e({},n.getContext()),t))},this.setTrait=function(t,i){var a;if(n.api)return n.setContext(e(e({},n.evaluationContext),{identity:e(e({},n.evaluationContext.identity),{traits:e(e({},null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.traits),u(Object.fromEntries([[t,i]])))})}))},this.setTraits=function(t){var i;if(n.api)return n.setContext(e(e({},n.evaluationContext),{identity:e(e({},n.evaluationContext.identity),{traits:e(e({},null===(i=n.evaluationContext.identity)||void 0===i?void 0:i.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,l(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var i,a,o="object"==typeof e,r=n.flags&&n.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!r&&o&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!0),(o&&!e.skipAnalytics||!e)&&n.evaluateFlag(t,"ENABLED"),n.sentryClient)try{null===(a=null===(i=n.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===i?void 0:i.addFeatureFlag)||void 0===a||a.call(i,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=n.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=n.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,i){var a,o,r,s=n.headers,l={method:e||"GET",body:i,cache:"no-cache",headers:{}};n.evaluationContext.environment&&(l.headers["X-Environment-Key"]=n.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(a=n.applicationMetadata)||void 0===a?void 0:a.name)&&(l.headers["Flagsmith-Application-Name"]=n.applicationMetadata.name),(null===(o=n.applicationMetadata)||void 0===o?void 0:o.version)&&(l.headers["Flagsmith-Application-Version"]=n.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("12.0.1"),s&&Object.assign(l.headers,s),d||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=n.evaluationContext.identity)||void 0===r?void 0:r.identifier);return d(t,l).then((function(i){var a,o,r="".concat(null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.identifier);if(u===r){var s=null===(o=i.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");n.timestamp=l}catch(t){n.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return n.log("Fetch response: "+i.status+" "+(e||"GET")+0+t),i.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&i.status&&(e="API Response: ".concat(i.status)),i.status&&i.status>=200&&i.status<300?e:Promise.reject(new Error(e))}))}n.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(n.datadogRum&&(n.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?n.datadogRum.client.addFeatureFlagEvaluation("flagsmith_value_"+t,n.getValue(t,{},!0)):n.datadogRum.client.addFeatureFlagEvaluation("flagsmith_enabled_"+t,n.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),n.enableAnalytics){if(!n.evaluationEvent||!n.evaluationContext.environment)return;n.evaluationEvent[n.evaluationContext.environment.apiKey]||(n.evaluationEvent[n.evaluationContext.environment.apiKey]={}),void 0===n.evaluationEvent[n.evaluationContext.environment.apiKey][t]&&(n.evaluationEvent[n.evaluationContext.environment.apiKey][t]=0),n.evaluationEvent[n.evaluationContext.environment.apiKey][t]+=1}n.updateEventStorage()},this._onChange=function(t,e,i){var a,o;n.setLoadingState(i),null===(a=n.onChange)||void 0===a||a.call(n,t,e,n.loadingState),null===(o=n._trigger)||void 0===o||o.call(n)},d=t.fetch?t.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!t.browserlessStorage,this.applicationMetadata=t.applicationMetadata,this.log("Constructing flagsmith instance "+t),t.eventSource&&(v=t.eventSource),t.AsyncStorage&&(g=t.AsyncStorage)}return t.prototype.init=function(t){var a,o,s,l;return n(this,void 0,void 0,(function(){var u,v,y,m,S,C,_,E,b,x,O,F,w,I,j,A,L,k,N,T,P,R,K,D,U,G,J,M,V,H,B,W,q,Y,X,z=this;return i(this,(function(Q){switch(Q.label){case 0:u=c(t.evaluationContext||this.evaluationContext),Q.label=1;case 1:if(Q.trys.push([1,13,,14]),v=t.AsyncStorage,y=t._trigger,m=t._triggerLoadingState,S=t.angularHttpClient,C=t.api,_=void 0===C?p:C,E=t.applicationMetadata,b=t.cacheFlags,x=t.cacheOptions,O=t.datadogRum,F=t.defaultFlags,w=t.enableAnalytics,I=t.enableDynatrace,j=t.enableLogs,A=t.environmentID,L=t.eventSourceUrl,k=void 0===L?"https://realtime.flagsmith.com/":L,N=t.fetch,T=t.headers,P=t.identity,R=t.onChange,K=t.onError,D=t.preventFetch,U=t.realtime,G=t.sentryClient,J=t.state,M=t.traits,u.environment=A?{apiKey:A}:u.environment,!u.environment||!u.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(u.identity=P||M?{identifier:P,traits:M?Object.fromEntries(Object.entries(M).map((function(t){return[t[0],{value:t[1]}]}))):{}}:u.identity,this.evaluationContext=u,this.api=(Z=_).endsWith("/")?Z:Z+"/",this.headers=T,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=y||this._trigger,this._triggerLoadingState=m||this._triggerLoadingState,this.onError=function(t){z.setLoadingState(e(e({},z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==K||K(t)},this.enableLogs=j||!1,this.cacheOptions=x?{skipAPI:!!x.skipAPI,ttl:x.ttl||0,storageKey:x.storageKey,loadStale:!!x.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),N&&(d=N),this.enableAnalytics=w||!1,this.flags=Object.assign({},F)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==g&&!!b,this.applicationMetadata=E,f="FLAGSMITH_EVENT_"+u.environment.apiKey,v&&(g=v),U&&"undefined"!=typeof window&&this.setupRealtime(k,u.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:h.DEFAULT_FLAGS})),this.setState(J),this.log("Initialising with properties",t,this),I&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),G&&(this.sentryClient=G),S&&(d=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(S)),g&&this.canUseStorage&&g.getItem(f).then((function(t){try{z.evaluationEvent=JSON.parse(t)||{}}catch(t){z.evaluationEvent={}}z.analyticsInterval=setInterval(z.analyticsFlags,z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),g&&this.canUseStorage&&g.getItem(f,(function(t,n){if(n&&z.evaluationContext.environment){var i=JSON.parse(n);if(i[z.evaluationContext.environment.apiKey]){var a=z.getState();z.log("Retrieved events from cache",n),z.setState(e(e({},a),{evaluationEvent:i[z.evaluationContext.environment.apiKey]}))}}}))),!b)return[3,9];if(!g||!this.canUseStorage)return[3,8];H=function(t,a){return n(z,void 0,void 0,(function(){var t,n,o,s,l,u,d,v,g,f,p,y,m,S,C,_,E,b,x,O=this;return i(this,(function(i){switch(i.label){case 0:if(!a)return[3,7];t=null,n=null,i.label=1;case 1:return i.trys.push([1,5,,6]),o=JSON.parse(a),s=!1,l=!1,o&&o.api===this.api&&(null===(f=null===(g=o.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(u=!0,this.evaluationContext.identity&&(null===(m=null===(y=o.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=o.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),u=!1),this.cacheOptions.ttl&&(!o.ts||(new Date).valueOf()-o.ts>this.cacheOptions.ttl)&&(o.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),u=!1):o.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+o.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-o.ts)+"ms"),l=!0,u=!0)),u&&(s=!0,t=r(this.flags,o.flags),this.setState(e(e({},o),{evaluationContext:c(e(e({},o.evaluationContext),{identity:(null===(_=o.evaluationContext)||void 0===_?void 0:_.identity)?e(e({},null===(E=o.evaluationContext)||void 0===E?void 0:E.identity),{traits:e({},M||{})}):void 0}))})),this.log("Retrieved flags from cache",o))),s?(d=!D&&(!this.cacheOptions.skipAPI||l),this._onChange(null,{isFromServer:!1,flagsChanged:t,traitsChanged:n},this._loadedState(null,h.CACHE,d)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!l&&this.log("Skipping API, using cache"),d&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:i.sent(),i.label=4;case 4:return[3,6];case 5:throw v=i.sent(),this.log("Exception fetching cached logs",v),v;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(F)this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(b=this.evaluationContext.identity)||void 0===b?void 0:b.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,h.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},Q.label=2;case 2:return Q.trys.push([2,7,,8]),g.getItemSync?(B=g.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,g.getItem(this.getStorageKey())];case 4:B=Q.sent(),Q.label=5;case 5:return[4,H(null,B)];case 6:return Q.sent(),[3,8];case 7:if(W=Q.sent(),!this.flags||0===Object.keys(this.flags).length)throw W;return X=W instanceof Error?W:new Error("".concat(W)),null===(a=this.onError)||void 0===a||a.call(this,X),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return Q.sent(),[3,12];case 11:if(F)this._onChange(null,{isFromServer:!1,flagsChanged:r({},F),traitsChanged:r({},null===(o=u.identity)||void 0===o?void 0:o.traits)},this._loadedState(null,h.DEFAULT_FLAGS));else if(this.flags&&(q=null,0===Object.keys(this.flags).length&&(q=V),this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(s=u.identity)||void 0===s?void 0:s.traits)},this._loadedState(q,h.DEFAULT_FLAGS)),q))throw new Error(q);Q.label=12;case 12:return[3,14];case 13:throw Y=Q.sent(),this.log("Error during initialisation ",Y),X=Y instanceof Error?Y:new Error("".concat(Y)),null===(l=this.onError)||void 0===l||l.call(this,X),Y;case 14:return[2]}var Z}))}))},t.prototype.getAllFlags=function(){return this.flags},t.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,l(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},t.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},t.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||p,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this),this.loadingState.source===h.NONE&&this.flags&&Object.keys(this.flags).length>0&&this.setLoadingState(this._loadedState(null,h.SERVER)))},t.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},t.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},t.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},t.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},t.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,a(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},t.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),g.setItem(this.getStorageKey(),t)}},t.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);g.setItem(f,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},t.prototype.setLoadingState=function(t){var n;o(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(n=this._triggerLoadingState)||void 0===n||n.call(this))},t.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";v?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new v(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},t}();function m(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new y({fetch:e,AsyncStorage:n,eventSource:i})}var S,C=(S=function(t,e){return S=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},S(t,e)},function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");function n(){this.constructor=t}S(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),_=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],i=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},E=function(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var i,a,o=n.call(t),r=[];try{for(;(void 0===e||e-- >0)&&!(i=o.next()).done;)r.push(i.value)}catch(t){a={error:t}}finally{try{i&&!i.done&&(n=o.return)&&n.call(o)}finally{if(a)throw a.error}}return r},b=function(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))},x=function(t){function e(){return t.call(this,"EventSource not available.\nConsider loading an EventSource polyfill and making it available globally as EventSource, or passing one in as eventSourceClass to the ReconnectingEventSource constructor.")||this}return C(e,t),e}(Error),O=function(){function t(t,e){var n=this;if(this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,this._configuration=null!=e?Object.assign({},e):void 0,this.withCredentials=!1,this._eventSource=null,this._lastEventId=null,this._timer=null,this._listeners={open:[],error:[],message:[]},this.url=t.toString(),this.readyState=this.CONNECTING,this.max_retry_time=3e3,this.eventSourceClass=globalThis.FlagsmithEventSource,null!=this._configuration&&(this._configuration.lastEventId&&(this._lastEventId=this._configuration.lastEventId,delete this._configuration.lastEventId),this._configuration.max_retry_time&&(this.max_retry_time=this._configuration.max_retry_time,delete this._configuration.max_retry_time),this._configuration.eventSourceClass&&(this.eventSourceClass=this._configuration.eventSourceClass,delete this._configuration.eventSourceClass)),null==this.eventSourceClass||"function"!=typeof this.eventSourceClass)throw new x;this._onevent_wrapped=function(t){n._onevent(t)},this._start()}return t.prototype.dispatchEvent=function(t){throw new Error("Method not implemented.")},t.prototype._start=function(){var t,e,n=this,i=this.url;this._lastEventId&&(-1===i.indexOf("?")?i+="?":i+="&",i+="lastEventId="+encodeURIComponent(this._lastEventId)),this._eventSource=new this.eventSourceClass(i,this._configuration),this._eventSource.onopen=function(t){n._onopen(t)},this._eventSource.onerror=function(t){n._onerror(t)},this._eventSource.onmessage=function(t){n.onmessage(t)};try{for(var a=_(Object.keys(this._listeners)),o=a.next();!o.done;o=a.next()){var r=o.value;this._eventSource.addEventListener(r,this._onevent_wrapped)}}catch(e){t={error:e}}finally{try{o&&!o.done&&(e=a.return)&&e.call(a)}finally{if(t)throw t.error}}},t.prototype._onopen=function(t){0===this.readyState&&(this.readyState=1,this.onopen(t))},t.prototype._onerror=function(t){var e=this;if(1===this.readyState&&(this.readyState=0,this.onerror(t)),this._eventSource){this._eventSource.close(),this._eventSource=null;var n=Math.round(this.max_retry_time*Math.random());this._timer=setTimeout((function(){return e._start()}),n)}},t.prototype._onevent=function(t){var e,n;t&&t.lastEventId&&(this._lastEventId=t.lastEventId);var i=this._listeners[t.type];if(null!=i)try{for(var a=_(b([],E(i),!1)),o=a.next();!o.done;o=a.next()){o.value.call(this,t)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(n=a.return)&&n.call(a)}finally{if(e)throw e.error}}"message"===t.type&&this.onmessage(t)},t.prototype.onopen=function(t){},t.prototype.onerror=function(t){},t.prototype.onmessage=function(t){},t.prototype.close=function(){this._timer&&(clearTimeout(this._timer),this._timer=null),this._eventSource&&(this._eventSource.close(),this._eventSource=null),this.readyState=2},t.prototype.addEventListener=function(t,e,n){null==this._listeners[t]&&(this._listeners[t]=[],null!=this._eventSource&&this._eventSource.addEventListener(t,this._onevent_wrapped));var i=this._listeners[t];i.includes(e)||(this._listeners[t]=b(b([],E(i),!1),[e],!1))},t.prototype.removeEventListener=function(t,e,n){var i=this._listeners[t];this._listeners[t]=i.filter((function(t){return t!==e}))},t}();globalThis.FlagsmithEventSource="undefined"!=typeof EventSource?EventSource:null;var F=m({AsyncStorage:t,eventSource:"undefined"!=typeof window?O:null});"undefined"!=typeof window&&(window.flagsmith=F);var w=function(){return m({AsyncStorage:t,eventSource:"undefined"!=typeof window?O:null})};export{h as FlagSource,w as createFlagsmithInstance,F as default};
2
2
  //# sourceMappingURL=isomorphic.mjs.map
@@ -1,2 +1,2 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["next-middleware"]={})}(this,(function(t){"use strict";var e=function(){return e=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},e.apply(this,arguments)};function n(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{s(i.next(t))}catch(t){o(t)}}function l(t){try{s(i.throw(t))}catch(t){o(t)}}function s(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,l)}s((i=i.apply(t,e||[])).next())}))}function i(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function a(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var o=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function r(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!o(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function l(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function s(t){return!!t&&"object"==typeof t&&void 0!==t.value}function u(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))}function c(t){return e(e({},t),{identity:t.identity?e(e({},t.identity),{traits:u(t.identity.traits||{})}):void 0})}var d,v;t.FlagSource=void 0,(d=t.FlagSource||(t.FlagSource={})).NONE="NONE",d.DEFAULT_FLAGS="DEFAULT_FLAGS",d.CACHE="CACHE",d.SERVER="SERVER";var g,h=null,f="FLAGSMITH_EVENT",p=f,y="https://edge.api.flagsmith.com/api/v1/",m="flagsmith_value_",S="flagsmith_enabled_",C="flagsmith_trait_",b=function(){function d(n){var i=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var n=i,a=n.api,o=n.evaluationContext;i.log("Get Flags"),i.isLoading=!0,i.loadingState.isFetching||i.setLoadingState(e(e({},i.loadingState),{isFetching:!0}));var s="".concat(i.getContext().identity),u=function(n){var a,o,u,c;if(n&&s==="".concat(i.getContext().identity)){var d=n.flags,v=n.traits,g=n.identifier;i.isLoading=!1;var h={},f={};v=v||[],(d=d||[]).forEach((function(t){h[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),v.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),i.oldFlags=e({},i.flags);var p=r(i.oldFlags,h),y=r(null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.traits,f);if((g||Object.keys(f).length)&&(i.evaluationContext.identity=e(e({},i.evaluationContext.identity),{traits:f}),g&&(i.evaluationContext.identity.identifier=g,i.identity=g)),i.flags=h,i.updateStorage(),i._onChange(i.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},i._loadedState(null,t.FlagSource.SERVER)),i.datadogRum)try{if(i.datadogRum.trackTraits){var b={};Object.keys((null===(o=i.evaluationContext.identity)||void 0===o?void 0:o.traits)||{}).map((function(t){b[C+t]=i.getTrait(t)}));var F=e(e(e({},i.datadogRum.client.getUser()),{id:i.datadogRum.client.getUser().id||(null===(u=i.evaluationContext.identity)||void 0===u?void 0:u.identifier)}),b);i.log("Setting Datadog user",F),i.datadogRum.client.setUser(F)}}catch(t){console.error(t)}if(i.dtrum)try{var x={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(i.flags).map((function(t){l(x,m+t,i.getValue(t,{skipAnalytics:!0})),l(x,S+t,i.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=i.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){l(x,C+t,i.getTrait(t))})),i.log("Sending javaLongOrObject traits to dynatrace",x.javaLongOrObject),i.log("Sending date traits to dynatrace",x.date),i.log("Sending shortString traits to dynatrace",x.shortString),i.log("Sending javaDouble to dynatrace",x.javaDouble),i.dtrum.sendSessionProperties(x.javaLongOrObject,x.date,x.shortString,x.javaDouble)}catch(t){console.error(t)}}};return o.identity?Promise.all([o.identity.traits&&Object.keys(o.identity.traits).length||!o.identity.identifier?i.getJSON(a+"identities/","POST",JSON.stringify({identifier:o.identity.identifier,transient:o.identity.transient,traits:Object.entries(o.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(i.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):i.getJSON(a+"identities/?identifier="+encodeURIComponent(o.identity.identifier)+(o.identity.transient?"&transient=true":""))]).then((function(t){return i.evaluationContext.identity=e(e({},i.evaluationContext.identity),{traits:{}}),u(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):i.getJSON(a+"flags/").then((function(t){return u({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=i.api;if(i.evaluationEvent&&i.evaluationContext.environment&&i.evaluationEvent[i.evaluationContext.environment.apiKey])return i.evaluationEvent&&0!==Object.getOwnPropertyNames(i.evaluationEvent).length&&0!==Object.getOwnPropertyNames(i.evaluationEvent[i.evaluationContext.environment.apiKey]).length?i.getJSON(t+"analytics/flags/","POST",JSON.stringify(i.evaluationEvent[i.evaluationContext.environment.apiKey])).then((function(t){if(i.evaluationContext.environment){var n=i.getState();i.evaluationEvent||(i.evaluationEvent={}),i.evaluationEvent[i.evaluationContext.environment.apiKey]={},i.setState(e(e({},n),{evaluationEvent:i.evaluationEvent})),i.updateEventStorage()}})).catch((function(t){i.log("Exception fetching evaluationEvent",t)})):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:t.FlagSource.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.getValue=function(t,e,n){var a=i.flags&&i.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(a&&(o=a.value),(null==e?void 0:e.skipAnalytics)||n||i.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(i.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,n;return(null===(e=i.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=i.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=i.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var n,a,o=c(t);return i.evaluationContext=e(e({},o),{environment:o.environment||i.evaluationContext.environment}),i.identity=null===(a=null===(n=i.getContext())||void 0===n?void 0:n.identity)||void 0===a?void 0:a.identifier,i.initialised?i.getFlags():Promise.resolve()},this.getContext=function(){return i.evaluationContext},this.updateContext=function(t){return i.setContext(e(e({},i.getContext()),t))},this.setTrait=function(t,n){var a;if(i.api)return i.setContext(e(e({},i.evaluationContext),{identity:e(e({},i.evaluationContext.identity),{traits:e(e({},null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.traits),u(Object.fromEntries([[t,n]])))})}))},this.setTraits=function(t){var n;if(i.api)return i.setContext(e(e({},i.evaluationContext),{identity:e(e({},i.evaluationContext.identity),{traits:e(e({},null===(n=i.evaluationContext.identity)||void 0===n?void 0:n.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,a,o="object"==typeof e,r=i.flags&&i.flags[t.toLowerCase().replace(/ /g,"_")],l=!1;if(!r&&o&&void 0!==e.fallback?l=null==e?void 0:e.fallback:r&&r.enabled&&(l=!0),(o&&!e.skipAnalytics||!e)&&i.evaluateFlag(t,"ENABLED"),i.sentryClient)try{null===(a=null===(n=i.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===a||a.call(n,t,l)}catch(t){console.error(t)}return l},this.getStorageKey=function(){var t,e;return(null===(t=i.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=i.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var a,o,r,l=i.headers,s={method:e||"GET",body:n,cache:"no-cache",headers:{}};i.evaluationContext.environment&&(s.headers["X-Environment-Key"]=i.evaluationContext.environment.apiKey),e&&"GET"!==e&&(s.headers["Content-Type"]="application/json; charset=utf-8"),(null===(a=i.applicationMetadata)||void 0===a?void 0:a.name)&&(s.headers["Flagsmith-Application-Name"]=i.applicationMetadata.name),(null===(o=i.applicationMetadata)||void 0===o?void 0:o.version)&&(s.headers["Flagsmith-Application-Version"]=i.applicationMetadata.version),s.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("12.0.0"),l&&Object.assign(s.headers,l),v||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=i.evaluationContext.identity)||void 0===r?void 0:r.identifier);return v(t,s).then((function(n){var a,o,r="".concat(null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.identifier);if(u===r){var l=null===(o=n.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(l)try{var s=parseFloat(l);if(isNaN(s))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");i.timestamp=s}catch(t){i.log(t,"Failed to parse x-flagsmith-document-updated-at",l)}return i.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}i.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(i.datadogRum&&(i.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?i.datadogRum.client.addFeatureFlagEvaluation(m+t,i.getValue(t,{},!0)):i.datadogRum.client.addFeatureFlagEvaluation(S+t,i.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),i.enableAnalytics){if(!i.evaluationEvent||!i.evaluationContext.environment)return;i.evaluationEvent[i.evaluationContext.environment.apiKey]||(i.evaluationEvent[i.evaluationContext.environment.apiKey]={}),void 0===i.evaluationEvent[i.evaluationContext.environment.apiKey][t]&&(i.evaluationEvent[i.evaluationContext.environment.apiKey][t]=0),i.evaluationEvent[i.evaluationContext.environment.apiKey][t]+=1}i.updateEventStorage()},this._onChange=function(t,e,n){var a,o;i.setLoadingState(n),null===(a=i.onChange)||void 0===a||a.call(i,t,e,i.loadingState),null===(o=i._trigger)||void 0===o||o.call(i)},v=n.fetch?n.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!n.browserlessStorage,this.applicationMetadata=n.applicationMetadata,this.log("Constructing flagsmith instance "+n),n.eventSource&&(g=n.eventSource),n.AsyncStorage&&(h=n.AsyncStorage)}return d.prototype.init=function(a){var o,l,s,u;return n(this,void 0,void 0,(function(){var d,g,f,m,S,C,b,F,x,E,O,_,j,w,A,L,k,I,T,N,P,R,K,D,U,J,G,M,V,H,B,W,q,Y,X,z=this;return i(this,(function(Q){switch(Q.label){case 0:d=c(a.evaluationContext||this.evaluationContext),Q.label=1;case 1:if(Q.trys.push([1,13,,14]),g=a.AsyncStorage,f=a._trigger,m=a._triggerLoadingState,S=a.angularHttpClient,C=a.api,b=void 0===C?y:C,F=a.applicationMetadata,x=a.cacheFlags,E=a.cacheOptions,O=a.datadogRum,_=a.defaultFlags,j=a.enableAnalytics,w=a.enableDynatrace,A=a.enableLogs,L=a.environmentID,k=a.eventSourceUrl,I=void 0===k?"https://realtime.flagsmith.com/":k,T=a.fetch,N=a.headers,P=a.identity,R=a.onChange,K=a.onError,D=a.preventFetch,U=a.realtime,J=a.sentryClient,G=a.state,M=a.traits,d.environment=L?{apiKey:L}:d.environment,!d.environment||!d.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(d.identity=P||M?{identifier:P,traits:M?Object.fromEntries(Object.entries(M).map((function(t){return[t[0],{value:t[1]}]}))):{}}:d.identity,this.evaluationContext=d,this.api=(Z=b).endsWith("/")?Z:Z+"/",this.headers=N,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=f||this._trigger,this._triggerLoadingState=m||this._triggerLoadingState,this.onError=function(t){z.setLoadingState(e(e({},z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==K||K(t)},this.enableLogs=A||!1,this.cacheOptions=E?{skipAPI:!!E.skipAPI,ttl:E.ttl||0,storageKey:E.storageKey,loadStale:!!E.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),T&&(v=T),this.enableAnalytics=j||!1,this.flags=Object.assign({},_)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==h&&!!x,this.applicationMetadata=F,p="FLAGSMITH_EVENT_"+d.environment.apiKey,g&&(h=g),U&&"undefined"!=typeof window&&this.setupRealtime(I,d.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(G),this.log("Initialising with properties",a,this),w&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),S&&(v=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},l=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(l(t,!t.status||t.status>=200&&t.status<300))},s=function(t){return n(l(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,s);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,s);default:return s({status:405,message:"Unsupported method: ".concat(a)})}}))}}(S)),h&&this.canUseStorage&&h.getItem(p).then((function(t){try{z.evaluationEvent=JSON.parse(t)||{}}catch(t){z.evaluationEvent={}}z.analyticsInterval=setInterval(z.analyticsFlags,z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),h&&this.canUseStorage&&h.getItem(p,(function(t,n){if(n&&z.evaluationContext.environment){var i=JSON.parse(n);if(i[z.evaluationContext.environment.apiKey]){var a=z.getState();z.log("Retrieved events from cache",n),z.setState(e(e({},a),{evaluationEvent:i[z.evaluationContext.environment.apiKey]}))}}}))),!x)return[3,9];if(!h||!this.canUseStorage)return[3,8];H=function(a,o){return n(z,void 0,void 0,(function(){var n,a,l,s,u,d,v,g,h,f,p,y,m,S,C,b,F,x,E,O=this;return i(this,(function(i){switch(i.label){case 0:if(!o)return[3,7];n=null,a=null,i.label=1;case 1:return i.trys.push([1,5,,6]),l=JSON.parse(o),s=!1,u=!1,l&&l.api===this.api&&(null===(f=null===(h=l.evaluationContext)||void 0===h?void 0:h.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(d=!0,this.evaluationContext.identity&&(null===(m=null===(y=l.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=l.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),d=!1),this.cacheOptions.ttl&&(!l.ts||(new Date).valueOf()-l.ts>this.cacheOptions.ttl)&&(l.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+l.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-l.ts)+"ms"),d=!1):l.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+l.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-l.ts)+"ms"),u=!0,d=!0)),d&&(s=!0,n=r(this.flags,l.flags),this.setState(e(e({},l),{evaluationContext:c(e(e({},l.evaluationContext),{identity:(null===(b=l.evaluationContext)||void 0===b?void 0:b.identity)?e(e({},null===(F=l.evaluationContext)||void 0===F?void 0:F.identity),{traits:e({},M||{})}):void 0}))})),this.log("Retrieved flags from cache",l))),s?(v=!D&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:n,traitsChanged:a},this._loadedState(null,t.FlagSource.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!u&&this.log("Skipping API, using cache"),v&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:i.sent(),i.label=4;case 4:return[3,6];case 5:throw g=i.sent(),this.log("Exception fetching cached logs",g),g;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(E=this.evaluationContext.identity)||void 0===E?void 0:E.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},Q.label=2;case 2:return Q.trys.push([2,7,,8]),h.getItemSync?(B=h.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,h.getItem(this.getStorageKey())];case 4:B=Q.sent(),Q.label=5;case 5:return[4,H(null,B)];case 6:return Q.sent(),[3,8];case 7:if(W=Q.sent(),!this.flags||0===Object.keys(this.flags).length)throw W;return X=W instanceof Error?W:new Error("".concat(W)),null===(o=this.onError)||void 0===o||o.call(this,X),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return Q.sent(),[3,12];case 11:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:r({},_),traitsChanged:r({},null===(l=d.identity)||void 0===l?void 0:l.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else if(this.flags&&(q=null,0===Object.keys(this.flags).length&&(q=V),this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(s=d.identity)||void 0===s?void 0:s.traits)},this._loadedState(q,t.FlagSource.DEFAULT_FLAGS)),q))throw new Error(q);Q.label=12;case 12:return[3,14];case 13:throw Y=Q.sent(),this.log("Error during initialisation ",Y),X=Y instanceof Error?Y:new Error("".concat(Y)),null===(u=this.onError)||void 0===u||u.call(this,X),Y;case 14:return[2]}var Z}))}))},d.prototype.getAllFlags=function(){return this.flags},d.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},d.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},d.prototype.setState=function(e){var n,i;e&&(this.initialised=!0,this.api=e.api||this.api||y,this.flags=e.flags||this.flags,this.evaluationContext=e.evaluationContext||this.evaluationContext,this.evaluationEvent=e.evaluationEvent||this.evaluationEvent,this.identity=null===(i=null===(n=this.getContext())||void 0===n?void 0:n.identity)||void 0===i?void 0:i.identifier,this.log("setState called",this),this.loadingState.source===t.FlagSource.NONE&&this.flags&&Object.keys(this.flags).length>0&&this.setLoadingState(this._loadedState(null,t.FlagSource.SERVER)))},d.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},d.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},d.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},d.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},d.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,a(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},d.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),h.setItem(this.getStorageKey(),t)}},d.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);h.setItem(p,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},d.prototype.setLoadingState=function(t){var n;o(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(n=this._triggerLoadingState)||void 0===n||n.call(this))},d.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";g?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new g(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},d}();function F(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new b({fetch:e,AsyncStorage:n,eventSource:i})}var x=F({});t.createFlagsmithInstance=function(){return F({})},t.default=x,Object.defineProperty(t,"__esModule",{value:!0})}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["next-middleware"]={})}(this,(function(t){"use strict";var e=function(){return e=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},e.apply(this,arguments)};function n(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{s(i.next(t))}catch(t){o(t)}}function l(t){try{s(i.throw(t))}catch(t){o(t)}}function s(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,l)}s((i=i.apply(t,e||[])).next())}))}function i(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function a(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var o=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function r(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],a=null==e?void 0:e[n];return!o(i,a)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function l(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function s(t){return!!t&&"object"==typeof t&&void 0!==t.value}function u(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))}function c(t){return e(e({},t),{identity:t.identity?e(e({},t.identity),{traits:u(t.identity.traits||{})}):void 0})}var d,v;t.FlagSource=void 0,(d=t.FlagSource||(t.FlagSource={})).NONE="NONE",d.DEFAULT_FLAGS="DEFAULT_FLAGS",d.CACHE="CACHE",d.SERVER="SERVER";var g,h=null,f="FLAGSMITH_EVENT",p=f,y="https://edge.api.flagsmith.com/api/v1/",m="flagsmith_value_",S="flagsmith_enabled_",C="flagsmith_trait_",b=function(){function d(n){var i=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var n=i,a=n.api,o=n.evaluationContext;i.log("Get Flags"),i.isLoading=!0,i.loadingState.isFetching||i.setLoadingState(e(e({},i.loadingState),{isFetching:!0}));var s="".concat(i.getContext().identity),u=function(n){var a,o,u,c;if(n&&s==="".concat(i.getContext().identity)){var d=n.flags,v=n.traits,g=n.identifier;i.isLoading=!1;var h={},f={};v=v||[],(d=d||[]).forEach((function(t){h[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),v.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),i.oldFlags=e({},i.flags);var p=r(i.oldFlags,h),y=r(null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.traits,f);if((g||Object.keys(f).length)&&(i.evaluationContext.identity=e(e({},i.evaluationContext.identity),{traits:f}),g&&(i.evaluationContext.identity.identifier=g,i.identity=g)),i.flags=h,i.updateStorage(),i._onChange(i.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},i._loadedState(null,t.FlagSource.SERVER)),i.datadogRum)try{if(i.datadogRum.trackTraits){var b={};Object.keys((null===(o=i.evaluationContext.identity)||void 0===o?void 0:o.traits)||{}).map((function(t){b[C+t]=i.getTrait(t)}));var F=e(e(e({},i.datadogRum.client.getUser()),{id:i.datadogRum.client.getUser().id||(null===(u=i.evaluationContext.identity)||void 0===u?void 0:u.identifier)}),b);i.log("Setting Datadog user",F),i.datadogRum.client.setUser(F)}}catch(t){console.error(t)}if(i.dtrum)try{var x={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(i.flags).map((function(t){l(x,m+t,i.getValue(t,{skipAnalytics:!0})),l(x,S+t,i.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(c=i.evaluationContext.identity)||void 0===c?void 0:c.traits)||{}).map((function(t){l(x,C+t,i.getTrait(t))})),i.log("Sending javaLongOrObject traits to dynatrace",x.javaLongOrObject),i.log("Sending date traits to dynatrace",x.date),i.log("Sending shortString traits to dynatrace",x.shortString),i.log("Sending javaDouble to dynatrace",x.javaDouble),i.dtrum.sendSessionProperties(x.javaLongOrObject,x.date,x.shortString,x.javaDouble)}catch(t){console.error(t)}}};return o.identity?Promise.all([o.identity.traits&&Object.keys(o.identity.traits).length||!o.identity.identifier?i.getJSON(a+"identities/","POST",JSON.stringify({identifier:o.identity.identifier,transient:o.identity.transient,traits:Object.entries(o.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(i.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):i.getJSON(a+"identities/?identifier="+encodeURIComponent(o.identity.identifier)+(o.identity.transient?"&transient=true":""))]).then((function(t){return i.evaluationContext.identity=e(e({},i.evaluationContext.identity),{traits:{}}),u(null==t?void 0:t[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):i.getJSON(a+"flags/").then((function(t){return u({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var t=i.api;if(i.evaluationEvent&&i.evaluationContext.environment&&i.evaluationEvent[i.evaluationContext.environment.apiKey])return i.evaluationEvent&&0!==Object.getOwnPropertyNames(i.evaluationEvent).length&&0!==Object.getOwnPropertyNames(i.evaluationEvent[i.evaluationContext.environment.apiKey]).length?i.getJSON(t+"analytics/flags/","POST",JSON.stringify(i.evaluationEvent[i.evaluationContext.environment.apiKey])).then((function(t){if(i.evaluationContext.environment){var n=i.getState();i.evaluationEvent||(i.evaluationEvent={}),i.evaluationEvent[i.evaluationContext.environment.apiKey]={},i.setState(e(e({},n),{evaluationEvent:i.evaluationEvent})),i.updateEventStorage()}})).catch((function(t){i.log("Exception fetching evaluationEvent",t)})):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:t.FlagSource.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.getValue=function(t,e,n){var a=i.flags&&i.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(a&&(o=a.value),(null==e?void 0:e.skipAnalytics)||n||i.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(i.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,n;return(null===(e=i.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(n=i.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===n?void 0:n.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=i.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(t){var n,a,o=c(t);return i.evaluationContext=e(e({},o),{environment:o.environment||i.evaluationContext.environment}),i.identity=null===(a=null===(n=i.getContext())||void 0===n?void 0:n.identity)||void 0===a?void 0:a.identifier,i.initialised?i.getFlags():Promise.resolve()},this.getContext=function(){return i.evaluationContext},this.updateContext=function(t){return i.setContext(e(e({},i.getContext()),t))},this.setTrait=function(t,n){var a;if(i.api)return i.setContext(e(e({},i.evaluationContext),{identity:e(e({},i.evaluationContext.identity),{traits:e(e({},null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.traits),u(Object.fromEntries([[t,n]])))})}))},this.setTraits=function(t){var n;if(i.api)return i.setContext(e(e({},i.evaluationContext),{identity:e(e({},i.evaluationContext.identity),{traits:e(e({},null===(n=i.evaluationContext.identity)||void 0===n?void 0:n.traits),Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var n,a,o="object"==typeof e,r=i.flags&&i.flags[t.toLowerCase().replace(/ /g,"_")],l=!1;if(!r&&o&&void 0!==e.fallback?l=null==e?void 0:e.fallback:r&&r.enabled&&(l=!0),(o&&!e.skipAnalytics||!e)&&i.evaluateFlag(t,"ENABLED"),i.sentryClient)try{null===(a=null===(n=i.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===n?void 0:n.addFeatureFlag)||void 0===a||a.call(n,t,l)}catch(t){console.error(t)}return l},this.getStorageKey=function(){var t,e;return(null===(t=i.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=i.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,n){var a,o,r,l=i.headers,s={method:e||"GET",body:n,cache:"no-cache",headers:{}};i.evaluationContext.environment&&(s.headers["X-Environment-Key"]=i.evaluationContext.environment.apiKey),e&&"GET"!==e&&(s.headers["Content-Type"]="application/json; charset=utf-8"),(null===(a=i.applicationMetadata)||void 0===a?void 0:a.name)&&(s.headers["Flagsmith-Application-Name"]=i.applicationMetadata.name),(null===(o=i.applicationMetadata)||void 0===o?void 0:o.version)&&(s.headers["Flagsmith-Application-Version"]=i.applicationMetadata.version),s.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("12.0.1"),l&&Object.assign(s.headers,l),v||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=i.evaluationContext.identity)||void 0===r?void 0:r.identifier);return v(t,s).then((function(n){var a,o,r="".concat(null===(a=i.evaluationContext.identity)||void 0===a?void 0:a.identifier);if(u===r){var l=null===(o=n.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(l)try{var s=parseFloat(l);if(isNaN(s))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");i.timestamp=s}catch(t){i.log(t,"Failed to parse x-flagsmith-document-updated-at",l)}return i.log("Fetch response: "+n.status+" "+(e||"GET")+0+t),n.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&n.status&&(e="API Response: ".concat(n.status)),n.status&&n.status>=200&&n.status<300?e:Promise.reject(new Error(e))}))}i.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(i.datadogRum&&(i.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?i.datadogRum.client.addFeatureFlagEvaluation(m+t,i.getValue(t,{},!0)):i.datadogRum.client.addFeatureFlagEvaluation(S+t,i.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),i.enableAnalytics){if(!i.evaluationEvent||!i.evaluationContext.environment)return;i.evaluationEvent[i.evaluationContext.environment.apiKey]||(i.evaluationEvent[i.evaluationContext.environment.apiKey]={}),void 0===i.evaluationEvent[i.evaluationContext.environment.apiKey][t]&&(i.evaluationEvent[i.evaluationContext.environment.apiKey][t]=0),i.evaluationEvent[i.evaluationContext.environment.apiKey][t]+=1}i.updateEventStorage()},this._onChange=function(t,e,n){var a,o;i.setLoadingState(n),null===(a=i.onChange)||void 0===a||a.call(i,t,e,i.loadingState),null===(o=i._trigger)||void 0===o||o.call(i)},v=n.fetch?n.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!n.browserlessStorage,this.applicationMetadata=n.applicationMetadata,this.log("Constructing flagsmith instance "+n),n.eventSource&&(g=n.eventSource),n.AsyncStorage&&(h=n.AsyncStorage)}return d.prototype.init=function(a){var o,l,s,u;return n(this,void 0,void 0,(function(){var d,g,f,m,S,C,b,F,x,E,O,_,j,w,A,L,k,I,T,N,P,R,K,D,U,J,G,M,V,H,B,W,q,Y,X,z=this;return i(this,(function(Q){switch(Q.label){case 0:d=c(a.evaluationContext||this.evaluationContext),Q.label=1;case 1:if(Q.trys.push([1,13,,14]),g=a.AsyncStorage,f=a._trigger,m=a._triggerLoadingState,S=a.angularHttpClient,C=a.api,b=void 0===C?y:C,F=a.applicationMetadata,x=a.cacheFlags,E=a.cacheOptions,O=a.datadogRum,_=a.defaultFlags,j=a.enableAnalytics,w=a.enableDynatrace,A=a.enableLogs,L=a.environmentID,k=a.eventSourceUrl,I=void 0===k?"https://realtime.flagsmith.com/":k,T=a.fetch,N=a.headers,P=a.identity,R=a.onChange,K=a.onError,D=a.preventFetch,U=a.realtime,J=a.sentryClient,G=a.state,M=a.traits,d.environment=L?{apiKey:L}:d.environment,!d.environment||!d.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(d.identity=P||M?{identifier:P,traits:M?Object.fromEntries(Object.entries(M).map((function(t){return[t[0],{value:t[1]}]}))):{}}:d.identity,this.evaluationContext=d,this.api=(Z=b).endsWith("/")?Z:Z+"/",this.headers=N,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=R,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=f||this._trigger,this._triggerLoadingState=m||this._triggerLoadingState,this.onError=function(t){z.setLoadingState(e(e({},z.loadingState),{isFetching:!1,isLoading:!1,error:t})),null==K||K(t)},this.enableLogs=A||!1,this.cacheOptions=E?{skipAPI:!!E.skipAPI,ttl:E.ttl||0,storageKey:E.storageKey,loadStale:!!E.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),T&&(v=T),this.enableAnalytics=j||!1,this.flags=Object.assign({},_)||{},this.datadogRum=O||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==h&&!!x,this.applicationMetadata=F,p="FLAGSMITH_EVENT_"+d.environment.apiKey,g&&(h=g),U&&"undefined"!=typeof window&&this.setupRealtime(I,d.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=e(e({},this.loadingState),{isLoading:!1,source:t.FlagSource.DEFAULT_FLAGS})),this.setState(G),this.log("Initialising with properties",a,this),w&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),S&&(v=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},l=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(l(t,!t.status||t.status>=200&&t.status<300))},s=function(t){return n(l(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,s);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,s);default:return s({status:405,message:"Unsupported method: ".concat(a)})}}))}}(S)),h&&this.canUseStorage&&h.getItem(p).then((function(t){try{z.evaluationEvent=JSON.parse(t)||{}}catch(t){z.evaluationEvent={}}z.analyticsInterval=setInterval(z.analyticsFlags,z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),h&&this.canUseStorage&&h.getItem(p,(function(t,n){if(n&&z.evaluationContext.environment){var i=JSON.parse(n);if(i[z.evaluationContext.environment.apiKey]){var a=z.getState();z.log("Retrieved events from cache",n),z.setState(e(e({},a),{evaluationEvent:i[z.evaluationContext.environment.apiKey]}))}}}))),!x)return[3,9];if(!h||!this.canUseStorage)return[3,8];H=function(a,o){return n(z,void 0,void 0,(function(){var n,a,l,s,u,d,v,g,h,f,p,y,m,S,C,b,F,x,E,O=this;return i(this,(function(i){switch(i.label){case 0:if(!o)return[3,7];n=null,a=null,i.label=1;case 1:return i.trys.push([1,5,,6]),l=JSON.parse(o),s=!1,u=!1,l&&l.api===this.api&&(null===(f=null===(h=l.evaluationContext)||void 0===h?void 0:h.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(d=!0,this.evaluationContext.identity&&(null===(m=null===(y=l.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=l.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),d=!1),this.cacheOptions.ttl&&(!l.ts||(new Date).valueOf()-l.ts>this.cacheOptions.ttl)&&(l.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+l.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-l.ts)+"ms"),d=!1):l.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+l.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-l.ts)+"ms"),u=!0,d=!0)),d&&(s=!0,n=r(this.flags,l.flags),this.setState(e(e({},l),{evaluationContext:c(e(e({},l.evaluationContext),{identity:(null===(b=l.evaluationContext)||void 0===b?void 0:b.identity)?e(e({},null===(F=l.evaluationContext)||void 0===F?void 0:F.identity),{traits:e({},M||{})}):void 0}))})),this.log("Retrieved flags from cache",l))),s?(v=!D&&(!this.cacheOptions.skipAPI||u),this._onChange(null,{isFromServer:!1,flagsChanged:n,traitsChanged:a},this._loadedState(null,t.FlagSource.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!u&&this.log("Skipping API, using cache"),v&&this.getFlags().catch((function(t){var e;null===(e=O.onError)||void 0===e||e.call(O,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:i.sent(),i.label=4;case 4:return[3,6];case 5:throw g=i.sent(),this.log("Exception fetching cached logs",g),g;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return i.sent(),[3,10];case 9:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(E=this.evaluationContext.identity)||void 0===E?void 0:E.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS))}i.label=10;case 10:return[2]}}))}))},Q.label=2;case 2:return Q.trys.push([2,7,,8]),h.getItemSync?(B=h.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,h.getItem(this.getStorageKey())];case 4:B=Q.sent(),Q.label=5;case 5:return[4,H(null,B)];case 6:return Q.sent(),[3,8];case 7:if(W=Q.sent(),!this.flags||0===Object.keys(this.flags).length)throw W;return X=W instanceof Error?W:new Error("".concat(W)),null===(o=this.onError)||void 0===o||o.call(this,X),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return Q.sent(),[3,12];case 11:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:r({},_),traitsChanged:r({},null===(l=d.identity)||void 0===l?void 0:l.traits)},this._loadedState(null,t.FlagSource.DEFAULT_FLAGS));else if(this.flags&&(q=null,0===Object.keys(this.flags).length&&(q=V),this._onChange(null,{isFromServer:!1,flagsChanged:r({},this.flags),traitsChanged:r({},null===(s=d.identity)||void 0===s?void 0:s.traits)},this._loadedState(q,t.FlagSource.DEFAULT_FLAGS)),q))throw new Error(q);Q.label=12;case 12:return[3,14];case 13:throw Y=Q.sent(),this.log("Error during initialisation ",Y),X=Y instanceof Error?Y:new Error("".concat(Y)),null===(u=this.onError)||void 0===u||u.call(this,X),Y;case 14:return[2]}var Z}))}))},d.prototype.getAllFlags=function(){return this.flags},d.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},d.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},d.prototype.setState=function(e){var n,i;e&&(this.initialised=!0,this.api=e.api||this.api||y,this.flags=e.flags||this.flags,this.evaluationContext=e.evaluationContext||this.evaluationContext,this.evaluationEvent=e.evaluationEvent||this.evaluationEvent,this.identity=null===(i=null===(n=this.getContext())||void 0===n?void 0:n.identity)||void 0===i?void 0:i.identifier,this.log("setState called",this),this.loadingState.source===t.FlagSource.NONE&&this.flags&&Object.keys(this.flags).length>0&&this.setLoadingState(this._loadedState(null,t.FlagSource.SERVER)))},d.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},d.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},d.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},d.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},d.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,a(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},d.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),h.setItem(this.getStorageKey(),t)}},d.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);h.setItem(p,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},d.prototype.setLoadingState=function(t){var n;o(t,this.loadingState)||(this.loadingState=e({},t),this.log("Loading state changed",t),null===(n=this._triggerLoadingState)||void 0===n||n.call(this))},d.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";g?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new g(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},d}();function F(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new b({fetch:e,AsyncStorage:n,eventSource:i})}var x=F({});t.createFlagsmithInstance=function(){return F({})},t.default=x,Object.defineProperty(t,"__esModule",{value:!0})}));
2
2
  //# sourceMappingURL=next-middleware.js.map
@@ -1,2 +1,2 @@
1
- var t=function(){return t=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},t.apply(this,arguments)};function e(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((i=i.apply(t,e||[])).next())}))}function n(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function i(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var a=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function o(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],o=null==e?void 0:e[n];return!a(i,o)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function r(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function s(t){return!!t&&"object"==typeof t&&void 0!==t.value}function l(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))}function u(e){return t(t({},e),{identity:e.identity?t(t({},e.identity),{traits:l(e.identity.traits||{})}):void 0})}var c,d;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(c||(c={}));var v,h=null,g="FLAGSMITH_EVENT",f="https://edge.api.flagsmith.com/api/v1/",p=function(){function p(e){var n=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var e=n,i=e.api,a=e.evaluationContext;n.log("Get Flags"),n.isLoading=!0,n.loadingState.isFetching||n.setLoadingState(t(t({},n.loadingState),{isFetching:!0}));var s="".concat(n.getContext().identity),l=function(e){var i,a,l,u;if(e&&s==="".concat(n.getContext().identity)){var d=e.flags,v=e.traits,h=e.identifier;n.isLoading=!1;var g={},f={};v=v||[],(d=d||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),v.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),n.oldFlags=t({},n.flags);var p=o(n.oldFlags,g),y=o(null===(i=n.evaluationContext.identity)||void 0===i?void 0:i.traits,f);if((h||Object.keys(f).length)&&(n.evaluationContext.identity=t(t({},n.evaluationContext.identity),{traits:f}),h&&(n.evaluationContext.identity.identifier=h,n.identity=h)),n.flags=g,n.updateStorage(),n._onChange(n.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},n._loadedState(null,c.SERVER)),n.datadogRum)try{if(n.datadogRum.trackTraits){var m={};Object.keys((null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.traits)||{}).map((function(t){m["flagsmith_trait_"+t]=n.getTrait(t)}));var S=t(t(t({},n.datadogRum.client.getUser()),{id:n.datadogRum.client.getUser().id||(null===(l=n.evaluationContext.identity)||void 0===l?void 0:l.identifier)}),m);n.log("Setting Datadog user",S),n.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(n.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(n.flags).map((function(t){r(C,"flagsmith_value_"+t,n.getValue(t,{skipAnalytics:!0})),r(C,"flagsmith_enabled_"+t,n.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(u=n.evaluationContext.identity)||void 0===u?void 0:u.traits)||{}).map((function(t){r(C,"flagsmith_trait_"+t,n.getTrait(t))})),n.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),n.log("Sending date traits to dynatrace",C.date),n.log("Sending shortString traits to dynatrace",C.shortString),n.log("Sending javaDouble to dynatrace",C.javaDouble),n.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return a.identity?Promise.all([a.identity.traits&&Object.keys(a.identity.traits).length||!a.identity.identifier?n.getJSON(i+"identities/","POST",JSON.stringify({identifier:a.identity.identifier,transient:a.identity.transient,traits:Object.entries(a.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(n.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):n.getJSON(i+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(e){return n.evaluationContext.identity=t(t({},n.evaluationContext.identity),{traits:{}}),l(null==e?void 0:e[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):n.getJSON(i+"flags/").then((function(t){return l({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var e=n.api;if(n.evaluationEvent&&n.evaluationContext.environment&&n.evaluationEvent[n.evaluationContext.environment.apiKey])return n.evaluationEvent&&0!==Object.getOwnPropertyNames(n.evaluationEvent).length&&0!==Object.getOwnPropertyNames(n.evaluationEvent[n.evaluationContext.environment.apiKey]).length?n.getJSON(e+"analytics/flags/","POST",JSON.stringify(n.evaluationEvent[n.evaluationContext.environment.apiKey])).then((function(e){if(n.evaluationContext.environment){var i=n.getState();n.evaluationEvent||(n.evaluationEvent={}),n.evaluationEvent[n.evaluationContext.environment.apiKey]={},n.setState(t(t({},i),{evaluationEvent:n.evaluationEvent})),n.updateEventStorage()}})).catch((function(t){n.log("Exception fetching evaluationEvent",t)})):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:c.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.getValue=function(t,e,i){var a=n.flags&&n.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(a&&(o=a.value),(null==e?void 0:e.skipAnalytics)||i||n.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(n.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,i;return(null===(e=n.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(i=n.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===i?void 0:i.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=n.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(e){var i,a,o=u(e);return n.evaluationContext=t(t({},o),{environment:o.environment||n.evaluationContext.environment}),n.identity=null===(a=null===(i=n.getContext())||void 0===i?void 0:i.identity)||void 0===a?void 0:a.identifier,n.initialised?n.getFlags():Promise.resolve()},this.getContext=function(){return n.evaluationContext},this.updateContext=function(e){return n.setContext(t(t({},n.getContext()),e))},this.setTrait=function(e,i){var a;if(n.api)return n.setContext(t(t({},n.evaluationContext),{identity:t(t({},n.evaluationContext.identity),{traits:t(t({},null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.traits),l(Object.fromEntries([[e,i]])))})}))},this.setTraits=function(e){var i;if(n.api)return n.setContext(t(t({},n.evaluationContext),{identity:t(t({},n.evaluationContext.identity),{traits:t(t({},null===(i=n.evaluationContext.identity)||void 0===i?void 0:i.traits),Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var i,a,o="object"==typeof e,r=n.flags&&n.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!r&&o&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!0),(o&&!e.skipAnalytics||!e)&&n.evaluateFlag(t,"ENABLED"),n.sentryClient)try{null===(a=null===(i=n.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===i?void 0:i.addFeatureFlag)||void 0===a||a.call(i,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=n.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=n.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,i){var a,o,r,s=n.headers,l={method:e||"GET",body:i,cache:"no-cache",headers:{}};n.evaluationContext.environment&&(l.headers["X-Environment-Key"]=n.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(a=n.applicationMetadata)||void 0===a?void 0:a.name)&&(l.headers["Flagsmith-Application-Name"]=n.applicationMetadata.name),(null===(o=n.applicationMetadata)||void 0===o?void 0:o.version)&&(l.headers["Flagsmith-Application-Version"]=n.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("12.0.0"),s&&Object.assign(l.headers,s),d||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=n.evaluationContext.identity)||void 0===r?void 0:r.identifier);return d(t,l).then((function(i){var a,o,r="".concat(null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.identifier);if(u===r){var s=null===(o=i.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");n.timestamp=l}catch(t){n.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return n.log("Fetch response: "+i.status+" "+(e||"GET")+0+t),i.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&i.status&&(e="API Response: ".concat(i.status)),i.status&&i.status>=200&&i.status<300?e:Promise.reject(new Error(e))}))}n.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(n.datadogRum&&(n.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?n.datadogRum.client.addFeatureFlagEvaluation("flagsmith_value_"+t,n.getValue(t,{},!0)):n.datadogRum.client.addFeatureFlagEvaluation("flagsmith_enabled_"+t,n.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),n.enableAnalytics){if(!n.evaluationEvent||!n.evaluationContext.environment)return;n.evaluationEvent[n.evaluationContext.environment.apiKey]||(n.evaluationEvent[n.evaluationContext.environment.apiKey]={}),void 0===n.evaluationEvent[n.evaluationContext.environment.apiKey][t]&&(n.evaluationEvent[n.evaluationContext.environment.apiKey][t]=0),n.evaluationEvent[n.evaluationContext.environment.apiKey][t]+=1}n.updateEventStorage()},this._onChange=function(t,e,i){var a,o;n.setLoadingState(i),null===(a=n.onChange)||void 0===a||a.call(n,t,e,n.loadingState),null===(o=n._trigger)||void 0===o||o.call(n)},d=e.fetch?e.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!e.browserlessStorage,this.applicationMetadata=e.applicationMetadata,this.log("Constructing flagsmith instance "+e),e.eventSource&&(v=e.eventSource),e.AsyncStorage&&(h=e.AsyncStorage)}return p.prototype.init=function(i){var a,r,s,l;return e(this,void 0,void 0,(function(){var v,p,y,m,S,C,b,E,x,O,F,_,w,A,j,L,k,I,N,T,R,P,K,D,U,J,G,M,V,H,B,W,q,Y,X,z=this;return n(this,(function(Q){switch(Q.label){case 0:v=u(i.evaluationContext||this.evaluationContext),Q.label=1;case 1:if(Q.trys.push([1,13,,14]),p=i.AsyncStorage,y=i._trigger,m=i._triggerLoadingState,S=i.angularHttpClient,C=i.api,b=void 0===C?f:C,E=i.applicationMetadata,x=i.cacheFlags,O=i.cacheOptions,F=i.datadogRum,_=i.defaultFlags,w=i.enableAnalytics,A=i.enableDynatrace,j=i.enableLogs,L=i.environmentID,k=i.eventSourceUrl,I=void 0===k?"https://realtime.flagsmith.com/":k,N=i.fetch,T=i.headers,R=i.identity,P=i.onChange,K=i.onError,D=i.preventFetch,U=i.realtime,J=i.sentryClient,G=i.state,M=i.traits,v.environment=L?{apiKey:L}:v.environment,!v.environment||!v.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(v.identity=R||M?{identifier:R,traits:M?Object.fromEntries(Object.entries(M).map((function(t){return[t[0],{value:t[1]}]}))):{}}:v.identity,this.evaluationContext=v,this.api=(Z=b).endsWith("/")?Z:Z+"/",this.headers=T,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=P,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=y||this._trigger,this._triggerLoadingState=m||this._triggerLoadingState,this.onError=function(e){z.setLoadingState(t(t({},z.loadingState),{isFetching:!1,isLoading:!1,error:e})),null==K||K(e)},this.enableLogs=j||!1,this.cacheOptions=O?{skipAPI:!!O.skipAPI,ttl:O.ttl||0,storageKey:O.storageKey,loadStale:!!O.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),N&&(d=N),this.enableAnalytics=w||!1,this.flags=Object.assign({},_)||{},this.datadogRum=F||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==h&&!!x,this.applicationMetadata=E,g="FLAGSMITH_EVENT_"+v.environment.apiKey,p&&(h=p),U&&"undefined"!=typeof window&&this.setupRealtime(I,v.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=t(t({},this.loadingState),{isLoading:!1,source:c.DEFAULT_FLAGS})),this.setState(G),this.log("Initialising with properties",i,this),A&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),S&&(d=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(S)),h&&this.canUseStorage&&h.getItem(g).then((function(t){try{z.evaluationEvent=JSON.parse(t)||{}}catch(t){z.evaluationEvent={}}z.analyticsInterval=setInterval(z.analyticsFlags,z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),h&&this.canUseStorage&&h.getItem(g,(function(e,n){if(n&&z.evaluationContext.environment){var i=JSON.parse(n);if(i[z.evaluationContext.environment.apiKey]){var a=z.getState();z.log("Retrieved events from cache",n),z.setState(t(t({},a),{evaluationEvent:i[z.evaluationContext.environment.apiKey]}))}}}))),!x)return[3,9];if(!h||!this.canUseStorage)return[3,8];H=function(i,a){return e(z,void 0,void 0,(function(){var e,i,r,s,l,d,v,h,g,f,p,y,m,S,C,b,E,x,O,F=this;return n(this,(function(n){switch(n.label){case 0:if(!a)return[3,7];e=null,i=null,n.label=1;case 1:return n.trys.push([1,5,,6]),r=JSON.parse(a),s=!1,l=!1,r&&r.api===this.api&&(null===(f=null===(g=r.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(d=!0,this.evaluationContext.identity&&(null===(m=null===(y=r.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=r.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),d=!1),this.cacheOptions.ttl&&(!r.ts||(new Date).valueOf()-r.ts>this.cacheOptions.ttl)&&(r.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),d=!1):r.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),l=!0,d=!0)),d&&(s=!0,e=o(this.flags,r.flags),this.setState(t(t({},r),{evaluationContext:u(t(t({},r.evaluationContext),{identity:(null===(b=r.evaluationContext)||void 0===b?void 0:b.identity)?t(t({},null===(E=r.evaluationContext)||void 0===E?void 0:E.identity),{traits:t({},M||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),s?(v=!D&&(!this.cacheOptions.skipAPI||l),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,c.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!l&&this.log("Skipping API, using cache"),v&&this.getFlags().catch((function(t){var e;null===(e=F.onError)||void 0===e||e.call(F,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:n.sent(),n.label=4;case 4:return[3,6];case 5:throw h=n.sent(),this.log("Exception fetching cached logs",h),h;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return n.sent(),[3,10];case 9:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:o({},this.flags),traitsChanged:o({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,c.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);this._onChange(null,{isFromServer:!1,flagsChanged:o({},this.flags),traitsChanged:o({},null===(O=this.evaluationContext.identity)||void 0===O?void 0:O.traits)},this._loadedState(null,c.DEFAULT_FLAGS))}n.label=10;case 10:return[2]}}))}))},Q.label=2;case 2:return Q.trys.push([2,7,,8]),h.getItemSync?(B=h.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,h.getItem(this.getStorageKey())];case 4:B=Q.sent(),Q.label=5;case 5:return[4,H(null,B)];case 6:return Q.sent(),[3,8];case 7:if(W=Q.sent(),!this.flags||0===Object.keys(this.flags).length)throw W;return X=W instanceof Error?W:new Error("".concat(W)),null===(a=this.onError)||void 0===a||a.call(this,X),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return Q.sent(),[3,12];case 11:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:o({},_),traitsChanged:o({},null===(r=v.identity)||void 0===r?void 0:r.traits)},this._loadedState(null,c.DEFAULT_FLAGS));else if(this.flags&&(q=null,0===Object.keys(this.flags).length&&(q=V),this._onChange(null,{isFromServer:!1,flagsChanged:o({},this.flags),traitsChanged:o({},null===(s=v.identity)||void 0===s?void 0:s.traits)},this._loadedState(q,c.DEFAULT_FLAGS)),q))throw new Error(q);Q.label=12;case 12:return[3,14];case 13:throw Y=Q.sent(),this.log("Error during initialisation ",Y),X=Y instanceof Error?Y:new Error("".concat(Y)),null===(l=this.onError)||void 0===l||l.call(this,X),Y;case 14:return[2]}var Z}))}))},p.prototype.getAllFlags=function(){return this.flags},p.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},p.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},p.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||f,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this),this.loadingState.source===c.NONE&&this.flags&&Object.keys(this.flags).length>0&&this.setLoadingState(this._loadedState(null,c.SERVER)))},p.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},p.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},p.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},p.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},p.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,i(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},p.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),h.setItem(this.getStorageKey(),t)}},p.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);h.setItem(g,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},p.prototype.setLoadingState=function(e){var n;a(e,this.loadingState)||(this.loadingState=t({},e),this.log("Loading state changed",e),null===(n=this._triggerLoadingState)||void 0===n||n.call(this))},p.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";v?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new v(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},p}();function y(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new p({fetch:e,AsyncStorage:n,eventSource:i})}var m=y({}),S=function(){return y({})};export{c as FlagSource,S as createFlagsmithInstance,m as default};
1
+ var t=function(){return t=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++)for(var a in e=arguments[n])Object.prototype.hasOwnProperty.call(e,a)&&(t[a]=e[a]);return t},t.apply(this,arguments)};function e(t,e,n,i){return new(n||(n=Promise))((function(a,o){function r(t){try{l(i.next(t))}catch(t){o(t)}}function s(t){try{l(i.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?a(t.value):(e=t.value,e instanceof n?e:new n((function(t){t(e)}))).then(r,s)}l((i=i.apply(t,e||[])).next())}))}function n(t,e){var n,i,a,o,r={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(a=2&o[0]?i.return:o[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,o[1])).done)return a;switch(i=0,a&&(o=[2&o[0],a.value]),o[0]){case 0:case 1:a=o;break;case 4:return r.label++,{value:o[1],done:!1};case 5:r.label++,i=o[1],o=[0];continue;case 7:o=r.ops.pop(),r.trys.pop();continue;default:if(!(a=r.trys,(a=a.length>0&&a[a.length-1])||6!==o[0]&&2!==o[0])){r=0;continue}if(3===o[0]&&(!a||o[1]>a[0]&&o[1]<a[3])){r.label=o[1];break}if(6===o[0]&&r.label<a[1]){r.label=a[1],a=o;break}if(a&&r.label<a[2]){r.label=a[2],r.ops.push(o);break}a[2]&&r.ops.pop(),r.trys.pop();continue}o=e.call(t,r)}catch(t){o=[6,t],i=0}finally{n=a=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,s])}}}function i(t,e,n){if(n||2===arguments.length)for(var i,a=0,o=e.length;a<o;a++)!i&&a in e||(i||(i=Array.prototype.slice.call(e,0,a)),i[a]=e[a]);return t.concat(i||Array.prototype.slice.call(e))}var a=function t(e,n){if(e===n)return!0;if(e&&n&&"object"==typeof e&&"object"==typeof n){if(e.constructor!==n.constructor)return!1;var i,a,o;if(Array.isArray(e)){if((i=e.length)!=n.length)return!1;for(a=i;0!=a--;)if(!t(e[a],n[a]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if((i=(o=Object.keys(e)).length)!==Object.keys(n).length)return!1;for(a=i;0!=a--;)if(!Object.prototype.hasOwnProperty.call(n,o[a]))return!1;for(a=i;0!=a--;){var r=o[a];if(!t(e[r],n[r]))return!1}return!0}return e!=e&&n!=n};function o(t,e){var n=Object.keys(e||{}).filter((function(n){var i=null==t?void 0:t[n],o=null==e?void 0:e[n];return!a(i,o)}));return Object.keys(t||{}).filter((function(t){Object.keys(e||{}).includes(t)||n.push(t)})),Object.keys(n).length?n:null}function r(t,e,n){var i="shortString",a=!0;"number"==typeof n&&(i="javaDouble",a=!1),t[i]=t[i]||{},t[i][e]=a?n+"":n}function s(t){return!!t&&"object"==typeof t&&void 0!==t.value}function l(t){return Object.fromEntries(Object.entries(t).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))}function u(e){return t(t({},e),{identity:e.identity?t(t({},e.identity),{traits:l(e.identity.traits||{})}):void 0})}var c,d;!function(t){t.NONE="NONE",t.DEFAULT_FLAGS="DEFAULT_FLAGS",t.CACHE="CACHE",t.SERVER="SERVER"}(c||(c={}));var v,h=null,g="FLAGSMITH_EVENT",f="https://edge.api.flagsmith.com/api/v1/",p=function(){function p(e){var n=this;this._trigger=null,this._triggerLoadingState=null,this.timestamp=null,this.isLoading=!1,this.eventSource=null,this.getFlags=function(){var e=n,i=e.api,a=e.evaluationContext;n.log("Get Flags"),n.isLoading=!0,n.loadingState.isFetching||n.setLoadingState(t(t({},n.loadingState),{isFetching:!0}));var s="".concat(n.getContext().identity),l=function(e){var i,a,l,u;if(e&&s==="".concat(n.getContext().identity)){var d=e.flags,v=e.traits,h=e.identifier;n.isLoading=!1;var g={},f={};v=v||[],(d=d||[]).forEach((function(t){g[t.feature.name.toLowerCase().replace(/ /g,"_")]={id:t.feature.id,enabled:t.enabled,value:t.feature_state_value}})),v.forEach((function(t){f[t.trait_key.toLowerCase().replace(/ /g,"_")]={transient:t.transient,value:t.trait_value}})),n.oldFlags=t({},n.flags);var p=o(n.oldFlags,g),y=o(null===(i=n.evaluationContext.identity)||void 0===i?void 0:i.traits,f);if((h||Object.keys(f).length)&&(n.evaluationContext.identity=t(t({},n.evaluationContext.identity),{traits:f}),h&&(n.evaluationContext.identity.identifier=h,n.identity=h)),n.flags=g,n.updateStorage(),n._onChange(n.oldFlags,{isFromServer:!0,flagsChanged:p,traitsChanged:y},n._loadedState(null,c.SERVER)),n.datadogRum)try{if(n.datadogRum.trackTraits){var m={};Object.keys((null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.traits)||{}).map((function(t){m["flagsmith_trait_"+t]=n.getTrait(t)}));var S=t(t(t({},n.datadogRum.client.getUser()),{id:n.datadogRum.client.getUser().id||(null===(l=n.evaluationContext.identity)||void 0===l?void 0:l.identifier)}),m);n.log("Setting Datadog user",S),n.datadogRum.client.setUser(S)}}catch(t){console.error(t)}if(n.dtrum)try{var C={javaDouble:{},date:{},shortString:{},javaLongOrObject:{}};Object.keys(n.flags).map((function(t){r(C,"flagsmith_value_"+t,n.getValue(t,{skipAnalytics:!0})),r(C,"flagsmith_enabled_"+t,n.hasFeature(t,{skipAnalytics:!0}))})),Object.keys((null===(u=n.evaluationContext.identity)||void 0===u?void 0:u.traits)||{}).map((function(t){r(C,"flagsmith_trait_"+t,n.getTrait(t))})),n.log("Sending javaLongOrObject traits to dynatrace",C.javaLongOrObject),n.log("Sending date traits to dynatrace",C.date),n.log("Sending shortString traits to dynatrace",C.shortString),n.log("Sending javaDouble to dynatrace",C.javaDouble),n.dtrum.sendSessionProperties(C.javaLongOrObject,C.date,C.shortString,C.javaDouble)}catch(t){console.error(t)}}};return a.identity?Promise.all([a.identity.traits&&Object.keys(a.identity.traits).length||!a.identity.identifier?n.getJSON(i+"identities/","POST",JSON.stringify({identifier:a.identity.identifier,transient:a.identity.transient,traits:Object.entries(a.identity.traits).map((function(t){var e=t[0],n=t[1];return{trait_key:e,trait_value:null==n?void 0:n.value,transient:null==n?void 0:n.transient}})).filter((function(t){return void 0!==t.trait_value||(n.log("Warning - attempted to set an undefined trait value for key",t.trait_key),!1)}))})):n.getJSON(i+"identities/?identifier="+encodeURIComponent(a.identity.identifier)+(a.identity.transient?"&transient=true":""))]).then((function(e){return n.evaluationContext.identity=t(t({},n.evaluationContext.identity),{traits:{}}),l(null==e?void 0:e[0])})).catch((function(t){var e=t.message,n=new Error(e);return Promise.reject(n)})):n.getJSON(i+"flags/").then((function(t){return l({flags:t,traits:void 0})}))},this.analyticsFlags=function(){var e=n.api;if(n.evaluationEvent&&n.evaluationContext.environment&&n.evaluationEvent[n.evaluationContext.environment.apiKey])return n.evaluationEvent&&0!==Object.getOwnPropertyNames(n.evaluationEvent).length&&0!==Object.getOwnPropertyNames(n.evaluationEvent[n.evaluationContext.environment.apiKey]).length?n.getJSON(e+"analytics/flags/","POST",JSON.stringify(n.evaluationEvent[n.evaluationContext.environment.apiKey])).then((function(e){if(n.evaluationContext.environment){var i=n.getState();n.evaluationEvent||(n.evaluationEvent={}),n.evaluationEvent[n.evaluationContext.environment.apiKey]={},n.setState(t(t({},i),{evaluationEvent:n.evaluationEvent})),n.updateEventStorage()}})).catch((function(t){n.log("Exception fetching evaluationEvent",t)})):void 0},this.datadogRum=null,this.loadingState={isLoading:!0,isFetching:!0,error:null,source:c.NONE},this.canUseStorage=!1,this.analyticsInterval=null,this.api=null,this.cacheFlags=!1,this.enableAnalytics=!1,this.enableLogs=!1,this.evaluationContext={},this.evaluationEvent=null,this.flags=null,this.getFlagInterval=null,this.headers=null,this.identity=null,this.initialised=!1,this.oldFlags=null,this.onChange=null,this.onError=null,this.ticks=null,this.timer=null,this.dtrum=null,this.sentryClient=null,this.withTraits=null,this.cacheOptions={ttl:0,skipAPI:!1,loadStale:!1,storageKey:void 0},this.getValue=function(t,e,i){var a=n.flags&&n.flags[t.toLowerCase().replace(/ /g,"_")],o=null;if(a&&(o=a.value),(null==e?void 0:e.skipAnalytics)||i||n.evaluateFlag(t,"VALUE"),null===o&&void 0!==(null==e?void 0:e.fallback))return e.fallback;if(null==e?void 0:e.json)try{return null===o?(n.log("Tried to parse null flag as JSON: "+t),null):JSON.parse(o)}catch(t){return e.fallback}return o},this.getTrait=function(t){var e,i;return(null===(e=n.evaluationContext.identity)||void 0===e?void 0:e.traits)&&(null===(i=n.evaluationContext.identity.traits[t.toLowerCase().replace(/ /g,"_")])||void 0===i?void 0:i.value)},this.getAllTraits=function(){var t;return Object.fromEntries(Object.entries((null===(t=n.evaluationContext.identity)||void 0===t?void 0:t.traits)||{}).map((function(t){var e=t[0],n=t[1];return[e,null==n?void 0:n.value]})))},this.setContext=function(e){var i,a,o=u(e);return n.evaluationContext=t(t({},o),{environment:o.environment||n.evaluationContext.environment}),n.identity=null===(a=null===(i=n.getContext())||void 0===i?void 0:i.identity)||void 0===a?void 0:a.identifier,n.initialised?n.getFlags():Promise.resolve()},this.getContext=function(){return n.evaluationContext},this.updateContext=function(e){return n.setContext(t(t({},n.getContext()),e))},this.setTrait=function(e,i){var a;if(n.api)return n.setContext(t(t({},n.evaluationContext),{identity:t(t({},n.evaluationContext.identity),{traits:t(t({},null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.traits),l(Object.fromEntries([[e,i]])))})}))},this.setTraits=function(e){var i;if(n.api)return n.setContext(t(t({},n.evaluationContext),{identity:t(t({},n.evaluationContext.identity),{traits:t(t({},null===(i=n.evaluationContext.identity)||void 0===i?void 0:i.traits),Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]}))))})}));console.error("Attempted to "+"setTraits"+" a user before calling flagsmith.init. Call flagsmith.init first, if you wish to prevent it sending a request for flags, call init with preventFetch:true.")},this.hasFeature=function(t,e){var i,a,o="object"==typeof e,r=n.flags&&n.flags[t.toLowerCase().replace(/ /g,"_")],s=!1;if(!r&&o&&void 0!==e.fallback?s=null==e?void 0:e.fallback:r&&r.enabled&&(s=!0),(o&&!e.skipAnalytics||!e)&&n.evaluateFlag(t,"ENABLED"),n.sentryClient)try{null===(a=null===(i=n.sentryClient.getIntegrationByName("FeatureFlags"))||void 0===i?void 0:i.addFeatureFlag)||void 0===a||a.call(i,t,s)}catch(t){console.error(t)}return s},this.getStorageKey=function(){var t,e;return(null===(t=n.cacheOptions)||void 0===t?void 0:t.storageKey)||"FLAGSMITH_DB_"+(null===(e=n.evaluationContext.environment)||void 0===e?void 0:e.apiKey)},this.getJSON=function(t,e,i){var a,o,r,s=n.headers,l={method:e||"GET",body:i,cache:"no-cache",headers:{}};n.evaluationContext.environment&&(l.headers["X-Environment-Key"]=n.evaluationContext.environment.apiKey),e&&"GET"!==e&&(l.headers["Content-Type"]="application/json; charset=utf-8"),(null===(a=n.applicationMetadata)||void 0===a?void 0:a.name)&&(l.headers["Flagsmith-Application-Name"]=n.applicationMetadata.name),(null===(o=n.applicationMetadata)||void 0===o?void 0:o.version)&&(l.headers["Flagsmith-Application-Version"]=n.applicationMetadata.version),l.headers["Flagsmith-SDK-User-Agent"]="flagsmith-js-sdk/".concat("12.0.1"),s&&Object.assign(l.headers,s),d||console.error("Flagsmith: fetch is undefined, please specify a fetch implementation into flagsmith.init to support SSR.");var u="".concat(null===(r=n.evaluationContext.identity)||void 0===r?void 0:r.identifier);return d(t,l).then((function(i){var a,o,r="".concat(null===(a=n.evaluationContext.identity)||void 0===a?void 0:a.identifier);if(u===r){var s=null===(o=i.headers)||void 0===o?void 0:o.get("x-flagsmith-document-updated-at");if(s)try{var l=parseFloat(s);if(isNaN(l))return Promise.reject("Failed to parse x-flagsmith-document-updated-at");n.timestamp=l}catch(t){n.log(t,"Failed to parse x-flagsmith-document-updated-at",s)}return n.log("Fetch response: "+i.status+" "+(e||"GET")+0+t),i.text().then((function(t){var e=t;try{e=JSON.parse(t)}catch(t){}return!e&&i.status&&(e="API Response: ".concat(i.status)),i.status&&i.status>=200&&i.status<300?e:Promise.reject(new Error(e))}))}n.log("Received response with identity mismatch, ignoring response. Requested: ".concat(u,", Current: ").concat(r))}))},this.evaluateFlag=function(t,e){if(n.datadogRum&&(n.datadogRum.client.addFeatureFlagEvaluation?"VALUE"===e?n.datadogRum.client.addFeatureFlagEvaluation("flagsmith_value_"+t,n.getValue(t,{},!0)):n.datadogRum.client.addFeatureFlagEvaluation("flagsmith_enabled_"+t,n.hasFeature(t,!0)):console.error("Flagsmith: Your datadog RUM client does not support the function addFeatureFlagEvaluation, please update it.")),n.enableAnalytics){if(!n.evaluationEvent||!n.evaluationContext.environment)return;n.evaluationEvent[n.evaluationContext.environment.apiKey]||(n.evaluationEvent[n.evaluationContext.environment.apiKey]={}),void 0===n.evaluationEvent[n.evaluationContext.environment.apiKey][t]&&(n.evaluationEvent[n.evaluationContext.environment.apiKey][t]=0),n.evaluationEvent[n.evaluationContext.environment.apiKey][t]+=1}n.updateEventStorage()},this._onChange=function(t,e,i){var a,o;n.setLoadingState(i),null===(a=n.onChange)||void 0===a||a.call(n,t,e,n.loadingState),null===(o=n._trigger)||void 0===o||o.call(n)},d=e.fetch?e.fetch:"undefined"!=typeof fetch?fetch:null===global||void 0===global?void 0:global.fetch,this.canUseStorage="undefined"!=typeof window||!!e.browserlessStorage,this.applicationMetadata=e.applicationMetadata,this.log("Constructing flagsmith instance "+e),e.eventSource&&(v=e.eventSource),e.AsyncStorage&&(h=e.AsyncStorage)}return p.prototype.init=function(i){var a,r,s,l;return e(this,void 0,void 0,(function(){var v,p,y,m,S,C,b,E,x,O,F,_,w,A,j,L,k,I,N,T,R,P,K,D,U,J,G,M,V,H,B,W,q,Y,X,z=this;return n(this,(function(Q){switch(Q.label){case 0:v=u(i.evaluationContext||this.evaluationContext),Q.label=1;case 1:if(Q.trys.push([1,13,,14]),p=i.AsyncStorage,y=i._trigger,m=i._triggerLoadingState,S=i.angularHttpClient,C=i.api,b=void 0===C?f:C,E=i.applicationMetadata,x=i.cacheFlags,O=i.cacheOptions,F=i.datadogRum,_=i.defaultFlags,w=i.enableAnalytics,A=i.enableDynatrace,j=i.enableLogs,L=i.environmentID,k=i.eventSourceUrl,I=void 0===k?"https://realtime.flagsmith.com/":k,N=i.fetch,T=i.headers,R=i.identity,P=i.onChange,K=i.onError,D=i.preventFetch,U=i.realtime,J=i.sentryClient,G=i.state,M=i.traits,v.environment=L?{apiKey:L}:v.environment,!v.environment||!v.environment.apiKey)throw new Error("Please provide `evaluationContext.environment` with non-empty `apiKey`");if(v.identity=R||M?{identifier:R,traits:M?Object.fromEntries(Object.entries(M).map((function(t){return[t[0],{value:t[1]}]}))):{}}:v.identity,this.evaluationContext=v,this.api=(Z=b).endsWith("/")?Z:Z+"/",this.headers=T,this.getFlagInterval=null,this.analyticsInterval=null,this.onChange=P,V="Wrong Flagsmith Configuration: preventFetch is true and no defaulFlags provided",this._trigger=y||this._trigger,this._triggerLoadingState=m||this._triggerLoadingState,this.onError=function(e){z.setLoadingState(t(t({},z.loadingState),{isFetching:!1,isLoading:!1,error:e})),null==K||K(e)},this.enableLogs=j||!1,this.cacheOptions=O?{skipAPI:!!O.skipAPI,ttl:O.ttl||0,storageKey:O.storageKey,loadStale:!!O.loadStale}:this.cacheOptions,!this.cacheOptions.ttl&&this.cacheOptions.skipAPI&&console.warn("Flagsmith: you have set a cache ttl of 0 and are skipping API calls, this means the API will not be hit unless you clear local storage."),N&&(d=N),this.enableAnalytics=w||!1,this.flags=Object.assign({},_)||{},this.datadogRum=F||null,this.initialised=!0,this.ticks=1e4,this.timer=this.enableLogs?(new Date).valueOf():null,this.cacheFlags=void 0!==h&&!!x,this.applicationMetadata=E,g="FLAGSMITH_EVENT_"+v.environment.apiKey,p&&(h=p),U&&"undefined"!=typeof window&&this.setupRealtime(I,v.environment.apiKey),Object.keys(this.flags).length&&(this.loadingState=t(t({},this.loadingState),{isLoading:!1,source:c.DEFAULT_FLAGS})),this.setState(G),this.log("Initialising with properties",i,this),A&&("undefined"==typeof dtrum?console.error("You have attempted to enable dynatrace but dtrum is undefined, please check you have the Dynatrace RUM JavaScript API installed."):this.dtrum=dtrum),J&&(this.sentryClient=J),S&&(d=function(t){return function(e,n){var i=n.headers,a=n.method,o=n.body,r={headers:i,observe:"response",responseType:"text"},s=function(t,e){var n=t.status,i=t.headers,a=t.body,o=t.error,r=t.message;return{status:null!=n?n:e?200:500,ok:e,headers:{get:function(t){var e,n;return null!==(n=null===(e=null==i?void 0:i.get)||void 0===e?void 0:e.call(i,t))&&void 0!==n?n:null}},text:function(){var t,e,n=null!==(e=null!==(t=null!=a?a:o)&&void 0!==t?t:r)&&void 0!==e?e:"";return Promise.resolve("string"!=typeof n?JSON.stringify(n):n)}}};return new Promise((function(n){var i=function(t){return n(s(t,!t.status||t.status>=200&&t.status<300))},l=function(t){return n(s(t,!1))};switch(a){case"GET":return t.get(e,r).subscribe(i,l);case"POST":case"PUT":return t.post(e,null!=o?o:"",r).subscribe(i,l);default:return l({status:405,message:"Unsupported method: ".concat(a)})}}))}}(S)),h&&this.canUseStorage&&h.getItem(g).then((function(t){try{z.evaluationEvent=JSON.parse(t)||{}}catch(t){z.evaluationEvent={}}z.analyticsInterval=setInterval(z.analyticsFlags,z.ticks)})),this.enableAnalytics&&(this.analyticsInterval&&clearInterval(this.analyticsInterval),h&&this.canUseStorage&&h.getItem(g,(function(e,n){if(n&&z.evaluationContext.environment){var i=JSON.parse(n);if(i[z.evaluationContext.environment.apiKey]){var a=z.getState();z.log("Retrieved events from cache",n),z.setState(t(t({},a),{evaluationEvent:i[z.evaluationContext.environment.apiKey]}))}}}))),!x)return[3,9];if(!h||!this.canUseStorage)return[3,8];H=function(i,a){return e(z,void 0,void 0,(function(){var e,i,r,s,l,d,v,h,g,f,p,y,m,S,C,b,E,x,O,F=this;return n(this,(function(n){switch(n.label){case 0:if(!a)return[3,7];e=null,i=null,n.label=1;case 1:return n.trys.push([1,5,,6]),r=JSON.parse(a),s=!1,l=!1,r&&r.api===this.api&&(null===(f=null===(g=r.evaluationContext)||void 0===g?void 0:g.environment)||void 0===f?void 0:f.apiKey)===(null===(p=this.evaluationContext.environment)||void 0===p?void 0:p.apiKey)&&(d=!0,this.evaluationContext.identity&&(null===(m=null===(y=r.evaluationContext)||void 0===y?void 0:y.identity)||void 0===m?void 0:m.identifier)!==this.evaluationContext.identity.identifier&&(this.log("Ignoring cache, identity has changed from "+(null===(C=null===(S=r.evaluationContext)||void 0===S?void 0:S.identity)||void 0===C?void 0:C.identifier)+" to "+this.evaluationContext.identity.identifier),d=!1),this.cacheOptions.ttl&&(!r.ts||(new Date).valueOf()-r.ts>this.cacheOptions.ttl)&&(r.ts&&!this.cacheOptions.loadStale?(this.log("Ignoring cache, timestamp is too old ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),d=!1):r.ts&&this.cacheOptions.loadStale&&(this.log("Loading stale cache, timestamp ts:"+r.ts+" ttl: "+this.cacheOptions.ttl+" time elapsed since cache: "+((new Date).valueOf()-r.ts)+"ms"),l=!0,d=!0)),d&&(s=!0,e=o(this.flags,r.flags),this.setState(t(t({},r),{evaluationContext:u(t(t({},r.evaluationContext),{identity:(null===(b=r.evaluationContext)||void 0===b?void 0:b.identity)?t(t({},null===(E=r.evaluationContext)||void 0===E?void 0:E.identity),{traits:t({},M||{})}):void 0}))})),this.log("Retrieved flags from cache",r))),s?(v=!D&&(!this.cacheOptions.skipAPI||l),this._onChange(null,{isFromServer:!1,flagsChanged:e,traitsChanged:i},this._loadedState(null,c.CACHE,v)),this.oldFlags=this.flags,this.cacheOptions.skipAPI&&s&&!l&&this.log("Skipping API, using cache"),v&&this.getFlags().catch((function(t){var e;null===(e=F.onError)||void 0===e||e.call(F,t)})),[3,4]):[3,2];case 2:return D?[3,4]:[4,this.getFlags()];case 3:n.sent(),n.label=4;case 4:return[3,6];case 5:throw h=n.sent(),this.log("Exception fetching cached logs",h),h;case 6:return[3,10];case 7:return D?[3,9]:[4,this.getFlags()];case 8:return n.sent(),[3,10];case 9:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:o({},this.flags),traitsChanged:o({},null===(x=this.evaluationContext.identity)||void 0===x?void 0:x.traits)},this._loadedState(null,c.DEFAULT_FLAGS));else{if(!this.flags)throw new Error(V);this._onChange(null,{isFromServer:!1,flagsChanged:o({},this.flags),traitsChanged:o({},null===(O=this.evaluationContext.identity)||void 0===O?void 0:O.traits)},this._loadedState(null,c.DEFAULT_FLAGS))}n.label=10;case 10:return[2]}}))}))},Q.label=2;case 2:return Q.trys.push([2,7,,8]),h.getItemSync?(B=h.getItemSync(this.getStorageKey()),[3,5]):[3,3];case 3:return[4,h.getItem(this.getStorageKey())];case 4:B=Q.sent(),Q.label=5;case 5:return[4,H(null,B)];case 6:return Q.sent(),[3,8];case 7:if(W=Q.sent(),!this.flags||0===Object.keys(this.flags).length)throw W;return X=W instanceof Error?W:new Error("".concat(W)),null===(a=this.onError)||void 0===a||a.call(this,X),[3,8];case 8:return[3,12];case 9:return D?[3,11]:[4,this.getFlags()];case 10:return Q.sent(),[3,12];case 11:if(_)this._onChange(null,{isFromServer:!1,flagsChanged:o({},_),traitsChanged:o({},null===(r=v.identity)||void 0===r?void 0:r.traits)},this._loadedState(null,c.DEFAULT_FLAGS));else if(this.flags&&(q=null,0===Object.keys(this.flags).length&&(q=V),this._onChange(null,{isFromServer:!1,flagsChanged:o({},this.flags),traitsChanged:o({},null===(s=v.identity)||void 0===s?void 0:s.traits)},this._loadedState(q,c.DEFAULT_FLAGS)),q))throw new Error(q);Q.label=12;case 12:return[3,14];case 13:throw Y=Q.sent(),this.log("Error during initialisation ",Y),X=Y instanceof Error?Y:new Error("".concat(Y)),null===(l=this.onError)||void 0===l||l.call(this,X),Y;case 14:return[2]}var Z}))}))},p.prototype.getAllFlags=function(){return this.flags},p.prototype.identify=function(t,e,n){return this.identity=t,this.evaluationContext.identity={identifier:t,transient:n,traits:this.evaluationContext.identity&&this.evaluationContext.identity.identifier==t?this.evaluationContext.identity.traits:{}},this.evaluationContext.identity.identifier=t,this.log("Identify: "+this.evaluationContext.identity.identifier),e&&(this.evaluationContext.identity.traits=Object.fromEntries(Object.entries(e).map((function(t){var e=t[0],n=t[1];return[e,s(n)?n:{value:n}]})))),this.initialised?this.getFlags():Promise.resolve()},p.prototype.getState=function(){return{api:this.api,flags:this.flags,ts:this.ts,evaluationContext:this.evaluationContext,identity:this.identity,evaluationEvent:this.evaluationEvent}},p.prototype.setState=function(t){var e,n;t&&(this.initialised=!0,this.api=t.api||this.api||f,this.flags=t.flags||this.flags,this.evaluationContext=t.evaluationContext||this.evaluationContext,this.evaluationEvent=t.evaluationEvent||this.evaluationEvent,this.identity=null===(n=null===(e=this.getContext())||void 0===e?void 0:e.identity)||void 0===n?void 0:n.identifier,this.log("setState called",this),this.loadingState.source===c.NONE&&this.flags&&Object.keys(this.flags).length>0&&this.setLoadingState(this._loadedState(null,c.SERVER)))},p.prototype.logout=function(){return this.identity=null,this.evaluationContext.identity=null,this.initialised?this.getFlags():Promise.resolve()},p.prototype.startListening=function(t){void 0===t&&(t=1e3),this.getFlagInterval&&clearInterval(this.getFlagInterval),this.getFlagInterval=setInterval(this.getFlags,t)},p.prototype.stopListening=function(){this.getFlagInterval&&(clearInterval(this.getFlagInterval),this.getFlagInterval=null)},p.prototype._loadedState=function(t,e,n){return void 0===t&&(t=null),void 0===n&&(n=!1),{error:t,isFetching:n,isLoading:!1,source:e}},p.prototype.log=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];this.enableLogs&&console.log.apply(this,i(["FLAGSMITH:",(new Date).valueOf()-(this.timer||0),"ms"],t,!0))},p.prototype.updateStorage=function(){if(this.cacheFlags){this.ts=(new Date).valueOf();var t=JSON.stringify(this.getState());this.log("Setting storage",t),h.setItem(this.getStorageKey(),t)}},p.prototype.updateEventStorage=function(){if(this.enableAnalytics){var t=JSON.stringify(this.getState().evaluationEvent);h.setItem(g,t).catch((function(t){return console.error("Flagsmith: Error setting item in async storage",t)}))}},p.prototype.setLoadingState=function(e){var n;a(e,this.loadingState)||(this.loadingState=t({},e),this.log("Loading state changed",e),null===(n=this._triggerLoadingState)||void 0===n||n.call(this))},p.prototype.setupRealtime=function(t,e){var n=this,i=t+"sse/environments/"+e+"/stream";v?this.eventSource||(this.log("Creating event source with url "+i),this.eventSource=new v(i),this.eventSource.addEventListener("environment_updated",(function(t){var e;try{e=JSON.parse(t.data).updated_at}catch(t){n.log("Could not parse sse event",t)}e?!n.timestamp||e>n.timestamp?n.isLoading?n.log("updated_at is new, but flags are loading",t.data,n.timestamp):(n.log("updated_at is new, fetching flags",t.data,n.timestamp),n.getFlags()):n.log("updated_at is outdated, skipping get flags",t.data,n.timestamp):n.log("No updated_at received, fetching flags",t)}))):this.log("Error, EventSource is undefined")},p}();function y(t){var e=t.fetch,n=t.AsyncStorage,i=t.eventSource;return new p({fetch:e,AsyncStorage:n,eventSource:i})}var m=y({}),S=function(){return y({})};export{c as FlagSource,S as createFlagsmithInstance,m as default};
2
2
  //# sourceMappingURL=next-middleware.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flagsmith/flagsmith",
3
- "version": "12.0.0",
3
+ "version": "12.0.1",
4
4
  "description": "Feature flagging to support continuous development",
5
5
  "main": "./index.js",
6
6
  "module": "./index.mjs",
@@ -1,2 +1,2 @@
1
1
  // Auto-generated by write-version.js
2
- export const SDK_VERSION = "12.0.0";
2
+ export const SDK_VERSION = "12.0.1";
@@ -1 +1 @@
1
- export declare const SDK_VERSION = "12.0.0";
1
+ export declare const SDK_VERSION = "12.0.1";