@frigade/js 0.7.10 → 0.7.12
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 +5 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -19,10 +19,13 @@ declare class Collections {
|
|
|
19
19
|
private registryStateLocked;
|
|
20
20
|
private collections;
|
|
21
21
|
private flowsInCollections;
|
|
22
|
+
private hasChanges;
|
|
22
23
|
constructor(collectionsData: CollectionsList);
|
|
23
24
|
getCollection(collectionId: string): Collection;
|
|
24
25
|
getCollections(): CollectionsList;
|
|
26
|
+
collectionsHaveChanged(): boolean;
|
|
25
27
|
ingestCollectionsData(collectionsData: CollectionsList): void;
|
|
28
|
+
private checkIfCollectionsHaveChanged;
|
|
26
29
|
fireCallbacks(): void;
|
|
27
30
|
isFlowVisible(flowId: string): boolean;
|
|
28
31
|
lockRegistryState(): void;
|
|
@@ -640,6 +643,7 @@ declare class Frigade extends Fetchable {
|
|
|
640
643
|
getFlowSync(flowId: string): Flow;
|
|
641
644
|
getFlows(): Promise<Flow[]>;
|
|
642
645
|
getCollection(collectionId: string): Promise<EnrichedCollection>;
|
|
646
|
+
registerCollection(collectionId: string): Promise<void>;
|
|
643
647
|
/**
|
|
644
648
|
* @ignore
|
|
645
649
|
*/
|
|
@@ -655,6 +659,7 @@ declare class Frigade extends Fetchable {
|
|
|
655
659
|
* @param config optional config to use when reloading. If not passed, the current config will be used.
|
|
656
660
|
*/
|
|
657
661
|
reload(config?: FrigadeConfig): Promise<void>;
|
|
662
|
+
private triggerAllEventHandlers;
|
|
658
663
|
private resync;
|
|
659
664
|
/**
|
|
660
665
|
* Event handler that captures all changes that happen to the state of the Flows.
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
var rt=Object.defineProperty,at=Object.defineProperties;var nt=Object.getOwnPropertyDescriptors;var L=Object.getOwnPropertySymbols;var lt=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable;var M=(a,s,t)=>s in a?rt(a,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[s]=t,S=(a,s)=>{for(var t in s||(s={}))lt.call(s,t)&&M(a,t,s[t]);if(L)for(var t of L(s))ct.call(s,t)&&M(a,t,s[t]);return a},C=(a,s)=>at(a,nt(s));var c=(a,s,t)=>new Promise((e,i)=>{var n=r=>{try{o(t.next(r))}catch(l){i(l)}},g=r=>{try{o(t.throw(r))}catch(l){i(l)}},o=r=>r.done?e(r.value):Promise.resolve(r.value).then(n,g);o((t=t.apply(a,s)).next())});import{v4 as Y}from"uuid";var u={};function P(a){return`${a.__instanceId}-${a.apiKey}`}var I=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:V(),__instanceId:Math.random().toString(12).substring(4),generateGuestId:!0};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));!s.userId&&s.generateGuestId===!1&&delete this.config.userId,this.config=S(S({},this.config),t)}fetch(s,t,e=!1){return c(this,null,function*(){return this.config.__readOnly?w():H(this.getAPIUrl(s),S(S({keepalive:!0},t!=null?t:{}),U(this.config)),e)})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=P(this.config);if(!u[s])throw new Error("Frigade has not yet been initialized");return u[s]}};var F=class extends I{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,n,g,o,r,l;let e=y(t!=null?t:this.getStatefulFlow());this.rawData=e,this.title=(i=e==null?void 0:e.data)==null?void 0:i.title,this.subtitle=(n=e==null?void 0:e.data)==null?void 0:n.subtitle,this.type=(g=e==null?void 0:e.data)==null?void 0:g.type,this.props=(r=(o=e==null?void 0:e.data)==null?void 0:o.props)!=null?r:{},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 b;let h=this.initStepFromStatefulStep(p,d),f=(b=this.steps)==null?void 0:b.get(p.id);f&&Object.keys(h).forEach(E=>{f[E]=h[E]})}),this.getGlobalState().variables[this.id]&&this.applyVariables((l=this.getGlobalState().variables[this.id])!=null?l:{})}initStepFromStatefulStep(t,e){return C(S({},t),{flow:this,$state:C(S({},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,n)=>{let g=this.initStepFromStatefulStep(i,n);g.start=r=>c(this,null,function*(){let l=this.steps.get(i.id);if(this.getCurrentStep().id===l.id&&l.$state.started)return;let p=y(this.getGlobalState().flowStates[this.id]);p.data.steps[l.order].$state.started=!0,p.data.steps[l.order].$state.lastActionAt=new Date,p.$state.lastActionAt=new Date,p.$state.currentStepId=l.id,p.$state.currentStepIndex=l.order,this.getGlobalState().flowStates[this.id]=p,this.resyncState(),yield this.sendFlowStateToAPI(R,r,l.id)});let o=(r,l,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 b=y(this.getGlobalState().flowStates[this.id]);b.$state.currentStepId=this.getStepByIndex(d.order+1).id,b.$state.currentStepIndex=d.order+1,b.data.steps[d.order+1].$state.started=!0,this.getGlobalState().flowStates[this.id]=b,yield this.sendFlowStateToAPI(R,void 0,f.id),this.resyncState()}return}let h=this.getCurrentStepOrder()+1===this.getNumberOfAvailableSteps();if(p){let f=y(this.getGlobalState().flowStates[this.id]);if(f.$state.started=!0,r=="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)f.$state.completed=!0,f.$state.visible=!1;else{let b=this.getNextVisibleStepIndexAfterIndex(d.order);b!==-1&&(f.$state.currentStepId=this.getStepByIndex(b).id,f.$state.currentStepIndex=b,f.data.steps[b].$state.started=!0)}this.getGlobalState().flowStates[this.id]=f,this.resyncState(),h&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(r=="complete"?j:J,l,d.id),h&&(yield this.sendFlowStateToAPI(G,l))});g.complete=(r,l=!0)=>c(this,null,function*(){yield o("complete",r,l)}),g.skip=(r,l=!0)=>c(this,null,function*(){yield o("skip",r,l)}),g.reset=()=>c(this,null,function*(){let r=this.steps.get(i.id);if(!r.$state.completed)return;let l=y(this.getGlobalState().flowStates[this.id]);l.data.steps[r.order].$state.started=!1,l.data.steps[r.order].$state.completed=!1,l.data.steps[r.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=l,this.resyncState(),yield this.sendFlowStateToAPI(W,void 0,r.id)}),g.onStateChange=r=>{let l=p=>{if(p.id!==this.id)return;let d=p.steps.get(i.id),h=this.lastStepUpdate.get(r);(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))&&(r(d,h!=null?h:y(d)),this.lastStepUpdate.set(r,y(d)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(r,l),this.getGlobalState().onFlowStateChangeHandlers.push(l)},g.removeStateChangeHandler=r=>{let l=this.getGlobalState().onStepStateChangeHandlerWrappers.get(r);l&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(p=>p!==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 c(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(K,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(B,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(q)})}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,n)=>{i.id===this.id&&(i.isCompleted!==(n==null?void 0:n.isCompleted)||i.isStarted!==(n==null?void 0:n.isStarted)||i.isSkipped!==(n==null?void 0:n.isSkipped)||i.isVisible!==(n==null?void 0:n.isVisible)||JSON.stringify(i.steps)!==JSON.stringify(n==null?void 0:n.steps))&&t(i,n)};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 n,g;if(this.getGlobalState().variables[this.id]&&JSON.stringify(this.getGlobalState().variables[this.id])!==JSON.stringify(t)){this.getGlobalState().variables[this.id]=t,this.reload();return}let e=o=>{let r=o.match(/\${(.*?)}/g);return r&&r.forEach(l=>{let p=l.replace("${","").replace("}","");if(!t[p]){o=o.replace(l,"");return}o=o.replace(l,t[p])}),o};this.title=e((n=this.title)!=null?n:""),this.subtitle=e((g=this.subtitle)!=null?g:"");let i=o=>{o&&Object.keys(o).forEach(r=>{typeof o[r]=="string"?o[r]=e(o[r]):typeof o[r]=="object"?i(o[r]):Array.isArray(o[r])&&o[r].forEach(l=>{i(l)})})};this.steps&&this.steps.forEach(o=>{i(o)}),this.getGlobalState().variables[this.id]=t}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=y(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=y(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 o;let n=new Date;this.getGlobalState().lastFlowSyncDate[this.id]=n,this.getGlobalState().pendingRequests[this.id]=((o=this.getGlobalState().pendingRequests[this.id])!=null?o: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:n,context:T(this.getGlobalState())})});this.getGlobalState().pendingRequests[this.id]-=1,!(n<this.getGlobalState().lastFlowSyncDate[this.id]||this.getGlobalState().pendingRequests[this.id]>0)&&(yield this.getGlobalState().refreshStateFromAPI(g))})}optimisticallyMarkFlowSkipped(){let t=y(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 n=this.getGlobalState().previousFlows.get(this.id);(n==null?void 0:n._isVisible)!==i&&this.getGlobalState().onFlowStateChangeHandlers.forEach(g=>{g(this,n),this.getGlobalState().previousFlows.set(this.id,v(this))}),t==null||t(i)})}unregister(){this.getGlobalState().collections&&this.getGlobalState().collections.unregister(this.id)}};var z="0.7.10";var W="NOT_STARTED_STEP",G="COMPLETED_FLOW",B="SKIPPED_FLOW",K="STARTED_FLOW",q="NOT_STARTED_FLOW",j="COMPLETED_STEP",J="SKIPPED_STEP",R="STARTED_STEP",X="frigade-guest-key",x="guest_",dt="get-cache-",D="fr-js-",Q="Redundant call to Frigade API removed";function v(a){return new F({config:a.config,id:a.id})}function y(a){return JSON.parse(JSON.stringify(a))}function U(a){var s,t;return{headers:{Authorization:`Bearer ${a.apiKey}`,"Content-Type":"application/json","x-frigade-sdk-version":(s=a.__platformVersion)!=null?s:z,"x-frigade-sdk-platform":(t=a.__platformName)!=null?t:"Javascript"}}}function gt(a){return m()?window.localStorage.getItem(`${D}${a}`):null}function pt(a,s){m()&&window.localStorage.setItem(`${D}${a}`,s)}function Z(){Object.keys(u).forEach(a=>{a.startsWith(dt)&&delete u[a]})}function tt(){m()&&Object.keys(window.localStorage).forEach(a=>{a.startsWith(D)&&window.localStorage.removeItem(a)})}var _=class{constructor(){this.queue=[];this.ttlInMS=250;this.cacheSize=10;this.controller=new AbortController}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.controller.abort(Q),this.queue=[],this.controller=new AbortController}getController(){return this.controller}},A=new _;function H(a,s,t=!1){return c(this,null,function*(){var g;if(typeof globalThis.fetch!="function")return w("- Attempted to call fetch() in an environment that doesn't support it.");let e=`${a}${JSON.stringify((g=s.body)!=null?g:{})}`,i,n=m()&&s&&s.body&&s.method==="POST";if(n&&!t){let o=A.hasIdenticalRecentCall(e);o!=null&&o.response!=null&&(i=(yield o.response).clone())}if(!i)try{t&&A.cancelAllPendingRequests();let o=fetch(a,C(S({},s!=null?s:{}),{signal:A.getController().signal}));n&&A.push(e,o.then(r=>r.clone()).catch(()=>w())),i=yield o}catch(o){return w(o)}if(!i)return w("Received an empty response");if(i.status>=400)return w(i.statusText);try{if(i.status===204)return w();let o;try{o=yield i.json()}catch(r){return w()}return o.error?w(o.error):o}catch(o){return w(o)}})}function w(a){return a&&(a===Q?console.debug(a):console.warn("Call to Frigade failed:",a)),{json:()=>({}),clone:()=>({})}}function V(){if(m()){let a=gt(X);return a||(a=`${x}${Y()}`,pt(X,a)),a}else return`${x}${Y()}`}function m(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function T(a){let s={registeredCollectionIds:Array.from(a.registeredCollectionIds)};return m()?S({url:a.currentUrl,userAgent:navigator.userAgent},s):s}var O=class{constructor(s){this.registry=new Map;this.registryStateLocked=!1;this.collections=new Map;this.flowsInCollections=new Set;this.ingestCollectionsData(s)}getCollection(s){return this.collections.get(s)}getCollections(){return this.collections}ingestCollectionsData(s){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()}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 n=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 $=class extends I{constructor(t,e){super(S({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)return;this.getGlobalState().currentUrl=i.destination.url,this.refreshStateFromAPI(!0)}catch(n){}})))}getConfig(){return this.config}destroy(){if(m()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=P(this.config);u[t]&&(u[t].onFlowStateChangeHandlers=[])}}init(t){return c(this,null,function*(){if(this.updateConfig(S(S({},this.config),t)),!(!this.config.userId&&this.config.generateGuestId===!1))return this.initPromise=(()=>c(this,null,function*(){var e;this.config.__readOnly||(e=this.config.userId)!=null&&e.startsWith(x)||(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*(){yield this.updateConfig(C(S({},this.config),{userId:t})),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(C(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 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*(){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 c(this,null,function*(){return yield this.initIfNeeded(),this.getFlowSync(t)})}getFlowSync(t){return this.flows.find(e=>e.id==t)}getFlows(){return c(this,null,function*(){return yield this.initIfNeeded(),this.flows})}getCollection(t){return c(this,null,function*(){yield this.initIfNeeded();let e=this.getGlobalState().collections.getCollection(t);if(e==null)return;this.getGlobalState().registeredCollectionIds.add(t);let i=yield Promise.all(e.flows.map(n=>c(this,null,function*(){return C(S({},n),{flow:yield this.getFlow(n.flowId)})})));return e.flows=i,e})}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*(){tt(),Z(),t&&(yield this.updateConfig(t),this.mockFlowStates(P(this.config))),this.initPromise=null,yield this.init(this.config),this.flows.forEach(e=>{this.getGlobalState().onFlowStateChangeHandlers.forEach(i=>{let n=this.getGlobalState().previousFlows.get(e.id);i(e,n),this.getGlobalState().previousFlows.set(e.id,v(e))})})})}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(!u[e]){let i=this,n={set:function(g,o,r){if(g[o]){let l=g[o],p=r;JSON.stringify(l)!==JSON.stringify(p)&&i.triggerEventHandlers(p,l)}return g[o]=r,!0}};if(u[e]={refreshStateFromAPI:()=>c(this,null,function*(){}),collections:new O(new Map),registeredCollectionIds:new Set,flowStates:new Proxy({},n),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}u[e].refreshStateFromAPI=(g,o)=>c(this,null,function*(){var p,d;if(this.config.__readOnly)return;let r=g||(yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,context:T(this.getGlobalState())})},o)),l=new Map;(d=(p=r.collections)==null?void 0:p.computedOrder)==null||d.forEach(({allowedComponents:h,collectionId:f,collectionType:b,flowId:E,visible:ot})=>{var N;let k=(N=l.get(f))!=null?N:{allowedComponents:h,collectionType:b,flows:[]};k.flows.push({flowId:E,visible:ot}),l.set(f,k)}),l.size>0&&u[e].collections.ingestCollectionsData(l),r&&r.eligibleFlows?(r.eligibleFlows.forEach(h=>{u[e].flowStates[h.flowSlug]=h,this.flows.find(f=>f.id==h.flowSlug)?this.flows.forEach(f=>{f.id==h.flowSlug&&f.resyncState(h)}):this.flows.push(new F({config:this.config,id:h.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield u[e].refreshStateFromAPI(void 0,t)})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{u[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=S(S({},this.config),t),u[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(n=>{let g=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),n(i,g),this.getGlobalState().previousFlows.set(i.id,v(i))})})})}batchRegister(t){return c(this,null,function*(){let e=t.map(g=>c(this,[g],function*([i,n]){let o=yield this.getFlow(i);return[i,l=>{let p=this.getGlobalState().previousFlows.get(i);(p==null?void 0:p.isVisible)!==l&&this.getGlobalState().onFlowStateChangeHandlers.forEach(d=>{d(o,p),this.getGlobalState().previousFlows.set(i,v(o))}),n==null||n(l)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};var et=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(et||{}),it=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(it||{});var st=(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))(st||{});export{F as Flow,it as FlowStatus,st as FlowType,$ as Frigade,et as TriggerType};
|
|
2
|
+
var rt=Object.defineProperty,at=Object.defineProperties;var nt=Object.getOwnPropertyDescriptors;var L=Object.getOwnPropertySymbols;var lt=Object.prototype.hasOwnProperty,ct=Object.prototype.propertyIsEnumerable;var M=(n,s,t)=>s in n?rt(n,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[s]=t,S=(n,s)=>{for(var t in s||(s={}))lt.call(s,t)&&M(n,t,s[t]);if(L)for(var t of L(s))ct.call(s,t)&&M(n,t,s[t]);return n},F=(n,s)=>at(n,nt(s));var c=(n,s,t)=>new Promise((e,i)=>{var r=a=>{try{o(t.next(a))}catch(l){i(l)}},d=a=>{try{o(t.throw(a))}catch(l){i(l)}},o=a=>a.done?e(a.value):Promise.resolve(a.value).then(r,d);o((t=t.apply(n,s)).next())});import{v4 as Y}from"uuid";var u={};function P(n){return`${n.__instanceId}-${n.apiKey}`}var I=class{constructor(s){this.config={apiKey:"",apiUrl:"https://api.frigade.com",userId:V(),__instanceId:Math.random().toString(12).substring(4),generateGuestId:!0};let t=Object.fromEntries(Object.entries(s).filter(([e,i])=>i!=null));!s.userId&&s.generateGuestId===!1&&delete this.config.userId,this.config=S(S({},this.config),t)}fetch(s,t,e=!1){return c(this,null,function*(){return this.config.__readOnly?w():U(this.getAPIUrl(s),S(S({keepalive:!0},t!=null?t:{}),H(this.config)),e)})}getAPIUrl(s){return`${this.config.apiUrl.replace(/\/$/,"")}/${s.replace(/^\//,"")}`}getGlobalState(){let s=P(this.config);if(!u[s])throw new Error("Frigade has not yet been initialized");return u[s]}};var m=class extends I{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,d,o,a,l;let e=y(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=(d=e==null?void 0:e.data)==null?void 0:d.type,this.props=(a=(o=e==null?void 0:e.data)==null?void 0:o.props)!=null?a:{},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,g)=>{var b;let h=this.initStepFromStatefulStep(p,g),f=(b=this.steps)==null?void 0:b.get(p.id);f&&Object.keys(h).forEach(E=>{f[E]=h[E]})}),this.getGlobalState().variables[this.id]&&this.applyVariables((l=this.getGlobalState().variables[this.id])!=null?l:{})}initStepFromStatefulStep(t,e){return F(S({},t),{flow:this,$state:F(S({},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 d=this.initStepFromStatefulStep(i,r);d.start=a=>c(this,null,function*(){let l=this.steps.get(i.id);if(this.getCurrentStep().id===l.id&&l.$state.started)return;let p=y(this.getGlobalState().flowStates[this.id]);p.data.steps[l.order].$state.started=!0,p.data.steps[l.order].$state.lastActionAt=new Date,p.$state.lastActionAt=new Date,p.$state.currentStepId=l.id,p.$state.currentStepIndex=l.order,this.getGlobalState().flowStates[this.id]=p,this.resyncState(),yield this.sendFlowStateToAPI(R,a,l.id)});let o=(a,l,p=!0)=>c(this,null,function*(){let g=this.steps.get(i.id);if((g.$state.completed||g.$state.skipped)&&p){let f=this.getStepByIndex(g.order+1);for(;f&&!f.$state.visible&&f.order!==this.steps.size-1;)f=this.getStepByIndex(f.order+1);if(f){let b=y(this.getGlobalState().flowStates[this.id]);b.$state.currentStepId=this.getStepByIndex(g.order+1).id,b.$state.currentStepIndex=g.order+1,b.data.steps[g.order+1].$state.started=!0,this.getGlobalState().flowStates[this.id]=b,yield this.sendFlowStateToAPI(R,void 0,f.id),this.resyncState()}return}let h=this.getCurrentStepOrder()+1===this.getNumberOfAvailableSteps();if(p){let f=y(this.getGlobalState().flowStates[this.id]);if(f.$state.started=!0,a=="complete"?f.data.steps[g.order].$state.completed=!0:f.data.steps[g.order].$state.skipped=!0,f.data.steps[g.order].$state.started=!0,f.data.steps[g.order].$state.lastActionAt=new Date,h)f.$state.completed=!0,f.$state.visible=!1;else{let b=this.getNextVisibleStepIndexAfterIndex(g.order);b!==-1&&(f.$state.currentStepId=this.getStepByIndex(b).id,f.$state.currentStepIndex=b,f.data.steps[b].$state.started=!0)}this.getGlobalState().flowStates[this.id]=f,this.resyncState(),h&&this.optimisticallyMarkFlowCompleted()}yield this.sendFlowStateToAPI(a=="complete"?j:J,l,g.id),h&&(yield this.sendFlowStateToAPI(G,l))});d.complete=(a,l=!0)=>c(this,null,function*(){yield o("complete",a,l)}),d.skip=(a,l=!0)=>c(this,null,function*(){yield o("skip",a,l)}),d.reset=()=>c(this,null,function*(){let a=this.steps.get(i.id);if(!a.$state.completed)return;let l=y(this.getGlobalState().flowStates[this.id]);l.data.steps[a.order].$state.started=!1,l.data.steps[a.order].$state.completed=!1,l.data.steps[a.order].$state.lastActionAt=void 0,this.getGlobalState().flowStates[this.id]=l,this.resyncState(),yield this.sendFlowStateToAPI(W,void 0,a.id)}),d.onStateChange=a=>{let l=p=>{if(p.id!==this.id)return;let g=p.steps.get(i.id),h=this.lastStepUpdate.get(a);(g.$state.completed!==(h==null?void 0:h.$state.completed)||g.$state.started!==(h==null?void 0:h.$state.started)||g.$state.visible!==(h==null?void 0:h.$state.visible)||g.$state.blocked!==(h==null?void 0:h.$state.blocked))&&(a(g,h!=null?h:y(g)),this.lastStepUpdate.set(a,y(g)))};this.getGlobalState().onStepStateChangeHandlerWrappers.set(a,l),this.getGlobalState().onFlowStateChangeHandlers.push(l)},d.removeStateChangeHandler=a=>{let l=this.getGlobalState().onStepStateChangeHandlerWrappers.get(a);l&&(this.getGlobalState().onFlowStateChangeHandlers=this.getGlobalState().onFlowStateChangeHandlers.filter(p=>p!==l))},e.set(i.id,d)}),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 c(this,null,function*(){this.isStarted||this.isCompleted||(this.optimisticallyMarkFlowStarted(),yield this.sendFlowStateToAPI(K,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(B,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(q)})}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){var r,d;if(this.getGlobalState().variables[this.id]&&JSON.stringify(this.getGlobalState().variables[this.id])!==JSON.stringify(t)){this.getGlobalState().variables[this.id]=t,this.reload();return}let e=o=>{let a=o.match(/\${(.*?)}/g);return a&&a.forEach(l=>{let p=l.replace("${","").replace("}","");if(!t[p]){o=o.replace(l,"");return}o=o.replace(l,t[p])}),o};this.title=e((r=this.title)!=null?r:""),this.subtitle=e((d=this.subtitle)!=null?d:"");let i=o=>{o&&Object.keys(o).forEach(a=>{typeof o[a]=="string"?o[a]=e(o[a]):typeof o[a]=="object"?i(o[a]):Array.isArray(o[a])&&o[a].forEach(l=>{i(l)})})};this.steps&&this.steps.forEach(o=>{i(o)}),this.getGlobalState().variables[this.id]=t}getStatefulFlow(){return this.getGlobalState().flowStates[this.id]}optimisticallyMarkFlowCompleted(){let t=y(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=y(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 o;let r=new Date;this.getGlobalState().lastFlowSyncDate[this.id]=r,this.getGlobalState().pendingRequests[this.id]=((o=this.getGlobalState().pendingRequests[this.id])!=null?o:0)+1;let d=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:T(this.getGlobalState())})});this.getGlobalState().pendingRequests[this.id]-=1,!(r<this.getGlobalState().lastFlowSyncDate[this.id]||this.getGlobalState().pendingRequests[this.id]>0)&&(yield this.getGlobalState().refreshStateFromAPI(d))})}optimisticallyMarkFlowSkipped(){let t=y(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(d=>{d(this,r),this.getGlobalState().previousFlows.set(this.id,v(this))}),t==null||t(i)})}unregister(){this.getGlobalState().collections&&this.getGlobalState().collections.unregister(this.id)}};var z="0.7.12";var W="NOT_STARTED_STEP",G="COMPLETED_FLOW",B="SKIPPED_FLOW",K="STARTED_FLOW",q="NOT_STARTED_FLOW",j="COMPLETED_STEP",J="SKIPPED_STEP",R="STARTED_STEP",X="frigade-guest-key",x="guest_",dt="get-cache-",D="fr-js-",Q="Redundant call to Frigade API removed";function v(n){return new m({config:n.config,id:n.id})}function y(n){return JSON.parse(JSON.stringify(n))}function H(n){var s,t;return{headers:{Authorization:`Bearer ${n.apiKey}`,"Content-Type":"application/json","x-frigade-sdk-version":(s=n.__platformVersion)!=null?s:z,"x-frigade-sdk-platform":(t=n.__platformName)!=null?t:"Javascript"}}}function gt(n){return C()?window.localStorage.getItem(`${D}${n}`):null}function pt(n,s){C()&&window.localStorage.setItem(`${D}${n}`,s)}function Z(){Object.keys(u).forEach(n=>{n.startsWith(dt)&&delete u[n]})}function tt(){C()&&Object.keys(window.localStorage).forEach(n=>{n.startsWith(D)&&window.localStorage.removeItem(n)})}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=[]}},A=new _;function U(n,s,t=!1){return c(this,null,function*(){var d;if(typeof globalThis.fetch!="function")return w("- Attempted to call fetch() in an environment that doesn't support it.");let e=`${n}${JSON.stringify((d=s.body)!=null?d:{})}`,i,r=C()&&s&&s.body&&s.method==="POST";if(r&&!t){let o=A.hasIdenticalRecentCall(e);o!=null&&o.response!=null&&(i=(yield o.response).clone())}if(!i)try{t&&A.cancelAllPendingRequests();let o=fetch(n,s);r&&A.push(e,o.then(a=>a.clone()).catch(()=>w())),i=yield o,r&&!A.hasCall(e)&&(i=w(Q))}catch(o){return w(o)}if(!i)return w("Received an empty response");if(i.status>=400)return w(i.statusText);try{if(i.status===204)return w();let o;try{o=yield i.json()}catch(a){return w()}return o.error?w(o.error):o}catch(o){return w(o)}})}function w(n){return n&&(n===Q?console.debug(n):console.warn("Call to Frigade failed:",n)),{json:()=>({}),clone:()=>({})}}function V(){if(C()){let n=gt(X);return n||(n=`${x}${Y()}`,pt(X,n)),n}else return`${x}${Y()}`}function C(){return typeof window!="undefined"&&typeof window.document!="undefined"&&typeof window.localStorage!="undefined"}function T(n){let s={registeredCollectionIds:Array.from(n.registeredCollectionIds)};return C()?S({url:n.currentUrl,userAgent:navigator.userAgent},s):s}var O=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 d=e.get(i);if(r.flows.length!==d.flows.length){this.hasChanges=!0;break}for(let o=0;o<r.flows.length;o++)if(r.flows[o].flowId!==d.flows[o].flowId||r.flows[o].visible!==d.flows[o].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:d})=>d).filter(d=>d!==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 $=class extends I{constructor(t,e){super(S({apiKey:t},e));this.flows=[];this.hasFailed=!1;this.visibilityChangeHandler=()=>c(this,null,function*(){document.visibilityState==="visible"&&(yield this.refreshStateFromAPI())});this.init(this.config),C()&&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(r){}})))}getConfig(){return this.config}destroy(){if(C()){document.removeEventListener("visibilitychange",this.visibilityChangeHandler);let t=P(this.config);u[t]&&(u[t].onFlowStateChangeHandlers=[])}}init(t){return c(this,null,function*(){if(this.updateConfig(S(S({},this.config),t)),!(!this.config.userId&&this.config.generateGuestId===!1))return this.initPromise=(()=>c(this,null,function*(){var e;this.config.__readOnly||(e=this.config.userId)!=null&&e.startsWith(x)||(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*(){yield this.updateConfig(F(S({},this.config),{userId:t})),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(F(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 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*(){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 c(this,null,function*(){return yield this.initIfNeeded(),this.getFlowSync(t)})}getFlowSync(t){return this.flows.find(e=>e.id==t)}getFlows(){return c(this,null,function*(){return yield this.initIfNeeded(),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(r=>c(this,null,function*(){return F(S({},r),{flow:yield this.getFlow(r.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*(){tt(),Z(),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,v(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(!u[e]){let i=this,r={set:function(d,o,a){if(d[o]){let l=d[o],p=a;JSON.stringify(l)!==JSON.stringify(p)&&i.triggerEventHandlers(p,l)}return d[o]=a,!0}};if(u[e]={refreshStateFromAPI:()=>c(this,null,function*(){}),collections:new O(new Map),registeredCollectionIds:new Set,flowStates:new Proxy({},r),onFlowStateChangeHandlerWrappers:new Map,onStepStateChangeHandlerWrappers:new Map,onFlowStateChangeHandlers:[],previousFlows:new Map,variables:{},config:this.config,currentUrl:C()?window.location.href:"",pendingRequests:new Map,lastFlowSyncDate:new Map},this.config.__readOnly&&this.config.__flowStateOverrides){this.mockFlowStates(e);return}u[e].refreshStateFromAPI=(d,o)=>c(this,null,function*(){var p,g;if(this.config.__readOnly)return;let a=d||(yield this.fetch("/v1/public/flowStates",{method:"POST",body:JSON.stringify({userId:this.getGlobalState().config.userId,groupId:this.getGlobalState().config.groupId,context:T(this.getGlobalState())})},o)),l=new Map;(g=(p=a.collections)==null?void 0:p.computedOrder)==null||g.forEach(({allowedComponents:h,collectionId:f,collectionType:b,flowId:E,visible:ot})=>{var N;let k=(N=l.get(f))!=null?N:{allowedComponents:h,collectionType:b,flows:[]};k.flows.push({flowId:E,visible:ot}),l.set(f,k)}),l.size>0&&(u[e].collections.ingestCollectionsData(l),u[e].collections.collectionsHaveChanged()&&this.triggerAllEventHandlers()),a&&a.eligibleFlows?(a.eligibleFlows.forEach(h=>{u[e].flowStates[h.flowSlug]=h,this.flows.find(f=>f.id==h.flowSlug)?this.flows.forEach(f=>{f.id==h.flowSlug&&f.resyncState(h)}):this.flows.push(new m({config:this.config,id:h.flowSlug}))}),this.hasFailed=!1):this.hasFailed=!0})}yield u[e].refreshStateFromAPI(void 0,t)})}mockFlowStates(t){Object.keys(this.config.__flowStateOverrides).forEach(e=>{u[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 m({config:this.config,id:e}))})}updateConfig(t){return c(this,null,function*(){this.config=S(S({},this.config),t),u[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(r=>{let d=this.getGlobalState().previousFlows.get(i.id);i.resyncState(t),r(i,d),this.getGlobalState().previousFlows.set(i.id,v(i))})})})}batchRegister(t){return c(this,null,function*(){let e=t.map(d=>c(this,[d],function*([i,r]){let o=yield this.getFlow(i);return[i,l=>{let p=this.getGlobalState().previousFlows.get(i);(p==null?void 0:p.isVisible)!==l&&this.getGlobalState().onFlowStateChangeHandlers.forEach(g=>{g(o,p),this.getGlobalState().previousFlows.set(i,v(o))}),r==null||r(l)}]}));Promise.all(e).then(i=>{this.getGlobalState().collections.batchRegister(i)})})}};var et=(t=>(t.MANUAL="MANUAL",t.AUTOMATIC="AUTOMATIC",t))(et||{}),it=(e=>(e.DRAFT="DRAFT",e.ACTIVE="ACTIVE",e.ARCHIVED="ARCHIVED",e))(it||{});var st=(g=>(g.ANNOUNCEMENT="ANNOUNCEMENT",g.CHECKLIST="CHECKLIST",g.FORM="FORM",g.TOUR="TOUR",g.SUPPORT="SUPPORT",g.CUSTOM="CUSTOM",g.BANNER="BANNER",g.EMBEDDED_TIP="EMBEDDED_TIP",g.NPS_SURVEY="NPS_SURVEY",g.SURVEY="SURVEY",g.CARD="CARD",g))(st||{});export{m as Flow,it as FlowStatus,st as FlowType,$ as Frigade,et as TriggerType};
|
|
3
3
|
//# sourceMappingURL=index.js.map
|