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