@frigade/js 0.4.17 → 0.4.19

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 v=Object.defineProperty,tt=Object.defineProperties,et=Object.getOwnPropertyDescriptor,it=Object.getOwnPropertyDescriptors,st=Object.getOwnPropertyNames,$=Object.getOwnPropertySymbols;var M=Object.prototype.hasOwnProperty,at=Object.prototype.propertyIsEnumerable;var k=(a,s,t)=>s in a?v(a,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[s]=t,h=(a,s)=>{for(var t in s||(s={}))M.call(s,t)&&k(a,t,s[t]);if($)for(var t of $(s))at.call(s,t)&&k(a,t,s[t]);return a},m=(a,s)=>tt(a,it(s));var rt=(a,s)=>{for(var t in s)v(a,t,{get:s[t],enumerable:!0})},ot=(a,s,t,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of st(s))!M.call(a,i)&&i!==t&&v(a,i,{get:()=>s[i],enumerable:!(e=et(s,i))||e.enumerable});return a};var nt=a=>ot(v({},"__esModule",{value:!0}),a);var d=(a,s,t)=>new Promise((e,i)=>{var r=l=>{try{o(t.next(l))}catch(c){i(c)}},g=l=>{try{o(t.throw(l))}catch(c){i(c)}},o=l=>l.done?e(l.value):Promise.resolve(l.value).then(r,g);o((t=t.apply(a,s)).next())});var dt={};rt(dt,{Flow:()=>b,FlowStatus:()=>_,FlowType:()=>G,Frigade:()=>P,TriggerType:()=>O});module.exports=nt(dt);var N="0.2.20";var Y=require("uuid");var f={};function w(a){return`${a.__instanceId}-${a.apiKey}`}var F=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:U(),__instanceId:Math.random().toString(12).substring(4)};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));this.config=h(h({},this.config),t)}fetch(s,t){return d(this,null,function*(){return this.config.__readOnly?u():H(this.getAPIUrl(s),h(h({keepalive:!0},t!=null?t:{}),L(this.config.apiKey)))})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=w(this.config);if(!f[s])throw new Error("Frigade has not yet been initialized");return f[s]}};var b=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().rules.isFlowVisible(this.id)}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,r,g;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((o,l)=>{var n;let c=this.initStepFromStatefulStep(o,l),p=(n=this.steps)==null?void 0:n.get(o.id);p&&Object.keys(c).forEach(I=>{p[I]=c[I]})}),this.steps&&this.steps.size>0&&this.applyVariables((g=this.getGlobalState().variables[this.id])!=null?g:{})}initStepFromStatefulStep(t,e){return m(h({},t),{flow:this,$state:m(h({},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 g=this.initStepFromStatefulStep(i,r);g.start=o=>d(this,null,function*(){let l=this.steps.get(i.id);if(this.getCurrentStep().id===l.id&&l.$state.started)return;let c=S(this.getGlobalState().flowStates[this.id]);c.data.steps[l.order].$state.started=!0,c.data.steps[l.order].$state.lastActionAt=new Date,c.$state.lastActionAt=new Date,c.$state.currentStepId=l.id,c.$state.currentStepIndex=l.order,this.getGlobalState().flowStates[this.id]=c,this.resyncState(),l.$state.completed||(yield this.sendFlowStateToAPI(q,o,l.id))}),g.complete=(o,l=!0)=>d(this,null,function*(){let c=this.steps.get(i.id);if(!c.$state.completed){if(l){let p=c.order+1===this.getNumberOfAvailableSteps(),n=S(this.getGlobalState().flowStates[this.id]);n.$state.started=!0,n.data.steps[c.order].$state.completed=!0,n.data.steps[c.order].$state.started=!0,n.data.steps[c.order].$state.lastActionAt=new Date,p||(n.$state.currentStepId=this.getStepByIndex(c.order+1).id,n.$state.currentStepIndex=c.order+1),p&&(n.$state.completed=!0),this.getGlobalState().flowStates[this.id]=n,this.resyncState(),p&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(J,o,c.id)}}),g.reset=()=>d(this,null,function*(){let o=this.steps.get(i.id);if(!o.$state.completed)return;let l=S(this.getGlobalState().flowStates[this.id]);l.data.steps[o.order].$state.started=!1,l.data.steps[o.order].$state.completed=!1,l.data.steps[o.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=l,this.resyncState(),yield this.sendFlowStateToAPI(V,void 0,o.id)}),g.onStateChange=o=>{let l=c=>{if(c.id!==this.id)return;let p=c.steps.get(i.id),n=this.lastStepUpdate.get(o);(p.$state.completed!==(n==null?void 0:n.$state.completed)||p.$state.started!==(n==null?void 0:n.$state.started)||p.$state.visible!==(n==null?void 0:n.$state.visible)||p.$state.blocked!==(n==null?void 0:n.$state.blocked))&&(o(p,n!=null?n:S(p)),this.lastStepUpdate.set(o,S(p)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(o,l),this.getGlobalState().onFlowStateChangeHandlers.push(l)},g.removeStateChangeHandler=o=>{let l=this.getGlobalState().onStepStateChangeHandlerWrappers.get(o);l&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(c=>c!==l))},e.set(i.id,g)}),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 d(this,null,function*(){if(this.isStarted||this.isCompleted)return;let e=S(this.getGlobalState().flowStates[this.id]);e.$state.started=!0,this.getGlobalState().flowStates[this.id]=e,this.resyncState(),yield this.sendFlowStateToAPI(K,t)})}complete(t){return d(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(W,t))})}skip(t){return d(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(B,t))})}forward(t){return d(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()+1);e?yield e.start(t):yield this.complete(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*(){this.optimisticallyMarkFlowNotStarted(),yield this.sendFlowStateToAPI(j)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){var t;return(t=this.steps.get(this.getStatefulFlow().$state.currentStepId))!=null?t:this.steps.get(Array.from(this.steps.keys())[0])}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=g=>{let o=g.match(/\${(.*?)}/g);return o&&o.forEach(l=>{let c=l.replace("${","").replace("}","");t[c]&&(g=g.replace(l,t[c]))}),g};this.title=e((i=this.title)!=null?i:""),this.subtitle=e((r=this.subtitle)!=null?r:""),this.steps.forEach(g=>{Object.keys(g).forEach(o=>{typeof g[o]=="string"&&(g[o]=e(g[o]))})}),this.getGlobalState().variables={},this.getGlobalState().variables[this.id]=t}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=S(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()}optimisticallyMarkFlowNotStarted(){var e;let t=S(this.getGlobalState().flowStates[this.id]);t.$state.completed=!1,t.$state.started=!1,t.$state.visible=!0,t.$state.currentStepIndex=0,t.$state.currentStepId=(e=this.getStepByIndex(0))==null?void 0:e.id,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}sendFlowStateToAPI(t,e,i){return d(this,null,function*(){let r=new Date;this.getGlobalState().lastSyncDate=r;let g=yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,flowSlug:this.id,stepId:i!=null?i:this.getCurrentStep().id,data:e||{},actionType:t,createdAt:r})});r<this.getGlobalState().lastSyncDate||(yield this.getGlobalState().refreshStateFromAPI(g))})}optimisticallyMarkFlowSkipped(){let t=S(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().rules.register(this.id,i=>{let r=this.getGlobalState().previousFlows.get(this.id);(r==null?void 0:r._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(g=>{g(this,r),this.getGlobalState().previousFlows.set(this.id,R(this))}),t==null||t(i)})}unregister(){this.getGlobalState().rules.unregister(this.id)}};var V="NOT_STARTED_STEP",W="COMPLETED_FLOW",B="SKIPPED_FLOW",K="STARTED_FLOW",j="NOT_STARTED_FLOW",J="COMPLETED_STEP",q="STARTED_STEP",z="frigade-guest-key",T="guest_",lt="get-cache-",A="fr-js-";function R(a){return new b({config:a.config,id:a.id})}function S(a){return JSON.parse(JSON.stringify(a))}function L(a){return{headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json","X-Frigade-SDK-Version":N,"X-Frigade-SDK-Platform":"Javascript"}}}function ct(a){return y()?window.localStorage.getItem(`${A}${a}`):null}function gt(a,s){y()&&window.localStorage.setItem(`${A}${a}`,s)}function Q(){Object.keys(f).forEach(a=>{a.startsWith(lt)&&delete f[a]})}function Z(){y()&&Object.keys(window.localStorage).forEach(a=>{a.startsWith(A)&&window.localStorage.removeItem(a)})}var E=class{constructor(){this.queue=[];this.ttlInMS=500;this.cacheSize=5}push(s){let t=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:s,time:t.getTime()})}hasIdenticalCall(s){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.some(e=>e.call===s)}},X=new E;function H(a,s){return d(this,null,function*(){var e;if(typeof globalThis.fetch!="function")return u("- Attempted to call fetch() in an environment that doesn't support it.");if(y()&&s&&s.body&&s.method==="POST"){let i=`${a}${JSON.stringify((e=s.body)!=null?e:{})}`;if(X.hasIdenticalCall(i))return u();X.push(i)}let t;try{t=fetch(a,s),t=yield t}catch(i){return u(i)}if(!t)return u("Received an empty response");if(t.status>=400)return u(t.statusText);try{if(t.status===204)return u();let i;try{i=yield t.json()}catch(r){return u()}return i.error?u(i.error):i}catch(i){return u(i)}})}function u(a){return a&&console.log("Call to Frigade failed",a),{json:()=>({})}}function U(){if(y()){let a=ct(z);return a||(a=`${T}${(0,Y.v4)()}`,gt(z,a)),a}}function y(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}var C=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.rules=new Map;this.flowsInRules=new Set;this.ingestRulesData(s)}ingestRulesData(s){this.rules=s;for(let[,t]of this.rules)for(let{flowId:e}of t)this.flowsInRules.add(e);this.registry.size>0&&(this.registryStateLocked||this.resetRegistryState(),this.processRules()),this.fireCallbacks()}fireCallbacks(){for(let[s,{callback:t}]of this.registry)typeof t=="function"&&t(this.isFlowVisible(s))}isFlowVisible(s){let t=this.registry.get(s),e=this.flowsInRules.has(s);return t==null||!e?!0:t.visible}lockRegistryState(){this.registryStateLocked=!0}unlockRegistryState(){this.registryStateLocked=!1}resetRegistryState(){for(let[s,t]of this.registry)t.visible=!1,t.visited=!1,this.registry.set(s,t)}processRules(){for(let[,s]of this.rules)for(let{flowId:t,visible:e}of s){let i=this.registry.get(t);if(i==null)continue;if(e===!1&&i.visible!==!0){this.visit(t,!1);continue}if(i.visited&&this.registryStateLocked)continue;if(s.map(({flowId:o})=>o).filter(o=>o!==t).some(o=>{var p;let{visible:l,visited:c}=(p=this.registry.get(o))!=null?p:{};return l&&c})){this.visit(t,!1);continue}this.visit(t)}}register(s,t){if(Array.isArray(s)){this.batchRegister(s);return}this.registry.set(s,{callback:t!=null?t:()=>{},visible:!1,visited:!1}),this.registryStateLocked||this.resetRegistryState(),this.processRules(),this.fireCallbacks()}batchRegister(s){s.forEach(([t,e])=>{this.registry.set(t,{callback:e!=null?e:()=>{},visible:!1,visited:!1})}),this.registryStateLocked||this.resetRegistryState(),this.processRules(),this.lockRegistryState(),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.resetRegistryState(),this.processRules(),this.fireCallbacks()}visit(s,t=!0){var i;let e=(i=this.registry.get(s))!=null?i:{callback:()=>{},visible:t,visited:!0};e.visible=t,e.visited=!0,this.registry.set(s,e)}};var P=class extends F{constructor(t,e){super(h({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.visibilityChangeHandler=()=>d(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshStateFromAPI())});this.init(this.config),y()&&document.addEventListener("visibilitychange",this.visibilityChangeHandler)}getConfig(){return this.config}destroy(){if(y()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=w(this.config);f[t]&&(f[t].onFlowStateChangeHandlers=[])}}init(t){return d(this,null,function*(){return this.updateConfig(h(h({},this.config),t)),this.initPromise=(()=>d(this,null,function*(){var e;this.config.__readOnly||(e=this.config.userId)!=null&&e.startsWith(T)||(this.config.userId&&this.config.groupId?yield this.session({userId:this.config.userId,groupId:this.config.groupId}):this.config.userId&&(yield this.session({userId:this.config.userId}))),yield this.refreshStateFromAPI()}))(),this.initPromise})}identify(t,e){return d(this,null,function*(){this.updateConfig(m(h({},this.config),{userId:t})),yield this.initIfNeeded(),yield this.session({userId:this.config.userId,userProperties:e}),yield this.resync()})}group(t,e){return d(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(m(h({},this.config),{groupId:t})),yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupProperties: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.session({userId:this.config.userId,groupId:this.config.groupId,groupEvents:[{event:t,properties:e}],userEvents:[{event:t,properties:e}]}):this.config.userId&&(yield this.session({userId:this.config.userId,userEvents:[{event:t,properties:e}]})),yield this.resync()})}session(t){return d(this,null,function*(){yield this.fetch("/v1/public/sessions",{method:"POST",body:JSON.stringify(t)})})}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(t){return d(this,null,function*(){Z(),Q(),t&&(yield this.updateConfig(t),this.mockFlowStates(w(this.config))),this.initPromise=null,yield this.init(this.config),this.flows.forEach(e=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(i=>{let r=this.getGlobalState().previousFlows.get(e.id);i(e,r),this.getGlobalState().previousFlows.set(e.id,R(e))})})})}resync(){return d(this,null,function*(){yield this.refreshStateFromAPI()})}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)})}refreshStateFromAPI(){return d(this,null,function*(){let t=w(this.config);if(!f[t]){let e=this,i={set:function(r,g,o){if(r[g]){let l=r[g],c=o;JSON.stringify(l)!==JSON.stringify(c)&&e.triggerEventHandlers(c,l)}return r[g]=o,!0}};if(f[t]={refreshStateFromAPI:()=>d(this,null,function*(){}),rules:new C(new Map),flowStates:new Proxy({},i),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(t);return}f[t].refreshStateFromAPI=r=>d(this,null,function*(){var l,c;if(this.config.__readOnly)return;let g=r||(yield this.fetch(`/v1/public/flowStates?userId=${encodeURIComponent(this.config.userId)}${this.config.groupId?`&groupId=${encodeURIComponent(this.config.groupId)}`:""}`)),o=new Map;(c=(l=g.rules)==null?void 0:l.computedOrder)==null||c.forEach(({ruleId:p,flowId:n,visible:I})=>{var D;let x=(D=o.get(p))!=null?D:[];x.push({flowId:n,visible:I}),o.set(p,x)}),f[t].rules.ingestRulesData(o),g&&g.eligibleFlows?(g.eligibleFlows.forEach(p=>{f[t].flowStates[p.flowSlug]=p,this.flows.find(n=>n.id==p.flowSlug)||this.flows.push(new b({config:this.config,id:p.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield f[t].refreshStateFromAPI()})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{f[t].flowStates[e]=this.config.__flowStateOverrides[e],this.flows.find(i=>i.id==e)?this.flows.forEach(i=>{i.id==e&&i.resyncState(this.config.__flowStateOverrides[e])}):this.flows.push(new b({config:this.config,id:e}))})}updateConfig(t){return d(this,null,function*(){this.config=h(h({},this.config),t),f[w(this.config)]&&(this.getGlobalState().config=this.config)})}triggerEventHandlers(t,e){return d(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(r=>{let g=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),r(i,g),this.getGlobalState().previousFlows.set(i.id,R(i))})})})}batchRegister(t){return d(this,null,function*(){let e=t.map(g=>d(this,[g],function*([i,r]){let o=yield this.getFlow(i);return[i,c=>{let p=this.getGlobalState().previousFlows.get(i);(p==null?void 0:p.isVisible)!==c&&this.getGlobalState().onFlowStateChangeHandlers.forEach(n=>{n(o,p),this.getGlobalState().previousFlows.set(i,R(o))}),r==null||r(c)}]}));Promise.all(e).then(i=>{this.getGlobalState().rules.batchRegister(i)})})}};var O=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(O||{}),_=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(_||{}),G=(n=>(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))(G||{});0&&(module.exports={Flow,FlowStatus,FlowType,Frigade,TriggerType});
2
+ var v=Object.defineProperty,tt=Object.defineProperties,et=Object.getOwnPropertyDescriptor,it=Object.getOwnPropertyDescriptors,st=Object.getOwnPropertyNames,$=Object.getOwnPropertySymbols;var M=Object.prototype.hasOwnProperty,at=Object.prototype.propertyIsEnumerable;var k=(a,s,t)=>s in a?v(a,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[s]=t,h=(a,s)=>{for(var t in s||(s={}))M.call(s,t)&&k(a,t,s[t]);if($)for(var t of $(s))at.call(s,t)&&k(a,t,s[t]);return a},m=(a,s)=>tt(a,it(s));var rt=(a,s)=>{for(var t in s)v(a,t,{get:s[t],enumerable:!0})},ot=(a,s,t,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of st(s))!M.call(a,i)&&i!==t&&v(a,i,{get:()=>s[i],enumerable:!(e=et(s,i))||e.enumerable});return a};var nt=a=>ot(v({},"__esModule",{value:!0}),a);var d=(a,s,t)=>new Promise((e,i)=>{var r=l=>{try{n(t.next(l))}catch(c){i(c)}},g=l=>{try{n(t.throw(l))}catch(c){i(c)}},n=l=>l.done?e(l.value):Promise.resolve(l.value).then(r,g);n((t=t.apply(a,s)).next())});var dt={};rt(dt,{Flow:()=>y,FlowStatus:()=>_,FlowType:()=>G,Frigade:()=>E,TriggerType:()=>O});module.exports=nt(dt);var N="0.2.20";var Y=require("uuid");var f={};function w(a){return`${a.__instanceId}-${a.apiKey}`}var F=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:U(),__instanceId:Math.random().toString(12).substring(4)};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));this.config=h(h({},this.config),t)}fetch(s,t){return d(this,null,function*(){return this.config.__readOnly?S():H(this.getAPIUrl(s),h(h({keepalive:!0},t!=null?t:{}),L(this.config.apiKey)))})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=w(this.config);if(!f[s])throw new Error("Frigade has not yet been initialized");return f[s]}};var y=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().rules.isFlowVisible(this.id)}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,r,g;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((n,l)=>{var o;let c=this.initStepFromStatefulStep(n,l),p=(o=this.steps)==null?void 0:o.get(n.id);p&&Object.keys(c).forEach(I=>{p[I]=c[I]})}),this.steps&&this.steps.size>0&&this.applyVariables((g=this.getGlobalState().variables[this.id])!=null?g:{})}initStepFromStatefulStep(t,e){return m(h({},t),{flow:this,$state:m(h({},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 g=this.initStepFromStatefulStep(i,r);g.start=n=>d(this,null,function*(){let l=this.steps.get(i.id);if(this.getCurrentStep().id===l.id&&l.$state.started)return;let c=u(this.getGlobalState().flowStates[this.id]);c.data.steps[l.order].$state.started=!0,c.data.steps[l.order].$state.lastActionAt=new Date,c.$state.lastActionAt=new Date,c.$state.currentStepId=l.id,c.$state.currentStepIndex=l.order,this.getGlobalState().flowStates[this.id]=c,this.resyncState(),yield this.sendFlowStateToAPI(q,n,l.id)}),g.complete=(n,l=!0)=>d(this,null,function*(){let c=this.steps.get(i.id);if(l){let p=c.order+1===this.getNumberOfAvailableSteps(),o=u(this.getGlobalState().flowStates[this.id]);o.$state.started=!0,o.data.steps[c.order].$state.completed=!0,o.data.steps[c.order].$state.started=!0,o.data.steps[c.order].$state.lastActionAt=new Date,p||(o.$state.currentStepId=this.getStepByIndex(c.order+1).id,o.$state.currentStepIndex=c.order+1),p&&(o.$state.completed=!0),this.getGlobalState().flowStates[this.id]=o,this.resyncState(),p&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(J,n,c.id)}),g.reset=()=>d(this,null,function*(){let n=this.steps.get(i.id);if(!n.$state.completed)return;let l=u(this.getGlobalState().flowStates[this.id]);l.data.steps[n.order].$state.started=!1,l.data.steps[n.order].$state.completed=!1,l.data.steps[n.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=l,this.resyncState(),yield this.sendFlowStateToAPI(V,void 0,n.id)}),g.onStateChange=n=>{let l=c=>{if(c.id!==this.id)return;let p=c.steps.get(i.id),o=this.lastStepUpdate.get(n);(p.$state.completed!==(o==null?void 0:o.$state.completed)||p.$state.started!==(o==null?void 0:o.$state.started)||p.$state.visible!==(o==null?void 0:o.$state.visible)||p.$state.blocked!==(o==null?void 0:o.$state.blocked))&&(n(p,o!=null?o:u(p)),this.lastStepUpdate.set(n,u(p)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(n,l),this.getGlobalState().onFlowStateChangeHandlers.push(l)},g.removeStateChangeHandler=n=>{let l=this.getGlobalState().onStepStateChangeHandlerWrappers.get(n);l&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(c=>c!==l))},e.set(i.id,g)}),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 d(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(K,t))})}complete(t){return d(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(W,t))})}skip(t){return d(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(B,t))})}forward(t){return d(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()+1);e?yield e.start(t):yield this.complete(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*(){this.optimisticallyMarkFlowNotStarted(),yield this.sendFlowStateToAPI(j)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){var t;return(t=this.steps.get(this.getStatefulFlow().$state.currentStepId))!=null?t:this.steps.get(Array.from(this.steps.keys())[0])}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=g=>{let n=g.match(/\${(.*?)}/g);return n&&n.forEach(l=>{let c=l.replace("${","").replace("}","");t[c]&&(g=g.replace(l,t[c]))}),g};this.title=e((i=this.title)!=null?i:""),this.subtitle=e((r=this.subtitle)!=null?r:""),this.steps.forEach(g=>{Object.keys(g).forEach(n=>{typeof g[n]=="string"&&(g[n]=e(g[n]))})}),this.getGlobalState().variables[this.id]=t}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=u(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()}optimisticallyMarkFlowStarted(){let t=u(this.getGlobalState().flowStates[this.id]);t.$state.started=!0,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowNotStarted(){var e;let t=u(this.getGlobalState().flowStates[this.id]);t.$state.completed=!1,t.$state.started=!1,t.$state.visible=!0,t.$state.currentStepIndex=0,t.$state.currentStepId=(e=this.getStepByIndex(0))==null?void 0:e.id,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}sendFlowStateToAPI(t,e,i){return d(this,null,function*(){let r=new Date;this.getGlobalState().lastSyncDate=r;let g=yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,flowSlug:this.id,stepId:i!=null?i:this.getCurrentStep().id,data:e||{},actionType:t,createdAt:r})});r<this.getGlobalState().lastSyncDate||(yield this.getGlobalState().refreshStateFromAPI(g))})}optimisticallyMarkFlowSkipped(){let t=u(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().rules.register(this.id,i=>{let r=this.getGlobalState().previousFlows.get(this.id);(r==null?void 0:r._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(g=>{g(this,r),this.getGlobalState().previousFlows.set(this.id,C(this))}),t==null||t(i)})}unregister(){this.getGlobalState().rules.unregister(this.id)}};var V="NOT_STARTED_STEP",W="COMPLETED_FLOW",B="SKIPPED_FLOW",K="STARTED_FLOW",j="NOT_STARTED_FLOW",J="COMPLETED_STEP",q="STARTED_STEP",z="frigade-guest-key",T="guest_",lt="get-cache-",A="fr-js-";function C(a){return new y({config:a.config,id:a.id})}function u(a){return JSON.parse(JSON.stringify(a))}function L(a){return{headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json","X-Frigade-SDK-Version":N,"X-Frigade-SDK-Platform":"Javascript"}}}function ct(a){return b()?window.localStorage.getItem(`${A}${a}`):null}function gt(a,s){b()&&window.localStorage.setItem(`${A}${a}`,s)}function Q(){Object.keys(f).forEach(a=>{a.startsWith(lt)&&delete f[a]})}function Z(){b()&&Object.keys(window.localStorage).forEach(a=>{a.startsWith(A)&&window.localStorage.removeItem(a)})}var P=class{constructor(){this.queue=[];this.ttlInMS=500;this.cacheSize=5}push(s){let t=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:s,time:t.getTime()})}hasIdenticalCall(s){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.some(e=>e.call===s)}},X=new P;function H(a,s){return d(this,null,function*(){var e;if(typeof globalThis.fetch!="function")return S("- Attempted to call fetch() in an environment that doesn't support it.");if(b()&&s&&s.body&&s.method==="POST"){let i=`${a}${JSON.stringify((e=s.body)!=null?e:{})}`;if(X.hasIdenticalCall(i))return S();X.push(i)}let t;try{t=fetch(a,s),t=yield t}catch(i){return S(i)}if(!t)return S("Received an empty response");if(t.status>=400)return S(t.statusText);try{if(t.status===204)return S();let i;try{i=yield t.json()}catch(r){return S()}return i.error?S(i.error):i}catch(i){return S(i)}})}function S(a){return a&&console.log("Call to Frigade failed",a),{json:()=>({})}}function U(){if(b()){let a=ct(z);return a||(a=`${T}${(0,Y.v4)()}`,gt(z,a)),a}}function b(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}var R=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.rules=new Map;this.flowsInRules=new Set;this.ingestRulesData(s)}ingestRulesData(s){this.rules=s;for(let[,t]of this.rules)for(let{flowId:e}of t)this.flowsInRules.add(e);this.registry.size>0&&(this.registryStateLocked||this.resetRegistryState(),this.processRules()),this.fireCallbacks()}fireCallbacks(){for(let[s,{callback:t}]of this.registry)typeof t=="function"&&t(this.isFlowVisible(s))}isFlowVisible(s){let t=this.registry.get(s),e=this.flowsInRules.has(s);return t==null||!e?!0:t.visible}lockRegistryState(){this.registryStateLocked=!0}unlockRegistryState(){this.registryStateLocked=!1}resetRegistryState(){for(let[s,t]of this.registry)t.visible=!1,t.visited=!1,this.registry.set(s,t)}processRules(){for(let[,s]of this.rules)for(let{flowId:t,visible:e}of s){let i=this.registry.get(t);if(i==null)continue;if(e===!1&&i.visible!==!0){this.visit(t,!1);continue}if(i.visited&&this.registryStateLocked)continue;if(s.map(({flowId:n})=>n).filter(n=>n!==t).some(n=>{var p;let{visible:l,visited:c}=(p=this.registry.get(n))!=null?p:{};return l&&c})){this.visit(t,!1);continue}this.visit(t)}}register(s,t){if(Array.isArray(s)){this.batchRegister(s);return}this.registry.set(s,{callback:t!=null?t:()=>{},visible:!1,visited:!1}),this.registryStateLocked||this.resetRegistryState(),this.processRules(),this.fireCallbacks()}batchRegister(s){s.forEach(([t,e])=>{this.registry.set(t,{callback:e!=null?e:()=>{},visible:!1,visited:!1})}),this.registryStateLocked||this.resetRegistryState(),this.processRules(),this.lockRegistryState(),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.resetRegistryState(),this.processRules(),this.fireCallbacks()}visit(s,t=!0){var i;let e=(i=this.registry.get(s))!=null?i:{callback:()=>{},visible:t,visited:!0};e.visible=t,e.visited=!0,this.registry.set(s,e)}};var E=class extends F{constructor(t,e){super(h({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.visibilityChangeHandler=()=>d(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshStateFromAPI())});this.init(this.config),b()&&document.addEventListener("visibilitychange",this.visibilityChangeHandler)}getConfig(){return this.config}destroy(){if(b()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=w(this.config);f[t]&&(f[t].onFlowStateChangeHandlers=[])}}init(t){return d(this,null,function*(){return this.updateConfig(h(h({},this.config),t)),this.initPromise=(()=>d(this,null,function*(){var e;this.config.__readOnly||(e=this.config.userId)!=null&&e.startsWith(T)||(this.config.userId&&this.config.groupId?yield this.session({userId:this.config.userId,groupId:this.config.groupId}):this.config.userId&&(yield this.session({userId:this.config.userId}))),yield this.refreshStateFromAPI()}))(),this.initPromise})}identify(t,e){return d(this,null,function*(){yield this.updateConfig(m(h({},this.config),{userId:t})),yield this.initIfNeeded(),yield this.session({userId:this.config.userId,userProperties:e}),yield this.resync()})}group(t,e){return d(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(m(h({},this.config),{groupId:t})),yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupProperties: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.session({userId:this.config.userId,groupId:this.config.groupId,groupEvents:[{event:t,properties:e}],userEvents:[{event:t,properties:e}]}):this.config.userId&&(yield this.session({userId:this.config.userId,userEvents:[{event:t,properties:e}]})),yield this.resync()})}session(t){return d(this,null,function*(){yield this.fetch("/v1/public/sessions",{method:"POST",body:JSON.stringify(t)})})}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(t){return d(this,null,function*(){Z(),Q(),t&&(yield this.updateConfig(t),this.mockFlowStates(w(this.config))),this.initPromise=null,yield this.init(this.config),this.flows.forEach(e=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(i=>{let r=this.getGlobalState().previousFlows.get(e.id);i(e,r),this.getGlobalState().previousFlows.set(e.id,C(e))})})})}resync(){return d(this,null,function*(){yield this.refreshStateFromAPI()})}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)})}refreshStateFromAPI(){return d(this,null,function*(){let t=w(this.config);if(!f[t]){let e=this,i={set:function(r,g,n){if(r[g]){let l=r[g],c=n;JSON.stringify(l)!==JSON.stringify(c)&&e.triggerEventHandlers(c,l)}return r[g]=n,!0}};if(f[t]={refreshStateFromAPI:()=>d(this,null,function*(){}),rules:new R(new Map),flowStates:new Proxy({},i),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(t);return}f[t].refreshStateFromAPI=r=>d(this,null,function*(){var l,c;if(this.config.__readOnly)return;let g=r||(yield this.fetch(`/v1/public/flowStates?userId=${encodeURIComponent(this.config.userId)}${this.config.groupId?`&groupId=${encodeURIComponent(this.config.groupId)}`:""}`)),n=new Map;(c=(l=g.collections)==null?void 0:l.computedOrder)==null||c.forEach(({collectionId:p,flowId:o,visible:I})=>{var D;let x=(D=n.get(p))!=null?D:[];x.push({flowId:o,visible:I}),n.set(p,x)}),f[t].rules.ingestRulesData(n),g&&g.eligibleFlows?(g.eligibleFlows.forEach(p=>{f[t].flowStates[p.flowSlug]=p,this.flows.find(o=>o.id==p.flowSlug)?this.flows.forEach(o=>{o.id==p.flowSlug&&o.resyncState(p)}):this.flows.push(new y({config:this.config,id:p.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield f[t].refreshStateFromAPI()})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{f[t].flowStates[e]=this.config.__flowStateOverrides[e],this.flows.find(i=>i.id==e)?this.flows.forEach(i=>{i.id==e&&i.resyncState(this.config.__flowStateOverrides[e])}):this.flows.push(new y({config:this.config,id:e}))})}updateConfig(t){return d(this,null,function*(){this.config=h(h({},this.config),t),f[w(this.config)]&&(this.getGlobalState().config=this.config)})}triggerEventHandlers(t,e){return d(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(r=>{let g=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),r(i,g),this.getGlobalState().previousFlows.set(i.id,C(i))})})})}batchRegister(t){return d(this,null,function*(){let e=t.map(g=>d(this,[g],function*([i,r]){let n=yield this.getFlow(i);return[i,c=>{let p=this.getGlobalState().previousFlows.get(i);(p==null?void 0:p.isVisible)!==c&&this.getGlobalState().onFlowStateChangeHandlers.forEach(o=>{o(n,p),this.getGlobalState().previousFlows.set(i,C(n))}),r==null||r(c)}]}));Promise.all(e).then(i=>{this.getGlobalState().rules.batchRegister(i)})})}};var O=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(O||{}),_=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(_||{}),G=(o=>(o.ANNOUNCEMENT="ANNOUNCEMENT",o.CHECKLIST="CHECKLIST",o.FORM="FORM",o.TOUR="TOUR",o.SUPPORT="SUPPORT",o.CUSTOM="CUSTOM",o.BANNER="BANNER",o.EMBEDDED_TIP="EMBEDDED_TIP",o.NPS_SURVEY="NPS_SURVEY",o.SURVEY="SURVEY",o.CARD="CARD",o))(G||{});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/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/shared/fetchable.ts","../src/core/flow.ts","../src/core/rules.ts","../src/core/frigade.ts","../src/core/types.ts"],"sourcesContent":["export { Frigade } from './core/frigade'\nexport { Flow } from './core/flow'\nexport {\n FlowStatus,\n type FlowStep,\n type FrigadeConfig,\n FlowType,\n type StatefulFlow,\n TriggerType,\n PropertyPayload,\n} from './core/types'\nexport type { RulesRegistryCallback, RulesRegistryBatch } from './core/rules'\n","export const VERSION_NUMBER = '0.2.20'\n","import { VERSION_NUMBER } from '../core/version'\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'\nconst GUEST_KEY = 'frigade-guest-key'\nexport const GUEST_PREFIX = 'guest_'\nconst GET_CACHE_PREFIX = 'get-cache-'\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\nclass CallQueue {\n private queue: {\n call: string\n time: number\n }[] = []\n private readonly ttlInMS = 500\n private readonly cacheSize = 5\n\n public push(call: string) {\n const now = new Date()\n if (this.queue.length >= this.cacheSize) {\n this.queue.shift()\n }\n this.queue.push({\n call: call,\n time: now.getTime(),\n })\n }\n\n public hasIdenticalCall(call: string) {\n const now = new Date()\n this.queue = this.queue.filter((item) => now.getTime() - item.time < this.ttlInMS)\n return this.queue.some((item) => item.call === call)\n }\n}\n\nconst callQueue = new CallQueue()\n\nexport async function gracefulFetch(url: string, options: any) {\n if (typeof globalThis.fetch !== 'function') {\n return getEmptyResponse(\n \"- Attempted to call fetch() in an environment that doesn't support it.\"\n )\n }\n\n if (isWeb() && options && options.body && options.method === 'POST') {\n const lastCallDataKey = `${url}${JSON.stringify(options.body ?? {})}`\n if (callQueue.hasIdenticalCall(lastCallDataKey)) {\n return getEmptyResponse()\n }\n callQueue.push(lastCallDataKey)\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) {\n return getEmptyResponse()\n }\n\n let body\n try {\n body = await response.json()\n } catch (e) {\n return getEmptyResponse()\n }\n\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 { FlowStates, FlowStep, FrigadeConfig, StatefulFlow } from '../core/types'\nimport { Flow } from '../core/flow'\nimport type { Rules } from '../core/rules'\n\nexport interface FrigadeGlobalState {\n refreshStateFromAPI: (overrideFlowStatesRaw?: FlowStates) => Promise<void>\n flowStates: Record<string, StatefulFlow>\n rules: Rules\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 lastSyncDate?: Date\n config: FrigadeConfig\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}`\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',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(12).substring(4),\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 return `${this.config.apiUrl.replace(/\\/$/, '')}/${path.replace(/^\\//, '')}`\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 has not yet been initialized')\n }\n return frigadeGlobalState[globalStateKey]\n }\n}\n","import {\n FlowActionType,\n FlowStateDTO,\n FlowStates,\n FlowStep,\n FrigadeConfig,\n PropertyPayload,\n StatefulFlow,\n StatefulStep,\n} from './types'\nimport {\n clone,\n cloneFlow,\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 { RulesRegistryCallback } from './rules'\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().rules.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 Object.keys(stepObj).forEach((key) => {\n existingStep[key] = stepObj[key]\n })\n }\n })\n if (this.steps && this.steps.size > 0) {\n this.applyVariables(this.getGlobalState().variables[this.id] ?? {})\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?: PropertyPayload) => {\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.sendFlowStateToAPI(STARTED_STEP, properties, thisStep.id)\n }\n }\n\n stepObj.complete = async (properties?: PropertyPayload, optimistic: boolean = true) => {\n const thisStep = this.steps.get(step.id)\n\n if (thisStep.$state.completed) {\n return\n }\n\n if (optimistic) {\n const isLastStep = thisStep.order + 1 === this.getNumberOfAvailableSteps()\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\n // If there are more index, advance current step\n if (!isLastStep) {\n copy.$state.currentStepId = this.getStepByIndex(thisStep.order + 1).id\n copy.$state.currentStepIndex = thisStep.order + 1\n }\n\n if (isLastStep) {\n copy.$state.completed = true\n }\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n if (isLastStep) {\n this.optimisticallyMarkFlowCompleted()\n }\n }\n\n await this.sendFlowStateToAPI(COMPLETED_STEP, properties, thisStep.id)\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.sendFlowStateToAPI(NOT_STARTED_STEP, undefined, thisStep.id)\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?: PropertyPayload) {\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.sendFlowStateToAPI(STARTED_FLOW, properties)\n }\n\n /**\n * Marks the flow completed\n */\n public async complete(properties?: PropertyPayload) {\n if (this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowCompleted()\n await this.sendFlowStateToAPI(COMPLETED_FLOW, properties)\n }\n\n /**\n * Marks the flow skipped\n */\n public async skip(properties?: PropertyPayload) {\n if (this.isSkipped) {\n return\n }\n this.optimisticallyMarkFlowSkipped()\n await this.sendFlowStateToAPI(SKIPPED_FLOW, properties)\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?: PropertyPayload) {\n const nextStep = this.getStepByIndex(this.getCurrentStepIndex() + 1)\n if (nextStep) {\n await nextStep.start(properties)\n } else {\n await this.complete(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?: PropertyPayload) {\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 this.optimisticallyMarkFlowNotStarted()\n await this.sendFlowStateToAPI(NOT_STARTED_FLOW)\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 return (\n this.steps.get(this.getStatefulFlow().$state.currentStepId) ??\n this.steps.get(Array.from(this.steps.keys())[0])\n )\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 (flow.id === this.id) {\n if (\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 }\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 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 optimisticallyMarkFlowNotStarted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = false\n copy.$state.started = false\n copy.$state.visible = true\n copy.$state.currentStepIndex = 0\n copy.$state.currentStepId = this.getStepByIndex(0)?.id\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n private async sendFlowStateToAPI(\n action: FlowActionType,\n data?: PropertyPayload,\n stepId?: string\n ) {\n const date = new Date()\n this.getGlobalState().lastSyncDate = date\n const flowStatesRaw: FlowStates = await this.fetch('/v1/public/flowStates', {\n method: 'POST',\n body: JSON.stringify({\n userId: this.getGlobalState().config.userId,\n groupId: this.getGlobalState().config.groupId,\n flowSlug: this.id,\n stepId: stepId ?? this.getCurrentStep().id,\n data: data ? data : {},\n actionType: action,\n createdAt: date,\n } as FlowStateDTO),\n })\n if (date < this.getGlobalState().lastSyncDate) {\n return\n }\n await this.getGlobalState().refreshStateFromAPI(flowStatesRaw)\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?: RulesRegistryCallback) {\n const globalState = this.getGlobalState()\n\n globalState.rules.register(this.id, (visible) => {\n const prevFlow = this.getGlobalState().previousFlows.get(this.id)\n\n if (prevFlow?._isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(this, prevFlow)\n this.getGlobalState().previousFlows.set(this.id, cloneFlow(this))\n })\n }\n\n callback?.(visible)\n })\n }\n\n public unregister() {\n this.getGlobalState().rules.unregister(this.id)\n }\n}\n","export type RulesRegistryCallback = (visible: boolean) => void\n\nexport type RulesRegistryBatch = [string, RulesRegistryCallback][]\n\nexport interface RulesRegistryItem {\n visible: boolean\n visited: boolean\n callback: RulesRegistryCallback\n}\n\nexport type Rule = Array<{\n flowId: string\n visible: boolean\n}>\n\nexport type RulesData = Map<string, Rule>\n\nexport class Rules {\n private readonly registry: Map<string, RulesRegistryItem> = new Map()\n private registryStateLocked: boolean = false\n private rules: Map<string, Rule> = new Map()\n private flowsInRules: Set<string> = new Set()\n\n constructor(rulesData: RulesData) {\n this.ingestRulesData(rulesData)\n }\n\n ingestRulesData(rulesData: RulesData) {\n this.rules = rulesData\n\n for (const [, rule] of this.rules) {\n for (const { flowId } of rule) {\n this.flowsInRules.add(flowId)\n }\n }\n\n if (this.registry.size > 0) {\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n }\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 registeredFlow = this.registry.get(flowId)\n const flowInRules = this.flowsInRules.has(flowId)\n\n if (registeredFlow == null || !flowInRules) {\n return true\n }\n\n return registeredFlow.visible\n }\n\n lockRegistryState() {\n this.registryStateLocked = true\n }\n\n unlockRegistryState() {\n this.registryStateLocked = false\n }\n\n resetRegistryState() {\n for (const [flowId, item] of this.registry) {\n item.visible = false\n item.visited = false\n\n this.registry.set(flowId, item)\n }\n }\n\n processRules() {\n for (const [, rule] of this.rules) {\n for (const { flowId, visible: visibleAPIOverride } of rule) {\n const registeredFlow = this.registry.get(flowId)\n\n // If this flow in the rule isn't registered, we have no opinion on it yet\n if (registeredFlow == null) {\n continue\n }\n\n // The API can force a flow to be hidden due to cool-offs, etc.\n if (visibleAPIOverride === false && registeredFlow.visible !== true) {\n this.visit(flowId, false)\n continue\n }\n\n // If this flow was processed in a previous rule and the registry is locked,\n // visibility shouldn't change until next time we run processRules\n if (registeredFlow.visited && this.registryStateLocked) {\n continue\n }\n\n const flowIdsInThisRule = rule\n .map(({ flowId: otherFlowId }) => otherFlowId)\n .filter((otherFlowId) => otherFlowId !== flowId)\n\n // If another flow in this rule has been visited already and is visible...\n const anotherFlowInThisRuleIsVisible = flowIdsInThisRule.some((otherId) => {\n const { visible: otherVisible, visited: otherVisited } = this.registry.get(otherId) ?? {}\n\n return otherVisible && otherVisited\n })\n\n // ...then this flow is hidden\n if (anotherFlowInThisRuleIsVisible) {\n this.visit(flowId, false)\n\n continue\n }\n\n // No other flows are visible, so this flow is visible by default\n this.visit(flowId)\n }\n }\n }\n\n register(flowId: string | RulesRegistryBatch, callback?: RulesRegistryCallback) {\n if (Array.isArray(flowId)) {\n this.batchRegister(flowId)\n return\n }\n\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.fireCallbacks()\n }\n\n batchRegister(flowIds: RulesRegistryBatch) {\n flowIds.forEach(([flowId, callback]) => {\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.lockRegistryState()\n\n this.fireCallbacks()\n }\n\n unregister(flowId: string) {\n this.registry.delete(flowId)\n\n this.resetRegistryState()\n this.processRules()\n\n this.fireCallbacks()\n }\n\n private visit(flowId: string, visible: boolean = true) {\n const item = this.registry.get(flowId) ?? {\n callback: () => {},\n visible,\n visited: true,\n }\n\n item.visible = visible\n item.visited = true\n\n this.registry.set(flowId, item)\n }\n}\n","import { FlowStates, FrigadeConfig, PropertyPayload, SessionDTO, StatefulFlow } 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 { Rules, type RulesRegistryBatch } from './rules'\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 }\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 * Gets the current configuration.\n */\n getConfig() {\n return this.config\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.updateConfig({\n ...this.config,\n ...config,\n })\n\n this.initPromise = (async () => {\n if (!this.config.__readOnly) {\n if (this.config.userId?.startsWith(GUEST_PREFIX)) {\n // do nothing\n } else if (this.config.userId && this.config.groupId) {\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n })\n } else if (this.config.userId) {\n await this.session({\n userId: 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?: PropertyPayload): Promise<void> {\n this.updateConfig({ ...this.config, userId })\n await this.initIfNeeded()\n await this.session({\n userId: this.config.userId,\n userProperties: properties,\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?: PropertyPayload): Promise<void> {\n await this.initIfNeeded()\n this.updateConfig({ ...this.config, groupId })\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupProperties: properties,\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?: PropertyPayload): 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.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupEvents: [\n {\n event,\n properties,\n },\n ],\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n } else if (this.config.userId) {\n await this.session({\n userId: this.config.userId,\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n }\n await this.resync()\n }\n\n /**\n * @ignore\n */\n private async session(sessionDTO: SessionDTO) {\n await this.fetch('/v1/public/sessions', {\n method: 'POST',\n body: JSON.stringify(sessionDTO),\n })\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 * @param config optional config to use when reloading. If not passed, the current config will be used.\n */\n public async reload(config?: FrigadeConfig) {\n resetAllLocalStorage()\n clearCache()\n if (config) {\n await this.updateConfig(config)\n this.mockFlowStates(getGlobalStateKey(this.config))\n }\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 await this.refreshStateFromAPI()\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 rules: new Rules(new Map()),\n flowStates: new Proxy({}, validator),\n onFlowStateChangeHandlerWrappers: new Map(),\n onStepStateChangeHandlerWrappers: new Map(),\n onFlowStateChangeHandlers: [],\n previousFlows: new Map(),\n variables: {},\n config: this.config,\n }\n\n if (this.config.__readOnly && this.config.__flowStateOverrides) {\n this.mockFlowStates(globalStateKey)\n\n return\n }\n\n frigadeGlobalState[globalStateKey].refreshStateFromAPI = async (\n overrideFlowStateRaw?: FlowStates\n ) => {\n if (this.config.__readOnly) {\n return\n }\n\n const flowStateRaw: FlowStates = overrideFlowStateRaw\n ? overrideFlowStateRaw\n : await this.fetch(\n `/v1/public/flowStates?userId=${encodeURIComponent(this.config.userId)}${\n this.config.groupId ? `&groupId=${encodeURIComponent(this.config.groupId)}` : ''\n }`\n )\n\n const rulesData = new Map()\n\n flowStateRaw.rules?.computedOrder?.forEach(({ ruleId, flowId, visible }) => {\n const currentRule = rulesData.get(ruleId) ?? []\n\n currentRule.push({\n flowId,\n visible,\n })\n\n rulesData.set(ruleId, currentRule)\n })\n\n frigadeGlobalState[globalStateKey].rules.ingestRulesData(rulesData)\n\n if (flowStateRaw && flowStateRaw.eligibleFlows) {\n flowStateRaw.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 mockFlowStates(globalStateKey: string) {\n Object.keys(this.config.__flowStateOverrides).forEach((flowId) => {\n frigadeGlobalState[globalStateKey].flowStates[flowId] =\n this.config.__flowStateOverrides[flowId]\n\n if (!this.flows.find((flow) => flow.id == flowId)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: flowId,\n })\n )\n } else {\n this.flows.forEach((flow) => {\n if (flow.id == flowId) {\n flow.resyncState(this.config.__flowStateOverrides[flowId])\n }\n })\n }\n })\n }\n\n /**\n * @ignore\n */\n private async updateConfig(config: FrigadeConfig) {\n this.config = {\n ...this.config,\n ...config,\n }\n if (frigadeGlobalState[getGlobalStateKey(this.config)]) {\n this.getGlobalState().config = this.config\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 /**\n * @ignore\n */\n async batchRegister(flowIds: RulesRegistryBatch) {\n const flowIdsWithWrappedCallbacks = flowIds.map(async ([flowId, callback]) => {\n const currentFlow = await this.getFlow(flowId)\n const wrappedCallback = (visible: boolean) => {\n const prevFlow = this.getGlobalState().previousFlows.get(flowId)\n\n if (prevFlow?.isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(currentFlow, prevFlow)\n this.getGlobalState().previousFlows.set(flowId, cloneFlow(currentFlow))\n })\n }\n\n callback?.(visible)\n }\n\n return [flowId, wrappedCallback] as RulesRegistryBatch[number]\n })\n\n Promise.all(flowIdsWithWrappedCallbacks).then((results) => {\n this.getGlobalState().rules.batchRegister(results)\n })\n }\n}\n","import type { Flow } from './flow'\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 type PropertyPayload = Record<string, any>\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 * @description 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 * @description Primary button URI.\n */\n primaryButtonUri?: string\n\n /**\n * @deprecated Use primaryButton.target instead\n * @description 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 * @description 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 * @description Secondary button URI.\n */\n secondaryButtonUri?: string\n\n /**\n * @deprecated Use secondaryButton.target instead\n * @description 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?: PropertyPayload) => Promise<void>\n\n /**\n * Marks the step completed.\n * @param optimistic If true, the step will be marked as completed without waiting for the API and validation of any targeting rules.\n */\n complete: (properties?: PropertyPayload, optimistic?: boolean) => 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 State for all flows in the app that should be mocked.\n */\n __flowStateOverrides?: Record<string, StatefulFlow>\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 ComputedRule {\n ruleId: string\n flowId: string\n visible: boolean\n}\n\nexport interface RulesMetadata {\n computedOrder: ComputedRule[]\n}\n\nexport interface FlowStates {\n eligibleFlows: StatefulFlow[]\n ineligibleFlows: string[]\n rules?: RulesMetadata\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\nexport type FlowActionType =\n | 'STARTED_STEP'\n | 'COMPLETED_STEP'\n | 'NOT_STARTED_STEP'\n | 'STARTED_FLOW'\n | 'COMPLETED_FLOW'\n | 'SKIPPED_FLOW'\n | 'NOT_STARTED_FLOW'\n\nexport interface FlowStateDTO {\n userId: string\n groupId?: string\n flowSlug: string\n stepId?: string\n data?: any\n actionType: FlowActionType\n createdAt?: Date\n}\n\nexport interface TrackingEvent {\n event: string\n properties?: { [key: string]: any }\n}\n\nexport interface SessionDTO {\n userId: string\n groupId?: string\n userProperties?: { [key: string]: any }\n userEvents?: TrackingEvent[]\n groupProperties?: { [key: string]: any }\n groupEvents?: TrackingEvent[]\n linkGuestId?: string\n}\n"],"mappings":";k9BAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,UAAAE,EAAA,eAAAC,EAAA,aAAAC,EAAA,YAAAC,EAAA,gBAAAC,IAAA,eAAAC,GAAAP,ICAO,IAAMQ,EAAiB,SCC9B,IAAAC,EAA6B,gBCsBtB,IAAIC,EAAyD,CAAC,EAE9D,SAASC,EAAkBC,EAAuC,CACvE,MAAO,GAAGA,EAAe,gBAAgBA,EAAe,QAC1D,CCvBO,IAAMC,EAAN,KAAgB,CAQrB,YAAYC,EAAuB,CAPnC,KAAO,OAAwB,CAC7B,OAAQ,GACR,OAAQ,0BACR,OAAQC,EAAgB,EACxB,aAAc,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,UAAU,CAAC,CACtD,EAGE,IAAMC,EAAiB,OAAO,YAAY,OAAO,QAAQF,CAAM,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AAS,SACTA,EAAA,UAAY,YAFFA,OAAA,IAKAC,OACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SACTA,EAAA,SAAW,WAHDA,OAAA,IAoTAC,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_uuid","frigadeGlobalState","getGlobalStateKey","internalConfig","Fetchable","config","generateGuestId","filteredConfig","_","v","__spreadValues","path","options","__async","getEmptyResponse","gracefulFetch","getHeaders","globalStateKey","getGlobalStateKey","frigadeGlobalState","Flow","Fetchable","config","id","visible","overrideStatefulFlow","_a","_b","_c","statefulFlow","step","index","stepObj","existingStep","key","__spreadProps","__spreadValues","newSteps","properties","__async","thisStep","copy","clone","STARTED_STEP","optimistic","isLastStep","COMPLETED_STEP","NOT_STARTED_STEP","handler","wrapperHandler","flow","previousStep","h","STARTED_FLOW","COMPLETED_FLOW","SKIPPED_FLOW","nextStep","NOT_STARTED_FLOW","currentStep","previousFlow","variables","replaceVariables","str","matches","match","variable","action","data","stepId","date","flowStatesRaw","callback","prevFlow","cloneFlow","NOT_STARTED_STEP","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","GUEST_KEY","GUEST_PREFIX","GET_CACHE_PREFIX","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","CallQueue","call","now","item","callQueue","gracefulFetch","url","options","__async","_a","getEmptyResponse","lastCallDataKey","response","error","body","e","generateGuestId","guestId","getLocalStorage","GUEST_KEY","GUEST_PREFIX","uuidv4","setLocalStorage","isWeb","Rules","rulesData","rule","flowId","callback","registeredFlow","flowInRules","item","visibleAPIOverride","otherFlowId","otherId","_a","otherVisible","otherVisited","flowIds","visible","Frigade","Fetchable","apiKey","config","__spreadValues","__async","isWeb","globalStateKey","getGlobalStateKey","frigadeGlobalState","_a","GUEST_PREFIX","userId","properties","__spreadProps","groupId","event","sessionDTO","flowId","flow","resetAllLocalStorage","clearCache","handler","lastFlow","cloneFlow","h","that","validator","target","key","value","previousState","newState","Rules","overrideFlowStateRaw","_b","flowStateRaw","rulesData","ruleId","visible","currentRule","statefulFlow","Flow","flowIds","flowIdsWithWrappedCallbacks","_0","callback","currentFlow","prevFlow","results","TriggerType","FlowStatus","FlowType"]}
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.ts","../src/core/frigade.ts","../src/core/types.ts"],"sourcesContent":["export { Frigade } from './core/frigade'\nexport { Flow } from './core/flow'\nexport {\n FlowStatus,\n type FlowStep,\n type FrigadeConfig,\n FlowType,\n type StatefulFlow,\n TriggerType,\n PropertyPayload,\n} from './core/types'\nexport type { RulesRegistryCallback, RulesRegistryBatch } from './core/rules'\n","export const VERSION_NUMBER = '0.2.20'\n","import { VERSION_NUMBER } from '../core/version'\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'\nconst GUEST_KEY = 'frigade-guest-key'\nexport const GUEST_PREFIX = 'guest_'\nconst GET_CACHE_PREFIX = 'get-cache-'\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\nclass CallQueue {\n private queue: {\n call: string\n time: number\n }[] = []\n private readonly ttlInMS = 500\n private readonly cacheSize = 5\n\n public push(call: string) {\n const now = new Date()\n if (this.queue.length >= this.cacheSize) {\n this.queue.shift()\n }\n this.queue.push({\n call: call,\n time: now.getTime(),\n })\n }\n\n public hasIdenticalCall(call: string) {\n const now = new Date()\n this.queue = this.queue.filter((item) => now.getTime() - item.time < this.ttlInMS)\n return this.queue.some((item) => item.call === call)\n }\n}\n\nconst callQueue = new CallQueue()\n\nexport async function gracefulFetch(url: string, options: any) {\n if (typeof globalThis.fetch !== 'function') {\n return getEmptyResponse(\n \"- Attempted to call fetch() in an environment that doesn't support it.\"\n )\n }\n\n if (isWeb() && options && options.body && options.method === 'POST') {\n const lastCallDataKey = `${url}${JSON.stringify(options.body ?? {})}`\n if (callQueue.hasIdenticalCall(lastCallDataKey)) {\n return getEmptyResponse()\n }\n callQueue.push(lastCallDataKey)\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) {\n return getEmptyResponse()\n }\n\n let body\n try {\n body = await response.json()\n } catch (e) {\n return getEmptyResponse()\n }\n\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 { FlowStates, FlowStep, FrigadeConfig, StatefulFlow } from '../core/types'\nimport { Flow } from '../core/flow'\nimport type { Rules } from '../core/rules'\n\nexport interface FrigadeGlobalState {\n refreshStateFromAPI: (overrideFlowStatesRaw?: FlowStates) => Promise<void>\n flowStates: Record<string, StatefulFlow>\n rules: Rules\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 lastSyncDate?: Date\n config: FrigadeConfig\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}`\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',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(12).substring(4),\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 return `${this.config.apiUrl.replace(/\\/$/, '')}/${path.replace(/^\\//, '')}`\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 has not yet been initialized')\n }\n return frigadeGlobalState[globalStateKey]\n }\n}\n","import {\n FlowActionType,\n FlowStateDTO,\n FlowStates,\n FlowStep,\n FrigadeConfig,\n PropertyPayload,\n StatefulFlow,\n StatefulStep,\n} from './types'\nimport {\n clone,\n cloneFlow,\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 { RulesRegistryCallback } from './rules'\n\nexport class Flow extends Fetchable {\n /**\n * The Flow's ID.\n */\n public id: string\n /**\n * The Flow's component ID.\n */\n public componentId: 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().rules.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 Object.keys(stepObj).forEach((key) => {\n existingStep[key] = stepObj[key]\n })\n }\n })\n\n if (this.steps && this.steps.size > 0) {\n this.applyVariables(this.getGlobalState().variables[this.id] ?? {})\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?: PropertyPayload) => {\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 await this.sendFlowStateToAPI(STARTED_STEP, properties, thisStep.id)\n }\n\n stepObj.complete = async (properties?: PropertyPayload, optimistic: boolean = true) => {\n const thisStep = this.steps.get(step.id)\n\n if (optimistic) {\n const isLastStep = thisStep.order + 1 === this.getNumberOfAvailableSteps()\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\n // If there are more index, advance current step\n if (!isLastStep) {\n copy.$state.currentStepId = this.getStepByIndex(thisStep.order + 1).id\n copy.$state.currentStepIndex = thisStep.order + 1\n }\n\n if (isLastStep) {\n copy.$state.completed = true\n }\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n if (isLastStep) {\n this.optimisticallyMarkFlowCompleted()\n }\n }\n\n await this.sendFlowStateToAPI(COMPLETED_STEP, properties, thisStep.id)\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.sendFlowStateToAPI(NOT_STARTED_STEP, undefined, thisStep.id)\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?: PropertyPayload) {\n if (this.isStarted || this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowStarted()\n\n await this.sendFlowStateToAPI(STARTED_FLOW, properties)\n }\n\n /**\n * Marks the flow completed\n */\n public async complete(properties?: PropertyPayload) {\n if (this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowCompleted()\n await this.sendFlowStateToAPI(COMPLETED_FLOW, properties)\n }\n\n /**\n * Marks the flow skipped\n */\n public async skip(properties?: PropertyPayload) {\n if (this.isSkipped) {\n return\n }\n this.optimisticallyMarkFlowSkipped()\n await this.sendFlowStateToAPI(SKIPPED_FLOW, properties)\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?: PropertyPayload) {\n const nextStep = this.getStepByIndex(this.getCurrentStepIndex() + 1)\n if (nextStep) {\n await nextStep.start(properties)\n } else {\n await this.complete(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?: PropertyPayload) {\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 this.optimisticallyMarkFlowNotStarted()\n await this.sendFlowStateToAPI(NOT_STARTED_FLOW)\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 return (\n this.steps.get(this.getStatefulFlow().$state.currentStepId) ??\n this.steps.get(Array.from(this.steps.keys())[0])\n )\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 (flow.id === this.id) {\n if (\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 }\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 * Apply variables to the flow. This will replace any `${variable}` in the title, subtitle, and step fields with the value of the variable.\n * @param variables A record of variables to apply to the flow.\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[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 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 optimisticallyMarkFlowStarted() {\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\n /**\n * @ignore\n */\n private optimisticallyMarkFlowNotStarted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = false\n copy.$state.started = false\n copy.$state.visible = true\n copy.$state.currentStepIndex = 0\n copy.$state.currentStepId = this.getStepByIndex(0)?.id\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n private async sendFlowStateToAPI(\n action: FlowActionType,\n data?: PropertyPayload,\n stepId?: string\n ) {\n const date = new Date()\n this.getGlobalState().lastSyncDate = date\n const flowStatesRaw: FlowStates = await this.fetch('/v1/public/flowStates', {\n method: 'POST',\n body: JSON.stringify({\n userId: this.getGlobalState().config.userId,\n groupId: this.getGlobalState().config.groupId,\n flowSlug: this.id,\n stepId: stepId ?? this.getCurrentStep().id,\n data: data ? data : {},\n actionType: action,\n createdAt: date,\n } as FlowStateDTO),\n })\n if (date < this.getGlobalState().lastSyncDate) {\n return\n }\n await this.getGlobalState().refreshStateFromAPI(flowStatesRaw)\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?: RulesRegistryCallback) {\n const globalState = this.getGlobalState()\n\n globalState.rules.register(this.id, (visible) => {\n const prevFlow = this.getGlobalState().previousFlows.get(this.id)\n\n if (prevFlow?._isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(this, prevFlow)\n this.getGlobalState().previousFlows.set(this.id, cloneFlow(this))\n })\n }\n\n callback?.(visible)\n })\n }\n\n public unregister() {\n this.getGlobalState().rules.unregister(this.id)\n }\n}\n","export type RulesRegistryCallback = (visible: boolean) => void\n\nexport type RulesRegistryBatch = [string, RulesRegistryCallback][]\n\nexport interface RulesRegistryItem {\n visible: boolean\n visited: boolean\n callback: RulesRegistryCallback\n}\n\nexport type Rule = Array<{\n flowId: string\n visible: boolean\n}>\n\nexport type RulesData = Map<string, Rule>\n\nexport class Rules {\n private readonly registry: Map<string, RulesRegistryItem> = new Map()\n private registryStateLocked: boolean = false\n private rules: Map<string, Rule> = new Map()\n private flowsInRules: Set<string> = new Set()\n\n constructor(rulesData: RulesData) {\n this.ingestRulesData(rulesData)\n }\n\n ingestRulesData(rulesData: RulesData) {\n this.rules = rulesData\n\n for (const [, rule] of this.rules) {\n for (const { flowId } of rule) {\n this.flowsInRules.add(flowId)\n }\n }\n\n if (this.registry.size > 0) {\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n }\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 registeredFlow = this.registry.get(flowId)\n const flowInRules = this.flowsInRules.has(flowId)\n\n if (registeredFlow == null || !flowInRules) {\n return true\n }\n\n return registeredFlow.visible\n }\n\n lockRegistryState() {\n this.registryStateLocked = true\n }\n\n unlockRegistryState() {\n this.registryStateLocked = false\n }\n\n resetRegistryState() {\n for (const [flowId, item] of this.registry) {\n item.visible = false\n item.visited = false\n\n this.registry.set(flowId, item)\n }\n }\n\n processRules() {\n for (const [, rule] of this.rules) {\n for (const { flowId, visible: visibleAPIOverride } of rule) {\n const registeredFlow = this.registry.get(flowId)\n\n // If this flow in the rule isn't registered, we have no opinion on it yet\n if (registeredFlow == null) {\n continue\n }\n\n // The API can force a flow to be hidden due to cool-offs, etc.\n if (visibleAPIOverride === false && registeredFlow.visible !== true) {\n this.visit(flowId, false)\n continue\n }\n\n // If this flow was processed in a previous rule and the registry is locked,\n // visibility shouldn't change until next time we run processRules\n if (registeredFlow.visited && this.registryStateLocked) {\n continue\n }\n\n const flowIdsInThisRule = rule\n .map(({ flowId: otherFlowId }) => otherFlowId)\n .filter((otherFlowId) => otherFlowId !== flowId)\n\n // If another flow in this rule has been visited already and is visible...\n const anotherFlowInThisRuleIsVisible = flowIdsInThisRule.some((otherId) => {\n const { visible: otherVisible, visited: otherVisited } = this.registry.get(otherId) ?? {}\n\n return otherVisible && otherVisited\n })\n\n // ...then this flow is hidden\n if (anotherFlowInThisRuleIsVisible) {\n this.visit(flowId, false)\n\n continue\n }\n\n // No other flows are visible, so this flow is visible by default\n this.visit(flowId)\n }\n }\n }\n\n register(flowId: string | RulesRegistryBatch, callback?: RulesRegistryCallback) {\n if (Array.isArray(flowId)) {\n this.batchRegister(flowId)\n return\n }\n\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.fireCallbacks()\n }\n\n batchRegister(flowIds: RulesRegistryBatch) {\n flowIds.forEach(([flowId, callback]) => {\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.lockRegistryState()\n\n this.fireCallbacks()\n }\n\n unregister(flowId: string) {\n this.registry.delete(flowId)\n\n this.resetRegistryState()\n this.processRules()\n\n this.fireCallbacks()\n }\n\n private visit(flowId: string, visible: boolean = true) {\n const item = this.registry.get(flowId) ?? {\n callback: () => {},\n visible,\n visited: true,\n }\n\n item.visible = visible\n item.visited = true\n\n this.registry.set(flowId, item)\n }\n}\n","import { FlowStates, FrigadeConfig, PropertyPayload, SessionDTO, StatefulFlow } 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 { Rules, type RulesRegistryBatch } from './rules'\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 }\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 * Gets the current configuration.\n */\n getConfig() {\n return this.config\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.updateConfig({\n ...this.config,\n ...config,\n })\n\n this.initPromise = (async () => {\n if (!this.config.__readOnly) {\n if (this.config.userId?.startsWith(GUEST_PREFIX)) {\n // do nothing\n } else if (this.config.userId && this.config.groupId) {\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n })\n } else if (this.config.userId) {\n await this.session({\n userId: 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?: PropertyPayload): Promise<void> {\n await this.updateConfig({ ...this.config, userId })\n await this.initIfNeeded()\n await this.session({\n userId: this.config.userId,\n userProperties: properties,\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?: PropertyPayload): Promise<void> {\n await this.initIfNeeded()\n this.updateConfig({ ...this.config, groupId })\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupProperties: properties,\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?: PropertyPayload): 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.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupEvents: [\n {\n event,\n properties,\n },\n ],\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n } else if (this.config.userId) {\n await this.session({\n userId: this.config.userId,\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n }\n await this.resync()\n }\n\n /**\n * @ignore\n */\n private async session(sessionDTO: SessionDTO) {\n await this.fetch('/v1/public/sessions', {\n method: 'POST',\n body: JSON.stringify(sessionDTO),\n })\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 * @param config optional config to use when reloading. If not passed, the current config will be used.\n */\n public async reload(config?: FrigadeConfig) {\n resetAllLocalStorage()\n clearCache()\n if (config) {\n await this.updateConfig(config)\n this.mockFlowStates(getGlobalStateKey(this.config))\n }\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 await this.refreshStateFromAPI()\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 rules: new Rules(new Map()),\n flowStates: new Proxy({}, validator),\n onFlowStateChangeHandlerWrappers: new Map(),\n onStepStateChangeHandlerWrappers: new Map(),\n onFlowStateChangeHandlers: [],\n previousFlows: new Map(),\n variables: {},\n config: this.config,\n }\n\n if (this.config.__readOnly && this.config.__flowStateOverrides) {\n this.mockFlowStates(globalStateKey)\n\n return\n }\n\n frigadeGlobalState[globalStateKey].refreshStateFromAPI = async (\n overrideFlowStateRaw?: FlowStates\n ) => {\n if (this.config.__readOnly) {\n return\n }\n\n const flowStateRaw: FlowStates = overrideFlowStateRaw\n ? overrideFlowStateRaw\n : await this.fetch(\n `/v1/public/flowStates?userId=${encodeURIComponent(this.config.userId)}${\n this.config.groupId ? `&groupId=${encodeURIComponent(this.config.groupId)}` : ''\n }`\n )\n\n const rulesData = new Map()\n\n flowStateRaw.collections?.computedOrder?.forEach(({ collectionId, flowId, visible }) => {\n const currentRule = rulesData.get(collectionId) ?? []\n\n currentRule.push({\n flowId,\n visible,\n })\n\n rulesData.set(collectionId, currentRule)\n })\n\n frigadeGlobalState[globalStateKey].rules.ingestRulesData(rulesData)\n\n if (flowStateRaw && flowStateRaw.eligibleFlows) {\n flowStateRaw.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 } else {\n this.flows.forEach((flow) => {\n if (flow.id == statefulFlow.flowSlug) {\n flow.resyncState(statefulFlow)\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 mockFlowStates(globalStateKey: string) {\n Object.keys(this.config.__flowStateOverrides).forEach((flowId) => {\n frigadeGlobalState[globalStateKey].flowStates[flowId] =\n this.config.__flowStateOverrides[flowId]\n\n if (!this.flows.find((flow) => flow.id == flowId)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: flowId,\n })\n )\n } else {\n this.flows.forEach((flow) => {\n if (flow.id == flowId) {\n flow.resyncState(this.config.__flowStateOverrides[flowId])\n }\n })\n }\n })\n }\n\n /**\n * @ignore\n */\n private async updateConfig(config: FrigadeConfig) {\n this.config = {\n ...this.config,\n ...config,\n }\n if (frigadeGlobalState[getGlobalStateKey(this.config)]) {\n this.getGlobalState().config = this.config\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 /**\n * @ignore\n */\n async batchRegister(flowIds: RulesRegistryBatch) {\n const flowIdsWithWrappedCallbacks = flowIds.map(async ([flowId, callback]) => {\n const currentFlow = await this.getFlow(flowId)\n const wrappedCallback = (visible: boolean) => {\n const prevFlow = this.getGlobalState().previousFlows.get(flowId)\n\n if (prevFlow?.isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(currentFlow, prevFlow)\n this.getGlobalState().previousFlows.set(flowId, cloneFlow(currentFlow))\n })\n }\n\n callback?.(visible)\n }\n\n return [flowId, wrappedCallback] as RulesRegistryBatch[number]\n })\n\n Promise.all(flowIdsWithWrappedCallbacks).then((results) => {\n this.getGlobalState().rules.batchRegister(results)\n })\n }\n}\n","import type { Flow } from './flow'\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 type PropertyPayload = Record<string, any>\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 * @description 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 * @description Primary button URI.\n */\n primaryButtonUri?: string\n\n /**\n * @deprecated Use primaryButton.target instead\n * @description 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 * @description 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 * @description Secondary button URI.\n */\n secondaryButtonUri?: string\n\n /**\n * @deprecated Use secondaryButton.target instead\n * @description 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?: PropertyPayload) => Promise<void>\n\n /**\n * Marks the step completed.\n * @param optimistic If true, the step will be marked as completed without waiting for the API and validation of any targeting rules.\n */\n complete: (properties?: PropertyPayload, optimistic?: boolean) => 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 State for all flows in the app that should be mocked.\n */\n __flowStateOverrides?: Record<string, StatefulFlow>\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 ComputedCollection {\n collectionId: string\n flowId: string\n visible: boolean\n}\n\nexport interface CollectionMetadata {\n computedOrder: ComputedCollection[]\n}\n\nexport interface FlowStates {\n eligibleFlows: StatefulFlow[]\n ineligibleFlows: string[]\n collections?: CollectionMetadata\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\nexport type FlowActionType =\n | 'STARTED_STEP'\n | 'COMPLETED_STEP'\n | 'NOT_STARTED_STEP'\n | 'STARTED_FLOW'\n | 'COMPLETED_FLOW'\n | 'SKIPPED_FLOW'\n | 'NOT_STARTED_FLOW'\n\nexport interface FlowStateDTO {\n userId: string\n groupId?: string\n flowSlug: string\n stepId?: string\n data?: any\n actionType: FlowActionType\n createdAt?: Date\n}\n\nexport interface TrackingEvent {\n event: string\n properties?: { [key: string]: any }\n}\n\nexport interface SessionDTO {\n userId: string\n groupId?: string\n userProperties?: { [key: string]: any }\n userEvents?: TrackingEvent[]\n groupProperties?: { [key: string]: any }\n groupEvents?: TrackingEvent[]\n linkGuestId?: string\n}\n"],"mappings":";k9BAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,UAAAE,EAAA,eAAAC,EAAA,aAAAC,EAAA,YAAAC,EAAA,gBAAAC,IAAA,eAAAC,GAAAP,ICAO,IAAMQ,EAAiB,SCC9B,IAAAC,EAA6B,gBCsBtB,IAAIC,EAAyD,CAAC,EAE9D,SAASC,EAAkBC,EAAuC,CACvE,MAAO,GAAGA,EAAe,gBAAgBA,EAAe,QAC1D,CCvBO,IAAMC,EAAN,KAAgB,CAQrB,YAAYC,EAAuB,CAPnC,KAAO,OAAwB,CAC7B,OAAQ,GACR,OAAQ,0BACR,OAAQC,EAAgB,EACxB,aAAc,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,UAAU,CAAC,CACtD,EAGE,IAAMC,EAAiB,O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,KAAK,eAAe,EAAE,MAAM,cAAcA,CAAO,CACnD,CAAC,CACH,GACF,EC3bO,IAAKC,OACVA,EAAA,OAAS,SACTA,EAAA,UAAY,YAFFA,OAAA,IAKAC,OACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SACTA,EAAA,SAAW,WAHDA,OAAA,IAoTAC,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_uuid","frigadeGlobalState","getGlobalStateKey","internalConfig","Fetchable","config","generateGuestId","filteredConfig","_","v","__spreadValues","path","options","__async","getEmptyResponse","gracefulFetch","getHeaders","globalStateKey","getGlobalStateKey","frigadeGlobalState","Flow","Fetchable","config","id","visible","overrideStatefulFlow","_a","_b","_c","statefulFlow","step","index","stepObj","existingStep","key","__spreadProps","__spreadValues","newSteps","properties","__async","thisStep","copy","clone","STARTED_STEP","optimistic","isLastStep","COMPLETED_STEP","NOT_STARTED_STEP","handler","wrapperHandler","flow","previousStep","h","STARTED_FLOW","COMPLETED_FLOW","SKIPPED_FLOW","nextStep","NOT_STARTED_FLOW","currentStep","previousFlow","variables","replaceVariables","str","matches","match","variable","action","data","stepId","date","flowStatesRaw","callback","prevFlow","cloneFlow","NOT_STARTED_STEP","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","GUEST_KEY","GUEST_PREFIX","GET_CACHE_PREFIX","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","CallQueue","call","now","item","callQueue","gracefulFetch","url","options","__async","_a","getEmptyResponse","lastCallDataKey","response","error","body","e","generateGuestId","guestId","getLocalStorage","GUEST_KEY","GUEST_PREFIX","uuidv4","setLocalStorage","isWeb","Rules","rulesData","rule","flowId","callback","registeredFlow","flowInRules","item","visibleAPIOverride","otherFlowId","otherId","_a","otherVisible","otherVisited","flowIds","visible","Frigade","Fetchable","apiKey","config","__spreadValues","__async","isWeb","globalStateKey","getGlobalStateKey","frigadeGlobalState","_a","GUEST_PREFIX","userId","properties","__spreadProps","groupId","event","sessionDTO","flowId","flow","resetAllLocalStorage","clearCache","handler","lastFlow","cloneFlow","h","that","validator","target","key","value","previousState","newState","Rules","overrideFlowStateRaw","_b","flowStateRaw","rulesData","collectionId","visible","currentRule","statefulFlow","Flow","flowIds","flowIdsWithWrappedCallbacks","_0","callback","currentFlow","prevFlow","results","TriggerType","FlowStatus","FlowType"]}
package/dist/index.d.ts CHANGED
@@ -56,6 +56,10 @@ declare class Flow extends Fetchable {
56
56
  * The Flow's ID.
57
57
  */
58
58
  id: string;
59
+ /**
60
+ * The Flow's component ID.
61
+ */
62
+ componentId: string;
59
63
  /**
60
64
  * Ordered map of the Steps in the Flow.
61
65
  * See [Flow Step Definition](https://docs.frigade.com/v2/sdk/js/step) for more information.
@@ -173,7 +177,8 @@ declare class Flow extends Fetchable {
173
177
  */
174
178
  removeStateChangeHandler(handler: (flow: Flow, previousFlow: Flow) => void): void;
175
179
  /**
176
- * @ignore
180
+ * Apply variables to the flow. This will replace any `${variable}` in the title, subtitle, and step fields with the value of the variable.
181
+ * @param variables A record of variables to apply to the flow.
177
182
  */
178
183
  applyVariables(variables: Record<string, any>): void;
179
184
  /**
@@ -184,6 +189,10 @@ declare class Flow extends Fetchable {
184
189
  * @ignore
185
190
  */
186
191
  private optimisticallyMarkFlowCompleted;
192
+ /**
193
+ * @ignore
194
+ */
195
+ private optimisticallyMarkFlowStarted;
187
196
  /**
188
197
  * @ignore
189
198
  */
@@ -435,18 +444,18 @@ interface StatefulFlow {
435
444
  lastActionAt?: Date;
436
445
  };
437
446
  }
438
- interface ComputedRule {
439
- ruleId: string;
447
+ interface ComputedCollection {
448
+ collectionId: string;
440
449
  flowId: string;
441
450
  visible: boolean;
442
451
  }
443
- interface RulesMetadata {
444
- computedOrder: ComputedRule[];
452
+ interface CollectionMetadata {
453
+ computedOrder: ComputedCollection[];
445
454
  }
446
455
  interface FlowStates {
447
456
  eligibleFlows: StatefulFlow[];
448
457
  ineligibleFlows: string[];
449
- rules?: RulesMetadata;
458
+ collections?: CollectionMetadata;
450
459
  }
451
460
  declare enum FlowType {
452
461
  ANNOUNCEMENT = "ANNOUNCEMENT",
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  "use client";
2
- var Y=Object.defineProperty,Q=Object.defineProperties;var Z=Object.getOwnPropertyDescriptors;var _=Object.getOwnPropertySymbols;var tt=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var G=(r,s,t)=>s in r?Y(r,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[s]=t,h=(r,s)=>{for(var t in s||(s={}))tt.call(s,t)&&G(r,t,s[t]);if(_)for(var t of _(s))et.call(s,t)&&G(r,t,s[t]);return r},m=(r,s)=>Q(r,Z(s));var d=(r,s,t)=>new Promise((e,i)=>{var a=l=>{try{o(t.next(l))}catch(c){i(c)}},g=l=>{try{o(t.throw(l))}catch(c){i(c)}},o=l=>l.done?e(l.value):Promise.resolve(l.value).then(a,g);o((t=t.apply(r,s)).next())});var x="0.2.20";import{v4 as it}from"uuid";var f={};function w(r){return`${r.__instanceId}-${r.apiKey}`}var F=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:k(),__instanceId:Math.random().toString(12).substring(4)};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));this.config=h(h({},this.config),t)}fetch(s,t){return d(this,null,function*(){return this.config.__readOnly?u():$(this.getAPIUrl(s),h(h({keepalive:!0},t!=null?t:{}),D(this.config.apiKey)))})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=w(this.config);if(!f[s])throw new Error("Frigade has not yet been initialized");return f[s]}};var b=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().rules.isFlowVisible(this.id)}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,a,g;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=(a=e==null?void 0:e.data)==null?void 0:a.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((o,l)=>{var n;let c=this.initStepFromStatefulStep(o,l),p=(n=this.steps)==null?void 0:n.get(o.id);p&&Object.keys(c).forEach(I=>{p[I]=c[I]})}),this.steps&&this.steps.size>0&&this.applyVariables((g=this.getGlobalState().variables[this.id])!=null?g:{})}initStepFromStatefulStep(t,e){return m(h({},t),{flow:this,$state:m(h({},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,a)=>{let g=this.initStepFromStatefulStep(i,a);g.start=o=>d(this,null,function*(){let l=this.steps.get(i.id);if(this.getCurrentStep().id===l.id&&l.$state.started)return;let c=S(this.getGlobalState().flowStates[this.id]);c.data.steps[l.order].$state.started=!0,c.data.steps[l.order].$state.lastActionAt=new Date,c.$state.lastActionAt=new Date,c.$state.currentStepId=l.id,c.$state.currentStepIndex=l.order,this.getGlobalState().flowStates[this.id]=c,this.resyncState(),l.$state.completed||(yield this.sendFlowStateToAPI(W,o,l.id))}),g.complete=(o,l=!0)=>d(this,null,function*(){let c=this.steps.get(i.id);if(!c.$state.completed){if(l){let p=c.order+1===this.getNumberOfAvailableSteps(),n=S(this.getGlobalState().flowStates[this.id]);n.$state.started=!0,n.data.steps[c.order].$state.completed=!0,n.data.steps[c.order].$state.started=!0,n.data.steps[c.order].$state.lastActionAt=new Date,p||(n.$state.currentStepId=this.getStepByIndex(c.order+1).id,n.$state.currentStepIndex=c.order+1),p&&(n.$state.completed=!0),this.getGlobalState().flowStates[this.id]=n,this.resyncState(),p&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(V,o,c.id)}}),g.reset=()=>d(this,null,function*(){let o=this.steps.get(i.id);if(!o.$state.completed)return;let l=S(this.getGlobalState().flowStates[this.id]);l.data.steps[o.order].$state.started=!1,l.data.steps[o.order].$state.completed=!1,l.data.steps[o.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=l,this.resyncState(),yield this.sendFlowStateToAPI(M,void 0,o.id)}),g.onStateChange=o=>{let l=c=>{if(c.id!==this.id)return;let p=c.steps.get(i.id),n=this.lastStepUpdate.get(o);(p.$state.completed!==(n==null?void 0:n.$state.completed)||p.$state.started!==(n==null?void 0:n.$state.started)||p.$state.visible!==(n==null?void 0:n.$state.visible)||p.$state.blocked!==(n==null?void 0:n.$state.blocked))&&(o(p,n!=null?n:S(p)),this.lastStepUpdate.set(o,S(p)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(o,l),this.getGlobalState().onFlowStateChangeHandlers.push(l)},g.removeStateChangeHandler=o=>{let l=this.getGlobalState().onStepStateChangeHandlerWrappers.get(o);l&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(c=>c!==l))},e.set(i.id,g)}),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 d(this,null,function*(){if(this.isStarted||this.isCompleted)return;let e=S(this.getGlobalState().flowStates[this.id]);e.$state.started=!0,this.getGlobalState().flowStates[this.id]=e,this.resyncState(),yield this.sendFlowStateToAPI(H,t)})}complete(t){return d(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(N,t))})}skip(t){return d(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(L,t))})}forward(t){return d(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()+1);e?yield e.start(t):yield this.complete(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*(){this.optimisticallyMarkFlowNotStarted(),yield this.sendFlowStateToAPI(U)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){var t;return(t=this.steps.get(this.getStatefulFlow().$state.currentStepId))!=null?t:this.steps.get(Array.from(this.steps.keys())[0])}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,a)=>{i.id===this.id&&(i.isCompleted!==(a==null?void 0:a.isCompleted)||i.isStarted!==(a==null?void 0:a.isStarted)||i.isSkipped!==(a==null?void 0:a.isSkipped)||i.isVisible!==(a==null?void 0:a.isVisible)||JSON.stringify(i.steps)!==JSON.stringify(a==null?void 0:a.steps))&&t(i,a)};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,a;let e=g=>{let o=g.match(/\${(.*?)}/g);return o&&o.forEach(l=>{let c=l.replace("${","").replace("}","");t[c]&&(g=g.replace(l,t[c]))}),g};this.title=e((i=this.title)!=null?i:""),this.subtitle=e((a=this.subtitle)!=null?a:""),this.steps.forEach(g=>{Object.keys(g).forEach(o=>{typeof g[o]=="string"&&(g[o]=e(g[o]))})}),this.getGlobalState().variables={},this.getGlobalState().variables[this.id]=t}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=S(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()}optimisticallyMarkFlowNotStarted(){var e;let t=S(this.getGlobalState().flowStates[this.id]);t.$state.completed=!1,t.$state.started=!1,t.$state.visible=!0,t.$state.currentStepIndex=0,t.$state.currentStepId=(e=this.getStepByIndex(0))==null?void 0:e.id,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}sendFlowStateToAPI(t,e,i){return d(this,null,function*(){let a=new Date;this.getGlobalState().lastSyncDate=a;let g=yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,flowSlug:this.id,stepId:i!=null?i:this.getCurrentStep().id,data:e||{},actionType:t,createdAt:a})});a<this.getGlobalState().lastSyncDate||(yield this.getGlobalState().refreshStateFromAPI(g))})}optimisticallyMarkFlowSkipped(){let t=S(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().rules.register(this.id,i=>{let a=this.getGlobalState().previousFlows.get(this.id);(a==null?void 0:a._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(g=>{g(this,a),this.getGlobalState().previousFlows.set(this.id,R(this))}),t==null||t(i)})}unregister(){this.getGlobalState().rules.unregister(this.id)}};var M="NOT_STARTED_STEP",N="COMPLETED_FLOW",L="SKIPPED_FLOW",H="STARTED_FLOW",U="NOT_STARTED_FLOW",V="COMPLETED_STEP",W="STARTED_STEP",B="frigade-guest-key",P="guest_",st="get-cache-",E="fr-js-";function R(r){return new b({config:r.config,id:r.id})}function S(r){return JSON.parse(JSON.stringify(r))}function D(r){return{headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json","X-Frigade-SDK-Version":x,"X-Frigade-SDK-Platform":"Javascript"}}}function at(r){return y()?window.localStorage.getItem(`${E}${r}`):null}function rt(r,s){y()&&window.localStorage.setItem(`${E}${r}`,s)}function j(){Object.keys(f).forEach(r=>{r.startsWith(st)&&delete f[r]})}function J(){y()&&Object.keys(window.localStorage).forEach(r=>{r.startsWith(E)&&window.localStorage.removeItem(r)})}var C=class{constructor(){this.queue=[];this.ttlInMS=500;this.cacheSize=5}push(s){let t=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:s,time:t.getTime()})}hasIdenticalCall(s){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.some(e=>e.call===s)}},K=new C;function $(r,s){return d(this,null,function*(){var e;if(typeof globalThis.fetch!="function")return u("- Attempted to call fetch() in an environment that doesn't support it.");if(y()&&s&&s.body&&s.method==="POST"){let i=`${r}${JSON.stringify((e=s.body)!=null?e:{})}`;if(K.hasIdenticalCall(i))return u();K.push(i)}let t;try{t=fetch(r,s),t=yield t}catch(i){return u(i)}if(!t)return u("Received an empty response");if(t.status>=400)return u(t.statusText);try{if(t.status===204)return u();let i;try{i=yield t.json()}catch(a){return u()}return i.error?u(i.error):i}catch(i){return u(i)}})}function u(r){return r&&console.log("Call to Frigade failed",r),{json:()=>({})}}function k(){if(y()){let r=at(B);return r||(r=`${P}${it()}`,rt(B,r)),r}}function y(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}var v=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.rules=new Map;this.flowsInRules=new Set;this.ingestRulesData(s)}ingestRulesData(s){this.rules=s;for(let[,t]of this.rules)for(let{flowId:e}of t)this.flowsInRules.add(e);this.registry.size>0&&(this.registryStateLocked||this.resetRegistryState(),this.processRules()),this.fireCallbacks()}fireCallbacks(){for(let[s,{callback:t}]of this.registry)typeof t=="function"&&t(this.isFlowVisible(s))}isFlowVisible(s){let t=this.registry.get(s),e=this.flowsInRules.has(s);return t==null||!e?!0:t.visible}lockRegistryState(){this.registryStateLocked=!0}unlockRegistryState(){this.registryStateLocked=!1}resetRegistryState(){for(let[s,t]of this.registry)t.visible=!1,t.visited=!1,this.registry.set(s,t)}processRules(){for(let[,s]of this.rules)for(let{flowId:t,visible:e}of s){let i=this.registry.get(t);if(i==null)continue;if(e===!1&&i.visible!==!0){this.visit(t,!1);continue}if(i.visited&&this.registryStateLocked)continue;if(s.map(({flowId:o})=>o).filter(o=>o!==t).some(o=>{var p;let{visible:l,visited:c}=(p=this.registry.get(o))!=null?p:{};return l&&c})){this.visit(t,!1);continue}this.visit(t)}}register(s,t){if(Array.isArray(s)){this.batchRegister(s);return}this.registry.set(s,{callback:t!=null?t:()=>{},visible:!1,visited:!1}),this.registryStateLocked||this.resetRegistryState(),this.processRules(),this.fireCallbacks()}batchRegister(s){s.forEach(([t,e])=>{this.registry.set(t,{callback:e!=null?e:()=>{},visible:!1,visited:!1})}),this.registryStateLocked||this.resetRegistryState(),this.processRules(),this.lockRegistryState(),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.resetRegistryState(),this.processRules(),this.fireCallbacks()}visit(s,t=!0){var i;let e=(i=this.registry.get(s))!=null?i:{callback:()=>{},visible:t,visited:!0};e.visible=t,e.visited=!0,this.registry.set(s,e)}};var T=class extends F{constructor(t,e){super(h({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.visibilityChangeHandler=()=>d(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshStateFromAPI())});this.init(this.config),y()&&document.addEventListener("visibilitychange",this.visibilityChangeHandler)}getConfig(){return this.config}destroy(){if(y()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=w(this.config);f[t]&&(f[t].onFlowStateChangeHandlers=[])}}init(t){return d(this,null,function*(){return this.updateConfig(h(h({},this.config),t)),this.initPromise=(()=>d(this,null,function*(){var e;this.config.__readOnly||(e=this.config.userId)!=null&&e.startsWith(P)||(this.config.userId&&this.config.groupId?yield this.session({userId:this.config.userId,groupId:this.config.groupId}):this.config.userId&&(yield this.session({userId:this.config.userId}))),yield this.refreshStateFromAPI()}))(),this.initPromise})}identify(t,e){return d(this,null,function*(){this.updateConfig(m(h({},this.config),{userId:t})),yield this.initIfNeeded(),yield this.session({userId:this.config.userId,userProperties:e}),yield this.resync()})}group(t,e){return d(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(m(h({},this.config),{groupId:t})),yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupProperties: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.session({userId:this.config.userId,groupId:this.config.groupId,groupEvents:[{event:t,properties:e}],userEvents:[{event:t,properties:e}]}):this.config.userId&&(yield this.session({userId:this.config.userId,userEvents:[{event:t,properties:e}]})),yield this.resync()})}session(t){return d(this,null,function*(){yield this.fetch("/v1/public/sessions",{method:"POST",body:JSON.stringify(t)})})}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(t){return d(this,null,function*(){J(),j(),t&&(yield this.updateConfig(t),this.mockFlowStates(w(this.config))),this.initPromise=null,yield this.init(this.config),this.flows.forEach(e=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(i=>{let a=this.getGlobalState().previousFlows.get(e.id);i(e,a),this.getGlobalState().previousFlows.set(e.id,R(e))})})})}resync(){return d(this,null,function*(){yield this.refreshStateFromAPI()})}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)})}refreshStateFromAPI(){return d(this,null,function*(){let t=w(this.config);if(!f[t]){let e=this,i={set:function(a,g,o){if(a[g]){let l=a[g],c=o;JSON.stringify(l)!==JSON.stringify(c)&&e.triggerEventHandlers(c,l)}return a[g]=o,!0}};if(f[t]={refreshStateFromAPI:()=>d(this,null,function*(){}),rules:new v(new Map),flowStates:new Proxy({},i),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(t);return}f[t].refreshStateFromAPI=a=>d(this,null,function*(){var l,c;if(this.config.__readOnly)return;let g=a||(yield this.fetch(`/v1/public/flowStates?userId=${encodeURIComponent(this.config.userId)}${this.config.groupId?`&groupId=${encodeURIComponent(this.config.groupId)}`:""}`)),o=new Map;(c=(l=g.rules)==null?void 0:l.computedOrder)==null||c.forEach(({ruleId:p,flowId:n,visible:I})=>{var O;let A=(O=o.get(p))!=null?O:[];A.push({flowId:n,visible:I}),o.set(p,A)}),f[t].rules.ingestRulesData(o),g&&g.eligibleFlows?(g.eligibleFlows.forEach(p=>{f[t].flowStates[p.flowSlug]=p,this.flows.find(n=>n.id==p.flowSlug)||this.flows.push(new b({config:this.config,id:p.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield f[t].refreshStateFromAPI()})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{f[t].flowStates[e]=this.config.__flowStateOverrides[e],this.flows.find(i=>i.id==e)?this.flows.forEach(i=>{i.id==e&&i.resyncState(this.config.__flowStateOverrides[e])}):this.flows.push(new b({config:this.config,id:e}))})}updateConfig(t){return d(this,null,function*(){this.config=h(h({},this.config),t),f[w(this.config)]&&(this.getGlobalState().config=this.config)})}triggerEventHandlers(t,e){return d(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(a=>{let g=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),a(i,g),this.getGlobalState().previousFlows.set(i.id,R(i))})})})}batchRegister(t){return d(this,null,function*(){let e=t.map(g=>d(this,[g],function*([i,a]){let o=yield this.getFlow(i);return[i,c=>{let p=this.getGlobalState().previousFlows.get(i);(p==null?void 0:p.isVisible)!==c&&this.getGlobalState().onFlowStateChangeHandlers.forEach(n=>{n(o,p),this.getGlobalState().previousFlows.set(i,R(o))}),a==null||a(c)}]}));Promise.all(e).then(i=>{this.getGlobalState().rules.batchRegister(i)})})}};var q=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(q||{}),z=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(z||{}),X=(n=>(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))(X||{});export{b as Flow,z as FlowStatus,X as FlowType,T as Frigade,q as TriggerType};
2
+ var Y=Object.defineProperty,Q=Object.defineProperties;var Z=Object.getOwnPropertyDescriptors;var _=Object.getOwnPropertySymbols;var tt=Object.prototype.hasOwnProperty,et=Object.prototype.propertyIsEnumerable;var G=(o,s,t)=>s in o?Y(o,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):o[s]=t,h=(o,s)=>{for(var t in s||(s={}))tt.call(s,t)&&G(o,t,s[t]);if(_)for(var t of _(s))et.call(s,t)&&G(o,t,s[t]);return o},m=(o,s)=>Q(o,Z(s));var d=(o,s,t)=>new Promise((e,i)=>{var a=l=>{try{n(t.next(l))}catch(c){i(c)}},g=l=>{try{n(t.throw(l))}catch(c){i(c)}},n=l=>l.done?e(l.value):Promise.resolve(l.value).then(a,g);n((t=t.apply(o,s)).next())});var x="0.2.20";import{v4 as it}from"uuid";var f={};function w(o){return`${o.__instanceId}-${o.apiKey}`}var F=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:k(),__instanceId:Math.random().toString(12).substring(4)};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));this.config=h(h({},this.config),t)}fetch(s,t){return d(this,null,function*(){return this.config.__readOnly?S():$(this.getAPIUrl(s),h(h({keepalive:!0},t!=null?t:{}),D(this.config.apiKey)))})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=w(this.config);if(!f[s])throw new Error("Frigade has not yet been initialized");return f[s]}};var y=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().rules.isFlowVisible(this.id)}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,a,g;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=(a=e==null?void 0:e.data)==null?void 0:a.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((n,l)=>{var r;let c=this.initStepFromStatefulStep(n,l),p=(r=this.steps)==null?void 0:r.get(n.id);p&&Object.keys(c).forEach(I=>{p[I]=c[I]})}),this.steps&&this.steps.size>0&&this.applyVariables((g=this.getGlobalState().variables[this.id])!=null?g:{})}initStepFromStatefulStep(t,e){return m(h({},t),{flow:this,$state:m(h({},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,a)=>{let g=this.initStepFromStatefulStep(i,a);g.start=n=>d(this,null,function*(){let l=this.steps.get(i.id);if(this.getCurrentStep().id===l.id&&l.$state.started)return;let c=u(this.getGlobalState().flowStates[this.id]);c.data.steps[l.order].$state.started=!0,c.data.steps[l.order].$state.lastActionAt=new Date,c.$state.lastActionAt=new Date,c.$state.currentStepId=l.id,c.$state.currentStepIndex=l.order,this.getGlobalState().flowStates[this.id]=c,this.resyncState(),yield this.sendFlowStateToAPI(W,n,l.id)}),g.complete=(n,l=!0)=>d(this,null,function*(){let c=this.steps.get(i.id);if(l){let p=c.order+1===this.getNumberOfAvailableSteps(),r=u(this.getGlobalState().flowStates[this.id]);r.$state.started=!0,r.data.steps[c.order].$state.completed=!0,r.data.steps[c.order].$state.started=!0,r.data.steps[c.order].$state.lastActionAt=new Date,p||(r.$state.currentStepId=this.getStepByIndex(c.order+1).id,r.$state.currentStepIndex=c.order+1),p&&(r.$state.completed=!0),this.getGlobalState().flowStates[this.id]=r,this.resyncState(),p&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(V,n,c.id)}),g.reset=()=>d(this,null,function*(){let n=this.steps.get(i.id);if(!n.$state.completed)return;let l=u(this.getGlobalState().flowStates[this.id]);l.data.steps[n.order].$state.started=!1,l.data.steps[n.order].$state.completed=!1,l.data.steps[n.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=l,this.resyncState(),yield this.sendFlowStateToAPI(M,void 0,n.id)}),g.onStateChange=n=>{let l=c=>{if(c.id!==this.id)return;let p=c.steps.get(i.id),r=this.lastStepUpdate.get(n);(p.$state.completed!==(r==null?void 0:r.$state.completed)||p.$state.started!==(r==null?void 0:r.$state.started)||p.$state.visible!==(r==null?void 0:r.$state.visible)||p.$state.blocked!==(r==null?void 0:r.$state.blocked))&&(n(p,r!=null?r:u(p)),this.lastStepUpdate.set(n,u(p)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(n,l),this.getGlobalState().onFlowStateChangeHandlers.push(l)},g.removeStateChangeHandler=n=>{let l=this.getGlobalState().onStepStateChangeHandlerWrappers.get(n);l&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(c=>c!==l))},e.set(i.id,g)}),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 d(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(H,t))})}complete(t){return d(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(N,t))})}skip(t){return d(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(L,t))})}forward(t){return d(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()+1);e?yield e.start(t):yield this.complete(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*(){this.optimisticallyMarkFlowNotStarted(),yield this.sendFlowStateToAPI(U)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){var t;return(t=this.steps.get(this.getStatefulFlow().$state.currentStepId))!=null?t:this.steps.get(Array.from(this.steps.keys())[0])}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,a)=>{i.id===this.id&&(i.isCompleted!==(a==null?void 0:a.isCompleted)||i.isStarted!==(a==null?void 0:a.isStarted)||i.isSkipped!==(a==null?void 0:a.isSkipped)||i.isVisible!==(a==null?void 0:a.isVisible)||JSON.stringify(i.steps)!==JSON.stringify(a==null?void 0:a.steps))&&t(i,a)};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,a;let e=g=>{let n=g.match(/\${(.*?)}/g);return n&&n.forEach(l=>{let c=l.replace("${","").replace("}","");t[c]&&(g=g.replace(l,t[c]))}),g};this.title=e((i=this.title)!=null?i:""),this.subtitle=e((a=this.subtitle)!=null?a:""),this.steps.forEach(g=>{Object.keys(g).forEach(n=>{typeof g[n]=="string"&&(g[n]=e(g[n]))})}),this.getGlobalState().variables[this.id]=t}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=u(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()}optimisticallyMarkFlowStarted(){let t=u(this.getGlobalState().flowStates[this.id]);t.$state.started=!0,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}optimisticallyMarkFlowNotStarted(){var e;let t=u(this.getGlobalState().flowStates[this.id]);t.$state.completed=!1,t.$state.started=!1,t.$state.visible=!0,t.$state.currentStepIndex=0,t.$state.currentStepId=(e=this.getStepByIndex(0))==null?void 0:e.id,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}sendFlowStateToAPI(t,e,i){return d(this,null,function*(){let a=new Date;this.getGlobalState().lastSyncDate=a;let g=yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,flowSlug:this.id,stepId:i!=null?i:this.getCurrentStep().id,data:e||{},actionType:t,createdAt:a})});a<this.getGlobalState().lastSyncDate||(yield this.getGlobalState().refreshStateFromAPI(g))})}optimisticallyMarkFlowSkipped(){let t=u(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().rules.register(this.id,i=>{let a=this.getGlobalState().previousFlows.get(this.id);(a==null?void 0:a._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(g=>{g(this,a),this.getGlobalState().previousFlows.set(this.id,C(this))}),t==null||t(i)})}unregister(){this.getGlobalState().rules.unregister(this.id)}};var M="NOT_STARTED_STEP",N="COMPLETED_FLOW",L="SKIPPED_FLOW",H="STARTED_FLOW",U="NOT_STARTED_FLOW",V="COMPLETED_STEP",W="STARTED_STEP",B="frigade-guest-key",E="guest_",st="get-cache-",P="fr-js-";function C(o){return new y({config:o.config,id:o.id})}function u(o){return JSON.parse(JSON.stringify(o))}function D(o){return{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Frigade-SDK-Version":x,"X-Frigade-SDK-Platform":"Javascript"}}}function at(o){return b()?window.localStorage.getItem(`${P}${o}`):null}function rt(o,s){b()&&window.localStorage.setItem(`${P}${o}`,s)}function j(){Object.keys(f).forEach(o=>{o.startsWith(st)&&delete f[o]})}function J(){b()&&Object.keys(window.localStorage).forEach(o=>{o.startsWith(P)&&window.localStorage.removeItem(o)})}var R=class{constructor(){this.queue=[];this.ttlInMS=500;this.cacheSize=5}push(s){let t=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:s,time:t.getTime()})}hasIdenticalCall(s){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.some(e=>e.call===s)}},K=new R;function $(o,s){return d(this,null,function*(){var e;if(typeof globalThis.fetch!="function")return S("- Attempted to call fetch() in an environment that doesn't support it.");if(b()&&s&&s.body&&s.method==="POST"){let i=`${o}${JSON.stringify((e=s.body)!=null?e:{})}`;if(K.hasIdenticalCall(i))return S();K.push(i)}let t;try{t=fetch(o,s),t=yield t}catch(i){return S(i)}if(!t)return S("Received an empty response");if(t.status>=400)return S(t.statusText);try{if(t.status===204)return S();let i;try{i=yield t.json()}catch(a){return S()}return i.error?S(i.error):i}catch(i){return S(i)}})}function S(o){return o&&console.log("Call to Frigade failed",o),{json:()=>({})}}function k(){if(b()){let o=at(B);return o||(o=`${E}${it()}`,rt(B,o)),o}}function b(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}var v=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.rules=new Map;this.flowsInRules=new Set;this.ingestRulesData(s)}ingestRulesData(s){this.rules=s;for(let[,t]of this.rules)for(let{flowId:e}of t)this.flowsInRules.add(e);this.registry.size>0&&(this.registryStateLocked||this.resetRegistryState(),this.processRules()),this.fireCallbacks()}fireCallbacks(){for(let[s,{callback:t}]of this.registry)typeof t=="function"&&t(this.isFlowVisible(s))}isFlowVisible(s){let t=this.registry.get(s),e=this.flowsInRules.has(s);return t==null||!e?!0:t.visible}lockRegistryState(){this.registryStateLocked=!0}unlockRegistryState(){this.registryStateLocked=!1}resetRegistryState(){for(let[s,t]of this.registry)t.visible=!1,t.visited=!1,this.registry.set(s,t)}processRules(){for(let[,s]of this.rules)for(let{flowId:t,visible:e}of s){let i=this.registry.get(t);if(i==null)continue;if(e===!1&&i.visible!==!0){this.visit(t,!1);continue}if(i.visited&&this.registryStateLocked)continue;if(s.map(({flowId:n})=>n).filter(n=>n!==t).some(n=>{var p;let{visible:l,visited:c}=(p=this.registry.get(n))!=null?p:{};return l&&c})){this.visit(t,!1);continue}this.visit(t)}}register(s,t){if(Array.isArray(s)){this.batchRegister(s);return}this.registry.set(s,{callback:t!=null?t:()=>{},visible:!1,visited:!1}),this.registryStateLocked||this.resetRegistryState(),this.processRules(),this.fireCallbacks()}batchRegister(s){s.forEach(([t,e])=>{this.registry.set(t,{callback:e!=null?e:()=>{},visible:!1,visited:!1})}),this.registryStateLocked||this.resetRegistryState(),this.processRules(),this.lockRegistryState(),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.resetRegistryState(),this.processRules(),this.fireCallbacks()}visit(s,t=!0){var i;let e=(i=this.registry.get(s))!=null?i:{callback:()=>{},visible:t,visited:!0};e.visible=t,e.visited=!0,this.registry.set(s,e)}};var T=class extends F{constructor(t,e){super(h({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.visibilityChangeHandler=()=>d(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshStateFromAPI())});this.init(this.config),b()&&document.addEventListener("visibilitychange",this.visibilityChangeHandler)}getConfig(){return this.config}destroy(){if(b()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=w(this.config);f[t]&&(f[t].onFlowStateChangeHandlers=[])}}init(t){return d(this,null,function*(){return this.updateConfig(h(h({},this.config),t)),this.initPromise=(()=>d(this,null,function*(){var e;this.config.__readOnly||(e=this.config.userId)!=null&&e.startsWith(E)||(this.config.userId&&this.config.groupId?yield this.session({userId:this.config.userId,groupId:this.config.groupId}):this.config.userId&&(yield this.session({userId:this.config.userId}))),yield this.refreshStateFromAPI()}))(),this.initPromise})}identify(t,e){return d(this,null,function*(){yield this.updateConfig(m(h({},this.config),{userId:t})),yield this.initIfNeeded(),yield this.session({userId:this.config.userId,userProperties:e}),yield this.resync()})}group(t,e){return d(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(m(h({},this.config),{groupId:t})),yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupProperties: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.session({userId:this.config.userId,groupId:this.config.groupId,groupEvents:[{event:t,properties:e}],userEvents:[{event:t,properties:e}]}):this.config.userId&&(yield this.session({userId:this.config.userId,userEvents:[{event:t,properties:e}]})),yield this.resync()})}session(t){return d(this,null,function*(){yield this.fetch("/v1/public/sessions",{method:"POST",body:JSON.stringify(t)})})}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(t){return d(this,null,function*(){J(),j(),t&&(yield this.updateConfig(t),this.mockFlowStates(w(this.config))),this.initPromise=null,yield this.init(this.config),this.flows.forEach(e=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(i=>{let a=this.getGlobalState().previousFlows.get(e.id);i(e,a),this.getGlobalState().previousFlows.set(e.id,C(e))})})})}resync(){return d(this,null,function*(){yield this.refreshStateFromAPI()})}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)})}refreshStateFromAPI(){return d(this,null,function*(){let t=w(this.config);if(!f[t]){let e=this,i={set:function(a,g,n){if(a[g]){let l=a[g],c=n;JSON.stringify(l)!==JSON.stringify(c)&&e.triggerEventHandlers(c,l)}return a[g]=n,!0}};if(f[t]={refreshStateFromAPI:()=>d(this,null,function*(){}),rules:new v(new Map),flowStates:new Proxy({},i),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(t);return}f[t].refreshStateFromAPI=a=>d(this,null,function*(){var l,c;if(this.config.__readOnly)return;let g=a||(yield this.fetch(`/v1/public/flowStates?userId=${encodeURIComponent(this.config.userId)}${this.config.groupId?`&groupId=${encodeURIComponent(this.config.groupId)}`:""}`)),n=new Map;(c=(l=g.collections)==null?void 0:l.computedOrder)==null||c.forEach(({collectionId:p,flowId:r,visible:I})=>{var O;let A=(O=n.get(p))!=null?O:[];A.push({flowId:r,visible:I}),n.set(p,A)}),f[t].rules.ingestRulesData(n),g&&g.eligibleFlows?(g.eligibleFlows.forEach(p=>{f[t].flowStates[p.flowSlug]=p,this.flows.find(r=>r.id==p.flowSlug)?this.flows.forEach(r=>{r.id==p.flowSlug&&r.resyncState(p)}):this.flows.push(new y({config:this.config,id:p.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield f[t].refreshStateFromAPI()})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{f[t].flowStates[e]=this.config.__flowStateOverrides[e],this.flows.find(i=>i.id==e)?this.flows.forEach(i=>{i.id==e&&i.resyncState(this.config.__flowStateOverrides[e])}):this.flows.push(new y({config:this.config,id:e}))})}updateConfig(t){return d(this,null,function*(){this.config=h(h({},this.config),t),f[w(this.config)]&&(this.getGlobalState().config=this.config)})}triggerEventHandlers(t,e){return d(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(a=>{let g=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),a(i,g),this.getGlobalState().previousFlows.set(i.id,C(i))})})})}batchRegister(t){return d(this,null,function*(){let e=t.map(g=>d(this,[g],function*([i,a]){let n=yield this.getFlow(i);return[i,c=>{let p=this.getGlobalState().previousFlows.get(i);(p==null?void 0:p.isVisible)!==c&&this.getGlobalState().onFlowStateChangeHandlers.forEach(r=>{r(n,p),this.getGlobalState().previousFlows.set(i,C(n))}),a==null||a(c)}]}));Promise.all(e).then(i=>{this.getGlobalState().rules.batchRegister(i)})})}};var q=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(q||{}),z=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(z||{}),X=(r=>(r.ANNOUNCEMENT="ANNOUNCEMENT",r.CHECKLIST="CHECKLIST",r.FORM="FORM",r.TOUR="TOUR",r.SUPPORT="SUPPORT",r.CUSTOM="CUSTOM",r.BANNER="BANNER",r.EMBEDDED_TIP="EMBEDDED_TIP",r.NPS_SURVEY="NPS_SURVEY",r.SURVEY="SURVEY",r.CARD="CARD",r))(X||{});export{y as Flow,z as FlowStatus,X as FlowType,T as Frigade,q as TriggerType};
3
3
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/shared/fetchable.ts","../src/core/flow.ts","../src/core/rules.ts","../src/core/frigade.ts","../src/core/types.ts"],"sourcesContent":["export const VERSION_NUMBER = '0.2.20'\n","import { VERSION_NUMBER } from '../core/version'\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'\nconst GUEST_KEY = 'frigade-guest-key'\nexport const GUEST_PREFIX = 'guest_'\nconst GET_CACHE_PREFIX = 'get-cache-'\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\nclass CallQueue {\n private queue: {\n call: string\n time: number\n }[] = []\n private readonly ttlInMS = 500\n private readonly cacheSize = 5\n\n public push(call: string) {\n const now = new Date()\n if (this.queue.length >= this.cacheSize) {\n this.queue.shift()\n }\n this.queue.push({\n call: call,\n time: now.getTime(),\n })\n }\n\n public hasIdenticalCall(call: string) {\n const now = new Date()\n this.queue = this.queue.filter((item) => now.getTime() - item.time < this.ttlInMS)\n return this.queue.some((item) => item.call === call)\n }\n}\n\nconst callQueue = new CallQueue()\n\nexport async function gracefulFetch(url: string, options: any) {\n if (typeof globalThis.fetch !== 'function') {\n return getEmptyResponse(\n \"- Attempted to call fetch() in an environment that doesn't support it.\"\n )\n }\n\n if (isWeb() && options && options.body && options.method === 'POST') {\n const lastCallDataKey = `${url}${JSON.stringify(options.body ?? {})}`\n if (callQueue.hasIdenticalCall(lastCallDataKey)) {\n return getEmptyResponse()\n }\n callQueue.push(lastCallDataKey)\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) {\n return getEmptyResponse()\n }\n\n let body\n try {\n body = await response.json()\n } catch (e) {\n return getEmptyResponse()\n }\n\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 { FlowStates, FlowStep, FrigadeConfig, StatefulFlow } from '../core/types'\nimport { Flow } from '../core/flow'\nimport type { Rules } from '../core/rules'\n\nexport interface FrigadeGlobalState {\n refreshStateFromAPI: (overrideFlowStatesRaw?: FlowStates) => Promise<void>\n flowStates: Record<string, StatefulFlow>\n rules: Rules\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 lastSyncDate?: Date\n config: FrigadeConfig\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}`\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',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(12).substring(4),\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 return `${this.config.apiUrl.replace(/\\/$/, '')}/${path.replace(/^\\//, '')}`\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 has not yet been initialized')\n }\n return frigadeGlobalState[globalStateKey]\n }\n}\n","import {\n FlowActionType,\n FlowStateDTO,\n FlowStates,\n FlowStep,\n FrigadeConfig,\n PropertyPayload,\n StatefulFlow,\n StatefulStep,\n} from './types'\nimport {\n clone,\n cloneFlow,\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 { RulesRegistryCallback } from './rules'\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().rules.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 Object.keys(stepObj).forEach((key) => {\n existingStep[key] = stepObj[key]\n })\n }\n })\n if (this.steps && this.steps.size > 0) {\n this.applyVariables(this.getGlobalState().variables[this.id] ?? {})\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?: PropertyPayload) => {\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.sendFlowStateToAPI(STARTED_STEP, properties, thisStep.id)\n }\n }\n\n stepObj.complete = async (properties?: PropertyPayload, optimistic: boolean = true) => {\n const thisStep = this.steps.get(step.id)\n\n if (thisStep.$state.completed) {\n return\n }\n\n if (optimistic) {\n const isLastStep = thisStep.order + 1 === this.getNumberOfAvailableSteps()\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\n // If there are more index, advance current step\n if (!isLastStep) {\n copy.$state.currentStepId = this.getStepByIndex(thisStep.order + 1).id\n copy.$state.currentStepIndex = thisStep.order + 1\n }\n\n if (isLastStep) {\n copy.$state.completed = true\n }\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n if (isLastStep) {\n this.optimisticallyMarkFlowCompleted()\n }\n }\n\n await this.sendFlowStateToAPI(COMPLETED_STEP, properties, thisStep.id)\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.sendFlowStateToAPI(NOT_STARTED_STEP, undefined, thisStep.id)\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?: PropertyPayload) {\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.sendFlowStateToAPI(STARTED_FLOW, properties)\n }\n\n /**\n * Marks the flow completed\n */\n public async complete(properties?: PropertyPayload) {\n if (this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowCompleted()\n await this.sendFlowStateToAPI(COMPLETED_FLOW, properties)\n }\n\n /**\n * Marks the flow skipped\n */\n public async skip(properties?: PropertyPayload) {\n if (this.isSkipped) {\n return\n }\n this.optimisticallyMarkFlowSkipped()\n await this.sendFlowStateToAPI(SKIPPED_FLOW, properties)\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?: PropertyPayload) {\n const nextStep = this.getStepByIndex(this.getCurrentStepIndex() + 1)\n if (nextStep) {\n await nextStep.start(properties)\n } else {\n await this.complete(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?: PropertyPayload) {\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 this.optimisticallyMarkFlowNotStarted()\n await this.sendFlowStateToAPI(NOT_STARTED_FLOW)\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 return (\n this.steps.get(this.getStatefulFlow().$state.currentStepId) ??\n this.steps.get(Array.from(this.steps.keys())[0])\n )\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 (flow.id === this.id) {\n if (\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 }\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 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 optimisticallyMarkFlowNotStarted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = false\n copy.$state.started = false\n copy.$state.visible = true\n copy.$state.currentStepIndex = 0\n copy.$state.currentStepId = this.getStepByIndex(0)?.id\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n private async sendFlowStateToAPI(\n action: FlowActionType,\n data?: PropertyPayload,\n stepId?: string\n ) {\n const date = new Date()\n this.getGlobalState().lastSyncDate = date\n const flowStatesRaw: FlowStates = await this.fetch('/v1/public/flowStates', {\n method: 'POST',\n body: JSON.stringify({\n userId: this.getGlobalState().config.userId,\n groupId: this.getGlobalState().config.groupId,\n flowSlug: this.id,\n stepId: stepId ?? this.getCurrentStep().id,\n data: data ? data : {},\n actionType: action,\n createdAt: date,\n } as FlowStateDTO),\n })\n if (date < this.getGlobalState().lastSyncDate) {\n return\n }\n await this.getGlobalState().refreshStateFromAPI(flowStatesRaw)\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?: RulesRegistryCallback) {\n const globalState = this.getGlobalState()\n\n globalState.rules.register(this.id, (visible) => {\n const prevFlow = this.getGlobalState().previousFlows.get(this.id)\n\n if (prevFlow?._isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(this, prevFlow)\n this.getGlobalState().previousFlows.set(this.id, cloneFlow(this))\n })\n }\n\n callback?.(visible)\n })\n }\n\n public unregister() {\n this.getGlobalState().rules.unregister(this.id)\n }\n}\n","export type RulesRegistryCallback = (visible: boolean) => void\n\nexport type RulesRegistryBatch = [string, RulesRegistryCallback][]\n\nexport interface RulesRegistryItem {\n visible: boolean\n visited: boolean\n callback: RulesRegistryCallback\n}\n\nexport type Rule = Array<{\n flowId: string\n visible: boolean\n}>\n\nexport type RulesData = Map<string, Rule>\n\nexport class Rules {\n private readonly registry: Map<string, RulesRegistryItem> = new Map()\n private registryStateLocked: boolean = false\n private rules: Map<string, Rule> = new Map()\n private flowsInRules: Set<string> = new Set()\n\n constructor(rulesData: RulesData) {\n this.ingestRulesData(rulesData)\n }\n\n ingestRulesData(rulesData: RulesData) {\n this.rules = rulesData\n\n for (const [, rule] of this.rules) {\n for (const { flowId } of rule) {\n this.flowsInRules.add(flowId)\n }\n }\n\n if (this.registry.size > 0) {\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n }\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 registeredFlow = this.registry.get(flowId)\n const flowInRules = this.flowsInRules.has(flowId)\n\n if (registeredFlow == null || !flowInRules) {\n return true\n }\n\n return registeredFlow.visible\n }\n\n lockRegistryState() {\n this.registryStateLocked = true\n }\n\n unlockRegistryState() {\n this.registryStateLocked = false\n }\n\n resetRegistryState() {\n for (const [flowId, item] of this.registry) {\n item.visible = false\n item.visited = false\n\n this.registry.set(flowId, item)\n }\n }\n\n processRules() {\n for (const [, rule] of this.rules) {\n for (const { flowId, visible: visibleAPIOverride } of rule) {\n const registeredFlow = this.registry.get(flowId)\n\n // If this flow in the rule isn't registered, we have no opinion on it yet\n if (registeredFlow == null) {\n continue\n }\n\n // The API can force a flow to be hidden due to cool-offs, etc.\n if (visibleAPIOverride === false && registeredFlow.visible !== true) {\n this.visit(flowId, false)\n continue\n }\n\n // If this flow was processed in a previous rule and the registry is locked,\n // visibility shouldn't change until next time we run processRules\n if (registeredFlow.visited && this.registryStateLocked) {\n continue\n }\n\n const flowIdsInThisRule = rule\n .map(({ flowId: otherFlowId }) => otherFlowId)\n .filter((otherFlowId) => otherFlowId !== flowId)\n\n // If another flow in this rule has been visited already and is visible...\n const anotherFlowInThisRuleIsVisible = flowIdsInThisRule.some((otherId) => {\n const { visible: otherVisible, visited: otherVisited } = this.registry.get(otherId) ?? {}\n\n return otherVisible && otherVisited\n })\n\n // ...then this flow is hidden\n if (anotherFlowInThisRuleIsVisible) {\n this.visit(flowId, false)\n\n continue\n }\n\n // No other flows are visible, so this flow is visible by default\n this.visit(flowId)\n }\n }\n }\n\n register(flowId: string | RulesRegistryBatch, callback?: RulesRegistryCallback) {\n if (Array.isArray(flowId)) {\n this.batchRegister(flowId)\n return\n }\n\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.fireCallbacks()\n }\n\n batchRegister(flowIds: RulesRegistryBatch) {\n flowIds.forEach(([flowId, callback]) => {\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.lockRegistryState()\n\n this.fireCallbacks()\n }\n\n unregister(flowId: string) {\n this.registry.delete(flowId)\n\n this.resetRegistryState()\n this.processRules()\n\n this.fireCallbacks()\n }\n\n private visit(flowId: string, visible: boolean = true) {\n const item = this.registry.get(flowId) ?? {\n callback: () => {},\n visible,\n visited: true,\n }\n\n item.visible = visible\n item.visited = true\n\n this.registry.set(flowId, item)\n }\n}\n","import { FlowStates, FrigadeConfig, PropertyPayload, SessionDTO, StatefulFlow } 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 { Rules, type RulesRegistryBatch } from './rules'\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 }\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 * Gets the current configuration.\n */\n getConfig() {\n return this.config\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.updateConfig({\n ...this.config,\n ...config,\n })\n\n this.initPromise = (async () => {\n if (!this.config.__readOnly) {\n if (this.config.userId?.startsWith(GUEST_PREFIX)) {\n // do nothing\n } else if (this.config.userId && this.config.groupId) {\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n })\n } else if (this.config.userId) {\n await this.session({\n userId: 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?: PropertyPayload): Promise<void> {\n this.updateConfig({ ...this.config, userId })\n await this.initIfNeeded()\n await this.session({\n userId: this.config.userId,\n userProperties: properties,\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?: PropertyPayload): Promise<void> {\n await this.initIfNeeded()\n this.updateConfig({ ...this.config, groupId })\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupProperties: properties,\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?: PropertyPayload): 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.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupEvents: [\n {\n event,\n properties,\n },\n ],\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n } else if (this.config.userId) {\n await this.session({\n userId: this.config.userId,\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n }\n await this.resync()\n }\n\n /**\n * @ignore\n */\n private async session(sessionDTO: SessionDTO) {\n await this.fetch('/v1/public/sessions', {\n method: 'POST',\n body: JSON.stringify(sessionDTO),\n })\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 * @param config optional config to use when reloading. If not passed, the current config will be used.\n */\n public async reload(config?: FrigadeConfig) {\n resetAllLocalStorage()\n clearCache()\n if (config) {\n await this.updateConfig(config)\n this.mockFlowStates(getGlobalStateKey(this.config))\n }\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 await this.refreshStateFromAPI()\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 rules: new Rules(new Map()),\n flowStates: new Proxy({}, validator),\n onFlowStateChangeHandlerWrappers: new Map(),\n onStepStateChangeHandlerWrappers: new Map(),\n onFlowStateChangeHandlers: [],\n previousFlows: new Map(),\n variables: {},\n config: this.config,\n }\n\n if (this.config.__readOnly && this.config.__flowStateOverrides) {\n this.mockFlowStates(globalStateKey)\n\n return\n }\n\n frigadeGlobalState[globalStateKey].refreshStateFromAPI = async (\n overrideFlowStateRaw?: FlowStates\n ) => {\n if (this.config.__readOnly) {\n return\n }\n\n const flowStateRaw: FlowStates = overrideFlowStateRaw\n ? overrideFlowStateRaw\n : await this.fetch(\n `/v1/public/flowStates?userId=${encodeURIComponent(this.config.userId)}${\n this.config.groupId ? `&groupId=${encodeURIComponent(this.config.groupId)}` : ''\n }`\n )\n\n const rulesData = new Map()\n\n flowStateRaw.rules?.computedOrder?.forEach(({ ruleId, flowId, visible }) => {\n const currentRule = rulesData.get(ruleId) ?? []\n\n currentRule.push({\n flowId,\n visible,\n })\n\n rulesData.set(ruleId, currentRule)\n })\n\n frigadeGlobalState[globalStateKey].rules.ingestRulesData(rulesData)\n\n if (flowStateRaw && flowStateRaw.eligibleFlows) {\n flowStateRaw.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 mockFlowStates(globalStateKey: string) {\n Object.keys(this.config.__flowStateOverrides).forEach((flowId) => {\n frigadeGlobalState[globalStateKey].flowStates[flowId] =\n this.config.__flowStateOverrides[flowId]\n\n if (!this.flows.find((flow) => flow.id == flowId)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: flowId,\n })\n )\n } else {\n this.flows.forEach((flow) => {\n if (flow.id == flowId) {\n flow.resyncState(this.config.__flowStateOverrides[flowId])\n }\n })\n }\n })\n }\n\n /**\n * @ignore\n */\n private async updateConfig(config: FrigadeConfig) {\n this.config = {\n ...this.config,\n ...config,\n }\n if (frigadeGlobalState[getGlobalStateKey(this.config)]) {\n this.getGlobalState().config = this.config\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 /**\n * @ignore\n */\n async batchRegister(flowIds: RulesRegistryBatch) {\n const flowIdsWithWrappedCallbacks = flowIds.map(async ([flowId, callback]) => {\n const currentFlow = await this.getFlow(flowId)\n const wrappedCallback = (visible: boolean) => {\n const prevFlow = this.getGlobalState().previousFlows.get(flowId)\n\n if (prevFlow?.isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(currentFlow, prevFlow)\n this.getGlobalState().previousFlows.set(flowId, cloneFlow(currentFlow))\n })\n }\n\n callback?.(visible)\n }\n\n return [flowId, wrappedCallback] as RulesRegistryBatch[number]\n })\n\n Promise.all(flowIdsWithWrappedCallbacks).then((results) => {\n this.getGlobalState().rules.batchRegister(results)\n })\n }\n}\n","import type { Flow } from './flow'\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 type PropertyPayload = Record<string, any>\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 * @description 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 * @description Primary button URI.\n */\n primaryButtonUri?: string\n\n /**\n * @deprecated Use primaryButton.target instead\n * @description 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 * @description 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 * @description Secondary button URI.\n */\n secondaryButtonUri?: string\n\n /**\n * @deprecated Use secondaryButton.target instead\n * @description 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?: PropertyPayload) => Promise<void>\n\n /**\n * Marks the step completed.\n * @param optimistic If true, the step will be marked as completed without waiting for the API and validation of any targeting rules.\n */\n complete: (properties?: PropertyPayload, optimistic?: boolean) => 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 State for all flows in the app that should be mocked.\n */\n __flowStateOverrides?: Record<string, StatefulFlow>\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 ComputedRule {\n ruleId: string\n flowId: string\n visible: boolean\n}\n\nexport interface RulesMetadata {\n computedOrder: ComputedRule[]\n}\n\nexport interface FlowStates {\n eligibleFlows: StatefulFlow[]\n ineligibleFlows: string[]\n rules?: RulesMetadata\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\nexport type FlowActionType =\n | 'STARTED_STEP'\n | 'COMPLETED_STEP'\n | 'NOT_STARTED_STEP'\n | 'STARTED_FLOW'\n | 'COMPLETED_FLOW'\n | 'SKIPPED_FLOW'\n | 'NOT_STARTED_FLOW'\n\nexport interface FlowStateDTO {\n userId: string\n groupId?: string\n flowSlug: string\n stepId?: string\n data?: any\n actionType: FlowActionType\n createdAt?: Date\n}\n\nexport interface TrackingEvent {\n event: string\n properties?: { [key: string]: any }\n}\n\nexport interface SessionDTO {\n userId: string\n groupId?: string\n userProperties?: { [key: string]: any }\n userEvents?: TrackingEvent[]\n groupProperties?: { [key: string]: any }\n groupEvents?: TrackingEvent[]\n linkGuestId?: string\n}\n"],"mappings":";8nBAAO,IAAMA,EAAiB,SCC9B,OAAS,MAAMC,OAAc,OCsBtB,IAAIC,EAAyD,CAAC,EAE9D,SAASC,EAAkBC,EAAuC,CACvE,MAAO,GAAGA,EAAe,gBAAgBA,EAAe,QAC1D,CCvBO,IAAMC,EAAN,KAAgB,CAQrB,YAAYC,EAAuB,CAPnC,KAAO,OAAwB,CAC7B,OAAQ,GACR,OAAQ,0BACR,OAAQC,EAAgB,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,KAAK,QACLH,EAEP,CAKa,MAAMI,EAAcC,EAA4B,QAAAC,EAAA,sBAC3D,OAAI,KAAK,OAAO,WACPC,EAAiB,EAGnBC,EAAc,KAAK,UAAUJ,CAAI,EAAGD,IAAA,CACzC,UAAW,IACPE,GAAA,KAAAA,EAAW,CAAC,GACbI,EAAW,KAAK,OAAO,MAAM,EACjC,CACH,GAEQ,UAAUL,EAAc,CAC9B,MAAO,GAAG,KAAK,OAAO,OAAO,QAAQ,MAAO,EAAE,KAAKA,EAAK,QAAQ,MAAO,EAAE,GAC3E,CAKU,gBAAqC,CAC7C,IAAMM,EAAiBC,EAAkB,KAAK,MAAM,EACpD,GAAI,CAACC,EAAmBF,CAAc,EACpC,MAAM,IAAI,MAAM,sCAAsC,EAExD,OAAOE,EAAmBF,CAAc,CAC1C,C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IAAMuC,EAA8BD,EAAQ,IAAWE,GAAuBxC,EAAA,MAAvBwC,GAAuB,UAAvB,CAAC3B,EAAQ4B,CAAQ,EAAM,CAC5E,IAAMC,EAAc,MAAM,KAAK,QAAQ7B,CAAM,EAe7C,MAAO,CAACA,EAdiBqB,GAAqB,CAC5C,IAAMS,EAAW,KAAK,eAAe,EAAE,cAAc,IAAI9B,CAAM,GAE3D8B,GAAA,YAAAA,EAAU,aAAcT,GAE1B,KAAK,eAAe,EAAE,0BAA0B,QAASjB,GAAY,CACnEA,EAAQyB,EAAaC,CAAQ,EAC7B,KAAK,eAAe,EAAE,cAAc,IAAI9B,EAAQM,EAAUuB,CAAW,CAAC,CACxE,CAAC,EAGHD,GAAA,MAAAA,EAAWP,EACb,CAE+B,CACjC,EAAC,EAED,QAAQ,IAAIK,CAA2B,EAAE,KAAMK,GAAY,CACzD,KAAK,eAAe,EAAE,MAAM,cAAcA,CAAO,CACnD,CAAC,CACH,GACF,ECrbO,IAAKC,OACVA,EAAA,OAAS,SACTA,EAAA,UAAY,YAFFA,OAAA,IAKAC,OACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SACTA,EAAA,SAAW,WAHDA,OAAA,IAoTAC,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":["VERSION_NUMBER","uuidv4","frigadeGlobalState","getGlobalStateKey","internalConfig","Fetchable","config","generateGuestId","filteredConfig","_","v","__spreadValues","path","options","__async","getEmptyResponse","gracefulFetch","getHeaders","globalStateKey","getGlobalStateKey","frigadeGlobalState","Flow","Fetchable","config","id","visible","overrideStatefulFlow","_a","_b","_c","statefulFlow","step","index","stepObj","existingStep","key","__spreadProps","__spreadValues","newSteps","properties","__async","thisStep","copy","clone","STARTED_STEP","optimistic","isLastStep","COMPLETED_STEP","NOT_STARTED_STEP","handler","wrapperHandler","flow","previousStep","h","STARTED_FLOW","COMPLETED_FLOW","SKIPPED_FLOW","nextStep","NOT_STARTED_FLOW","currentStep","previousFlow","variables","replaceVariables","str","matches","match","variable","action","data","stepId","date","flowStatesRaw","callback","prevFlow","cloneFlow","NOT_STARTED_STEP","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","GUEST_KEY","GUEST_PREFIX","GET_CACHE_PREFIX","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","CallQueue","call","now","item","callQueue","gracefulFetch","url","options","__async","_a","getEmptyResponse","lastCallDataKey","response","error","body","e","generateGuestId","guestId","getLocalStorage","GUEST_KEY","GUEST_PREFIX","uuidv4","setLocalStorage","isWeb","Rules","rulesData","rule","flowId","callback","registeredFlow","flowInRules","item","visibleAPIOverride","otherFlowId","otherId","_a","otherVisible","otherVisited","flowIds","visible","Frigade","Fetchable","apiKey","config","__spreadValues","__async","isWeb","globalStateKey","getGlobalStateKey","frigadeGlobalState","_a","GUEST_PREFIX","userId","properties","__spreadProps","groupId","event","sessionDTO","flowId","flow","resetAllLocalStorage","clearCache","handler","lastFlow","cloneFlow","h","that","validator","target","key","value","previousState","newState","Rules","overrideFlowStateRaw","_b","flowStateRaw","rulesData","ruleId","visible","currentRule","statefulFlow","Flow","flowIds","flowIdsWithWrappedCallbacks","_0","callback","currentFlow","prevFlow","results","TriggerType","FlowStatus","FlowType"]}
1
+ {"version":3,"sources":["../src/core/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/shared/fetchable.ts","../src/core/flow.ts","../src/core/rules.ts","../src/core/frigade.ts","../src/core/types.ts"],"sourcesContent":["export const VERSION_NUMBER = '0.2.20'\n","import { VERSION_NUMBER } from '../core/version'\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'\nconst GUEST_KEY = 'frigade-guest-key'\nexport const GUEST_PREFIX = 'guest_'\nconst GET_CACHE_PREFIX = 'get-cache-'\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\nclass CallQueue {\n private queue: {\n call: string\n time: number\n }[] = []\n private readonly ttlInMS = 500\n private readonly cacheSize = 5\n\n public push(call: string) {\n const now = new Date()\n if (this.queue.length >= this.cacheSize) {\n this.queue.shift()\n }\n this.queue.push({\n call: call,\n time: now.getTime(),\n })\n }\n\n public hasIdenticalCall(call: string) {\n const now = new Date()\n this.queue = this.queue.filter((item) => now.getTime() - item.time < this.ttlInMS)\n return this.queue.some((item) => item.call === call)\n }\n}\n\nconst callQueue = new CallQueue()\n\nexport async function gracefulFetch(url: string, options: any) {\n if (typeof globalThis.fetch !== 'function') {\n return getEmptyResponse(\n \"- Attempted to call fetch() in an environment that doesn't support it.\"\n )\n }\n\n if (isWeb() && options && options.body && options.method === 'POST') {\n const lastCallDataKey = `${url}${JSON.stringify(options.body ?? {})}`\n if (callQueue.hasIdenticalCall(lastCallDataKey)) {\n return getEmptyResponse()\n }\n callQueue.push(lastCallDataKey)\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) {\n return getEmptyResponse()\n }\n\n let body\n try {\n body = await response.json()\n } catch (e) {\n return getEmptyResponse()\n }\n\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 { FlowStates, FlowStep, FrigadeConfig, StatefulFlow } from '../core/types'\nimport { Flow } from '../core/flow'\nimport type { Rules } from '../core/rules'\n\nexport interface FrigadeGlobalState {\n refreshStateFromAPI: (overrideFlowStatesRaw?: FlowStates) => Promise<void>\n flowStates: Record<string, StatefulFlow>\n rules: Rules\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 lastSyncDate?: Date\n config: FrigadeConfig\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: FrigadeConfig): string {\n return `${internalConfig.__instanceId}-${internalConfig.apiKey}`\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',\n userId: generateGuestId(),\n __instanceId: Math.random().toString(12).substring(4),\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 return `${this.config.apiUrl.replace(/\\/$/, '')}/${path.replace(/^\\//, '')}`\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 has not yet been initialized')\n }\n return frigadeGlobalState[globalStateKey]\n }\n}\n","import {\n FlowActionType,\n FlowStateDTO,\n FlowStates,\n FlowStep,\n FrigadeConfig,\n PropertyPayload,\n StatefulFlow,\n StatefulStep,\n} from './types'\nimport {\n clone,\n cloneFlow,\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 { RulesRegistryCallback } from './rules'\n\nexport class Flow extends Fetchable {\n /**\n * The Flow's ID.\n */\n public id: string\n /**\n * The Flow's component ID.\n */\n public componentId: 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().rules.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 Object.keys(stepObj).forEach((key) => {\n existingStep[key] = stepObj[key]\n })\n }\n })\n\n if (this.steps && this.steps.size > 0) {\n this.applyVariables(this.getGlobalState().variables[this.id] ?? {})\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?: PropertyPayload) => {\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 await this.sendFlowStateToAPI(STARTED_STEP, properties, thisStep.id)\n }\n\n stepObj.complete = async (properties?: PropertyPayload, optimistic: boolean = true) => {\n const thisStep = this.steps.get(step.id)\n\n if (optimistic) {\n const isLastStep = thisStep.order + 1 === this.getNumberOfAvailableSteps()\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\n // If there are more index, advance current step\n if (!isLastStep) {\n copy.$state.currentStepId = this.getStepByIndex(thisStep.order + 1).id\n copy.$state.currentStepIndex = thisStep.order + 1\n }\n\n if (isLastStep) {\n copy.$state.completed = true\n }\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n\n if (isLastStep) {\n this.optimisticallyMarkFlowCompleted()\n }\n }\n\n await this.sendFlowStateToAPI(COMPLETED_STEP, properties, thisStep.id)\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.sendFlowStateToAPI(NOT_STARTED_STEP, undefined, thisStep.id)\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?: PropertyPayload) {\n if (this.isStarted || this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowStarted()\n\n await this.sendFlowStateToAPI(STARTED_FLOW, properties)\n }\n\n /**\n * Marks the flow completed\n */\n public async complete(properties?: PropertyPayload) {\n if (this.isCompleted) {\n return\n }\n this.optimisticallyMarkFlowCompleted()\n await this.sendFlowStateToAPI(COMPLETED_FLOW, properties)\n }\n\n /**\n * Marks the flow skipped\n */\n public async skip(properties?: PropertyPayload) {\n if (this.isSkipped) {\n return\n }\n this.optimisticallyMarkFlowSkipped()\n await this.sendFlowStateToAPI(SKIPPED_FLOW, properties)\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?: PropertyPayload) {\n const nextStep = this.getStepByIndex(this.getCurrentStepIndex() + 1)\n if (nextStep) {\n await nextStep.start(properties)\n } else {\n await this.complete(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?: PropertyPayload) {\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 this.optimisticallyMarkFlowNotStarted()\n await this.sendFlowStateToAPI(NOT_STARTED_FLOW)\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 return (\n this.steps.get(this.getStatefulFlow().$state.currentStepId) ??\n this.steps.get(Array.from(this.steps.keys())[0])\n )\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 (flow.id === this.id) {\n if (\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 }\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 * Apply variables to the flow. This will replace any `${variable}` in the title, subtitle, and step fields with the value of the variable.\n * @param variables A record of variables to apply to the flow.\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[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 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 optimisticallyMarkFlowStarted() {\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\n /**\n * @ignore\n */\n private optimisticallyMarkFlowNotStarted() {\n const copy = clone(this.getGlobalState().flowStates[this.id])\n copy.$state.completed = false\n copy.$state.started = false\n copy.$state.visible = true\n copy.$state.currentStepIndex = 0\n copy.$state.currentStepId = this.getStepByIndex(0)?.id\n\n this.getGlobalState().flowStates[this.id] = copy\n this.resyncState()\n }\n\n private async sendFlowStateToAPI(\n action: FlowActionType,\n data?: PropertyPayload,\n stepId?: string\n ) {\n const date = new Date()\n this.getGlobalState().lastSyncDate = date\n const flowStatesRaw: FlowStates = await this.fetch('/v1/public/flowStates', {\n method: 'POST',\n body: JSON.stringify({\n userId: this.getGlobalState().config.userId,\n groupId: this.getGlobalState().config.groupId,\n flowSlug: this.id,\n stepId: stepId ?? this.getCurrentStep().id,\n data: data ? data : {},\n actionType: action,\n createdAt: date,\n } as FlowStateDTO),\n })\n if (date < this.getGlobalState().lastSyncDate) {\n return\n }\n await this.getGlobalState().refreshStateFromAPI(flowStatesRaw)\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?: RulesRegistryCallback) {\n const globalState = this.getGlobalState()\n\n globalState.rules.register(this.id, (visible) => {\n const prevFlow = this.getGlobalState().previousFlows.get(this.id)\n\n if (prevFlow?._isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(this, prevFlow)\n this.getGlobalState().previousFlows.set(this.id, cloneFlow(this))\n })\n }\n\n callback?.(visible)\n })\n }\n\n public unregister() {\n this.getGlobalState().rules.unregister(this.id)\n }\n}\n","export type RulesRegistryCallback = (visible: boolean) => void\n\nexport type RulesRegistryBatch = [string, RulesRegistryCallback][]\n\nexport interface RulesRegistryItem {\n visible: boolean\n visited: boolean\n callback: RulesRegistryCallback\n}\n\nexport type Rule = Array<{\n flowId: string\n visible: boolean\n}>\n\nexport type RulesData = Map<string, Rule>\n\nexport class Rules {\n private readonly registry: Map<string, RulesRegistryItem> = new Map()\n private registryStateLocked: boolean = false\n private rules: Map<string, Rule> = new Map()\n private flowsInRules: Set<string> = new Set()\n\n constructor(rulesData: RulesData) {\n this.ingestRulesData(rulesData)\n }\n\n ingestRulesData(rulesData: RulesData) {\n this.rules = rulesData\n\n for (const [, rule] of this.rules) {\n for (const { flowId } of rule) {\n this.flowsInRules.add(flowId)\n }\n }\n\n if (this.registry.size > 0) {\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n }\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 registeredFlow = this.registry.get(flowId)\n const flowInRules = this.flowsInRules.has(flowId)\n\n if (registeredFlow == null || !flowInRules) {\n return true\n }\n\n return registeredFlow.visible\n }\n\n lockRegistryState() {\n this.registryStateLocked = true\n }\n\n unlockRegistryState() {\n this.registryStateLocked = false\n }\n\n resetRegistryState() {\n for (const [flowId, item] of this.registry) {\n item.visible = false\n item.visited = false\n\n this.registry.set(flowId, item)\n }\n }\n\n processRules() {\n for (const [, rule] of this.rules) {\n for (const { flowId, visible: visibleAPIOverride } of rule) {\n const registeredFlow = this.registry.get(flowId)\n\n // If this flow in the rule isn't registered, we have no opinion on it yet\n if (registeredFlow == null) {\n continue\n }\n\n // The API can force a flow to be hidden due to cool-offs, etc.\n if (visibleAPIOverride === false && registeredFlow.visible !== true) {\n this.visit(flowId, false)\n continue\n }\n\n // If this flow was processed in a previous rule and the registry is locked,\n // visibility shouldn't change until next time we run processRules\n if (registeredFlow.visited && this.registryStateLocked) {\n continue\n }\n\n const flowIdsInThisRule = rule\n .map(({ flowId: otherFlowId }) => otherFlowId)\n .filter((otherFlowId) => otherFlowId !== flowId)\n\n // If another flow in this rule has been visited already and is visible...\n const anotherFlowInThisRuleIsVisible = flowIdsInThisRule.some((otherId) => {\n const { visible: otherVisible, visited: otherVisited } = this.registry.get(otherId) ?? {}\n\n return otherVisible && otherVisited\n })\n\n // ...then this flow is hidden\n if (anotherFlowInThisRuleIsVisible) {\n this.visit(flowId, false)\n\n continue\n }\n\n // No other flows are visible, so this flow is visible by default\n this.visit(flowId)\n }\n }\n }\n\n register(flowId: string | RulesRegistryBatch, callback?: RulesRegistryCallback) {\n if (Array.isArray(flowId)) {\n this.batchRegister(flowId)\n return\n }\n\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.fireCallbacks()\n }\n\n batchRegister(flowIds: RulesRegistryBatch) {\n flowIds.forEach(([flowId, callback]) => {\n this.registry.set(flowId, {\n callback: callback ?? (() => {}),\n visible: false,\n visited: false,\n })\n })\n\n if (!this.registryStateLocked) {\n this.resetRegistryState()\n }\n\n this.processRules()\n\n this.lockRegistryState()\n\n this.fireCallbacks()\n }\n\n unregister(flowId: string) {\n this.registry.delete(flowId)\n\n this.resetRegistryState()\n this.processRules()\n\n this.fireCallbacks()\n }\n\n private visit(flowId: string, visible: boolean = true) {\n const item = this.registry.get(flowId) ?? {\n callback: () => {},\n visible,\n visited: true,\n }\n\n item.visible = visible\n item.visited = true\n\n this.registry.set(flowId, item)\n }\n}\n","import { FlowStates, FrigadeConfig, PropertyPayload, SessionDTO, StatefulFlow } 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 { Rules, type RulesRegistryBatch } from './rules'\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 }\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 * Gets the current configuration.\n */\n getConfig() {\n return this.config\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.updateConfig({\n ...this.config,\n ...config,\n })\n\n this.initPromise = (async () => {\n if (!this.config.__readOnly) {\n if (this.config.userId?.startsWith(GUEST_PREFIX)) {\n // do nothing\n } else if (this.config.userId && this.config.groupId) {\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n })\n } else if (this.config.userId) {\n await this.session({\n userId: 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?: PropertyPayload): Promise<void> {\n await this.updateConfig({ ...this.config, userId })\n await this.initIfNeeded()\n await this.session({\n userId: this.config.userId,\n userProperties: properties,\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?: PropertyPayload): Promise<void> {\n await this.initIfNeeded()\n this.updateConfig({ ...this.config, groupId })\n await this.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupProperties: properties,\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?: PropertyPayload): 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.session({\n userId: this.config.userId,\n groupId: this.config.groupId,\n groupEvents: [\n {\n event,\n properties,\n },\n ],\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n } else if (this.config.userId) {\n await this.session({\n userId: this.config.userId,\n userEvents: [\n {\n event,\n properties,\n },\n ],\n })\n }\n await this.resync()\n }\n\n /**\n * @ignore\n */\n private async session(sessionDTO: SessionDTO) {\n await this.fetch('/v1/public/sessions', {\n method: 'POST',\n body: JSON.stringify(sessionDTO),\n })\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 * @param config optional config to use when reloading. If not passed, the current config will be used.\n */\n public async reload(config?: FrigadeConfig) {\n resetAllLocalStorage()\n clearCache()\n if (config) {\n await this.updateConfig(config)\n this.mockFlowStates(getGlobalStateKey(this.config))\n }\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 await this.refreshStateFromAPI()\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 rules: new Rules(new Map()),\n flowStates: new Proxy({}, validator),\n onFlowStateChangeHandlerWrappers: new Map(),\n onStepStateChangeHandlerWrappers: new Map(),\n onFlowStateChangeHandlers: [],\n previousFlows: new Map(),\n variables: {},\n config: this.config,\n }\n\n if (this.config.__readOnly && this.config.__flowStateOverrides) {\n this.mockFlowStates(globalStateKey)\n\n return\n }\n\n frigadeGlobalState[globalStateKey].refreshStateFromAPI = async (\n overrideFlowStateRaw?: FlowStates\n ) => {\n if (this.config.__readOnly) {\n return\n }\n\n const flowStateRaw: FlowStates = overrideFlowStateRaw\n ? overrideFlowStateRaw\n : await this.fetch(\n `/v1/public/flowStates?userId=${encodeURIComponent(this.config.userId)}${\n this.config.groupId ? `&groupId=${encodeURIComponent(this.config.groupId)}` : ''\n }`\n )\n\n const rulesData = new Map()\n\n flowStateRaw.collections?.computedOrder?.forEach(({ collectionId, flowId, visible }) => {\n const currentRule = rulesData.get(collectionId) ?? []\n\n currentRule.push({\n flowId,\n visible,\n })\n\n rulesData.set(collectionId, currentRule)\n })\n\n frigadeGlobalState[globalStateKey].rules.ingestRulesData(rulesData)\n\n if (flowStateRaw && flowStateRaw.eligibleFlows) {\n flowStateRaw.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 } else {\n this.flows.forEach((flow) => {\n if (flow.id == statefulFlow.flowSlug) {\n flow.resyncState(statefulFlow)\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 mockFlowStates(globalStateKey: string) {\n Object.keys(this.config.__flowStateOverrides).forEach((flowId) => {\n frigadeGlobalState[globalStateKey].flowStates[flowId] =\n this.config.__flowStateOverrides[flowId]\n\n if (!this.flows.find((flow) => flow.id == flowId)) {\n this.flows.push(\n new Flow({\n config: this.config,\n id: flowId,\n })\n )\n } else {\n this.flows.forEach((flow) => {\n if (flow.id == flowId) {\n flow.resyncState(this.config.__flowStateOverrides[flowId])\n }\n })\n }\n })\n }\n\n /**\n * @ignore\n */\n private async updateConfig(config: FrigadeConfig) {\n this.config = {\n ...this.config,\n ...config,\n }\n if (frigadeGlobalState[getGlobalStateKey(this.config)]) {\n this.getGlobalState().config = this.config\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 /**\n * @ignore\n */\n async batchRegister(flowIds: RulesRegistryBatch) {\n const flowIdsWithWrappedCallbacks = flowIds.map(async ([flowId, callback]) => {\n const currentFlow = await this.getFlow(flowId)\n const wrappedCallback = (visible: boolean) => {\n const prevFlow = this.getGlobalState().previousFlows.get(flowId)\n\n if (prevFlow?.isVisible !== visible) {\n // TODO: Store these in a hash so we can grab this flow's handler and call it\n this.getGlobalState().onFlowStateChangeHandlers.forEach((handler) => {\n handler(currentFlow, prevFlow)\n this.getGlobalState().previousFlows.set(flowId, cloneFlow(currentFlow))\n })\n }\n\n callback?.(visible)\n }\n\n return [flowId, wrappedCallback] as RulesRegistryBatch[number]\n })\n\n Promise.all(flowIdsWithWrappedCallbacks).then((results) => {\n this.getGlobalState().rules.batchRegister(results)\n })\n }\n}\n","import type { Flow } from './flow'\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 type PropertyPayload = Record<string, any>\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 * @description 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 * @description Primary button URI.\n */\n primaryButtonUri?: string\n\n /**\n * @deprecated Use primaryButton.target instead\n * @description 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 * @description 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 * @description Secondary button URI.\n */\n secondaryButtonUri?: string\n\n /**\n * @deprecated Use secondaryButton.target instead\n * @description 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?: PropertyPayload) => Promise<void>\n\n /**\n * Marks the step completed.\n * @param optimistic If true, the step will be marked as completed without waiting for the API and validation of any targeting rules.\n */\n complete: (properties?: PropertyPayload, optimistic?: boolean) => 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 State for all flows in the app that should be mocked.\n */\n __flowStateOverrides?: Record<string, StatefulFlow>\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 ComputedCollection {\n collectionId: string\n flowId: string\n visible: boolean\n}\n\nexport interface CollectionMetadata {\n computedOrder: ComputedCollection[]\n}\n\nexport interface FlowStates {\n eligibleFlows: StatefulFlow[]\n ineligibleFlows: string[]\n collections?: CollectionMetadata\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\nexport type FlowActionType =\n | 'STARTED_STEP'\n | 'COMPLETED_STEP'\n | 'NOT_STARTED_STEP'\n | 'STARTED_FLOW'\n | 'COMPLETED_FLOW'\n | 'SKIPPED_FLOW'\n | 'NOT_STARTED_FLOW'\n\nexport interface FlowStateDTO {\n userId: string\n groupId?: string\n flowSlug: string\n stepId?: string\n data?: any\n actionType: FlowActionType\n createdAt?: Date\n}\n\nexport interface TrackingEvent {\n event: string\n properties?: { [key: string]: any }\n}\n\nexport interface SessionDTO {\n userId: string\n groupId?: string\n userProperties?: { [key: string]: any }\n userEvents?: TrackingEvent[]\n groupProperties?: { [key: string]: any }\n groupEvents?: TrackingEvent[]\n linkGuestId?: string\n}\n"],"mappings":";8nBAAO,IAAMA,EAAiB,SCC9B,OAAS,MAAMC,OAAc,OCsBtB,IAAIC,EAAyD,CAAC,EAE9D,SAASC,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cT,GAE1B,KAAK,eAAe,EAAE,0BAA0B,QAASjB,GAAY,CACnEA,EAAQyB,EAAaC,CAAQ,EAC7B,KAAK,eAAe,EAAE,cAAc,IAAI9B,EAAQM,EAAUuB,CAAW,CAAC,CACxE,CAAC,EAGHD,GAAA,MAAAA,EAAWP,EACb,CAE+B,CACjC,EAAC,EAED,QAAQ,IAAIK,CAA2B,EAAE,KAAMK,GAAY,CACzD,KAAK,eAAe,EAAE,MAAM,cAAcA,CAAO,CACnD,CAAC,CACH,GACF,EC3bO,IAAKC,OACVA,EAAA,OAAS,SACTA,EAAA,UAAY,YAFFA,OAAA,IAKAC,OACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SACTA,EAAA,SAAW,WAHDA,OAAA,IAoTAC,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":["VERSION_NUMBER","uuidv4","frigadeGlobalState","getGlobalStateKey","internalConfig","Fetchable","config","generateGuestId","filteredConfig","_","v","__spreadValues","path","options","__async","getEmptyResponse","gracefulFetch","getHeaders","globalStateKey","getGlobalStateKey","frigadeGlobalState","Flow","Fetchable","config","id","visible","overrideStatefulFlow","_a","_b","_c","statefulFlow","step","index","stepObj","existingStep","key","__spreadProps","__spreadValues","newSteps","properties","__async","thisStep","copy","clone","STARTED_STEP","optimistic","isLastStep","COMPLETED_STEP","NOT_STARTED_STEP","handler","wrapperHandler","flow","previousStep","h","STARTED_FLOW","COMPLETED_FLOW","SKIPPED_FLOW","nextStep","NOT_STARTED_FLOW","currentStep","previousFlow","variables","replaceVariables","str","matches","match","variable","action","data","stepId","date","flowStatesRaw","callback","prevFlow","cloneFlow","NOT_STARTED_STEP","COMPLETED_FLOW","SKIPPED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","GUEST_KEY","GUEST_PREFIX","GET_CACHE_PREFIX","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","CallQueue","call","now","item","callQueue","gracefulFetch","url","options","__async","_a","getEmptyResponse","lastCallDataKey","response","error","body","e","generateGuestId","guestId","getLocalStorage","GUEST_KEY","GUEST_PREFIX","uuidv4","setLocalStorage","isWeb","Rules","rulesData","rule","flowId","callback","registeredFlow","flowInRules","item","visibleAPIOverride","otherFlowId","otherId","_a","otherVisible","otherVisited","flowIds","visible","Frigade","Fetchable","apiKey","config","__spreadValues","__async","isWeb","globalStateKey","getGlobalStateKey","frigadeGlobalState","_a","GUEST_PREFIX","userId","properties","__spreadProps","groupId","event","sessionDTO","flowId","flow","resetAllLocalStorage","clearCache","handler","lastFlow","cloneFlow","h","that","validator","target","key","value","previousState","newState","Rules","overrideFlowStateRaw","_b","flowStateRaw","rulesData","collectionId","visible","currentRule","statefulFlow","Flow","flowIds","flowIdsWithWrappedCallbacks","_0","callback","currentFlow","prevFlow","results","TriggerType","FlowStatus","FlowType"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@frigade/js",
3
- "version": "0.4.17",
3
+ "version": "0.4.19",
4
4
  "description": "The official Javascript SDK for Frigade.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",