@frigade/js 0.2.39 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- var dt=Object.create;var v=Object.defineProperty,gt=Object.defineProperties,ct=Object.getOwnPropertyDescriptor,ht=Object.getOwnPropertyDescriptors,St=Object.getOwnPropertyNames,z=Object.getOwnPropertySymbols,ft=Object.getPrototypeOf,Q=Object.prototype.hasOwnProperty,pt=Object.prototype.propertyIsEnumerable;var q=(i,a,t)=>a in i?v(i,a,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[a]=t,F=(i,a)=>{for(var t in a||(a={}))Q.call(a,t)&&q(i,t,a[t]);if(z)for(var t of z(a))pt.call(a,t)&&q(i,t,a[t]);return i},N=(i,a)=>gt(i,ht(a));var wt=(i,a)=>{for(var t in a)v(i,t,{get:a[t],enumerable:!0})},Z=(i,a,t,e)=>{if(a&&typeof a=="object"||typeof a=="function")for(let s of St(a))!Q.call(i,s)&&s!==t&&v(i,s,{get:()=>a[s],enumerable:!(e=ct(a,s))||e.enumerable});return i};var ut=(i,a,t)=>(t=i!=null?dt(ft(i)):{},Z(a||!i||!i.__esModule?v(t,"default",{value:i,enumerable:!0}):t,i)),Ft=i=>Z(v({},"__esModule",{value:!0}),i);var d=(i,a,t)=>new Promise((e,s)=>{var o=h=>{try{r(t.next(h))}catch(p){s(p)}},g=h=>{try{r(t.throw(h))}catch(p){s(p)}},r=h=>h.done?e(h.value):Promise.resolve(h.value).then(o,g);r((t=t.apply(i,a)).next())});var Ct={};wt(Ct,{Flow:()=>y,FlowStatus:()=>H,FlowType:()=>x,Frigade:()=>k,TriggerType:()=>L});module.exports=Ft(Ct);var L=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(L||{}),H=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(H||{}),x=(S=>(S.ANNOUNCEMENT="ANNOUNCEMENT",S.CHECKLIST="CHECKLIST",S.FORM="FORM",S.TOUR="TOUR",S.SUPPORT="SUPPORT",S.CUSTOM="CUSTOM",S.BANNER="BANNER",S.EMBEDDED_TIP="EMBEDDED_TIP",S.NPS_SURVEY="NPS_SURVEY",S.SURVEY="SURVEY",S.CARD="CARD",S))(x||{});var tt="0.2.20";var rt=ut(require("cross-fetch"),1),nt=require("uuid");var f={};function P(i){var a,t;return`${i.__instanceId}-${i.apiKey}:${(a=i.userId)!=null?a:""}:${(t=i.groupId)!=null?t:""}`}var R=class{constructor(a){this.config={apiKey:"",apiUrl:"https://api.frigade.com/v1/public",userId:st(),__instanceId:Math.random().toString(36).substring(7)};let t=Object.fromEntries(Object.entries(a).filter(([e,s])=>s!=null));this.config=F(F({},this.config),t)}fetch(a,t){return d(this,null,function*(){return this.config.__readOnly?b():it(this.getAPIUrl(a),F(F({keepalive:!0},t!=null?t:{}),et(this.config.apiKey)))})}getAPIUrl(a){let t="/v1/public";return new URL(`${t}${a}`,this.config.apiUrl.replace(t,"")).toString()}getGlobalState(){let a=P(this.config);if(!f[a])throw new Error("Frigade not initialized");return f[a]}};var y=class extends R{constructor(t,e){super(t);this.isVisible=!1;this.isTargeted=!1;this.lastStepUpdate=new Map;this.flowDataRaw=e,this.initFromRawData(e)}reload(){this.initFromRawData(this.flowDataRaw)}initFromRawData(t){var p,O;let e=JSON.parse(t.data),s=(O=(p=e.steps)!=null?p:e.data)!=null?O:[];this.id=t.slug,this.rawData=t,this.configYmlAsJson=e,this.title=this.configYmlAsJson.title,this.subtitle=this.configYmlAsJson.subtitle;let o=this.getUserFlowState();if(!o)return;this.userFlowStateRaw=o,this.isCompleted=o.flowState==G,this.isStarted=o.flowState==D,this.isSkipped=o.flowState==M;let g=this.isCompleted||this.isSkipped,r=t.targetingLogic&&o.shouldTrigger===!1;this.isVisible=!g&&!r,this.flowDataRaw.active===!1&&(this.isVisible=!1),this.isTargeted=t.targetingLogic?r===!1:!0;let h=new Map;s.forEach((S,j)=>{let E=o.stepStates[S.id],A=N(F({},S),{isCompleted:E.actionType==I,isStarted:E.actionType==T,isHidden:E.hidden,isBlocked:E.blocked,lastActionAt:E.lastActionAt?new Date(E.lastActionAt):void 0,order:j});A.start=n=>d(this,null,function*(){let l=this.steps.get(S.id);if(this.getCurrentStep().id===l.id&&l.isStarted)return;l.isStarted=!0;let w=m(this.getGlobalState().userFlowStates[this.id]);w.stepStates[l.id].actionType=T,w.stepStates[l.id].lastActionAt=new Date().toISOString(),w.lastStepId=l.id,this.getGlobalState().userFlowStates[this.id]=w,l.isCompleted||(yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:l.id,data:n!=null?n:{},createdAt:n!=null&&n.createdAt?new Date(n.createdAt):new Date().toISOString(),actionType:T})}),yield this.refreshUserFlowState());let u=this.getUserFlowState();l.isCompleted=u.stepStates[l.id].actionType==I,l.isStarted=u.stepStates[l.id].actionType==T,l.lastActionAt=new Date}),A.complete=n=>d(this,null,function*(){let l=this.steps.get(S.id);if(l.isCompleted)return;let u=this.getNumberOfCompletedSteps()+1==this.steps.size;l.isCompleted=!0,this.isStarted=!0;let c=m(this.getGlobalState().userFlowStates[this.id]);c.stepStates[l.id].actionType=I,c.stepStates[l.id].lastActionAt=new Date().toISOString(),c.flowState=u?G:D;let _=Array.from(this.steps.keys())[j+1];if(_){c.lastStepId=_,c.stepStates[_].actionType=T;let X=new Date;c.stepStates[_].lastActionAt=X.toISOString(),this.steps.get(_).isStarted=!0,this.steps.get(_).lastActionAt=X}u&&this.optimisticallyMarkFlowCompleted(),this.getGlobalState().userFlowStates[this.id]=c,yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:l.id,data:n!=null?n:{},createdAt:n!=null&&n.createdAt?new Date(n.createdAt):new Date().toISOString(),actionType:I})}),yield this.refreshUserFlowState();let Y=this.getUserFlowState();l.isCompleted=Y.stepStates[l.id].actionType==I,l.isStarted=Y.stepStates[l.id].actionType==T,l.lastActionAt=new Date}),A.reset=()=>d(this,null,function*(){let n=this.steps.get(S.id);if(!n.isCompleted)return;n.isCompleted=!1,n.isStarted=!1,n.lastActionAt=void 0;let l=m(this.getGlobalState().userFlowStates[this.id]);l.stepStates[n.id].actionType=W,l.stepStates[n.id].lastActionAt=void 0,l.flowState=D,this.getGlobalState().userFlowStates[this.id]=l,yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:n.id,data:{},createdAt:new Date().toISOString(),actionType:W})}),yield this.refreshUserFlowState();let w=this.getUserFlowState();n.isCompleted=w.stepStates[n.id].actionType==I,n.isStarted=w.stepStates[n.id].actionType==T,n.lastActionAt=void 0}),A.onStateChange=n=>{let l=w=>{if(w.id!==this.id)return;let u=w.steps.get(S.id),c=this.lastStepUpdate.get(n);(u.isCompleted!==(c==null?void 0:c.isCompleted)||u.isStarted!==(c==null?void 0:c.isStarted)||u.isHidden!==(c==null?void 0:c.isHidden)||u.isBlocked!==(c==null?void 0:c.isBlocked))&&(n(u,c!=null?c:m(u)),this.lastStepUpdate.set(n,m(u)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(n,l),this.getGlobalState().onFlowStateChangeHandlers.push(l)},A.removeStateChangeHandler=n=>{let l=this.getGlobalState().onStepStateChangeHandlerWrappers.get(n);l&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(w=>w!==l))},h.set(S.id,A)}),this.steps=h,this.getGlobalState().variables&&this.getGlobalState().variables[this.id]&&Object.keys(this.getGlobalState().variables[this.id]).length>0&&this.applyVariables(this.getGlobalState().variables[this.id])}start(t){return d(this,null,function*(){if(this.isStarted||this.isCompleted)return;this.isStarted=!0;let e=m(this.getGlobalState().userFlowStates[this.id]);e.flowState=D,this.getGlobalState().userFlowStates[this.id]=e,yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t!=null?t:{},createdAt:new Date().toISOString(),actionType:D})}),yield this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)})}complete(t){return d(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t!=null?t:{},createdAt:t!=null&&t.createdAt?new Date(t.createdAt):new Date().toISOString(),actionType:G})}),yield this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw))})}optimisticallyMarkFlowCompleted(){this.isStarted=!0,this.isCompleted=!0;let t=m(this.getGlobalState().userFlowStates[this.id]);t.flowState=G,this.getGlobalState().userFlowStates[this.id]=t,this.isVisible=!1}optimisticallyMarkFlowSkipped(){this.isSkipped=!0;let t=m(this.getGlobalState().userFlowStates[this.id]);t.flowState=M,this.getGlobalState().userFlowStates[this.id]=t,this.isVisible=!1}skip(t){return d(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t!=null?t:{},createdAt:t!=null&&t.createdAt?new Date(t.createdAt):new Date().toISOString(),actionType:M})}),yield this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw))})}forward(t){return d(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()+1);e&&(yield e.start(t))})}back(t){return d(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()-1);e&&(yield e.start(t))})}restart(){return d(this,null,function*(){yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:"unknown",data:{},createdAt:new Date().toISOString(),actionType:at})}),yield this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){let t=Array.from(this.steps.keys()).find(s=>this.steps.get(s).isCompleted===!1&&this.steps.get(s).isHidden===!1);Array.from(this.steps.keys()).forEach(s=>{var o,g;this.steps.get(s).isStarted&&this.steps.get(s).lastActionAt&&this.steps.get(s).lastActionAt>((g=(o=this.steps.get(t))==null?void 0:o.lastActionAt)!=null?g:new Date(0))&&(t=s)});let e=t!=null?t:Array.from(this.steps.keys())[0];return this.steps.get(e)}getCurrentStepIndex(){let t=this.getCurrentStep();return Array.from(this.steps.keys()).indexOf(t.id)}getNumberOfCompletedSteps(){return Array.from(this.steps.values()).filter(t=>t.isCompleted).length}getNumberOfAvailableSteps(){return Array.from(this.steps.values()).filter(t=>!t.isHidden).length}onStateChange(t){let e=(s,o)=>{(s.id===this.id&&(s.isCompleted!==o.isCompleted||s.isStarted!==o.isStarted||s.isSkipped!==o.isSkipped||s.isVisible!==o.isVisible)||JSON.stringify(s.steps)!==JSON.stringify(o.steps))&&t(s,o)};this.getGlobalState().onFlowStateChangeHandlerWrappers.set(t,e),this.getGlobalState().onFlowStateChangeHandlers.push(e)}removeStateChangeHandler(t){let e=this.getGlobalState().onFlowStateChangeHandlerWrappers.get(t);e&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(s=>s!==e))}applyVariables(t){var s,o;let e=g=>{let r=g.match(/\${(.*?)}/g);return r&&r.forEach(h=>{let p=h.replace("${","").replace("}","");t[p]&&(g=g.replace(h,t[p]))}),g};this.title=e((s=this.title)!=null?s:""),this.subtitle=e((o=this.subtitle)!=null?o:""),this.steps.forEach(g=>{Object.keys(g).forEach(r=>{typeof g[r]=="string"&&(g[r]=e(g[r]))})}),this.getGlobalState().variables={},this.getGlobalState().variables[this.id]=t}getUserFlowState(){return this.getGlobalState().userFlowStates[this.id]}refreshUserFlowState(){return d(this,null,function*(){yield this.getGlobalState().refreshUserFlowStates()})}};var W="NOT_STARTED_STEP",G="COMPLETED_FLOW",M="SKIPPED_FLOW",D="STARTED_FLOW",at="NOT_STARTED_FLOW",I="COMPLETED_STEP",T="STARTED_STEP",bt="frigade-last-call-at-",mt="frigade-last-call-data-",ot="frigade-guest-key",V="guest_",yt="get-cache-";var Tt=1e3,B="fr-js-";function U(i){let a=new y(i.config,i.rawData);return a.isCompleted=i.isCompleted,a.isStarted=i.isStarted,a.isSkipped=i.isSkipped,a.isVisible=i.isVisible,a.steps=i.steps,a}function m(i){return JSON.parse(JSON.stringify(i))}function et(i){return{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Frigade-SDK-Version":tt,"X-Frigade-SDK-Platform":"Javascript"}}}function J(i){return C()?window.localStorage.getItem(`${B}${i}`):null}function K(i,a){C()&&window.localStorage.setItem(`${B}${i}`,a)}function $(){Object.keys(f).forEach(i=>{i.startsWith(yt)&&delete f[i]})}function lt(){C()&&Object.keys(window.localStorage).forEach(i=>{i.startsWith(B)&&window.localStorage.removeItem(i)})}function it(i,a){return d(this,null,function*(){let t=bt+i,e=mt+i;if(C()&&a&&a.body&&a.method==="POST"){let o=J(t),g=J(e);if(o&&g&&g==a.body){let r=new Date(o);if(new Date().getTime()-r.getTime()<Tt)return b()}K(t,new Date().toISOString()),K(e,a.body),$()}let s;try{s=(0,rt.default)(i,a),s=yield s}catch(o){return b(o)}if(!s)return b("Received an empty response");if(s.status>=400)return b(s.statusText);try{if(s.status===204||s.status===201)return b();let o=yield s.json();return o.error?b(o.error):o}catch(o){return b(o)}})}function b(i){return i&&console.log("Call to Frigade failed",i),{json:()=>({})}}function st(){if(C()){let i=J(ot);return i||(i=`${V}${(0,nt.v4)()}`,K(ot,i)),i}}function C(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}var k=class extends R{constructor(t,e){super(F({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.visibilityChangeHandler=()=>d(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshFlows(),yield this.refreshUserFlowStates(),this.flows.forEach(t=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(e=>{let s=this.getGlobalState().previousFlows.get(t.id);e(t,s),this.getGlobalState().previousFlows.set(t.id,U(t))})}))});this.init(this.config),C()&&document.addEventListener("visibilitychange",this.visibilityChangeHandler)}destroy(){if(C()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=P(this.config);f[t]&&(f[t].onFlowStateChangeHandlers=[])}}init(t){return d(this,null,function*(){return this.config=F(F({},this.config),t),this.initPromise=(()=>d(this,null,function*(){var e;this.config.userId&&!((e=this.config.userId)!=null&&e.startsWith(V))&&(yield this.fetch("/users",{method:"POST",body:JSON.stringify({foreignId:this.config.userId})})),yield this.refreshUserFlowStates(),yield this.refreshFlows()}))(),this.initPromise})}identify(t,e){return d(this,null,function*(){this.config=N(F({},this.config),{userId:t}),yield this.initIfNeeded(),yield this.fetch("/users",{method:"POST",body:JSON.stringify({foreignId:this.config.userId,properties:e})}),yield this.resync()})}group(t,e){return d(this,null,function*(){yield this.initIfNeeded(),this.config.groupId=t,yield this.fetch("/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,properties:e})}),yield this.resync()})}track(t,e){return d(this,null,function*(){if(yield this.initIfNeeded(),!t){console.error("Event name is required to track an event");return}this.config.userId&&this.config.groupId?yield this.fetch("/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,events:[{event:t,properties:e}]})}):this.config.userId&&(yield this.fetch("/users",{method:"POST",body:JSON.stringify({foreignId:this.config.userId,events:[{event:t,properties:e}]})})),yield this.resync()})}isReady(){return!!(this.config.__instanceId&&this.config.apiKey&&this.initPromise)}getFlow(t){return d(this,null,function*(){return yield this.initIfNeeded(),this.flows.find(e=>e.id==t)})}getFlows(){return d(this,null,function*(){return yield this.initIfNeeded(),this.flows})}reload(){return d(this,null,function*(){lt(),$(),yield this.refreshUserFlowStates(),yield this.refreshFlows(),this.initPromise=null,yield this.init(this.config),this.flows.forEach(t=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(e=>{let s=this.getGlobalState().previousFlows.get(t.id);e(t,s),this.getGlobalState().previousFlows.set(t.id,U(t))})})})}resync(){return d(this,null,function*(){this.initPromise=null,yield this.init(this.config),this.flows.forEach(t=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(e=>{let s=this.getGlobalState().previousFlows.get(t.id);e(t,s),this.getGlobalState().previousFlows.set(t.id,U(t))})})})}onStateChange(t){return d(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers.push(t)})}hasFailedToLoad(){return this.hasFailed}removeStateChangeHandler(t){return d(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(e=>e!==t)})}initIfNeeded(){return d(this,null,function*(){return this.initPromise!==null?this.initPromise:this.init(this.config)})}refreshUserFlowStates(){return d(this,null,function*(){let t=P(this.config);if(!f[t]){let e=this,s={set:function(o,g,r){return o[g]&&o[g].flowState&&(JSON.stringify(o[g].flowState)!==JSON.stringify(r==null?void 0:r.flowState)||JSON.stringify(o[g].stepStates)!==JSON.stringify(r==null?void 0:r.stepStates)||JSON.stringify(o[g].shouldTrigger)!==JSON.stringify(r==null?void 0:r.shouldTrigger))&&e.triggerEventHandlers(o[g]),o[g]=r,!0}};if(f[t]={refreshUserFlowStates:()=>d(this,null,function*(){}),userFlowStates:new Proxy({},s),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{}},this.config.__readOnly&&this.config.__flowConfigOverrides){this.mockUserFlowStates(t);return}f[t].refreshUserFlowStates=()=>d(this,null,function*(){if(this.config.__readOnly)return;let o=yield this.fetch(`/userFlowStates?foreignUserId=${encodeURIComponent(this.config.userId)}${this.config.groupId?`&foreignUserGroupId=${encodeURIComponent(this.config.groupId)}`:""}`);o&&o.data?(o.data.forEach(r=>{let h=!1,p=f[t].userFlowStates[r.flowId];p&&p.shouldTrigger==!1&&r.shouldTrigger==!0&&(h=!0),f[t].userFlowStates[r.flowId]=r,h&&this.flows.forEach(O=>{O.id==r.flowId&&(O.reload(),this.triggerEventHandlers(f[t].userFlowStates[O.id]))})}),this.hasFailed=!1):this.hasFailed=!0})}yield f[t].refreshUserFlowStates()})}refreshFlows(){return d(this,null,function*(){if(this.flows=[],this.config.__flowConfigOverrides){this.mockFlowConfigs();return}let t=yield this.fetch("/flows");t&&t.data?t.data.forEach(s=>{this.flows.push(new y(this.config,s)),this.getGlobalState().previousFlows.set(s.slug,U(this.flows[this.flows.length-1]))}):this.hasFailed=!0})}mockFlowConfigs(){Object.keys(this.config.__flowConfigOverrides).forEach(t=>{this.flows.push(new y(this.config,{id:-1,name:"",description:"",data:this.config.__flowConfigOverrides[t],createdAt:new Date().toISOString(),modifiedAt:new Date().toISOString(),slug:t,targetingLogic:"",type:"CHECKLIST",triggerType:"MANUAL",status:"ACTIVE",version:1,active:!0}))})}mockUserFlowStates(t){Object.keys(this.config.__flowConfigOverrides).forEach(e=>{var o,g;let s=JSON.parse(this.config.__flowConfigOverrides[e]);f[t].userFlowStates[e]={flowId:e,flowState:"NOT_STARTED_FLOW",lastStepId:null,userId:this.config.userId,foreignUserId:this.config.userId,stepStates:(g=(o=s==null?void 0:s.steps)==null?void 0:o.reduce((r,h)=>(r[h.id]={stepId:h.id,flowSlug:e,actionType:"NOT_STARTED_STEP",createdAt:new Date().toISOString(),blocked:!1,hidden:!1},r),{}))!=null?g:{},shouldTrigger:!1}})}triggerEventHandlers(t){return d(this,null,function*(){t&&this.flows.forEach(e=>{e.id==t.flowId&&this.getGlobalState().onFlowStateChangeHandlers.forEach(s=>{let o=this.getGlobalState().previousFlows.get(e.id);s(e,o),this.getGlobalState().previousFlows.set(e.id,U(e))})})})}};0&&(module.exports={Flow,FlowStatus,FlowType,Frigade,TriggerType});
2
+ var at=Object.create;var I=Object.defineProperty,rt=Object.defineProperties,ot=Object.getOwnPropertyDescriptor,nt=Object.getOwnPropertyDescriptors,lt=Object.getOwnPropertyNames,U=Object.getOwnPropertySymbols,dt=Object.getPrototypeOf,L=Object.prototype.hasOwnProperty,gt=Object.prototype.propertyIsEnumerable;var k=(a,s,t)=>s in a?I(a,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[s]=t,p=(a,s)=>{for(var t in s||(s={}))L.call(s,t)&&k(a,t,s[t]);if(U)for(var t of U(s))gt.call(s,t)&&k(a,t,s[t]);return a},y=(a,s)=>rt(a,nt(s));var ct=(a,s)=>{for(var t in s)I(a,t,{get:s[t],enumerable:!0})},H=(a,s,t,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of lt(s))!L.call(a,i)&&i!==t&&I(a,i,{get:()=>s[i],enumerable:!(e=ot(s,i))||e.enumerable});return a};var ht=(a,s,t)=>(t=a!=null?at(dt(a)):{},H(s||!a||!a.__esModule?I(t,"default",{value:a,enumerable:!0}):t,a)),ft=a=>H(I({},"__esModule",{value:!0}),a);var g=(a,s,t)=>new Promise((e,i)=>{var r=n=>{try{o(t.next(n))}catch(c){i(c)}},l=n=>{try{o(t.throw(n))}catch(c){i(c)}},o=n=>n.done?e(n.value):Promise.resolve(n.value).then(r,l);o((t=t.apply(a,s)).next())});var wt={};ct(wt,{Flow:()=>u,FlowStatus:()=>N,FlowType:()=>x,Frigade:()=>E,TriggerType:()=>$});module.exports=ft(wt);var M="0.2.20";var Z=ht(require("cross-fetch"),1),tt=require("uuid");var h={};function C(a){var s,t;return`${a.__instanceId}-${a.apiKey}:${(s=a.userId)!=null?s:""}:${(t=a.groupId)!=null?t:""}`}var F=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com/v1/public",userId:K(),__instanceId:Math.random().toString(36).substring(7)};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));this.config=p(p({},this.config),t)}fetch(s,t){return g(this,null,function*(){return this.config.__readOnly?b():V(this.getAPIUrl(s),p(p({keepalive:!0},t!=null?t:{}),W(this.config.apiKey)))})}getAPIUrl(s){let t="/v1/public";return new URL(`${t}${s}`,this.config.apiUrl.replace(t,"")).toString()}getGlobalState(){let s=C(this.config);if(!h[s])throw new Error("Frigade not initialized");return h[s]}};var u=class extends F{constructor({config:t,id:e}){super(t);this._isVisible=!1;this.lastStepUpdate=new Map;this.id=e,this.init()}get isVisible(){return this._isVisible===!1?!1:this.getGlobalState().rulesGraph.isFlowVisible(this.id)}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,r;let e=t!=null?t:this.getStatefulFlow();this.rawData=e,this.title=(i=e==null?void 0:e.data)==null?void 0:i.title,this.subtitle=(r=e==null?void 0:e.data)==null?void 0:r.subtitle,this.isCompleted=e.$state.completed,this.isStarted=e.$state.started,this.isSkipped=e.$state.skipped,this._isVisible=e.$state.visible,e.data.steps.forEach((l,o)=>{var f;let n=this.initStepFromStatefulStep(l,o),c=(f=this.steps)==null?void 0:f.get(l.id);c&&(c.$state=n.$state)})}initStepFromStatefulStep(t,e){return y(p({},t),{flow:this,$state:y(p({},t.$state),{lastActionAt:t.$state.lastActionAt?new Date(t.$state.lastActionAt):void 0}),order:e})}init(){let t=this.getStatefulFlow();this.resyncState();let e=new Map;t.data.steps.forEach((i,r)=>{let l=this.initStepFromStatefulStep(i,r);l.start=o=>g(this,null,function*(){let n=this.steps.get(i.id);if(this.getCurrentStep().id===n.id&&n.$state.started)return;let c=w(this.getGlobalState().flowStates[this.id]);c.data.steps[n.order].$state.started=!0,c.data.steps[n.order].$state.lastActionAt=new Date,c.$state.lastActionAt=new Date,c.$state.currentStepId=n.id,c.$state.currentStepIndex=n.order,this.getGlobalState().flowStates[this.id]=c,this.resyncState(),n.$state.completed||(yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:n.id,data:o!=null?o:{},createdAt:o!=null&&o.createdAt?new Date(o.createdAt):new Date().toISOString(),actionType:q})}),yield this.refreshStateFromAPI())}),l.complete=o=>g(this,null,function*(){let n=this.steps.get(i.id);if(n.$state.completed)return;let f=this.getNumberOfCompletedSteps()+1==this.steps.size,d=w(this.getGlobalState().flowStates[this.id]);d.$state.started=!0,d.data.steps[n.order].$state.completed=!0,d.data.steps[n.order].$state.started=!0,d.data.steps[n.order].$state.lastActionAt=new Date,f&&(d.$state.completed=!0);let S=Array.from(this.steps.keys())[r+1];S&&(d.$state.currentStepId=S,d.data.steps[r+1].$state.started=!0,d.data.steps[r+1].$state.lastActionAt=new Date),this.getGlobalState().flowStates[this.id]=d,this.resyncState(),f&&this.optimisticallyMarkFlowCompleted(),yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:n.id,data:o!=null?o:{},createdAt:o!=null&&o.createdAt?new Date(o.createdAt):new Date().toISOString(),actionType:z})}),yield this.refreshStateFromAPI()}),l.reset=()=>g(this,null,function*(){let o=this.steps.get(i.id);if(!o.$state.completed)return;let n=w(this.getGlobalState().flowStates[this.id]);n.data.steps[o.order].$state.started=!1,n.data.steps[o.order].$state.completed=!1,n.data.steps[o.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=n,this.resyncState(),yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:o.id,data:{},createdAt:new Date().toISOString(),actionType:J})}),yield this.refreshStateFromAPI()}),l.onStateChange=o=>{let n=c=>{if(c.id!==this.id)return;let f=c.steps.get(i.id),d=this.lastStepUpdate.get(o);(f.$state.completed!==(d==null?void 0:d.$state.completed)||f.$state.started!==(d==null?void 0:d.$state.started)||f.$state.visible!==(d==null?void 0:d.$state.visible)||f.$state.blocked!==(d==null?void 0:d.$state.blocked))&&(o(f,d!=null?d:w(f)),this.lastStepUpdate.set(o,w(f)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(o,n),this.getGlobalState().onFlowStateChangeHandlers.push(n)},l.removeStateChangeHandler=o=>{let n=this.getGlobalState().onStepStateChangeHandlerWrappers.get(o);n&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(c=>c!==n))},e.set(i.id,l)}),this.steps=e,this.getGlobalState().variables&&this.getGlobalState().variables[this.id]&&Object.keys(this.getGlobalState().variables[this.id]).length>0&&this.applyVariables(this.getGlobalState().variables[this.id])}start(t){return g(this,null,function*(){if(this.isStarted||this.isCompleted)return;let e=w(this.getGlobalState().flowStates[this.id]);e.$state.started=!0,this.getGlobalState().flowStates[this.id]=e,this.resyncState(),yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t!=null?t:{},createdAt:new Date().toISOString(),actionType:X})}),yield this.refreshStateFromAPI()})}complete(t){return g(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t!=null?t:{},createdAt:t!=null&&t.createdAt?new Date(t.createdAt):new Date().toISOString(),actionType:B})}),yield this.refreshStateFromAPI())})}skip(t){return g(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:this.getCurrentStep().id,data:t!=null?t:{},createdAt:t!=null&&t.createdAt?new Date(t.createdAt):new Date().toISOString(),actionType:j})}),yield this.refreshStateFromAPI())})}forward(t){return g(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()+1);e&&(yield e.start(t))})}back(t){return g(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()-1);e&&(yield e.start(t))})}restart(){return g(this,null,function*(){yield this.fetch("/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,flowSlug:this.id,stepId:"unknown",data:{},createdAt:new Date().toISOString(),actionType:Y})}),yield this.refreshStateFromAPI()})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){let t=Array.from(this.steps.keys()).find(i=>this.steps.get(i).$state.completed===!1&&this.steps.get(i).$state.visible!==!1);Array.from(this.steps.keys()).forEach(i=>{var r,l;this.steps.get(i).$state.started&&this.steps.get(i).$state.lastActionAt&&this.steps.get(i).$state.lastActionAt>((l=(r=this.steps.get(t))==null?void 0:r.$state.lastActionAt)!=null?l:new Date(0))&&(t=i)});let e=t!=null?t:Array.from(this.steps.keys())[0];return this.steps.get(e)}getCurrentStepIndex(){let t=this.getCurrentStep();return Array.from(this.steps.keys()).indexOf(t.id)}getNumberOfCompletedSteps(){return Array.from(this.steps.values()).filter(t=>t.$state.completed).length}getNumberOfAvailableSteps(){return Array.from(this.steps.values()).filter(t=>t.$state.visible).length}onStateChange(t){let e=(i,r)=>{(i.id===this.id&&(i.isCompleted!==(r==null?void 0:r.isCompleted)||i.isStarted!==(r==null?void 0:r.isStarted)||i.isSkipped!==(r==null?void 0:r.isSkipped)||i.isVisible!==(r==null?void 0:r.isVisible))||JSON.stringify(i.steps)!==JSON.stringify(r==null?void 0:r.steps))&&t(i,r)};this.getGlobalState().onFlowStateChangeHandlerWrappers.set(t,e),this.getGlobalState().onFlowStateChangeHandlers.push(e)}removeStateChangeHandler(t){let e=this.getGlobalState().onFlowStateChangeHandlerWrappers.get(t);e&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(i=>i!==e))}applyVariables(t){var i,r;let e=l=>{let o=l.match(/\${(.*?)}/g);return o&&o.forEach(n=>{let c=n.replace("${","").replace("}","");t[c]&&(l=l.replace(n,t[c]))}),l};this.title=e((i=this.title)!=null?i:""),this.subtitle=e((r=this.subtitle)!=null?r:""),this.steps.forEach(l=>{Object.keys(l).forEach(o=>{typeof l[o]=="string"&&(l[o]=e(l[o]))})}),this.getGlobalState().variables={},this.getGlobalState().variables[this.id]=t}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}refreshStateFromAPI(){return g(this,null,function*(){yield this.getGlobalState().refreshStateFromAPI(),this.resyncState()})}optimisticallyMarkFlowCompleted(){let t=w(this.getGlobalState().flowStates[this.id]);t.$state.completed=!0,t.$state.started=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowSkipped(){let t=w(this.getGlobalState().flowStates[this.id]);t.$state.skipped=!0,t.$state.visible=!1,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}register(t){this.getGlobalState().rulesGraph.register(this.id,t)}unregister(){this.getGlobalState().rulesGraph.unregister(this.id)}};var J="NOT_STARTED_STEP",B="COMPLETED_FLOW",j="SKIPPED_FLOW",X="STARTED_FLOW",Y="NOT_STARTED_FLOW",z="COMPLETED_STEP",q="STARTED_STEP",pt="frigade-last-call-at-",St="frigade-last-call-data-",Q="frigade-guest-key",_="guest_",ut="get-cache-";var bt=1e3,P="fr-js-";function A(a){return new u({config:a.config,id:a.id})}function w(a){return JSON.parse(JSON.stringify(a))}function W(a){return{headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json","X-Frigade-SDK-Version":M,"X-Frigade-SDK-Platform":"Javascript"}}}function R(a){return m()?window.localStorage.getItem(`${P}${a}`):null}function v(a,s){m()&&window.localStorage.setItem(`${P}${a}`,s)}function D(){Object.keys(h).forEach(a=>{a.startsWith(ut)&&delete h[a]})}function et(){m()&&Object.keys(window.localStorage).forEach(a=>{a.startsWith(P)&&window.localStorage.removeItem(a)})}function V(a,s){return g(this,null,function*(){let t=pt+a,e=St+a;if(m()&&s&&s.body&&s.method==="POST"){let r=R(t),l=R(e);if(r&&l&&l==s.body){let o=new Date(r);if(new Date().getTime()-o.getTime()<bt)return b()}v(t,new Date().toISOString()),v(e,s.body),D()}let i;try{i=(0,Z.default)(a,s),i=yield i}catch(r){return b(r)}if(!i)return b("Received an empty response");if(i.status>=400)return b(i.statusText);try{if(i.status===204||i.status===201)return b();let r=yield i.json();return r.error?b(r.error):r}catch(r){return b(r)}})}function b(a){return a&&console.log("Call to Frigade failed",a),{json:()=>({})}}function K(){if(m()){let a=R(Q);return a||(a=`${_}${(0,tt.v4)()}`,v(Q,a)),a}}function m(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}var T=class{constructor(s,t){this.graph=new Map;this.registry=new Map;this._rawGraphData=s,t&&(this.registry=t),this.ingestGraphData(s)}get rawGraphData(){return this._rawGraphData}ingestGraphData(s){this.graph=new Map(Object.entries(s)),this.fireCallbacks()}fireCallbacks(){for(let[s,t]of this.registry)typeof t=="function"&&t(this.isFlowVisible(s))}isFlowVisible(s){let t=this.graph.get(s);return t?t.visible===!1?!1:t.edges.length===0?!0:this.findRegisteredDescendant(s)==null:!0}register(s,t){this.registry.set(s,t),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.fireCallbacks()}getRegistry(){return this.registry}findRegisteredDescendant(s,t=s,e){let i=this.graph.get(s);if(i==null)return;if(this.registry.has(s)&&t!==s)return i;let r;if(i.edges.length>0)for(let l of i.edges){if(e!=null&&l.ruleId!==e)continue;let o=this.findRegisteredDescendant(l.head,t,e!=null?e:l.ruleId);if(o!=null&&o.visible){r=o;break}}return r}};var E=class extends F{constructor(t,e){super(p({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.visibilityChangeHandler=()=>g(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshStateFromAPI())});this.init(this.config),m()&&document.addEventListener("visibilitychange",this.visibilityChangeHandler)}destroy(){if(m()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=C(this.config);h[t]&&(h[t].onFlowStateChangeHandlers=[])}}init(t){return g(this,null,function*(){return this.config=p(p({},this.config),t),this.initPromise=(()=>g(this,null,function*(){var e;this.config.userId&&!((e=this.config.userId)!=null&&e.startsWith(_))&&(yield this.fetch("/users",{method:"POST",body:JSON.stringify({foreignId:this.config.userId})})),yield this.refreshStateFromAPI()}))(),this.initPromise})}identify(t,e){return g(this,null,function*(){this.config=y(p({},this.config),{userId:t}),yield this.initIfNeeded(),yield this.fetch("/users",{method:"POST",body:JSON.stringify({foreignId:this.config.userId,properties:e})}),yield this.resync()})}group(t,e){return g(this,null,function*(){yield this.initIfNeeded(),this.config.groupId=t,yield this.fetch("/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,properties:e})}),yield this.resync()})}track(t,e){return g(this,null,function*(){if(yield this.initIfNeeded(),!t){console.error("Event name is required to track an event");return}this.config.userId&&this.config.groupId?yield this.fetch("/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.config.userId,foreignUserGroupId:this.config.groupId,events:[{event:t,properties:e}]})}):this.config.userId&&(yield this.fetch("/users",{method:"POST",body:JSON.stringify({foreignId:this.config.userId,events:[{event:t,properties:e}]})})),yield this.resync()})}isReady(){return!!(this.config.__instanceId&&this.config.apiKey&&this.initPromise)}getFlow(t){return g(this,null,function*(){return yield this.initIfNeeded(),this.flows.find(e=>e.id==t)})}getFlows(){return g(this,null,function*(){return yield this.initIfNeeded(),this.flows})}reload(){return g(this,null,function*(){et(),D(),yield this.refreshStateFromAPI(),this.initPromise=null,yield this.init(this.config),this.flows.forEach(t=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(e=>{let i=this.getGlobalState().previousFlows.get(t.id);e(t,i),this.getGlobalState().previousFlows.set(t.id,A(t))})})})}resync(){return g(this,null,function*(){this.initPromise=null,yield this.init(this.config),this.flows.forEach(t=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(e=>{let i=this.getGlobalState().previousFlows.get(t.id);e(t,i),this.getGlobalState().previousFlows.set(t.id,A(t))})})})}onStateChange(t){return g(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers.push(t)})}hasFailedToLoad(){return this.hasFailed}removeStateChangeHandler(t){return g(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(e=>e!==t)})}initIfNeeded(){return g(this,null,function*(){return this.initPromise!==null?this.initPromise:this.init(this.config)})}refreshStateFromAPI(){return g(this,null,function*(){let t=C(this.config);if(!h[t]){let e=this,i={set:function(r,l,o){if(r[l]){let n=r[l],c=o;JSON.stringify(n)!==JSON.stringify(c)&&e.triggerEventHandlers(c,n)}return r[l]=o,!0}};if(h[t]={refreshStateFromAPI:()=>g(this,null,function*(){}),rulesGraph:new T({}),flowStates:new Proxy({},i),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{}},this.config.__readOnly&&this.config.__flowConfigOverrides){this.mockFlowStates(t);return}h[t].refreshStateFromAPI=()=>g(this,null,function*(){var o,n,c,f,d;if(this.config.__readOnly)return;let r=yield this.fetch(`/flowStates?userId=${encodeURIComponent(this.config.userId)}${this.config.groupId?`&groupId=${encodeURIComponent(this.config.groupId)}`:""}`),l=JSON.stringify(h[t].rulesGraph.rawGraphData)!==JSON.stringify((o=r.ruleGraph)==null?void 0:o.graph);h[t].rulesGraph=new T((c=(n=r.ruleGraph)==null?void 0:n.graph)!=null?c:{},(d=(f=h[t])==null?void 0:f.rulesGraph)==null?void 0:d.getRegistry()),l&&this.flows.forEach(S=>{var G;if((G=r.ruleGraph)!=null&&G.graph[S.id]){let it=r.eligibleFlows.find(O=>O.flowSlug===S.id),st=this.getGlobalState().previousFlows.get(S.id);S.resyncState(it),this.getGlobalState().onFlowStateChangeHandlers.forEach(O=>{O(S,st),this.getGlobalState().previousFlows.set(S.id,A(S))})}}),r&&r.eligibleFlows?(r.eligibleFlows.forEach(S=>{h[t].flowStates[S.flowSlug]=S,this.flows.find(G=>G.id==S.flowSlug)||this.flows.push(new u({config:this.config,id:S.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield h[t].refreshStateFromAPI()})}mockFlowConfigs(){Object.keys(this.config.__flowConfigOverrides).forEach(t=>{this.flows.push(new u({config:this.config,id:t}))})}mockFlowStates(t){Object.keys(this.config.__flowConfigOverrides).forEach(e=>{var r,l,o;let i=JSON.parse(this.config.__flowConfigOverrides[e]);h[t].flowStates[e]={flowSlug:e,flowName:(r=i==null?void 0:i.name)!=null?r:e,flowType:(l=i==null?void 0:i.type)!=null?l:"CHECKLIST",data:y(p({},i),{steps:((o=i==null?void 0:i.steps)!=null?o:[]).map(n=>p({id:n.id,$state:{completed:!1,started:!1,visible:!0,blocked:!1}},n))}),$state:{currentStepId:null,currentStepIndex:-1,completed:!1,started:!1,skipped:!1,visible:!0}},this.flows.push(new u({config:this.config,id:e}))})}triggerEventHandlers(t,e){return g(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(r=>{let l=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),r(i,l),this.getGlobalState().previousFlows.set(i.id,A(i))})})})}};var $=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))($||{}),N=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(N||{}),x=(d=>(d.ANNOUNCEMENT="ANNOUNCEMENT",d.CHECKLIST="CHECKLIST",d.FORM="FORM",d.TOUR="TOUR",d.SUPPORT="SUPPORT",d.CUSTOM="CUSTOM",d.BANNER="BANNER",d.EMBEDDED_TIP="EMBEDDED_TIP",d.NPS_SURVEY="NPS_SURVEY",d.SURVEY="SURVEY",d.CARD="CARD",d))(x||{});0&&(module.exports={Flow,FlowStatus,FlowType,Frigade,TriggerType});
3
3
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/core/types.ts","../src/core/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/shared/fetchable.ts","../src/core/flow.ts","../src/core/frigade.ts"],"sourcesContent":["export { Frigade } from './core/frigade'\nexport { Flow } from './core/flow'\nexport { FlowStatus, FlowStep, FrigadeConfig, FlowType, TriggerType } from './core/types'\n","export interface FlowDataRaw {\n id: number\n name: string\n description: string\n data: string\n createdAt: string\n modifiedAt: string\n slug: string\n targetingLogic: string\n type: FlowType\n triggerType: TriggerType\n status: FlowStatus\n version: number\n active: boolean\n}\n\nexport enum TriggerType {\n MANUAL = 'MANUAL',\n AUTOMATIC = 'AUTOMATIC',\n}\n\nexport enum FlowStatus {\n DRAFT = 'DRAFT',\n ACTIVE = 'ACTIVE',\n ARCHIVED = 'ARCHIVED',\n}\n\nexport interface FlowStep {\n /**\n * Unique identifier for the step.\n */\n id: string\n\n /**\n * Order of the step in the Flow.\n */\n order: number\n\n /**\n * Name of the step when shown in a list view.\n */\n stepName?: string\n\n /**\n * Title of the step.\n */\n title?: string\n\n /**\n * Subtitle of the step.\n */\n subtitle?: string\n\n /**\n * Primary button title. If omitted, the primary button will not be shown.\n */\n primaryButtonTitle?: string\n\n /**\n * Primary button URI.\n */\n primaryButtonUri?: string\n\n /**\n * Primary button URI target (either _blank or _self).\n */\n primaryButtonUriTarget?: string\n\n /**\n * Secondary button title. If omitted, the secondary button will not be shown.\n */\n secondaryButtonTitle?: string\n\n /**\n * Secondary button URI.\n */\n secondaryButtonUri?: string\n\n /**\n * Secondary button URI target (either _blank or _self)\n */\n secondaryButtonUriTarget?: string\n\n /**\n * Text on button if a back button is present.\n */\n backButtonTitle?: string\n\n /**\n * If true, the step will be marked as completed when the secondary button is clicked.\n */\n skippable?: boolean\n\n /**\n * Video url to be shown for components supporting video.\n */\n videoUri?: string\n\n /**\n * Image url to be shown for components supporting image.\n */\n imageUri?: string | null\n\n /**\n * Automatically mark the step as completed when the primary button is clicked. Default is false.\n */\n autoMarkCompleted?: boolean\n\n /**\n * Whether the step has been completed (equivalent to step status === COMPLETED_STEP).\n */\n isCompleted: boolean\n\n /**\n * Whether the step has been completed (equivalent to step status === COMPLETED_STEP).\n */\n isStarted: boolean\n\n /**\n * Whether the step is blocked (can't be accessed yet) based on `startCriteria`.\n */\n isBlocked: boolean\n\n /**\n * Whether the step is hidden (not shown in the list view) based on `visibilityCriteria`.\n */\n isHidden: boolean\n\n /**\n * Last state update.\n */\n lastActionAt?: Date\n\n /**\n * @ignore\n */\n props?: any\n /**\n * Criteria that needs to be met for the step to complete.\n * Completion criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be completed.\n */\n completionCriteria?: string\n\n /**\n * Criteria that needs to be met for the step to start.\n * Start criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be started.\n */\n startCriteria?: string\n\n /**\n * Criteria that needs to be met for the step to be visible.\n * Visibility criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be visible.\n */\n visibilityCriteria?: string\n\n /**\n * Progress if the step is tied to another Frigade Flow through completionCriteria.\n */\n progress?: number\n\n /**\n * Whether the step is dismissible (for instance, tooltips or other non-essential steps).\n */\n dismissible?: boolean\n\n /**\n * Any other additional props defined in the YAML config.\n */\n [x: string | number | symbol]: unknown\n\n /**\n * Marks the step started.\n */\n start: (properties?: Record<string | number, any>) => Promise<void>\n\n /**\n * Marks the step completed.\n */\n complete: (properties?: Record<string | number, any>) => Promise<void>\n\n /**\n * Resets the step (useful for undoing a finished step).\n */\n reset: () => Promise<void>\n\n /**\n * Event handler for this given step's state changes.\n */\n onStateChange: (callback: (step: FlowStep, previousStep?: FlowStep) => void) => void\n\n /**\n * Removes the given callback from the list of event handlers.\n */\n removeStateChangeHandler: (callback: (step: FlowStep, previousStep?: FlowStep) => void) => void\n}\n\nexport interface FrigadeConfig {\n /**\n * Frigade API key. You can find your API key in the Frigade Dashboard under \"Developer\".\n */\n apiKey?: string\n /**\n * API url to use for all requests. Defaults to https://api.frigade.com\n */\n apiUrl?: string\n\n /**\n * User ID to use for all requests. If not provided, a Guest ID will be generated.\n */\n userId?: string\n\n /**\n * Group ID (organization) to use for all requests.\n */\n groupId?: string\n\n /**\n * @ignore Internal use only.\n * If enabled, Frigade will not send any data to the API. A user's state will be reset on page refresh.\n */\n __readOnly?: boolean\n\n /**\n * @ignore Internal use only.\n * Map of Flow ID to Flow Config for all flows in the app.\n * Configs will have to be provided in serialized JSON format rather than YAML.\n */\n __flowConfigOverrides?: Record<string, string>\n\n /**\n * @ignore Internal use only.\n */\n __instanceId?: string\n}\n\nexport interface UserFlowState {\n flowId: string\n flowState: 'COMPLETED_FLOW' | 'STARTED_FLOW' | 'SKIPPED_FLOW' | 'NOT_STARTED_FLOW'\n lastStepId: string\n userId: string\n foreignUserId: string\n stepStates: Record<string, UserFlowStepState>\n shouldTrigger: boolean\n}\n\nexport interface UserFlowStepState {\n stepId: string\n flowSlug: string\n actionType: 'NOT_STARTED_STEP' | 'STARTED_STEP' | 'COMPLETED_STEP'\n createdAt: string\n blocked: boolean\n hidden: boolean\n lastActionAt?: string\n}\n\nexport interface InternalConfig {\n apiKey: string\n userId?: string\n organizationId?: string\n __instanceId?: string\n}\n\nexport enum FlowType {\n ANNOUNCEMENT = 'ANNOUNCEMENT',\n CHECKLIST = 'CHECKLIST',\n FORM = 'FORM',\n TOUR = 'TOUR',\n SUPPORT = 'SUPPORT',\n CUSTOM = 'CUSTOM',\n BANNER = 'BANNER',\n EMBEDDED_TIP = 'EMBEDDED_TIP',\n NPS_SURVEY = 'NPS_SURVEY',\n SURVEY = 'SURVEY',\n CARD = 'CARD',\n}\n","export const VERSION_NUMBER = '0.2.20'\n","import { VERSION_NUMBER } from '../core/version'\nimport fetch from 'cross-fetch'\nimport { v4 as uuidv4 } from 'uuid'\nimport { Flow } from '../core/flow'\nimport { frigadeGlobalState } from './state'\n\nexport const NOT_STARTED_STEP = 'NOT_STARTED_STEP'\nexport const COMPLETED_FLOW = 'COMPLETED_FLOW'\nexport const SKIPPED_FLOW = 'SKIPPED_FLOW'\nexport const STARTED_FLOW = 'STARTED_FLOW'\nexport const NOT_STARTED_FLOW = 'NOT_STARTED_FLOW'\nexport const COMPLETED_STEP = 'COMPLETED_STEP'\nexport const STARTED_STEP = 'STARTED_STEP'\nexport type StepActionType = 'STARTED_STEP' | 'COMPLETED_STEP' | 'NOT_STARTED_STEP'\nexport type UserFlowStatus = 'NOT_STARTED_FLOW' | 'STARTED_FLOW' | 'COMPLETED_FLOW' | 'SKIPPED_FLOW'\nconst LAST_POST_CALL_AT = 'frigade-last-call-at-'\nconst LAST_POST_CALL_DATA = 'frigade-last-call-data-'\nconst GUEST_KEY = 'frigade-guest-key'\nexport const GUEST_PREFIX = 'guest_'\nconst GET_CACHE_PREFIX = 'get-cache-'\nconst GET_CACHE_TTL_MS = 1000\nconst POST_CACHE_TTL_MS = 1000\nconst LOCAL_STORAGE_PREFIX = 'fr-js-'\n\nexport function cloneFlow(flow: Flow): Flow {\n const newFlow = new Flow(flow.config, flow.rawData)\n newFlow.isCompleted = flow.isCompleted\n newFlow.isStarted = flow.isStarted\n newFlow.isSkipped = flow.isSkipped\n newFlow.isVisible = flow.isVisible\n newFlow.steps = flow.steps\n return newFlow\n}\n\nexport function clone<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj))\n}\n\nexport function getHeaders(apiKey: string) {\n return {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Frigade-SDK-Version': VERSION_NUMBER,\n 'X-Frigade-SDK-Platform': 'Javascript',\n },\n }\n}\n\nfunction getLocalStorage(key: string) {\n if (isWeb()) {\n return window.localStorage.getItem(`${LOCAL_STORAGE_PREFIX}${key}`)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (isWeb()) {\n window.localStorage.setItem(`${LOCAL_STORAGE_PREFIX}${key}`, value)\n }\n}\n\nfunction setGlobalState(key: string, value: any) {\n frigadeGlobalState[key] = value\n}\n\nfunction getGlobalState(key: string): any {\n return frigadeGlobalState[key]\n}\n\nexport function clearCache() {\n Object.keys(frigadeGlobalState).forEach((key) => {\n if (key.startsWith(GET_CACHE_PREFIX)) {\n delete frigadeGlobalState[key]\n }\n })\n}\n\nexport function resetAllLocalStorage() {\n if (isWeb()) {\n // Clear all local storage items that begin with `frigade-`\n Object.keys(window.localStorage).forEach((key) => {\n if (key.startsWith(LOCAL_STORAGE_PREFIX)) {\n window.localStorage.removeItem(key)\n }\n })\n }\n}\n\nexport async function gracefulFetch(url: string, options: any) {\n const lastCallAtKey = LAST_POST_CALL_AT + url\n const lastCallDataKey = LAST_POST_CALL_DATA + url\n if (isWeb() && options && options.body && options.method === 'POST') {\n const lastCall = getLocalStorage(lastCallAtKey)\n const lastCallData = getLocalStorage(lastCallDataKey)\n if (lastCall && lastCallData && lastCallData == options.body) {\n const lastCallDate = new Date(lastCall)\n const now = new Date()\n const diff = now.getTime() - lastCallDate.getTime()\n // Throttle consecutive POST calls to 1 second\n if (diff < POST_CACHE_TTL_MS) {\n return getEmptyResponse()\n }\n }\n setLocalStorage(lastCallAtKey, new Date().toISOString())\n setLocalStorage(lastCallDataKey, options.body)\n clearCache()\n }\n\n let response\n try {\n response = fetch(url, options)\n response = await response\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse('Received an empty response')\n }\n\n if (response.status >= 400) {\n return getEmptyResponse(response.statusText)\n }\n\n try {\n if (response.status === 204 || response.status === 201) {\n return getEmptyResponse()\n }\n\n const body = await response.json()\n if (body.error) {\n return getEmptyResponse(body.error)\n }\n return body\n } catch (e) {\n return getEmptyResponse(e)\n }\n}\n\nexport function getEmptyResponse(error?: any) {\n if (error) {\n console.log('Call to Frigade failed', error)\n }\n\n // Create empty response that contains the .json method and returns an empty object\n return {\n json: () => ({}),\n }\n}\n\nexport function generateGuestId() {\n if (isWeb()) {\n let guestId = getLocalStorage(GUEST_KEY)\n if (!guestId) {\n guestId = `${GUEST_PREFIX}${uuidv4()}`\n setLocalStorage(GUEST_KEY, guestId)\n }\n return guestId\n }\n}\n\nexport function fetcher(apiKey: string, path: string, options?: Record<any, any>) {\n return gracefulFetch(`//api.frigade.com/v1/public${path}`, {\n ...(options ?? {}),\n ...getHeaders(apiKey),\n })\n}\n\nexport function isWeb() {\n return (\n typeof window !== 'undefined' &&\n typeof window.document !== 'undefined' &&\n typeof window.localStorage !== 'undefined'\n )\n}\n","import { FlowStep, FrigadeConfig, UserFlowState } from '../core/types'\nimport { Flow } from '../core/flow'\n\nexport interface FrigadeGlobalState {\n refreshUserFlowStates: () => Promise<void>\n userFlowStates: Record<string, UserFlowState>\n onFlowStateChangeHandlerWrappers: Map<\n (flow: Flow, previousFlow: Flow) => void,\n (flow: Flow, previousFlow: Flow) => void\n >\n onStepStateChangeHandlerWrappers: Map<\n (step: FlowStep, previousStep: FlowStep) => void,\n (flow: Flow, previousFlow: Flow) => void\n >\n onFlowStateChangeHandlers: ((flow: Flow, previousFlow: Flow) => void)[]\n previousFlows: Map<string, Flow>\n variables: Record<string, Record<string, any>>\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}:${internalConfig.userId ?? ''}:${\n internalConfig.groupId ?? ''\n }`\n}\n","import { generateGuestId, getEmptyResponse, getHeaders, gracefulFetch } from './utils'\nimport { FrigadeConfig } from '../core/types'\nimport { frigadeGlobalState, FrigadeGlobalState, getGlobalStateKey } from './state'\n\nexport class Fetchable {\n public config: FrigadeConfig = {\n apiKey: '',\n apiUrl: 'https://api.frigade.com/v1/public',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(36).substring(7),\n }\n\n constructor(config: FrigadeConfig) {\n const filteredConfig = Object.fromEntries(Object.entries(config).filter(([_, v]) => v != null))\n\n this.config = {\n ...this.config,\n ...filteredConfig,\n }\n }\n\n /**\n * @ignore\n */\n public async fetch(path: string, options?: Record<any, any>) {\n if (this.config.__readOnly) {\n return getEmptyResponse()\n }\n\n return gracefulFetch(this.getAPIUrl(path), {\n keepalive: true,\n ...(options ?? {}),\n ...getHeaders(this.config.apiKey),\n })\n }\n\n private getAPIUrl(path: string) {\n const pathPrefix = '/v1/public'\n const apiUrl = new URL(\n `${pathPrefix}${path}`,\n this.config.apiUrl.replace(pathPrefix, '')\n ).toString()\n\n return apiUrl\n }\n\n /**\n * @ignore\n */\n protected getGlobalState(): FrigadeGlobalState {\n const globalStateKey = getGlobalStateKey(this.config)\n if (!frigadeGlobalState[globalStateKey]) {\n throw new Error('Frigade not initialized')\n }\n return frigadeGlobalState[globalStateKey]\n }\n}\n","import { FlowDataRaw, FlowStep, FrigadeConfig, UserFlowState } from './types'\nimport {\n clone,\n COMPLETED_FLOW,\n COMPLETED_STEP,\n NOT_STARTED_FLOW,\n NOT_STARTED_STEP,\n SKIPPED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { Fetchable } from '../shared/fetchable'\n\nexport class Flow extends Fetchable {\n /**\n * The Flow's ID.\n */\n public id: string\n /**\n * The raw data defined in `config.yml` as a JSON decoded object.\n * @ignore\n */\n public configYmlAsJson: any\n /**\n * Ordered map of the Steps in the Flow.\n * See [Flow Step Definition](https://docs.frigade.com/v2/sdk/js/step) for more information.\n */\n public steps: Map<string, FlowStep>\n /**\n * The user-facing title of the Flow, if defined at the top level of the YAML config.\n */\n public title?: string\n /**\n * The user-facing description of the Flow, if defined at the top level of the YAML config.\n */\n public subtitle?: string\n /**\n * The metadata of the Flow.\n * @ignore\n */\n public rawData: FlowDataRaw\n /**\n * Whether the Flow is completed or not.\n */\n public isCompleted: boolean\n /**\n * Whether the Flow is started or not.\n */\n public isStarted: boolean\n /**\n * Whether the Flow has been skipped or not.\n */\n public isSkipped: boolean\n /**\n * Whether the Flow is visible to the user based on the current user/group's state.\n */\n public isVisible: boolean = false\n /**\n * Whether the Flow targeting logic/audience matches the current user/group.\n */\n public isTargeted: boolean = false\n /**\n * @ignore\n */\n private readonly flowDataRaw: FlowDataRaw\n /**\n * @ignore\n */\n private userFlowStateRaw?: UserFlowState\n /**\n * @ignore\n */\n private lastStepUpdate: Map<(step: FlowStep, previousStep: FlowStep) => void, FlowStep> =\n new Map()\n\n constructor(config: FrigadeConfig, flowDataRaw: FlowDataRaw) {\n super(config)\n this.flowDataRaw = flowDataRaw\n this.initFromRawData(flowDataRaw)\n }\n\n /**\n * Reload the Flow data from the server\n */\n reload() {\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * @ignore\n */\n private initFromRawData(flowDataRaw: FlowDataRaw) {\n const flowDataYml = JSON.parse(flowDataRaw.data)\n const steps = flowDataYml.steps ?? flowDataYml.data ?? []\n this.id = flowDataRaw.slug\n this.rawData = flowDataRaw\n this.configYmlAsJson = flowDataYml\n this.title = this.configYmlAsJson.title\n this.subtitle = this.configYmlAsJson.subtitle\n\n const userFlowState = this.getUserFlowState()\n if (!userFlowState) {\n return\n }\n this.userFlowStateRaw = userFlowState\n\n this.isCompleted = userFlowState.flowState == COMPLETED_FLOW\n this.isStarted = userFlowState.flowState == STARTED_FLOW\n this.isSkipped = userFlowState.flowState == SKIPPED_FLOW\n const hasCompleted = this.isCompleted || this.isSkipped\n const targetingShouldHideFlow =\n flowDataRaw.targetingLogic && userFlowState.shouldTrigger === false\n this.isVisible = !hasCompleted && !targetingShouldHideFlow\n if (this.flowDataRaw.active === false) {\n this.isVisible = false\n }\n this.isTargeted = !flowDataRaw.targetingLogic ? true : targetingShouldHideFlow === false\n\n const newSteps = new Map<string, FlowStep>()\n\n steps.forEach((step, index) => {\n const userFlowStateStep = userFlowState.stepStates[step.id]\n const stepObj = {\n ...step,\n isCompleted: userFlowStateStep.actionType == COMPLETED_STEP,\n isStarted: userFlowStateStep.actionType == STARTED_STEP,\n isHidden: userFlowStateStep.hidden,\n isBlocked: userFlowStateStep.blocked,\n lastActionAt: userFlowStateStep.lastActionAt\n ? new Date(userFlowStateStep.lastActionAt)\n : undefined,\n order: index,\n } as FlowStep\n\n stepObj.start = async (properties?: Record<string | number, any>) => {\n const thisStep = this.steps.get(step.id)\n\n if (this.getCurrentStep().id === thisStep.id && thisStep.isStarted) {\n return\n }\n\n thisStep.isStarted = true\n const copy = clone(this.getGlobalState().userFlowStates[this.id])\n copy.stepStates[thisStep.id].actionType = STARTED_STEP\n copy.stepStates[thisStep.id].lastActionAt = new Date().toISOString()\n copy.lastStepId = thisStep.id\n\n this.getGlobalState().userFlowStates[this.id] = copy\n\n if (!thisStep.isCompleted) {\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: thisStep.id,\n data: properties ?? {},\n createdAt: properties?.createdAt\n ? new Date(properties.createdAt)\n : new Date().toISOString(),\n actionType: STARTED_STEP,\n }),\n })\n await this.refreshUserFlowState()\n }\n\n const updatedUserFlowState = this.getUserFlowState()\n thisStep.isCompleted =\n updatedUserFlowState.stepStates[thisStep.id].actionType == COMPLETED_STEP\n thisStep.isStarted = updatedUserFlowState.stepStates[thisStep.id].actionType == STARTED_STEP\n thisStep.lastActionAt = new Date()\n }\n\n stepObj.complete = async (properties?: Record<string | number, any>) => {\n const thisStep = this.steps.get(step.id)\n\n if (thisStep.isCompleted) {\n return\n }\n\n const numberOfCompletedSteps = this.getNumberOfCompletedSteps()\n const isLastStep = numberOfCompletedSteps + 1 == this.steps.size\n\n thisStep.isCompleted = true\n this.isStarted = true\n const copy = clone(this.getGlobalState().userFlowStates[this.id])\n\n copy.stepStates[thisStep.id].actionType = COMPLETED_STEP\n copy.stepStates[thisStep.id].lastActionAt = new Date().toISOString()\n copy.flowState = isLastStep ? COMPLETED_FLOW : STARTED_FLOW\n\n const nextStepId = Array.from(this.steps.keys())[index + 1]\n if (nextStepId) {\n copy.lastStepId = nextStepId\n copy.stepStates[nextStepId].actionType = STARTED_STEP\n const lastAction = new Date()\n copy.stepStates[nextStepId].lastActionAt = lastAction.toISOString()\n this.steps.get(nextStepId).isStarted = true\n this.steps.get(nextStepId).lastActionAt = lastAction\n }\n\n if (isLastStep) {\n this.optimisticallyMarkFlowCompleted()\n }\n\n this.getGlobalState().userFlowStates[this.id] = copy\n\n // if all steps are now completed, mark flow completed\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: thisStep.id,\n data: properties ?? {},\n createdAt: properties?.createdAt\n ? new Date(properties.createdAt)\n : new Date().toISOString(),\n actionType: COMPLETED_STEP,\n }),\n })\n\n await this.refreshUserFlowState()\n\n const updatedUserFlowState = this.getUserFlowState()\n thisStep.isCompleted =\n updatedUserFlowState.stepStates[thisStep.id].actionType == COMPLETED_STEP\n thisStep.isStarted = updatedUserFlowState.stepStates[thisStep.id].actionType == STARTED_STEP\n thisStep.lastActionAt = new Date()\n }\n\n stepObj.reset = async () => {\n const thisStep = this.steps.get(step.id)\n\n if (!thisStep.isCompleted) {\n return\n }\n\n thisStep.isCompleted = false\n thisStep.isStarted = false\n thisStep.lastActionAt = undefined\n const copy = clone(this.getGlobalState().userFlowStates[this.id])\n copy.stepStates[thisStep.id].actionType = NOT_STARTED_STEP\n copy.stepStates[thisStep.id].lastActionAt = undefined\n copy.flowState = STARTED_FLOW\n this.getGlobalState().userFlowStates[this.id] = copy\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: thisStep.id,\n data: {},\n createdAt: new Date().toISOString(),\n actionType: NOT_STARTED_STEP,\n }),\n })\n\n await this.refreshUserFlowState()\n\n const updatedUserFlowState = this.getUserFlowState()\n thisStep.isCompleted =\n updatedUserFlowState.stepStates[thisStep.id].actionType == COMPLETED_STEP\n thisStep.isStarted = updatedUserFlowState.stepStates[thisStep.id].actionType == STARTED_STEP\n thisStep.lastActionAt = undefined\n }\n\n stepObj.onStateChange = (handler: (step: FlowStep, previousStep: FlowStep) => void) => {\n const wrapperHandler = (flow: Flow) => {\n if (flow.id !== this.id) {\n return\n }\n const thisStep = flow.steps.get(step.id)\n const previousStep = this.lastStepUpdate.get(handler)\n\n if (\n thisStep.isCompleted !== previousStep?.isCompleted ||\n thisStep.isStarted !== previousStep?.isStarted ||\n thisStep.isHidden !== previousStep?.isHidden ||\n thisStep.isBlocked !== previousStep?.isBlocked\n ) {\n handler(thisStep, previousStep ?? clone(thisStep))\n this.lastStepUpdate.set(handler, clone(thisStep))\n }\n }\n this.getGlobalState().onStepStateChangeHandlerWrappers.set(handler, wrapperHandler)\n this.getGlobalState().onFlowStateChangeHandlers.push(wrapperHandler)\n }\n\n stepObj.removeStateChangeHandler = (\n handler: (step: FlowStep, previousStep: FlowStep) => void\n ) => {\n const wrapperHandler = this.getGlobalState().onStepStateChangeHandlerWrappers.get(handler)\n if (wrapperHandler) {\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== wrapperHandler)\n }\n }\n\n newSteps.set(step.id, stepObj)\n })\n this.steps = newSteps\n // Check if empty object\n if (\n this.getGlobalState().variables &&\n this.getGlobalState().variables[this.id] &&\n Object.keys(this.getGlobalState().variables[this.id]).length > 0\n ) {\n this.applyVariables(this.getGlobalState().variables[this.id])\n }\n }\n\n /**\n * Marks the flow started\n */\n public async start(properties?: Record<string | number, any>) {\n if (this.isStarted || this.isCompleted) {\n return\n }\n\n this.isStarted = true\n const copy = clone(this.getGlobalState().userFlowStates[this.id])\n copy.flowState = STARTED_FLOW\n this.getGlobalState().userFlowStates[this.id] = copy\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Marks the flow completed\n */\n public async complete(properties?: Record<string | number, any>) {\n if (this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowCompleted()\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: properties?.createdAt\n ? new Date(properties.createdAt)\n : new Date().toISOString(),\n actionType: COMPLETED_FLOW,\n }),\n })\n\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowCompleted() {\n this.isStarted = true\n this.isCompleted = true\n const copy = clone(this.getGlobalState().userFlowStates[this.id])\n copy.flowState = COMPLETED_FLOW\n this.getGlobalState().userFlowStates[this.id] = copy\n this.isVisible = false\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowSkipped() {\n this.isSkipped = true\n const copy = clone(this.getGlobalState().userFlowStates[this.id])\n copy.flowState = SKIPPED_FLOW\n this.getGlobalState().userFlowStates[this.id] = copy\n this.isVisible = false\n }\n\n /**\n * Marks the flow skipped\n */\n public async skip(properties?: Record<string | number, any>) {\n if (this.isSkipped) {\n return\n }\n\n this.optimisticallyMarkFlowSkipped()\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: properties?.createdAt\n ? new Date(properties.createdAt)\n : new Date().toISOString(),\n actionType: SKIPPED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Navigates the flow to the next step if one exists. This will mark that step started, but will not complete the previous step.\n */\n public async forward(properties?: Record<string | number, any>) {\n const nextStep = this.getStepByIndex(this.getCurrentStepIndex() + 1)\n if (nextStep) {\n await nextStep.start(properties)\n }\n }\n\n /**\n * Navigates the flow to the previous step if one exists. This will mark that step started, but will not complete the previous step.\n */\n public async back(properties?: Record<string | number, any>) {\n const previousStep = this.getStepByIndex(this.getCurrentStepIndex() - 1)\n if (previousStep) {\n await previousStep.start(properties)\n }\n }\n\n /**\n * Restarts the flow/marks it not started\n */\n public async restart() {\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: 'unknown',\n data: {},\n createdAt: new Date().toISOString(),\n actionType: NOT_STARTED_FLOW,\n }),\n })\n\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Get a step by index\n * @param index\n */\n public getStepByIndex(index: number): FlowStep | undefined {\n return this.steps.get(Array.from(this.steps.keys())[index])\n }\n\n /**\n * Gets current step\n */\n public getCurrentStep(): FlowStep {\n let maybeCurrentStepId = Array.from(this.steps.keys()).find(\n (key) => this.steps.get(key).isCompleted === false && this.steps.get(key).isHidden === false\n )\n Array.from(this.steps.keys()).forEach((key) => {\n if (\n this.steps.get(key).isStarted &&\n this.steps.get(key).lastActionAt &&\n this.steps.get(key).lastActionAt >\n (this.steps.get(maybeCurrentStepId)?.lastActionAt ?? new Date(0))\n ) {\n maybeCurrentStepId = key\n }\n })\n\n const currentStepId = maybeCurrentStepId ?? Array.from(this.steps.keys())[0]\n return this.steps.get(currentStepId)\n }\n\n /**\n * Get the index of the current step. Starts at 0\n */\n public getCurrentStepIndex(): number {\n const currentStep = this.getCurrentStep()\n return Array.from(this.steps.keys()).indexOf(currentStep.id)\n }\n\n /**\n * Get the number of completed steps for the current user in the current flow\n */\n public getNumberOfCompletedSteps(): number {\n return Array.from(this.steps.values()).filter((step) => step.isCompleted).length\n }\n\n /**\n * Get the number of available steps for the current user in the current flow. This is the number of steps that are not hidden.\n */\n public getNumberOfAvailableSteps(): number {\n return Array.from(this.steps.values()).filter((step) => !step.isHidden).length\n }\n\n /**\n * @ignore\n */\n public onStateChange(handler: (flow: Flow, previousFlow: Flow) => void) {\n const wrapperHandler = (flow: Flow, previousFlow: Flow) => {\n if (\n (flow.id === this.id &&\n (flow.isCompleted !== previousFlow.isCompleted ||\n flow.isStarted !== previousFlow.isStarted ||\n flow.isSkipped !== previousFlow.isSkipped ||\n flow.isVisible !== previousFlow.isVisible)) ||\n JSON.stringify(flow.steps) !== JSON.stringify(previousFlow.steps)\n ) {\n handler(flow, previousFlow)\n }\n }\n this.getGlobalState().onFlowStateChangeHandlerWrappers.set(handler, wrapperHandler)\n this.getGlobalState().onFlowStateChangeHandlers.push(wrapperHandler)\n }\n\n /**\n * @ignore\n */\n public removeStateChangeHandler(handler: (flow: Flow, previousFlow: Flow) => void) {\n const wrapperHandler = this.getGlobalState().onFlowStateChangeHandlerWrappers.get(handler)\n if (wrapperHandler) {\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== wrapperHandler)\n }\n }\n\n /**\n * @ignore\n */\n public applyVariables(variables: Record<string, any>) {\n // Replace ${variable} with the value of the variable\n const replaceVariables = (str: string) => {\n const matches = str.match(/\\${(.*?)}/g)\n if (matches) {\n matches.forEach((match) => {\n const variable = match.replace('${', '').replace('}', '')\n if (!variables[variable]) {\n return\n }\n str = str.replace(match, variables[variable])\n })\n }\n return str\n }\n\n this.title = replaceVariables(this.title ?? '')\n this.subtitle = replaceVariables(this.subtitle ?? '')\n this.steps.forEach((step) => {\n // Iterate over every string field in the step and replace variables\n Object.keys(step).forEach((key) => {\n if (typeof step[key] === 'string') {\n // @ts-ignore\n step[key] = replaceVariables(step[key])\n }\n })\n })\n\n this.getGlobalState().variables = {}\n this.getGlobalState().variables[this.id] = variables\n }\n\n /**\n * @ignore\n */\n private getUserFlowState(): UserFlowState {\n const userFlowStates = this.getGlobalState().userFlowStates\n return userFlowStates[this.id]\n }\n\n /**\n * @ignore\n */\n private async refreshUserFlowState() {\n await this.getGlobalState().refreshUserFlowStates()\n }\n}\n","import {\n FlowDataRaw,\n FlowStatus,\n FlowType,\n FrigadeConfig,\n TriggerType,\n UserFlowState,\n} from './types'\nimport { clearCache, cloneFlow, GUEST_PREFIX, isWeb, resetAllLocalStorage } from '../shared/utils'\nimport { Flow } from './flow'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/fetchable'\n\nexport class Frigade extends Fetchable {\n /**\n * @ignore\n */\n private flows: Flow[] = []\n /**\n * @ignore\n */\n private initPromise: Promise<void>\n /**\n * @ignore\n */\n private hasFailed = false\n\n /**\n * @ignore\n */\n private visibilityChangeHandler = async () => {\n if (document.visibilityState === 'visible') {\n await this.refreshFlows()\n await this.refreshUserFlowStates()\n // Trigger all event handlers\n this.flows.forEach((flow) => {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n })\n }\n }\n\n constructor(apiKey: string, config?: FrigadeConfig) {\n super({\n apiKey,\n ...config,\n })\n this.init(this.config)\n if (isWeb()) {\n document.addEventListener('visibilitychange', this.visibilityChangeHandler)\n }\n }\n\n /**\n * @ignore\n */\n destroy() {\n if (isWeb()) {\n document.removeEventListener('visibilitychange', this.visibilityChangeHandler)\n // Remove all other event listeners\n const globalStateKey = getGlobalStateKey(this.config)\n if (frigadeGlobalState[globalStateKey]) {\n frigadeGlobalState[globalStateKey].onFlowStateChangeHandlers = []\n }\n }\n }\n\n /**\n * @ignore\n */\n private async init(config: FrigadeConfig): Promise<void> {\n this.config = {\n ...this.config,\n ...config,\n }\n\n this.initPromise = (async () => {\n if (this.config.userId && !this.config.userId?.startsWith(GUEST_PREFIX)) {\n await this.fetch('/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.config.userId,\n }),\n })\n }\n await this.refreshUserFlowStates()\n await this.refreshFlows()\n })()\n\n return this.initPromise\n }\n\n /**\n * Set the current user.\n * @param userId\n * @param properties\n */\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n this.config = { ...this.config, userId }\n await this.initIfNeeded()\n await this.fetch('/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.config.userId,\n properties,\n }),\n })\n await this.resync()\n }\n\n /**\n * Set the group for the current user.\n * @param groupId\n * @param properties\n */\n public async group(groupId: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n this.config.groupId = groupId\n await this.fetch('/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n properties,\n }),\n })\n await this.resync()\n }\n\n /**\n * Track an event for the current user (and group if set).\n * @param event\n * @param properties\n */\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n if (!event) {\n console.error('Event name is required to track an event')\n return\n }\n if (this.config.userId && this.config.groupId) {\n await this.fetch('/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n events: [\n {\n event,\n properties,\n },\n ],\n }),\n })\n } else if (this.config.userId) {\n await this.fetch('/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.config.userId,\n events: [\n {\n event,\n properties,\n },\n ],\n }),\n })\n }\n await this.resync()\n }\n\n /**\n * @ignore\n */\n public isReady(): boolean {\n return Boolean(this.config.__instanceId && this.config.apiKey && this.initPromise)\n }\n\n /**\n * Get a Flow by its ID.\n * @param flowId\n */\n public async getFlow(flowId: string) {\n await this.initIfNeeded()\n\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n public async getFlows() {\n await this.initIfNeeded()\n return this.flows\n }\n\n /**\n * Reload the current state of the flows by calling the Frigade API.\n * This will trigger all event handlers.\n */\n public async reload() {\n resetAllLocalStorage()\n clearCache()\n await this.refreshUserFlowStates()\n await this.refreshFlows()\n this.initPromise = null\n await this.init(this.config)\n // Trigger all event handlers\n this.flows.forEach((flow) => {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n })\n }\n\n private async resync() {\n this.initPromise = null\n await this.init(this.config)\n this.flows.forEach((flow) => {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n })\n }\n\n /**\n * Event handler that captures all changes that happen to the state of the Flows.\n * @param handler\n */\n public async onStateChange(handler: (flow: Flow, previousFlow?: Flow) => void) {\n await this.initIfNeeded()\n this.getGlobalState().onFlowStateChangeHandlers.push(handler)\n }\n\n /**\n * Returns true if the JS SDK failed to connect to the Frigade API.\n */\n hasFailedToLoad() {\n return this.hasFailed\n }\n\n /**\n * Removes the given handler from the list of event handlers.\n * @param handler\n */\n public async removeStateChangeHandler(handler: (flow: Flow, previousFlow?: Flow) => void) {\n await this.initIfNeeded()\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== handler)\n }\n\n /**\n * @ignore\n */\n private async initIfNeeded() {\n if (this.initPromise !== null) {\n return this.initPromise\n } else {\n return this.init(this.config)\n }\n }\n\n /**\n * @ignore\n */\n private async refreshUserFlowStates(): Promise<void> {\n const globalStateKey = getGlobalStateKey(this.config)\n\n if (!frigadeGlobalState[globalStateKey]) {\n const that = this\n\n let validator = {\n set: function (target: any, key: any, value: any) {\n if (\n target[key] &&\n target[key].flowState &&\n (JSON.stringify(target[key].flowState) !== JSON.stringify(value?.flowState) ||\n JSON.stringify(target[key].stepStates) !== JSON.stringify(value?.stepStates) ||\n JSON.stringify(target[key].shouldTrigger) !== JSON.stringify(value?.shouldTrigger))\n ) {\n that.triggerEventHandlers(target[key])\n }\n\n target[key] = value\n return true\n },\n }\n\n frigadeGlobalState[globalStateKey] = {\n refreshUserFlowStates: async () => {},\n userFlowStates: new Proxy({}, validator),\n onFlowStateChangeHandlerWrappers: new Map(),\n onStepStateChangeHandlerWrappers: new Map(),\n onFlowStateChangeHandlers: [],\n previousFlows: new Map(),\n variables: {},\n }\n\n if (this.config.__readOnly && this.config.__flowConfigOverrides) {\n this.mockUserFlowStates(globalStateKey)\n\n return\n }\n\n frigadeGlobalState[globalStateKey].refreshUserFlowStates = async () => {\n if (this.config.__readOnly) {\n return\n }\n\n const userFlowStatesRaw = await this.fetch(\n `/userFlowStates?foreignUserId=${encodeURIComponent(this.config.userId)}${\n this.config.groupId\n ? `&foreignUserGroupId=${encodeURIComponent(this.config.groupId)}`\n : ''\n }`\n )\n if (userFlowStatesRaw && userFlowStatesRaw.data) {\n let userFlowStates = userFlowStatesRaw.data as UserFlowState[]\n userFlowStates.forEach((userFlowState) => {\n let shouldReload = false\n const before = frigadeGlobalState[globalStateKey].userFlowStates[userFlowState.flowId]\n\n // Special case: for flows that show up based on targeting logic/rules, we need to check if the flow should be triggered\n if (before && before.shouldTrigger == false && userFlowState.shouldTrigger == true) {\n shouldReload = true\n }\n frigadeGlobalState[globalStateKey].userFlowStates[userFlowState.flowId] = userFlowState\n if (shouldReload) {\n this.flows.forEach((flow) => {\n if (flow.id == userFlowState.flowId) {\n flow.reload()\n this.triggerEventHandlers(\n frigadeGlobalState[globalStateKey].userFlowStates[flow.id]\n )\n }\n })\n }\n })\n this.hasFailed = false\n } else {\n this.hasFailed = true\n }\n }\n }\n\n await frigadeGlobalState[globalStateKey].refreshUserFlowStates()\n }\n\n /**\n * @ignore\n */\n private async refreshFlows() {\n this.flows = []\n\n if (this.config.__flowConfigOverrides) {\n this.mockFlowConfigs()\n return\n }\n\n const flowDataRaw = await this.fetch('/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowDatas = flowDataRaw.data as FlowDataRaw[]\n flowDatas.forEach((flowData) => {\n this.flows.push(new Flow(this.config, flowData))\n this.getGlobalState().previousFlows.set(\n flowData.slug,\n cloneFlow(this.flows[this.flows.length - 1])\n )\n })\n } else {\n this.hasFailed = true\n }\n }\n\n /**\n * @ignore\n */\n private mockFlowConfigs() {\n Object.keys(this.config.__flowConfigOverrides).forEach((flowId) => {\n this.flows.push(\n new Flow(this.config, {\n id: -1,\n name: '',\n description: '',\n data: this.config.__flowConfigOverrides[flowId],\n createdAt: new Date().toISOString(),\n modifiedAt: new Date().toISOString(),\n slug: flowId,\n targetingLogic: '',\n type: FlowType.CHECKLIST,\n triggerType: TriggerType.MANUAL,\n status: FlowStatus.ACTIVE,\n version: 1,\n active: true,\n })\n )\n })\n }\n\n /**\n * @ignore\n */\n private mockUserFlowStates(globalStateKey: string) {\n Object.keys(this.config.__flowConfigOverrides).forEach((flowId) => {\n const parsed = JSON.parse(this.config.__flowConfigOverrides[flowId])\n frigadeGlobalState[globalStateKey].userFlowStates[flowId] = {\n flowId,\n flowState: 'NOT_STARTED_FLOW',\n lastStepId: null,\n userId: this.config.userId,\n foreignUserId: this.config.userId,\n stepStates:\n parsed?.steps?.reduce((acc, step) => {\n acc[step.id] = {\n stepId: step.id,\n flowSlug: flowId,\n actionType: 'NOT_STARTED_STEP',\n createdAt: new Date().toISOString(),\n blocked: false,\n hidden: false,\n }\n return acc\n }, {}) ?? {},\n shouldTrigger: false,\n }\n })\n }\n\n /**\n * @ignore\n */\n private async triggerEventHandlers(previousUserFlowState: UserFlowState) {\n if (previousUserFlowState) {\n this.flows.forEach((flow) => {\n if (flow.id == previousUserFlowState.flowId) {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n }\n })\n }\n }\n}\n"],"mappings":";kmCAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,UAAAE,EAAA,eAAAC,EAAA,aAAAC,EAAA,YAAAC,EAAA,gBAAAC,IAAA,eAAAC,GAAAP,ICgBO,IAAKQ,OACVA,EAAA,OAAS,SACTA,EAAA,UAAY,YAFFA,OAAA,IAKAC,OACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SACTA,EAAA,SAAW,WAHDA,OAAA,IAiPAC,OACVA,EAAA,aAAe,eACfA,EAAA,UAAY,YACZA,EAAA,KAAO,OACPA,EAAA,KAAO,OACPA,EAAA,QAAU,UACVA,EAAA,OAAS,SACTA,EAAA,OAAS,SACTA,EAAA,aAAe,eACfA,EAAA,WAAa,aACbA,EAAA,OAAS,SACTA,EAAA,KAAO,OAXGA,OAAA,ICtQL,IAAMC,GAAiB,SCC9B,IAAAC,GAAkB,6BAClBC,GAA6B,gBCiBtB,IAAIC,EAAyD,CAAC,EAE9D,SAASC,EAAkBC,EAAuC,CArBzE,IAAAC,EAAAC,EAsBE,MAAO,GAAGF,EAAe,gBAAgBA,EAAe,WAAUC,EAAAD,EAAe,SAAf,KAAAC,EAAyB,OACzFC,EAAAF,EAAe,UAAf,KAAAE,EAA0B,IAE9B,CCrBO,IAAMC,EAAN,KAAgB,CAQrB,YAAYC,EAAuB,CAPnC,KAAO,OAAwB,CAC7B,OAAQ,GACR,OAAQ,oCACR,OAAQC,GAAgB,EACxB,aAAc,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,UAAU,CAAC,CACtD,EAGE,IAAMC,EAAiB,OAAO,YAAY,OAAO,QAAQF,CAAM,EAAE,OAAO,CAAC,CAACG,EAAGC,CAAC,IAAMA,GAAK,IAAI,CAAC,EAE9F,KAAK,OAASC,IAAA,GACT,K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CAEL,CAAC,CAEL,GACF","names":["src_exports","__export","Flow","FlowStatus","FlowType","Frigade","TriggerType","__toCommonJS","TriggerType","FlowStatus","FlowType","VERSION_NUMBER","import_cross_fetch","import_uuid","frigadeGlobalState","getGlobalStateKey","internalConfig","_a","_b","Fetchable","config","generateGuestId","filteredConfig","_","v","__spreadValues","path","options","__async","getEmptyResponse","gracefulFetch","getHeaders","pathPrefix","globalStateKey","getGlobalStateKey","frigadeGlobalState","Flow","Fetchable","config","flowDataRaw","_a","_b","flowDataYml","steps","userFlowState","COMPLETED_FLOW","STARTED_FLOW","SKIPPED_FLOW","hasCompleted","targetingShouldHideFlow","newSteps","step","index","userFlowStateStep","stepObj","__spreadProps","__spreadValues","COMPLETED_STEP","STARTED_STEP","properties","__async","thisStep","copy","clone","updatedUserFlowState","isLastStep","nextStepId","lastAction","NOT_STARTED_STEP","handler","wrapperHandler","flow","previousStep","h","nextStep","NOT_STARTED_FLOW","maybeCurrentStepId","key","currentStepId","currentStep","previousFlow","variables","replaceVariables","str","matches","match","variable","NOT_STARTED_STEP","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","GUEST_KEY","GUEST_PREFIX","GET_CACHE_PREFIX","POST_CACHE_TTL_MS","LOCAL_STORAGE_PREFIX","cloneFlow","flow","newFlow","Flow","clone","obj","getHeaders","apiKey","VERSION_NUMBER","getLocalStorage","key","isWeb","setLocalStorage","value","clearCache","frigadeGlobalState","key","GET_CACHE_PREFIX","resetAllLocalStorage","isWeb","LOCAL_STORAGE_PREFIX","gracefulFetch","url","options","__async","lastCallAtKey","LAST_POST_CALL_AT","lastCallDataKey","LAST_POST_CALL_DATA","lastCall","getLocalStorage","lastCallData","lastCallDate","POST_CACHE_TTL_MS","getEmptyResponse","setLocalStorage","response","fetch","error","body","e","generateGuestId","guestId","GUEST_KEY","GUEST_PREFIX","uuidv4","isWeb","Frigade","Fetchable","apiKey","config","__spreadValues","__async","flow","handler","lastFlow","cloneFlow","isWeb","globalStateKey","getGlobalStateKey","frigadeGlobalState","_a","GUEST_PREFIX","userId","properties","__spreadProps","groupId","event","flowId","resetAllLocalStorage","clearCache","h","that","validator","target","key","value","userFlowStatesRaw","userFlowState","shouldReload","before","flowDataRaw","flowData","Flow","_b","parsed","acc","step","previousUserFlowState"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/core/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/shared/fetchable.ts","../src/core/flow.ts","../src/core/rules-graph.ts","../src/core/frigade.ts","../src/core/types.ts"],"sourcesContent":["export { Frigade } from './core/frigade'\nexport { Flow } from './core/flow'\nexport { FlowStatus, FlowStep, FrigadeConfig, FlowType, TriggerType } from './core/types'\n","export const VERSION_NUMBER = '0.2.20'\n","import { VERSION_NUMBER } from '../core/version'\nimport fetch from 'cross-fetch'\nimport { v4 as uuidv4 } from 'uuid'\nimport { Flow } from '../core/flow'\nimport { frigadeGlobalState } from './state'\n\nexport const NOT_STARTED_STEP = 'NOT_STARTED_STEP'\nexport const COMPLETED_FLOW = 'COMPLETED_FLOW'\nexport const SKIPPED_FLOW = 'SKIPPED_FLOW'\nexport const STARTED_FLOW = 'STARTED_FLOW'\nexport const NOT_STARTED_FLOW = 'NOT_STARTED_FLOW'\nexport const COMPLETED_STEP = 'COMPLETED_STEP'\nexport const STARTED_STEP = 'STARTED_STEP'\nexport type StepActionType = 'STARTED_STEP' | 'COMPLETED_STEP' | 'NOT_STARTED_STEP'\nexport type UserFlowStatus = 'NOT_STARTED_FLOW' | 'STARTED_FLOW' | 'COMPLETED_FLOW' | 'SKIPPED_FLOW'\nconst LAST_POST_CALL_AT = 'frigade-last-call-at-'\nconst LAST_POST_CALL_DATA = 'frigade-last-call-data-'\nconst GUEST_KEY = 'frigade-guest-key'\nexport const GUEST_PREFIX = 'guest_'\nconst GET_CACHE_PREFIX = 'get-cache-'\nconst GET_CACHE_TTL_MS = 1000\nconst POST_CACHE_TTL_MS = 1000\nconst LOCAL_STORAGE_PREFIX = 'fr-js-'\n\nexport function cloneFlow(flow: Flow): Flow {\n const newFlow = new Flow({\n config: flow.config,\n id: flow.id,\n })\n return newFlow\n}\n\nexport function clone<T>(obj: T): T {\n return JSON.parse(JSON.stringify(obj))\n}\n\nexport function getHeaders(apiKey: string) {\n return {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Frigade-SDK-Version': VERSION_NUMBER,\n 'X-Frigade-SDK-Platform': 'Javascript',\n },\n }\n}\n\nfunction getLocalStorage(key: string) {\n if (isWeb()) {\n return window.localStorage.getItem(`${LOCAL_STORAGE_PREFIX}${key}`)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (isWeb()) {\n window.localStorage.setItem(`${LOCAL_STORAGE_PREFIX}${key}`, value)\n }\n}\n\nfunction setGlobalState(key: string, value: any) {\n frigadeGlobalState[key] = value\n}\n\nfunction getGlobalState(key: string): any {\n return frigadeGlobalState[key]\n}\n\nexport function clearCache() {\n Object.keys(frigadeGlobalState).forEach((key) => {\n if (key.startsWith(GET_CACHE_PREFIX)) {\n delete frigadeGlobalState[key]\n }\n })\n}\n\nexport function resetAllLocalStorage() {\n if (isWeb()) {\n // Clear all local storage items that begin with `frigade-`\n Object.keys(window.localStorage).forEach((key) => {\n if (key.startsWith(LOCAL_STORAGE_PREFIX)) {\n window.localStorage.removeItem(key)\n }\n })\n }\n}\n\nexport async function gracefulFetch(url: string, options: any) {\n const lastCallAtKey = LAST_POST_CALL_AT + url\n const lastCallDataKey = LAST_POST_CALL_DATA + url\n if (isWeb() && options && options.body && options.method === 'POST') {\n const lastCall = getLocalStorage(lastCallAtKey)\n const lastCallData = getLocalStorage(lastCallDataKey)\n if (lastCall && lastCallData && lastCallData == options.body) {\n const lastCallDate = new Date(lastCall)\n const now = new Date()\n const diff = now.getTime() - lastCallDate.getTime()\n // Throttle consecutive POST calls to 1 second\n if (diff < POST_CACHE_TTL_MS) {\n return getEmptyResponse()\n }\n }\n setLocalStorage(lastCallAtKey, new Date().toISOString())\n setLocalStorage(lastCallDataKey, options.body)\n clearCache()\n }\n\n let response\n try {\n response = fetch(url, options)\n response = await response\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse('Received an empty response')\n }\n\n if (response.status >= 400) {\n return getEmptyResponse(response.statusText)\n }\n\n try {\n if (response.status === 204 || response.status === 201) {\n return getEmptyResponse()\n }\n\n const body = await response.json()\n if (body.error) {\n return getEmptyResponse(body.error)\n }\n return body\n } catch (e) {\n return getEmptyResponse(e)\n }\n}\n\nexport function getEmptyResponse(error?: any) {\n if (error) {\n console.log('Call to Frigade failed', error)\n }\n\n // Create empty response that contains the .json method and returns an empty object\n return {\n json: () => ({}),\n }\n}\n\nexport function generateGuestId() {\n if (isWeb()) {\n let guestId = getLocalStorage(GUEST_KEY)\n if (!guestId) {\n guestId = `${GUEST_PREFIX}${uuidv4()}`\n setLocalStorage(GUEST_KEY, guestId)\n }\n return guestId\n }\n}\n\nexport function fetcher(apiKey: string, path: string, options?: Record<any, any>) {\n return gracefulFetch(`//api.frigade.com/v1/public${path}`, {\n ...(options ?? {}),\n ...getHeaders(apiKey),\n })\n}\n\nexport function isWeb() {\n return (\n typeof window !== 'undefined' &&\n typeof window.document !== 'undefined' &&\n typeof window.localStorage !== 'undefined'\n )\n}\n","import { FlowStep, FrigadeConfig, StatefulFlow } from '../core/types'\nimport { Flow } from '../core/flow'\nimport { RulesGraph } from '../core/rules-graph'\n\nexport interface FrigadeGlobalState {\n refreshStateFromAPI: () => Promise<void>\n flowStates: Record<string, StatefulFlow>\n rulesGraph: RulesGraph\n onFlowStateChangeHandlerWrappers: Map<\n (flow: Flow, previousFlow: Flow) => void,\n (flow: Flow, previousFlow: Flow) => void\n >\n onStepStateChangeHandlerWrappers: Map<\n (step: FlowStep, previousStep: FlowStep) => void,\n (flow: Flow, previousFlow: Flow) => void\n >\n onFlowStateChangeHandlers: ((flow: Flow, previousFlow: Flow) => void)[]\n previousFlows: Map<string, Flow>\n variables: Record<string, Record<string, any>>\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}:${internalConfig.userId ?? ''}:${\n internalConfig.groupId ?? ''\n }`\n}\n","import { generateGuestId, getEmptyResponse, getHeaders, gracefulFetch } from './utils'\nimport { FrigadeConfig } from '../core/types'\nimport { frigadeGlobalState, FrigadeGlobalState, getGlobalStateKey } from './state'\n\nexport class Fetchable {\n public config: FrigadeConfig = {\n apiKey: '',\n apiUrl: 'https://api.frigade.com/v1/public',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(36).substring(7),\n }\n\n constructor(config: FrigadeConfig) {\n const filteredConfig = Object.fromEntries(Object.entries(config).filter(([_, v]) => v != null))\n\n this.config = {\n ...this.config,\n ...filteredConfig,\n }\n }\n\n /**\n * @ignore\n */\n public async fetch(path: string, options?: Record<any, any>) {\n if (this.config.__readOnly) {\n return getEmptyResponse()\n }\n\n return gracefulFetch(this.getAPIUrl(path), {\n keepalive: true,\n ...(options ?? {}),\n ...getHeaders(this.config.apiKey),\n })\n }\n\n private getAPIUrl(path: string) {\n const pathPrefix = '/v1/public'\n const apiUrl = new URL(\n `${pathPrefix}${path}`,\n this.config.apiUrl.replace(pathPrefix, '')\n ).toString()\n\n return apiUrl\n }\n\n /**\n * @ignore\n */\n protected getGlobalState(): FrigadeGlobalState {\n const globalStateKey = getGlobalStateKey(this.config)\n if (!frigadeGlobalState[globalStateKey]) {\n throw new Error('Frigade not initialized')\n }\n return frigadeGlobalState[globalStateKey]\n }\n}\n","import { FlowStep, FrigadeConfig, StatefulFlow, StatefulStep } from './types'\nimport {\n clone,\n COMPLETED_FLOW,\n COMPLETED_STEP,\n NOT_STARTED_FLOW,\n NOT_STARTED_STEP,\n SKIPPED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { Fetchable } from '../shared/fetchable'\nimport { RulesGraphRegistryCallback } from './rules-graph'\n\nexport class Flow extends Fetchable {\n /**\n * The Flow's ID.\n */\n public id: string\n /**\n * Ordered map of the Steps in the Flow.\n * See [Flow Step Definition](https://docs.frigade.com/v2/sdk/js/step) for more information.\n */\n public steps: Map<string, FlowStep>\n /**\n * The user-facing title of the Flow, if defined at the top level of the YAML config.\n */\n public title?: string\n /**\n * The user-facing description of the Flow, if defined at the top level of the YAML config.\n */\n public subtitle?: string\n /**\n * The metadata of the Flow.\n * @ignore\n */\n public rawData: StatefulFlow\n /**\n * Whether the Flow is completed or not.\n */\n public isCompleted: boolean\n /**\n * Whether the Flow is started or not.\n */\n public isStarted: boolean\n /**\n * Whether the Flow has been skipped or not.\n */\n public isSkipped: boolean\n /**\n * @ignore\n */\n private _isVisible: boolean = false\n /**\n * Whether the Flow is visible to the user based on the current user/group's state.\n */\n get isVisible() {\n if (this._isVisible === false) {\n return false\n }\n\n return this.getGlobalState().rulesGraph.isFlowVisible(this.id)\n }\n set isVisible(visible: boolean) {\n this._isVisible = visible\n }\n\n /**\n * @ignore\n */\n private lastStepUpdate: Map<(step: FlowStep, previousStep: FlowStep) => void, FlowStep> =\n new Map()\n\n constructor({ config, id }: { config: FrigadeConfig; id: string }) {\n super(config)\n this.id = id\n this.init()\n }\n\n /**\n * Reload the Flow data from the server\n */\n reload() {\n this.init()\n }\n\n /**\n * @ignore\n */\n resyncState(overrideStatefulFlow?: StatefulFlow) {\n const statefulFlow = overrideStatefulFlow ?? this.getStatefulFlow()\n\n this.rawData = statefulFlow\n this.title = statefulFlow?.data?.title\n this.subtitle = statefulFlow?.data?.subtitle\n\n this.isCompleted = statefulFlow.$state.completed\n this.isStarted = statefulFlow.$state.started\n this.isSkipped = statefulFlow.$state.skipped\n this._isVisible = statefulFlow.$state.visible\n\n statefulFlow.data.steps.forEach((step, index) => {\n const stepObj = this.initStepFromStatefulStep(step, index)\n\n const existingStep = this.steps?.get(step.id)\n if (existingStep) {\n existingStep.$state = stepObj.$state\n }\n })\n }\n\n /**\n * @ignore\n */\n private initStepFromStatefulStep(step: StatefulStep, index: number) {\n return {\n ...step,\n flow: this,\n $state: {\n ...step.$state,\n lastActionAt: step.$state.lastActionAt ? new Date(step.$state.lastActionAt) : undefined,\n },\n order: index,\n } as Partial<FlowStep>\n }\n\n /**\n * @ignore\n */\n private init() {\n const statefulFlow = this.getStatefulFlow()\n\n this.resyncState()\n\n const newSteps = new Map<string, FlowStep>()\n\n statefulFlow.data.steps.forEach((step, index) => {\n const stepObj = this.initStepFromStatefulStep(step, index)\n\n stepObj.start = async (properties?: Record<string | number, any>) => {\n const thisStep = this.steps.get(step.id)\n\n if (this.getCurrentStep().id === thisStep.id && thisStep.$state.started) {\n return\n }\n\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.data.steps[thisStep.order].$state.started = true\n copy.data.steps[thisStep.order].$state.lastActionAt = new Date()\n copy.$state.lastActionAt = new Date()\n copy.$state.currentStepId = thisStep.id\n copy.$state.currentStepIndex = thisStep.order\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n if (!thisStep.$state.completed) {\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: thisStep.id,\n data: properties ?? {},\n createdAt: properties?.createdAt\n ? new Date(properties.createdAt)\n : new Date().toISOString(),\n actionType: STARTED_STEP,\n }),\n })\n await this.refreshStateFromAPI()\n }\n }\n\n stepObj.complete = async (properties?: Record<string | number, any>) => {\n const thisStep = this.steps.get(step.id)\n\n if (thisStep.$state.completed) {\n return\n }\n\n const numberOfCompletedSteps = this.getNumberOfCompletedSteps()\n const isLastStep = numberOfCompletedSteps + 1 == this.steps.size\n const copy = clone(this.getGlobalState().flowStates[this.id])\n\n copy.$state.started = true\n copy.data.steps[thisStep.order].$state.completed = true\n copy.data.steps[thisStep.order].$state.started = true\n copy.data.steps[thisStep.order].$state.lastActionAt = new Date()\n if (isLastStep) {\n copy.$state.completed = true\n }\n\n const nextStepId = Array.from(this.steps.keys())[index + 1]\n if (nextStepId) {\n copy.$state.currentStepId = nextStepId\n copy.data.steps[index + 1].$state.started = true\n copy.data.steps[index + 1].$state.lastActionAt = new Date()\n }\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n if (isLastStep) {\n this.optimisticallyMarkFlowCompleted()\n }\n\n // if all steps are now completed, mark flow completed\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: thisStep.id,\n data: properties ?? {},\n createdAt: properties?.createdAt\n ? new Date(properties.createdAt)\n : new Date().toISOString(),\n actionType: COMPLETED_STEP,\n }),\n })\n await this.refreshStateFromAPI()\n }\n\n stepObj.reset = async () => {\n const thisStep = this.steps.get(step.id)\n\n if (!thisStep.$state.completed) {\n return\n }\n\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.data.steps[thisStep.order].$state.started = false\n copy.data.steps[thisStep.order].$state.completed = false\n copy.data.steps[thisStep.order].$state.lastActionAt = undefined\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: thisStep.id,\n data: {},\n createdAt: new Date().toISOString(),\n actionType: NOT_STARTED_STEP,\n }),\n })\n await this.refreshStateFromAPI()\n }\n\n stepObj.onStateChange = (handler: (step: FlowStep, previousStep: FlowStep) => void) => {\n const wrapperHandler = (flow: Flow) => {\n if (flow.id !== this.id) {\n return\n }\n const thisStep = flow.steps.get(step.id)\n const previousStep = this.lastStepUpdate.get(handler)\n\n if (\n thisStep.$state.completed !== previousStep?.$state.completed ||\n thisStep.$state.started !== previousStep?.$state.started ||\n thisStep.$state.visible !== previousStep?.$state.visible ||\n thisStep.$state.blocked !== previousStep?.$state.blocked\n ) {\n handler(thisStep, previousStep ?? clone(thisStep))\n this.lastStepUpdate.set(handler, clone(thisStep))\n }\n }\n this.getGlobalState().onStepStateChangeHandlerWrappers.set(handler, wrapperHandler)\n this.getGlobalState().onFlowStateChangeHandlers.push(wrapperHandler)\n }\n\n stepObj.removeStateChangeHandler = (\n handler: (step: FlowStep, previousStep: FlowStep) => void\n ) => {\n const wrapperHandler = this.getGlobalState().onStepStateChangeHandlerWrappers.get(handler)\n if (wrapperHandler) {\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== wrapperHandler)\n }\n }\n\n newSteps.set(step.id, stepObj as FlowStep)\n })\n this.steps = newSteps\n // Check if empty object\n if (\n this.getGlobalState().variables &&\n this.getGlobalState().variables[this.id] &&\n Object.keys(this.getGlobalState().variables[this.id]).length > 0\n ) {\n this.applyVariables(this.getGlobalState().variables[this.id])\n }\n }\n\n /**\n * Marks the flow started\n */\n public async start(properties?: Record<string | number, any>) {\n if (this.isStarted || this.isCompleted) {\n return\n }\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.started = true\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_FLOW,\n }),\n })\n await this.refreshStateFromAPI()\n }\n\n /**\n * Marks the flow completed\n */\n public async complete(properties?: Record<string | number, any>) {\n if (this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowCompleted()\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: properties?.createdAt\n ? new Date(properties.createdAt)\n : new Date().toISOString(),\n actionType: COMPLETED_FLOW,\n }),\n })\n\n await this.refreshStateFromAPI()\n }\n\n /**\n * Marks the flow skipped\n */\n public async skip(properties?: Record<string | number, any>) {\n if (this.isSkipped) {\n return\n }\n\n this.optimisticallyMarkFlowSkipped()\n\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: this.getCurrentStep().id,\n data: properties ?? {},\n createdAt: properties?.createdAt\n ? new Date(properties.createdAt)\n : new Date().toISOString(),\n actionType: SKIPPED_FLOW,\n }),\n })\n await this.refreshStateFromAPI()\n }\n\n /**\n * Navigates the flow to the next step if one exists. This will mark that step started, but will not complete the previous step.\n */\n public async forward(properties?: Record<string | number, any>) {\n const nextStep = this.getStepByIndex(this.getCurrentStepIndex() + 1)\n if (nextStep) {\n await nextStep.start(properties)\n }\n }\n\n /**\n * Navigates the flow to the previous step if one exists. This will mark that step started, but will not complete the previous step.\n */\n public async back(properties?: Record<string | number, any>) {\n const previousStep = this.getStepByIndex(this.getCurrentStepIndex() - 1)\n if (previousStep) {\n await previousStep.start(properties)\n }\n }\n\n /**\n * Restarts the flow/marks it not started\n */\n public async restart() {\n await this.fetch('/flowResponses', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n flowSlug: this.id,\n stepId: 'unknown',\n data: {},\n createdAt: new Date().toISOString(),\n actionType: NOT_STARTED_FLOW,\n }),\n })\n\n await this.refreshStateFromAPI()\n }\n\n /**\n * Get a step by index\n * @param index\n */\n public getStepByIndex(index: number): FlowStep | undefined {\n return this.steps.get(Array.from(this.steps.keys())[index])\n }\n\n /**\n * Gets current step\n */\n public getCurrentStep(): FlowStep {\n let maybeCurrentStepId = Array.from(this.steps.keys()).find(\n (key) =>\n this.steps.get(key).$state.completed === false &&\n this.steps.get(key).$state.visible !== false\n )\n Array.from(this.steps.keys()).forEach((key) => {\n if (\n this.steps.get(key).$state.started &&\n this.steps.get(key).$state.lastActionAt &&\n this.steps.get(key).$state.lastActionAt >\n (this.steps.get(maybeCurrentStepId)?.$state.lastActionAt ?? new Date(0))\n ) {\n maybeCurrentStepId = key\n }\n })\n\n const currentStepId = maybeCurrentStepId ?? Array.from(this.steps.keys())[0]\n return this.steps.get(currentStepId)\n }\n\n /**\n * Get the index of the current step. Starts at 0\n */\n public getCurrentStepIndex(): number {\n const currentStep = this.getCurrentStep()\n return Array.from(this.steps.keys()).indexOf(currentStep.id)\n }\n\n /**\n * Get the number of completed steps for the current user in the current flow\n */\n public getNumberOfCompletedSteps(): number {\n return Array.from(this.steps.values()).filter((step) => step.$state.completed).length\n }\n\n /**\n * Get the number of available steps for the current user in the current flow. This is the number of steps that are not hidden.\n */\n public getNumberOfAvailableSteps(): number {\n return Array.from(this.steps.values()).filter((step) => step.$state.visible).length\n }\n\n /**\n * @ignore\n */\n public onStateChange(handler: (flow: Flow, previousFlow: Flow) => void) {\n const wrapperHandler = (flow: Flow, previousFlow: Flow) => {\n if (\n (flow.id === this.id &&\n (flow.isCompleted !== previousFlow?.isCompleted ||\n flow.isStarted !== previousFlow?.isStarted ||\n flow.isSkipped !== previousFlow?.isSkipped ||\n flow.isVisible !== previousFlow?.isVisible)) ||\n JSON.stringify(flow.steps) !== JSON.stringify(previousFlow?.steps)\n ) {\n handler(flow, previousFlow)\n }\n }\n this.getGlobalState().onFlowStateChangeHandlerWrappers.set(handler, wrapperHandler)\n this.getGlobalState().onFlowStateChangeHandlers.push(wrapperHandler)\n }\n\n /**\n * @ignore\n */\n public removeStateChangeHandler(handler: (flow: Flow, previousFlow: Flow) => void) {\n const wrapperHandler = this.getGlobalState().onFlowStateChangeHandlerWrappers.get(handler)\n if (wrapperHandler) {\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== wrapperHandler)\n }\n }\n\n /**\n * @ignore\n */\n public applyVariables(variables: Record<string, any>) {\n // Replace ${variable} with the value of the variable\n const replaceVariables = (str: string) => {\n const matches = str.match(/\\${(.*?)}/g)\n if (matches) {\n matches.forEach((match) => {\n const variable = match.replace('${', '').replace('}', '')\n if (!variables[variable]) {\n return\n }\n str = str.replace(match, variables[variable])\n })\n }\n return str\n }\n\n this.title = replaceVariables(this.title ?? '')\n this.subtitle = replaceVariables(this.subtitle ?? '')\n this.steps.forEach((step) => {\n // Iterate over every string field in the step and replace variables\n Object.keys(step).forEach((key) => {\n if (typeof step[key] === 'string') {\n // @ts-ignore\n step[key] = replaceVariables(step[key])\n }\n })\n })\n\n this.getGlobalState().variables = {}\n this.getGlobalState().variables[this.id] = variables\n }\n\n /**\n * @ignore\n */\n private getStatefulFlow(): StatefulFlow {\n const userFlowStates = this.getGlobalState().flowStates\n return userFlowStates[this.id]\n }\n\n /**\n * @ignore\n */\n private async refreshStateFromAPI() {\n await this.getGlobalState().refreshStateFromAPI()\n this.resyncState()\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowCompleted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = true\n copy.$state.started = true\n copy.$state.visible = false\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n /**\n * @ignore\n */\n private optimisticallyMarkFlowSkipped() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.skipped = true\n copy.$state.visible = false\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n public register(callback?: RulesGraphRegistryCallback) {\n this.getGlobalState().rulesGraph.register(this.id, callback)\n }\n\n public unregister() {\n this.getGlobalState().rulesGraph.unregister(this.id)\n }\n}\n","export interface RulesGraphNode {\n visible: boolean\n edges: RulesGraphEdge[]\n}\n\nexport interface RulesGraphEdge {\n head: string\n ruleId: string\n}\n\nexport type RulesGraphRegistryCallback = (visible: boolean) => void\n\nexport type RulesGraphData = [string, RulesGraphNode][]\n\n// TODO: JSDoc this class\nexport class RulesGraph {\n private graph: Map<string, RulesGraphNode> = new Map()\n private readonly registry: Map<string, RulesGraphRegistryCallback> = new Map()\n private readonly _rawGraphData: Record<string, RulesGraphNode>\n public get rawGraphData() {\n return this._rawGraphData\n }\n\n constructor(\n graphData: Record<string, RulesGraphNode>,\n registry?: Map<string, RulesGraphRegistryCallback>\n ) {\n this._rawGraphData = graphData\n if (registry) {\n this.registry = registry\n }\n this.ingestGraphData(graphData)\n }\n\n ingestGraphData(graphData: Record<string, RulesGraphNode>) {\n this.graph = new Map(Object.entries(graphData))\n\n this.fireCallbacks()\n }\n\n fireCallbacks() {\n for (const [flowId, callback] of this.registry) {\n if (typeof callback === 'function') {\n callback(this.isFlowVisible(flowId))\n }\n }\n }\n\n isFlowVisible(flowId: string) {\n const currentNode = this.graph.get(flowId)\n\n // Is the flow in the graph?\n // If not, it belongs to 0 rules and can carry on about its business\n if (!currentNode) {\n return true\n }\n\n if (currentNode.visible === false) {\n return false\n }\n\n // Does the flow have edges?\n // If not, it's the king of all flows, and it does what it wants\n if (currentNode.edges.length === 0) {\n return true\n }\n\n // Are any of the flow's descendants visible and in the registry already?\n const registeredDescendant = this.findRegisteredDescendant(flowId)\n\n // If so, this flow is not visible\n if (registeredDescendant != null) {\n return false\n }\n\n // Congrats! There are no conditions in the graph that disqualify this flow from being visible\n return true\n }\n\n register(flowId: string, callback?: RulesGraphRegistryCallback) {\n this.registry.set(flowId, callback)\n\n this.fireCallbacks()\n }\n\n unregister(flowId: string) {\n this.registry.delete(flowId)\n\n this.fireCallbacks()\n }\n\n getRegistry() {\n return this.registry\n }\n\n private findRegisteredDescendant(nodeId: string, originId = nodeId, ruleId?: string) {\n const node = this.graph.get(nodeId)\n\n if (node == null) {\n return undefined\n }\n\n if (this.registry.has(nodeId) && originId !== nodeId) {\n return node\n }\n\n let result = undefined\n\n if (node.edges.length > 0) {\n for (const edge of node.edges) {\n // If we went past the end of the rule, stop searching for this rule\n if (ruleId != null && edge.ruleId !== ruleId) {\n continue\n }\n\n const ancestor = this.findRegisteredDescendant(edge.head, originId, ruleId ?? edge.ruleId)\n\n if (ancestor != null && ancestor.visible) {\n result = ancestor\n break\n }\n }\n }\n\n return result\n }\n}\n","import { FlowState, FrigadeConfig, StatefulFlow, StatefulStep } from './types'\nimport { clearCache, cloneFlow, GUEST_PREFIX, isWeb, resetAllLocalStorage } from '../shared/utils'\nimport { Flow } from './flow'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\nimport { Fetchable } from '../shared/fetchable'\nimport { RulesGraph } from './rules-graph'\n\nexport class Frigade extends Fetchable {\n /**\n * @ignore\n */\n private flows: Flow[] = []\n /**\n * @ignore\n */\n private initPromise: Promise<void>\n /**\n * @ignore\n */\n private hasFailed = false\n\n /**\n * @ignore\n */\n private visibilityChangeHandler = async () => {\n if (document.visibilityState === 'visible') {\n await this.refreshStateFromAPI()\n\n // // Trigger all event handlers\n // this.flows.forEach((flow) => {\n // this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n // const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n // handler(flow, lastFlow)\n // this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n // })\n // })\n }\n }\n\n constructor(apiKey: string, config?: FrigadeConfig) {\n super({\n apiKey,\n ...config,\n })\n this.init(this.config)\n if (isWeb()) {\n document.addEventListener('visibilitychange', this.visibilityChangeHandler)\n }\n }\n\n /**\n * @ignore\n */\n destroy() {\n if (isWeb()) {\n document.removeEventListener('visibilitychange', this.visibilityChangeHandler)\n // Remove all other event listeners\n const globalStateKey = getGlobalStateKey(this.config)\n if (frigadeGlobalState[globalStateKey]) {\n frigadeGlobalState[globalStateKey].onFlowStateChangeHandlers = []\n }\n }\n }\n\n /**\n * @ignore\n */\n private async init(config: FrigadeConfig): Promise<void> {\n this.config = {\n ...this.config,\n ...config,\n }\n\n this.initPromise = (async () => {\n if (this.config.userId && !this.config.userId?.startsWith(GUEST_PREFIX)) {\n await this.fetch('/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.config.userId,\n }),\n })\n }\n await this.refreshStateFromAPI()\n })()\n\n return this.initPromise\n }\n\n /**\n * Set the current user.\n * @param userId\n * @param properties\n */\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n this.config = { ...this.config, userId }\n await this.initIfNeeded()\n await this.fetch('/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.config.userId,\n properties,\n }),\n })\n await this.resync()\n }\n\n /**\n * Set the group for the current user.\n * @param groupId\n * @param properties\n */\n public async group(groupId: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n this.config.groupId = groupId\n await this.fetch('/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n properties,\n }),\n })\n await this.resync()\n }\n\n /**\n * Track an event for the current user (and group if set).\n * @param event\n * @param properties\n */\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n await this.initIfNeeded()\n if (!event) {\n console.error('Event name is required to track an event')\n return\n }\n if (this.config.userId && this.config.groupId) {\n await this.fetch('/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.config.userId,\n foreignUserGroupId: this.config.groupId,\n events: [\n {\n event,\n properties,\n },\n ],\n }),\n })\n } else if (this.config.userId) {\n await this.fetch('/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.config.userId,\n events: [\n {\n event,\n properties,\n },\n ],\n }),\n })\n }\n await this.resync()\n }\n\n /**\n * @ignore\n */\n public isReady(): boolean {\n return Boolean(this.config.__instanceId && this.config.apiKey && this.initPromise)\n }\n\n /**\n * Get a Flow by its ID.\n * @param flowId\n */\n public async getFlow(flowId: string) {\n await this.initIfNeeded()\n\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n public async getFlows() {\n await this.initIfNeeded()\n return this.flows\n }\n\n /**\n * Reload the current state of the flows by calling the Frigade API.\n * This will trigger all event handlers.\n */\n public async reload() {\n resetAllLocalStorage()\n clearCache()\n await this.refreshStateFromAPI()\n this.initPromise = null\n await this.init(this.config)\n // Trigger all event handlers\n this.flows.forEach((flow) => {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n })\n }\n\n private async resync() {\n this.initPromise = null\n await this.init(this.config)\n this.flows.forEach((flow) => {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n })\n }\n\n /**\n * Event handler that captures all changes that happen to the state of the Flows.\n * @param handler\n */\n public async onStateChange(handler: (flow: Flow, previousFlow?: Flow) => void) {\n await this.initIfNeeded()\n this.getGlobalState().onFlowStateChangeHandlers.push(handler)\n }\n\n /**\n * Returns true if the JS SDK failed to connect to the Frigade API.\n */\n hasFailedToLoad() {\n return this.hasFailed\n }\n\n /**\n * Removes the given handler from the list of event handlers.\n * @param handler\n */\n public async removeStateChangeHandler(handler: (flow: Flow, previousFlow?: Flow) => void) {\n await this.initIfNeeded()\n this.getGlobalState().onFlowStateChangeHandlers =\n this.getGlobalState().onFlowStateChangeHandlers.filter((h) => h !== handler)\n }\n\n /**\n * @ignore\n */\n private async initIfNeeded() {\n if (this.initPromise !== null) {\n return this.initPromise\n } else {\n return this.init(this.config)\n }\n }\n\n /**\n * @ignore\n */\n private async refreshStateFromAPI(): Promise<void> {\n const globalStateKey = getGlobalStateKey(this.config)\n\n if (!frigadeGlobalState[globalStateKey]) {\n const that = this\n\n let validator = {\n set: function (target: any, key: any, value: any) {\n if (target[key]) {\n const previousState = target[key] as StatefulFlow\n const newState = value as StatefulFlow\n if (JSON.stringify(previousState) !== JSON.stringify(newState)) {\n that.triggerEventHandlers(newState, previousState)\n }\n }\n\n target[key] = value\n return true\n },\n }\n\n frigadeGlobalState[globalStateKey] = {\n refreshStateFromAPI: async () => {},\n rulesGraph: new RulesGraph({}),\n flowStates: new Proxy({}, validator),\n onFlowStateChangeHandlerWrappers: new Map(),\n onStepStateChangeHandlerWrappers: new Map(),\n onFlowStateChangeHandlers: [],\n previousFlows: new Map(),\n variables: {},\n }\n\n if (this.config.__readOnly && this.config.__flowConfigOverrides) {\n this.mockFlowStates(globalStateKey)\n\n return\n }\n\n frigadeGlobalState[globalStateKey].refreshStateFromAPI = async () => {\n if (this.config.__readOnly) {\n return\n }\n\n const flowStatesRaw: FlowState = await this.fetch(\n `/flowStates?userId=${encodeURIComponent(this.config.userId)}${\n this.config.groupId ? `&groupId=${encodeURIComponent(this.config.groupId)}` : ''\n }`\n )\n\n const hasRuleGraphChanged =\n JSON.stringify(frigadeGlobalState[globalStateKey].rulesGraph.rawGraphData) !==\n JSON.stringify(flowStatesRaw.ruleGraph?.graph)\n\n frigadeGlobalState[globalStateKey].rulesGraph = new RulesGraph(\n flowStatesRaw.ruleGraph?.graph ?? {},\n frigadeGlobalState[globalStateKey]?.rulesGraph?.getRegistry()\n )\n\n // Call all event handlers for the flows in the rulesgraph\n if (hasRuleGraphChanged) {\n this.flows.forEach((flow) => {\n if (flowStatesRaw.ruleGraph?.graph[flow.id]) {\n const flowState = flowStatesRaw.eligibleFlows.find((f) => f.flowSlug === flow.id)\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n flow.resyncState(flowState)\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n }\n })\n }\n\n if (flowStatesRaw && flowStatesRaw.eligibleFlows) {\n flowStatesRaw.eligibleFlows.forEach((statefulFlow) => {\n frigadeGlobalState[globalStateKey].flowStates[statefulFlow.flowSlug] = statefulFlow\n if (!this.flows.find((flow) => flow.id == statefulFlow.flowSlug)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: statefulFlow.flowSlug,\n })\n )\n }\n })\n this.hasFailed = false\n } else {\n this.hasFailed = true\n }\n }\n }\n\n await frigadeGlobalState[globalStateKey].refreshStateFromAPI()\n }\n\n /**\n * @ignore\n */\n private mockFlowConfigs() {\n Object.keys(this.config.__flowConfigOverrides).forEach((flowId) => {\n this.flows.push(\n new Flow({\n config: this.config,\n id: flowId,\n })\n )\n })\n }\n\n /**\n * @ignore\n */\n private mockFlowStates(globalStateKey: string) {\n Object.keys(this.config.__flowConfigOverrides).forEach((flowId) => {\n const parsed = JSON.parse(this.config.__flowConfigOverrides[flowId])\n frigadeGlobalState[globalStateKey].flowStates[flowId] = {\n flowSlug: flowId,\n flowName: parsed?.name ?? flowId,\n flowType: parsed?.type ?? 'CHECKLIST',\n data: {\n ...parsed,\n steps: (parsed?.steps ?? []).map((step: any): StatefulStep => {\n return {\n id: step.id,\n $state: {\n completed: false,\n started: false,\n visible: true,\n blocked: false,\n },\n ...step,\n }\n }),\n },\n $state: {\n currentStepId: null,\n currentStepIndex: -1,\n completed: false,\n started: false,\n skipped: false,\n visible: true,\n },\n } as StatefulFlow\n\n this.flows.push(\n new Flow({\n config: this.config,\n id: flowId,\n })\n )\n })\n }\n\n /**\n * @ignore\n */\n private async triggerEventHandlers(newState: StatefulFlow, previousState?: StatefulFlow) {\n if (newState) {\n this.flows.forEach((flow) => {\n if (flow.id == previousState.flowSlug) {\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n const lastFlow = this.getGlobalState().previousFlows.get(flow.id)\n flow.resyncState(newState)\n handler(flow, lastFlow)\n this.getGlobalState().previousFlows.set(flow.id, cloneFlow(flow))\n })\n }\n })\n }\n }\n}\n","import type { Flow } from './flow'\n\nimport { RulesGraphNode } from './rules-graph'\n\nexport enum TriggerType {\n MANUAL = 'MANUAL',\n AUTOMATIC = 'AUTOMATIC',\n}\n\nexport enum FlowStatus {\n DRAFT = 'DRAFT',\n ACTIVE = 'ACTIVE',\n ARCHIVED = 'ARCHIVED',\n}\n\nexport type StepAction =\n | 'flow.back'\n | 'flow.complete'\n | 'flow.forward'\n | 'flow.restart'\n | 'flow.skip'\n | 'flow.start'\n | 'step.complete'\n | 'step.reset'\n | 'step.start'\n | false\n\nexport interface FlowStep extends StatefulStep {\n /**\n * Order of the step in the Flow.\n */\n order: number\n\n /**\n * Name of the step when shown in a list view.\n */\n stepName?: string\n\n /**\n * Title of the step.\n */\n title?: string\n\n /**\n * Subtitle of the step.\n */\n subtitle?: string\n\n /**\n * Config for the primary button in this step\n */\n primaryButton?: {\n /**\n * Primary button action. (defaults to step.complete)\n */\n action?: StepAction\n\n /**\n * Primary button URI target (defaults to _self).\n */\n target?: string\n\n /**\n * Primary button title. If omitted, the primary button will not be shown.\n */\n title?: string\n\n /**\n * Primary button URI.\n */\n uri?: string\n }\n\n /**\n * @deprecated use primaryButton.title instead\n * Primary button title. If omitted, the primary button will not be shown.\n */\n primaryButtonTitle?: string\n\n /**\n * @deprecated use primaryButton.uri instead\n * Primary button URI.\n */\n primaryButtonUri?: string\n\n /**\n * @deprecated use primaryButton.target instead\n * Primary button URI target (defaults to _self).\n */\n primaryButtonUriTarget?: string\n\n /**\n * Config for the secondary button in this step\n */\n secondaryButton?: {\n /**\n * Secondary button action. (defaults to step.complete)\n */\n action?: StepAction\n\n /**\n * Secondary button URI target (defaults to _self).\n */\n target?: string\n\n /**\n * Secondary button title. If omitted, the secondary button will not be shown.\n */\n title?: string\n\n /**\n * Secondary button URI.\n */\n uri?: string\n }\n\n /**\n * @deprecated use secondaryButton.title instead\n * Secondary button title. If omitted, the secondary button will not be shown.\n */\n secondaryButtonTitle?: string\n\n /**\n * @deprecated use secondaryButton.uri instead\n * Secondary button URI.\n */\n secondaryButtonUri?: string\n\n /**\n * @deprecated use secondaryButton.target instead\n * Secondary button URI target (defaults to _self)\n */\n secondaryButtonUriTarget?: string\n\n /**\n * Text on button if a back button is present.\n */\n backButtonTitle?: string\n\n /**\n * If true, the step will be marked as completed when the secondary button is clicked.\n */\n skippable?: boolean\n\n /**\n * Video url to be shown for components supporting video.\n */\n videoUri?: string\n\n /**\n * Image url to be shown for components supporting image.\n */\n imageUri?: string | null\n\n /**\n * Automatically mark the step as completed when the primary button is clicked. Default is false.\n */\n autoMarkCompleted?: boolean\n\n /**\n * @ignore\n */\n props?: any\n /**\n * Criteria that needs to be met for the step to complete.\n * Completion criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be completed.\n */\n completionCriteria?: string\n\n /**\n * Criteria that needs to be met for the step to start.\n * Start criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be started.\n */\n startCriteria?: string\n\n /**\n * Criteria that needs to be met for the step to be visible.\n * Visibility criteria uses Frigade's [Targeting Engine](https://docs.frigade.com/v2/platform/targeting) to determine if the step should be visible.\n */\n visibilityCriteria?: string\n\n /**\n * Progress if the step is tied to another Frigade Flow through completionCriteria.\n */\n progress?: number\n\n /**\n * Whether the step is dismissible (for instance, tooltips or other non-essential steps).\n */\n dismissible?: boolean\n\n /**\n * Any other additional props defined in the YAML config.\n */\n [x: string | number | symbol]: unknown\n\n /**\n * Marks the step started.\n */\n start: (properties?: Record<string | number, any>) => Promise<void>\n\n /**\n * Marks the step completed.\n */\n complete: (properties?: Record<string | number, any>) => Promise<void>\n\n /**\n * Resets the step (useful for undoing a finished step).\n */\n reset: () => Promise<void>\n\n /**\n * Event handler called when this step's state changes.\n */\n onStateChange: (callback: (step: FlowStep, previousStep?: FlowStep) => void) => void\n\n /**\n * Removes the given callback from the list of event handlers.\n */\n removeStateChangeHandler: (callback: (step: FlowStep, previousStep?: FlowStep) => void) => void\n\n /**\n * Reference to this step's parent Flow\n */\n flow: Flow\n}\n\nexport interface FrigadeConfig {\n /**\n * Frigade API key. You can find your API key in the Frigade Dashboard under \"Developer\".\n */\n apiKey?: string\n /**\n * API url to use for all requests. Defaults to https://api.frigade.com\n */\n apiUrl?: string\n\n /**\n * User ID to use for all requests. If not provided, a Guest ID will be generated.\n */\n userId?: string\n\n /**\n * Group ID (organization) to use for all requests.\n */\n groupId?: string\n\n /**\n * @ignore Internal use only.\n * If enabled, Frigade will not send any data to the API. A user's state will be reset on page refresh.\n */\n __readOnly?: boolean\n\n /**\n * @ignore Internal use only.\n * Map of Flow ID to Flow Config for all flows in the app.\n * Configs will have to be provided in serialized JSON format rather than YAML.\n */\n __flowConfigOverrides?: Record<string, string>\n\n /**\n * @ignore Internal use only.\n */\n __instanceId?: string\n}\n\nexport interface StatefulStep {\n id: string\n $state: {\n completed: boolean\n started: boolean\n visible: boolean\n blocked: boolean\n lastActionAt?: Date\n }\n // allow any other properties\n [key: string]: any\n}\n\nexport interface StatefulFlow {\n flowSlug: string\n flowName: string\n flowType: FlowType\n data: {\n steps: StatefulStep[]\n // allow any other properties\n [key: string]: any\n }\n $state: {\n currentStepId: string\n currentStepIndex: number\n completed: boolean\n started: boolean\n skipped: boolean\n visible: boolean\n lastActionAt?: Date\n }\n}\n\nexport interface FlowState {\n eligibleFlows: StatefulFlow[]\n ineligibleFlows: string[]\n ruleGraph?: {\n graph: Record<string, RulesGraphNode>\n }\n}\n\nexport interface InternalConfig {\n apiKey: string\n userId?: string\n organizationId?: string\n __instanceId?: string\n}\n\nexport enum FlowType {\n ANNOUNCEMENT = 'ANNOUNCEMENT',\n CHECKLIST = 'CHECKLIST',\n FORM = 'FORM',\n TOUR = 'TOUR',\n SUPPORT = 'SUPPORT',\n CUSTOM = 'CUSTOM',\n BANNER = 'BANNER',\n EMBEDDED_TIP = 'EMBEDDED_TIP',\n NPS_SURVEY = 'NPS_SURVEY',\n SURVEY = 'SURVEY',\n CARD = 'CARD',\n}\n"],"mappings":";kmCAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,UAAAE,EAAA,eAAAC,EAAA,aAAAC,EAAA,YAAAC,EAAA,gBAAAC,IAAA,eAAAC,GAAAP,IC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Ac,UAC3B,KAAK,eAAe,EAAE,0BAA0B,QAAST,GAAY,CACnE,IAAMC,EAAW,KAAK,eAAe,EAAE,cAAc,IAAIJ,EAAK,EAAE,EAChEA,EAAK,YAAYa,CAAQ,EACzBV,EAAQH,EAAMI,CAAQ,EACtB,KAAK,eAAe,EAAE,cAAc,IAAIJ,EAAK,GAAIK,EAAUL,CAAI,CAAC,CAClE,CAAC,CAEL,CAAC,CAEL,GACF,EC3aO,IAAK2B,OACVA,EAAA,OAAS,SACTA,EAAA,UAAY,YAFFA,OAAA,IAKAC,OACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SACTA,EAAA,SAAW,WAHDA,OAAA,IAiTAC,OACVA,EAAA,aAAe,eACfA,EAAA,UAAY,YACZA,EAAA,KAAO,OACPA,EAAA,KAAO,OACPA,EAAA,QAAU,UACVA,EAAA,OAAS,SACTA,EAAA,OAAS,SACTA,EAAA,aAAe,eACfA,EAAA,WAAa,aACbA,EAAA,OAAS,SACTA,EAAA,KAAO,OAXGA,OAAA","names":["src_exports","__export","Flow","FlowStatus","FlowType","Frigade","TriggerType","__toCommonJS","VERSION_NUMBER","import_cross_fetch","import_uuid","frigadeGlobalState","getGlobalStateKey","internalConfig","_a","_b","Fetchable","config","generateGuestId","filteredConfig","_","v","__spreadValues","path","options","__async","getEmptyResponse","gracefulFetch","getHeaders","pathPrefix","globalStateKey","getGlobalStateKey","frigadeGlobalState","Flow","Fetchable","config","id","visible","overrideStatefulFlow","_a","_b","statefulFlow","step","index","stepObj","existingStep","__spreadProps","__spreadValues","newSteps","properties","__async","thisStep","copy","clone","STARTED_STEP","isLastStep","nextStepId","COMPLETED_STEP","NOT_STARTED_STEP","handler","wrapperHandler","flow","previousStep","h","STARTED_FLOW","COMPLETED_FLOW","SKIPPED_FLOW","nextStep","NOT_STARTED_FLOW","maybeCurrentStepId","key","currentStepId","currentStep","previousFlow","variables","replaceVariables","str","matches","match","variable","callback","NOT_STARTED_STEP","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","GUEST_KEY","GUEST_PREFIX","GET_CACHE_PREFIX","POST_CACHE_TTL_MS","LOCAL_STORAGE_PREFIX","cloneFlow","flow","Flow","clone","obj","getHeaders","apiKey","VERSION_NUMBER","getLocalStorage","key","isWeb","setLocalStorage","value","clearCache","frigadeGlobalState","key","GET_CACHE_PREFIX","resetAllLocalStorage","isWeb","LOCAL_STORAGE_PREFIX","gracefulFetch","url","options","__async","lastCallAtKey","LAST_POST_CALL_AT","lastCallDataKey","LAST_POST_CALL_DATA","lastCall","getLocalStorage","lastCallData","lastCallDate","POST_CACHE_TTL_MS","getEmptyResponse","setLocalStorage","response","fetch","error","body","e","generateGuestId","guestId","GUEST_KEY","GUEST_PREFIX","uuidv4","isWeb","RulesGraph","graphData","registry","flowId","callback","currentNode","nodeId","originId","ruleId","node","result","edge","ancestor","Frigade","Fetchable","apiKey","config","__spreadValues","__async","isWeb","globalStateKey","getGlobalStateKey","frigadeGlobalState","_a","GUEST_PREFIX","userId","properties","__spreadProps","groupId","event","flowId","flow","resetAllLocalStorage","clearCache","handler","lastFlow","cloneFlow","h","that","validator","target","key","value","previousState","newState","RulesGraph","_b","_c","_d","_e","flowStatesRaw","hasRuleGraphChanged","flowState","f","statefulFlow","Flow","parsed","step","TriggerType","FlowStatus","FlowType"]}