unleash-proxy-client
Advanced tools
Comparing version 3.7.2 to 3.7.3
@@ -6,2 +6,11 @@ import { IContext } from '.'; | ||
export declare const computeContextHashValue: (obj: IContext) => Promise<string>; | ||
export declare const parseHeaders: ({ clientKey, appName, connectionId, customHeaders, headerName, etag, isPost, }: { | ||
clientKey: string; | ||
connectionId: string; | ||
appName: string; | ||
customHeaders?: Record<string, string>; | ||
headerName?: string; | ||
etag?: string; | ||
isPost?: boolean; | ||
}) => Record<string, string>; | ||
//# sourceMappingURL=util.d.ts.map |
@@ -1,2 +0,2 @@ | ||
export declare const sdkVersion = "unleash-js@__VERSION__"; | ||
export declare const sdkVersion = "unleash-client-js:__VERSION__"; | ||
//# sourceMappingURL=version.d.ts.map |
@@ -1,2 +0,2 @@ | ||
var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};var e=function(){return e=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},e.apply(this,arguments)};function r(t,e,r,n){return new(r||(r=Promise))((function(o,i){function s(t){try{c(n.next(t))}catch(t){i(t)}}function a(t){try{c(n.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}c((n=n.apply(t,e||[])).next())}))}function n(t,e){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=e.call(t,i)}catch(t){a=[6,t],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}"function"==typeof SuppressedError&&SuppressedError;var o={exports:{}};function i(){}i.prototype={on:function(t,e,r){var n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:r}),this},once:function(t,e,r){var n=this;function o(){n.off(t,o),e.apply(r,arguments)}return o._=e,this.on(t,o,r)},emit:function(t){for(var e=[].slice.call(arguments,1),r=((this.e||(this.e={}))[t]||[]).slice(),n=0,o=r.length;n<o;n++)r[n].fn.apply(r[n].ctx,e);return this},off:function(t,e){var r=this.e||(this.e={}),n=r[t],o=[];if(n&&e)for(var i=0,s=n.length;i<s;i++)n[i].fn!==e&&n[i].fn._!==e&&o.push(n[i]);return o.length?r[t]=o:delete r[t],this}},o.exports=i;var s=o.exports.TinyEmitter=i,a=function(t){var e=t[1];return null!=e},c=function(t){var e=t.properties,r=void 0===e?{}:e,n=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(t);o<n.length;o++)e.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(t,n[o])&&(r[n[o]]=t[n[o]])}return r}(t,["properties"]),o=function(t){return Object.entries(t).sort((function(t,e){var r=t[0],n=e[0];return r.localeCompare(n,void 0)}))};return JSON.stringify([o(n),o(r)])},u=function(t){return r(void 0,void 0,void 0,(function(){var e;return n(this,(function(o){switch(o.label){case 0:e=c(t),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,(i=e,r(void 0,void 0,void 0,(function(){var t,e,r,o,s;return n(this,(function(n){switch(n.label){case 0:if(t="undefined"!=typeof globalThis&&(null===(o=globalThis.crypto)||void 0===o?void 0:o.subtle)?null===(s=globalThis.crypto)||void 0===s?void 0:s.subtle:void 0,"undefined"==typeof TextEncoder||!(null==t?void 0:t.digest)||"undefined"==typeof Uint8Array)throw new Error("Hashing function not available");return e=(new TextEncoder).encode(i),[4,t.digest("SHA-256",e)];case 1:return r=n.sent(),[2,Array.from(new Uint8Array(r)).map((function(t){return t.toString(16).padStart(2,"0")})).join("")]}}))})))];case 2:return[2,o.sent()];case 3:return o.sent(),[2,e];case 4:return[2]}var i}))}))},l="unleash-js@3.7.2",h=function(){},p=function(){function t(t){var e=t.onError,r=t.onSent,n=t.appName,o=t.metricsInterval,i=t.disableMetrics,s=void 0!==i&&i,a=t.url,c=t.clientKey,u=t.fetch,l=t.headerName,p=t.customHeaders,f=void 0===p?{}:p,d=t.metricsIntervalInitial,v=t.connectionId;this.onError=e,this.onSent=r||h,this.disabled=s,this.metricsInterval=1e3*o,this.metricsIntervalInitial=1e3*d,this.appName=n,this.url=a instanceof URL?a:new URL(a),this.clientKey=c,this.bucket=this.createEmptyBucket(),this.fetch=u,this.headerName=l,this.customHeaders=f,this.connectionId=v}return t.prototype.start=function(){var t=this;if(this.disabled)return!1;"number"==typeof this.metricsInterval&&this.metricsInterval>0&&(this.metricsIntervalInitial>0?setTimeout((function(){t.startTimer(),t.sendMetrics()}),this.metricsIntervalInitial):this.startTimer())},t.prototype.stop=function(){this.timer&&(clearTimeout(this.timer),delete this.timer)},t.prototype.createEmptyBucket=function(){return{start:new Date,stop:null,toggles:{}}},t.prototype.getHeaders=function(){var t,e=((t={})[this.headerName]=this.clientKey,t.Accept="application/json",t["Content-Type"]="application/json",t["x-unleash-sdk"]=l,t["x-unleash-connection-id"]=this.connectionId,t["x-unleash-appname"]=this.appName,t);return Object.entries(this.customHeaders).filter(a).forEach((function(t){var r=t[0],n=t[1];return e[r]=n})),e},t.prototype.sendMetrics=function(){return r(this,void 0,void 0,(function(){var t,e,r;return n(this,(function(n){switch(n.label){case 0:if(t="".concat(this.url,"/client/metrics"),e=this.getPayload(),this.bucketIsEmpty(e))return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.fetch(t,{cache:"no-cache",method:"POST",headers:this.getHeaders(),body:JSON.stringify(e)})];case 2:return n.sent(),this.onSent(e),[3,4];case 3:return r=n.sent(),console.error("Unleash: unable to send feature metrics",r),this.onError(r),[3,4];case 4:return[2]}}))}))},t.prototype.count=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t][e?"yes":"no"]++,!0)},t.prototype.countVariant=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t].variants[e]?this.bucket.toggles[t].variants[e]+=1:this.bucket.toggles[t].variants[e]=1,!0)},t.prototype.assertBucket=function(t){if(this.disabled||!this.bucket)return!1;this.bucket.toggles[t]||(this.bucket.toggles[t]={yes:0,no:0,variants:{}})},t.prototype.startTimer=function(){var t=this;this.timer=setInterval((function(){t.sendMetrics()}),this.metricsInterval)},t.prototype.bucketIsEmpty=function(t){return 0===Object.keys(t.bucket.toggles).length},t.prototype.getPayload=function(){var t=e(e({},this.bucket),{stop:new Date});return this.bucket=this.createEmptyBucket(),{bucket:t,appName:this.appName,instanceId:"browser"}},t}(),f=function(){function t(){this.store=new Map}return t.prototype.save=function(t,e){return r(this,void 0,void 0,(function(){return n(this,(function(r){return this.store.set(t,e),[2]}))}))},t.prototype.get=function(t){return r(this,void 0,void 0,(function(){return n(this,(function(e){return[2,this.store.get(t)]}))}))},t}(),d=function(){function t(t){void 0===t&&(t="unleash:repository"),this.prefix=t}return t.prototype.save=function(t,e){return r(this,void 0,void 0,(function(){var r,o;return n(this,(function(n){r=JSON.stringify(e),o="".concat(this.prefix,":").concat(t);try{window.localStorage.setItem(o,r)}catch(t){console.error(t)}return[2]}))}))},t.prototype.get=function(t){try{var e="".concat(this.prefix,":").concat(t),r=window.localStorage.getItem(e);return r?JSON.parse(r):void 0}catch(t){console.error(t)}},t}();let v;const m=new Uint8Array(16);function g(){if(!v&&(v="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!v))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return v(m)}const y=[];for(let t=0;t<256;++t)y.push((t+256).toString(16).slice(1));var b={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function x(t,e,r){if(b.randomUUID&&!e&&!t)return b.randomUUID();const n=(t=t||{}).random||(t.rng||g)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,e){r=r||0;for(let t=0;t<16;++t)e[r+t]=n[t];return e}return function(t,e=0){return y[t[e+0]]+y[t[e+1]]+y[t[e+2]]+y[t[e+3]]+"-"+y[t[e+4]]+y[t[e+5]]+"-"+y[t[e+6]]+y[t[e+7]]+"-"+y[t[e+8]]+y[t[e+9]]+"-"+y[t[e+10]]+y[t[e+11]]+y[t[e+12]]+y[t[e+13]]+y[t[e+14]]+y[t[e+15]]}(n)}var T=function(){function t(){}return t.prototype.generateEventId=function(){return x()},t.prototype.createImpressionEvent=function(t,r,n,o,i,s){var a=this.createBaseEvent(t,r,n,o,i);return s?e(e({},a),{variant:s}):a},t.prototype.createBaseEvent=function(t,e,r,n,o){return{eventType:n,eventId:this.generateEventId(),context:t,enabled:e,featureName:r,impressionData:o}},t}(),w=["userId","sessionId","remoteAddress","currentTime"],E=function(t){return w.includes(t)},S={INIT:"initialized",ERROR:"error",READY:"ready",UPDATE:"update",IMPRESSION:"impression",SENT:"sent",RECOVERED:"recovered"},I="isEnabled",R="getVariant",O={name:"disabled",enabled:!1,feature_enabled:!1},k="repo",N="repoLastUpdateTimestamp",A=function(){try{if("undefined"!=typeof window&&"fetch"in window)return fetch.bind(window);if("fetch"in globalThis)return fetch.bind(globalThis)}catch(t){console.error('Unleash failed to resolve "fetch"',t)}},U=function(o){function i(t){var r=t.storageProvider,n=t.url,i=t.clientKey,s=t.disableRefresh,a=void 0!==s&&s,c=t.refreshInterval,u=void 0===c?30:c,l=t.metricsInterval,h=void 0===l?30:l,v=t.metricsIntervalInitial,m=void 0===v?2:v,g=t.disableMetrics,y=void 0!==g&&g,b=t.appName,x=t.environment,w=void 0===x?"default":x,E=t.context,I=t.fetch,R=void 0===I?A():I,O=t.createAbortController,k=void 0===O?function(){try{if("undefined"!=typeof window&&"AbortController"in window)return function(){return new window.AbortController};if("fetch"in globalThis)return function(){return new globalThis.AbortController}}catch(t){console.error('Unleash failed to resolve "AbortController" factory',t)}}():O,N=t.bootstrap,U=t.bootstrapOverride,D=void 0===U||U,j=t.headerName,C=void 0===j?"Authorization":j,P=t.customHeaders,L=void 0===P?{}:P,H=t.impressionDataAll,M=void 0!==H&&H,_=t.usePOSTrequests,F=void 0!==_&&_,K=t.experimental,V=o.call(this)||this;if(V.toggles=[],V.etag="",V.readyEventEmitted=!1,V.fetchedFromServer=!1,V.usePOSTrequests=!1,V.started=!1,!n)throw new Error("url is required");if(!i)throw new Error("clientKey is required");if(!b)throw new Error("appName is required.");return V.eventsHandler=new T,V.impressionDataAll=M,V.toggles=N&&N.length>0?N:[],V.url=n instanceof URL?n:new URL(n),V.clientKey=i,V.headerName=C,V.customHeaders=L,V.storage=r||("undefined"!=typeof window?new d:new f),V.refreshInterval=a?0:1e3*u,V.context=e({appName:b,environment:w},E),V.usePOSTrequests=F,V.sdkState="initializing",V.experimental=e({},K),(null==K?void 0:K.togglesStorageTTL)&&(null==K?void 0:K.togglesStorageTTL)>0&&(V.experimental.togglesStorageTTL=1e3*K.togglesStorageTTL),V.lastRefreshTimestamp=0,V.ready=new Promise((function(t){V.init().then(t).catch((function(e){console.error(e),V.sdkState="error",V.emit(S.ERROR,e),V.lastError=e,t()}))})),R||console.error('Unleash: You must either provide your own "fetch" implementation or run in an environment where "fetch" is available.'),k||console.error('Unleash: You must either provide your own "AbortController" implementation or run in an environment where "AbortController" is available.'),V.fetch=R,V.createAbortController=k,V.bootstrap=N&&N.length>0?N:void 0,V.bootstrapOverride=D,V.connectionId="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})),V.metrics=new p({onError:V.emit.bind(V,S.ERROR),onSent:V.emit.bind(V,S.SENT),appName:b,metricsInterval:h,disableMetrics:y,url:V.url,clientKey:i,fetch:R,headerName:C,customHeaders:L,metricsIntervalInitial:m,connectionId:V.connectionId}),V}return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}(i,o),i.prototype.getAllToggles=function(){return function(t,e,r){if(r||2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}([],this.toggles,!0)},i.prototype.isEnabled=function(t){var e,r=this.toggles.find((function(e){return e.name===t})),n=!!r&&r.enabled;if(this.metrics.count(t,n),(null==r?void 0:r.impressionData)||this.impressionDataAll){var o=this.eventsHandler.createImpressionEvent(this.context,n,t,I,null!==(e=null==r?void 0:r.impressionData)&&void 0!==e?e:void 0);this.emit(S.IMPRESSION,o)}return n},i.prototype.getVariant=function(t){var r,n=this.toggles.find((function(e){return e.name===t})),o=(null==n?void 0:n.enabled)||!1,i=n?n.variant:O;if(i.name&&this.metrics.countVariant(t,i.name),this.metrics.count(t,o),(null==n?void 0:n.impressionData)||this.impressionDataAll){var s=this.eventsHandler.createImpressionEvent(this.context,o,t,R,null!==(r=null==n?void 0:n.impressionData)&&void 0!==r?r:void 0,i.name);this.emit(S.IMPRESSION,s)}return e(e({},i),{feature_enabled:o})},i.prototype.updateToggles=function(){return r(this,void 0,void 0,(function(){var t=this;return n(this,(function(e){switch(e.label){case 0:return this.timerRef||this.fetchedFromServer?[4,this.fetchToggles()]:[3,2];case 1:return e.sent(),[3,4];case 2:return this.started?[4,new Promise((function(e){var r=function(){t.fetchToggles().then((function(){t.off(S.READY,r),e()}))};t.once(S.READY,r)}))]:[3,4];case 3:e.sent(),e.label=4;case 4:return[2]}}))}))},i.prototype.updateContext=function(t){return r(this,void 0,void 0,(function(){var r;return n(this,(function(n){switch(n.label){case 0:return(t.appName||t.environment)&&console.warn("appName and environment are static. They can't be updated with updateContext."),r={environment:this.context.environment,appName:this.context.appName,sessionId:this.context.sessionId},this.context=e(e({},r),t),[4,this.updateToggles()];case 1:return n.sent(),[2]}}))}))},i.prototype.getContext=function(){return e({},this.context)},i.prototype.setContextField=function(t,r){var n,o;if(E(t))this.context=e(e({},this.context),((n={})[t]=r,n));else{var i=e(e({},this.context.properties),((o={})[t]=r,o));this.context=e(e({},this.context),{properties:i})}this.updateToggles()},i.prototype.removeContextField=function(t){var r;E(t)?this.context=e(e({},this.context),((r={})[t]=void 0,r)):"object"==typeof this.context.properties&&delete this.context.properties[t],this.updateToggles()},i.prototype.setReady=function(){this.readyEventEmitted=!0,this.emit(S.READY)},i.prototype.init=function(){return r(this,void 0,void 0,(function(){var t,r,o;return n(this,(function(n){switch(n.label){case 0:return[4,this.resolveSessionId()];case 1:return t=n.sent(),this.context=e({sessionId:t},this.context),r=this,[4,this.storage.get(k)];case 2:return r.toggles=n.sent()||[],o=this,[4,this.getLastRefreshTimestamp()];case 3:return o.lastRefreshTimestamp=n.sent(),!this.bootstrap||!this.bootstrapOverride&&0!==this.toggles.length?[3,6]:[4,this.storage.save(k,this.bootstrap)];case 4:return n.sent(),this.toggles=this.bootstrap,this.sdkState="healthy",[4,this.storeLastRefreshTimestamp()];case 5:n.sent(),this.setReady(),n.label=6;case 6:return this.sdkState="healthy",this.emit(S.INIT),[2]}}))}))},i.prototype.start=function(){return r(this,void 0,void 0,(function(){var t,e=this;return n(this,(function(r){switch(r.label){case 0:return this.started=!0,this.timerRef?(console.error("Unleash SDK has already started, if you want to restart the SDK you should call client.stop() before starting again."),[2]):[4,this.ready];case 1:return r.sent(),this.metrics.start(),t=this.refreshInterval,[4,this.initialFetchToggles()];case 2:return r.sent(),t>0&&(this.timerRef=setInterval((function(){return e.fetchToggles()}),t)),[2]}}))}))},i.prototype.stop=function(){this.timerRef&&(clearInterval(this.timerRef),this.timerRef=void 0),this.metrics.stop()},i.prototype.isReady=function(){return this.readyEventEmitted},i.prototype.getError=function(){return"error"===this.sdkState?this.lastError:void 0},i.prototype.sendMetrics=function(){return this.metrics.sendMetrics()},i.prototype.resolveSessionId=function(){return r(this,void 0,void 0,(function(){var t;return n(this,(function(e){switch(e.label){case 0:return this.context.sessionId?[2,this.context.sessionId]:[4,this.storage.get("sessionId")];case 1:return(t=e.sent())?[3,3]:(t=Math.floor(1e9*Math.random()),[4,this.storage.save("sessionId",t.toString(10))]);case 2:e.sent(),e.label=3;case 3:return[2,t.toString(10)]}}))}))},i.prototype.getHeaders=function(){var t,e=this.usePOSTrequests,r=((t={})[this.headerName]=this.clientKey,t.Accept="application/json",t["x-unleash-sdk"]=l,t["x-unleash-connection-id"]=this.connectionId,t["x-unleash-appname"]=this.context.appName,t);return e&&(r["Content-Type"]="application/json"),this.etag&&(r["If-None-Match"]=this.etag),Object.entries(this.customHeaders).filter(a).forEach((function(t){var e=t[0],n=t[1];return r[e]=n})),r},i.prototype.storeToggles=function(t){return r(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return this.toggles=t,this.emit(S.UPDATE),[4,this.storage.save(k,t)];case 1:return e.sent(),[2]}}))}))},i.prototype.isTogglesStorageTTLEnabled=function(){var t;return!!((null===(t=this.experimental)||void 0===t?void 0:t.togglesStorageTTL)&&this.experimental.togglesStorageTTL>0)},i.prototype.isUpToDate=function(){var t;if(!this.isTogglesStorageTTLEnabled())return!1;var e=Date.now(),r=(null===(t=this.experimental)||void 0===t?void 0:t.togglesStorageTTL)||0;return this.lastRefreshTimestamp>0&&this.lastRefreshTimestamp<=e&&e-this.lastRefreshTimestamp<=r},i.prototype.getLastRefreshTimestamp=function(){return r(this,void 0,void 0,(function(){var t,e;return n(this,(function(r){switch(r.label){case 0:return this.isTogglesStorageTTLEnabled()?[4,this.storage.get(N)]:[3,3];case 1:return t=r.sent(),[4,u(this.context)];case 2:return e=r.sent(),[2,(null==t?void 0:t.key)===e?t.timestamp:0];case 3:return[2,0]}}))}))},i.prototype.storeLastRefreshTimestamp=function(){return r(this,void 0,void 0,(function(){var t,e;return n(this,(function(r){switch(r.label){case 0:return this.isTogglesStorageTTLEnabled()?(this.lastRefreshTimestamp=Date.now(),e={},[4,u(this.context)]):[3,3];case 1:return e.key=r.sent(),e.timestamp=this.lastRefreshTimestamp,t=e,[4,this.storage.save(N,t)];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},i.prototype.initialFetchToggles=function(){if(!this.isUpToDate())return this.fetchToggles();this.fetchedFromServer||(this.fetchedFromServer=!0,this.setReady())},i.prototype.fetchToggles=function(){return r(this,void 0,void 0,(function(){var t,e,r,o,i,s,c,u,l;return n(this,(function(n){switch(n.label){case 0:if(!this.fetch)return[3,9];this.abortController&&this.abortController.abort(),this.abortController=null===(l=this.createAbortController)||void 0===l?void 0:l.call(this),t=this.abortController?this.abortController.signal:void 0,n.label=1;case 1:return n.trys.push([1,7,8,9]),e=this.usePOSTrequests,r=e?this.url:function(t,e){var r=new URL(t.toString());return Object.entries(e).filter(a).forEach((function(t){var e=t[0],n=t[1];"properties"===e&&n?Object.entries(n).filter(a).forEach((function(t){var e=t[0],n=t[1];return r.searchParams.append("properties[".concat(e,"]"),n)})):r.searchParams.append(e,n)})),r}(this.url,this.context),o=e?"POST":"GET",i=e?JSON.stringify({context:this.context}):void 0,[4,this.fetch(r.toString(),{method:o,cache:"no-cache",headers:this.getHeaders(),body:i,signal:t})];case 2:return s=n.sent(),"error"===this.sdkState&&s.status<400&&(this.sdkState="healthy",this.emit(S.RECOVERED)),s.ok?(this.etag=s.headers.get("ETag")||"",[4,s.json()]):[3,5];case 3:return c=n.sent(),[4,this.storeToggles(c.toggles)];case 4:return n.sent(),"healthy"!==this.sdkState&&(this.sdkState="healthy"),this.fetchedFromServer||(this.fetchedFromServer=!0,this.setReady()),this.storeLastRefreshTimestamp(),[3,6];case 5:304===s.status?this.storeLastRefreshTimestamp():(console.error("Unleash: Fetching feature toggles did not have an ok response"),this.sdkState="error",this.emit(S.ERROR,{type:"HttpError",code:s.status}),this.lastError={type:"HttpError",code:s.status}),n.label=6;case 6:return[3,9];case 7:return"object"==typeof(u=n.sent())&&null!==u&&"name"in u&&"AbortError"===u.name||(console.error("Unleash: unable to fetch feature toggles",u),this.sdkState="error",this.emit(S.ERROR,u),this.lastError=u),[3,9];case 8:return this.abortController=null,[7];case 9:return[2]}}))}))},i}(s);export{S as EVENTS,f as InMemoryStorageProvider,d as LocalStorageProvider,U as UnleashClient,N as lastUpdateKey,A as resolveFetch}; | ||
var t=function(e,r){return t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},t(e,r)};var e=function(){return e=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},e.apply(this,arguments)};function r(t,e,r,n){return new(r||(r=Promise))((function(o,i){function s(t){try{c(n.next(t))}catch(t){i(t)}}function a(t){try{c(n.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}c((n=n.apply(t,e||[])).next())}))}function n(t,e){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=e.call(t,i)}catch(t){a=[6,t],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}"function"==typeof SuppressedError&&SuppressedError;var o={exports:{}};function i(){}i.prototype={on:function(t,e,r){var n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:r}),this},once:function(t,e,r){var n=this;function o(){n.off(t,o),e.apply(r,arguments)}return o._=e,this.on(t,o,r)},emit:function(t){for(var e=[].slice.call(arguments,1),r=((this.e||(this.e={}))[t]||[]).slice(),n=0,o=r.length;n<o;n++)r[n].fn.apply(r[n].ctx,e);return this},off:function(t,e){var r=this.e||(this.e={}),n=r[t],o=[];if(n&&e)for(var i=0,s=n.length;i<s;i++)n[i].fn!==e&&n[i].fn._!==e&&o.push(n[i]);return o.length?r[t]=o:delete r[t],this}},o.exports=i;var s=o.exports.TinyEmitter=i,a=function(t){var e=t[1];return null!=e},c=function(t){var e=t.properties,r=void 0===e?{}:e,n=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(t);o<n.length;o++)e.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(t,n[o])&&(r[n[o]]=t[n[o]])}return r}(t,["properties"]),o=function(t){return Object.entries(t).sort((function(t,e){var r=t[0],n=e[0];return r.localeCompare(n,void 0)}))};return JSON.stringify([o(n),o(r)])},u=function(t){return r(void 0,void 0,void 0,(function(){var e;return n(this,(function(o){switch(o.label){case 0:e=c(t),o.label=1;case 1:return o.trys.push([1,3,,4]),[4,(i=e,r(void 0,void 0,void 0,(function(){var t,e,r,o,s;return n(this,(function(n){switch(n.label){case 0:if(t="undefined"!=typeof globalThis&&(null===(o=globalThis.crypto)||void 0===o?void 0:o.subtle)?null===(s=globalThis.crypto)||void 0===s?void 0:s.subtle:void 0,"undefined"==typeof TextEncoder||!(null==t?void 0:t.digest)||"undefined"==typeof Uint8Array)throw new Error("Hashing function not available");return e=(new TextEncoder).encode(i),[4,t.digest("SHA-256",e)];case 1:return r=n.sent(),[2,Array.from(new Uint8Array(r)).map((function(t){return t.toString(16).padStart(2,"0")})).join("")]}}))})))];case 2:return[2,o.sent()];case 3:return o.sent(),[2,e];case 4:return[2]}var i}))}))},l=function(t){var e,r=t.clientKey,n=t.appName,o=t.connectionId,i=t.customHeaders,s=t.headerName,c=void 0===s?"authorization":s,u=t.etag,l=t.isPost,h=((e={accept:"application/json"})[c.toLocaleLowerCase()]=r,e["unleash-sdk"]="unleash-client-js:3.7.3",e["unleash-appname"]=n,e);return l&&(h["content-type"]="application/json"),u&&(h["if-none-match"]=u),Object.entries(i||{}).filter(a).forEach((function(t){var e=t[0],r=t[1];return h[e.toLocaleLowerCase()]=r})),h["unleash-connection-id"]=o,h},h=function(){},p=function(){function t(t){var e=t.onError,r=t.onSent,n=t.appName,o=t.metricsInterval,i=t.disableMetrics,s=void 0!==i&&i,a=t.url,c=t.clientKey,u=t.fetch,l=t.headerName,p=t.customHeaders,d=void 0===p?{}:p,f=t.metricsIntervalInitial,v=t.connectionId;this.onError=e,this.onSent=r||h,this.disabled=s,this.metricsInterval=1e3*o,this.metricsIntervalInitial=1e3*f,this.appName=n,this.url=a instanceof URL?a:new URL(a),this.clientKey=c,this.bucket=this.createEmptyBucket(),this.fetch=u,this.headerName=l,this.customHeaders=d,this.connectionId=v}return t.prototype.start=function(){var t=this;if(this.disabled)return!1;"number"==typeof this.metricsInterval&&this.metricsInterval>0&&(this.metricsIntervalInitial>0?setTimeout((function(){t.startTimer(),t.sendMetrics()}),this.metricsIntervalInitial):this.startTimer())},t.prototype.stop=function(){this.timer&&(clearTimeout(this.timer),delete this.timer)},t.prototype.createEmptyBucket=function(){return{start:new Date,stop:null,toggles:{}}},t.prototype.getHeaders=function(){return l({clientKey:this.clientKey,appName:this.appName,connectionId:this.connectionId,customHeaders:this.customHeaders,headerName:this.headerName,isPost:!0})},t.prototype.sendMetrics=function(){return r(this,void 0,void 0,(function(){var t,e,r;return n(this,(function(n){switch(n.label){case 0:if(t="".concat(this.url,"/client/metrics"),e=this.getPayload(),this.bucketIsEmpty(e))return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.fetch(t,{cache:"no-cache",method:"POST",headers:this.getHeaders(),body:JSON.stringify(e)})];case 2:return n.sent(),this.onSent(e),[3,4];case 3:return r=n.sent(),console.error("Unleash: unable to send feature metrics",r),this.onError(r),[3,4];case 4:return[2]}}))}))},t.prototype.count=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t][e?"yes":"no"]++,!0)},t.prototype.countVariant=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t].variants[e]?this.bucket.toggles[t].variants[e]+=1:this.bucket.toggles[t].variants[e]=1,!0)},t.prototype.assertBucket=function(t){if(this.disabled||!this.bucket)return!1;this.bucket.toggles[t]||(this.bucket.toggles[t]={yes:0,no:0,variants:{}})},t.prototype.startTimer=function(){var t=this;this.timer=setInterval((function(){t.sendMetrics()}),this.metricsInterval)},t.prototype.bucketIsEmpty=function(t){return 0===Object.keys(t.bucket.toggles).length},t.prototype.getPayload=function(){var t=e(e({},this.bucket),{stop:new Date});return this.bucket=this.createEmptyBucket(),{bucket:t,appName:this.appName,instanceId:"browser"}},t}(),d=function(){function t(){this.store=new Map}return t.prototype.save=function(t,e){return r(this,void 0,void 0,(function(){return n(this,(function(r){return this.store.set(t,e),[2]}))}))},t.prototype.get=function(t){return r(this,void 0,void 0,(function(){return n(this,(function(e){return[2,this.store.get(t)]}))}))},t}(),f=function(){function t(t){void 0===t&&(t="unleash:repository"),this.prefix=t}return t.prototype.save=function(t,e){return r(this,void 0,void 0,(function(){var r,o;return n(this,(function(n){r=JSON.stringify(e),o="".concat(this.prefix,":").concat(t);try{window.localStorage.setItem(o,r)}catch(t){console.error(t)}return[2]}))}))},t.prototype.get=function(t){try{var e="".concat(this.prefix,":").concat(t),r=window.localStorage.getItem(e);return r?JSON.parse(r):void 0}catch(t){console.error(t)}},t}();let v;const m=new Uint8Array(16);function g(){if(!v&&(v="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!v))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return v(m)}const y=[];for(let t=0;t<256;++t)y.push((t+256).toString(16).slice(1));var b={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function x(t,e,r){if(b.randomUUID&&!e&&!t)return b.randomUUID();const n=(t=t||{}).random||(t.rng||g)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,e){r=r||0;for(let t=0;t<16;++t)e[r+t]=n[t];return e}return function(t,e=0){return y[t[e+0]]+y[t[e+1]]+y[t[e+2]]+y[t[e+3]]+"-"+y[t[e+4]]+y[t[e+5]]+"-"+y[t[e+6]]+y[t[e+7]]+"-"+y[t[e+8]]+y[t[e+9]]+"-"+y[t[e+10]]+y[t[e+11]]+y[t[e+12]]+y[t[e+13]]+y[t[e+14]]+y[t[e+15]]}(n)}var T=function(){function t(){}return t.prototype.generateEventId=function(){return x()},t.prototype.createImpressionEvent=function(t,r,n,o,i,s){var a=this.createBaseEvent(t,r,n,o,i);return s?e(e({},a),{variant:s}):a},t.prototype.createBaseEvent=function(t,e,r,n,o){return{eventType:n,eventId:this.generateEventId(),context:t,enabled:e,featureName:r,impressionData:o}},t}(),w=["userId","sessionId","remoteAddress","currentTime"],E=function(t){return w.includes(t)},I={INIT:"initialized",ERROR:"error",READY:"ready",UPDATE:"update",IMPRESSION:"impression",SENT:"sent",RECOVERED:"recovered"},S="isEnabled",R="getVariant",O={name:"disabled",enabled:!1,feature_enabled:!1},k="repo",N="repoLastUpdateTimestamp",A=function(){try{if("undefined"!=typeof window&&"fetch"in window)return fetch.bind(window);if("fetch"in globalThis)return fetch.bind(globalThis)}catch(t){console.error('Unleash failed to resolve "fetch"',t)}},U=function(o){function i(t){var r=t.storageProvider,n=t.url,i=t.clientKey,s=t.disableRefresh,a=void 0!==s&&s,c=t.refreshInterval,u=void 0===c?30:c,l=t.metricsInterval,h=void 0===l?30:l,v=t.metricsIntervalInitial,m=void 0===v?2:v,g=t.disableMetrics,y=void 0!==g&&g,b=t.appName,x=t.environment,w=void 0===x?"default":x,E=t.context,S=t.fetch,R=void 0===S?A():S,O=t.createAbortController,k=void 0===O?function(){try{if("undefined"!=typeof window&&"AbortController"in window)return function(){return new window.AbortController};if("fetch"in globalThis)return function(){return new globalThis.AbortController}}catch(t){console.error('Unleash failed to resolve "AbortController" factory',t)}}():O,N=t.bootstrap,U=t.bootstrapOverride,D=void 0===U||U,P=t.headerName,L=void 0===P?"Authorization":P,C=t.customHeaders,j=void 0===C?{}:C,H=t.impressionDataAll,M=void 0!==H&&H,K=t.usePOSTrequests,_=void 0!==K&&K,F=t.experimental,V=o.call(this)||this;if(V.toggles=[],V.etag="",V.readyEventEmitted=!1,V.fetchedFromServer=!1,V.usePOSTrequests=!1,V.started=!1,!n)throw new Error("url is required");if(!i)throw new Error("clientKey is required");if(!b)throw new Error("appName is required.");return V.eventsHandler=new T,V.impressionDataAll=M,V.toggles=N&&N.length>0?N:[],V.url=n instanceof URL?n:new URL(n),V.clientKey=i,V.headerName=L,V.customHeaders=j,V.storage=r||("undefined"!=typeof window?new f:new d),V.refreshInterval=a?0:1e3*u,V.context=e({appName:b,environment:w},E),V.usePOSTrequests=_,V.sdkState="initializing",V.experimental=e({},F),(null==F?void 0:F.togglesStorageTTL)&&(null==F?void 0:F.togglesStorageTTL)>0&&(V.experimental.togglesStorageTTL=1e3*F.togglesStorageTTL),V.lastRefreshTimestamp=0,V.ready=new Promise((function(t){V.init().then(t).catch((function(e){console.error(e),V.sdkState="error",V.emit(I.ERROR,e),V.lastError=e,t()}))})),R||console.error('Unleash: You must either provide your own "fetch" implementation or run in an environment where "fetch" is available.'),k||console.error('Unleash: You must either provide your own "AbortController" implementation or run in an environment where "AbortController" is available.'),V.fetch=R,V.createAbortController=k,V.bootstrap=N&&N.length>0?N:void 0,V.bootstrapOverride=D,V.connectionId="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})),V.metrics=new p({onError:V.emit.bind(V,I.ERROR),onSent:V.emit.bind(V,I.SENT),appName:b,metricsInterval:h,disableMetrics:y,url:V.url,clientKey:i,fetch:R,headerName:L,customHeaders:j,metricsIntervalInitial:m,connectionId:V.connectionId}),V}return function(e,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=e}t(e,r),e.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}(i,o),i.prototype.getAllToggles=function(){return function(t,e,r){if(r||2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}([],this.toggles,!0)},i.prototype.isEnabled=function(t){var e,r=this.toggles.find((function(e){return e.name===t})),n=!!r&&r.enabled;if(this.metrics.count(t,n),(null==r?void 0:r.impressionData)||this.impressionDataAll){var o=this.eventsHandler.createImpressionEvent(this.context,n,t,S,null!==(e=null==r?void 0:r.impressionData)&&void 0!==e?e:void 0);this.emit(I.IMPRESSION,o)}return n},i.prototype.getVariant=function(t){var r,n=this.toggles.find((function(e){return e.name===t})),o=(null==n?void 0:n.enabled)||!1,i=n?n.variant:O;if(i.name&&this.metrics.countVariant(t,i.name),this.metrics.count(t,o),(null==n?void 0:n.impressionData)||this.impressionDataAll){var s=this.eventsHandler.createImpressionEvent(this.context,o,t,R,null!==(r=null==n?void 0:n.impressionData)&&void 0!==r?r:void 0,i.name);this.emit(I.IMPRESSION,s)}return e(e({},i),{feature_enabled:o})},i.prototype.updateToggles=function(){return r(this,void 0,void 0,(function(){var t=this;return n(this,(function(e){switch(e.label){case 0:return this.timerRef||this.fetchedFromServer?[4,this.fetchToggles()]:[3,2];case 1:return e.sent(),[3,4];case 2:return this.started?[4,new Promise((function(e){var r=function(){t.fetchToggles().then((function(){t.off(I.READY,r),e()}))};t.once(I.READY,r)}))]:[3,4];case 3:e.sent(),e.label=4;case 4:return[2]}}))}))},i.prototype.updateContext=function(t){return r(this,void 0,void 0,(function(){var r;return n(this,(function(n){switch(n.label){case 0:return(t.appName||t.environment)&&console.warn("appName and environment are static. They can't be updated with updateContext."),r={environment:this.context.environment,appName:this.context.appName,sessionId:this.context.sessionId},this.context=e(e({},r),t),[4,this.updateToggles()];case 1:return n.sent(),[2]}}))}))},i.prototype.getContext=function(){return e({},this.context)},i.prototype.setContextField=function(t,r){var n,o;if(E(t))this.context=e(e({},this.context),((n={})[t]=r,n));else{var i=e(e({},this.context.properties),((o={})[t]=r,o));this.context=e(e({},this.context),{properties:i})}this.updateToggles()},i.prototype.removeContextField=function(t){var r;E(t)?this.context=e(e({},this.context),((r={})[t]=void 0,r)):"object"==typeof this.context.properties&&delete this.context.properties[t],this.updateToggles()},i.prototype.setReady=function(){this.readyEventEmitted=!0,this.emit(I.READY)},i.prototype.init=function(){return r(this,void 0,void 0,(function(){var t,r,o;return n(this,(function(n){switch(n.label){case 0:return[4,this.resolveSessionId()];case 1:return t=n.sent(),this.context=e({sessionId:t},this.context),r=this,[4,this.storage.get(k)];case 2:return r.toggles=n.sent()||[],o=this,[4,this.getLastRefreshTimestamp()];case 3:return o.lastRefreshTimestamp=n.sent(),!this.bootstrap||!this.bootstrapOverride&&0!==this.toggles.length?[3,6]:[4,this.storage.save(k,this.bootstrap)];case 4:return n.sent(),this.toggles=this.bootstrap,this.sdkState="healthy",[4,this.storeLastRefreshTimestamp()];case 5:n.sent(),this.setReady(),n.label=6;case 6:return this.sdkState="healthy",this.emit(I.INIT),[2]}}))}))},i.prototype.start=function(){return r(this,void 0,void 0,(function(){var t,e=this;return n(this,(function(r){switch(r.label){case 0:return this.started=!0,this.timerRef?(console.error("Unleash SDK has already started, if you want to restart the SDK you should call client.stop() before starting again."),[2]):[4,this.ready];case 1:return r.sent(),this.metrics.start(),t=this.refreshInterval,[4,this.initialFetchToggles()];case 2:return r.sent(),t>0&&(this.timerRef=setInterval((function(){return e.fetchToggles()}),t)),[2]}}))}))},i.prototype.stop=function(){this.timerRef&&(clearInterval(this.timerRef),this.timerRef=void 0),this.metrics.stop()},i.prototype.isReady=function(){return this.readyEventEmitted},i.prototype.getError=function(){return"error"===this.sdkState?this.lastError:void 0},i.prototype.sendMetrics=function(){return this.metrics.sendMetrics()},i.prototype.resolveSessionId=function(){return r(this,void 0,void 0,(function(){var t;return n(this,(function(e){switch(e.label){case 0:return this.context.sessionId?[2,this.context.sessionId]:[4,this.storage.get("sessionId")];case 1:return(t=e.sent())?[3,3]:(t=Math.floor(1e9*Math.random()),[4,this.storage.save("sessionId",t.toString(10))]);case 2:e.sent(),e.label=3;case 3:return[2,t.toString(10)]}}))}))},i.prototype.getHeaders=function(){return l({clientKey:this.clientKey,connectionId:this.connectionId,appName:this.context.appName,customHeaders:this.customHeaders,headerName:this.headerName,etag:this.etag,isPost:this.usePOSTrequests})},i.prototype.storeToggles=function(t){return r(this,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return this.toggles=t,this.emit(I.UPDATE),[4,this.storage.save(k,t)];case 1:return e.sent(),[2]}}))}))},i.prototype.isTogglesStorageTTLEnabled=function(){var t;return!!((null===(t=this.experimental)||void 0===t?void 0:t.togglesStorageTTL)&&this.experimental.togglesStorageTTL>0)},i.prototype.isUpToDate=function(){var t;if(!this.isTogglesStorageTTLEnabled())return!1;var e=Date.now(),r=(null===(t=this.experimental)||void 0===t?void 0:t.togglesStorageTTL)||0;return this.lastRefreshTimestamp>0&&this.lastRefreshTimestamp<=e&&e-this.lastRefreshTimestamp<=r},i.prototype.getLastRefreshTimestamp=function(){return r(this,void 0,void 0,(function(){var t,e;return n(this,(function(r){switch(r.label){case 0:return this.isTogglesStorageTTLEnabled()?[4,this.storage.get(N)]:[3,3];case 1:return t=r.sent(),[4,u(this.context)];case 2:return e=r.sent(),[2,(null==t?void 0:t.key)===e?t.timestamp:0];case 3:return[2,0]}}))}))},i.prototype.storeLastRefreshTimestamp=function(){return r(this,void 0,void 0,(function(){var t,e;return n(this,(function(r){switch(r.label){case 0:return this.isTogglesStorageTTLEnabled()?(this.lastRefreshTimestamp=Date.now(),e={},[4,u(this.context)]):[3,3];case 1:return e.key=r.sent(),e.timestamp=this.lastRefreshTimestamp,t=e,[4,this.storage.save(N,t)];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},i.prototype.initialFetchToggles=function(){if(!this.isUpToDate())return this.fetchToggles();this.fetchedFromServer||(this.fetchedFromServer=!0,this.setReady())},i.prototype.fetchToggles=function(){return r(this,void 0,void 0,(function(){var t,e,r,o,i,s,c,u,l;return n(this,(function(n){switch(n.label){case 0:if(!this.fetch)return[3,9];this.abortController&&this.abortController.abort(),this.abortController=null===(l=this.createAbortController)||void 0===l?void 0:l.call(this),t=this.abortController?this.abortController.signal:void 0,n.label=1;case 1:return n.trys.push([1,7,8,9]),e=this.usePOSTrequests,r=e?this.url:function(t,e){var r=new URL(t.toString());return Object.entries(e).filter(a).forEach((function(t){var e=t[0],n=t[1];"properties"===e&&n?Object.entries(n).filter(a).forEach((function(t){var e=t[0],n=t[1];return r.searchParams.append("properties[".concat(e,"]"),n)})):r.searchParams.append(e,n)})),r}(this.url,this.context),o=e?"POST":"GET",i=e?JSON.stringify({context:this.context}):void 0,[4,this.fetch(r.toString(),{method:o,cache:"no-cache",headers:this.getHeaders(),body:i,signal:t})];case 2:return s=n.sent(),"error"===this.sdkState&&s.status<400&&(this.sdkState="healthy",this.emit(I.RECOVERED)),s.ok?(this.etag=s.headers.get("ETag")||"",[4,s.json()]):[3,5];case 3:return c=n.sent(),[4,this.storeToggles(c.toggles)];case 4:return n.sent(),"healthy"!==this.sdkState&&(this.sdkState="healthy"),this.fetchedFromServer||(this.fetchedFromServer=!0,this.setReady()),this.storeLastRefreshTimestamp(),[3,6];case 5:304===s.status?this.storeLastRefreshTimestamp():(console.error("Unleash: Fetching feature toggles did not have an ok response"),this.sdkState="error",this.emit(I.ERROR,{type:"HttpError",code:s.status}),this.lastError={type:"HttpError",code:s.status}),n.label=6;case 6:return[3,9];case 7:return"object"==typeof(u=n.sent())&&null!==u&&"name"in u&&"AbortError"===u.name||(console.error("Unleash: unable to fetch feature toggles",u),this.sdkState="error",this.emit(I.ERROR,u),this.lastError=u),[3,9];case 8:return this.abortController=null,[7];case 9:return[2]}}))}))},i}(s);export{I as EVENTS,d as InMemoryStorageProvider,f as LocalStorageProvider,U as UnleashClient,N as lastUpdateKey,A as resolveFetch}; | ||
//# sourceMappingURL=main.esm.js.map |
@@ -1,2 +0,2 @@ | ||
!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).unleash={})}(this,(function(t){"use strict";var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},e(t,r)};var r=function(){return r=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},r.apply(this,arguments)};function n(t,e,r,n){return new(r||(r=Promise))((function(o,i){function s(t){try{c(n.next(t))}catch(t){i(t)}}function a(t){try{c(n.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}c((n=n.apply(t,e||[])).next())}))}function o(t,e){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=e.call(t,i)}catch(t){a=[6,t],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}"function"==typeof SuppressedError&&SuppressedError;var i={exports:{}};function s(){}s.prototype={on:function(t,e,r){var n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:r}),this},once:function(t,e,r){var n=this;function o(){n.off(t,o),e.apply(r,arguments)}return o._=e,this.on(t,o,r)},emit:function(t){for(var e=[].slice.call(arguments,1),r=((this.e||(this.e={}))[t]||[]).slice(),n=0,o=r.length;n<o;n++)r[n].fn.apply(r[n].ctx,e);return this},off:function(t,e){var r=this.e||(this.e={}),n=r[t],o=[];if(n&&e)for(var i=0,s=n.length;i<s;i++)n[i].fn!==e&&n[i].fn._!==e&&o.push(n[i]);return o.length?r[t]=o:delete r[t],this}},i.exports=s;var a=i.exports.TinyEmitter=s,c=function(t){var e=t[1];return null!=e},u=function(t){var e=t.properties,r=void 0===e?{}:e,n=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(t);o<n.length;o++)e.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(t,n[o])&&(r[n[o]]=t[n[o]])}return r}(t,["properties"]),o=function(t){return Object.entries(t).sort((function(t,e){var r=t[0],n=e[0];return r.localeCompare(n,void 0)}))};return JSON.stringify([o(n),o(r)])},l=function(t){return n(void 0,void 0,void 0,(function(){var e;return o(this,(function(r){switch(r.label){case 0:e=u(t),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,(i=e,n(void 0,void 0,void 0,(function(){var t,e,r,n,s;return o(this,(function(o){switch(o.label){case 0:if(t="undefined"!=typeof globalThis&&(null===(n=globalThis.crypto)||void 0===n?void 0:n.subtle)?null===(s=globalThis.crypto)||void 0===s?void 0:s.subtle:void 0,"undefined"==typeof TextEncoder||!(null==t?void 0:t.digest)||"undefined"==typeof Uint8Array)throw new Error("Hashing function not available");return e=(new TextEncoder).encode(i),[4,t.digest("SHA-256",e)];case 1:return r=o.sent(),[2,Array.from(new Uint8Array(r)).map((function(t){return t.toString(16).padStart(2,"0")})).join("")]}}))})))];case 2:return[2,r.sent()];case 3:return r.sent(),[2,e];case 4:return[2]}var i}))}))},h="unleash-js@3.7.2",p=function(){},f=function(){function t(t){var e=t.onError,r=t.onSent,n=t.appName,o=t.metricsInterval,i=t.disableMetrics,s=void 0!==i&&i,a=t.url,c=t.clientKey,u=t.fetch,l=t.headerName,h=t.customHeaders,f=void 0===h?{}:h,d=t.metricsIntervalInitial,v=t.connectionId;this.onError=e,this.onSent=r||p,this.disabled=s,this.metricsInterval=1e3*o,this.metricsIntervalInitial=1e3*d,this.appName=n,this.url=a instanceof URL?a:new URL(a),this.clientKey=c,this.bucket=this.createEmptyBucket(),this.fetch=u,this.headerName=l,this.customHeaders=f,this.connectionId=v}return t.prototype.start=function(){var t=this;if(this.disabled)return!1;"number"==typeof this.metricsInterval&&this.metricsInterval>0&&(this.metricsIntervalInitial>0?setTimeout((function(){t.startTimer(),t.sendMetrics()}),this.metricsIntervalInitial):this.startTimer())},t.prototype.stop=function(){this.timer&&(clearTimeout(this.timer),delete this.timer)},t.prototype.createEmptyBucket=function(){return{start:new Date,stop:null,toggles:{}}},t.prototype.getHeaders=function(){var t,e=((t={})[this.headerName]=this.clientKey,t.Accept="application/json",t["Content-Type"]="application/json",t["x-unleash-sdk"]=h,t["x-unleash-connection-id"]=this.connectionId,t["x-unleash-appname"]=this.appName,t);return Object.entries(this.customHeaders).filter(c).forEach((function(t){var r=t[0],n=t[1];return e[r]=n})),e},t.prototype.sendMetrics=function(){return n(this,void 0,void 0,(function(){var t,e,r;return o(this,(function(n){switch(n.label){case 0:if(t="".concat(this.url,"/client/metrics"),e=this.getPayload(),this.bucketIsEmpty(e))return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.fetch(t,{cache:"no-cache",method:"POST",headers:this.getHeaders(),body:JSON.stringify(e)})];case 2:return n.sent(),this.onSent(e),[3,4];case 3:return r=n.sent(),console.error("Unleash: unable to send feature metrics",r),this.onError(r),[3,4];case 4:return[2]}}))}))},t.prototype.count=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t][e?"yes":"no"]++,!0)},t.prototype.countVariant=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t].variants[e]?this.bucket.toggles[t].variants[e]+=1:this.bucket.toggles[t].variants[e]=1,!0)},t.prototype.assertBucket=function(t){if(this.disabled||!this.bucket)return!1;this.bucket.toggles[t]||(this.bucket.toggles[t]={yes:0,no:0,variants:{}})},t.prototype.startTimer=function(){var t=this;this.timer=setInterval((function(){t.sendMetrics()}),this.metricsInterval)},t.prototype.bucketIsEmpty=function(t){return 0===Object.keys(t.bucket.toggles).length},t.prototype.getPayload=function(){var t=r(r({},this.bucket),{stop:new Date});return this.bucket=this.createEmptyBucket(),{bucket:t,appName:this.appName,instanceId:"browser"}},t}(),d=function(){function t(){this.store=new Map}return t.prototype.save=function(t,e){return n(this,void 0,void 0,(function(){return o(this,(function(r){return this.store.set(t,e),[2]}))}))},t.prototype.get=function(t){return n(this,void 0,void 0,(function(){return o(this,(function(e){return[2,this.store.get(t)]}))}))},t}(),v=function(){function t(t){void 0===t&&(t="unleash:repository"),this.prefix=t}return t.prototype.save=function(t,e){return n(this,void 0,void 0,(function(){var r,n;return o(this,(function(o){r=JSON.stringify(e),n="".concat(this.prefix,":").concat(t);try{window.localStorage.setItem(n,r)}catch(t){console.error(t)}return[2]}))}))},t.prototype.get=function(t){try{var e="".concat(this.prefix,":").concat(t),r=window.localStorage.getItem(e);return r?JSON.parse(r):void 0}catch(t){console.error(t)}},t}();let m;const g=new Uint8Array(16);function y(){if(!m&&(m="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!m))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return m(g)}const b=[];for(let t=0;t<256;++t)b.push((t+256).toString(16).slice(1));var x={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function T(t,e,r){if(x.randomUUID&&!e&&!t)return x.randomUUID();const n=(t=t||{}).random||(t.rng||y)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,e){r=r||0;for(let t=0;t<16;++t)e[r+t]=n[t];return e}return function(t,e=0){return b[t[e+0]]+b[t[e+1]]+b[t[e+2]]+b[t[e+3]]+"-"+b[t[e+4]]+b[t[e+5]]+"-"+b[t[e+6]]+b[t[e+7]]+"-"+b[t[e+8]]+b[t[e+9]]+"-"+b[t[e+10]]+b[t[e+11]]+b[t[e+12]]+b[t[e+13]]+b[t[e+14]]+b[t[e+15]]}(n)}var w=function(){function t(){}return t.prototype.generateEventId=function(){return T()},t.prototype.createImpressionEvent=function(t,e,n,o,i,s){var a=this.createBaseEvent(t,e,n,o,i);return s?r(r({},a),{variant:s}):a},t.prototype.createBaseEvent=function(t,e,r,n,o){return{eventType:n,eventId:this.generateEventId(),context:t,enabled:e,featureName:r,impressionData:o}},t}(),E=["userId","sessionId","remoteAddress","currentTime"],S=function(t){return E.includes(t)},I={INIT:"initialized",ERROR:"error",READY:"ready",UPDATE:"update",IMPRESSION:"impression",SENT:"sent",RECOVERED:"recovered"},R="isEnabled",O="getVariant",k={name:"disabled",enabled:!1,feature_enabled:!1},N="repo",A="repoLastUpdateTimestamp",U=function(){try{if("undefined"!=typeof window&&"fetch"in window)return fetch.bind(window);if("fetch"in globalThis)return fetch.bind(globalThis)}catch(t){console.error('Unleash failed to resolve "fetch"',t)}},D=function(t){function i(e){var n=e.storageProvider,o=e.url,i=e.clientKey,s=e.disableRefresh,a=void 0!==s&&s,c=e.refreshInterval,u=void 0===c?30:c,l=e.metricsInterval,h=void 0===l?30:l,p=e.metricsIntervalInitial,m=void 0===p?2:p,g=e.disableMetrics,y=void 0!==g&&g,b=e.appName,x=e.environment,T=void 0===x?"default":x,E=e.context,S=e.fetch,R=void 0===S?U():S,O=e.createAbortController,k=void 0===O?function(){try{if("undefined"!=typeof window&&"AbortController"in window)return function(){return new window.AbortController};if("fetch"in globalThis)return function(){return new globalThis.AbortController}}catch(t){console.error('Unleash failed to resolve "AbortController" factory',t)}}():O,N=e.bootstrap,A=e.bootstrapOverride,D=void 0===A||A,j=e.headerName,P=void 0===j?"Authorization":j,C=e.customHeaders,L=void 0===C?{}:C,H=e.impressionDataAll,M=void 0!==H&&H,F=e.usePOSTrequests,_=void 0!==F&&F,K=e.experimental,V=t.call(this)||this;if(V.toggles=[],V.etag="",V.readyEventEmitted=!1,V.fetchedFromServer=!1,V.usePOSTrequests=!1,V.started=!1,!o)throw new Error("url is required");if(!i)throw new Error("clientKey is required");if(!b)throw new Error("appName is required.");return V.eventsHandler=new w,V.impressionDataAll=M,V.toggles=N&&N.length>0?N:[],V.url=o instanceof URL?o:new URL(o),V.clientKey=i,V.headerName=P,V.customHeaders=L,V.storage=n||("undefined"!=typeof window?new v:new d),V.refreshInterval=a?0:1e3*u,V.context=r({appName:b,environment:T},E),V.usePOSTrequests=_,V.sdkState="initializing",V.experimental=r({},K),(null==K?void 0:K.togglesStorageTTL)&&(null==K?void 0:K.togglesStorageTTL)>0&&(V.experimental.togglesStorageTTL=1e3*K.togglesStorageTTL),V.lastRefreshTimestamp=0,V.ready=new Promise((function(t){V.init().then(t).catch((function(e){console.error(e),V.sdkState="error",V.emit(I.ERROR,e),V.lastError=e,t()}))})),R||console.error('Unleash: You must either provide your own "fetch" implementation or run in an environment where "fetch" is available.'),k||console.error('Unleash: You must either provide your own "AbortController" implementation or run in an environment where "AbortController" is available.'),V.fetch=R,V.createAbortController=k,V.bootstrap=N&&N.length>0?N:void 0,V.bootstrapOverride=D,V.connectionId="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})),V.metrics=new f({onError:V.emit.bind(V,I.ERROR),onSent:V.emit.bind(V,I.SENT),appName:b,metricsInterval:h,disableMetrics:y,url:V.url,clientKey:i,fetch:R,headerName:P,customHeaders:L,metricsIntervalInitial:m,connectionId:V.connectionId}),V}return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}(i,t),i.prototype.getAllToggles=function(){return function(t,e,r){if(r||2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}([],this.toggles,!0)},i.prototype.isEnabled=function(t){var e,r=this.toggles.find((function(e){return e.name===t})),n=!!r&&r.enabled;if(this.metrics.count(t,n),(null==r?void 0:r.impressionData)||this.impressionDataAll){var o=this.eventsHandler.createImpressionEvent(this.context,n,t,R,null!==(e=null==r?void 0:r.impressionData)&&void 0!==e?e:void 0);this.emit(I.IMPRESSION,o)}return n},i.prototype.getVariant=function(t){var e,n=this.toggles.find((function(e){return e.name===t})),o=(null==n?void 0:n.enabled)||!1,i=n?n.variant:k;if(i.name&&this.metrics.countVariant(t,i.name),this.metrics.count(t,o),(null==n?void 0:n.impressionData)||this.impressionDataAll){var s=this.eventsHandler.createImpressionEvent(this.context,o,t,O,null!==(e=null==n?void 0:n.impressionData)&&void 0!==e?e:void 0,i.name);this.emit(I.IMPRESSION,s)}return r(r({},i),{feature_enabled:o})},i.prototype.updateToggles=function(){return n(this,void 0,void 0,(function(){var t=this;return o(this,(function(e){switch(e.label){case 0:return this.timerRef||this.fetchedFromServer?[4,this.fetchToggles()]:[3,2];case 1:return e.sent(),[3,4];case 2:return this.started?[4,new Promise((function(e){var r=function(){t.fetchToggles().then((function(){t.off(I.READY,r),e()}))};t.once(I.READY,r)}))]:[3,4];case 3:e.sent(),e.label=4;case 4:return[2]}}))}))},i.prototype.updateContext=function(t){return n(this,void 0,void 0,(function(){var e;return o(this,(function(n){switch(n.label){case 0:return(t.appName||t.environment)&&console.warn("appName and environment are static. They can't be updated with updateContext."),e={environment:this.context.environment,appName:this.context.appName,sessionId:this.context.sessionId},this.context=r(r({},e),t),[4,this.updateToggles()];case 1:return n.sent(),[2]}}))}))},i.prototype.getContext=function(){return r({},this.context)},i.prototype.setContextField=function(t,e){var n,o;if(S(t))this.context=r(r({},this.context),((n={})[t]=e,n));else{var i=r(r({},this.context.properties),((o={})[t]=e,o));this.context=r(r({},this.context),{properties:i})}this.updateToggles()},i.prototype.removeContextField=function(t){var e;S(t)?this.context=r(r({},this.context),((e={})[t]=void 0,e)):"object"==typeof this.context.properties&&delete this.context.properties[t],this.updateToggles()},i.prototype.setReady=function(){this.readyEventEmitted=!0,this.emit(I.READY)},i.prototype.init=function(){return n(this,void 0,void 0,(function(){var t,e,n;return o(this,(function(o){switch(o.label){case 0:return[4,this.resolveSessionId()];case 1:return t=o.sent(),this.context=r({sessionId:t},this.context),e=this,[4,this.storage.get(N)];case 2:return e.toggles=o.sent()||[],n=this,[4,this.getLastRefreshTimestamp()];case 3:return n.lastRefreshTimestamp=o.sent(),!this.bootstrap||!this.bootstrapOverride&&0!==this.toggles.length?[3,6]:[4,this.storage.save(N,this.bootstrap)];case 4:return o.sent(),this.toggles=this.bootstrap,this.sdkState="healthy",[4,this.storeLastRefreshTimestamp()];case 5:o.sent(),this.setReady(),o.label=6;case 6:return this.sdkState="healthy",this.emit(I.INIT),[2]}}))}))},i.prototype.start=function(){return n(this,void 0,void 0,(function(){var t,e=this;return o(this,(function(r){switch(r.label){case 0:return this.started=!0,this.timerRef?(console.error("Unleash SDK has already started, if you want to restart the SDK you should call client.stop() before starting again."),[2]):[4,this.ready];case 1:return r.sent(),this.metrics.start(),t=this.refreshInterval,[4,this.initialFetchToggles()];case 2:return r.sent(),t>0&&(this.timerRef=setInterval((function(){return e.fetchToggles()}),t)),[2]}}))}))},i.prototype.stop=function(){this.timerRef&&(clearInterval(this.timerRef),this.timerRef=void 0),this.metrics.stop()},i.prototype.isReady=function(){return this.readyEventEmitted},i.prototype.getError=function(){return"error"===this.sdkState?this.lastError:void 0},i.prototype.sendMetrics=function(){return this.metrics.sendMetrics()},i.prototype.resolveSessionId=function(){return n(this,void 0,void 0,(function(){var t;return o(this,(function(e){switch(e.label){case 0:return this.context.sessionId?[2,this.context.sessionId]:[4,this.storage.get("sessionId")];case 1:return(t=e.sent())?[3,3]:(t=Math.floor(1e9*Math.random()),[4,this.storage.save("sessionId",t.toString(10))]);case 2:e.sent(),e.label=3;case 3:return[2,t.toString(10)]}}))}))},i.prototype.getHeaders=function(){var t,e=this.usePOSTrequests,r=((t={})[this.headerName]=this.clientKey,t.Accept="application/json",t["x-unleash-sdk"]=h,t["x-unleash-connection-id"]=this.connectionId,t["x-unleash-appname"]=this.context.appName,t);return e&&(r["Content-Type"]="application/json"),this.etag&&(r["If-None-Match"]=this.etag),Object.entries(this.customHeaders).filter(c).forEach((function(t){var e=t[0],n=t[1];return r[e]=n})),r},i.prototype.storeToggles=function(t){return n(this,void 0,void 0,(function(){return o(this,(function(e){switch(e.label){case 0:return this.toggles=t,this.emit(I.UPDATE),[4,this.storage.save(N,t)];case 1:return e.sent(),[2]}}))}))},i.prototype.isTogglesStorageTTLEnabled=function(){var t;return!!((null===(t=this.experimental)||void 0===t?void 0:t.togglesStorageTTL)&&this.experimental.togglesStorageTTL>0)},i.prototype.isUpToDate=function(){var t;if(!this.isTogglesStorageTTLEnabled())return!1;var e=Date.now(),r=(null===(t=this.experimental)||void 0===t?void 0:t.togglesStorageTTL)||0;return this.lastRefreshTimestamp>0&&this.lastRefreshTimestamp<=e&&e-this.lastRefreshTimestamp<=r},i.prototype.getLastRefreshTimestamp=function(){return n(this,void 0,void 0,(function(){var t,e;return o(this,(function(r){switch(r.label){case 0:return this.isTogglesStorageTTLEnabled()?[4,this.storage.get(A)]:[3,3];case 1:return t=r.sent(),[4,l(this.context)];case 2:return e=r.sent(),[2,(null==t?void 0:t.key)===e?t.timestamp:0];case 3:return[2,0]}}))}))},i.prototype.storeLastRefreshTimestamp=function(){return n(this,void 0,void 0,(function(){var t,e;return o(this,(function(r){switch(r.label){case 0:return this.isTogglesStorageTTLEnabled()?(this.lastRefreshTimestamp=Date.now(),e={},[4,l(this.context)]):[3,3];case 1:return e.key=r.sent(),e.timestamp=this.lastRefreshTimestamp,t=e,[4,this.storage.save(A,t)];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},i.prototype.initialFetchToggles=function(){if(!this.isUpToDate())return this.fetchToggles();this.fetchedFromServer||(this.fetchedFromServer=!0,this.setReady())},i.prototype.fetchToggles=function(){return n(this,void 0,void 0,(function(){var t,e,r,n,i,s,a,u,l;return o(this,(function(o){switch(o.label){case 0:if(!this.fetch)return[3,9];this.abortController&&this.abortController.abort(),this.abortController=null===(l=this.createAbortController)||void 0===l?void 0:l.call(this),t=this.abortController?this.abortController.signal:void 0,o.label=1;case 1:return o.trys.push([1,7,8,9]),e=this.usePOSTrequests,r=e?this.url:function(t,e){var r=new URL(t.toString());return Object.entries(e).filter(c).forEach((function(t){var e=t[0],n=t[1];"properties"===e&&n?Object.entries(n).filter(c).forEach((function(t){var e=t[0],n=t[1];return r.searchParams.append("properties[".concat(e,"]"),n)})):r.searchParams.append(e,n)})),r}(this.url,this.context),n=e?"POST":"GET",i=e?JSON.stringify({context:this.context}):void 0,[4,this.fetch(r.toString(),{method:n,cache:"no-cache",headers:this.getHeaders(),body:i,signal:t})];case 2:return s=o.sent(),"error"===this.sdkState&&s.status<400&&(this.sdkState="healthy",this.emit(I.RECOVERED)),s.ok?(this.etag=s.headers.get("ETag")||"",[4,s.json()]):[3,5];case 3:return a=o.sent(),[4,this.storeToggles(a.toggles)];case 4:return o.sent(),"healthy"!==this.sdkState&&(this.sdkState="healthy"),this.fetchedFromServer||(this.fetchedFromServer=!0,this.setReady()),this.storeLastRefreshTimestamp(),[3,6];case 5:304===s.status?this.storeLastRefreshTimestamp():(console.error("Unleash: Fetching feature toggles did not have an ok response"),this.sdkState="error",this.emit(I.ERROR,{type:"HttpError",code:s.status}),this.lastError={type:"HttpError",code:s.status}),o.label=6;case 6:return[3,9];case 7:return"object"==typeof(u=o.sent())&&null!==u&&"name"in u&&"AbortError"===u.name||(console.error("Unleash: unable to fetch feature toggles",u),this.sdkState="error",this.emit(I.ERROR,u),this.lastError=u),[3,9];case 8:return this.abortController=null,[7];case 9:return[2]}}))}))},i}(a);t.EVENTS=I,t.InMemoryStorageProvider=d,t.LocalStorageProvider=v,t.UnleashClient=D,t.lastUpdateKey=A,t.resolveFetch=U})); | ||
!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).unleash={})}(this,(function(t){"use strict";var e=function(t,r){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r])},e(t,r)};var r=function(){return r=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t},r.apply(this,arguments)};function n(t,e,r,n){return new(r||(r=Promise))((function(o,i){function s(t){try{c(n.next(t))}catch(t){i(t)}}function a(t){try{c(n.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(s,a)}c((n=n.apply(t,e||[])).next())}))}function o(t,e){var r,n,o,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function a(a){return function(c){return function(a){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,a[0]&&(i=0)),i;)try{if(r=1,n&&(o=2&a[0]?n.return:a[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,a[1])).done)return o;switch(n=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,n=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=i.trys,(o=o.length>0&&o[o.length-1])||6!==a[0]&&2!==a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=e.call(t,i)}catch(t){a=[6,t],n=0}finally{r=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,c])}}}"function"==typeof SuppressedError&&SuppressedError;var i={exports:{}};function s(){}s.prototype={on:function(t,e,r){var n=this.e||(this.e={});return(n[t]||(n[t]=[])).push({fn:e,ctx:r}),this},once:function(t,e,r){var n=this;function o(){n.off(t,o),e.apply(r,arguments)}return o._=e,this.on(t,o,r)},emit:function(t){for(var e=[].slice.call(arguments,1),r=((this.e||(this.e={}))[t]||[]).slice(),n=0,o=r.length;n<o;n++)r[n].fn.apply(r[n].ctx,e);return this},off:function(t,e){var r=this.e||(this.e={}),n=r[t],o=[];if(n&&e)for(var i=0,s=n.length;i<s;i++)n[i].fn!==e&&n[i].fn._!==e&&o.push(n[i]);return o.length?r[t]=o:delete r[t],this}},i.exports=s;var a=i.exports.TinyEmitter=s,c=function(t){var e=t[1];return null!=e},u=function(t){var e=t.properties,r=void 0===e?{}:e,n=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(n=Object.getOwnPropertySymbols(t);o<n.length;o++)e.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(t,n[o])&&(r[n[o]]=t[n[o]])}return r}(t,["properties"]),o=function(t){return Object.entries(t).sort((function(t,e){var r=t[0],n=e[0];return r.localeCompare(n,void 0)}))};return JSON.stringify([o(n),o(r)])},l=function(t){return n(void 0,void 0,void 0,(function(){var e;return o(this,(function(r){switch(r.label){case 0:e=u(t),r.label=1;case 1:return r.trys.push([1,3,,4]),[4,(i=e,n(void 0,void 0,void 0,(function(){var t,e,r,n,s;return o(this,(function(o){switch(o.label){case 0:if(t="undefined"!=typeof globalThis&&(null===(n=globalThis.crypto)||void 0===n?void 0:n.subtle)?null===(s=globalThis.crypto)||void 0===s?void 0:s.subtle:void 0,"undefined"==typeof TextEncoder||!(null==t?void 0:t.digest)||"undefined"==typeof Uint8Array)throw new Error("Hashing function not available");return e=(new TextEncoder).encode(i),[4,t.digest("SHA-256",e)];case 1:return r=o.sent(),[2,Array.from(new Uint8Array(r)).map((function(t){return t.toString(16).padStart(2,"0")})).join("")]}}))})))];case 2:return[2,r.sent()];case 3:return r.sent(),[2,e];case 4:return[2]}var i}))}))},h=function(t){var e,r=t.clientKey,n=t.appName,o=t.connectionId,i=t.customHeaders,s=t.headerName,a=void 0===s?"authorization":s,u=t.etag,l=t.isPost,h=((e={accept:"application/json"})[a.toLocaleLowerCase()]=r,e["unleash-sdk"]="unleash-client-js:3.7.3",e["unleash-appname"]=n,e);return l&&(h["content-type"]="application/json"),u&&(h["if-none-match"]=u),Object.entries(i||{}).filter(c).forEach((function(t){var e=t[0],r=t[1];return h[e.toLocaleLowerCase()]=r})),h["unleash-connection-id"]=o,h},p=function(){},d=function(){function t(t){var e=t.onError,r=t.onSent,n=t.appName,o=t.metricsInterval,i=t.disableMetrics,s=void 0!==i&&i,a=t.url,c=t.clientKey,u=t.fetch,l=t.headerName,h=t.customHeaders,d=void 0===h?{}:h,f=t.metricsIntervalInitial,v=t.connectionId;this.onError=e,this.onSent=r||p,this.disabled=s,this.metricsInterval=1e3*o,this.metricsIntervalInitial=1e3*f,this.appName=n,this.url=a instanceof URL?a:new URL(a),this.clientKey=c,this.bucket=this.createEmptyBucket(),this.fetch=u,this.headerName=l,this.customHeaders=d,this.connectionId=v}return t.prototype.start=function(){var t=this;if(this.disabled)return!1;"number"==typeof this.metricsInterval&&this.metricsInterval>0&&(this.metricsIntervalInitial>0?setTimeout((function(){t.startTimer(),t.sendMetrics()}),this.metricsIntervalInitial):this.startTimer())},t.prototype.stop=function(){this.timer&&(clearTimeout(this.timer),delete this.timer)},t.prototype.createEmptyBucket=function(){return{start:new Date,stop:null,toggles:{}}},t.prototype.getHeaders=function(){return h({clientKey:this.clientKey,appName:this.appName,connectionId:this.connectionId,customHeaders:this.customHeaders,headerName:this.headerName,isPost:!0})},t.prototype.sendMetrics=function(){return n(this,void 0,void 0,(function(){var t,e,r;return o(this,(function(n){switch(n.label){case 0:if(t="".concat(this.url,"/client/metrics"),e=this.getPayload(),this.bucketIsEmpty(e))return[2];n.label=1;case 1:return n.trys.push([1,3,,4]),[4,this.fetch(t,{cache:"no-cache",method:"POST",headers:this.getHeaders(),body:JSON.stringify(e)})];case 2:return n.sent(),this.onSent(e),[3,4];case 3:return r=n.sent(),console.error("Unleash: unable to send feature metrics",r),this.onError(r),[3,4];case 4:return[2]}}))}))},t.prototype.count=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t][e?"yes":"no"]++,!0)},t.prototype.countVariant=function(t,e){return!(this.disabled||!this.bucket)&&(this.assertBucket(t),this.bucket.toggles[t].variants[e]?this.bucket.toggles[t].variants[e]+=1:this.bucket.toggles[t].variants[e]=1,!0)},t.prototype.assertBucket=function(t){if(this.disabled||!this.bucket)return!1;this.bucket.toggles[t]||(this.bucket.toggles[t]={yes:0,no:0,variants:{}})},t.prototype.startTimer=function(){var t=this;this.timer=setInterval((function(){t.sendMetrics()}),this.metricsInterval)},t.prototype.bucketIsEmpty=function(t){return 0===Object.keys(t.bucket.toggles).length},t.prototype.getPayload=function(){var t=r(r({},this.bucket),{stop:new Date});return this.bucket=this.createEmptyBucket(),{bucket:t,appName:this.appName,instanceId:"browser"}},t}(),f=function(){function t(){this.store=new Map}return t.prototype.save=function(t,e){return n(this,void 0,void 0,(function(){return o(this,(function(r){return this.store.set(t,e),[2]}))}))},t.prototype.get=function(t){return n(this,void 0,void 0,(function(){return o(this,(function(e){return[2,this.store.get(t)]}))}))},t}(),v=function(){function t(t){void 0===t&&(t="unleash:repository"),this.prefix=t}return t.prototype.save=function(t,e){return n(this,void 0,void 0,(function(){var r,n;return o(this,(function(o){r=JSON.stringify(e),n="".concat(this.prefix,":").concat(t);try{window.localStorage.setItem(n,r)}catch(t){console.error(t)}return[2]}))}))},t.prototype.get=function(t){try{var e="".concat(this.prefix,":").concat(t),r=window.localStorage.getItem(e);return r?JSON.parse(r):void 0}catch(t){console.error(t)}},t}();let m;const g=new Uint8Array(16);function y(){if(!m&&(m="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!m))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return m(g)}const b=[];for(let t=0;t<256;++t)b.push((t+256).toString(16).slice(1));var T={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function x(t,e,r){if(T.randomUUID&&!e&&!t)return T.randomUUID();const n=(t=t||{}).random||(t.rng||y)();if(n[6]=15&n[6]|64,n[8]=63&n[8]|128,e){r=r||0;for(let t=0;t<16;++t)e[r+t]=n[t];return e}return function(t,e=0){return b[t[e+0]]+b[t[e+1]]+b[t[e+2]]+b[t[e+3]]+"-"+b[t[e+4]]+b[t[e+5]]+"-"+b[t[e+6]]+b[t[e+7]]+"-"+b[t[e+8]]+b[t[e+9]]+"-"+b[t[e+10]]+b[t[e+11]]+b[t[e+12]]+b[t[e+13]]+b[t[e+14]]+b[t[e+15]]}(n)}var w=function(){function t(){}return t.prototype.generateEventId=function(){return x()},t.prototype.createImpressionEvent=function(t,e,n,o,i,s){var a=this.createBaseEvent(t,e,n,o,i);return s?r(r({},a),{variant:s}):a},t.prototype.createBaseEvent=function(t,e,r,n,o){return{eventType:n,eventId:this.generateEventId(),context:t,enabled:e,featureName:r,impressionData:o}},t}(),E=["userId","sessionId","remoteAddress","currentTime"],S=function(t){return E.includes(t)},I={INIT:"initialized",ERROR:"error",READY:"ready",UPDATE:"update",IMPRESSION:"impression",SENT:"sent",RECOVERED:"recovered"},R="isEnabled",O="getVariant",k={name:"disabled",enabled:!1,feature_enabled:!1},N="repo",U="repoLastUpdateTimestamp",A=function(){try{if("undefined"!=typeof window&&"fetch"in window)return fetch.bind(window);if("fetch"in globalThis)return fetch.bind(globalThis)}catch(t){console.error('Unleash failed to resolve "fetch"',t)}},P=function(t){function i(e){var n=e.storageProvider,o=e.url,i=e.clientKey,s=e.disableRefresh,a=void 0!==s&&s,c=e.refreshInterval,u=void 0===c?30:c,l=e.metricsInterval,h=void 0===l?30:l,p=e.metricsIntervalInitial,m=void 0===p?2:p,g=e.disableMetrics,y=void 0!==g&&g,b=e.appName,T=e.environment,x=void 0===T?"default":T,E=e.context,S=e.fetch,R=void 0===S?A():S,O=e.createAbortController,k=void 0===O?function(){try{if("undefined"!=typeof window&&"AbortController"in window)return function(){return new window.AbortController};if("fetch"in globalThis)return function(){return new globalThis.AbortController}}catch(t){console.error('Unleash failed to resolve "AbortController" factory',t)}}():O,N=e.bootstrap,U=e.bootstrapOverride,P=void 0===U||U,D=e.headerName,L=void 0===D?"Authorization":D,C=e.customHeaders,j=void 0===C?{}:C,H=e.impressionDataAll,M=void 0!==H&&H,K=e.usePOSTrequests,F=void 0!==K&&K,_=e.experimental,V=t.call(this)||this;if(V.toggles=[],V.etag="",V.readyEventEmitted=!1,V.fetchedFromServer=!1,V.usePOSTrequests=!1,V.started=!1,!o)throw new Error("url is required");if(!i)throw new Error("clientKey is required");if(!b)throw new Error("appName is required.");return V.eventsHandler=new w,V.impressionDataAll=M,V.toggles=N&&N.length>0?N:[],V.url=o instanceof URL?o:new URL(o),V.clientKey=i,V.headerName=L,V.customHeaders=j,V.storage=n||("undefined"!=typeof window?new v:new f),V.refreshInterval=a?0:1e3*u,V.context=r({appName:b,environment:x},E),V.usePOSTrequests=F,V.sdkState="initializing",V.experimental=r({},_),(null==_?void 0:_.togglesStorageTTL)&&(null==_?void 0:_.togglesStorageTTL)>0&&(V.experimental.togglesStorageTTL=1e3*_.togglesStorageTTL),V.lastRefreshTimestamp=0,V.ready=new Promise((function(t){V.init().then(t).catch((function(e){console.error(e),V.sdkState="error",V.emit(I.ERROR,e),V.lastError=e,t()}))})),R||console.error('Unleash: You must either provide your own "fetch" implementation or run in an environment where "fetch" is available.'),k||console.error('Unleash: You must either provide your own "AbortController" implementation or run in an environment where "AbortController" is available.'),V.fetch=R,V.createAbortController=k,V.bootstrap=N&&N.length>0?N:void 0,V.bootstrapOverride=P,V.connectionId="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})),V.metrics=new d({onError:V.emit.bind(V,I.ERROR),onSent:V.emit.bind(V,I.SENT),appName:b,metricsInterval:h,disableMetrics:y,url:V.url,clientKey:i,fetch:R,headerName:L,customHeaders:j,metricsIntervalInitial:m,connectionId:V.connectionId}),V}return function(t,r){if("function"!=typeof r&&null!==r)throw new TypeError("Class extends value "+String(r)+" is not a constructor or null");function n(){this.constructor=t}e(t,r),t.prototype=null===r?Object.create(r):(n.prototype=r.prototype,new n)}(i,t),i.prototype.getAllToggles=function(){return function(t,e,r){if(r||2===arguments.length)for(var n,o=0,i=e.length;o<i;o++)!n&&o in e||(n||(n=Array.prototype.slice.call(e,0,o)),n[o]=e[o]);return t.concat(n||Array.prototype.slice.call(e))}([],this.toggles,!0)},i.prototype.isEnabled=function(t){var e,r=this.toggles.find((function(e){return e.name===t})),n=!!r&&r.enabled;if(this.metrics.count(t,n),(null==r?void 0:r.impressionData)||this.impressionDataAll){var o=this.eventsHandler.createImpressionEvent(this.context,n,t,R,null!==(e=null==r?void 0:r.impressionData)&&void 0!==e?e:void 0);this.emit(I.IMPRESSION,o)}return n},i.prototype.getVariant=function(t){var e,n=this.toggles.find((function(e){return e.name===t})),o=(null==n?void 0:n.enabled)||!1,i=n?n.variant:k;if(i.name&&this.metrics.countVariant(t,i.name),this.metrics.count(t,o),(null==n?void 0:n.impressionData)||this.impressionDataAll){var s=this.eventsHandler.createImpressionEvent(this.context,o,t,O,null!==(e=null==n?void 0:n.impressionData)&&void 0!==e?e:void 0,i.name);this.emit(I.IMPRESSION,s)}return r(r({},i),{feature_enabled:o})},i.prototype.updateToggles=function(){return n(this,void 0,void 0,(function(){var t=this;return o(this,(function(e){switch(e.label){case 0:return this.timerRef||this.fetchedFromServer?[4,this.fetchToggles()]:[3,2];case 1:return e.sent(),[3,4];case 2:return this.started?[4,new Promise((function(e){var r=function(){t.fetchToggles().then((function(){t.off(I.READY,r),e()}))};t.once(I.READY,r)}))]:[3,4];case 3:e.sent(),e.label=4;case 4:return[2]}}))}))},i.prototype.updateContext=function(t){return n(this,void 0,void 0,(function(){var e;return o(this,(function(n){switch(n.label){case 0:return(t.appName||t.environment)&&console.warn("appName and environment are static. They can't be updated with updateContext."),e={environment:this.context.environment,appName:this.context.appName,sessionId:this.context.sessionId},this.context=r(r({},e),t),[4,this.updateToggles()];case 1:return n.sent(),[2]}}))}))},i.prototype.getContext=function(){return r({},this.context)},i.prototype.setContextField=function(t,e){var n,o;if(S(t))this.context=r(r({},this.context),((n={})[t]=e,n));else{var i=r(r({},this.context.properties),((o={})[t]=e,o));this.context=r(r({},this.context),{properties:i})}this.updateToggles()},i.prototype.removeContextField=function(t){var e;S(t)?this.context=r(r({},this.context),((e={})[t]=void 0,e)):"object"==typeof this.context.properties&&delete this.context.properties[t],this.updateToggles()},i.prototype.setReady=function(){this.readyEventEmitted=!0,this.emit(I.READY)},i.prototype.init=function(){return n(this,void 0,void 0,(function(){var t,e,n;return o(this,(function(o){switch(o.label){case 0:return[4,this.resolveSessionId()];case 1:return t=o.sent(),this.context=r({sessionId:t},this.context),e=this,[4,this.storage.get(N)];case 2:return e.toggles=o.sent()||[],n=this,[4,this.getLastRefreshTimestamp()];case 3:return n.lastRefreshTimestamp=o.sent(),!this.bootstrap||!this.bootstrapOverride&&0!==this.toggles.length?[3,6]:[4,this.storage.save(N,this.bootstrap)];case 4:return o.sent(),this.toggles=this.bootstrap,this.sdkState="healthy",[4,this.storeLastRefreshTimestamp()];case 5:o.sent(),this.setReady(),o.label=6;case 6:return this.sdkState="healthy",this.emit(I.INIT),[2]}}))}))},i.prototype.start=function(){return n(this,void 0,void 0,(function(){var t,e=this;return o(this,(function(r){switch(r.label){case 0:return this.started=!0,this.timerRef?(console.error("Unleash SDK has already started, if you want to restart the SDK you should call client.stop() before starting again."),[2]):[4,this.ready];case 1:return r.sent(),this.metrics.start(),t=this.refreshInterval,[4,this.initialFetchToggles()];case 2:return r.sent(),t>0&&(this.timerRef=setInterval((function(){return e.fetchToggles()}),t)),[2]}}))}))},i.prototype.stop=function(){this.timerRef&&(clearInterval(this.timerRef),this.timerRef=void 0),this.metrics.stop()},i.prototype.isReady=function(){return this.readyEventEmitted},i.prototype.getError=function(){return"error"===this.sdkState?this.lastError:void 0},i.prototype.sendMetrics=function(){return this.metrics.sendMetrics()},i.prototype.resolveSessionId=function(){return n(this,void 0,void 0,(function(){var t;return o(this,(function(e){switch(e.label){case 0:return this.context.sessionId?[2,this.context.sessionId]:[4,this.storage.get("sessionId")];case 1:return(t=e.sent())?[3,3]:(t=Math.floor(1e9*Math.random()),[4,this.storage.save("sessionId",t.toString(10))]);case 2:e.sent(),e.label=3;case 3:return[2,t.toString(10)]}}))}))},i.prototype.getHeaders=function(){return h({clientKey:this.clientKey,connectionId:this.connectionId,appName:this.context.appName,customHeaders:this.customHeaders,headerName:this.headerName,etag:this.etag,isPost:this.usePOSTrequests})},i.prototype.storeToggles=function(t){return n(this,void 0,void 0,(function(){return o(this,(function(e){switch(e.label){case 0:return this.toggles=t,this.emit(I.UPDATE),[4,this.storage.save(N,t)];case 1:return e.sent(),[2]}}))}))},i.prototype.isTogglesStorageTTLEnabled=function(){var t;return!!((null===(t=this.experimental)||void 0===t?void 0:t.togglesStorageTTL)&&this.experimental.togglesStorageTTL>0)},i.prototype.isUpToDate=function(){var t;if(!this.isTogglesStorageTTLEnabled())return!1;var e=Date.now(),r=(null===(t=this.experimental)||void 0===t?void 0:t.togglesStorageTTL)||0;return this.lastRefreshTimestamp>0&&this.lastRefreshTimestamp<=e&&e-this.lastRefreshTimestamp<=r},i.prototype.getLastRefreshTimestamp=function(){return n(this,void 0,void 0,(function(){var t,e;return o(this,(function(r){switch(r.label){case 0:return this.isTogglesStorageTTLEnabled()?[4,this.storage.get(U)]:[3,3];case 1:return t=r.sent(),[4,l(this.context)];case 2:return e=r.sent(),[2,(null==t?void 0:t.key)===e?t.timestamp:0];case 3:return[2,0]}}))}))},i.prototype.storeLastRefreshTimestamp=function(){return n(this,void 0,void 0,(function(){var t,e;return o(this,(function(r){switch(r.label){case 0:return this.isTogglesStorageTTLEnabled()?(this.lastRefreshTimestamp=Date.now(),e={},[4,l(this.context)]):[3,3];case 1:return e.key=r.sent(),e.timestamp=this.lastRefreshTimestamp,t=e,[4,this.storage.save(U,t)];case 2:r.sent(),r.label=3;case 3:return[2]}}))}))},i.prototype.initialFetchToggles=function(){if(!this.isUpToDate())return this.fetchToggles();this.fetchedFromServer||(this.fetchedFromServer=!0,this.setReady())},i.prototype.fetchToggles=function(){return n(this,void 0,void 0,(function(){var t,e,r,n,i,s,a,u,l;return o(this,(function(o){switch(o.label){case 0:if(!this.fetch)return[3,9];this.abortController&&this.abortController.abort(),this.abortController=null===(l=this.createAbortController)||void 0===l?void 0:l.call(this),t=this.abortController?this.abortController.signal:void 0,o.label=1;case 1:return o.trys.push([1,7,8,9]),e=this.usePOSTrequests,r=e?this.url:function(t,e){var r=new URL(t.toString());return Object.entries(e).filter(c).forEach((function(t){var e=t[0],n=t[1];"properties"===e&&n?Object.entries(n).filter(c).forEach((function(t){var e=t[0],n=t[1];return r.searchParams.append("properties[".concat(e,"]"),n)})):r.searchParams.append(e,n)})),r}(this.url,this.context),n=e?"POST":"GET",i=e?JSON.stringify({context:this.context}):void 0,[4,this.fetch(r.toString(),{method:n,cache:"no-cache",headers:this.getHeaders(),body:i,signal:t})];case 2:return s=o.sent(),"error"===this.sdkState&&s.status<400&&(this.sdkState="healthy",this.emit(I.RECOVERED)),s.ok?(this.etag=s.headers.get("ETag")||"",[4,s.json()]):[3,5];case 3:return a=o.sent(),[4,this.storeToggles(a.toggles)];case 4:return o.sent(),"healthy"!==this.sdkState&&(this.sdkState="healthy"),this.fetchedFromServer||(this.fetchedFromServer=!0,this.setReady()),this.storeLastRefreshTimestamp(),[3,6];case 5:304===s.status?this.storeLastRefreshTimestamp():(console.error("Unleash: Fetching feature toggles did not have an ok response"),this.sdkState="error",this.emit(I.ERROR,{type:"HttpError",code:s.status}),this.lastError={type:"HttpError",code:s.status}),o.label=6;case 6:return[3,9];case 7:return"object"==typeof(u=o.sent())&&null!==u&&"name"in u&&"AbortError"===u.name||(console.error("Unleash: unable to fetch feature toggles",u),this.sdkState="error",this.emit(I.ERROR,u),this.lastError=u),[3,9];case 8:return this.abortController=null,[7];case 9:return[2]}}))}))},i}(a);t.EVENTS=I,t.InMemoryStorageProvider=f,t.LocalStorageProvider=v,t.UnleashClient=P,t.lastUpdateKey=U,t.resolveFetch=A})); | ||
//# sourceMappingURL=main.min.js.map |
{ | ||
"name": "unleash-proxy-client", | ||
"version": "3.7.2", | ||
"version": "3.7.3", | ||
"description": "A browser client that can be used together with Unleash Edge or the Unleash Frontend API.", | ||
@@ -5,0 +5,0 @@ "type": "module", |
@@ -9,6 +9,5 @@ import { TinyEmitter } from 'tiny-emitter'; | ||
computeContextHashValue, | ||
notNullOrUndefined, | ||
parseHeaders, | ||
urlWithContextAsQuery, | ||
} from './util'; | ||
import { sdkVersion } from './version'; | ||
import { uuidv4 } from './uuidv4'; | ||
@@ -474,20 +473,11 @@ | ||
private getHeaders() { | ||
const isPOST = this.usePOSTrequests; | ||
const headers = { | ||
[this.headerName]: this.clientKey, | ||
Accept: 'application/json', | ||
'x-unleash-sdk': sdkVersion, | ||
'x-unleash-connection-id': this.connectionId, | ||
'x-unleash-appname': this.context.appName, | ||
}; | ||
if (isPOST) { | ||
headers['Content-Type'] = 'application/json'; | ||
} | ||
if (this.etag) { | ||
headers['If-None-Match'] = this.etag; | ||
} | ||
Object.entries(this.customHeaders) | ||
.filter(notNullOrUndefined) | ||
.forEach(([name, value]) => (headers[name] = value)); | ||
return headers; | ||
return parseHeaders({ | ||
clientKey: this.clientKey, | ||
connectionId: this.connectionId, | ||
appName: this.context.appName, | ||
customHeaders: this.customHeaders, | ||
headerName: this.headerName, | ||
etag: this.etag, | ||
isPost: this.usePOSTrequests, | ||
}); | ||
} | ||
@@ -494,0 +484,0 @@ |
@@ -94,3 +94,3 @@ import { FetchMock } from 'jest-fetch-mock'; | ||
expect(requestBody.headers).toMatchObject({ | ||
NotAuthorization: '123', | ||
notauthorization: '123', | ||
}); | ||
@@ -275,3 +275,3 @@ }); | ||
const customHeaders = { | ||
Authorization: 'definitely-not-the-client-key', | ||
authorization: 'definitely-not-the-client-key', | ||
}; | ||
@@ -308,2 +308,33 @@ | ||
); | ||
test('Should use case-insensitive headers', () => { | ||
const metrics = new Metrics({ | ||
onError: console.error, | ||
appName: 'test', | ||
metricsInterval: 5, | ||
disableMetrics: false, | ||
url: 'http://localhost:3000', | ||
clientKey: '123', | ||
fetch: fetchMock, | ||
headerName: 'Authorization', | ||
customHeaders: { | ||
'Custom-Header': '123', | ||
'custom-header': '456', | ||
'unleash-APPname': 'override', | ||
'unleash-connection-id': 'override', | ||
}, | ||
connectionId: '123', | ||
metricsIntervalInitial: 2, | ||
}); | ||
metrics.count('foo', true); | ||
metrics.sendMetrics(); | ||
const requestBody = getTypeSafeRequest(fetchMock); | ||
expect(requestBody.headers).toMatchObject({ | ||
'custom-header': '456', | ||
'unleash-appname': 'override', | ||
'unleash-connection-id': '123', | ||
}); | ||
}); | ||
}); |
// Simplified version of: https://github.com/Unleash/unleash-client-node/blob/main/src/metrics.ts | ||
import { notNullOrUndefined } from './util'; | ||
import { sdkVersion } from './version'; | ||
import { parseHeaders } from './util'; | ||
@@ -125,16 +124,10 @@ export interface MetricsOptions { | ||
private getHeaders() { | ||
const headers = { | ||
[this.headerName]: this.clientKey, | ||
Accept: 'application/json', | ||
'Content-Type': 'application/json', | ||
'x-unleash-sdk': sdkVersion, | ||
'x-unleash-connection-id': this.connectionId, | ||
'x-unleash-appname': this.appName, | ||
}; | ||
Object.entries(this.customHeaders) | ||
.filter(notNullOrUndefined) | ||
.forEach(([name, value]) => (headers[name] = value)); | ||
return headers; | ||
return parseHeaders({ | ||
clientKey: this.clientKey, | ||
appName: this.appName, | ||
connectionId: this.connectionId, | ||
customHeaders: this.customHeaders, | ||
headerName: this.headerName, | ||
isPost: true, | ||
}); | ||
} | ||
@@ -141,0 +134,0 @@ |
@@ -6,2 +6,3 @@ import type { IContext } from '.'; | ||
urlWithContextAsQuery, | ||
parseHeaders, | ||
} from './util'; | ||
@@ -123,1 +124,117 @@ | ||
}); | ||
describe('parseHeaders', () => { | ||
const clientKey = 'test-client-key'; | ||
const appName = 'appName'; | ||
const connectionId = '1234-5678'; | ||
test('should set basic headers correctly', () => { | ||
const result = parseHeaders({ | ||
clientKey, | ||
appName, | ||
connectionId, | ||
}); | ||
expect(result).toEqual({ | ||
authorization: clientKey, | ||
'unleash-sdk': 'unleash-client-js:__VERSION__', | ||
'unleash-appname': appName, | ||
accept: 'application/json', | ||
'unleash-connection-id': connectionId, | ||
}); | ||
}); | ||
test('should set custom client key header name', () => { | ||
const result = parseHeaders({ | ||
clientKey, | ||
appName, | ||
connectionId, | ||
headerName: 'auth', | ||
}); | ||
expect(result).toMatchObject({ auth: clientKey }); | ||
expect(Object.keys(result)).not.toContain('authorization'); | ||
}); | ||
test('should add custom headers', () => { | ||
const customHeaders = { | ||
'custom-header': 'custom-value', | ||
'unleash-connection-id': 'should-not-be-overwritten', | ||
'unleash-appname': 'new-app-name', | ||
}; | ||
const result = parseHeaders({ | ||
clientKey, | ||
appName, | ||
connectionId, | ||
customHeaders, | ||
}); | ||
expect(Object.keys(result)).toHaveLength(6); | ||
expect(result).toMatchObject({ | ||
'custom-header': 'custom-value', | ||
'unleash-connection-id': connectionId, | ||
'unleash-appname': 'new-app-name', | ||
}); | ||
}); | ||
test('should include etag if provided', () => { | ||
const etag = '12345'; | ||
const result = parseHeaders({ | ||
clientKey, | ||
appName, | ||
connectionId, | ||
etag, | ||
}); | ||
expect(result['if-none-match']).toBe(etag); | ||
}); | ||
test('should handle custom headers in a case-insensitive way and normalize them', () => { | ||
const customHeaders = { | ||
'custom-HEADER': 'custom-value-1', | ||
'Custom-Header': 'custom-value-2', | ||
}; | ||
const result = parseHeaders({ | ||
clientKey, | ||
appName, | ||
connectionId, | ||
customHeaders, | ||
}); | ||
expect(result).toMatchObject({ | ||
'custom-header': 'custom-value-2', | ||
}); | ||
}); | ||
test('should ignore null or undefined custom headers', () => { | ||
const customHeaders = { | ||
header1: 'value1', | ||
header2: null as any, | ||
header3: undefined as any, | ||
}; | ||
const result = parseHeaders({ | ||
clientKey, | ||
appName, | ||
connectionId, | ||
customHeaders, | ||
}); | ||
expect(result).toEqual( | ||
expect.not.objectContaining({ | ||
header2: expect.anything(), | ||
header3: expect.anything(), | ||
}) | ||
); | ||
}); | ||
test('should include content-type for POST requests', () => { | ||
const result = parseHeaders({ | ||
clientKey, | ||
appName, | ||
connectionId, | ||
isPost: true, | ||
}); | ||
expect(result['content-type']).toBe('application/json'); | ||
}); | ||
}); |
import { IContext } from '.'; | ||
import { sdkVersion } from './version'; | ||
@@ -73,1 +74,44 @@ export const notNullOrUndefined = ([, value]: [string, string]) => | ||
}; | ||
export const parseHeaders = ({ | ||
clientKey, | ||
appName, | ||
connectionId, | ||
customHeaders, | ||
headerName = 'authorization', | ||
etag, | ||
isPost, | ||
}: { | ||
clientKey: string; | ||
connectionId: string; | ||
appName: string; | ||
customHeaders?: Record<string, string>; | ||
headerName?: string; | ||
etag?: string; | ||
isPost?: boolean; | ||
}): Record<string, string> => { | ||
const headers: Record<string, string> = { | ||
accept: 'application/json', | ||
[headerName.toLocaleLowerCase()]: clientKey, | ||
'unleash-sdk': sdkVersion, | ||
'unleash-appname': appName, | ||
}; | ||
if (isPost) { | ||
headers['content-type'] = 'application/json'; | ||
} | ||
if (etag) { | ||
headers['if-none-match'] = etag; | ||
} | ||
Object.entries(customHeaders || {}) | ||
.filter(notNullOrUndefined) | ||
.forEach( | ||
([name, value]) => (headers[name.toLocaleLowerCase()] = value) | ||
); | ||
headers['unleash-connection-id'] = connectionId; | ||
return headers; | ||
}; |
@@ -1,1 +0,1 @@ | ||
export const sdkVersion = `unleash-js@__VERSION__`; | ||
export const sdkVersion = `unleash-client-js:__VERSION__`; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
383781
4170