Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@harnessio/ff-javascript-client-sdk

Package Overview
Dependencies
Maintainers
0
Versions
113
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@harnessio/ff-javascript-client-sdk - npm Package Compare versions

Comparing version 1.28.0 to 1.29.0-rc.0

4

dist/sdk.cjs.js

@@ -1,2 +0,2 @@

var we=Object.create;var x=Object.defineProperty,Ae=Object.defineProperties,Te=Object.getOwnPropertyDescriptor,Oe=Object.getOwnPropertyDescriptors,De=Object.getOwnPropertyNames,ne=Object.getOwnPropertySymbols,Pe=Object.getPrototypeOf,ae=Object.prototype.hasOwnProperty,xe=Object.prototype.propertyIsEnumerable;var re=(n,e,r)=>e in n?x(n,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):n[e]=r,w=(n,e)=>{for(var r in e||(e={}))ae.call(e,r)&&re(n,r,e[r]);if(ne)for(var r of ne(e))xe.call(e,r)&&re(n,r,e[r]);return n},K=(n,e)=>Ae(n,Oe(e));var Me=(n,e)=>{for(var r in e)x(n,r,{get:e[r],enumerable:!0})},oe=(n,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of De(e))!ae.call(n,a)&&a!==r&&x(n,a,{get:()=>e[a],enumerable:!(s=Te(e,a))||s.enumerable});return n};var se=(n,e,r)=>(r=n!=null?we(Pe(n)):{},oe(e||!n||!n.__esModule?x(r,"default",{value:n,enumerable:!0}):r,n)),Fe=n=>oe(x({},"__esModule",{value:!0}),n);var v=(n,e,r)=>new Promise((s,a)=>{var l=R=>{try{E(r.next(R))}catch(u){a(u)}},h=R=>{try{E(r.throw(R))}catch(u){a(u)}},E=R=>R.done?s(R.value):Promise.resolve(R.value).then(l,h);E((r=r.apply(n,e)).next())});var je={};Me(je,{Event:()=>M,initialize:()=>Ke});module.exports=Fe(je);var he=se(require("jwt-decode")),me=se(require("mitt"));var M=(p=>(p.READY="ready",p.CONNECTED="connected",p.DISCONNECTED="disconnected",p.STOPPED="stopped",p.POLLING="polling",p.POLLING_STOPPED="polling stopped",p.FLAGS_LOADED="flags loaded",p.CACHE_LOADED="cache loaded",p.CHANGED="changed",p.ERROR="error",p.ERROR_CACHE="cache error",p.ERROR_METRICS="metrics error",p.ERROR_AUTH="auth error",p.ERROR_FETCH_FLAGS="fetch flags error",p.ERROR_FETCH_FLAG="fetch flag error",p.ERROR_STREAM="stream error",p))(M||{});var Ne={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},le=n=>{let e=w(w({},Ne),n);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},j=(n,e=!0)=>{e?setTimeout(n,0):n()},V=(n,e)=>Math.round(Math.random()*(e-n)+n),ce=n=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",r="",s=0,a=ke(JSON.stringify(n));for(;s<a.length;){let l=a.charCodeAt(s++),h=a.charCodeAt(s++),E=a.charCodeAt(s++),R=l>>2,u=(l&3)<<4|h>>4,y=(h&15)<<2|E>>6,A=E&63;isNaN(h)?y=A=64:isNaN(E)&&(A=64),r+=e.charAt(R)+e.charAt(u)+e.charAt(y)+e.charAt(A)}return r},ke=n=>n.replace(/\r\n/g,`
`).split("").map(e=>{let r=e.charCodeAt(0);return r<128?String.fromCharCode(r):r>127&&r<2048?String.fromCharCode(r>>6|192)+String.fromCharCode(r&63|128):String.fromCharCode(r>>12|224)+String.fromCharCode(r>>6&63|128)+String.fromCharCode(r&63|128)}).join("");function U(n){return function(...r){let[s,a]=n(r);return fetch(s,a)}}var ue=3e4,_=class{constructor(e,r,s,a,l,h,E,R,u,y){this.eventBus=e;this.configurations=r;this.url=s;this.apiKey=a;this.standardHeaders=l;this.fallbackPoller=h;this.logDebug=E;this.logError=R;this.eventCallback=u;this.maxRetries=y;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1;this.reconnectAttempts=0;this.retriesExhausted=!1}start(){let e=u=>{u.toString().split(/\r?\n/).forEach(r)},r=u=>{if(u.startsWith("data:")){let y=JSON.parse(u.substring(5));this.logDebugMessage("Received event from stream: ",y),this.eventCallback(y)}},s=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected"),this.reconnectAttempts=0},a=()=>{clearInterval(this.readTimeoutCheckerId);let u=V(1e3,1e4);if(this.reconnectAttempts++,this.logDebugMessage("Stream disconnected, will reconnect in "+u+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),this.reconnectAttempts>=5&&this.reconnectAttempts%5===0&&this.logErrorMessage(`Reconnection failed after ${this.reconnectAttempts} attempts; attempting further reconnections.`),this.reconnectAttempts>=this.maxRetries){this.retriesExhausted=!0,this.configurations.pollingEnabled?this.logErrorMessage("Max streaming retries reached. Staying in polling mode."):this.logErrorMessage("Max streaming retries reached. Polling mode is disabled and will receive no further flag updates until SDK client is restarted.");return}setTimeout(()=>this.start(),u)},l=u=>{this.retriesExhausted||(u&&this.logDebugMessage("Stream has issue",u),this.fallBackToPolling(),this.eventBus.emit("stream error",u),this.eventBus.emit("error",u),a())},h=w({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[u,y]of Object.entries(h))this.xhr.setRequestHeader(u,y);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{l(`Received XMLHttpRequest onLoad event: ${this.xhr.status}`)};let E=0,R=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(s(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),R=Date.now();let u=this.xhr.responseText.slice(E);E+=u.length,this.logDebugMessage("SSE GOT: "+u),e(u)},this.readTimeoutCheckerId=setInterval(()=>{R<Date.now()-ue&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},ue),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...r){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...r)}logErrorMessage(e,...r){this.logError(`Streaming: ${e}`,...r)}};function ge(n,e,r,s,a){let l=n in r,h=l?r[n]:e;return l&&s(n,h),a?{value:h,isDefaultValue:!l}:h}var F=class{constructor(e,r,s,a,l){this.fetchFlagsFn=e;this.configurations=r;this.eventBus=s;this.logDebug=a;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.isRunning&&this.attemptFetch().finally(()=>{this.isRunning&&(this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval))})}attemptFetch(){return v(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let r=yield this.fetchFlagsFn();if(r.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",r.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,r.error);let s=V(1e3,1e4);yield new Promise(a=>setTimeout(a,s))}})}stop(){this.timeoutId&&(this.isRunning=!1,clearTimeout(this.timeoutId),this.timeoutId=void 0,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...r){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...r)}logErrorMessage(e,...r){this.logError(`Poller: ${e}`,...r)}};function de(r){return v(this,arguments,function*(n,e={}){let s=yield He(n),a=$e(e);return{loadFromCache:()=>W(s,a,e),saveToCache:l=>J(s,a,l),updateCachedEvaluation:l=>_e(s,a,l),removeCachedEvaluation:l=>Le(s,a,l)}})}function W(s,a){return v(this,arguments,function*(n,e,r={}){let l=parseInt(yield e.getItem(n+".ts"));if(r!=null&&r.ttl&&!isNaN(l)&&l+r.ttl<Date.now())return yield Ve(n,e),[];let h=yield e.getItem(n);if(h)try{return JSON.parse(h)}catch(E){}return[]})}function Ve(n,e){return v(this,null,function*(){yield e.removeItem(n),yield e.removeItem(n+".ts")})}function J(n,e,r){return v(this,null,function*(){yield e.setItem(n,JSON.stringify(r)),yield e.setItem(n+".ts",Date.now().toString())})}function _e(n,e,r){return v(this,null,function*(){let s=yield W(n,e),a=s.find(({flag:l})=>l===r.flag);a?Object.assign(a,r):s.push(r),yield J(n,e,s)})}function Le(n,e,r){return v(this,null,function*(){let s=yield W(n,e),a=s.findIndex(({flag:l})=>l===r);a>-1&&(s.splice(a,1),yield J(n,e,s))})}function He(n){return v(this,null,function*(){var r,s;let e=n;if(globalThis!=null&&globalThis.TextEncoder&&((s=(r=globalThis==null?void 0:globalThis.crypto)==null?void 0:r.subtle)!=null&&s.digest)){let l=new TextEncoder().encode(n),h=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(h)).map(R=>R.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(n));return"HARNESS_FF_CACHE_"+e})}function $e(n){let e;return!n.storage||typeof n.storage!="object"||!("getItem"in n.storage)||!("setItem"in n.storage)||!("removeItem"in n.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Ge:e=n.storage,{getItem(s){return v(this,null,function*(){let a=e.getItem(s);return a instanceof Promise?yield a:a})},setItem(s,a){return v(this,null,function*(){let l=e.setItem(s,a);l instanceof Promise&&(yield l)})},removeItem(s){return v(this,null,function*(){let a=e.removeItem(s);a instanceof Promise&&(yield a)})}}}var Ge={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var ve="1.26.1",fe=`Javascript ${ve} Client`,qe=500,Be=globalThis.fetch,Y=!!globalThis.Proxy,Ke=(n,e,r)=>{let s=!1,a,l,h,E,R,u,y=!0,A={},N=U(t=>t),X=0,z=!1,L=()=>{y=!1},p=()=>{y=!0},C=[],d=(0,me.default)(),m=le(r),b=(t,...i)=>{m.debug&&m.logger.debug(`[FF-SDK] ${t}`,...i)},T=(t,...i)=>{m.logger.error(`[FF-SDK] ${t}`,...i)},pe=(t,...i)=>{m.logger.warn(`[FF-SDK] ${t}`,...i)},H=t=>{let{value:i}=t;try{switch(t.kind.toLowerCase()){case"int":case"number":i=Number(i);break;case"boolean":i=i.toString().toLowerCase()==="true";break;case"json":i=JSON.parse(i);break}}catch(c){T(c)}return i},$=t=>{if(y){let i=Date.now();i-t.lastAccessed>qe&&(t.count++,t.lastAccessed=i)}},Ee=()=>v(void 0,null,function*(){if(m.cache){b("initializing cache");try{let t=!0,i=yield de(e.identifier+n,typeof m.cache=="boolean"?{}:m.cache),c=yield i.loadFromCache();c!=null&&c.length&&j(()=>{b("loading from cache",c),te(c,!1),d.emit("cache loaded",c)}),B("flags loaded",f=>v(void 0,null,function*(){yield i.saveToCache(f),t=!1})),B("changed",f=>v(void 0,null,function*(){t||(f.deleted?yield i.removeCachedEvaluation(f.flag):yield i.updateCachedEvaluation(f))}))}catch(t){T("Cache error: ",t),d.emit("cache error",t),d.emit("error",t)}}}),Re=(t,i)=>v(void 0,null,function*(){let c=`${i.baseUrl}/client/auth`,f={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":fe},body:JSON.stringify({apiKey:t,target:K(w({},e),{identifier:String(e.identifier)})})},S,o;window.AbortController&&m.authRequestReadTimeout>0?(o=new AbortController,f.signal=o.signal,S=window.setTimeout(()=>o.abort(),i.authRequestReadTimeout)):i.authRequestReadTimeout>0&&pe("AbortController is not available, auth request will not timeout");try{let g=yield Be(c,f);if(!g.ok)throw new Error(`${g.status}: ${g.statusText}`);return(yield g.json()).authToken}catch(g){if(o&&o.signal.aborted)throw new Error(`Request to ${c} failed: Request timeout via configured authRequestTimeout of ${m.authRequestReadTimeout}`);let D=g instanceof Error?g.message:String(g);throw new Error(`Request to ${c} failed: ${D}`)}finally{S&&clearTimeout(S)}}),G=0,q=()=>{if(C.length){b("Sending metrics...",{metrics:C,evaluations:I});let t={metricsData:C.map(i=>({timestamp:Date.now(),count:i.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:i.featureIdentifier},{key:"featureName",value:i.featureIdentifier},{key:"variationIdentifier",value:i.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:ve}]}))};N(`${m.eventUrl}/metrics/${a}?cluster=${l}`,{method:"POST",headers:w({"Content-Type":"application/json"},A),body:JSON.stringify(t)}).then(()=>{C=[],G=0}).catch(i=>{G++&&(C=[],G=0),b(i),d.emit("metrics error",i)}).finally(()=>{u=window.setTimeout(q,m.eventsSyncInterval)})}else u=window.setTimeout(q,m.eventsSyncInterval)},I={},be=t=>{b("Sending event for",t.flag),Y?d.emit("changed",new Proxy(t,{get(i,c){var f;if(y&&i.hasOwnProperty(c)&&c==="value"){let S=i.flag,o=t.value,g=C.find(D=>D.featureIdentifier===S&&D.featureValue===o);g?($(g),g.variationIdentifier=((f=I[S])==null?void 0:f.identifier)||""):C.push({featureIdentifier:S,featureValue:String(o),variationIdentifier:I[S].identifier||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag",c,"has been read with value via stream update",o)}return c==="value"?H(t):t[c]}})):d.emit("changed",{deleted:t.deleted,flag:t.flag,value:H(t)})},Q=function(){return Y?new Proxy({},{get(t,i){var f,S,o;let c=t[i];if(y&&t.hasOwnProperty(i)){let g=t[i],D=C.find(ie=>ie.featureIdentifier===i&&g===ie.featureValue);D?(D.variationIdentifier=((f=I[i])==null?void 0:f.identifier)||"",$(D)):C.push({featureIdentifier:i,featureValue:g,variationIdentifier:((S=I[i])==null?void 0:S.identifier)||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag:",i,"has been read with value:",g,"variationIdentifier:",(o=I[i])==null?void 0:o.identifier)}return c}}):{}},O=Q();Ee().then(()=>Re(n,m).then(t=>v(void 0,null,function*(){if(s)return;R=t;let i=(0,he.default)(t);A={Authorization:`Bearer ${R}`,"Harness-AccountID":i.accountID,"Harness-EnvironmentID":i.environmentIdentifier,"Harness-SDK-Info":fe};let c=ce(e);c.length<262144&&(A["Harness-Target"]=c),b("Authenticated",i),u=window.setTimeout(q,m.eventsSyncInterval),a=i.environment,l=i.clusterIdentifier;let f=!!Object.keys(I).length;if((yield k()).type==="success"&&b("Fetch all flags ok",O),!s){if(m.streamEnabled?(b("Streaming mode enabled"),Se()):m.pollingEnabled?(b("Polling mode enabled"),ye()):b("Streaming and polling mode disabled"),!f){L();let o=w({},O);p(),d.emit("ready",o)}z=!0}})).catch(t=>{T("Authentication error: ",t),d.emit("auth error",t),d.emit("error",t)}));let k=()=>v(void 0,null,function*(){try{let t=yield N(`${m.baseUrl}/client/env/${a}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:A});if(t.ok){let i=yield t.json();return i.forEach(P),d.emit("flags loaded",i),{type:"success",data:i}}else return T("Features fetch operation error: ",t),d.emit("fetch flags error",t),d.emit("error",t),{type:"error",error:t}}catch(t){return T("Features fetch operation error: ",t),d.emit("fetch flags error",t),d.emit("error",t),{type:"error",error:t}}}),Z=t=>v(void 0,null,function*(){try{let i=yield N(`${m.baseUrl}/client/env/${a}/target/${e.identifier}/evaluations/${t}?cluster=${l}`,{headers:A});if(i.ok){let c=yield i.json();P(c)}else T("Feature fetch operation error: ",i),d.emit("fetch flag error",i),d.emit("error",i)}catch(i){T("Feature fetch operation error: ",i),d.emit("fetch flag error",i),d.emit("error",i)}}),P=t=>{L();let i=H(t);i!==O[t.flag]&&(b("Flag variation has changed for ",t.identifier),O[t.flag]=i,I[t.flag]=K(w({},t),{value:i}),be(t)),p()};E=new F(k,m,d,b,T);let Se=()=>{let t=o=>{switch(o.event){case"create":c(o.evaluations)?o.evaluations.forEach(g=>{P(g)}):setTimeout(()=>Z(o.identifier),1e3);break;case"patch":c(o.evaluations)?o.evaluations.forEach(g=>{P(g)}):Z(o.identifier);break;case"delete":delete O[o.identifier],d.emit("changed",{flag:o.identifier,value:void 0,deleted:!0}),b("Evaluation deleted",{message:o,storage:O});break}},i=o=>!(!o||!o.flag||!o.identifier||!o.kind||!o.value),c=o=>!(!o||o.length==0||!o.every(g=>i(g))),f=o=>{o.event==="patch"&&(c(o.evaluations)?o.evaluations.forEach(g=>{P(g)}):k())},S=`${m.baseUrl}/stream?cluster=${l}`;h=new _(d,m,S,n,A,E,b,T,o=>{o.domain==="flag"?t(o):o.domain==="target-segment"&&f(o)},m.maxStreamRetries),h.start()},ye=()=>{E.start()},B=(t,i)=>d.on(t,i),Ie=(t,i)=>{t?d.off(t,i):ee()},Ce=(t,i)=>{var o;if(!y||Y||i===void 0)return;let c=i,f=t,S=C.find(g=>g.featureIdentifier===f&&g.featureValue===c);S?($(S),S.variationIdentifier=((o=I[f])==null?void 0:o.identifier)||""):C.push({featureIdentifier:f,featureValue:c,count:1,variationIdentifier:I[f].identifier||"",lastAccessed:Date.now()})},ee=()=>{s=!0,m.streamEnabled&&(b("Closing event stream"),typeof(h==null?void 0:h.close)=="function"&&h.close(),d.all.clear()),m.pollingEnabled&&E.isPolling()&&(b("Closing Poller"),E.stop()),O=Q(),I={},clearTimeout(u)},te=(t,i=!0)=>{t.length&&j(()=>{let c=!!Object.keys(I).length;if(t.forEach(P),!c){L();let f=w({},O);p(),d.emit("ready",f)}},i)};return{on:B,off:Ie,close:ee,setEvaluations:te,registerAPIRequestMiddleware:t=>{N=U(t)},refreshEvaluations:()=>{z&&!s&&Date.now()-X>=6e4&&(k(),X=Date.now())},variation:(t,i,c=!1)=>ge(t,i,O,Ce,c)}};0&&(module.exports={Event,initialize});
var Ce=Object.create;var F=Object.defineProperty,Te=Object.defineProperties,Ae=Object.getOwnPropertyDescriptor,Oe=Object.getOwnPropertyDescriptors,we=Object.getOwnPropertyNames,ne=Object.getOwnPropertySymbols,De=Object.getPrototypeOf,re=Object.prototype.hasOwnProperty,Pe=Object.prototype.propertyIsEnumerable;var ae=(i,e,a)=>e in i?F(i,e,{enumerable:!0,configurable:!0,writable:!0,value:a}):i[e]=a,T=(i,e)=>{for(var a in e||(e={}))re.call(e,a)&&ae(i,a,e[a]);if(ne)for(var a of ne(e))Pe.call(e,a)&&ae(i,a,e[a]);return i},j=(i,e)=>Te(i,Oe(e));var Fe=(i,e)=>{for(var a in e)F(i,a,{get:e[a],enumerable:!0})},oe=(i,e,a,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of we(e))!re.call(i,r)&&r!==a&&F(i,r,{get:()=>e[r],enumerable:!(o=Ae(e,r))||o.enumerable});return i};var se=(i,e,a)=>(a=i!=null?Ce(De(i)):{},oe(e||!i||!i.__esModule?F(a,"default",{value:i,enumerable:!0}):a,i)),Me=i=>oe(F({},"__esModule",{value:!0}),i);var h=(i,e,a)=>new Promise((o,r)=>{var l=E=>{try{p(a.next(E))}catch(g){r(g)}},u=E=>{try{p(a.throw(E))}catch(g){r(g)}},p=E=>E.done?o(E.value):Promise.resolve(E.value).then(l,u);p((a=a.apply(i,e)).next())});var je={};Fe(je,{Event:()=>M,initialize:()=>Ke});module.exports=Me(je);var he=se(require("jwt-decode")),me=se(require("mitt"));var M=(m=>(m.READY="ready",m.CONNECTED="connected",m.DISCONNECTED="disconnected",m.STOPPED="stopped",m.POLLING="polling",m.POLLING_STOPPED="polling stopped",m.FLAGS_LOADED="flags loaded",m.CACHE_LOADED="cache loaded",m.CHANGED="changed",m.ERROR="error",m.ERROR_CACHE="cache error",m.ERROR_METRICS="metrics error",m.ERROR_AUTH="auth error",m.ERROR_FETCH_FLAGS="fetch flags error",m.ERROR_FETCH_FLAG="fetch flag error",m.ERROR_STREAM="stream error",m))(M||{});var Ne={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1},le=i=>{let e=T(T({},Ne),i);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},U=(i,e=!0)=>{e?setTimeout(i,0):i()},V=(i,e)=>Math.round(Math.random()*(e-i)+i),ce=i=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a="",o=0,r=xe(JSON.stringify(i));for(;o<r.length;){let l=r.charCodeAt(o++),u=r.charCodeAt(o++),p=r.charCodeAt(o++),E=l>>2,g=(l&3)<<4|u>>4,b=(u&15)<<2|p>>6,A=p&63;isNaN(u)?b=A=64:isNaN(p)&&(A=64),a+=e.charAt(E)+e.charAt(g)+e.charAt(b)+e.charAt(A)}return a},xe=i=>i.replace(/\r\n/g,`
`).split("").map(e=>{let a=e.charCodeAt(0);return a<128?String.fromCharCode(a):a>127&&a<2048?String.fromCharCode(a>>6|192)+String.fromCharCode(a&63|128):String.fromCharCode(a>>12|224)+String.fromCharCode(a>>6&63|128)+String.fromCharCode(a&63|128)}).join("");function q(i){return function(...a){let[o,r]=i(a);return fetch(o,r)}}var ge=3e4,_=class{constructor(e,a,o,r,l,u,p,E,g){this.eventBus=e;this.configurations=a;this.url=o;this.apiKey=r;this.standardHeaders=l;this.fallbackPoller=u;this.logDebug=p;this.logError=E;this.eventCallback=g;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1}start(){let e=g=>{g.toString().split(/\r?\n/).forEach(a)},a=g=>{if(g.startsWith("data:")){let b=JSON.parse(g.substring(5));this.logDebugMessage("Received event from stream: ",b),this.eventCallback(b)}},o=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected")},r=()=>{clearInterval(this.readTimeoutCheckerId);let g=V(1e3,1e4);this.logDebugMessage("Stream disconnected, will reconnect in "+g+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),setTimeout(()=>this.start(),g)},l=g=>{g&&this.logErrorMessage("Stream has issue",g),this.fallBackToPolling(),this.eventBus.emit("stream error",g),this.eventBus.emit("error",g),r()},u=T({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[g,b]of Object.entries(u))this.xhr.setRequestHeader(g,b);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{if(this.xhr.status>=400&&this.xhr.status<=599){l(`HTTP code ${this.xhr.status}`);return}this.connectionOpened||(o(),this.connectionOpened=!0,this.disconnectEventEmitted=!1)};let p=0,E=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(o(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),E=Date.now();let g=this.xhr.responseText.slice(p);p+=g.length,this.logDebugMessage("SSE GOT: "+g),e(g)},this.readTimeoutCheckerId=setInterval(()=>{E<Date.now()-ge&&(this.logErrorMessage("SSE read timeout"),this.xhr.abort())},ge),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...a){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...a)}logErrorMessage(e,...a){this.logError(`Streaming: ${e}`,...a)}};function de(i,e,a,o,r){let l=i in a,u=l?a[i]:e;return l&&o(i,u),r?{value:u,isDefaultValue:!l}:u}var N=class{constructor(e,a,o,r,l){this.fetchFlagsFn=e;this.configurations=a;this.eventBus=o;this.logDebug=r;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.attemptFetch().finally(()=>{this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)})}attemptFetch(){return h(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let a=yield this.fetchFlagsFn();if(a.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",a.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,a.error);let o=V(1e3,1e4);yield new Promise(r=>setTimeout(r,o))}})}stop(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0,this.isRunning=!1,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...a){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...a)}logErrorMessage(e,...a){this.logError(`Poller: ${e}`,...a)}};function ue(a){return h(this,arguments,function*(i,e={}){let o=yield Le(i),r=He(e);return{loadFromCache:()=>W(o,r,e),saveToCache:l=>J(o,r,l),updateCachedEvaluation:l=>Ve(o,r,l),removeCachedEvaluation:l=>_e(o,r,l)}})}function W(o,r){return h(this,arguments,function*(i,e,a={}){let l=parseInt(yield e.getItem(i+".ts"));if(a!=null&&a.ttl&&!isNaN(l)&&l+a.ttl<Date.now())return yield ke(i,e),[];let u=yield e.getItem(i);if(u)try{return JSON.parse(u)}catch(p){}return[]})}function ke(i,e){return h(this,null,function*(){yield e.removeItem(i),yield e.removeItem(i+".ts")})}function J(i,e,a){return h(this,null,function*(){yield e.setItem(i,JSON.stringify(a)),yield e.setItem(i+".ts",Date.now().toString())})}function Ve(i,e,a){return h(this,null,function*(){let o=yield W(i,e),r=o.find(({flag:l})=>l===a.flag);r?Object.assign(r,a):o.push(a),yield J(i,e,o)})}function _e(i,e,a){return h(this,null,function*(){let o=yield W(i,e),r=o.findIndex(({flag:l})=>l===a);r>-1&&(o.splice(r,1),yield J(i,e,o))})}function Le(i){return h(this,null,function*(){var a,o;let e=i;if(globalThis!=null&&globalThis.TextEncoder&&((o=(a=globalThis==null?void 0:globalThis.crypto)==null?void 0:a.subtle)!=null&&o.digest)){let l=new TextEncoder().encode(i),u=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(u)).map(E=>E.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(i));return"HARNESS_FF_CACHE_"+e})}function He(i){let e;return!i.storage||typeof i.storage!="object"||!("getItem"in i.storage)||!("setItem"in i.storage)||!("removeItem"in i.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Ge:e=i.storage,{getItem(o){return h(this,null,function*(){let r=e.getItem(o);return r instanceof Promise?yield r:r})},setItem(o,r){return h(this,null,function*(){let l=e.setItem(o,r);l instanceof Promise&&(yield l)})},removeItem(o){return h(this,null,function*(){let r=e.removeItem(o);r instanceof Promise&&(yield r)})}}}var Ge={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var ve="1.26.1",fe=`Javascript ${ve} Client`,$e=500,Be=globalThis.fetch,Y=!!globalThis.Proxy,Ke=(i,e,a)=>{let o=!1,r,l,u,p,E,g,b=!0,A={},x=q(t=>t),z=0,X=!1,L=()=>{b=!1},m=()=>{b=!0},C=[],d=(0,me.default)(),v=le(a),R=(t,...n)=>{v.debug&&v.logger.debug(`[FF-SDK] ${t}`,...n)},O=(t,...n)=>{v.logger.error(`[FF-SDK] ${t}`,...n)},H=t=>{let{value:n}=t;try{switch(t.kind.toLowerCase()){case"int":case"number":n=Number(n);break;case"boolean":n=n.toString().toLowerCase()==="true";break;case"json":n=JSON.parse(n);break}}catch(c){O(c)}return n},G=t=>{if(b){let n=Date.now();n-t.lastAccessed>$e&&(t.count++,t.lastAccessed=n)}},pe=()=>h(void 0,null,function*(){if(v.cache){R("initializing cache");try{let t=!0,n=yield ue(e.identifier+i,typeof v.cache=="boolean"?{}:v.cache),c=yield n.loadFromCache();c!=null&&c.length&&U(()=>{R("loading from cache",c),te(c,!1),d.emit("cache loaded",c)}),K("flags loaded",f=>h(void 0,null,function*(){yield n.saveToCache(f),t=!1})),K("changed",f=>h(void 0,null,function*(){t||(f.deleted?yield n.removeCachedEvaluation(f.flag):yield n.updateCachedEvaluation(f))}))}catch(t){O("Cache error: ",t),d.emit("cache error",t),d.emit("error",t)}}}),Ee=(t,n)=>h(void 0,null,function*(){return(yield(yield Be(`${n.baseUrl}/client/auth`,{method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":fe},body:JSON.stringify({apiKey:t,target:j(T({},e),{identifier:String(e.identifier)})})})).json()).authToken}),$=0,B=()=>{if(C.length){R("Sending metrics...",{metrics:C,evaluations:I});let t={metricsData:C.map(n=>({timestamp:Date.now(),count:n.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:n.featureIdentifier},{key:"featureName",value:n.featureIdentifier},{key:"variationIdentifier",value:n.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:ve}]}))};x(`${v.eventUrl}/metrics/${r}?cluster=${l}`,{method:"POST",headers:T({"Content-Type":"application/json"},A),body:JSON.stringify(t)}).then(()=>{C=[],$=0}).catch(n=>{$++&&(C=[],$=0),R(n),d.emit("metrics error",n)}).finally(()=>{g=window.setTimeout(B,v.eventsSyncInterval)})}else g=window.setTimeout(B,v.eventsSyncInterval)},I={},Re=t=>{R("Sending event for",t.flag),Y?d.emit("changed",new Proxy(t,{get(n,c){var f;if(b&&n.hasOwnProperty(c)&&c==="value"){let S=n.flag,s=t.value,y=C.find(P=>P.featureIdentifier===S&&P.featureValue===s);y?(G(y),y.variationIdentifier=((f=I[S])==null?void 0:f.identifier)||""):C.push({featureIdentifier:S,featureValue:String(s),variationIdentifier:I[S].identifier||"",count:1,lastAccessed:Date.now()}),R("Metrics event: Flag",c,"has been read with value via stream update",s)}return c==="value"?H(t):t[c]}})):d.emit("changed",{deleted:t.deleted,flag:t.flag,value:H(t)})},Q=function(){return Y?new Proxy({},{get(t,n){var f,S,s;let c=t[n];if(b&&t.hasOwnProperty(n)){let y=t[n],P=C.find(ie=>ie.featureIdentifier===n&&y===ie.featureValue);P?(P.variationIdentifier=((f=I[n])==null?void 0:f.identifier)||"",G(P)):C.push({featureIdentifier:n,featureValue:y,variationIdentifier:((S=I[n])==null?void 0:S.identifier)||"",count:1,lastAccessed:Date.now()}),R("Metrics event: Flag:",n,"has been read with value:",y,"variationIdentifier:",(s=I[n])==null?void 0:s.identifier)}return c}}):{}},w=Q();pe().then(()=>Ee(i,v).then(t=>h(void 0,null,function*(){if(o)return;E=t;let n=(0,he.default)(t);A={Authorization:`Bearer ${E}`,"Harness-AccountID":n.accountID,"Harness-EnvironmentID":n.environmentIdentifier,"Harness-SDK-Info":fe};let c=ce(e);c.length<262144&&(A["Harness-Target"]=c),R("Authenticated",n),g=window.setTimeout(B,v.eventsSyncInterval),r=n.environment,l=n.clusterIdentifier;let f=!!Object.keys(I).length;if((yield k()).type==="success"&&R("Fetch all flags ok",w),!o){if(v.streamEnabled?(R("Streaming mode enabled"),ye()):v.pollingEnabled?(R("Polling mode enabled"),be()):R("Streaming and polling mode disabled"),!f){L();let s=T({},w);m(),d.emit("ready",s)}X=!0}})).catch(t=>{O("Authentication error: ",t),d.emit("auth error",t),d.emit("error",t)}));let k=()=>h(void 0,null,function*(){try{let t=yield x(`${v.baseUrl}/client/env/${r}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:A});if(t.ok){let n=yield t.json();return n.forEach(D),d.emit("flags loaded",n),{type:"success",data:n}}else return O("Features fetch operation error: ",t),d.emit("fetch flags error",t),d.emit("error",t),{type:"error",error:t}}catch(t){return O("Features fetch operation error: ",t),d.emit("fetch flags error",t),d.emit("error",t),{type:"error",error:t}}}),Z=t=>h(void 0,null,function*(){try{let n=yield x(`${v.baseUrl}/client/env/${r}/target/${e.identifier}/evaluations/${t}?cluster=${l}`,{headers:A});if(n.ok){let c=yield n.json();D(c)}else O("Feature fetch operation error: ",n),d.emit("fetch flag error",n),d.emit("error",n)}catch(n){O("Feature fetch operation error: ",n),d.emit("fetch flag error",n),d.emit("error",n)}}),D=t=>{L();let n=H(t);n!==w[t.flag]&&(R("Flag variation has changed for ",t.identifier),w[t.flag]=n,I[t.flag]=j(T({},t),{value:n}),Re(t)),m()};p=new N(k,v,d,R,O);let ye=()=>{let t=s=>{switch(s.event){case"create":c(s.evaluations)?s.evaluations.forEach(y=>{D(y)}):setTimeout(()=>Z(s.identifier),1e3);break;case"patch":c(s.evaluations)?s.evaluations.forEach(y=>{D(y)}):Z(s.identifier);break;case"delete":delete w[s.identifier],d.emit("changed",{flag:s.identifier,value:void 0,deleted:!0}),R("Evaluation deleted",{message:s,storage:w});break}},n=s=>!(!s||!s.flag||!s.identifier||!s.kind||!s.value),c=s=>!(!s||s.length==0||!s.every(y=>n(y))),f=s=>{s.event==="patch"&&(c(s.evaluations)?s.evaluations.forEach(y=>{D(y)}):k())},S=`${v.baseUrl}/stream?cluster=${l}`;u=new _(d,v,S,i,A,p,R,O,s=>{s.domain==="flag"?t(s):s.domain==="target-segment"&&f(s)}),u.start()},be=()=>{p.start()},K=(t,n)=>d.on(t,n),Se=(t,n)=>{t?d.off(t,n):ee()},Ie=(t,n)=>{var s;if(!b||Y||n===void 0)return;let c=n,f=t,S=C.find(y=>y.featureIdentifier===f&&y.featureValue===c);S?(G(S),S.variationIdentifier=((s=I[f])==null?void 0:s.identifier)||""):C.push({featureIdentifier:f,featureValue:c,count:1,variationIdentifier:I[f].identifier||"",lastAccessed:Date.now()})},ee=()=>{o=!0,v.streamEnabled&&(R("Closing event stream"),typeof(u==null?void 0:u.close)=="function"&&u.close(),d.all.clear()),v.pollingEnabled&&p.isPolling()&&(R("Closing Poller"),p.stop()),w=Q(),I={},clearTimeout(g)},te=(t,n=!0)=>{t.length&&U(()=>{let c=!!Object.keys(I).length;if(t.forEach(D),!c){L();let f=T({},w);m(),d.emit("ready",f)}},n)};return{on:K,off:Se,close:ee,setEvaluations:te,registerAPIRequestMiddleware:t=>{x=q(t)},refreshEvaluations:()=>{X&&!o&&Date.now()-z>=6e4&&(k(),z=Date.now())},variation:(t,n,c=!1)=>de(t,n,w,Ie,c)}};0&&(module.exports={Event,initialize});

@@ -1,2 +0,2 @@

var HarnessFFSDK=(()=>{var N=Object.defineProperty,Ae=Object.defineProperties,Te=Object.getOwnPropertyDescriptor,Oe=Object.getOwnPropertyDescriptors,De=Object.getOwnPropertyNames,ae=Object.getOwnPropertySymbols;var se=Object.prototype.hasOwnProperty,Pe=Object.prototype.propertyIsEnumerable;var oe=(t,e,i)=>e in t?N(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,C=(t,e)=>{for(var i in e||(e={}))se.call(e,i)&&oe(t,i,e[i]);if(ae)for(var i of ae(e))Pe.call(e,i)&&oe(t,i,e[i]);return t},U=(t,e)=>Ae(t,Oe(e));var xe=(t,e)=>{for(var i in e)N(t,i,{get:e[i],enumerable:!0})},Me=(t,e,i,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of De(e))!se.call(t,o)&&o!==i&&N(t,o,{get:()=>e[o],enumerable:!(a=Te(e,o))||a.enumerable});return t};var Fe=t=>Me(N({},"__esModule",{value:!0}),t);var p=(t,e,i)=>new Promise((a,o)=>{var l=R=>{try{E(i.next(R))}catch(u){o(u)}},d=R=>{try{E(i.throw(R))}catch(u){o(u)}},E=R=>R.done?a(R.value):Promise.resolve(R.value).then(l,d);E((i=i.apply(t,e)).next())});var We={};xe(We,{Event:()=>x,initialize:()=>je});function j(t){this.message=t}j.prototype=new Error,j.prototype.name="InvalidCharacterError";var le=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new j("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,a,o=0,l=0,d="";a=e.charAt(l++);~a&&(i=o%4?64*i+a:a,o++%4)?d+=String.fromCharCode(255&i>>(-2*o&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return d};function ke(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(i){return decodeURIComponent(le(i).replace(/(.)/g,function(a,o){var l=o.charCodeAt(0).toString(16).toUpperCase();return l.length<2&&(l="0"+l),"%"+l}))}(e)}catch(i){return le(e)}}function V(t){this.message=t}function Ne(t,e){if(typeof t!="string")throw new V("Invalid token specified");var i=(e=e||{}).header===!0?0:1;try{return JSON.parse(ke(t.split(".")[i]))}catch(a){throw new V("Invalid token specified: "+a.message)}}V.prototype=new Error,V.prototype.name="InvalidTokenError";var ce=Ne;function ue(t){return{all:t=t||new Map,on:function(e,i){var a=t.get(e);a&&a.push(i)||t.set(e,[i])},off:function(e,i){var a=t.get(e);a&&a.splice(a.indexOf(i)>>>0,1)},emit:function(e,i){(t.get(e)||[]).slice().map(function(a){a(i)}),(t.get("*")||[]).slice().map(function(a){a(e,i)})}}}var x=(v=>(v.READY="ready",v.CONNECTED="connected",v.DISCONNECTED="disconnected",v.STOPPED="stopped",v.POLLING="polling",v.POLLING_STOPPED="polling stopped",v.FLAGS_LOADED="flags loaded",v.CACHE_LOADED="cache loaded",v.CHANGED="changed",v.ERROR="error",v.ERROR_CACHE="cache error",v.ERROR_METRICS="metrics error",v.ERROR_AUTH="auth error",v.ERROR_FETCH_FLAGS="fetch flags error",v.ERROR_FETCH_FLAG="fetch flag error",v.ERROR_STREAM="stream error",v))(x||{});var Ve={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},de=t=>{let e=C(C({},Ve),t);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},W=(t,e=!0)=>{e?setTimeout(t,0):t()},_=(t,e)=>Math.round(Math.random()*(e-t)+t),ge=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i="",a=0,o=_e(JSON.stringify(t));for(;a<o.length;){let l=o.charCodeAt(a++),d=o.charCodeAt(a++),E=o.charCodeAt(a++),R=l>>2,u=(l&3)<<4|d>>4,S=(d&15)<<2|E>>6,A=E&63;isNaN(d)?S=A=64:isNaN(E)&&(A=64),i+=e.charAt(R)+e.charAt(u)+e.charAt(S)+e.charAt(A)}return i},_e=t=>t.replace(/\r\n/g,`
`).split("").map(e=>{let i=e.charCodeAt(0);return i<128?String.fromCharCode(i):i>127&&i<2048?String.fromCharCode(i>>6|192)+String.fromCharCode(i&63|128):String.fromCharCode(i>>12|224)+String.fromCharCode(i>>6&63|128)+String.fromCharCode(i&63|128)}).join("");function J(t){return function(...i){let[a,o]=t(i);return fetch(a,o)}}var fe=3e4,L=class{constructor(e,i,a,o,l,d,E,R,u,S){this.eventBus=e;this.configurations=i;this.url=a;this.apiKey=o;this.standardHeaders=l;this.fallbackPoller=d;this.logDebug=E;this.logError=R;this.eventCallback=u;this.maxRetries=S;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1;this.reconnectAttempts=0;this.retriesExhausted=!1}start(){let e=u=>{u.toString().split(/\r?\n/).forEach(i)},i=u=>{if(u.startsWith("data:")){let S=JSON.parse(u.substring(5));this.logDebugMessage("Received event from stream: ",S),this.eventCallback(S)}},a=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected"),this.reconnectAttempts=0},o=()=>{clearInterval(this.readTimeoutCheckerId);let u=_(1e3,1e4);if(this.reconnectAttempts++,this.logDebugMessage("Stream disconnected, will reconnect in "+u+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),this.reconnectAttempts>=5&&this.reconnectAttempts%5===0&&this.logErrorMessage(`Reconnection failed after ${this.reconnectAttempts} attempts; attempting further reconnections.`),this.reconnectAttempts>=this.maxRetries){this.retriesExhausted=!0,this.configurations.pollingEnabled?this.logErrorMessage("Max streaming retries reached. Staying in polling mode."):this.logErrorMessage("Max streaming retries reached. Polling mode is disabled and will receive no further flag updates until SDK client is restarted.");return}setTimeout(()=>this.start(),u)},l=u=>{this.retriesExhausted||(u&&this.logDebugMessage("Stream has issue",u),this.fallBackToPolling(),this.eventBus.emit("stream error",u),this.eventBus.emit("error",u),o())},d=C({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[u,S]of Object.entries(d))this.xhr.setRequestHeader(u,S);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{l(`Received XMLHttpRequest onLoad event: ${this.xhr.status}`)};let E=0,R=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(a(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),R=Date.now();let u=this.xhr.responseText.slice(E);E+=u.length,this.logDebugMessage("SSE GOT: "+u),e(u)},this.readTimeoutCheckerId=setInterval(()=>{R<Date.now()-fe&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},fe),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...i){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...i)}logErrorMessage(e,...i){this.logError(`Streaming: ${e}`,...i)}};function he(t,e,i,a,o){let l=t in i,d=l?i[t]:e;return l&&a(t,d),o?{value:d,isDefaultValue:!l}:d}var M=class{constructor(e,i,a,o,l){this.fetchFlagsFn=e;this.configurations=i;this.eventBus=a;this.logDebug=o;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.isRunning&&this.attemptFetch().finally(()=>{this.isRunning&&(this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval))})}attemptFetch(){return p(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let i=yield this.fetchFlagsFn();if(i.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",i.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,i.error);let a=_(1e3,1e4);yield new Promise(o=>setTimeout(o,a))}})}stop(){this.timeoutId&&(this.isRunning=!1,clearTimeout(this.timeoutId),this.timeoutId=void 0,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...i){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...i)}logErrorMessage(e,...i){this.logError(`Poller: ${e}`,...i)}};function me(i){return p(this,arguments,function*(t,e={}){let a=yield Ge(t),o=qe(e);return{loadFromCache:()=>Y(a,o,e),saveToCache:l=>X(a,o,l),updateCachedEvaluation:l=>He(a,o,l),removeCachedEvaluation:l=>$e(a,o,l)}})}function Y(a,o){return p(this,arguments,function*(t,e,i={}){let l=parseInt(yield e.getItem(t+".ts"));if(i!=null&&i.ttl&&!isNaN(l)&&l+i.ttl<Date.now())return yield Le(t,e),[];let d=yield e.getItem(t);if(d)try{return JSON.parse(d)}catch(E){}return[]})}function Le(t,e){return p(this,null,function*(){yield e.removeItem(t),yield e.removeItem(t+".ts")})}function X(t,e,i){return p(this,null,function*(){yield e.setItem(t,JSON.stringify(i)),yield e.setItem(t+".ts",Date.now().toString())})}function He(t,e,i){return p(this,null,function*(){let a=yield Y(t,e),o=a.find(({flag:l})=>l===i.flag);o?Object.assign(o,i):a.push(i),yield X(t,e,a)})}function $e(t,e,i){return p(this,null,function*(){let a=yield Y(t,e),o=a.findIndex(({flag:l})=>l===i);o>-1&&(a.splice(o,1),yield X(t,e,a))})}function Ge(t){return p(this,null,function*(){var i,a;let e=t;if(globalThis!=null&&globalThis.TextEncoder&&((a=(i=globalThis==null?void 0:globalThis.crypto)==null?void 0:i.subtle)!=null&&a.digest)){let l=new TextEncoder().encode(t),d=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(d)).map(R=>R.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(t));return"HARNESS_FF_CACHE_"+e})}function qe(t){let e;return!t.storage||typeof t.storage!="object"||!("getItem"in t.storage)||!("setItem"in t.storage)||!("removeItem"in t.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Be:e=t.storage,{getItem(a){return p(this,null,function*(){let o=e.getItem(a);return o instanceof Promise?yield o:o})},setItem(a,o){return p(this,null,function*(){let l=e.setItem(a,o);l instanceof Promise&&(yield l)})},removeItem(a){return p(this,null,function*(){let o=e.removeItem(a);o instanceof Promise&&(yield o)})}}}var Be={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var ve="1.26.1",pe=`Javascript ${ve} Client`,Ke=500,Ue=globalThis.fetch,z=!!globalThis.Proxy,je=(t,e,i)=>{let a=!1,o,l,d,E,R,u,S=!0,A={},F=J(n=>n),Q=0,Z=!1,H=()=>{S=!1},v=()=>{S=!0},w=[],f=ue(),m=de(i),b=(n,...r)=>{m.debug&&m.logger.debug(`[FF-SDK] ${n}`,...r)},T=(n,...r)=>{m.logger.error(`[FF-SDK] ${n}`,...r)},Ee=(n,...r)=>{m.logger.warn(`[FF-SDK] ${n}`,...r)},$=n=>{let{value:r}=n;try{switch(n.kind.toLowerCase()){case"int":case"number":r=Number(r);break;case"boolean":r=r.toString().toLowerCase()==="true";break;case"json":r=JSON.parse(r);break}}catch(c){T(c)}return r},G=n=>{if(S){let r=Date.now();r-n.lastAccessed>Ke&&(n.count++,n.lastAccessed=r)}},Re=()=>p(void 0,null,function*(){if(m.cache){b("initializing cache");try{let n=!0,r=yield me(e.identifier+t,typeof m.cache=="boolean"?{}:m.cache),c=yield r.loadFromCache();c!=null&&c.length&&W(()=>{b("loading from cache",c),ne(c,!1),f.emit("cache loaded",c)}),K("flags loaded",h=>p(void 0,null,function*(){yield r.saveToCache(h),n=!1})),K("changed",h=>p(void 0,null,function*(){n||(h.deleted?yield r.removeCachedEvaluation(h.flag):yield r.updateCachedEvaluation(h))}))}catch(n){T("Cache error: ",n),f.emit("cache error",n),f.emit("error",n)}}}),be=(n,r)=>p(void 0,null,function*(){let c=`${r.baseUrl}/client/auth`,h={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":pe},body:JSON.stringify({apiKey:n,target:U(C({},e),{identifier:String(e.identifier)})})},y,s;window.AbortController&&m.authRequestReadTimeout>0?(s=new AbortController,h.signal=s.signal,y=window.setTimeout(()=>s.abort(),r.authRequestReadTimeout)):r.authRequestReadTimeout>0&&Ee("AbortController is not available, auth request will not timeout");try{let g=yield Ue(c,h);if(!g.ok)throw new Error(`${g.status}: ${g.statusText}`);return(yield g.json()).authToken}catch(g){if(s&&s.signal.aborted)throw new Error(`Request to ${c} failed: Request timeout via configured authRequestTimeout of ${m.authRequestReadTimeout}`);let D=g instanceof Error?g.message:String(g);throw new Error(`Request to ${c} failed: ${D}`)}finally{y&&clearTimeout(y)}}),q=0,B=()=>{if(w.length){b("Sending metrics...",{metrics:w,evaluations:I});let n={metricsData:w.map(r=>({timestamp:Date.now(),count:r.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:r.featureIdentifier},{key:"featureName",value:r.featureIdentifier},{key:"variationIdentifier",value:r.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:ve}]}))};F(`${m.eventUrl}/metrics/${o}?cluster=${l}`,{method:"POST",headers:C({"Content-Type":"application/json"},A),body:JSON.stringify(n)}).then(()=>{w=[],q=0}).catch(r=>{q++&&(w=[],q=0),b(r),f.emit("metrics error",r)}).finally(()=>{u=window.setTimeout(B,m.eventsSyncInterval)})}else u=window.setTimeout(B,m.eventsSyncInterval)},I={},ye=n=>{b("Sending event for",n.flag),z?f.emit("changed",new Proxy(n,{get(r,c){var h;if(S&&r.hasOwnProperty(c)&&c==="value"){let y=r.flag,s=n.value,g=w.find(D=>D.featureIdentifier===y&&D.featureValue===s);g?(G(g),g.variationIdentifier=((h=I[y])==null?void 0:h.identifier)||""):w.push({featureIdentifier:y,featureValue:String(s),variationIdentifier:I[y].identifier||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag",c,"has been read with value via stream update",s)}return c==="value"?$(n):n[c]}})):f.emit("changed",{deleted:n.deleted,flag:n.flag,value:$(n)})},ee=function(){return z?new Proxy({},{get(n,r){var h,y,s;let c=n[r];if(S&&n.hasOwnProperty(r)){let g=n[r],D=w.find(re=>re.featureIdentifier===r&&g===re.featureValue);D?(D.variationIdentifier=((h=I[r])==null?void 0:h.identifier)||"",G(D)):w.push({featureIdentifier:r,featureValue:g,variationIdentifier:((y=I[r])==null?void 0:y.identifier)||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag:",r,"has been read with value:",g,"variationIdentifier:",(s=I[r])==null?void 0:s.identifier)}return c}}):{}},O=ee();Re().then(()=>be(t,m).then(n=>p(void 0,null,function*(){if(a)return;R=n;let r=ce(n);A={Authorization:`Bearer ${R}`,"Harness-AccountID":r.accountID,"Harness-EnvironmentID":r.environmentIdentifier,"Harness-SDK-Info":pe};let c=ge(e);c.length<262144&&(A["Harness-Target"]=c),b("Authenticated",r),u=window.setTimeout(B,m.eventsSyncInterval),o=r.environment,l=r.clusterIdentifier;let h=!!Object.keys(I).length;if((yield k()).type==="success"&&b("Fetch all flags ok",O),!a){if(m.streamEnabled?(b("Streaming mode enabled"),Se()):m.pollingEnabled?(b("Polling mode enabled"),Ie()):b("Streaming and polling mode disabled"),!h){H();let s=C({},O);v(),f.emit("ready",s)}Z=!0}})).catch(n=>{T("Authentication error: ",n),f.emit("auth error",n),f.emit("error",n)}));let k=()=>p(void 0,null,function*(){try{let n=yield F(`${m.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:A});if(n.ok){let r=yield n.json();return r.forEach(P),f.emit("flags loaded",r),{type:"success",data:r}}else return T("Features fetch operation error: ",n),f.emit("fetch flags error",n),f.emit("error",n),{type:"error",error:n}}catch(n){return T("Features fetch operation error: ",n),f.emit("fetch flags error",n),f.emit("error",n),{type:"error",error:n}}}),te=n=>p(void 0,null,function*(){try{let r=yield F(`${m.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations/${n}?cluster=${l}`,{headers:A});if(r.ok){let c=yield r.json();P(c)}else T("Feature fetch operation error: ",r),f.emit("fetch flag error",r),f.emit("error",r)}catch(r){T("Feature fetch operation error: ",r),f.emit("fetch flag error",r),f.emit("error",r)}}),P=n=>{H();let r=$(n);r!==O[n.flag]&&(b("Flag variation has changed for ",n.identifier),O[n.flag]=r,I[n.flag]=U(C({},n),{value:r}),ye(n)),v()};E=new M(k,m,f,b,T);let Se=()=>{let n=s=>{switch(s.event){case"create":c(s.evaluations)?s.evaluations.forEach(g=>{P(g)}):setTimeout(()=>te(s.identifier),1e3);break;case"patch":c(s.evaluations)?s.evaluations.forEach(g=>{P(g)}):te(s.identifier);break;case"delete":delete O[s.identifier],f.emit("changed",{flag:s.identifier,value:void 0,deleted:!0}),b("Evaluation deleted",{message:s,storage:O});break}},r=s=>!(!s||!s.flag||!s.identifier||!s.kind||!s.value),c=s=>!(!s||s.length==0||!s.every(g=>r(g))),h=s=>{s.event==="patch"&&(c(s.evaluations)?s.evaluations.forEach(g=>{P(g)}):k())},y=`${m.baseUrl}/stream?cluster=${l}`;d=new L(f,m,y,t,A,E,b,T,s=>{s.domain==="flag"?n(s):s.domain==="target-segment"&&h(s)},m.maxStreamRetries),d.start()},Ie=()=>{E.start()},K=(n,r)=>f.on(n,r),we=(n,r)=>{n?f.off(n,r):ie()},Ce=(n,r)=>{var s;if(!S||z||r===void 0)return;let c=r,h=n,y=w.find(g=>g.featureIdentifier===h&&g.featureValue===c);y?(G(y),y.variationIdentifier=((s=I[h])==null?void 0:s.identifier)||""):w.push({featureIdentifier:h,featureValue:c,count:1,variationIdentifier:I[h].identifier||"",lastAccessed:Date.now()})},ie=()=>{a=!0,m.streamEnabled&&(b("Closing event stream"),typeof(d==null?void 0:d.close)=="function"&&d.close(),f.all.clear()),m.pollingEnabled&&E.isPolling()&&(b("Closing Poller"),E.stop()),O=ee(),I={},clearTimeout(u)},ne=(n,r=!0)=>{n.length&&W(()=>{let c=!!Object.keys(I).length;if(n.forEach(P),!c){H();let h=C({},O);v(),f.emit("ready",h)}},r)};return{on:K,off:we,close:ie,setEvaluations:ne,registerAPIRequestMiddleware:n=>{F=J(n)},refreshEvaluations:()=>{Z&&!a&&Date.now()-Q>=6e4&&(k(),Q=Date.now())},variation:(n,r,c=!1)=>he(n,r,O,Ce,c)}};return Fe(We);})();
var HarnessFFSDK=(()=>{var N=Object.defineProperty,we=Object.defineProperties,Te=Object.getOwnPropertyDescriptor,Ae=Object.getOwnPropertyDescriptors,Oe=Object.getOwnPropertyNames,ae=Object.getOwnPropertySymbols;var se=Object.prototype.hasOwnProperty,De=Object.prototype.propertyIsEnumerable;var oe=(t,e,i)=>e in t?N(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,w=(t,e)=>{for(var i in e||(e={}))se.call(e,i)&&oe(t,i,e[i]);if(ae)for(var i of ae(e))De.call(e,i)&&oe(t,i,e[i]);return t},j=(t,e)=>we(t,Ae(e));var Pe=(t,e)=>{for(var i in e)N(t,i,{get:e[i],enumerable:!0})},Fe=(t,e,i,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Oe(e))!se.call(t,o)&&o!==i&&N(t,o,{get:()=>e[o],enumerable:!(a=Te(e,o))||a.enumerable});return t};var xe=t=>Fe(N({},"__esModule",{value:!0}),t);var h=(t,e,i)=>new Promise((a,o)=>{var s=E=>{try{p(i.next(E))}catch(d){o(d)}},g=E=>{try{p(i.throw(E))}catch(d){o(d)}},p=E=>E.done?a(E.value):Promise.resolve(E.value).then(s,g);p((i=i.apply(t,e)).next())});var qe={};Pe(qe,{Event:()=>F,initialize:()=>je});function q(t){this.message=t}q.prototype=new Error,q.prototype.name="InvalidCharacterError";var le=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(t){var e=String(t).replace(/=+$/,"");if(e.length%4==1)throw new q("'atob' failed: The string to be decoded is not correctly encoded.");for(var i,a,o=0,s=0,g="";a=e.charAt(s++);~a&&(i=o%4?64*i+a:a,o++%4)?g+=String.fromCharCode(255&i>>(-2*o&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return g};function ke(t){var e=t.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(i){return decodeURIComponent(le(i).replace(/(.)/g,function(a,o){var s=o.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch(i){return le(e)}}function V(t){this.message=t}function Me(t,e){if(typeof t!="string")throw new V("Invalid token specified");var i=(e=e||{}).header===!0?0:1;try{return JSON.parse(ke(t.split(".")[i]))}catch(a){throw new V("Invalid token specified: "+a.message)}}V.prototype=new Error,V.prototype.name="InvalidTokenError";var ce=Me;function de(t){return{all:t=t||new Map,on:function(e,i){var a=t.get(e);a&&a.push(i)||t.set(e,[i])},off:function(e,i){var a=t.get(e);a&&a.splice(a.indexOf(i)>>>0,1)},emit:function(e,i){(t.get(e)||[]).slice().map(function(a){a(i)}),(t.get("*")||[]).slice().map(function(a){a(e,i)})}}}var F=(m=>(m.READY="ready",m.CONNECTED="connected",m.DISCONNECTED="disconnected",m.STOPPED="stopped",m.POLLING="polling",m.POLLING_STOPPED="polling stopped",m.FLAGS_LOADED="flags loaded",m.CACHE_LOADED="cache loaded",m.CHANGED="changed",m.ERROR="error",m.ERROR_CACHE="cache error",m.ERROR_METRICS="metrics error",m.ERROR_AUTH="auth error",m.ERROR_FETCH_FLAGS="fetch flags error",m.ERROR_FETCH_FLAG="fetch flag error",m.ERROR_STREAM="stream error",m))(F||{});var Ne={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1},ge=t=>{let e=w(w({},Ne),t);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},J=(t,e=!0)=>{e?setTimeout(t,0):t()},_=(t,e)=>Math.round(Math.random()*(e-t)+t),ue=t=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",i="",a=0,o=Ve(JSON.stringify(t));for(;a<o.length;){let s=o.charCodeAt(a++),g=o.charCodeAt(a++),p=o.charCodeAt(a++),E=s>>2,d=(s&3)<<4|g>>4,R=(g&15)<<2|p>>6,T=p&63;isNaN(g)?R=T=64:isNaN(p)&&(T=64),i+=e.charAt(E)+e.charAt(d)+e.charAt(R)+e.charAt(T)}return i},Ve=t=>t.replace(/\r\n/g,`
`).split("").map(e=>{let i=e.charCodeAt(0);return i<128?String.fromCharCode(i):i>127&&i<2048?String.fromCharCode(i>>6|192)+String.fromCharCode(i&63|128):String.fromCharCode(i>>12|224)+String.fromCharCode(i>>6&63|128)+String.fromCharCode(i&63|128)}).join("");function W(t){return function(...i){let[a,o]=t(i);return fetch(a,o)}}var fe=3e4,L=class{constructor(e,i,a,o,s,g,p,E,d){this.eventBus=e;this.configurations=i;this.url=a;this.apiKey=o;this.standardHeaders=s;this.fallbackPoller=g;this.logDebug=p;this.logError=E;this.eventCallback=d;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1}start(){let e=d=>{d.toString().split(/\r?\n/).forEach(i)},i=d=>{if(d.startsWith("data:")){let R=JSON.parse(d.substring(5));this.logDebugMessage("Received event from stream: ",R),this.eventCallback(R)}},a=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected")},o=()=>{clearInterval(this.readTimeoutCheckerId);let d=_(1e3,1e4);this.logDebugMessage("Stream disconnected, will reconnect in "+d+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),setTimeout(()=>this.start(),d)},s=d=>{d&&this.logErrorMessage("Stream has issue",d),this.fallBackToPolling(),this.eventBus.emit("stream error",d),this.eventBus.emit("error",d),o()},g=w({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[d,R]of Object.entries(g))this.xhr.setRequestHeader(d,R);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,s("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||s(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,s("SSE timeout")},this.xhr.onload=()=>{if(this.xhr.status>=400&&this.xhr.status<=599){s(`HTTP code ${this.xhr.status}`);return}this.connectionOpened||(a(),this.connectionOpened=!0,this.disconnectEventEmitted=!1)};let p=0,E=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(a(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),E=Date.now();let d=this.xhr.responseText.slice(p);p+=d.length,this.logDebugMessage("SSE GOT: "+d),e(d)},this.readTimeoutCheckerId=setInterval(()=>{E<Date.now()-fe&&(this.logErrorMessage("SSE read timeout"),this.xhr.abort())},fe),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...i){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...i)}logErrorMessage(e,...i){this.logError(`Streaming: ${e}`,...i)}};function he(t,e,i,a,o){let s=t in i,g=s?i[t]:e;return s&&a(t,g),o?{value:g,isDefaultValue:!s}:g}var x=class{constructor(e,i,a,o,s){this.fetchFlagsFn=e;this.configurations=i;this.eventBus=a;this.logDebug=o;this.logError=s;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.attemptFetch().finally(()=>{this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)})}attemptFetch(){return h(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let i=yield this.fetchFlagsFn();if(i.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",i.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,i.error);let a=_(1e3,1e4);yield new Promise(o=>setTimeout(o,a))}})}stop(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0,this.isRunning=!1,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...i){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...i)}logErrorMessage(e,...i){this.logError(`Poller: ${e}`,...i)}};function me(i){return h(this,arguments,function*(t,e={}){let a=yield Ge(t),o=$e(e);return{loadFromCache:()=>Y(a,o,e),saveToCache:s=>z(a,o,s),updateCachedEvaluation:s=>Le(a,o,s),removeCachedEvaluation:s=>He(a,o,s)}})}function Y(a,o){return h(this,arguments,function*(t,e,i={}){let s=parseInt(yield e.getItem(t+".ts"));if(i!=null&&i.ttl&&!isNaN(s)&&s+i.ttl<Date.now())return yield _e(t,e),[];let g=yield e.getItem(t);if(g)try{return JSON.parse(g)}catch(p){}return[]})}function _e(t,e){return h(this,null,function*(){yield e.removeItem(t),yield e.removeItem(t+".ts")})}function z(t,e,i){return h(this,null,function*(){yield e.setItem(t,JSON.stringify(i)),yield e.setItem(t+".ts",Date.now().toString())})}function Le(t,e,i){return h(this,null,function*(){let a=yield Y(t,e),o=a.find(({flag:s})=>s===i.flag);o?Object.assign(o,i):a.push(i),yield z(t,e,a)})}function He(t,e,i){return h(this,null,function*(){let a=yield Y(t,e),o=a.findIndex(({flag:s})=>s===i);o>-1&&(a.splice(o,1),yield z(t,e,a))})}function Ge(t){return h(this,null,function*(){var i,a;let e=t;if(globalThis!=null&&globalThis.TextEncoder&&((a=(i=globalThis==null?void 0:globalThis.crypto)==null?void 0:i.subtle)!=null&&a.digest)){let s=new TextEncoder().encode(t),g=yield crypto.subtle.digest("SHA-256",s);e=Array.from(new Uint8Array(g)).map(E=>E.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(t));return"HARNESS_FF_CACHE_"+e})}function $e(t){let e;return!t.storage||typeof t.storage!="object"||!("getItem"in t.storage)||!("setItem"in t.storage)||!("removeItem"in t.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Be:e=t.storage,{getItem(a){return h(this,null,function*(){let o=e.getItem(a);return o instanceof Promise?yield o:o})},setItem(a,o){return h(this,null,function*(){let s=e.setItem(a,o);s instanceof Promise&&(yield s)})},removeItem(a){return h(this,null,function*(){let o=e.removeItem(a);o instanceof Promise&&(yield o)})}}}var Be={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var pe="1.26.1",ve=`Javascript ${pe} Client`,Ke=500,Ue=globalThis.fetch,X=!!globalThis.Proxy,je=(t,e,i)=>{let a=!1,o,s,g,p,E,d,R=!0,T={},k=W(n=>n),Q=0,Z=!1,H=()=>{R=!1},m=()=>{R=!0},C=[],u=de(),v=ge(i),y=(n,...r)=>{v.debug&&v.logger.debug(`[FF-SDK] ${n}`,...r)},A=(n,...r)=>{v.logger.error(`[FF-SDK] ${n}`,...r)},G=n=>{let{value:r}=n;try{switch(n.kind.toLowerCase()){case"int":case"number":r=Number(r);break;case"boolean":r=r.toString().toLowerCase()==="true";break;case"json":r=JSON.parse(r);break}}catch(c){A(c)}return r},$=n=>{if(R){let r=Date.now();r-n.lastAccessed>Ke&&(n.count++,n.lastAccessed=r)}},Ee=()=>h(void 0,null,function*(){if(v.cache){y("initializing cache");try{let n=!0,r=yield me(e.identifier+t,typeof v.cache=="boolean"?{}:v.cache),c=yield r.loadFromCache();c!=null&&c.length&&J(()=>{y("loading from cache",c),ne(c,!1),u.emit("cache loaded",c)}),U("flags loaded",f=>h(void 0,null,function*(){yield r.saveToCache(f),n=!1})),U("changed",f=>h(void 0,null,function*(){n||(f.deleted?yield r.removeCachedEvaluation(f.flag):yield r.updateCachedEvaluation(f))}))}catch(n){A("Cache error: ",n),u.emit("cache error",n),u.emit("error",n)}}}),ye=(n,r)=>h(void 0,null,function*(){return(yield(yield Ue(`${r.baseUrl}/client/auth`,{method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":ve},body:JSON.stringify({apiKey:n,target:j(w({},e),{identifier:String(e.identifier)})})})).json()).authToken}),B=0,K=()=>{if(C.length){y("Sending metrics...",{metrics:C,evaluations:I});let n={metricsData:C.map(r=>({timestamp:Date.now(),count:r.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:r.featureIdentifier},{key:"featureName",value:r.featureIdentifier},{key:"variationIdentifier",value:r.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:pe}]}))};k(`${v.eventUrl}/metrics/${o}?cluster=${s}`,{method:"POST",headers:w({"Content-Type":"application/json"},T),body:JSON.stringify(n)}).then(()=>{C=[],B=0}).catch(r=>{B++&&(C=[],B=0),y(r),u.emit("metrics error",r)}).finally(()=>{d=window.setTimeout(K,v.eventsSyncInterval)})}else d=window.setTimeout(K,v.eventsSyncInterval)},I={},be=n=>{y("Sending event for",n.flag),X?u.emit("changed",new Proxy(n,{get(r,c){var f;if(R&&r.hasOwnProperty(c)&&c==="value"){let S=r.flag,l=n.value,b=C.find(P=>P.featureIdentifier===S&&P.featureValue===l);b?($(b),b.variationIdentifier=((f=I[S])==null?void 0:f.identifier)||""):C.push({featureIdentifier:S,featureValue:String(l),variationIdentifier:I[S].identifier||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag",c,"has been read with value via stream update",l)}return c==="value"?G(n):n[c]}})):u.emit("changed",{deleted:n.deleted,flag:n.flag,value:G(n)})},ee=function(){return X?new Proxy({},{get(n,r){var f,S,l;let c=n[r];if(R&&n.hasOwnProperty(r)){let b=n[r],P=C.find(re=>re.featureIdentifier===r&&b===re.featureValue);P?(P.variationIdentifier=((f=I[r])==null?void 0:f.identifier)||"",$(P)):C.push({featureIdentifier:r,featureValue:b,variationIdentifier:((S=I[r])==null?void 0:S.identifier)||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag:",r,"has been read with value:",b,"variationIdentifier:",(l=I[r])==null?void 0:l.identifier)}return c}}):{}},O=ee();Ee().then(()=>ye(t,v).then(n=>h(void 0,null,function*(){if(a)return;E=n;let r=ce(n);T={Authorization:`Bearer ${E}`,"Harness-AccountID":r.accountID,"Harness-EnvironmentID":r.environmentIdentifier,"Harness-SDK-Info":ve};let c=ue(e);c.length<262144&&(T["Harness-Target"]=c),y("Authenticated",r),d=window.setTimeout(K,v.eventsSyncInterval),o=r.environment,s=r.clusterIdentifier;let f=!!Object.keys(I).length;if((yield M()).type==="success"&&y("Fetch all flags ok",O),!a){if(v.streamEnabled?(y("Streaming mode enabled"),Re()):v.pollingEnabled?(y("Polling mode enabled"),Se()):y("Streaming and polling mode disabled"),!f){H();let l=w({},O);m(),u.emit("ready",l)}Z=!0}})).catch(n=>{A("Authentication error: ",n),u.emit("auth error",n),u.emit("error",n)}));let M=()=>h(void 0,null,function*(){try{let n=yield k(`${v.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations?cluster=${s}`,{headers:T});if(n.ok){let r=yield n.json();return r.forEach(D),u.emit("flags loaded",r),{type:"success",data:r}}else return A("Features fetch operation error: ",n),u.emit("fetch flags error",n),u.emit("error",n),{type:"error",error:n}}catch(n){return A("Features fetch operation error: ",n),u.emit("fetch flags error",n),u.emit("error",n),{type:"error",error:n}}}),te=n=>h(void 0,null,function*(){try{let r=yield k(`${v.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations/${n}?cluster=${s}`,{headers:T});if(r.ok){let c=yield r.json();D(c)}else A("Feature fetch operation error: ",r),u.emit("fetch flag error",r),u.emit("error",r)}catch(r){A("Feature fetch operation error: ",r),u.emit("fetch flag error",r),u.emit("error",r)}}),D=n=>{H();let r=G(n);r!==O[n.flag]&&(y("Flag variation has changed for ",n.identifier),O[n.flag]=r,I[n.flag]=j(w({},n),{value:r}),be(n)),m()};p=new x(M,v,u,y,A);let Re=()=>{let n=l=>{switch(l.event){case"create":c(l.evaluations)?l.evaluations.forEach(b=>{D(b)}):setTimeout(()=>te(l.identifier),1e3);break;case"patch":c(l.evaluations)?l.evaluations.forEach(b=>{D(b)}):te(l.identifier);break;case"delete":delete O[l.identifier],u.emit("changed",{flag:l.identifier,value:void 0,deleted:!0}),y("Evaluation deleted",{message:l,storage:O});break}},r=l=>!(!l||!l.flag||!l.identifier||!l.kind||!l.value),c=l=>!(!l||l.length==0||!l.every(b=>r(b))),f=l=>{l.event==="patch"&&(c(l.evaluations)?l.evaluations.forEach(b=>{D(b)}):M())},S=`${v.baseUrl}/stream?cluster=${s}`;g=new L(u,v,S,t,T,p,y,A,l=>{l.domain==="flag"?n(l):l.domain==="target-segment"&&f(l)}),g.start()},Se=()=>{p.start()},U=(n,r)=>u.on(n,r),Ie=(n,r)=>{n?u.off(n,r):ie()},Ce=(n,r)=>{var l;if(!R||X||r===void 0)return;let c=r,f=n,S=C.find(b=>b.featureIdentifier===f&&b.featureValue===c);S?($(S),S.variationIdentifier=((l=I[f])==null?void 0:l.identifier)||""):C.push({featureIdentifier:f,featureValue:c,count:1,variationIdentifier:I[f].identifier||"",lastAccessed:Date.now()})},ie=()=>{a=!0,v.streamEnabled&&(y("Closing event stream"),typeof(g==null?void 0:g.close)=="function"&&g.close(),u.all.clear()),v.pollingEnabled&&p.isPolling()&&(y("Closing Poller"),p.stop()),O=ee(),I={},clearTimeout(d)},ne=(n,r=!0)=>{n.length&&J(()=>{let c=!!Object.keys(I).length;if(n.forEach(D),!c){H();let f=w({},O);m(),u.emit("ready",f)}},r)};return{on:U,off:Ie,close:ie,setEvaluations:ne,registerAPIRequestMiddleware:n=>{k=W(n)},refreshEvaluations:()=>{Z&&!a&&Date.now()-Q>=6e4&&(M(),Q=Date.now())},variation:(n,r,c=!1)=>he(n,r,O,Ce,c)}};return xe(qe);})();

@@ -1,2 +0,2 @@

var we=Object.defineProperty,Ce=Object.defineProperties;var Ae=Object.getOwnPropertyDescriptors;var re=Object.getOwnPropertySymbols;var Te=Object.prototype.hasOwnProperty,Oe=Object.prototype.propertyIsEnumerable;var ae=(i,e,t)=>e in i?we(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,C=(i,e)=>{for(var t in e||(e={}))Te.call(e,t)&&ae(i,t,e[t]);if(re)for(var t of re(e))Oe.call(e,t)&&ae(i,t,e[t]);return i},K=(i,e)=>Ce(i,Ae(e));var p=(i,e,t)=>new Promise((a,o)=>{var l=R=>{try{E(t.next(R))}catch(u){o(u)}},d=R=>{try{E(t.throw(R))}catch(u){o(u)}},E=R=>R.done?a(R.value):Promise.resolve(R.value).then(l,d);E((t=t.apply(i,e)).next())});function U(i){this.message=i}U.prototype=new Error,U.prototype.name="InvalidCharacterError";var oe=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(i){var e=String(i).replace(/=+$/,"");if(e.length%4==1)throw new U("'atob' failed: The string to be decoded is not correctly encoded.");for(var t,a,o=0,l=0,d="";a=e.charAt(l++);~a&&(t=o%4?64*t+a:a,o++%4)?d+=String.fromCharCode(255&t>>(-2*o&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return d};function De(i){var e=i.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(oe(t).replace(/(.)/g,function(a,o){var l=o.charCodeAt(0).toString(16).toUpperCase();return l.length<2&&(l="0"+l),"%"+l}))}(e)}catch(t){return oe(e)}}function k(i){this.message=i}function Pe(i,e){if(typeof i!="string")throw new k("Invalid token specified");var t=(e=e||{}).header===!0?0:1;try{return JSON.parse(De(i.split(".")[t]))}catch(a){throw new k("Invalid token specified: "+a.message)}}k.prototype=new Error,k.prototype.name="InvalidTokenError";var se=Pe;function le(i){return{all:i=i||new Map,on:function(e,t){var a=i.get(e);a&&a.push(t)||i.set(e,[t])},off:function(e,t){var a=i.get(e);a&&a.splice(a.indexOf(t)>>>0,1)},emit:function(e,t){(i.get(e)||[]).slice().map(function(a){a(t)}),(i.get("*")||[]).slice().map(function(a){a(e,t)})}}}var N=(v=>(v.READY="ready",v.CONNECTED="connected",v.DISCONNECTED="disconnected",v.STOPPED="stopped",v.POLLING="polling",v.POLLING_STOPPED="polling stopped",v.FLAGS_LOADED="flags loaded",v.CACHE_LOADED="cache loaded",v.CHANGED="changed",v.ERROR="error",v.ERROR_CACHE="cache error",v.ERROR_METRICS="metrics error",v.ERROR_AUTH="auth error",v.ERROR_FETCH_FLAGS="fetch flags error",v.ERROR_FETCH_FLAG="fetch flag error",v.ERROR_STREAM="stream error",v))(N||{});var xe={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},ce=i=>{let e=C(C({},xe),i);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},j=(i,e=!0)=>{e?setTimeout(i,0):i()},V=(i,e)=>Math.round(Math.random()*(e-i)+i),ue=i=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",a=0,o=Me(JSON.stringify(i));for(;a<o.length;){let l=o.charCodeAt(a++),d=o.charCodeAt(a++),E=o.charCodeAt(a++),R=l>>2,u=(l&3)<<4|d>>4,S=(d&15)<<2|E>>6,A=E&63;isNaN(d)?S=A=64:isNaN(E)&&(A=64),t+=e.charAt(R)+e.charAt(u)+e.charAt(S)+e.charAt(A)}return t},Me=i=>i.replace(/\r\n/g,`
`).split("").map(e=>{let t=e.charCodeAt(0);return t<128?String.fromCharCode(t):t>127&&t<2048?String.fromCharCode(t>>6|192)+String.fromCharCode(t&63|128):String.fromCharCode(t>>12|224)+String.fromCharCode(t>>6&63|128)+String.fromCharCode(t&63|128)}).join("");function W(i){return function(...t){let[a,o]=i(t);return fetch(a,o)}}var de=3e4,_=class{constructor(e,t,a,o,l,d,E,R,u,S){this.eventBus=e;this.configurations=t;this.url=a;this.apiKey=o;this.standardHeaders=l;this.fallbackPoller=d;this.logDebug=E;this.logError=R;this.eventCallback=u;this.maxRetries=S;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1;this.reconnectAttempts=0;this.retriesExhausted=!1}start(){let e=u=>{u.toString().split(/\r?\n/).forEach(t)},t=u=>{if(u.startsWith("data:")){let S=JSON.parse(u.substring(5));this.logDebugMessage("Received event from stream: ",S),this.eventCallback(S)}},a=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected"),this.reconnectAttempts=0},o=()=>{clearInterval(this.readTimeoutCheckerId);let u=V(1e3,1e4);if(this.reconnectAttempts++,this.logDebugMessage("Stream disconnected, will reconnect in "+u+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),this.reconnectAttempts>=5&&this.reconnectAttempts%5===0&&this.logErrorMessage(`Reconnection failed after ${this.reconnectAttempts} attempts; attempting further reconnections.`),this.reconnectAttempts>=this.maxRetries){this.retriesExhausted=!0,this.configurations.pollingEnabled?this.logErrorMessage("Max streaming retries reached. Staying in polling mode."):this.logErrorMessage("Max streaming retries reached. Polling mode is disabled and will receive no further flag updates until SDK client is restarted.");return}setTimeout(()=>this.start(),u)},l=u=>{this.retriesExhausted||(u&&this.logDebugMessage("Stream has issue",u),this.fallBackToPolling(),this.eventBus.emit("stream error",u),this.eventBus.emit("error",u),o())},d=C({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[u,S]of Object.entries(d))this.xhr.setRequestHeader(u,S);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{l(`Received XMLHttpRequest onLoad event: ${this.xhr.status}`)};let E=0,R=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(a(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),R=Date.now();let u=this.xhr.responseText.slice(E);E+=u.length,this.logDebugMessage("SSE GOT: "+u),e(u)},this.readTimeoutCheckerId=setInterval(()=>{R<Date.now()-de&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},de),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...t){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...t)}logErrorMessage(e,...t){this.logError(`Streaming: ${e}`,...t)}};function ge(i,e,t,a,o){let l=i in t,d=l?t[i]:e;return l&&a(i,d),o?{value:d,isDefaultValue:!l}:d}var x=class{constructor(e,t,a,o,l){this.fetchFlagsFn=e;this.configurations=t;this.eventBus=a;this.logDebug=o;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.isRunning&&this.attemptFetch().finally(()=>{this.isRunning&&(this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval))})}attemptFetch(){return p(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let t=yield this.fetchFlagsFn();if(t.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",t.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,t.error);let a=V(1e3,1e4);yield new Promise(o=>setTimeout(o,a))}})}stop(){this.timeoutId&&(this.isRunning=!1,clearTimeout(this.timeoutId),this.timeoutId=void 0,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...t){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...t)}logErrorMessage(e,...t){this.logError(`Poller: ${e}`,...t)}};function fe(t){return p(this,arguments,function*(i,e={}){let a=yield Ve(i),o=_e(e);return{loadFromCache:()=>J(a,o,e),saveToCache:l=>Y(a,o,l),updateCachedEvaluation:l=>ke(a,o,l),removeCachedEvaluation:l=>Ne(a,o,l)}})}function J(a,o){return p(this,arguments,function*(i,e,t={}){let l=parseInt(yield e.getItem(i+".ts"));if(t!=null&&t.ttl&&!isNaN(l)&&l+t.ttl<Date.now())return yield Fe(i,e),[];let d=yield e.getItem(i);if(d)try{return JSON.parse(d)}catch(E){}return[]})}function Fe(i,e){return p(this,null,function*(){yield e.removeItem(i),yield e.removeItem(i+".ts")})}function Y(i,e,t){return p(this,null,function*(){yield e.setItem(i,JSON.stringify(t)),yield e.setItem(i+".ts",Date.now().toString())})}function ke(i,e,t){return p(this,null,function*(){let a=yield J(i,e),o=a.find(({flag:l})=>l===t.flag);o?Object.assign(o,t):a.push(t),yield Y(i,e,a)})}function Ne(i,e,t){return p(this,null,function*(){let a=yield J(i,e),o=a.findIndex(({flag:l})=>l===t);o>-1&&(a.splice(o,1),yield Y(i,e,a))})}function Ve(i){return p(this,null,function*(){var t,a;let e=i;if(globalThis!=null&&globalThis.TextEncoder&&((a=(t=globalThis==null?void 0:globalThis.crypto)==null?void 0:t.subtle)!=null&&a.digest)){let l=new TextEncoder().encode(i),d=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(d)).map(R=>R.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(i));return"HARNESS_FF_CACHE_"+e})}function _e(i){let e;return!i.storage||typeof i.storage!="object"||!("getItem"in i.storage)||!("setItem"in i.storage)||!("removeItem"in i.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Le:e=i.storage,{getItem(a){return p(this,null,function*(){let o=e.getItem(a);return o instanceof Promise?yield o:o})},setItem(a,o){return p(this,null,function*(){let l=e.setItem(a,o);l instanceof Promise&&(yield l)})},removeItem(a){return p(this,null,function*(){let o=e.removeItem(a);o instanceof Promise&&(yield o)})}}}var Le={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var me="1.26.1",he=`Javascript ${me} Client`,He=500,$e=globalThis.fetch,X=!!globalThis.Proxy,yt=(i,e,t)=>{let a=!1,o,l,d,E,R,u,S=!0,A={},M=W(n=>n),z=0,Q=!1,L=()=>{S=!1},v=()=>{S=!0},w=[],f=le(),m=ce(t),b=(n,...r)=>{m.debug&&m.logger.debug(`[FF-SDK] ${n}`,...r)},T=(n,...r)=>{m.logger.error(`[FF-SDK] ${n}`,...r)},pe=(n,...r)=>{m.logger.warn(`[FF-SDK] ${n}`,...r)},H=n=>{let{value:r}=n;try{switch(n.kind.toLowerCase()){case"int":case"number":r=Number(r);break;case"boolean":r=r.toString().toLowerCase()==="true";break;case"json":r=JSON.parse(r);break}}catch(c){T(c)}return r},$=n=>{if(S){let r=Date.now();r-n.lastAccessed>He&&(n.count++,n.lastAccessed=r)}},ve=()=>p(void 0,null,function*(){if(m.cache){b("initializing cache");try{let n=!0,r=yield fe(e.identifier+i,typeof m.cache=="boolean"?{}:m.cache),c=yield r.loadFromCache();c!=null&&c.length&&j(()=>{b("loading from cache",c),ie(c,!1),f.emit("cache loaded",c)}),B("flags loaded",h=>p(void 0,null,function*(){yield r.saveToCache(h),n=!1})),B("changed",h=>p(void 0,null,function*(){n||(h.deleted?yield r.removeCachedEvaluation(h.flag):yield r.updateCachedEvaluation(h))}))}catch(n){T("Cache error: ",n),f.emit("cache error",n),f.emit("error",n)}}}),Ee=(n,r)=>p(void 0,null,function*(){let c=`${r.baseUrl}/client/auth`,h={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":he},body:JSON.stringify({apiKey:n,target:K(C({},e),{identifier:String(e.identifier)})})},y,s;window.AbortController&&m.authRequestReadTimeout>0?(s=new AbortController,h.signal=s.signal,y=window.setTimeout(()=>s.abort(),r.authRequestReadTimeout)):r.authRequestReadTimeout>0&&pe("AbortController is not available, auth request will not timeout");try{let g=yield $e(c,h);if(!g.ok)throw new Error(`${g.status}: ${g.statusText}`);return(yield g.json()).authToken}catch(g){if(s&&s.signal.aborted)throw new Error(`Request to ${c} failed: Request timeout via configured authRequestTimeout of ${m.authRequestReadTimeout}`);let D=g instanceof Error?g.message:String(g);throw new Error(`Request to ${c} failed: ${D}`)}finally{y&&clearTimeout(y)}}),G=0,q=()=>{if(w.length){b("Sending metrics...",{metrics:w,evaluations:I});let n={metricsData:w.map(r=>({timestamp:Date.now(),count:r.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:r.featureIdentifier},{key:"featureName",value:r.featureIdentifier},{key:"variationIdentifier",value:r.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:me}]}))};M(`${m.eventUrl}/metrics/${o}?cluster=${l}`,{method:"POST",headers:C({"Content-Type":"application/json"},A),body:JSON.stringify(n)}).then(()=>{w=[],G=0}).catch(r=>{G++&&(w=[],G=0),b(r),f.emit("metrics error",r)}).finally(()=>{u=window.setTimeout(q,m.eventsSyncInterval)})}else u=window.setTimeout(q,m.eventsSyncInterval)},I={},Re=n=>{b("Sending event for",n.flag),X?f.emit("changed",new Proxy(n,{get(r,c){var h;if(S&&r.hasOwnProperty(c)&&c==="value"){let y=r.flag,s=n.value,g=w.find(D=>D.featureIdentifier===y&&D.featureValue===s);g?($(g),g.variationIdentifier=((h=I[y])==null?void 0:h.identifier)||""):w.push({featureIdentifier:y,featureValue:String(s),variationIdentifier:I[y].identifier||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag",c,"has been read with value via stream update",s)}return c==="value"?H(n):n[c]}})):f.emit("changed",{deleted:n.deleted,flag:n.flag,value:H(n)})},Z=function(){return X?new Proxy({},{get(n,r){var h,y,s;let c=n[r];if(S&&n.hasOwnProperty(r)){let g=n[r],D=w.find(ne=>ne.featureIdentifier===r&&g===ne.featureValue);D?(D.variationIdentifier=((h=I[r])==null?void 0:h.identifier)||"",$(D)):w.push({featureIdentifier:r,featureValue:g,variationIdentifier:((y=I[r])==null?void 0:y.identifier)||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag:",r,"has been read with value:",g,"variationIdentifier:",(s=I[r])==null?void 0:s.identifier)}return c}}):{}},O=Z();ve().then(()=>Ee(i,m).then(n=>p(void 0,null,function*(){if(a)return;R=n;let r=se(n);A={Authorization:`Bearer ${R}`,"Harness-AccountID":r.accountID,"Harness-EnvironmentID":r.environmentIdentifier,"Harness-SDK-Info":he};let c=ue(e);c.length<262144&&(A["Harness-Target"]=c),b("Authenticated",r),u=window.setTimeout(q,m.eventsSyncInterval),o=r.environment,l=r.clusterIdentifier;let h=!!Object.keys(I).length;if((yield F()).type==="success"&&b("Fetch all flags ok",O),!a){if(m.streamEnabled?(b("Streaming mode enabled"),be()):m.pollingEnabled?(b("Polling mode enabled"),ye()):b("Streaming and polling mode disabled"),!h){L();let s=C({},O);v(),f.emit("ready",s)}Q=!0}})).catch(n=>{T("Authentication error: ",n),f.emit("auth error",n),f.emit("error",n)}));let F=()=>p(void 0,null,function*(){try{let n=yield M(`${m.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:A});if(n.ok){let r=yield n.json();return r.forEach(P),f.emit("flags loaded",r),{type:"success",data:r}}else return T("Features fetch operation error: ",n),f.emit("fetch flags error",n),f.emit("error",n),{type:"error",error:n}}catch(n){return T("Features fetch operation error: ",n),f.emit("fetch flags error",n),f.emit("error",n),{type:"error",error:n}}}),ee=n=>p(void 0,null,function*(){try{let r=yield M(`${m.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations/${n}?cluster=${l}`,{headers:A});if(r.ok){let c=yield r.json();P(c)}else T("Feature fetch operation error: ",r),f.emit("fetch flag error",r),f.emit("error",r)}catch(r){T("Feature fetch operation error: ",r),f.emit("fetch flag error",r),f.emit("error",r)}}),P=n=>{L();let r=H(n);r!==O[n.flag]&&(b("Flag variation has changed for ",n.identifier),O[n.flag]=r,I[n.flag]=K(C({},n),{value:r}),Re(n)),v()};E=new x(F,m,f,b,T);let be=()=>{let n=s=>{switch(s.event){case"create":c(s.evaluations)?s.evaluations.forEach(g=>{P(g)}):setTimeout(()=>ee(s.identifier),1e3);break;case"patch":c(s.evaluations)?s.evaluations.forEach(g=>{P(g)}):ee(s.identifier);break;case"delete":delete O[s.identifier],f.emit("changed",{flag:s.identifier,value:void 0,deleted:!0}),b("Evaluation deleted",{message:s,storage:O});break}},r=s=>!(!s||!s.flag||!s.identifier||!s.kind||!s.value),c=s=>!(!s||s.length==0||!s.every(g=>r(g))),h=s=>{s.event==="patch"&&(c(s.evaluations)?s.evaluations.forEach(g=>{P(g)}):F())},y=`${m.baseUrl}/stream?cluster=${l}`;d=new _(f,m,y,i,A,E,b,T,s=>{s.domain==="flag"?n(s):s.domain==="target-segment"&&h(s)},m.maxStreamRetries),d.start()},ye=()=>{E.start()},B=(n,r)=>f.on(n,r),Se=(n,r)=>{n?f.off(n,r):te()},Ie=(n,r)=>{var s;if(!S||X||r===void 0)return;let c=r,h=n,y=w.find(g=>g.featureIdentifier===h&&g.featureValue===c);y?($(y),y.variationIdentifier=((s=I[h])==null?void 0:s.identifier)||""):w.push({featureIdentifier:h,featureValue:c,count:1,variationIdentifier:I[h].identifier||"",lastAccessed:Date.now()})},te=()=>{a=!0,m.streamEnabled&&(b("Closing event stream"),typeof(d==null?void 0:d.close)=="function"&&d.close(),f.all.clear()),m.pollingEnabled&&E.isPolling()&&(b("Closing Poller"),E.stop()),O=Z(),I={},clearTimeout(u)},ie=(n,r=!0)=>{n.length&&j(()=>{let c=!!Object.keys(I).length;if(n.forEach(P),!c){L();let h=C({},O);v(),f.emit("ready",h)}},r)};return{on:B,off:Se,close:te,setEvaluations:ie,registerAPIRequestMiddleware:n=>{M=W(n)},refreshEvaluations:()=>{Q&&!a&&Date.now()-z>=6e4&&(F(),z=Date.now())},variation:(n,r,c=!1)=>ge(n,r,O,Ie,c)}};export{N as Event,yt as initialize};
var Ie=Object.defineProperty,Ce=Object.defineProperties;var we=Object.getOwnPropertyDescriptors;var re=Object.getOwnPropertySymbols;var Te=Object.prototype.hasOwnProperty,Ae=Object.prototype.propertyIsEnumerable;var ae=(i,e,t)=>e in i?Ie(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t,w=(i,e)=>{for(var t in e||(e={}))Te.call(e,t)&&ae(i,t,e[t]);if(re)for(var t of re(e))Ae.call(e,t)&&ae(i,t,e[t]);return i},U=(i,e)=>Ce(i,we(e));var h=(i,e,t)=>new Promise((a,o)=>{var s=E=>{try{p(t.next(E))}catch(d){o(d)}},g=E=>{try{p(t.throw(E))}catch(d){o(d)}},p=E=>E.done?a(E.value):Promise.resolve(E.value).then(s,g);p((t=t.apply(i,e)).next())});function j(i){this.message=i}j.prototype=new Error,j.prototype.name="InvalidCharacterError";var oe=typeof window!="undefined"&&window.atob&&window.atob.bind(window)||function(i){var e=String(i).replace(/=+$/,"");if(e.length%4==1)throw new j("'atob' failed: The string to be decoded is not correctly encoded.");for(var t,a,o=0,s=0,g="";a=e.charAt(s++);~a&&(t=o%4?64*t+a:a,o++%4)?g+=String.fromCharCode(255&t>>(-2*o&6)):0)a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(a);return g};function Oe(i){var e=i.replace(/-/g,"+").replace(/_/g,"/");switch(e.length%4){case 0:break;case 2:e+="==";break;case 3:e+="=";break;default:throw"Illegal base64url string!"}try{return function(t){return decodeURIComponent(oe(t).replace(/(.)/g,function(a,o){var s=o.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(e)}catch(t){return oe(e)}}function M(i){this.message=i}function De(i,e){if(typeof i!="string")throw new M("Invalid token specified");var t=(e=e||{}).header===!0?0:1;try{return JSON.parse(Oe(i.split(".")[t]))}catch(a){throw new M("Invalid token specified: "+a.message)}}M.prototype=new Error,M.prototype.name="InvalidTokenError";var se=De;function le(i){return{all:i=i||new Map,on:function(e,t){var a=i.get(e);a&&a.push(t)||i.set(e,[t])},off:function(e,t){var a=i.get(e);a&&a.splice(a.indexOf(t)>>>0,1)},emit:function(e,t){(i.get(e)||[]).slice().map(function(a){a(t)}),(i.get("*")||[]).slice().map(function(a){a(e,t)})}}}var N=(m=>(m.READY="ready",m.CONNECTED="connected",m.DISCONNECTED="disconnected",m.STOPPED="stopped",m.POLLING="polling",m.POLLING_STOPPED="polling stopped",m.FLAGS_LOADED="flags loaded",m.CACHE_LOADED="cache loaded",m.CHANGED="changed",m.ERROR="error",m.ERROR_CACHE="cache error",m.ERROR_METRICS="metrics error",m.ERROR_AUTH="auth error",m.ERROR_FETCH_FLAGS="fetch flags error",m.ERROR_FETCH_FLAG="fetch flag error",m.ERROR_STREAM="stream error",m))(N||{});var Pe={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1},ce=i=>{let e=w(w({},Pe),i);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},q=(i,e=!0)=>{e?setTimeout(i,0):i()},V=(i,e)=>Math.round(Math.random()*(e-i)+i),de=i=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",t="",a=0,o=Fe(JSON.stringify(i));for(;a<o.length;){let s=o.charCodeAt(a++),g=o.charCodeAt(a++),p=o.charCodeAt(a++),E=s>>2,d=(s&3)<<4|g>>4,R=(g&15)<<2|p>>6,T=p&63;isNaN(g)?R=T=64:isNaN(p)&&(T=64),t+=e.charAt(E)+e.charAt(d)+e.charAt(R)+e.charAt(T)}return t},Fe=i=>i.replace(/\r\n/g,`
`).split("").map(e=>{let t=e.charCodeAt(0);return t<128?String.fromCharCode(t):t>127&&t<2048?String.fromCharCode(t>>6|192)+String.fromCharCode(t&63|128):String.fromCharCode(t>>12|224)+String.fromCharCode(t>>6&63|128)+String.fromCharCode(t&63|128)}).join("");function J(i){return function(...t){let[a,o]=i(t);return fetch(a,o)}}var ge=3e4,_=class{constructor(e,t,a,o,s,g,p,E,d){this.eventBus=e;this.configurations=t;this.url=a;this.apiKey=o;this.standardHeaders=s;this.fallbackPoller=g;this.logDebug=p;this.logError=E;this.eventCallback=d;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1}start(){let e=d=>{d.toString().split(/\r?\n/).forEach(t)},t=d=>{if(d.startsWith("data:")){let R=JSON.parse(d.substring(5));this.logDebugMessage("Received event from stream: ",R),this.eventCallback(R)}},a=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected")},o=()=>{clearInterval(this.readTimeoutCheckerId);let d=V(1e3,1e4);this.logDebugMessage("Stream disconnected, will reconnect in "+d+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),setTimeout(()=>this.start(),d)},s=d=>{d&&this.logErrorMessage("Stream has issue",d),this.fallBackToPolling(),this.eventBus.emit("stream error",d),this.eventBus.emit("error",d),o()},g=w({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[d,R]of Object.entries(g))this.xhr.setRequestHeader(d,R);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,s("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||s(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,s("SSE timeout")},this.xhr.onload=()=>{if(this.xhr.status>=400&&this.xhr.status<=599){s(`HTTP code ${this.xhr.status}`);return}this.connectionOpened||(a(),this.connectionOpened=!0,this.disconnectEventEmitted=!1)};let p=0,E=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(a(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),E=Date.now();let d=this.xhr.responseText.slice(p);p+=d.length,this.logDebugMessage("SSE GOT: "+d),e(d)},this.readTimeoutCheckerId=setInterval(()=>{E<Date.now()-ge&&(this.logErrorMessage("SSE read timeout"),this.xhr.abort())},ge),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...t){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...t)}logErrorMessage(e,...t){this.logError(`Streaming: ${e}`,...t)}};function ue(i,e,t,a,o){let s=i in t,g=s?t[i]:e;return s&&a(i,g),o?{value:g,isDefaultValue:!s}:g}var F=class{constructor(e,t,a,o,s){this.fetchFlagsFn=e;this.configurations=t;this.eventBus=a;this.logDebug=o;this.logError=s;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.attemptFetch().finally(()=>{this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)})}attemptFetch(){return h(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let t=yield this.fetchFlagsFn();if(t.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",t.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,t.error);let a=V(1e3,1e4);yield new Promise(o=>setTimeout(o,a))}})}stop(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0,this.isRunning=!1,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...t){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...t)}logErrorMessage(e,...t){this.logError(`Poller: ${e}`,...t)}};function fe(t){return h(this,arguments,function*(i,e={}){let a=yield Ne(i),o=Ve(e);return{loadFromCache:()=>W(a,o,e),saveToCache:s=>Y(a,o,s),updateCachedEvaluation:s=>ke(a,o,s),removeCachedEvaluation:s=>Me(a,o,s)}})}function W(a,o){return h(this,arguments,function*(i,e,t={}){let s=parseInt(yield e.getItem(i+".ts"));if(t!=null&&t.ttl&&!isNaN(s)&&s+t.ttl<Date.now())return yield xe(i,e),[];let g=yield e.getItem(i);if(g)try{return JSON.parse(g)}catch(p){}return[]})}function xe(i,e){return h(this,null,function*(){yield e.removeItem(i),yield e.removeItem(i+".ts")})}function Y(i,e,t){return h(this,null,function*(){yield e.setItem(i,JSON.stringify(t)),yield e.setItem(i+".ts",Date.now().toString())})}function ke(i,e,t){return h(this,null,function*(){let a=yield W(i,e),o=a.find(({flag:s})=>s===t.flag);o?Object.assign(o,t):a.push(t),yield Y(i,e,a)})}function Me(i,e,t){return h(this,null,function*(){let a=yield W(i,e),o=a.findIndex(({flag:s})=>s===t);o>-1&&(a.splice(o,1),yield Y(i,e,a))})}function Ne(i){return h(this,null,function*(){var t,a;let e=i;if(globalThis!=null&&globalThis.TextEncoder&&((a=(t=globalThis==null?void 0:globalThis.crypto)==null?void 0:t.subtle)!=null&&a.digest)){let s=new TextEncoder().encode(i),g=yield crypto.subtle.digest("SHA-256",s);e=Array.from(new Uint8Array(g)).map(E=>E.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(i));return"HARNESS_FF_CACHE_"+e})}function Ve(i){let e;return!i.storage||typeof i.storage!="object"||!("getItem"in i.storage)||!("setItem"in i.storage)||!("removeItem"in i.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=_e:e=i.storage,{getItem(a){return h(this,null,function*(){let o=e.getItem(a);return o instanceof Promise?yield o:o})},setItem(a,o){return h(this,null,function*(){let s=e.setItem(a,o);s instanceof Promise&&(yield s)})},removeItem(a){return h(this,null,function*(){let o=e.removeItem(a);o instanceof Promise&&(yield o)})}}}var _e={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var me="1.26.1",he=`Javascript ${me} Client`,Le=500,He=globalThis.fetch,z=!!globalThis.Proxy,bt=(i,e,t)=>{let a=!1,o,s,g,p,E,d,R=!0,T={},x=J(n=>n),X=0,Q=!1,L=()=>{R=!1},m=()=>{R=!0},C=[],u=le(),v=ce(t),y=(n,...r)=>{v.debug&&v.logger.debug(`[FF-SDK] ${n}`,...r)},A=(n,...r)=>{v.logger.error(`[FF-SDK] ${n}`,...r)},H=n=>{let{value:r}=n;try{switch(n.kind.toLowerCase()){case"int":case"number":r=Number(r);break;case"boolean":r=r.toString().toLowerCase()==="true";break;case"json":r=JSON.parse(r);break}}catch(c){A(c)}return r},G=n=>{if(R){let r=Date.now();r-n.lastAccessed>Le&&(n.count++,n.lastAccessed=r)}},ve=()=>h(void 0,null,function*(){if(v.cache){y("initializing cache");try{let n=!0,r=yield fe(e.identifier+i,typeof v.cache=="boolean"?{}:v.cache),c=yield r.loadFromCache();c!=null&&c.length&&q(()=>{y("loading from cache",c),ie(c,!1),u.emit("cache loaded",c)}),K("flags loaded",f=>h(void 0,null,function*(){yield r.saveToCache(f),n=!1})),K("changed",f=>h(void 0,null,function*(){n||(f.deleted?yield r.removeCachedEvaluation(f.flag):yield r.updateCachedEvaluation(f))}))}catch(n){A("Cache error: ",n),u.emit("cache error",n),u.emit("error",n)}}}),pe=(n,r)=>h(void 0,null,function*(){return(yield(yield He(`${r.baseUrl}/client/auth`,{method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":he},body:JSON.stringify({apiKey:n,target:U(w({},e),{identifier:String(e.identifier)})})})).json()).authToken}),$=0,B=()=>{if(C.length){y("Sending metrics...",{metrics:C,evaluations:I});let n={metricsData:C.map(r=>({timestamp:Date.now(),count:r.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:r.featureIdentifier},{key:"featureName",value:r.featureIdentifier},{key:"variationIdentifier",value:r.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:me}]}))};x(`${v.eventUrl}/metrics/${o}?cluster=${s}`,{method:"POST",headers:w({"Content-Type":"application/json"},T),body:JSON.stringify(n)}).then(()=>{C=[],$=0}).catch(r=>{$++&&(C=[],$=0),y(r),u.emit("metrics error",r)}).finally(()=>{d=window.setTimeout(B,v.eventsSyncInterval)})}else d=window.setTimeout(B,v.eventsSyncInterval)},I={},Ee=n=>{y("Sending event for",n.flag),z?u.emit("changed",new Proxy(n,{get(r,c){var f;if(R&&r.hasOwnProperty(c)&&c==="value"){let S=r.flag,l=n.value,b=C.find(P=>P.featureIdentifier===S&&P.featureValue===l);b?(G(b),b.variationIdentifier=((f=I[S])==null?void 0:f.identifier)||""):C.push({featureIdentifier:S,featureValue:String(l),variationIdentifier:I[S].identifier||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag",c,"has been read with value via stream update",l)}return c==="value"?H(n):n[c]}})):u.emit("changed",{deleted:n.deleted,flag:n.flag,value:H(n)})},Z=function(){return z?new Proxy({},{get(n,r){var f,S,l;let c=n[r];if(R&&n.hasOwnProperty(r)){let b=n[r],P=C.find(ne=>ne.featureIdentifier===r&&b===ne.featureValue);P?(P.variationIdentifier=((f=I[r])==null?void 0:f.identifier)||"",G(P)):C.push({featureIdentifier:r,featureValue:b,variationIdentifier:((S=I[r])==null?void 0:S.identifier)||"",count:1,lastAccessed:Date.now()}),y("Metrics event: Flag:",r,"has been read with value:",b,"variationIdentifier:",(l=I[r])==null?void 0:l.identifier)}return c}}):{}},O=Z();ve().then(()=>pe(i,v).then(n=>h(void 0,null,function*(){if(a)return;E=n;let r=se(n);T={Authorization:`Bearer ${E}`,"Harness-AccountID":r.accountID,"Harness-EnvironmentID":r.environmentIdentifier,"Harness-SDK-Info":he};let c=de(e);c.length<262144&&(T["Harness-Target"]=c),y("Authenticated",r),d=window.setTimeout(B,v.eventsSyncInterval),o=r.environment,s=r.clusterIdentifier;let f=!!Object.keys(I).length;if((yield k()).type==="success"&&y("Fetch all flags ok",O),!a){if(v.streamEnabled?(y("Streaming mode enabled"),ye()):v.pollingEnabled?(y("Polling mode enabled"),be()):y("Streaming and polling mode disabled"),!f){L();let l=w({},O);m(),u.emit("ready",l)}Q=!0}})).catch(n=>{A("Authentication error: ",n),u.emit("auth error",n),u.emit("error",n)}));let k=()=>h(void 0,null,function*(){try{let n=yield x(`${v.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations?cluster=${s}`,{headers:T});if(n.ok){let r=yield n.json();return r.forEach(D),u.emit("flags loaded",r),{type:"success",data:r}}else return A("Features fetch operation error: ",n),u.emit("fetch flags error",n),u.emit("error",n),{type:"error",error:n}}catch(n){return A("Features fetch operation error: ",n),u.emit("fetch flags error",n),u.emit("error",n),{type:"error",error:n}}}),ee=n=>h(void 0,null,function*(){try{let r=yield x(`${v.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations/${n}?cluster=${s}`,{headers:T});if(r.ok){let c=yield r.json();D(c)}else A("Feature fetch operation error: ",r),u.emit("fetch flag error",r),u.emit("error",r)}catch(r){A("Feature fetch operation error: ",r),u.emit("fetch flag error",r),u.emit("error",r)}}),D=n=>{L();let r=H(n);r!==O[n.flag]&&(y("Flag variation has changed for ",n.identifier),O[n.flag]=r,I[n.flag]=U(w({},n),{value:r}),Ee(n)),m()};p=new F(k,v,u,y,A);let ye=()=>{let n=l=>{switch(l.event){case"create":c(l.evaluations)?l.evaluations.forEach(b=>{D(b)}):setTimeout(()=>ee(l.identifier),1e3);break;case"patch":c(l.evaluations)?l.evaluations.forEach(b=>{D(b)}):ee(l.identifier);break;case"delete":delete O[l.identifier],u.emit("changed",{flag:l.identifier,value:void 0,deleted:!0}),y("Evaluation deleted",{message:l,storage:O});break}},r=l=>!(!l||!l.flag||!l.identifier||!l.kind||!l.value),c=l=>!(!l||l.length==0||!l.every(b=>r(b))),f=l=>{l.event==="patch"&&(c(l.evaluations)?l.evaluations.forEach(b=>{D(b)}):k())},S=`${v.baseUrl}/stream?cluster=${s}`;g=new _(u,v,S,i,T,p,y,A,l=>{l.domain==="flag"?n(l):l.domain==="target-segment"&&f(l)}),g.start()},be=()=>{p.start()},K=(n,r)=>u.on(n,r),Re=(n,r)=>{n?u.off(n,r):te()},Se=(n,r)=>{var l;if(!R||z||r===void 0)return;let c=r,f=n,S=C.find(b=>b.featureIdentifier===f&&b.featureValue===c);S?(G(S),S.variationIdentifier=((l=I[f])==null?void 0:l.identifier)||""):C.push({featureIdentifier:f,featureValue:c,count:1,variationIdentifier:I[f].identifier||"",lastAccessed:Date.now()})},te=()=>{a=!0,v.streamEnabled&&(y("Closing event stream"),typeof(g==null?void 0:g.close)=="function"&&g.close(),u.all.clear()),v.pollingEnabled&&p.isPolling()&&(y("Closing Poller"),p.stop()),O=Z(),I={},clearTimeout(d)},ie=(n,r=!0)=>{n.length&&q(()=>{let c=!!Object.keys(I).length;if(n.forEach(D),!c){L();let f=w({},O);m(),u.emit("ready",f)}},r)};return{on:K,off:Re,close:te,setEvaluations:ie,registerAPIRequestMiddleware:n=>{x=J(n)},refreshEvaluations:()=>{Q&&!a&&Date.now()-X>=6e4&&(k(),X=Date.now())},variation:(n,r,c=!1)=>ue(n,r,O,Se,c)}};export{N as Event,bt as initialize};

@@ -1,2 +0,2 @@

var Re=Object.defineProperty,be=Object.defineProperties;var Se=Object.getOwnPropertyDescriptors;var ie=Object.getOwnPropertySymbols;var ye=Object.prototype.hasOwnProperty,Ie=Object.prototype.propertyIsEnumerable;var ne=(r,e,n)=>e in r?Re(r,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):r[e]=n,w=(r,e)=>{for(var n in e||(e={}))ye.call(e,n)&&ne(r,n,e[n]);if(ie)for(var n of ie(e))Ie.call(e,n)&&ne(r,n,e[n]);return r},B=(r,e)=>be(r,Se(e));var v=(r,e,n)=>new Promise((o,s)=>{var l=R=>{try{E(n.next(R))}catch(u){s(u)}},h=R=>{try{E(n.throw(R))}catch(u){s(u)}},E=R=>R.done?o(R.value):Promise.resolve(R.value).then(l,h);E((n=n.apply(r,e)).next())});import Me from"jwt-decode";import Fe from"mitt";var N=(p=>(p.READY="ready",p.CONNECTED="connected",p.DISCONNECTED="disconnected",p.STOPPED="stopped",p.POLLING="polling",p.POLLING_STOPPED="polling stopped",p.FLAGS_LOADED="flags loaded",p.CACHE_LOADED="cache loaded",p.CHANGED="changed",p.ERROR="error",p.ERROR_CACHE="cache error",p.ERROR_METRICS="metrics error",p.ERROR_AUTH="auth error",p.ERROR_FETCH_FLAGS="fetch flags error",p.ERROR_FETCH_FLAG="fetch flag error",p.ERROR_STREAM="stream error",p))(N||{});var Ce={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1,authRequestReadTimeout:0,maxStreamRetries:1/0},re=r=>{let e=w(w({},Ce),r);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},K=(r,e=!0)=>{e?setTimeout(r,0):r()},k=(r,e)=>Math.round(Math.random()*(e-r)+r),ae=r=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",n="",o=0,s=we(JSON.stringify(r));for(;o<s.length;){let l=s.charCodeAt(o++),h=s.charCodeAt(o++),E=s.charCodeAt(o++),R=l>>2,u=(l&3)<<4|h>>4,y=(h&15)<<2|E>>6,A=E&63;isNaN(h)?y=A=64:isNaN(E)&&(A=64),n+=e.charAt(R)+e.charAt(u)+e.charAt(y)+e.charAt(A)}return n},we=r=>r.replace(/\r\n/g,`
`).split("").map(e=>{let n=e.charCodeAt(0);return n<128?String.fromCharCode(n):n>127&&n<2048?String.fromCharCode(n>>6|192)+String.fromCharCode(n&63|128):String.fromCharCode(n>>12|224)+String.fromCharCode(n>>6&63|128)+String.fromCharCode(n&63|128)}).join("");function j(r){return function(...n){let[o,s]=r(n);return fetch(o,s)}}var oe=3e4,V=class{constructor(e,n,o,s,l,h,E,R,u,y){this.eventBus=e;this.configurations=n;this.url=o;this.apiKey=s;this.standardHeaders=l;this.fallbackPoller=h;this.logDebug=E;this.logError=R;this.eventCallback=u;this.maxRetries=y;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1;this.reconnectAttempts=0;this.retriesExhausted=!1}start(){let e=u=>{u.toString().split(/\r?\n/).forEach(n)},n=u=>{if(u.startsWith("data:")){let y=JSON.parse(u.substring(5));this.logDebugMessage("Received event from stream: ",y),this.eventCallback(y)}},o=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected"),this.reconnectAttempts=0},s=()=>{clearInterval(this.readTimeoutCheckerId);let u=k(1e3,1e4);if(this.reconnectAttempts++,this.logDebugMessage("Stream disconnected, will reconnect in "+u+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),this.reconnectAttempts>=5&&this.reconnectAttempts%5===0&&this.logErrorMessage(`Reconnection failed after ${this.reconnectAttempts} attempts; attempting further reconnections.`),this.reconnectAttempts>=this.maxRetries){this.retriesExhausted=!0,this.configurations.pollingEnabled?this.logErrorMessage("Max streaming retries reached. Staying in polling mode."):this.logErrorMessage("Max streaming retries reached. Polling mode is disabled and will receive no further flag updates until SDK client is restarted.");return}setTimeout(()=>this.start(),u)},l=u=>{this.retriesExhausted||(u&&this.logDebugMessage("Stream has issue",u),this.fallBackToPolling(),this.eventBus.emit("stream error",u),this.eventBus.emit("error",u),s())},h=w({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[u,y]of Object.entries(h))this.xhr.setRequestHeader(u,y);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{l(`Received XMLHttpRequest onLoad event: ${this.xhr.status}`)};let E=0,R=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(o(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),R=Date.now();let u=this.xhr.responseText.slice(E);E+=u.length,this.logDebugMessage("SSE GOT: "+u),e(u)},this.readTimeoutCheckerId=setInterval(()=>{R<Date.now()-oe&&(this.logDebugMessage("SSE read timeout"),this.xhr.abort())},oe),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...n){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...n)}logErrorMessage(e,...n){this.logError(`Streaming: ${e}`,...n)}};function se(r,e,n,o,s){let l=r in n,h=l?n[r]:e;return l&&o(r,h),s?{value:h,isDefaultValue:!l}:h}var x=class{constructor(e,n,o,s,l){this.fetchFlagsFn=e;this.configurations=n;this.eventBus=o;this.logDebug=s;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.isRunning&&this.attemptFetch().finally(()=>{this.isRunning&&(this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval))})}attemptFetch(){return v(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let n=yield this.fetchFlagsFn();if(n.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",n.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,n.error);let o=k(1e3,1e4);yield new Promise(s=>setTimeout(s,o))}})}stop(){this.timeoutId&&(this.isRunning=!1,clearTimeout(this.timeoutId),this.timeoutId=void 0,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...n){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...n)}logErrorMessage(e,...n){this.logError(`Poller: ${e}`,...n)}};function le(n){return v(this,arguments,function*(r,e={}){let o=yield De(r),s=Pe(e);return{loadFromCache:()=>U(o,s,e),saveToCache:l=>W(o,s,l),updateCachedEvaluation:l=>Te(o,s,l),removeCachedEvaluation:l=>Oe(o,s,l)}})}function U(o,s){return v(this,arguments,function*(r,e,n={}){let l=parseInt(yield e.getItem(r+".ts"));if(n!=null&&n.ttl&&!isNaN(l)&&l+n.ttl<Date.now())return yield Ae(r,e),[];let h=yield e.getItem(r);if(h)try{return JSON.parse(h)}catch(E){}return[]})}function Ae(r,e){return v(this,null,function*(){yield e.removeItem(r),yield e.removeItem(r+".ts")})}function W(r,e,n){return v(this,null,function*(){yield e.setItem(r,JSON.stringify(n)),yield e.setItem(r+".ts",Date.now().toString())})}function Te(r,e,n){return v(this,null,function*(){let o=yield U(r,e),s=o.find(({flag:l})=>l===n.flag);s?Object.assign(s,n):o.push(n),yield W(r,e,o)})}function Oe(r,e,n){return v(this,null,function*(){let o=yield U(r,e),s=o.findIndex(({flag:l})=>l===n);s>-1&&(o.splice(s,1),yield W(r,e,o))})}function De(r){return v(this,null,function*(){var n,o;let e=r;if(globalThis!=null&&globalThis.TextEncoder&&((o=(n=globalThis==null?void 0:globalThis.crypto)==null?void 0:n.subtle)!=null&&o.digest)){let l=new TextEncoder().encode(r),h=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(h)).map(R=>R.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(r));return"HARNESS_FF_CACHE_"+e})}function Pe(r){let e;return!r.storage||typeof r.storage!="object"||!("getItem"in r.storage)||!("setItem"in r.storage)||!("removeItem"in r.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=xe:e=r.storage,{getItem(o){return v(this,null,function*(){let s=e.getItem(o);return s instanceof Promise?yield s:s})},setItem(o,s){return v(this,null,function*(){let l=e.setItem(o,s);l instanceof Promise&&(yield l)})},removeItem(o){return v(this,null,function*(){let s=e.removeItem(o);s instanceof Promise&&(yield s)})}}}var xe={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var ue="1.26.1",ce=`Javascript ${ue} Client`,Ne=500,ke=globalThis.fetch,J=!!globalThis.Proxy,ht=(r,e,n)=>{let o=!1,s,l,h,E,R,u,y=!0,A={},M=j(t=>t),Y=0,X=!1,_=()=>{y=!1},p=()=>{y=!0},C=[],d=Fe(),m=re(n),b=(t,...i)=>{m.debug&&m.logger.debug(`[FF-SDK] ${t}`,...i)},T=(t,...i)=>{m.logger.error(`[FF-SDK] ${t}`,...i)},ge=(t,...i)=>{m.logger.warn(`[FF-SDK] ${t}`,...i)},L=t=>{let{value:i}=t;try{switch(t.kind.toLowerCase()){case"int":case"number":i=Number(i);break;case"boolean":i=i.toString().toLowerCase()==="true";break;case"json":i=JSON.parse(i);break}}catch(c){T(c)}return i},H=t=>{if(y){let i=Date.now();i-t.lastAccessed>Ne&&(t.count++,t.lastAccessed=i)}},de=()=>v(void 0,null,function*(){if(m.cache){b("initializing cache");try{let t=!0,i=yield le(e.identifier+r,typeof m.cache=="boolean"?{}:m.cache),c=yield i.loadFromCache();c!=null&&c.length&&K(()=>{b("loading from cache",c),ee(c,!1),d.emit("cache loaded",c)}),q("flags loaded",f=>v(void 0,null,function*(){yield i.saveToCache(f),t=!1})),q("changed",f=>v(void 0,null,function*(){t||(f.deleted?yield i.removeCachedEvaluation(f.flag):yield i.updateCachedEvaluation(f))}))}catch(t){T("Cache error: ",t),d.emit("cache error",t),d.emit("error",t)}}}),fe=(t,i)=>v(void 0,null,function*(){let c=`${i.baseUrl}/client/auth`,f={method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":ce},body:JSON.stringify({apiKey:t,target:B(w({},e),{identifier:String(e.identifier)})})},S,a;window.AbortController&&m.authRequestReadTimeout>0?(a=new AbortController,f.signal=a.signal,S=window.setTimeout(()=>a.abort(),i.authRequestReadTimeout)):i.authRequestReadTimeout>0&&ge("AbortController is not available, auth request will not timeout");try{let g=yield ke(c,f);if(!g.ok)throw new Error(`${g.status}: ${g.statusText}`);return(yield g.json()).authToken}catch(g){if(a&&a.signal.aborted)throw new Error(`Request to ${c} failed: Request timeout via configured authRequestTimeout of ${m.authRequestReadTimeout}`);let D=g instanceof Error?g.message:String(g);throw new Error(`Request to ${c} failed: ${D}`)}finally{S&&clearTimeout(S)}}),$=0,G=()=>{if(C.length){b("Sending metrics...",{metrics:C,evaluations:I});let t={metricsData:C.map(i=>({timestamp:Date.now(),count:i.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:i.featureIdentifier},{key:"featureName",value:i.featureIdentifier},{key:"variationIdentifier",value:i.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:ue}]}))};M(`${m.eventUrl}/metrics/${s}?cluster=${l}`,{method:"POST",headers:w({"Content-Type":"application/json"},A),body:JSON.stringify(t)}).then(()=>{C=[],$=0}).catch(i=>{$++&&(C=[],$=0),b(i),d.emit("metrics error",i)}).finally(()=>{u=window.setTimeout(G,m.eventsSyncInterval)})}else u=window.setTimeout(G,m.eventsSyncInterval)},I={},he=t=>{b("Sending event for",t.flag),J?d.emit("changed",new Proxy(t,{get(i,c){var f;if(y&&i.hasOwnProperty(c)&&c==="value"){let S=i.flag,a=t.value,g=C.find(D=>D.featureIdentifier===S&&D.featureValue===a);g?(H(g),g.variationIdentifier=((f=I[S])==null?void 0:f.identifier)||""):C.push({featureIdentifier:S,featureValue:String(a),variationIdentifier:I[S].identifier||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag",c,"has been read with value via stream update",a)}return c==="value"?L(t):t[c]}})):d.emit("changed",{deleted:t.deleted,flag:t.flag,value:L(t)})},z=function(){return J?new Proxy({},{get(t,i){var f,S,a;let c=t[i];if(y&&t.hasOwnProperty(i)){let g=t[i],D=C.find(te=>te.featureIdentifier===i&&g===te.featureValue);D?(D.variationIdentifier=((f=I[i])==null?void 0:f.identifier)||"",H(D)):C.push({featureIdentifier:i,featureValue:g,variationIdentifier:((S=I[i])==null?void 0:S.identifier)||"",count:1,lastAccessed:Date.now()}),b("Metrics event: Flag:",i,"has been read with value:",g,"variationIdentifier:",(a=I[i])==null?void 0:a.identifier)}return c}}):{}},O=z();de().then(()=>fe(r,m).then(t=>v(void 0,null,function*(){if(o)return;R=t;let i=Me(t);A={Authorization:`Bearer ${R}`,"Harness-AccountID":i.accountID,"Harness-EnvironmentID":i.environmentIdentifier,"Harness-SDK-Info":ce};let c=ae(e);c.length<262144&&(A["Harness-Target"]=c),b("Authenticated",i),u=window.setTimeout(G,m.eventsSyncInterval),s=i.environment,l=i.clusterIdentifier;let f=!!Object.keys(I).length;if((yield F()).type==="success"&&b("Fetch all flags ok",O),!o){if(m.streamEnabled?(b("Streaming mode enabled"),me()):m.pollingEnabled?(b("Polling mode enabled"),ve()):b("Streaming and polling mode disabled"),!f){_();let a=w({},O);p(),d.emit("ready",a)}X=!0}})).catch(t=>{T("Authentication error: ",t),d.emit("auth error",t),d.emit("error",t)}));let F=()=>v(void 0,null,function*(){try{let t=yield M(`${m.baseUrl}/client/env/${s}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:A});if(t.ok){let i=yield t.json();return i.forEach(P),d.emit("flags loaded",i),{type:"success",data:i}}else return T("Features fetch operation error: ",t),d.emit("fetch flags error",t),d.emit("error",t),{type:"error",error:t}}catch(t){return T("Features fetch operation error: ",t),d.emit("fetch flags error",t),d.emit("error",t),{type:"error",error:t}}}),Q=t=>v(void 0,null,function*(){try{let i=yield M(`${m.baseUrl}/client/env/${s}/target/${e.identifier}/evaluations/${t}?cluster=${l}`,{headers:A});if(i.ok){let c=yield i.json();P(c)}else T("Feature fetch operation error: ",i),d.emit("fetch flag error",i),d.emit("error",i)}catch(i){T("Feature fetch operation error: ",i),d.emit("fetch flag error",i),d.emit("error",i)}}),P=t=>{_();let i=L(t);i!==O[t.flag]&&(b("Flag variation has changed for ",t.identifier),O[t.flag]=i,I[t.flag]=B(w({},t),{value:i}),he(t)),p()};E=new x(F,m,d,b,T);let me=()=>{let t=a=>{switch(a.event){case"create":c(a.evaluations)?a.evaluations.forEach(g=>{P(g)}):setTimeout(()=>Q(a.identifier),1e3);break;case"patch":c(a.evaluations)?a.evaluations.forEach(g=>{P(g)}):Q(a.identifier);break;case"delete":delete O[a.identifier],d.emit("changed",{flag:a.identifier,value:void 0,deleted:!0}),b("Evaluation deleted",{message:a,storage:O});break}},i=a=>!(!a||!a.flag||!a.identifier||!a.kind||!a.value),c=a=>!(!a||a.length==0||!a.every(g=>i(g))),f=a=>{a.event==="patch"&&(c(a.evaluations)?a.evaluations.forEach(g=>{P(g)}):F())},S=`${m.baseUrl}/stream?cluster=${l}`;h=new V(d,m,S,r,A,E,b,T,a=>{a.domain==="flag"?t(a):a.domain==="target-segment"&&f(a)},m.maxStreamRetries),h.start()},ve=()=>{E.start()},q=(t,i)=>d.on(t,i),pe=(t,i)=>{t?d.off(t,i):Z()},Ee=(t,i)=>{var a;if(!y||J||i===void 0)return;let c=i,f=t,S=C.find(g=>g.featureIdentifier===f&&g.featureValue===c);S?(H(S),S.variationIdentifier=((a=I[f])==null?void 0:a.identifier)||""):C.push({featureIdentifier:f,featureValue:c,count:1,variationIdentifier:I[f].identifier||"",lastAccessed:Date.now()})},Z=()=>{o=!0,m.streamEnabled&&(b("Closing event stream"),typeof(h==null?void 0:h.close)=="function"&&h.close(),d.all.clear()),m.pollingEnabled&&E.isPolling()&&(b("Closing Poller"),E.stop()),O=z(),I={},clearTimeout(u)},ee=(t,i=!0)=>{t.length&&K(()=>{let c=!!Object.keys(I).length;if(t.forEach(P),!c){_();let f=w({},O);p(),d.emit("ready",f)}},i)};return{on:q,off:pe,close:Z,setEvaluations:ee,registerAPIRequestMiddleware:t=>{M=j(t)},refreshEvaluations:()=>{X&&!o&&Date.now()-Y>=6e4&&(F(),Y=Date.now())},variation:(t,i,c=!1)=>se(t,i,O,Ee,c)}};export{N as Event,ht as initialize};
var Ee=Object.defineProperty,Re=Object.defineProperties;var ye=Object.getOwnPropertyDescriptors;var ie=Object.getOwnPropertySymbols;var be=Object.prototype.hasOwnProperty,Se=Object.prototype.propertyIsEnumerable;var ne=(a,e,n)=>e in a?Ee(a,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):a[e]=n,T=(a,e)=>{for(var n in e||(e={}))be.call(e,n)&&ne(a,n,e[n]);if(ie)for(var n of ie(e))Se.call(e,n)&&ne(a,n,e[n]);return a},K=(a,e)=>Re(a,ye(e));var h=(a,e,n)=>new Promise((r,o)=>{var l=E=>{try{p(n.next(E))}catch(g){o(g)}},u=E=>{try{p(n.throw(E))}catch(g){o(g)}},p=E=>E.done?r(E.value):Promise.resolve(E.value).then(l,u);p((n=n.apply(a,e)).next())});import Fe from"jwt-decode";import Me from"mitt";var x=(m=>(m.READY="ready",m.CONNECTED="connected",m.DISCONNECTED="disconnected",m.STOPPED="stopped",m.POLLING="polling",m.POLLING_STOPPED="polling stopped",m.FLAGS_LOADED="flags loaded",m.CACHE_LOADED="cache loaded",m.CHANGED="changed",m.ERROR="error",m.ERROR_CACHE="cache error",m.ERROR_METRICS="metrics error",m.ERROR_AUTH="auth error",m.ERROR_FETCH_FLAGS="fetch flags error",m.ERROR_FETCH_FLAG="fetch flag error",m.ERROR_STREAM="stream error",m))(x||{});var Ie={debug:!1,baseUrl:"https://config.ff.harness.io/api/1.0",eventUrl:"https://events.ff.harness.io/api/1.0",eventsSyncInterval:6e4,pollingInterval:6e4,streamEnabled:!0,cache:!1},ae=a=>{let e=T(T({},Ie),a);return e.pollingEnabled===void 0&&(e.pollingEnabled=e.streamEnabled),e.eventsSyncInterval<6e4&&(e.eventsSyncInterval=6e4),e.pollingInterval<6e4&&(e.pollingInterval=6e4),(!e.logger||!e.logger.debug||!e.logger.error||!e.logger.info||!e.logger.warn)&&(e.logger=console),e},j=(a,e=!0)=>{e?setTimeout(a,0):a()},k=(a,e)=>Math.round(Math.random()*(e-a)+a),re=a=>{let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",n="",r=0,o=Ce(JSON.stringify(a));for(;r<o.length;){let l=o.charCodeAt(r++),u=o.charCodeAt(r++),p=o.charCodeAt(r++),E=l>>2,g=(l&3)<<4|u>>4,b=(u&15)<<2|p>>6,A=p&63;isNaN(u)?b=A=64:isNaN(p)&&(A=64),n+=e.charAt(E)+e.charAt(g)+e.charAt(b)+e.charAt(A)}return n},Ce=a=>a.replace(/\r\n/g,`
`).split("").map(e=>{let n=e.charCodeAt(0);return n<128?String.fromCharCode(n):n>127&&n<2048?String.fromCharCode(n>>6|192)+String.fromCharCode(n&63|128):String.fromCharCode(n>>12|224)+String.fromCharCode(n>>6&63|128)+String.fromCharCode(n&63|128)}).join("");function U(a){return function(...n){let[r,o]=a(n);return fetch(r,o)}}var oe=3e4,V=class{constructor(e,n,r,o,l,u,p,E,g){this.eventBus=e;this.configurations=n;this.url=r;this.apiKey=o;this.standardHeaders=l;this.fallbackPoller=u;this.logDebug=p;this.logError=E;this.eventCallback=g;this.closed=!1;this.connectionOpened=!1;this.disconnectEventEmitted=!1}start(){let e=g=>{g.toString().split(/\r?\n/).forEach(n)},n=g=>{if(g.startsWith("data:")){let b=JSON.parse(g.substring(5));this.logDebugMessage("Received event from stream: ",b),this.eventCallback(b)}},r=()=>{this.logDebugMessage("Stream connected"),this.eventBus.emit("connected")},o=()=>{clearInterval(this.readTimeoutCheckerId);let g=k(1e3,1e4);this.logDebugMessage("Stream disconnected, will reconnect in "+g+"ms"),this.disconnectEventEmitted||(this.eventBus.emit("disconnected"),this.disconnectEventEmitted=!0),setTimeout(()=>this.start(),g)},l=g=>{g&&this.logErrorMessage("Stream has issue",g),this.fallBackToPolling(),this.eventBus.emit("stream error",g),this.eventBus.emit("error",g),o()},u=T({"Cache-Control":"no-cache",Accept:"text/event-stream","API-Key":this.apiKey},this.standardHeaders);this.logDebugMessage("SSE HTTP start request",this.url),this.xhr=new XMLHttpRequest,this.xhr.open("GET",this.url);for(let[g,b]of Object.entries(u))this.xhr.setRequestHeader(g,b);this.xhr.timeout=24*60*60*1e3,this.xhr.onerror=()=>{this.connectionOpened=!1,l("XMLHttpRequest error on SSE stream")},this.xhr.onabort=()=>{this.connectionOpened=!1,this.logDebugMessage("SSE aborted"),this.closed||l(null)},this.xhr.ontimeout=()=>{this.connectionOpened=!1,l("SSE timeout")},this.xhr.onload=()=>{if(this.xhr.status>=400&&this.xhr.status<=599){l(`HTTP code ${this.xhr.status}`);return}this.connectionOpened||(r(),this.connectionOpened=!0,this.disconnectEventEmitted=!1)};let p=0,E=Date.now();this.xhr.onprogress=()=>{this.connectionOpened||(r(),this.connectionOpened=!0,this.disconnectEventEmitted=!1),this.stopFallBackPolling(),E=Date.now();let g=this.xhr.responseText.slice(p);p+=g.length,this.logDebugMessage("SSE GOT: "+g),e(g)},this.readTimeoutCheckerId=setInterval(()=>{E<Date.now()-oe&&(this.logErrorMessage("SSE read timeout"),this.xhr.abort())},oe),this.xhr.send()}close(){this.connectionOpened=!1,this.closed=!0,this.xhr&&this.xhr.abort(),clearInterval(this.readTimeoutCheckerId),this.eventBus.emit("stopped"),this.stopFallBackPolling()}fallBackToPolling(){!this.fallbackPoller.isPolling()&&this.configurations.pollingEnabled&&(this.logDebugMessage("Falling back to polling mode while stream recovers"),this.fallbackPoller.start())}stopFallBackPolling(){this.fallbackPoller.isPolling()&&(this.logDebugMessage("Stopping fallback polling mode"),this.fallbackPoller.stop())}logDebugMessage(e,...n){this.configurations.debug&&this.logDebug(`Streaming: ${e}`,...n)}logErrorMessage(e,...n){this.logError(`Streaming: ${e}`,...n)}};function se(a,e,n,r,o){let l=a in n,u=l?n[a]:e;return l&&r(a,u),o?{value:u,isDefaultValue:!l}:u}var F=class{constructor(e,n,r,o,l){this.fetchFlagsFn=e;this.configurations=n;this.eventBus=r;this.logDebug=o;this.logError=l;this.maxAttempts=5}start(){if(this.isPolling()){this.logDebugMessage("Already polling.");return}this.isRunning=!0,this.eventBus.emit("polling"),this.logDebugMessage(`Starting poller, first poll will be in ${this.configurations.pollingInterval}ms`),this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)}poll(){this.attemptFetch().finally(()=>{this.timeoutId=setTimeout(()=>this.poll(),this.configurations.pollingInterval)})}attemptFetch(){return h(this,null,function*(){for(let e=1;e<=this.maxAttempts;e++){let n=yield this.fetchFlagsFn();if(n.type==="success"){this.logDebugMessage(`Successfully polled for flag updates, next poll in ${this.configurations.pollingInterval}ms. `);return}if(this.logErrorMessage("Error when polling for flag updates",n.error),e>=this.maxAttempts){this.logDebugMessage(`Maximum attempts reached for polling for flags. Next poll in ${this.configurations.pollingInterval}ms.`);return}this.logDebugMessage(`Polling for flags attempt #${e} failed. Remaining attempts: ${this.maxAttempts-e}`,n.error);let r=k(1e3,1e4);yield new Promise(o=>setTimeout(o,r))}})}stop(){this.timeoutId&&(clearTimeout(this.timeoutId),this.timeoutId=void 0,this.isRunning=!1,this.eventBus.emit("polling stopped"),this.logDebugMessage("Polling stopped"))}isPolling(){return this.isRunning}logDebugMessage(e,...n){this.configurations.debug&&this.logDebug(`Poller: ${e}`,...n)}logErrorMessage(e,...n){this.logError(`Poller: ${e}`,...n)}};function le(n){return h(this,arguments,function*(a,e={}){let r=yield we(a),o=De(e);return{loadFromCache:()=>q(r,o,e),saveToCache:l=>W(r,o,l),updateCachedEvaluation:l=>Ae(r,o,l),removeCachedEvaluation:l=>Oe(r,o,l)}})}function q(r,o){return h(this,arguments,function*(a,e,n={}){let l=parseInt(yield e.getItem(a+".ts"));if(n!=null&&n.ttl&&!isNaN(l)&&l+n.ttl<Date.now())return yield Te(a,e),[];let u=yield e.getItem(a);if(u)try{return JSON.parse(u)}catch(p){}return[]})}function Te(a,e){return h(this,null,function*(){yield e.removeItem(a),yield e.removeItem(a+".ts")})}function W(a,e,n){return h(this,null,function*(){yield e.setItem(a,JSON.stringify(n)),yield e.setItem(a+".ts",Date.now().toString())})}function Ae(a,e,n){return h(this,null,function*(){let r=yield q(a,e),o=r.find(({flag:l})=>l===n.flag);o?Object.assign(o,n):r.push(n),yield W(a,e,r)})}function Oe(a,e,n){return h(this,null,function*(){let r=yield q(a,e),o=r.findIndex(({flag:l})=>l===n);o>-1&&(r.splice(o,1),yield W(a,e,r))})}function we(a){return h(this,null,function*(){var n,r;let e=a;if(globalThis!=null&&globalThis.TextEncoder&&((r=(n=globalThis==null?void 0:globalThis.crypto)==null?void 0:n.subtle)!=null&&r.digest)){let l=new TextEncoder().encode(a),u=yield crypto.subtle.digest("SHA-256",l);e=Array.from(new Uint8Array(u)).map(E=>E.toString(16).padStart(2,"0")).join("")}else globalThis.btoa&&(e=btoa(a));return"HARNESS_FF_CACHE_"+e})}function De(a){let e;return!a.storage||typeof a.storage!="object"||!("getItem"in a.storage)||!("setItem"in a.storage)||!("removeItem"in a.storage)?globalThis.localStorage?e=globalThis.localStorage:globalThis.sessionStorage?e=globalThis.sessionStorage:e=Pe:e=a.storage,{getItem(r){return h(this,null,function*(){let o=e.getItem(r);return o instanceof Promise?yield o:o})},setItem(r,o){return h(this,null,function*(){let l=e.setItem(r,o);l instanceof Promise&&(yield l)})},removeItem(r){return h(this,null,function*(){let o=e.removeItem(r);o instanceof Promise&&(yield o)})}}}var Pe={getItem:()=>null,setItem:()=>{},removeItem:()=>{}};var ge="1.26.1",ce=`Javascript ${ge} Client`,Ne=500,xe=globalThis.fetch,J=!!globalThis.Proxy,ft=(a,e,n)=>{let r=!1,o,l,u,p,E,g,b=!0,A={},M=U(t=>t),Y=0,z=!1,_=()=>{b=!1},m=()=>{b=!0},C=[],d=Me(),v=ae(n),R=(t,...i)=>{v.debug&&v.logger.debug(`[FF-SDK] ${t}`,...i)},O=(t,...i)=>{v.logger.error(`[FF-SDK] ${t}`,...i)},L=t=>{let{value:i}=t;try{switch(t.kind.toLowerCase()){case"int":case"number":i=Number(i);break;case"boolean":i=i.toString().toLowerCase()==="true";break;case"json":i=JSON.parse(i);break}}catch(c){O(c)}return i},H=t=>{if(b){let i=Date.now();i-t.lastAccessed>Ne&&(t.count++,t.lastAccessed=i)}},de=()=>h(void 0,null,function*(){if(v.cache){R("initializing cache");try{let t=!0,i=yield le(e.identifier+a,typeof v.cache=="boolean"?{}:v.cache),c=yield i.loadFromCache();c!=null&&c.length&&j(()=>{R("loading from cache",c),ee(c,!1),d.emit("cache loaded",c)}),B("flags loaded",f=>h(void 0,null,function*(){yield i.saveToCache(f),t=!1})),B("changed",f=>h(void 0,null,function*(){t||(f.deleted?yield i.removeCachedEvaluation(f.flag):yield i.updateCachedEvaluation(f))}))}catch(t){O("Cache error: ",t),d.emit("cache error",t),d.emit("error",t)}}}),ue=(t,i)=>h(void 0,null,function*(){return(yield(yield xe(`${i.baseUrl}/client/auth`,{method:"POST",headers:{"Content-Type":"application/json","Harness-SDK-Info":ce},body:JSON.stringify({apiKey:t,target:K(T({},e),{identifier:String(e.identifier)})})})).json()).authToken}),G=0,$=()=>{if(C.length){R("Sending metrics...",{metrics:C,evaluations:I});let t={metricsData:C.map(i=>({timestamp:Date.now(),count:i.count,metricsType:"FFMETRICS",attributes:[{key:"featureIdentifier",value:i.featureIdentifier},{key:"featureName",value:i.featureIdentifier},{key:"variationIdentifier",value:i.variationIdentifier},{key:"target",value:e.identifier},{key:"SDK_NAME",value:"JavaScript"},{key:"SDK_LANGUAGE",value:"JavaScript"},{key:"SDK_TYPE",value:"client"},{key:"SDK_VERSION",value:ge}]}))};M(`${v.eventUrl}/metrics/${o}?cluster=${l}`,{method:"POST",headers:T({"Content-Type":"application/json"},A),body:JSON.stringify(t)}).then(()=>{C=[],G=0}).catch(i=>{G++&&(C=[],G=0),R(i),d.emit("metrics error",i)}).finally(()=>{g=window.setTimeout($,v.eventsSyncInterval)})}else g=window.setTimeout($,v.eventsSyncInterval)},I={},fe=t=>{R("Sending event for",t.flag),J?d.emit("changed",new Proxy(t,{get(i,c){var f;if(b&&i.hasOwnProperty(c)&&c==="value"){let S=i.flag,s=t.value,y=C.find(P=>P.featureIdentifier===S&&P.featureValue===s);y?(H(y),y.variationIdentifier=((f=I[S])==null?void 0:f.identifier)||""):C.push({featureIdentifier:S,featureValue:String(s),variationIdentifier:I[S].identifier||"",count:1,lastAccessed:Date.now()}),R("Metrics event: Flag",c,"has been read with value via stream update",s)}return c==="value"?L(t):t[c]}})):d.emit("changed",{deleted:t.deleted,flag:t.flag,value:L(t)})},X=function(){return J?new Proxy({},{get(t,i){var f,S,s;let c=t[i];if(b&&t.hasOwnProperty(i)){let y=t[i],P=C.find(te=>te.featureIdentifier===i&&y===te.featureValue);P?(P.variationIdentifier=((f=I[i])==null?void 0:f.identifier)||"",H(P)):C.push({featureIdentifier:i,featureValue:y,variationIdentifier:((S=I[i])==null?void 0:S.identifier)||"",count:1,lastAccessed:Date.now()}),R("Metrics event: Flag:",i,"has been read with value:",y,"variationIdentifier:",(s=I[i])==null?void 0:s.identifier)}return c}}):{}},w=X();de().then(()=>ue(a,v).then(t=>h(void 0,null,function*(){if(r)return;E=t;let i=Fe(t);A={Authorization:`Bearer ${E}`,"Harness-AccountID":i.accountID,"Harness-EnvironmentID":i.environmentIdentifier,"Harness-SDK-Info":ce};let c=re(e);c.length<262144&&(A["Harness-Target"]=c),R("Authenticated",i),g=window.setTimeout($,v.eventsSyncInterval),o=i.environment,l=i.clusterIdentifier;let f=!!Object.keys(I).length;if((yield N()).type==="success"&&R("Fetch all flags ok",w),!r){if(v.streamEnabled?(R("Streaming mode enabled"),he()):v.pollingEnabled?(R("Polling mode enabled"),me()):R("Streaming and polling mode disabled"),!f){_();let s=T({},w);m(),d.emit("ready",s)}z=!0}})).catch(t=>{O("Authentication error: ",t),d.emit("auth error",t),d.emit("error",t)}));let N=()=>h(void 0,null,function*(){try{let t=yield M(`${v.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations?cluster=${l}`,{headers:A});if(t.ok){let i=yield t.json();return i.forEach(D),d.emit("flags loaded",i),{type:"success",data:i}}else return O("Features fetch operation error: ",t),d.emit("fetch flags error",t),d.emit("error",t),{type:"error",error:t}}catch(t){return O("Features fetch operation error: ",t),d.emit("fetch flags error",t),d.emit("error",t),{type:"error",error:t}}}),Q=t=>h(void 0,null,function*(){try{let i=yield M(`${v.baseUrl}/client/env/${o}/target/${e.identifier}/evaluations/${t}?cluster=${l}`,{headers:A});if(i.ok){let c=yield i.json();D(c)}else O("Feature fetch operation error: ",i),d.emit("fetch flag error",i),d.emit("error",i)}catch(i){O("Feature fetch operation error: ",i),d.emit("fetch flag error",i),d.emit("error",i)}}),D=t=>{_();let i=L(t);i!==w[t.flag]&&(R("Flag variation has changed for ",t.identifier),w[t.flag]=i,I[t.flag]=K(T({},t),{value:i}),fe(t)),m()};p=new F(N,v,d,R,O);let he=()=>{let t=s=>{switch(s.event){case"create":c(s.evaluations)?s.evaluations.forEach(y=>{D(y)}):setTimeout(()=>Q(s.identifier),1e3);break;case"patch":c(s.evaluations)?s.evaluations.forEach(y=>{D(y)}):Q(s.identifier);break;case"delete":delete w[s.identifier],d.emit("changed",{flag:s.identifier,value:void 0,deleted:!0}),R("Evaluation deleted",{message:s,storage:w});break}},i=s=>!(!s||!s.flag||!s.identifier||!s.kind||!s.value),c=s=>!(!s||s.length==0||!s.every(y=>i(y))),f=s=>{s.event==="patch"&&(c(s.evaluations)?s.evaluations.forEach(y=>{D(y)}):N())},S=`${v.baseUrl}/stream?cluster=${l}`;u=new V(d,v,S,a,A,p,R,O,s=>{s.domain==="flag"?t(s):s.domain==="target-segment"&&f(s)}),u.start()},me=()=>{p.start()},B=(t,i)=>d.on(t,i),ve=(t,i)=>{t?d.off(t,i):Z()},pe=(t,i)=>{var s;if(!b||J||i===void 0)return;let c=i,f=t,S=C.find(y=>y.featureIdentifier===f&&y.featureValue===c);S?(H(S),S.variationIdentifier=((s=I[f])==null?void 0:s.identifier)||""):C.push({featureIdentifier:f,featureValue:c,count:1,variationIdentifier:I[f].identifier||"",lastAccessed:Date.now()})},Z=()=>{r=!0,v.streamEnabled&&(R("Closing event stream"),typeof(u==null?void 0:u.close)=="function"&&u.close(),d.all.clear()),v.pollingEnabled&&p.isPolling()&&(R("Closing Poller"),p.stop()),w=X(),I={},clearTimeout(g)},ee=(t,i=!0)=>{t.length&&j(()=>{let c=!!Object.keys(I).length;if(t.forEach(D),!c){_();let f=T({},w);m(),d.emit("ready",f)}},i)};return{on:B,off:ve,close:Z,setEvaluations:ee,registerAPIRequestMiddleware:t=>{M=U(t)},refreshEvaluations:()=>{z&&!r&&Date.now()-Y>=6e4&&(N(),Y=Date.now())},variation:(t,i,c=!1)=>se(t,i,w,pe,c)}};export{x as Event,ft as initialize};

@@ -14,3 +14,2 @@ import { type Options, StreamEvent } from './types';

private eventCallback;
private maxRetries;
private xhr;

@@ -21,5 +20,3 @@ private closed;

private disconnectEventEmitted;
private reconnectAttempts;
private retriesExhausted;
constructor(eventBus: Emitter, configurations: Options, url: string, apiKey: string, standardHeaders: Record<string, string>, fallbackPoller: Poller, logDebug: (...data: any[]) => void, logError: (...data: any[]) => void, eventCallback: (e: StreamEvent) => void, maxRetries: number);
constructor(eventBus: Emitter, configurations: Options, url: string, apiKey: string, standardHeaders: Record<string, string>, fallbackPoller: Poller, logDebug: (...data: any[]) => void, logError: (...data: any[]) => void, eventCallback: (e: StreamEvent) => void);
start(): void;

@@ -26,0 +23,0 @@ close(): void;

@@ -125,8 +125,2 @@ export interface Target {

*/
authRequestReadTimeout?: number;
/**
* The timeout in milliseconds for the authentication request to read the response.
* If the request takes longer than this timeout, it will be aborted and the SDK will fail to initialize, and `ERROR_AUTH` and `ERROR` events will be emitted.
* @default 0 (no timeout)
*/
debug?: boolean;

@@ -143,7 +137,2 @@ /**

logger?: Logger;
/**
* By default, the stream will attempt to reconnect indefinitely if it disconnects. Use this option to limit
* the number of attempts it will make.
*/
maxStreamRetries?: number;
}

@@ -150,0 +139,0 @@ export interface MetricsInfo {

{
"name": "@harnessio/ff-javascript-client-sdk",
"version": "1.28.0",
"version": "1.29.0-rc.0",
"author": "Harness",

@@ -5,0 +5,0 @@ "license": "Apache-2.0",

@@ -216,3 +216,3 @@ # Before you Begin

If you would like to know that the default variation was returned when getting the value, for example, if the provided flag identifier wasn't found then pass true for the third argument withDebug:
If you would like to know that the default variation was returned when getting the value, for example, if the provided flag wasn't found in the cache then pass true for the third argument withDebug:
```typescript

@@ -252,2 +252,19 @@ const result = client.variation('Dark_Theme', false, true);

- If the flag identifier 'Dark_Theme' does not exist, variationValue would be the default value provided, in this case, false
* Note the reasons for the default variation being returned can be
1. SDK Not Initialized Yet
2. Typo in Flag Identifier
3. Wrong project API key being used
#### Listening for the `ERROR_DEFAULT_VARIATION_RETURNED` event
You can also listen for the `ERROR_DEFAULT_VARIATION_RETURNED` event, which is emitted whenever a default variation is returned because the flag has not been found in the cache. This is useful for logging or taking other action when a flag is not found.
Example of listening for the event:
```typescript
client.on(Event.ERROR_DEFAULT_VARIATION_RETURNED, ({ flag, defaultVariation }) => {
console.warn(`Default variation returned for flag: ${flag}, value: ${defaultVariation}`)
})
```
### Cleaning up

@@ -341,2 +358,4 @@

The default value if not specified is `0` which means that no timeout will occur.
**This only applies to the authentiaction request. If you wish to set a read timeout on the remaining requests made by the SDK, you may register [API Middleware](#api-middleware)

@@ -346,3 +365,3 @@

const options = {
authRequestReadTimeout: 30000, // Timeout in milliseconds (default: 30000)
authRequestReadTimeout: 30000, // Timeout in milliseconds (default: 0 - no timeout)
};

@@ -349,0 +368,0 @@

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc