@frigade/js 0.7.24 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +46 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
var A=Object.defineProperty,at=Object.defineProperties,nt=Object.getOwnPropertyDescriptor,lt=Object.getOwnPropertyDescriptors,ct=Object.getOwnPropertyNames,V=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,dt=Object.prototype.propertyIsEnumerable;var W=(r,s,t)=>s in r?A(r,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[s]=t,u=(r,s)=>{for(var t in s||(s={}))B.call(s,t)&&W(r,t,s[t]);if(V)for(var t of V(s))dt.call(s,t)&&W(r,t,s[t]);return r},I=(r,s)=>at(r,lt(s));var gt=(r,s)=>{for(var t in s)A(r,t,{get:s[t],enumerable:!0})},pt=(r,s,t,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of ct(s))!B.call(r,i)&&i!==t&&A(r,i,{get:()=>s[i],enumerable:!(e=nt(s,i))||e.enumerable});return r};var ht=r=>pt(A({},"__esModule",{value:!0}),r);var c=(r,s,t)=>new Promise((e,i)=>{var a=o=>{try{l(t.next(o))}catch(n){i(n)}},g=o=>{try{l(t.throw(o))}catch(n){i(n)}},l=o=>o.done?e(o.value):Promise.resolve(o.value).then(a,g);l((t=t.apply(r,s)).next())});var bt={};gt(bt,{Flow:()=>F,FlowStatus:()=>L,FlowType:()=>M,Frigade:()=>R,TriggerType:()=>N});module.exports=ht(bt);var D=require("uuid");var S={};function P(r){return`${r.__instanceId}-${r.apiKey}`}var v=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:j(),__instanceId:Math.random().toString(12).substring(4),generateGuestId:!0};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));this.config=u(u({},this.config),t)}fetch(s,t,e=!1){return c(this,null,function*(){return this.config.__readOnly?y():q(this.getAPIUrl(s),u(u({keepalive:!0},t!=null?t:{}),K(this.config)),e)})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=P(this.config);if(!S[s])throw new Error("Frigade has not yet been initialized");return S[s]}};var F=class extends v{constructor({config:t,id:e}){super(t);this.props={};this._isVisible=!1;this.lastStepUpdate=new Map;this.id=e,this.init()}get isVisible(){return this._isVisible}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,a,g,l,o,n;let e=C(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.type=(g=e==null?void 0:e.data)==null?void 0:g.type,this.props=(o=(l=e==null?void 0:e.data)==null?void 0:l.props)!=null?o:{},this.isCompleted=e.$state.completed,this.isStarted=e.$state.started,this.isSkipped=e.$state.skipped,this._isVisible=e.$state.visible,e.data.steps.forEach((p,d)=>{var f;let h=this.initStepFromStatefulStep(p,d),b=(f=this.steps)==null?void 0:f.get(p.id);b&&Object.keys(h).forEach(w=>{b[w]=h[w]})}),this.getGlobalState().variables[this.id]?this.applyVariablesInternal((n=this.getGlobalState().variables[this.id])!=null?n:{}):this.applyVariablesInternal({})}initStepFromStatefulStep(t,e){return I(u({},t),{flow:this,$state:I(u({},t.$state),{lastActionAt:t.$state.lastActionAt?new Date(t.$state.lastActionAt):void 0}),order:e})}init(){let t=this.getStatefulFlow(),e=new Map;t.data.steps.forEach((i,a)=>{let g=this.initStepFromStatefulStep(i,a);g.start=o=>c(this,null,function*(){let n=this.steps.get(i.id);if(this.getCurrentStep().id===n.id&&n.$state.started)return;let p=C(this.getGlobalState().flowStates[this.id]);p.data.steps[n.order].$state.started=!0,p.data.steps[n.order].$state.lastActionAt=new Date,p.$state.lastActionAt=new Date,p.$state.currentStepId=n.id,p.$state.currentStepIndex=n.order,this.getGlobalState().flowStates[this.id]=p,this.resyncState(),yield this.sendFlowStateToAPI(_,o,n.id)});let l=(o,n,p=!0)=>c(this,null,function*(){let d=this.steps.get(i.id);if((d.$state.completed||d.$state.skipped)&&p){let f=this.getStepByIndex(d.order+1);for(;f&&!f.$state.visible&&f.order!==this.steps.size-1;)f=this.getStepByIndex(f.order+1);if(f){let w=C(this.getGlobalState().flowStates[this.id]);w.$state.currentStepId=this.getStepByIndex(d.order+1).id,w.$state.currentStepIndex=d.order+1,w.data.steps[d.order+1].$state.started=!0,this.getGlobalState().flowStates[this.id]=w,yield this.sendFlowStateToAPI(_,void 0,f.id),this.resyncState()}return}let h=this.getCurrentStepOrder()+1===this.getNumberOfAvailableSteps(),b=Array.from(this.steps.values()).filter(f=>f.$state.visible&&!f.$state.completed&&!f.$state.skipped).length===1&&h;if(p){let f=C(this.getGlobalState().flowStates[this.id]);if(f.$state.started=!0,o=="complete"?f.data.steps[d.order].$state.completed=!0:f.data.steps[d.order].$state.skipped=!0,f.data.steps[d.order].$state.started=!0,f.data.steps[d.order].$state.lastActionAt=new Date,!h){let w=this.getNextVisibleStepIndexAfterIndex(d.order);w!==-1&&(f.$state.currentStepId=this.getStepByIndex(w).id,f.$state.currentStepIndex=w,f.data.steps[w].$state.started=!0)}b&&(f.$state.completed=!0,f.$state.visible=!1),this.getGlobalState().flowStates[this.id]=f,this.resyncState(),b&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(o=="complete"?Q:Z,n,d.id),b&&(yield this.sendFlowStateToAPI(G,n))});g.complete=(o,n=!0)=>c(this,null,function*(){yield l("complete",o,n)}),g.skip=(o,n=!0)=>c(this,null,function*(){yield l("skip",o,n)}),g.reset=()=>c(this,null,function*(){let o=this.steps.get(i.id);if(!o.$state.completed)return;let n=C(this.getGlobalState().flowStates[this.id]);n.data.steps[o.order].$state.started=!1,n.data.steps[o.order].$state.completed=!1,n.data.steps[o.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=n,this.resyncState(),yield this.sendFlowStateToAPI(J,void 0,o.id)}),g.onStateChange=o=>{let n=p=>{if(p.id!==this.id)return;let d=p.steps.get(i.id),h=this.lastStepUpdate.get(o);(d.$state.completed!==(h==null?void 0:h.$state.completed)||d.$state.started!==(h==null?void 0:h.$state.started)||d.$state.visible!==(h==null?void 0:h.$state.visible)||d.$state.blocked!==(h==null?void 0:h.$state.blocked))&&(o(d,h!=null?h:C(d)),this.lastStepUpdate.set(o,C(d)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(o,n),this.getGlobalState().onFlowStateChangeHandlers.push(n)},g.removeStateChangeHandler=o=>{let n=this.getGlobalState().onStepStateChangeHandlerWrappers.get(o);n&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(p=>p!==n))},e.set(i.id,g)}),this.steps=e,this.resyncState()}start(t){return c(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(Y,t))})}complete(t){return c(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(G,t))})}skip(t){return c(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(z,t))})}forward(t){return c(this,null,function*(){let e=this.getStepByIndex(this.getNextVisibleStepIndexAfterIndex(this.getCurrentStepIndex()));e&&(yield e.start(t))})}back(t){return c(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()-1);for(;e&&!e.$state.visible&&e.order!==0;)e=this.getStepByIndex(e.order-1);e&&(yield e.start(t))})}restart(){return c(this,null,function*(){yield this.sendFlowStateToAPI(X)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){let t=this.steps.get(this.getStatefulFlow().$state.currentStepId);return t||(t=this.getFirstVisibleStep(),t)}getFirstVisibleStep(){return this.getStepByIndex(this.getNextVisibleStepIndexAfterIndex(-1))}getNextVisibleStepIndexAfterIndex(t){let e=Array.from(this.steps.values());for(let i=t+1;i<e.length;i++)if(e[i].$state.visible)return i;return-1}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}getCurrentStepOrder(){let t=this.getCurrentStep();return Array.from(this.steps.values()).filter(e=>e.$state.visible).indexOf(t)}getProgress(){return(this.getNumberOfCompletedSteps()||0)/(this.getNumberOfAvailableSteps()||1)}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){this.applyVariablesInternal(t,!0)}applyVariablesInternal(t,e=!1){var g,l;let i=o=>{let n=o.match(/\${(.*?)}/g);return n&&n.forEach(p=>{let d=p.replace("${","").replace("}","");if(!t[d]){o=o.replace(p,"");return}o=o.replace(p,t[d])}),o};this.title=i((g=this.title)!=null?g:""),this.subtitle=i((l=this.subtitle)!=null?l:"");let a=o=>{o&&Object.keys(o).forEach(n=>{typeof o[n]=="string"?o[n]=i(o[n]):typeof o[n]=="object"?a(o[n]):Array.isArray(o[n])&&o[n].forEach(p=>{a(p)})})};this.steps&&this.steps.forEach(o=>{try{a(o)}catch(n){}}),this.getGlobalState().variables[this.id]=u(u({},this.getGlobalState().variables[this.id]),t),e&&this.resyncState()}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=C(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=C(this.getGlobalState().flowStates[this.id]);t.$state.started=!0,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}sendFlowStateToAPI(t,e,i){return c(this,null,function*(){var l;let a=new Date;this.getGlobalState().lastFlowSyncDate[this.id]=a,this.getGlobalState().pendingRequests[this.id]=((l=this.getGlobalState().pendingRequests[this.id])!=null?l:0)+1;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,data:e||{},actionType:t,createdAt:a,context:O(this.getGlobalState())})});this.getGlobalState().pendingRequests[this.id]-=1,!(a<this.getGlobalState().lastFlowSyncDate[this.id]||this.getGlobalState().pendingRequests[this.id]>0)&&(yield this.getGlobalState().refreshStateFromAPI(g))})}optimisticallyMarkFlowSkipped(){let t=C(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().collections.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,E(this))}),t==null||t(i)})}unregister(){this.getGlobalState().collections&&this.getGlobalState().collections.unregister(this.id)}};var tt="0.7.24";var J="NOT_STARTED_STEP",G="COMPLETED_FLOW",z="SKIPPED_FLOW",Y="STARTED_FLOW",X="NOT_STARTED_FLOW",Q="COMPLETED_STEP",Z="SKIPPED_STEP",_="STARTED_STEP",et="frigade-guest-key",T="guest_",ft="get-cache-",k="fr-js-",it="Redundant call to Frigade API removed";function E(r){return new F({config:r.config,id:r.id})}function C(r){return JSON.parse(JSON.stringify(r))}function K(r){var s,t;return{headers:{Authorization:`Bearer ${r.apiKey}`,"Content-Type":"application/json","x-frigade-sdk-version":(s=r.__platformVersion)!=null?s:tt,"x-frigade-sdk-platform":(t=r.__platformName)!=null?t:"Javascript"}}}function ut(r){if(m())try{return window.localStorage.getItem(`${k}${r}`)}catch(s){return console.debug("Error getting localStorage:",s),null}return null}function St(r,s){if(m())try{window.localStorage.setItem(`${k}${r}`,s)}catch(t){console.debug("Error setting localStorage:",t)}}function st(){Object.keys(S).forEach(r=>{r.startsWith(ft)&&delete S[r]})}function ot(){m()&&Object.keys(window.localStorage).forEach(r=>{r.startsWith(k)&&window.localStorage.removeItem(r)})}var $=class{constructor(){this.queue=[];this.ttlInMS=250;this.cacheSize=10}push(s,t){let e=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:s,time:e.getTime(),response:t!=null?t:null})}hasIdenticalRecentCall(s){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.find(e=>e.call===s)}hasCall(s){return this.queue.find(t=>t.call===s)}cancelAllPendingRequests(){this.queue=[]}};globalThis.callQueue=new $;function q(r,s,t=!1){return c(this,null,function*(){var g;if(typeof globalThis.fetch!="function")return y("- Attempted to call fetch() in an environment that doesn't support it.");let e=`${r}${JSON.stringify((g=s.body)!=null?g:{})}`,i,a=m()&&s&&s.body&&s.method==="POST";if(a&&!t){let l=globalThis.callQueue.hasIdenticalRecentCall(e);l!=null&&l.response!=null&&(i=(yield l.response).clone())}if(!i)try{let l=fetch(r,s);a&&globalThis.callQueue.push(e,l.then(o=>o.clone()).catch(()=>y())),i=yield l,a&&!globalThis.callQueue.hasCall(e)&&(i=y(it))}catch(l){return y(l)}if(!i)return y("Received an empty response");if(i.status>=400)return y(i.statusText);try{if(i.status===204)return y();let l;try{l=yield i.json()}catch(o){return y()}return l.error?y(l.error):l}catch(l){return y(l)}})}function y(r){return r&&(r===it?console.debug(r):console.warn("Call to Frigade failed:",r)),{json:()=>({}),clone:()=>({})}}function j(){if(m()){let r=ut(et);return r||(r=`${T}${(0,D.v4)()}`,St(et,r)),r}else return`${T}${(0,D.v4)()}`}function m(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function O(r){let s={registeredCollectionIds:Array.from(r.registeredCollectionIds)};return m()?u({url:r.currentUrl,userAgent:navigator.userAgent},s):s}var x=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.collections=new Map;this.flowsInCollections=new Set;this.hasChanges=!1;this.ingestCollectionsData(s)}getCollection(s){return this.collections.get(s)}getCollections(){return this.collections}collectionsHaveChanged(){return this.hasChanges}ingestCollectionsData(s){if(this.hasChanges=!0,this.checkIfCollectionsHaveChanged(s),!!this.hasChanges){this.collections=s;for(let[,t]of this.collections)for(let{flowId:e}of t.flows)this.flowsInCollections.add(e);this.registry.size>0&&(this.registryStateLocked||this.resetRegistryState(),this.processCollections()),this.fireCallbacks()}}checkIfCollectionsHaveChanged(s){let t=this.collections,e=s;t.size!==e.size&&(this.hasChanges=!0);for(let[i,a]of t){let g=e.get(i);if(a.flows.length!==g.flows.length){this.hasChanges=!0;break}for(let l=0;l<a.flows.length;l++)if(a.flows[l].flowId!==g.flows[l].flowId||a.flows[l].visible!==g.flows[l].visible){this.hasChanges=!0;break}}}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.flowsInCollections.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)}processCollections(){for(let[,s]of this.collections)for(let{flowId:t,visible:e}of s.flows){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;let a=s.flows.map(({flowId:g})=>g).filter(g=>g!==t);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.processCollections(),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.processCollections(),this.lockRegistryState(),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.resetRegistryState(),this.processCollections(),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 R=class extends v{constructor(t,e){super(u({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.visibilityChangeHandler=()=>c(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshStateFromAPI())});this.init(this.config),m()&&this.config.syncOnWindowUpdates!==!1&&(document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.navigation&&window.navigation.addEventListener("navigate",i=>c(this,null,function*(){try{if(this.getGlobalState().currentUrl===i.destination.url||i.destination.url&&this.getGlobalState().currentUrl&&i.destination.url.split("#")[0]===this.getGlobalState().currentUrl.split("#")[0])return;this.getGlobalState().currentUrl=i.destination.url,this.refreshStateFromAPI(!0)}catch(a){}})))}getConfig(){return this.config}destroy(){if(m()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=P(this.config);S[t]&&(S[t].onFlowStateChangeHandlers=[])}}init(t){return c(this,null,function*(){if(this.updateConfig(u(u({},this.config),t)),!!this.config.userId)return this.initPromise=(()=>c(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,userProperties:this.config.userProperties,groupProperties:this.config.groupProperties}):this.config.userId&&(yield this.session({userId:this.config.userId,userProperties:this.config.userProperties}))),yield this.refreshStateFromAPI()}))(),this.initPromise})}identify(t,e){return c(this,null,function*(){t!==this.config.userId&&(yield this.updateConfig(I(u({},this.config),{userId:t})),yield this.reload()),yield this.initIfNeeded(),(yield this.session({userId:this.config.userId,userProperties:e}))&&(yield this.resync())})}group(t,e){return c(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(I(u({},this.config),{groupId:t})),yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupProperties:e}),yield this.resync()})}track(t,e){return c(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 c(this,null,function*(){let e=this.lastSessionDTO;return e&&JSON.stringify(e)===JSON.stringify(t)?!1:(yield this.fetch("/v1/public/sessions",{method:"POST",body:JSON.stringify(t)}),this.lastSessionDTO=t,!0)})}isReady(){return!!(this.config.__instanceId&&this.config.apiKey&&this.initPromise)}getFlow(t){return c(this,null,function*(){if(!(this.getConfig().generateGuestId===!1&&this.getConfig().userId&&this.getConfig().userId.startsWith(T)))return yield this.initIfNeeded(),this.getFlowSync(t)})}getFlowSync(t){return this.flows.find(e=>e.id==t)}getFlows(){return c(this,null,function*(){var t;return yield this.initIfNeeded(),this.config.generateGuestId===!1&&((t=this.getConfig().userId)!=null&&t.startsWith(T))?[]:this.flows})}getCollection(t){return c(this,null,function*(){yield this.initIfNeeded();let e=this.getGlobalState().collections.getCollection(t);if(e==null)return;this.registerCollection(t);let i=yield Promise.all(e.flows.map(a=>c(this,null,function*(){return I(u({},a),{flow:yield this.getFlow(a.flowId)})})));return e.flows=i,e})}registerCollection(t){return c(this,null,function*(){yield this.initIfNeeded(),t&&this.getGlobalState().registeredCollectionIds.add(t)})}getCollectionSync(t){let e=this.getGlobalState().collections.getCollection(t);if(e!=null)return this.getGlobalState().registeredCollectionIds.add(t),e}getCollectionsSync(){return this.getGlobalState().collections.getCollections()}getCollections(){return c(this,null,function*(){if(yield this.initIfNeeded(),!this.config.userId&&this.config.generateGuestId===!1)return;let t=this.getGlobalState().collections.getCollections();if(t!=null)return t})}reload(t){return c(this,null,function*(){ot(),st(),t&&(yield this.updateConfig(t),this.mockFlowStates(P(this.config))),this.initPromise=null,yield this.init(this.config),this.triggerAllEventHandlers()})}triggerAllEventHandlers(){this.flows.forEach(t=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(e=>{let i=this.getGlobalState().previousFlows.get(t.id);e(t,i),this.getGlobalState().previousFlows.set(t.id,E(t))})})}resync(){return c(this,null,function*(){yield this.refreshStateFromAPI()})}onStateChange(t){return c(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers.push(t)})}hasFailedToLoad(){return this.hasFailed}removeStateChangeHandler(t){return c(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(e=>e!==t)})}initIfNeeded(){return c(this,null,function*(){return this.initPromise?this.initPromise:this.init(this.config)})}refreshStateFromAPI(t=!1){return c(this,null,function*(){let e=P(this.config);if(!S[e]){let i=this,a={set:function(g,l,o){if(g[l]){let n=g[l],p=o;JSON.stringify(n)!==JSON.stringify(p)&&i.triggerEventHandlers(p,n)}return g[l]=o,!0}};if(S[e]={refreshStateFromAPI:()=>c(this,null,function*(){}),collections:new x(new Map),registeredCollectionIds:new Set,flowStates:new Proxy({},a),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config,currentUrl:m()?window.location.href:"",pendingRequests:new Map,lastFlowSyncDate:new Map},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(e);return}S[e].refreshStateFromAPI=(g,l)=>c(this,null,function*(){var p,d;if(this.config.__readOnly)return;let o=g||(yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,context:O(this.getGlobalState())})},l)),n=new Map;(d=(p=o.collections)==null?void 0:p.computedOrder)==null||d.forEach(({allowedComponents:h,collectionId:b,collectionType:f,flowId:w,visible:rt})=>{var U;let H=(U=n.get(b))!=null?U:{allowedComponents:h,collectionType:f,flows:[]};H.flows.push({flowId:w,visible:rt}),n.set(b,H)}),n.size>0&&(S[e].collections.ingestCollectionsData(n),S[e].collections.collectionsHaveChanged()&&!g&&this.triggerAllEventHandlers()),o&&o.eligibleFlows?(o.eligibleFlows.forEach(h=>{S[e].flowStates[h.flowSlug]=h,this.flows.find(b=>b.id==h.flowSlug)?this.flows.forEach(b=>{b.id==h.flowSlug&&b.resyncState(h)}):this.flows.push(new F({config:this.config,id:h.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield S[e].refreshStateFromAPI(void 0,t)})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{S[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 F({config:this.config,id:e}))})}updateConfig(t){return c(this,null,function*(){this.config=u(u({},this.config),t),S[P(this.config)]&&(this.getGlobalState().config=this.config)})}triggerEventHandlers(t,e){return c(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,E(i))})})})}batchRegister(t){return c(this,null,function*(){let e=t.map(g=>c(this,[g],function*([i,a]){let l=yield this.getFlow(i);return[i,n=>{let p=this.getGlobalState().previousFlows.get(i);(p==null?void 0:p.isVisible)!==n&&this.getGlobalState().onFlowStateChangeHandlers.forEach(d=>{d(l,p),this.getGlobalState().previousFlows.set(i,E(l))}),a==null||a(n)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};var N=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(N||{}),L=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(L||{});var M=(d=>(d.ANNOUNCEMENT="ANNOUNCEMENT",d.CHECKLIST="CHECKLIST",d.FORM="FORM",d.TOUR="TOUR",d.SUPPORT="SUPPORT",d.CUSTOM="CUSTOM",d.BANNER="BANNER",d.EMBEDDED_TIP="EMBEDDED_TIP",d.NPS_SURVEY="NPS_SURVEY",d.SURVEY="SURVEY",d.CARD="CARD",d))(M||{});0&&(module.exports={Flow,FlowStatus,FlowType,Frigade,TriggerType});
|
|
2
|
+
var A=Object.defineProperty,rt=Object.defineProperties,nt=Object.getOwnPropertyDescriptor,lt=Object.getOwnPropertyDescriptors,ct=Object.getOwnPropertyNames,V=Object.getOwnPropertySymbols;var B=Object.prototype.hasOwnProperty,dt=Object.prototype.propertyIsEnumerable;var W=(n,s,t)=>s in n?A(n,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[s]=t,S=(n,s)=>{for(var t in s||(s={}))B.call(s,t)&&W(n,t,s[t]);if(V)for(var t of V(s))dt.call(s,t)&&W(n,t,s[t]);return n},I=(n,s)=>rt(n,lt(s));var gt=(n,s)=>{for(var t in s)A(n,t,{get:s[t],enumerable:!0})},pt=(n,s,t,e)=>{if(s&&typeof s=="object"||typeof s=="function")for(let i of ct(s))!B.call(n,i)&&i!==t&&A(n,i,{get:()=>s[i],enumerable:!(e=nt(s,i))||e.enumerable});return n};var ft=n=>pt(A({},"__esModule",{value:!0}),n);var p=(n,s,t)=>new Promise((e,i)=>{var r=o=>{try{d(t.next(o))}catch(a){i(a)}},f=o=>{try{d(t.throw(o))}catch(a){i(a)}},d=o=>o.done?e(o.value):Promise.resolve(o.value).then(r,f);d((t=t.apply(n,s)).next())});var wt={};gt(wt,{Flow:()=>F,FlowStatus:()=>N,FlowType:()=>L,Frigade:()=>G,TriggerType:()=>H});module.exports=ft(wt);var $=require("uuid");var w={};function E(n){return`${n.__instanceId}-${n.apiKey}`}var T=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:J(),__instanceId:Math.random().toString(12).substring(4),generateGuestId:!0};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));this.config=S(S({},this.config),t)}fetch(s,t,e=!1){return p(this,null,function*(){return this.config.__readOnly?y():q(this.getAPIUrl(s),S(S({keepalive:!0},t!=null?t:{}),K(this.config)),e)})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=E(this.config);if(!w[s])throw new Error("Frigade has not yet been initialized");return w[s]}};var F=class extends T{constructor({config:t,id:e}){super(t);this.props={};this._isVisible=!1;this.lastStepUpdate=new Map;this.id=e,this.init()}get isVisible(){return this._isVisible}set isVisible(t){this._isVisible=t}reload(){this.init()}resyncState(t){var i,r,f,d,o,a;let e=C(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.type=(f=e==null?void 0:e.data)==null?void 0:f.type,this.props=(o=(d=e==null?void 0:e.data)==null?void 0:d.props)!=null?o:{},this.isCompleted=e.$state.completed,this.isStarted=e.$state.started,this.isSkipped=e.$state.skipped,this._isVisible=e.$state.visible,e.data.steps.forEach((g,c)=>{var u;let l=this.initStepFromStatefulStep(g,c),h=(u=this.steps)==null?void 0:u.get(g.id);h&&Object.keys(l).forEach(b=>{h[b]=l[b]})}),this.getGlobalState().variables[this.id]?this.applyVariablesInternal((a=this.getGlobalState().variables[this.id])!=null?a:{}):this.applyVariablesInternal({})}initStepFromStatefulStep(t,e){return I(S({},t),{flow:this,$state:I(S({},t.$state),{lastActionAt:t.$state.lastActionAt?new Date(t.$state.lastActionAt):void 0}),order:e})}init(){let t=this.getStatefulFlow(),e=new Map;t.data.steps.forEach((i,r)=>{let f=this.initStepFromStatefulStep(i,r);f.start=o=>p(this,null,function*(){let a=this.steps.get(i.id);if(this.getCurrentStep().id===a.id&&a.$state.started)return;let g=C(this.getGlobalState().flowStates[this.id]);g.data.steps[a.order].$state.started=!0,g.data.steps[a.order].$state.lastActionAt=new Date,g.$state.lastActionAt=new Date,g.$state.currentStepId=a.id,g.$state.currentStepIndex=a.order,this.getGlobalState().flowStates[this.id]=g,this.resyncState(),yield this.sendFlowStateToAPI(_,o,a.id)});let d=(o,a,g=!0)=>p(this,null,function*(){let c=this.steps.get(i.id);if((c.$state.completed||c.$state.skipped)&&g){let u=this.getStepByIndex(c.order+1);for(;u&&!u.$state.visible&&u.order!==this.steps.size-1;)u=this.getStepByIndex(u.order+1);if(u){let b=C(this.getGlobalState().flowStates[this.id]);b.$state.currentStepId=this.getStepByIndex(c.order+1).id,b.$state.currentStepIndex=c.order+1,b.data.steps[c.order+1].$state.started=!0,this.getGlobalState().flowStates[this.id]=b,yield this.sendFlowStateToAPI(_,void 0,u.id),this.resyncState()}return}let l=this.getCurrentStepOrder()+1===this.getNumberOfAvailableSteps(),h=Array.from(this.steps.values()).filter(u=>u.$state.visible&&!u.$state.completed&&!u.$state.skipped).length===1&&l;if(g){let u=C(this.getGlobalState().flowStates[this.id]);if(u.$state.started=!0,o=="complete"?u.data.steps[c.order].$state.completed=!0:u.data.steps[c.order].$state.skipped=!0,u.data.steps[c.order].$state.started=!0,u.data.steps[c.order].$state.lastActionAt=new Date,!l){let b=this.getNextVisibleStepIndexAfterIndex(c.order);b!==-1&&(u.$state.currentStepId=this.getStepByIndex(b).id,u.$state.currentStepIndex=b,u.data.steps[b].$state.started=!0)}h&&(u.$state.completed=!0,u.$state.visible=!1),this.getGlobalState().flowStates[this.id]=u,this.resyncState(),h&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(o=="complete"?Q:Z,a,c.id),h&&(yield this.sendFlowStateToAPI(R,a))});f.complete=(o,a=!0)=>p(this,null,function*(){yield d("complete",o,a)}),f.skip=(o,a=!0)=>p(this,null,function*(){yield d("skip",o,a)}),f.reset=()=>p(this,null,function*(){let o=this.steps.get(i.id);if(!o.$state.completed)return;let a=C(this.getGlobalState().flowStates[this.id]);a.data.steps[o.order].$state.started=!1,a.data.steps[o.order].$state.completed=!1,a.data.steps[o.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=a,this.resyncState(),yield this.sendFlowStateToAPI(j,void 0,o.id)}),f.onStateChange=o=>{let a=g=>{if(g.id!==this.id)return;let c=g.steps.get(i.id),l=this.lastStepUpdate.get(o);(c.$state.completed!==(l==null?void 0:l.$state.completed)||c.$state.started!==(l==null?void 0:l.$state.started)||c.$state.visible!==(l==null?void 0:l.$state.visible)||c.$state.blocked!==(l==null?void 0:l.$state.blocked))&&(o(c,l!=null?l:C(c)),this.lastStepUpdate.set(o,C(c)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(o,a),this.getGlobalState().onFlowStateChangeHandlers.push(a)},f.removeStateChangeHandler=o=>{let a=this.getGlobalState().onStepStateChangeHandlerWrappers.get(o);a&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(g=>g!==a))},e.set(i.id,f)}),this.steps=e,this.resyncState()}start(t){return p(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(Y,t))})}complete(t){return p(this,null,function*(){this.isCompleted||(this.optimisticallyMarkFlowCompleted(),yield this.sendFlowStateToAPI(R,t))})}skip(t){return p(this,null,function*(){this.isSkipped||(this.optimisticallyMarkFlowSkipped(),yield this.sendFlowStateToAPI(z,t))})}forward(t){return p(this,null,function*(){let e=this.getStepByIndex(this.getNextVisibleStepIndexAfterIndex(this.getCurrentStepIndex()));e&&(yield e.start(t))})}back(t){return p(this,null,function*(){let e=this.getStepByIndex(this.getCurrentStepIndex()-1);for(;e&&!e.$state.visible&&e.order!==0;)e=this.getStepByIndex(e.order-1);e&&(yield e.start(t))})}restart(){return p(this,null,function*(){yield this.sendFlowStateToAPI(X)})}getStepByIndex(t){return this.steps.get(Array.from(this.steps.keys())[t])}getCurrentStep(){let t=this.steps.get(this.getStatefulFlow().$state.currentStepId);return t||(t=this.getFirstVisibleStep(),t)}getFirstVisibleStep(){return this.getStepByIndex(this.getNextVisibleStepIndexAfterIndex(-1))}getNextVisibleStepIndexAfterIndex(t){let e=Array.from(this.steps.values());for(let i=t+1;i<e.length;i++)if(e[i].$state.visible)return i;return-1}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}getCurrentStepOrder(){let t=this.getCurrentStep();return Array.from(this.steps.values()).filter(e=>e.$state.visible).indexOf(t)}getProgress(){return(this.getNumberOfCompletedSteps()||0)/(this.getNumberOfAvailableSteps()||1)}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){this.applyVariablesInternal(t,!0)}applyVariablesInternal(t,e=!1){var f,d;let i=o=>{let a=o.match(/\${(.*?)}/g);return a&&a.forEach(g=>{let c=g.replace("${","").replace("}","");if(!t[c]){o=o.replace(g,"");return}o=o.replace(g,t[c])}),o};this.title=i((f=this.title)!=null?f:""),this.subtitle=i((d=this.subtitle)!=null?d:"");let r=o=>{o&&Object.keys(o).forEach(a=>{typeof o[a]=="string"?o[a]=i(o[a]):typeof o[a]=="object"?r(o[a]):Array.isArray(o[a])&&o[a].forEach(g=>{r(g)})})};this.steps&&this.steps.forEach(o=>{try{r(o)}catch(a){}}),this.getGlobalState().variables[this.id]=S(S({},this.getGlobalState().variables[this.id]),t),e&&this.resyncState()}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=C(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=C(this.getGlobalState().flowStates[this.id]);t.$state.started=!0,this.getGlobalState().flowStates[this.id]=t,this.resyncState()}sendFlowStateToAPI(t,e,i){return p(this,null,function*(){var d;let r=new Date;this.getGlobalState().lastFlowSyncDate[this.id]=r,this.getGlobalState().pendingRequests[this.id]=((d=this.getGlobalState().pendingRequests[this.id])!=null?d:0)+1;let f=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,data:e||{},actionType:t,createdAt:r,context:O(this.getGlobalState())})});this.getGlobalState().pendingRequests[this.id]-=1,!(r<this.getGlobalState().lastFlowSyncDate[this.id]||this.getGlobalState().pendingRequests[this.id]>0)&&(yield this.getGlobalState().refreshStateFromAPI(f))})}optimisticallyMarkFlowSkipped(){let t=C(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().collections.register(this.id,i=>{let r=this.getGlobalState().previousFlows.get(this.id);(r==null?void 0:r._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(f=>{f(this,r),this.getGlobalState().previousFlows.set(this.id,P(this))}),t==null||t(i)})}unregister(){this.getGlobalState().collections&&this.getGlobalState().collections.unregister(this.id)}};var tt="0.8.0";var j="NOT_STARTED_STEP",R="COMPLETED_FLOW",z="SKIPPED_FLOW",Y="STARTED_FLOW",X="NOT_STARTED_FLOW",Q="COMPLETED_STEP",Z="SKIPPED_STEP",_="STARTED_STEP",et="frigade-guest-key",v="guest_",ht="get-cache-",D="fr-js-",it="Redundant call to Frigade API removed";function P(n){return new F({config:n.config,id:n.id})}function C(n){return JSON.parse(JSON.stringify(n))}function K(n){var s,t;return{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json","x-frigade-sdk-version":(s=n.__platformVersion)!=null?s:tt,"x-frigade-sdk-platform":(t=n.__platformName)!=null?t:"Javascript"}}}function ut(n){if(m())try{return window.localStorage.getItem(`${D}${n}`)}catch(s){return console.debug("Error getting localStorage:",s),null}return null}function St(n,s){if(m())try{window.localStorage.setItem(`${D}${n}`,s)}catch(t){console.debug("Error setting localStorage:",t)}}function st(){Object.keys(w).forEach(n=>{n.startsWith(ht)&&delete w[n]})}function ot(){m()&&Object.keys(window.localStorage).forEach(n=>{n.startsWith(D)&&window.localStorage.removeItem(n)})}var k=class{constructor(){this.queue=[];this.ttlInMS=250;this.cacheSize=10}push(s,t){let e=new Date;this.queue.length>=this.cacheSize&&this.queue.shift(),this.queue.push({call:s,time:e.getTime(),response:t!=null?t:null})}hasIdenticalRecentCall(s){let t=new Date;return this.queue=this.queue.filter(e=>t.getTime()-e.time<this.ttlInMS),this.queue.find(e=>e.call===s)}hasCall(s){return this.queue.find(t=>t.call===s)}cancelAllPendingRequests(){this.queue=[]}};globalThis.callQueue=new k;function q(n,s,t=!1){return p(this,null,function*(){var f;if(typeof globalThis.fetch!="function")return y("- Attempted to call fetch() in an environment that doesn't support it.");let e=`${n}${JSON.stringify((f=s.body)!=null?f:{})}`,i,r=m()&&s&&s.body&&s.method==="POST";if(r&&!t){let d=globalThis.callQueue.hasIdenticalRecentCall(e);d!=null&&d.response!=null&&(i=(yield d.response).clone())}if(!i)try{let d=fetch(n,s);r&&globalThis.callQueue.push(e,d.then(o=>o.clone()).catch(()=>y())),i=yield d,r&&!globalThis.callQueue.hasCall(e)&&(i=y(it))}catch(d){return y(d)}if(!i)return y("Received an empty response");if(i.status>=400)return y(i.statusText);try{if(i.status===204)return y();let d;try{d=yield i.json()}catch(o){return y()}return d.error?y(d.error):d}catch(d){return y(d)}})}function y(n){return n&&(n===it?console.debug(n):console.warn("Call to Frigade failed:",n)),{json:()=>({}),clone:()=>({})}}function J(){if(m()){let n=ut(et);return n||(n=`${v}${(0,$.v4)()}`,St(et,n)),n}else return`${v}${(0,$.v4)()}`}function m(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function O(n){let s={registeredCollectionIds:Array.from(n.registeredCollectionIds)};return m()?S({url:n.currentUrl,userAgent:navigator.userAgent},s):s}var x=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.collections=new Map;this.flowsInCollections=new Set;this.hasChanges=!1;this.ingestCollectionsData(s)}getCollection(s){return this.collections.get(s)}getCollections(){return this.collections}collectionsHaveChanged(){return this.hasChanges}ingestCollectionsData(s){if(this.hasChanges=!0,this.checkIfCollectionsHaveChanged(s),!!this.hasChanges){this.collections=s;for(let[,t]of this.collections)for(let{flowId:e}of t.flows)this.flowsInCollections.add(e);this.registry.size>0&&(this.registryStateLocked||this.resetRegistryState(),this.processCollections()),this.fireCallbacks()}}checkIfCollectionsHaveChanged(s){let t=this.collections,e=s;t.size!==e.size&&(this.hasChanges=!0);for(let[i,r]of t){let f=e.get(i);if(r.flows.length!==f.flows.length){this.hasChanges=!0;break}for(let d=0;d<r.flows.length;d++)if(r.flows[d].flowId!==f.flows[d].flowId||r.flows[d].visible!==f.flows[d].visible){this.hasChanges=!0;break}}}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.flowsInCollections.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)}processCollections(){for(let[,s]of this.collections)for(let{flowId:t,visible:e}of s.flows){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;let r=s.flows.map(({flowId:f})=>f).filter(f=>f!==t);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.processCollections(),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.processCollections(),this.lockRegistryState(),this.fireCallbacks()}unregister(s){this.registry.delete(s),this.resetRegistryState(),this.processCollections(),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 G=class extends T{constructor(t,e){super(S({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.eventHandlers=new Map;this.visibilityChangeHandler=()=>p(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshStateFromAPI())});this.init(this.config),m()&&this.config.syncOnWindowUpdates!==!1&&(document.addEventListener("visibilitychange",this.visibilityChangeHandler),window.navigation&&window.navigation.addEventListener("navigate",i=>p(this,null,function*(){try{if(this.getGlobalState().currentUrl===i.destination.url||i.destination.url&&this.getGlobalState().currentUrl&&i.destination.url.split("#")[0]===this.getGlobalState().currentUrl.split("#")[0])return;this.getGlobalState().currentUrl=i.destination.url,this.refreshStateFromAPI(!0)}catch(r){}})))}getConfig(){return this.config}destroy(){if(m()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=E(this.config);w[t]&&(w[t].onFlowStateChangeHandlers=[])}}init(t){return p(this,null,function*(){if(this.updateConfig(S(S({},this.config),t)),!!this.config.userId)return this.initPromise=(()=>p(this,null,function*(){var e;this.config.__readOnly||(e=this.config.userId)!=null&&e.startsWith(v)||(this.config.userId&&this.config.groupId?yield this.session({userId:this.config.userId,groupId:this.config.groupId,userProperties:this.config.userProperties,groupProperties:this.config.groupProperties}):this.config.userId&&(yield this.session({userId:this.config.userId,userProperties:this.config.userProperties}))),yield this.refreshStateFromAPI()}))(),this.initPromise})}identify(t,e){return p(this,null,function*(){t!==this.config.userId&&(yield this.updateConfig(I(S({},this.config),{userId:t})),yield this.reload()),yield this.initIfNeeded(),(yield this.session({userId:this.config.userId,userProperties:e}))&&(yield this.resync())})}group(t,e){return p(this,null,function*(){yield this.initIfNeeded(),this.updateConfig(I(S({},this.config),{groupId:t})),yield this.session({userId:this.config.userId,groupId:this.config.groupId,groupProperties:e}),yield this.resync()})}track(t,e){return p(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 p(this,null,function*(){let e=this.lastSessionDTO;return e&&JSON.stringify(e)===JSON.stringify(t)?!1:(yield this.fetch("/v1/public/sessions",{method:"POST",body:JSON.stringify(t)}),this.lastSessionDTO=t,!0)})}isReady(){return!!(this.config.__instanceId&&this.config.apiKey&&this.initPromise)}getFlow(t){return p(this,null,function*(){if(!(this.getConfig().generateGuestId===!1&&this.getConfig().userId&&this.getConfig().userId.startsWith(v)))return yield this.initIfNeeded(),this.getFlowSync(t)})}getFlowSync(t){return this.flows.find(e=>e.id==t)}getFlows(){return p(this,null,function*(){var t;return yield this.initIfNeeded(),this.config.generateGuestId===!1&&((t=this.getConfig().userId)!=null&&t.startsWith(v))?[]:this.flows})}getCollection(t){return p(this,null,function*(){yield this.initIfNeeded();let e=this.getGlobalState().collections.getCollection(t);if(e==null)return;this.registerCollection(t);let i=yield Promise.all(e.flows.map(r=>p(this,null,function*(){return I(S({},r),{flow:yield this.getFlow(r.flowId)})})));return e.flows=i,e})}registerCollection(t){return p(this,null,function*(){yield this.initIfNeeded(),t&&this.getGlobalState().registeredCollectionIds.add(t)})}getCollectionSync(t){let e=this.getGlobalState().collections.getCollection(t);if(e!=null)return this.getGlobalState().registeredCollectionIds.add(t),e}getCollectionsSync(){return this.getGlobalState().collections.getCollections()}getCollections(){return p(this,null,function*(){if(yield this.initIfNeeded(),!this.config.userId&&this.config.generateGuestId===!1)return;let t=this.getGlobalState().collections.getCollections();if(t!=null)return t})}reload(t){return p(this,null,function*(){ot(),st(),t&&(yield this.updateConfig(t),this.mockFlowStates(E(this.config))),this.initPromise=null,yield this.init(this.config),this.triggerAllLegacyEventHandlers(),this.triggerAllEventHandlers()})}triggerAllLegacyEventHandlers(){this.flows.forEach(t=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(e=>{let i=this.getGlobalState().previousFlows.get(t.id);e(t,i),this.getGlobalState().previousFlows.set(t.id,P(t))})})}triggerAllEventHandlers(){this.flows.forEach(t=>{let e=this.getGlobalState().previousFlows.get(t.id);this.triggerEventHandlers(t.rawData,e==null?void 0:e.rawData)})}resync(){return p(this,null,function*(){yield this.refreshStateFromAPI()})}onStateChange(t){return p(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers.push(t)})}on(t,e){return p(this,null,function*(){var i;this.eventHandlers.set(t,[...(i=this.eventHandlers.get(t))!=null?i:[],e])})}off(t,e){return p(this,null,function*(){var i;this.eventHandlers.set(t,((i=this.eventHandlers.get(t))!=null?i:[]).filter(r=>r!==e))})}hasFailedToLoad(){return this.hasFailed}removeStateChangeHandler(t){return p(this,null,function*(){yield this.initIfNeeded(),this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(e=>e!==t)})}initIfNeeded(){return p(this,null,function*(){return this.initPromise?this.initPromise:this.init(this.config)})}refreshStateFromAPI(t=!1){return p(this,null,function*(){let e=E(this.config);if(!w[e]){let i=this,r={set:function(f,d,o){if(f[d]){let a=f[d],g=o;JSON.stringify(a)!==JSON.stringify(g)&&(i.triggerDeprecatedEventHandlers(g,a),i.triggerEventHandlers(g,a))}return f[d]=o,!0}};if(w[e]={refreshStateFromAPI:()=>p(this,null,function*(){}),collections:new x(new Map),registeredCollectionIds:new Set,flowStates:new Proxy({},r),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config,currentUrl:m()?window.location.href:"",pendingRequests:new Map,lastFlowSyncDate:new Map},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(e);return}w[e].refreshStateFromAPI=(f,d)=>p(this,null,function*(){var g,c;if(this.config.__readOnly)return;let o=f||(yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,context:O(this.getGlobalState())})},d)),a=new Map;(c=(g=o.collections)==null?void 0:g.computedOrder)==null||c.forEach(({allowedComponents:l,collectionId:h,collectionType:u,flowId:b,visible:at})=>{var U;let M=(U=a.get(h))!=null?U:{allowedComponents:l,collectionType:u,flows:[]};M.flows.push({flowId:b,visible:at}),a.set(h,M)}),a.size>0&&(w[e].collections.ingestCollectionsData(a),w[e].collections.collectionsHaveChanged()&&!f&&(this.triggerAllLegacyEventHandlers(),this.triggerAllEventHandlers())),o&&o.eligibleFlows?(o.eligibleFlows.forEach(l=>{w[e].flowStates[l.flowSlug]=l,this.flows.find(h=>h.id==l.flowSlug)?this.flows.forEach(h=>{h.id==l.flowSlug&&h.resyncState(l)}):this.flows.push(new F({config:this.config,id:l.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield w[e].refreshStateFromAPI(void 0,t)})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{w[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 F({config:this.config,id:e}))})}updateConfig(t){return p(this,null,function*(){this.config=S(S({},this.config),t),w[E(this.config)]&&(this.getGlobalState().config=this.config)})}triggerDeprecatedEventHandlers(t,e){return p(this,null,function*(){t&&this.flows.forEach(i=>{i.id==e.flowSlug&&this.getGlobalState().onFlowStateChangeHandlers.forEach(r=>{let f=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),r(i,f),this.getGlobalState().previousFlows.set(i.id,P(i))})})})}triggerEventHandlers(t,e){var i,r,f,d;if(t){for(let o of this.flows)if(o.id==t.flowSlug){let a=this.getGlobalState().previousFlows.get(o.id);o.resyncState(t);for(let[g,c]of this.eventHandlers.entries())switch(g){case"flow.complete":t.$state.completed&&(e==null?void 0:e.$state.completed)===!1&&c.forEach(l=>l(g,o,a));break;case"flow.restart":!t.$state.started&&(e==null?void 0:e.$state.started)===!0&&c.forEach(l=>l(g,o,a));break;case"flow.skip":t.$state.skipped&&(e==null?void 0:e.$state.skipped)===!1&&c.forEach(l=>l(g,o,a));break;case"flow.start":t.$state.started&&(e==null?void 0:e.$state.started)===!1&&c.forEach(l=>l(g,o,a));break;case"step.complete":for(let l of(i=t.data.steps)!=null?i:[])l.$state.completed&&!(e!=null&&e.data.steps.find(h=>h.id===l.id&&h.$state.completed))&&c.forEach(h=>h(g,o,a,o.steps.get(l.id)));break;case"step.reset":for(let l of(r=t.data.steps)!=null?r:[]){let h=e==null?void 0:e.data.steps.find(u=>u.id===l.id);l.$state.started==!1&&!l.$state.lastActionAt&&(h!=null&&h.$state.started)&&(h!=null&&h.$state.lastActionAt)&&c.forEach(u=>u(g,o,a,o.steps.get(l.id)))}break;case"step.skip":for(let l of(f=t.data.steps)!=null?f:[])l.$state.skipped&&!(e!=null&&e.data.steps.find(h=>h.id===l.id&&h.$state.skipped))&&c.forEach(h=>h(g,o,a,o.steps.get(l.id)));break;case"step.start":for(let l of(d=t.data.steps)!=null?d:[])l.$state.started&&(e!=null&&e.data.steps.find(h=>h.id===l.id&&h.$state.started===!1))&&c.forEach(h=>h(g,o,a,o.steps.get(l.id)));break;case"flow.any":JSON.stringify(t)!==JSON.stringify(e!=null?e:{})&&c.forEach(l=>l(g,o,a));break}this.getGlobalState().previousFlows.set(o.id,P(o))}}}batchRegister(t){return p(this,null,function*(){let e=t.map(f=>p(this,[f],function*([i,r]){let d=yield this.getFlow(i);return[i,a=>{let g=this.getGlobalState().previousFlows.get(i);(g==null?void 0:g.isVisible)!==a&&this.getGlobalState().onFlowStateChangeHandlers.forEach(c=>{c(d,g),this.getGlobalState().previousFlows.set(i,P(d))}),r==null||r(a)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};var H=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(H||{}),N=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(N||{});var L=(c=>(c.ANNOUNCEMENT="ANNOUNCEMENT",c.CHECKLIST="CHECKLIST",c.FORM="FORM",c.TOUR="TOUR",c.SUPPORT="SUPPORT",c.CUSTOM="CUSTOM",c.BANNER="BANNER",c.EMBEDDED_TIP="EMBEDDED_TIP",c.NPS_SURVEY="NPS_SURVEY",c.SURVEY="SURVEY",c.CARD="CARD",c))(L||{});0&&(module.exports={Flow,FlowStatus,FlowType,Frigade,TriggerType});
|
|
3
3
|
//# sourceMappingURL=index.cjs.map
|