@frigade/js 1.0.0 → 1.0.2
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/lib/index.d.ts +115 -62
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +1 -1
- package/lib/index.mjs.map +1 -1
- package/package.json +4 -2
package/lib/index.d.ts
CHANGED
|
@@ -1,4 +1,59 @@
|
|
|
1
|
-
interface
|
|
1
|
+
interface FrigadeConfig {
|
|
2
|
+
/**
|
|
3
|
+
* API url to use for all requests. Defaults to https://api.frigade.com
|
|
4
|
+
*/
|
|
5
|
+
apiUrl?: string;
|
|
6
|
+
/**
|
|
7
|
+
* User ID to use for all requests. Defaults to null.
|
|
8
|
+
*/
|
|
9
|
+
userId?: string;
|
|
10
|
+
/**
|
|
11
|
+
* Organization ID to use for all requests. Defaults to null.
|
|
12
|
+
*/
|
|
13
|
+
organizationId?: string;
|
|
14
|
+
}
|
|
15
|
+
interface InternalConfig {
|
|
16
|
+
apiKey: string;
|
|
17
|
+
userId?: string;
|
|
18
|
+
organizationId?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface FlowDataRaw {
|
|
22
|
+
id: number;
|
|
23
|
+
name: string;
|
|
24
|
+
description: string;
|
|
25
|
+
data: string;
|
|
26
|
+
createdAt: string;
|
|
27
|
+
modifiedAt: string;
|
|
28
|
+
slug: string;
|
|
29
|
+
targetingLogic: string;
|
|
30
|
+
type: FlowType;
|
|
31
|
+
triggerType: TriggerType;
|
|
32
|
+
status: FlowStatus;
|
|
33
|
+
version: number;
|
|
34
|
+
active: boolean;
|
|
35
|
+
}
|
|
36
|
+
declare enum FlowType {
|
|
37
|
+
CHECKLIST = "CHECKLIST",
|
|
38
|
+
FORM = "FORM",
|
|
39
|
+
TOUR = "TOUR",
|
|
40
|
+
SUPPORT = "SUPPORT",
|
|
41
|
+
CUSTOM = "CUSTOM",
|
|
42
|
+
BANNER = "BANNER",
|
|
43
|
+
EMBEDDED_TIP = "EMBEDDED_TIP",
|
|
44
|
+
NPS_SURVEY = "NPS_SURVEY"
|
|
45
|
+
}
|
|
46
|
+
declare enum TriggerType {
|
|
47
|
+
MANUAL = "MANUAL",
|
|
48
|
+
AUTOMATIC = "AUTOMATIC"
|
|
49
|
+
}
|
|
50
|
+
declare enum FlowStatus {
|
|
51
|
+
DRAFT = "DRAFT",
|
|
52
|
+
ACTIVE = "ACTIVE",
|
|
53
|
+
ARCHIVED = "ARCHIVED"
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
interface FlowStep {
|
|
2
57
|
/**
|
|
3
58
|
* Unique identifier for the step.
|
|
4
59
|
*/
|
|
@@ -62,7 +117,11 @@ interface FlowStepData {
|
|
|
62
117
|
/**
|
|
63
118
|
* Whether the step has been completed (equivalent to step status === COMPLETED_STEP)
|
|
64
119
|
*/
|
|
65
|
-
|
|
120
|
+
isCompleted: boolean;
|
|
121
|
+
/**
|
|
122
|
+
* Whether the step has been completed (equivalent to step status === COMPLETED_STEP)
|
|
123
|
+
*/
|
|
124
|
+
isStarted: boolean;
|
|
66
125
|
/**
|
|
67
126
|
* Whether the step is blocked (can't be accessed yet) based on `startCriteria`
|
|
68
127
|
*/
|
|
@@ -71,14 +130,6 @@ interface FlowStepData {
|
|
|
71
130
|
* Whether the step is hidden (not shown in the list view) based on `visibilityCriteria`
|
|
72
131
|
*/
|
|
73
132
|
hidden?: boolean;
|
|
74
|
-
/**
|
|
75
|
-
* Handler for when the primary button is clicked.
|
|
76
|
-
*/
|
|
77
|
-
handlePrimaryButtonClick?: () => void;
|
|
78
|
-
/**
|
|
79
|
-
* Handler for when the secondary button is clicked.
|
|
80
|
-
*/
|
|
81
|
-
handleSecondaryButtonClick?: () => void;
|
|
82
133
|
props?: any;
|
|
83
134
|
/**
|
|
84
135
|
* Criteria that needs to be met for the step to complete
|
|
@@ -96,95 +147,97 @@ interface FlowStepData {
|
|
|
96
147
|
* Whether the step is dismissible (for instance, tooltips or other non-essential steps)
|
|
97
148
|
*/
|
|
98
149
|
dismissible?: boolean;
|
|
99
|
-
}
|
|
100
|
-
interface FrigadeConfig {
|
|
101
150
|
/**
|
|
102
|
-
*
|
|
151
|
+
* Any other additional props defined in flow-data.yml
|
|
103
152
|
*/
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
modifiedAt: string;
|
|
114
|
-
slug: string;
|
|
115
|
-
targetingLogic: string;
|
|
116
|
-
type: FlowType;
|
|
117
|
-
triggerType: TriggerType;
|
|
118
|
-
status: FlowStatus;
|
|
119
|
-
version: number;
|
|
120
|
-
active: boolean;
|
|
121
|
-
}
|
|
122
|
-
declare enum FlowType {
|
|
123
|
-
CHECKLIST = "CHECKLIST",
|
|
124
|
-
FORM = "FORM",
|
|
125
|
-
TOUR = "TOUR",
|
|
126
|
-
SUPPORT = "SUPPORT",
|
|
127
|
-
CUSTOM = "CUSTOM",
|
|
128
|
-
BANNER = "BANNER",
|
|
129
|
-
EMBEDDED_TIP = "EMBEDDED_TIP",
|
|
130
|
-
NPS_SURVEY = "NPS_SURVEY"
|
|
131
|
-
}
|
|
132
|
-
declare enum TriggerType {
|
|
133
|
-
MANUAL = "MANUAL",
|
|
134
|
-
AUTOMATIC = "AUTOMATIC"
|
|
135
|
-
}
|
|
136
|
-
declare enum FlowStatus {
|
|
137
|
-
DRAFT = "DRAFT",
|
|
138
|
-
ACTIVE = "ACTIVE",
|
|
139
|
-
ARCHIVED = "ARCHIVED"
|
|
153
|
+
[x: string | number | symbol]: unknown;
|
|
154
|
+
/**
|
|
155
|
+
* Function that marks the step started
|
|
156
|
+
*/
|
|
157
|
+
start: (properties?: Record<string | number, any>) => void;
|
|
158
|
+
/**
|
|
159
|
+
* Function that marks the step completed
|
|
160
|
+
*/
|
|
161
|
+
complete: (properties?: Record<string | number, any>) => void;
|
|
140
162
|
}
|
|
141
163
|
|
|
142
164
|
declare class Flow {
|
|
143
165
|
/**
|
|
144
166
|
* THe Flow ID / slug of the flow
|
|
145
167
|
*/
|
|
146
|
-
|
|
147
|
-
/**
|
|
148
|
-
* The status of the flow
|
|
149
|
-
*/
|
|
150
|
-
readonly status: FlowStatus;
|
|
168
|
+
id: string;
|
|
151
169
|
/**
|
|
152
170
|
* The raw data defined in `flow-data.yml` as a JSON decoded object
|
|
153
171
|
*/
|
|
154
|
-
|
|
172
|
+
flowData: Record<any, any>;
|
|
155
173
|
/**
|
|
156
174
|
* The steps contained in the `data` array in `flow-data.yml`
|
|
157
175
|
*/
|
|
158
|
-
|
|
176
|
+
steps: FlowStep[];
|
|
159
177
|
/**
|
|
160
178
|
* The user-facing title of the flow, if defined at the top level of `flow-data.yml`
|
|
161
179
|
*/
|
|
162
|
-
|
|
180
|
+
title?: string;
|
|
163
181
|
/**
|
|
164
182
|
* The user-facing description of the flow, if defined at the top level of `flow-data.yml`
|
|
165
183
|
*/
|
|
166
|
-
|
|
184
|
+
subtitle?: string;
|
|
167
185
|
/**
|
|
168
186
|
* The metadata of the flow.
|
|
169
187
|
*/
|
|
170
|
-
|
|
171
|
-
|
|
188
|
+
metadata: FlowDataRaw;
|
|
189
|
+
/**
|
|
190
|
+
* Whether the flow is completed or not
|
|
191
|
+
*/
|
|
192
|
+
isCompleted: boolean;
|
|
193
|
+
/**
|
|
194
|
+
* Whether the flow is started or not
|
|
195
|
+
*/
|
|
196
|
+
isStarted: boolean;
|
|
197
|
+
private flowDataRaw;
|
|
198
|
+
private internalConfig;
|
|
199
|
+
constructor(internalConfig: InternalConfig, flowDataRaw: FlowDataRaw);
|
|
200
|
+
private initFromRawData;
|
|
201
|
+
/**
|
|
202
|
+
* Function that marks the flow started
|
|
203
|
+
*/
|
|
204
|
+
start(properties?: Record<string | number, any>): Promise<void>;
|
|
205
|
+
/**
|
|
206
|
+
* Function that marks the flow completed
|
|
207
|
+
*/
|
|
208
|
+
complete(properties?: Record<string | number, any>): Promise<void>;
|
|
209
|
+
/**
|
|
210
|
+
* Function that restarts the flow/marks it not started
|
|
211
|
+
*/
|
|
212
|
+
restart(): Promise<void>;
|
|
213
|
+
/**
|
|
214
|
+
* Function that gets current step index
|
|
215
|
+
*/
|
|
216
|
+
getCurrentStepIndex(): number;
|
|
217
|
+
private getUserFlowState;
|
|
218
|
+
private refreshUserFlowState;
|
|
172
219
|
}
|
|
173
220
|
|
|
174
221
|
declare class Frigade {
|
|
175
222
|
private apiKey?;
|
|
176
|
-
private userId
|
|
223
|
+
private userId;
|
|
177
224
|
private organizationId?;
|
|
178
225
|
private config?;
|
|
179
226
|
private hasInitialized;
|
|
227
|
+
private internalConfig?;
|
|
180
228
|
private flows;
|
|
181
229
|
init(apiKey: string, config?: FrigadeConfig): Promise<void>;
|
|
182
230
|
identify(userId: string, properties?: Record<string, any>): Promise<void>;
|
|
183
231
|
group(organizationId: string, properties?: Record<string, any>): Promise<void>;
|
|
184
232
|
track(event: string, properties?: Record<string, any>): Promise<void>;
|
|
185
233
|
getFlow(flowId: string): Promise<Flow>;
|
|
234
|
+
getFlows(): Promise<Flow[]>;
|
|
235
|
+
reset(): Promise<void>;
|
|
186
236
|
private errorOnUninitialized;
|
|
237
|
+
private refreshUserFlowStates;
|
|
187
238
|
private refreshFlows;
|
|
239
|
+
private refreshInternalConfig;
|
|
188
240
|
}
|
|
241
|
+
declare const frigade: Frigade;
|
|
189
242
|
|
|
190
|
-
export { Flow,
|
|
243
|
+
export { Flow, frigade as default };
|
package/lib/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
var
|
|
2
|
+
var A=Object.create;var h=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var v=Object.getPrototypeOf,z=Object.prototype.hasOwnProperty;var K=(i,t)=>{for(var e in t)h(i,e,{get:t[e],enumerable:!0})},O=(i,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of x(t))!z.call(i,a)&&a!==e&&h(i,a,{get:()=>t[a],enumerable:!(r=L(t,a))||r.enumerable});return i};var N=(i,t,e)=>(e=i!=null?A(v(i)):{},O(t||!i||!i.__esModule?h(e,"default",{value:i,enumerable:!0}):e,i)),G=i=>O(h({},"__esModule",{value:!0}),i);var V={};K(V,{Flow:()=>d,default:()=>j});module.exports=G(V);var D="1.0.2 ";var b=N(require("cross-fetch")),R=require("uuid");var T="COMPLETED_FLOW";var I="STARTED_FLOW",U="NOT_STARTED_FLOW",S="COMPLETED_STEP",g="STARTED_STEP",W="frigade-last-call-at-",J="frigade-last-call-data-",C="frigade-guest-key",M="guest_";function $(i){return{config:{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Frigade-SDK-Version":D,"X-Frigade-SDK-Platform":"Javascript"}}}}function y(i){return window&&window.localStorage?window.localStorage.getItem(i):null}function E(i,t){window&&window.localStorage&&window.localStorage.setItem(i,t)}function _(){window&&window.localStorage&&Object.keys(window.localStorage).forEach(i=>{i.startsWith("frigade-")&&window.localStorage.removeItem(i)})}async function k(i,t){let e=W+i,r=J+i;if(window&&window.localStorage&&t&&t.body&&t.method==="POST"){let s=y(e),w=y(r);if(s&&w&&w==t.body){let n=new Date(s);if(new Date().getTime()-n.getTime()<1e3)return u()}E(e,new Date().toISOString()),E(r,t.body)}let a;try{a=await(0,b.default)(i,t)}catch(s){return u(s)}return a?a.staus>=400?u(a.statusText):a.json():u()}function u(i){return i&&console.log("Call to Frigade failed",i),{json:()=>({})}}function F(){if(window&&window.localStorage){let i=y(C);return i||(i=`${M}${(0,R.v4)()}`,window.localStorage.setItem(C,i)),i}}function o(i,t,e){return k(`//api.frigade.com/v1/public${t}`,{...e??{},...$(i).config})}var l={};function p(i){return`${i.apiKey}:${i.userId??""}:${i.organizationId??""}`}var d=class{constructor(t,e){this.internalConfig=t,this.flowDataRaw=e,this.initFromRawData(e)}initFromRawData(t){let e=JSON.parse(t.data),r=e.data;this.id=t.slug,this.metadata=t,this.flowData=e,this.title=this.flowData.title,this.subtitle=this.flowData.subtitle;let a=this.getUserFlowState();this.isCompleted=a.flowState==T,this.isStarted=a.flowState==I,this.steps=[...r.map(s=>{let w=a.stepStates[s.id],n={...s,isCompleted:w.actionType==S,isStarted:w.actionType==g};return n.start=async c=>{n.isCompleted=!0,await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:s.id,data:c??{},createdAt:new Date().toISOString(),actionType:g})}),await this.refreshUserFlowState();let f=this.getUserFlowState();n.isCompleted=f.stepStates[s.id].actionType==S,n.isStarted=f.stepStates[s.id].actionType==g},n.complete=async c=>{n.isCompleted=!0,await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:s.id,data:c??{},createdAt:new Date().toISOString(),actionType:S})}),await this.refreshUserFlowState();let f=this.getUserFlowState();n.isCompleted=f.stepStates[s.id].actionType==S,n.isStarted=f.stepStates[s.id].actionType==g},n})]}async start(t){let e=this.getCurrentStepIndex(),r=e!=-1?this.steps[e].id:"unknown";await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:r,data:t??{},createdAt:new Date().toISOString(),actionType:I})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async complete(t){let e=this.getCurrentStepIndex(),r=e!=-1?this.steps[e].id:"unknown";await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:r,data:t??{},createdAt:new Date().toISOString(),actionType:T})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async restart(){await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:"unknown",data:{},createdAt:new Date().toISOString(),actionType:U})})}getCurrentStepIndex(){let t=this.getUserFlowState();if(!t)return 0;let e=t.lastStepId,r=this.steps.findIndex(a=>a.id===e);return r==-1?0:r}getUserFlowState(){return l[p(this.internalConfig)].userFlowStates[this.id]}async refreshUserFlowState(){await l[p(this.internalConfig)].refreshUserFlowStates()}};var m=class{constructor(){this.userId=F();this.hasInitialized=!1;this.flows=[]}async init(t,e){this.apiKey=t,this.config=e,e!=null&&e.userId&&(this.userId=e.userId),e!=null&&e.organizationId&&(this.organizationId=e.organizationId),this.refreshInternalConfig(),await this.refreshUserFlowStates(),await this.refreshFlows(),this.hasInitialized=!0}async identify(t,e){this.errorOnUninitialized(),this.userId=t,this.refreshInternalConfig(),await o(this.apiKey,"/users",{method:"POST",body:JSON.stringify({foreignId:this.userId,properties:e})}),await this.refreshUserFlowStates()}async group(t,e){this.errorOnUninitialized(),this.organizationId=t,this.refreshInternalConfig(),await o(this.apiKey,"/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.userId,foreignUserGroupId:this.organizationId,properties:e})}),await this.refreshUserFlowStates()}async track(t,e){this.errorOnUninitialized(),await o(this.apiKey,"/track",{method:"POST",body:JSON.stringify({foreignUserId:this.userId,foreignUserGroupId:this.organizationId,event:t,properties:e})})}async getFlow(t){return this.errorOnUninitialized(),this.flows.find(e=>e.id==t)}async getFlows(){return this.errorOnUninitialized(),this.flows}async reset(){_(),this.userId=F(),this.organizationId=void 0}errorOnUninitialized(){if(!this.hasInitialized)throw new Error("Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.")}async refreshUserFlowStates(){let t=p(this.internalConfig);l[t]={refreshUserFlowStates:async()=>{},userFlowStates:{}},l[t].refreshUserFlowStates=async()=>{let e=await o(this.apiKey,`/userFlowStates?foreignUserId=${this.userId}${this.organizationId?`&foreignUserGroupId=${this.organizationId}`:""}`);e&&e.data&&e.data.forEach(a=>{l[t].userFlowStates[a.flowId]=a})},await l[t].refreshUserFlowStates()}async refreshFlows(){this.flows=[];let t=await o(this.apiKey,"/flows");t&&t.data&&t.data.forEach(r=>{this.flows.push(new d(this.internalConfig,r))})}refreshInternalConfig(){this.internalConfig={apiKey:this.apiKey,userId:this.userId,organizationId:this.organizationId}}},B=new m,P=B;var j=P;0&&(module.exports={Flow});
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/core/version.ts","../src/shared/utils.ts","../src/core/flow.ts","../src/core/frigade.ts"],"sourcesContent":["import Frigade from './core/frigade'\nimport Flow from './core/flow'\n\nexport { Flow }\nexport default Frigade\n","export const VERSION_NUMBER = '1.0.0 '\n","import { VERSION_NUMBER } from '../core/version'\n\nexport const NOT_STARTED_STEP = 'NOT_STARTED_STEP'\nexport const COMPLETED_FLOW = 'COMPLETED_FLOW'\nexport const ABORTED_FLOW = 'ABORTED_FLOW'\nexport const STARTED_FLOW = 'STARTED_FLOW'\nexport const NOT_STARTED_FLOW = 'NOT_STARTED_FLOW'\nexport const COMPLETED_STEP = 'COMPLETED_STEP'\nexport const STARTED_STEP = 'STARTED_STEP'\nexport type StepActionType = 'STARTED_STEP' | 'COMPLETED_STEP' | 'NOT_STARTED_STEP'\nexport type UserFlowStatus = 'NOT_STARTED_FLOW' | 'STARTED_FLOW' | 'COMPLETED_FLOW' | 'ABORTED_FLOW'\nconst LAST_POST_CALL_AT = 'frigade-last-call-at-'\nconst LAST_POST_CALL_DATA = 'frigade-last-call-data-'\n\nfunction getConfig(apiKey: string) {\n return {\n config: {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Frigade-SDK-Version': VERSION_NUMBER,\n 'X-Frigade-SDK-Platform': 'Javascript',\n },\n },\n }\n}\n\nfunction getLocalStorage(key: string) {\n if (window && window.localStorage) {\n return window.localStorage.getItem(key)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (window && window.localStorage) {\n window.localStorage.setItem(key, value)\n }\n}\n\nexport async function gracefulFetch(url: string, options: any) {\n const lastCallAtKey = LAST_POST_CALL_AT + url\n const lastCallDataKey = LAST_POST_CALL_DATA + url\n if (window && window.localStorage && options && options.body && options.method === 'POST') {\n const lastCall = getLocalStorage(lastCallAtKey)\n const lastCallData = getLocalStorage(lastCallDataKey)\n if (lastCall && lastCallData && lastCallData == options.body) {\n const lastCallDate = new Date(lastCall)\n const now = new Date()\n const diff = now.getTime() - lastCallDate.getTime()\n // Throttle consecutive POST calls to 1 second\n if (diff < 1000) {\n return getEmptyResponse()\n }\n }\n setLocalStorage(lastCallAtKey, new Date().toISOString())\n setLocalStorage(lastCallDataKey, options.body)\n }\n\n let response\n try {\n response = await fetch(url, options)\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse()\n }\n\n if (!response.ok) {\n return getEmptyResponse(response.statusText)\n }\n\n return response\n}\n\nfunction getEmptyResponse(error?: any) {\n if (error) {\n console.log('Call to Frigade failed', error)\n }\n\n // Create empty response that contains the .json method and returns an empty object\n return {\n json: () => ({}),\n }\n}\n\nexport function fetcher(apiKey: string, url: string, options?: Record<any, any>) {\n return gracefulFetch(getUrl(apiKey, url), {\n ...(options ?? {}),\n ...getConfig(apiKey),\n })\n}\n\nfunction getUrl(apiUrl: string, postfix: string) {\n return `${apiUrl}/public/v1${postfix}`\n}\n","import { FlowStepData } from '../types'\nimport { FlowMetadata, FlowStatus } from './types'\n\nexport default class Flow {\n /**\n * THe Flow ID / slug of the flow\n */\n public readonly id: string\n /**\n * The status of the flow\n */\n public readonly status: FlowStatus\n /**\n * The raw data defined in `flow-data.yml` as a JSON decoded object\n */\n public readonly flowData: Record<any, any>\n /**\n * The steps contained in the `data` array in `flow-data.yml`\n */\n public readonly steps: FlowStepData[]\n /**\n * The user-facing title of the flow, if defined at the top level of `flow-data.yml`\n */\n public readonly title?: string\n /**\n * The user-facing description of the flow, if defined at the top level of `flow-data.yml`\n */\n public readonly subtitle?: string\n /**\n * The metadata of the flow.\n */\n public readonly metadata: FlowMetadata\n\n constructor(\n id: string,\n status: FlowStatus,\n rawData: Record<any, any>,\n steps: FlowStepData[],\n title?: string,\n subtitle?: string\n ) {\n this.id = id\n this.status = status\n this.flowData = rawData\n this.steps = steps\n this.title = title\n this.subtitle = subtitle\n }\n}\n","import { FrigadeConfig } from '../types'\nimport { fetcher } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowMetadata } from './types'\n\nexport default class Frigade {\n private apiKey?: string\n private userId?: string\n private organizationId?: string\n private config?: FrigadeConfig\n private hasInitialized = false\n\n private flows: Flow[] = []\n\n public async init(apiKey: string, config?: FrigadeConfig): Promise<void> {\n this.apiKey = apiKey\n this.config = config\n await this.refreshFlows()\n this.hasInitialized = true\n return Promise.any(null)\n }\n\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.userId = userId\n await fetcher(this.apiKey, '/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.userId,\n properties,\n }),\n })\n }\n\n public async group(organizationId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.organizationId = organizationId\n await fetcher(this.apiKey, '/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n properties,\n }),\n })\n }\n\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n await fetcher(this.apiKey, '/track', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n event,\n properties,\n }),\n })\n }\n\n public async getFlow(flowId: string) {\n this.errorOnUninitialized()\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n private errorOnUninitialized() {\n if (!this.hasInitialized) {\n throw new Error(\n 'Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.'\n )\n }\n }\n\n private async refreshFlows() {\n this.flows = []\n const flowDataRaw = await fetcher(this.apiKey, '/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowMetadatas = flowDataRaw.data as FlowMetadata[]\n flowMetadatas.forEach((flowMetadata) => {\n const rawData = JSON.parse(flowMetadata.data)\n this.flows.push(\n new Flow(\n flowMetadata.slug,\n flowMetadata.status,\n rawData,\n rawData?.data ?? [],\n rawData?.title,\n rawData?.subtitle\n )\n )\n })\n }\n }\n}\n"],"mappings":";4ZAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GCAO,IAAMK,EAAiB,SCW9B,IAAMC,EAAoB,wBACpBC,EAAsB,0BAE5B,SAASC,EAAUC,EAAgB,CACjC,MAAO,CACL,OAAQ,CACN,QAAS,CACP,cAAe,UAAUA,IACzB,eAAgB,mBAChB,wBAAyBC,EACzB,yBAA0B,YAC5B,CACF,CACF,CACF,CAEA,SAASC,EAAgBC,EAAa,CACpC,OAAI,QAAU,OAAO,aACZ,OAAO,aAAa,QAAQA,CAAG,EAEjC,IACT,CAEA,SAASC,EAAgBD,EAAaE,EAAe,CAC/C,QAAU,OAAO,cACnB,OAAO,aAAa,QAAQF,EAAKE,CAAK,CAE1C,CAEA,eAAsBC,EAAcC,EAAaC,EAAc,CAC7D,IAAMC,EAAgBZ,EAAoBU,EACpCG,EAAkBZ,EAAsBS,EAC9C,GAAI,QAAU,OAAO,cAAgBC,GAAWA,EAAQ,MAAQA,EAAQ,SAAW,OAAQ,CACzF,IAAMG,EAAWT,EAAgBO,CAAa,EACxCG,EAAeV,EAAgBQ,CAAe,EACpD,GAAIC,GAAYC,GAAgBA,GAAgBJ,EAAQ,KAAM,CAC5D,IAAMK,EAAe,IAAI,KAAKF,CAAQ,EAItC,GAHY,IAAI,KAAK,EACJ,QAAQ,EAAIE,EAAa,QAAQ,EAEvC,IACT,OAAOC,EAAiB,EAG5BV,EAAgBK,EAAe,IAAI,KAAK,EAAE,YAAY,CAAC,EACvDL,EAAgBM,EAAiBF,EAAQ,IAAI,EAG/C,IAAIO,EACJ,GAA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ACtB,MAAMD,EAAQ,KAAK,OAAQ,cAAe,CACxC,OAAQ,OACR,KAAM,KAAK,UAAU,CACnB,cAAe,KAAK,OACpB,mBAAoB,KAAK,eACzB,WAAAD,CACF,CAAC,CACH,CAAC,CACH,CAEA,MAAa,MAAMG,EAAeH,EAAiD,CACjF,KAAK,qBAAqB,EAC1B,MAAMC,EAAQ,KAAK,OAAQ,SAAU,CACnC,OAAQ,OACR,KAAM,KAAK,UAAU,CACnB,cAAe,KAAK,OACpB,mBAAoB,KAAK,eACzB,MAAAE,EACA,WAAAH,CACF,CAAC,CACH,CAAC,CACH,CAEA,MAAa,QAAQI,EAAgB,CACnC,YAAK,qBAAqB,EACnB,KAAK,MAAM,KAAMC,GAASA,EAAK,IAAMD,CAAM,CACpD,CAEQ,sBAAuB,CAC7B,GAAI,CAAC,KAAK,eACR,MAAM,IAAI,MACR,kGACF,CAEJ,CAEA,MAAc,cAAe,CAC3B,KAAK,MAAQ,CAAC,EACd,IAAME,EAAc,MAAML,EAAQ,KAAK,OAAQ,QAAQ,EACnDK,GAAeA,EAAY,MACTA,EAAY,KAClB,QAASC,GAAiB,CACtC,IAAMC,EAAU,KAAK,MAAMD,EAAa,IAAI,EAC5C,KAAK,MAAM,KACT,IAAIE,EACFF,EAAa,KACbA,EAAa,OACbC,GACAA,GAAA,YAAAA,EAAS,OAAQ,CAAC,EAClBA,GAAA,YAAAA,EAAS,MACTA,GAAA,YAAAA,EAAS,QACX,CACF,CACF,CAAC,CAEL,CACF,EJzFA,IAAOE,EAAQC","names":["src_exports","__export","Flow","src_default","__toCommonJS","VERSION_NUMBER","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","getConfig","apiKey","VERSION_NUMBER","getLocalStorage","key","setLocalStorage","value","gracefulFetch","url","options","lastCallAtKey","lastCallDataKey","lastCall","lastCallData","lastCallDate","getEmptyResponse","response","error","fetcher","getUrl","apiUrl","postfix","Flow","id","status","rawData","steps","title","subtitle","Frigade","apiKey","config","userId","properties","fetcher","organizationId","event","flowId","flow","flowDataRaw","flowMetadata","rawData","Flow","src_default","Frigade"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/core/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/core/flow.ts","../src/core/frigade.ts"],"sourcesContent":["import frigade from './core/frigade'\nimport Flow from './core/flow'\n\nexport { Flow }\n\nexport default frigade\n","export const VERSION_NUMBER = '1.0.2 '\n","import { VERSION_NUMBER } from '../core/version'\nimport fetch from 'cross-fetch'\nimport { v4 as uuidv4 } from 'uuid'\n\nexport const NOT_STARTED_STEP = 'NOT_STARTED_STEP'\nexport const COMPLETED_FLOW = 'COMPLETED_FLOW'\nexport const ABORTED_FLOW = 'ABORTED_FLOW'\nexport const STARTED_FLOW = 'STARTED_FLOW'\nexport const NOT_STARTED_FLOW = 'NOT_STARTED_FLOW'\nexport const COMPLETED_STEP = 'COMPLETED_STEP'\nexport const STARTED_STEP = 'STARTED_STEP'\nexport type StepActionType = 'STARTED_STEP' | 'COMPLETED_STEP' | 'NOT_STARTED_STEP'\nexport type UserFlowStatus = 'NOT_STARTED_FLOW' | 'STARTED_FLOW' | 'COMPLETED_FLOW' | 'ABORTED_FLOW'\nconst LAST_POST_CALL_AT = 'frigade-last-call-at-'\nconst LAST_POST_CALL_DATA = 'frigade-last-call-data-'\nconst GUEST_KEY = 'frigade-guest-key'\nconst GUEST_PREFIX = 'guest_'\n\nfunction getConfig(apiKey: string) {\n return {\n config: {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Frigade-SDK-Version': VERSION_NUMBER,\n 'X-Frigade-SDK-Platform': 'Javascript',\n },\n },\n }\n}\n\nfunction getLocalStorage(key: string) {\n if (window && window.localStorage) {\n return window.localStorage.getItem(key)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (window && window.localStorage) {\n window.localStorage.setItem(key, value)\n }\n}\n\nexport function resetAllLocalStorage() {\n if (window && window.localStorage) {\n // Clear all local storage items that begin with `frigade-`\n Object.keys(window.localStorage).forEach((key) => {\n if (key.startsWith('frigade-')) {\n window.localStorage.removeItem(key)\n }\n })\n }\n}\n\nexport async function gracefulFetch(url: string, options: any) {\n const lastCallAtKey = LAST_POST_CALL_AT + url\n const lastCallDataKey = LAST_POST_CALL_DATA + url\n if (window && window.localStorage && options && options.body && options.method === 'POST') {\n const lastCall = getLocalStorage(lastCallAtKey)\n const lastCallData = getLocalStorage(lastCallDataKey)\n if (lastCall && lastCallData && lastCallData == options.body) {\n const lastCallDate = new Date(lastCall)\n const now = new Date()\n const diff = now.getTime() - lastCallDate.getTime()\n // Throttle consecutive POST calls to 1 second\n if (diff < 1000) {\n return getEmptyResponse()\n }\n }\n setLocalStorage(lastCallAtKey, new Date().toISOString())\n setLocalStorage(lastCallDataKey, options.body)\n }\n\n let response\n try {\n response = await fetch(url, options)\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse()\n }\n\n if (response.staus >= 400) {\n return getEmptyResponse(response.statusText)\n }\n\n return response.json()\n}\n\nfunction getEmptyResponse(error?: any) {\n if (error) {\n console.log('Call to Frigade failed', error)\n }\n\n // Create empty response that contains the .json method and returns an empty object\n return {\n json: () => ({}),\n }\n}\n\nexport function generateGuestId() {\n if (window && window.localStorage) {\n let guestId = getLocalStorage(GUEST_KEY)\n if (!guestId) {\n guestId = `${GUEST_PREFIX}${uuidv4()}`\n window.localStorage.setItem(GUEST_KEY, guestId)\n }\n return guestId\n }\n}\n\nexport function fetcher(apiKey: string, path: string, options?: Record<any, any>) {\n return gracefulFetch(`//api.frigade.com/v1/public${path}`, {\n ...(options ?? {}),\n ...getConfig(apiKey).config,\n })\n}\n","import { InternalConfig, UserFlowState } from '../types'\n\nexport interface FrigadeGlobalState {\n refreshUserFlowStates: () => Promise<void>\n userFlowStates: Record<string, UserFlowState>\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: InternalConfig): string {\n return `${internalConfig.apiKey}:${internalConfig.userId ?? ''}:${\n internalConfig.organizationId ?? ''\n }`\n}\n","import { InternalConfig, UserFlowState } from '../types'\nimport { FlowDataRaw } from './types'\nimport {\n COMPLETED_FLOW,\n COMPLETED_STEP,\n fetcher,\n NOT_STARTED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { FlowStep } from './flow-step'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\n\nexport default class Flow {\n /**\n * THe Flow ID / slug of the flow\n */\n public id: string\n /**\n * The raw data defined in `flow-data.yml` as a JSON decoded object\n */\n public flowData: Record<any, any>\n /**\n * The steps contained in the `data` array in `flow-data.yml`\n */\n public steps: FlowStep[]\n /**\n * The user-facing title of the flow, if defined at the top level of `flow-data.yml`\n */\n public title?: string\n /**\n * The user-facing description of the flow, if defined at the top level of `flow-data.yml`\n */\n public subtitle?: string\n /**\n * The metadata of the flow.\n */\n public metadata: FlowDataRaw\n /**\n * Whether the flow is completed or not\n */\n public isCompleted: boolean\n /**\n * Whether the flow is started or not\n */\n public isStarted: boolean\n\n private flowDataRaw: FlowDataRaw\n\n private internalConfig: InternalConfig\n\n constructor(internalConfig: InternalConfig, flowDataRaw: FlowDataRaw) {\n this.internalConfig = internalConfig\n this.flowDataRaw = flowDataRaw\n this.initFromRawData(flowDataRaw)\n }\n\n private initFromRawData(flowDataRaw: FlowDataRaw) {\n const flowDataYml = JSON.parse(flowDataRaw.data)\n const steps = flowDataYml.data\n this.id = flowDataRaw.slug\n this.metadata = flowDataRaw\n this.flowData = flowDataYml\n this.title = this.flowData.title\n this.subtitle = this.flowData.subtitle\n\n const userFlowState = this.getUserFlowState()\n\n this.isCompleted = userFlowState.flowState == COMPLETED_FLOW\n this.isStarted = userFlowState.flowState == STARTED_FLOW\n this.steps = [\n ...steps.map((step) => {\n const userFlowStateStep = userFlowState.stepStates[step.id]\n const stepObj = {\n ...step,\n isCompleted: userFlowStateStep.actionType == COMPLETED_STEP,\n isStarted: userFlowStateStep.actionType == STARTED_STEP,\n } as FlowStep\n\n stepObj.start = async (properties?: Record<string | number, any>) => {\n stepObj.isCompleted = true\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: step.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_STEP,\n }),\n })\n await this.refreshUserFlowState()\n const updatedUserFlowState = this.getUserFlowState()\n stepObj.isCompleted =\n updatedUserFlowState.stepStates[step.id].actionType == COMPLETED_STEP\n stepObj.isStarted = updatedUserFlowState.stepStates[step.id].actionType == STARTED_STEP\n }\n\n stepObj.complete = async (properties?: Record<string | number, any>) => {\n stepObj.isCompleted = true\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: step.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_STEP,\n }),\n })\n await this.refreshUserFlowState()\n const updatedUserFlowState = this.getUserFlowState()\n stepObj.isCompleted =\n updatedUserFlowState.stepStates[step.id].actionType == COMPLETED_STEP\n stepObj.isStarted = updatedUserFlowState.stepStates[step.id].actionType == STARTED_STEP\n }\n\n return stepObj\n }),\n ]\n }\n\n /**\n * Function that marks the flow started\n */\n public async start(properties?: Record<string | number, any>) {\n const currentStepIndex = this.getCurrentStepIndex()\n const currentStepId = currentStepIndex != -1 ? this.steps[currentStepIndex].id : 'unknown'\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: currentStepId,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that marks the flow completed\n */\n public async complete(properties?: Record<string | number, any>) {\n const currentStepIndex = this.getCurrentStepIndex()\n const currentStepId = currentStepIndex != -1 ? this.steps[currentStepIndex].id : 'unknown'\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: currentStepId,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that restarts the flow/marks it not started\n */\n public async restart() {\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: 'unknown',\n data: {},\n createdAt: new Date().toISOString(),\n actionType: NOT_STARTED_FLOW,\n }),\n })\n }\n\n /**\n * Function that gets current step index\n */\n public getCurrentStepIndex(): number {\n // Find the userFlowState with most recent timestamp\n const userFlowState = this.getUserFlowState()\n if (!userFlowState) {\n return 0\n }\n const currentStepId = userFlowState.lastStepId\n const index = this.steps.findIndex((step) => step.id === currentStepId)\n return index == -1 ? 0 : index\n }\n\n private getUserFlowState(): UserFlowState {\n const userFlowStates = frigadeGlobalState[getGlobalStateKey(this.internalConfig)].userFlowStates\n return userFlowStates[this.id]\n }\n\n private async refreshUserFlowState() {\n await frigadeGlobalState[getGlobalStateKey(this.internalConfig)].refreshUserFlowStates()\n }\n}\n","import { FrigadeConfig, InternalConfig, UserFlowState } from '../types'\nimport { fetcher, generateGuestId, resetAllLocalStorage } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowDataRaw } from './types'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\n\nexport class Frigade {\n private apiKey?: string\n private userId: string = generateGuestId()\n private organizationId?: string\n private config?: FrigadeConfig\n private hasInitialized = false\n private internalConfig?: InternalConfig\n\n private flows: Flow[] = []\n\n public async init(apiKey: string, config?: FrigadeConfig): Promise<void> {\n this.apiKey = apiKey\n this.config = config\n if (config?.userId) {\n this.userId = config.userId\n }\n if (config?.organizationId) {\n this.organizationId = config.organizationId\n }\n this.refreshInternalConfig()\n await this.refreshUserFlowStates()\n await this.refreshFlows()\n this.hasInitialized = true\n }\n\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.userId = userId\n this.refreshInternalConfig()\n await fetcher(this.apiKey, '/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.userId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async group(organizationId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.organizationId = organizationId\n this.refreshInternalConfig()\n await fetcher(this.apiKey, '/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n await fetcher(this.apiKey, '/track', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n event,\n properties,\n }),\n })\n }\n\n public async getFlow(flowId: string) {\n this.errorOnUninitialized()\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n public async getFlows() {\n this.errorOnUninitialized()\n return this.flows\n }\n\n public async reset() {\n resetAllLocalStorage()\n this.userId = generateGuestId()\n this.organizationId = undefined\n }\n\n private errorOnUninitialized() {\n if (!this.hasInitialized) {\n throw new Error(\n 'Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.'\n )\n }\n }\n\n private async refreshUserFlowStates(): Promise<void> {\n const globalStateKey = getGlobalStateKey(this.internalConfig)\n frigadeGlobalState[globalStateKey] = {\n refreshUserFlowStates: async () => {},\n userFlowStates: {},\n }\n frigadeGlobalState[globalStateKey].refreshUserFlowStates = async () => {\n const userFlowStatesRaw = await fetcher(\n this.apiKey,\n `/userFlowStates?foreignUserId=${this.userId}${\n this.organizationId ? `&foreignUserGroupId=${this.organizationId}` : ''\n }`\n )\n if (userFlowStatesRaw && userFlowStatesRaw.data) {\n let userFlowStates = userFlowStatesRaw.data as UserFlowState[]\n userFlowStates.forEach((userFlowState) => {\n frigadeGlobalState[globalStateKey].userFlowStates[userFlowState.flowId] = userFlowState\n })\n }\n }\n await frigadeGlobalState[globalStateKey].refreshUserFlowStates()\n }\n\n private async refreshFlows() {\n this.flows = []\n const flowDataRaw = await fetcher(this.apiKey, '/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowDatas = flowDataRaw.data as FlowDataRaw[]\n flowDatas.forEach((flowData) => {\n this.flows.push(new Flow(this.internalConfig, flowData))\n })\n }\n }\n\n private refreshInternalConfig() {\n this.internalConfig = {\n apiKey: this.apiKey,\n userId: this.userId,\n organizationId: this.organizationId,\n }\n }\n}\n\nconst frigade = new Frigade()\nexport default frigade\n"],"mappings":";6iBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,UAAAE,EAAA,YAAAC,IAAA,eAAAC,EAAAJ,GCAO,IAAMK,EAAiB,SCC9B,IAAAC,EAAkB,0BAClBC,EAA6B,gBAGtB,IAAMC,EAAiB,iBAEvB,IAAMC,EAAe,eACfC,EAAmB,mBACnBC,EAAiB,iBACjBC,EAAe,eAGtBC,EAAoB,wBACpBC,EAAsB,0BACtBC,EAAY,oBACZC,EAAe,SAErB,SAASC,EAAUC,EAAgB,CACjC,MAAO,CACL,OAAQ,CACN,QAAS,CACP,cAAe,UAAUA,IACzB,eAAgB,mBAChB,wBAAyBC,EACzB,yBAA0B,YAC5B,CACF,CACF,CACF,CAEA,SAASC,EAAgBC,EAAa,CACpC,OAAI,QAAU,OAAO,aACZ,OAAO,aAAa,QAAQA,CAAG,EAEjC,IACT,CAEA,SAASC,EAAgBD,EAAaE,EAAe,CAC/C,QAAU,OAAO,cACnB,OAAO,aAAa,QAAQF,EAAKE,CAAK,CAE1C,CAEO,SAASC,GAA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nC,sBAAuB,SAAY,CAAC,EACpC,eAAgB,CAAC,CACnB,EACAE,EAAmBF,CAAc,EAAE,sBAAwB,SAAY,CACrE,IAAMG,EAAoB,MAAMT,EAC9B,KAAK,OACL,iCAAiC,KAAK,SACpC,KAAK,eAAiB,uBAAuB,KAAK,iBAAmB,IAEzE,EACIS,GAAqBA,EAAkB,MACpBA,EAAkB,KACxB,QAASC,GAAkB,CACxCF,EAAmBF,CAAc,EAAE,eAAeI,EAAc,MAAM,EAAIA,CAC5E,CAAC,CAEL,EACA,MAAMF,EAAmBF,CAAc,EAAE,sBAAsB,CACjE,CAEA,MAAc,cAAe,CAC3B,KAAK,MAAQ,CAAC,EACd,IAAMK,EAAc,MAAMX,EAAQ,KAAK,OAAQ,QAAQ,EACnDW,GAAeA,EAAY,MACbA,EAAY,KAClB,QAASC,GAAa,CAC9B,KAAK,MAAM,KAAK,IAAIC,EAAK,KAAK,eAAgBD,CAAQ,CAAC,CACzD,CAAC,CAEL,CAEQ,uBAAwB,CAC9B,KAAK,eAAiB,CACpB,OAAQ,KAAK,OACb,OAAQ,KAAK,OACb,eAAgB,KAAK,cACvB,CACF,CACF,EAEME,EAAU,IAAIpB,EACbqB,EAAQD,ELxIf,IAAOE,EAAQC","names":["src_exports","__export","Flow","src_default","__toCommonJS","VERSION_NUMBER","import_cross_fetch","import_uuid","COMPLETED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","GUEST_KEY","GUEST_PREFIX","getConfig","apiKey","VERSION_NUMBER","getLocalStorage","key","setLocalStorage","value","resetAllLocalStorage","gracefulFetch","url","options","lastCallAtKey","lastCallDataKey","lastCall","lastCallData","lastCallDate","getEmptyResponse","response","fetch","error","generateGuestId","guestId","uuidv4","fetcher","path","frigadeGlobalState","getGlobalStateKey","internalConfig","Flow","internalConfig","flowDataRaw","flowDataYml","steps","userFlowState","COMPLETED_FLOW","STARTED_FLOW","step","userFlowStateStep","stepObj","COMPLETED_STEP","STARTED_STEP","properties","fetcher","updatedUserFlowState","currentStepIndex","currentStepId","NOT_STARTED_FLOW","index","frigadeGlobalState","getGlobalStateKey","Frigade","generateGuestId","apiKey","config","userId","properties","fetcher","organizationId","event","flowId","flow","resetAllLocalStorage","globalStateKey","getGlobalStateKey","frigadeGlobalState","userFlowStatesRaw","userFlowState","flowDataRaw","flowData","Flow","frigade","frigade_default","src_default","frigade_default"]}
|
package/lib/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
var
|
|
2
|
+
var m="1.0.2 ";import R from"cross-fetch";import{v4 as U}from"uuid";var y="COMPLETED_FLOW";var T="STARTED_FLOW",C="NOT_STARTED_FLOW",S="COMPLETED_STEP",g="STARTED_STEP",_="frigade-last-call-at-",P="frigade-last-call-data-",O="frigade-guest-key",A="guest_";function L(i){return{config:{headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Frigade-SDK-Version":m,"X-Frigade-SDK-Platform":"Javascript"}}}}function u(i){return window&&window.localStorage?window.localStorage.getItem(i):null}function D(i,t){window&&window.localStorage&&window.localStorage.setItem(i,t)}function E(){window&&window.localStorage&&Object.keys(window.localStorage).forEach(i=>{i.startsWith("frigade-")&&window.localStorage.removeItem(i)})}async function x(i,t){let e=_+i,a=P+i;if(window&&window.localStorage&&t&&t.body&&t.method==="POST"){let s=u(e),w=u(a);if(s&&w&&w==t.body){let n=new Date(s);if(new Date().getTime()-n.getTime()<1e3)return h()}D(e,new Date().toISOString()),D(a,t.body)}let r;try{r=await R(i,t)}catch(s){return h(s)}return r?r.staus>=400?h(r.statusText):r.json():h()}function h(i){return i&&console.log("Call to Frigade failed",i),{json:()=>({})}}function I(){if(window&&window.localStorage){let i=u(O);return i||(i=`${A}${U()}`,window.localStorage.setItem(O,i)),i}}function o(i,t,e){return x(`//api.frigade.com/v1/public${t}`,{...e??{},...L(i).config})}var l={};function p(i){return`${i.apiKey}:${i.userId??""}:${i.organizationId??""}`}var f=class{constructor(t,e){this.internalConfig=t,this.flowDataRaw=e,this.initFromRawData(e)}initFromRawData(t){let e=JSON.parse(t.data),a=e.data;this.id=t.slug,this.metadata=t,this.flowData=e,this.title=this.flowData.title,this.subtitle=this.flowData.subtitle;let r=this.getUserFlowState();this.isCompleted=r.flowState==y,this.isStarted=r.flowState==T,this.steps=[...a.map(s=>{let w=r.stepStates[s.id],n={...s,isCompleted:w.actionType==S,isStarted:w.actionType==g};return n.start=async c=>{n.isCompleted=!0,await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:s.id,data:c??{},createdAt:new Date().toISOString(),actionType:g})}),await this.refreshUserFlowState();let d=this.getUserFlowState();n.isCompleted=d.stepStates[s.id].actionType==S,n.isStarted=d.stepStates[s.id].actionType==g},n.complete=async c=>{n.isCompleted=!0,await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:s.id,data:c??{},createdAt:new Date().toISOString(),actionType:S})}),await this.refreshUserFlowState();let d=this.getUserFlowState();n.isCompleted=d.stepStates[s.id].actionType==S,n.isStarted=d.stepStates[s.id].actionType==g},n})]}async start(t){let e=this.getCurrentStepIndex(),a=e!=-1?this.steps[e].id:"unknown";await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:a,data:t??{},createdAt:new Date().toISOString(),actionType:T})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async complete(t){let e=this.getCurrentStepIndex(),a=e!=-1?this.steps[e].id:"unknown";await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:a,data:t??{},createdAt:new Date().toISOString(),actionType:y})}),await this.refreshUserFlowState(),this.initFromRawData(this.flowDataRaw)}async restart(){await o(this.internalConfig.apiKey,"/flowResponses",{method:"POST",body:JSON.stringify({foreignUserId:this.internalConfig.userId,flowSlug:this.id,stepId:"unknown",data:{},createdAt:new Date().toISOString(),actionType:C})})}getCurrentStepIndex(){let t=this.getUserFlowState();if(!t)return 0;let e=t.lastStepId,a=this.steps.findIndex(r=>r.id===e);return a==-1?0:a}getUserFlowState(){return l[p(this.internalConfig)].userFlowStates[this.id]}async refreshUserFlowState(){await l[p(this.internalConfig)].refreshUserFlowStates()}};var F=class{constructor(){this.userId=I();this.hasInitialized=!1;this.flows=[]}async init(t,e){this.apiKey=t,this.config=e,e!=null&&e.userId&&(this.userId=e.userId),e!=null&&e.organizationId&&(this.organizationId=e.organizationId),this.refreshInternalConfig(),await this.refreshUserFlowStates(),await this.refreshFlows(),this.hasInitialized=!0}async identify(t,e){this.errorOnUninitialized(),this.userId=t,this.refreshInternalConfig(),await o(this.apiKey,"/users",{method:"POST",body:JSON.stringify({foreignId:this.userId,properties:e})}),await this.refreshUserFlowStates()}async group(t,e){this.errorOnUninitialized(),this.organizationId=t,this.refreshInternalConfig(),await o(this.apiKey,"/userGroups",{method:"POST",body:JSON.stringify({foreignUserId:this.userId,foreignUserGroupId:this.organizationId,properties:e})}),await this.refreshUserFlowStates()}async track(t,e){this.errorOnUninitialized(),await o(this.apiKey,"/track",{method:"POST",body:JSON.stringify({foreignUserId:this.userId,foreignUserGroupId:this.organizationId,event:t,properties:e})})}async getFlow(t){return this.errorOnUninitialized(),this.flows.find(e=>e.id==t)}async getFlows(){return this.errorOnUninitialized(),this.flows}async reset(){E(),this.userId=I(),this.organizationId=void 0}errorOnUninitialized(){if(!this.hasInitialized)throw new Error("Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.")}async refreshUserFlowStates(){let t=p(this.internalConfig);l[t]={refreshUserFlowStates:async()=>{},userFlowStates:{}},l[t].refreshUserFlowStates=async()=>{let e=await o(this.apiKey,`/userFlowStates?foreignUserId=${this.userId}${this.organizationId?`&foreignUserGroupId=${this.organizationId}`:""}`);e&&e.data&&e.data.forEach(r=>{l[t].userFlowStates[r.flowId]=r})},await l[t].refreshUserFlowStates()}async refreshFlows(){this.flows=[];let t=await o(this.apiKey,"/flows");t&&t.data&&t.data.forEach(a=>{this.flows.push(new f(this.internalConfig,a))})}refreshInternalConfig(){this.internalConfig={apiKey:this.apiKey,userId:this.userId,organizationId:this.organizationId}}},v=new F,b=v;var H=b;export{f as Flow,H as default};
|
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
package/lib/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/version.ts","../src/shared/utils.ts","../src/core/flow.ts","../src/core/frigade.ts","../src/index.ts"],"sourcesContent":["export const VERSION_NUMBER = '1.0.0 '\n","import { VERSION_NUMBER } from '../core/version'\n\nexport const NOT_STARTED_STEP = 'NOT_STARTED_STEP'\nexport const COMPLETED_FLOW = 'COMPLETED_FLOW'\nexport const ABORTED_FLOW = 'ABORTED_FLOW'\nexport const STARTED_FLOW = 'STARTED_FLOW'\nexport const NOT_STARTED_FLOW = 'NOT_STARTED_FLOW'\nexport const COMPLETED_STEP = 'COMPLETED_STEP'\nexport const STARTED_STEP = 'STARTED_STEP'\nexport type StepActionType = 'STARTED_STEP' | 'COMPLETED_STEP' | 'NOT_STARTED_STEP'\nexport type UserFlowStatus = 'NOT_STARTED_FLOW' | 'STARTED_FLOW' | 'COMPLETED_FLOW' | 'ABORTED_FLOW'\nconst LAST_POST_CALL_AT = 'frigade-last-call-at-'\nconst LAST_POST_CALL_DATA = 'frigade-last-call-data-'\n\nfunction getConfig(apiKey: string) {\n return {\n config: {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Frigade-SDK-Version': VERSION_NUMBER,\n 'X-Frigade-SDK-Platform': 'Javascript',\n },\n },\n }\n}\n\nfunction getLocalStorage(key: string) {\n if (window && window.localStorage) {\n return window.localStorage.getItem(key)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (window && window.localStorage) {\n window.localStorage.setItem(key, value)\n }\n}\n\nexport async function gracefulFetch(url: string, options: any) {\n const lastCallAtKey = LAST_POST_CALL_AT + url\n const lastCallDataKey = LAST_POST_CALL_DATA + url\n if (window && window.localStorage && options && options.body && options.method === 'POST') {\n const lastCall = getLocalStorage(lastCallAtKey)\n const lastCallData = getLocalStorage(lastCallDataKey)\n if (lastCall && lastCallData && lastCallData == options.body) {\n const lastCallDate = new Date(lastCall)\n const now = new Date()\n const diff = now.getTime() - lastCallDate.getTime()\n // Throttle consecutive POST calls to 1 second\n if (diff < 1000) {\n return getEmptyResponse()\n }\n }\n setLocalStorage(lastCallAtKey, new Date().toISOString())\n setLocalStorage(lastCallDataKey, options.body)\n }\n\n let response\n try {\n response = await fetch(url, options)\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse()\n }\n\n if (!response.ok) {\n return getEmptyResponse(response.statusText)\n }\n\n return response\n}\n\nfunction getEmptyResponse(error?: any) {\n if (error) {\n console.log('Call to Frigade failed', error)\n }\n\n // Create empty response that contains the .json method and returns an empty object\n return {\n json: () => ({}),\n }\n}\n\nexport function fetcher(apiKey: string, url: string, options?: Record<any, any>) {\n return gracefulFetch(getUrl(apiKey, url), {\n ...(options ?? {}),\n ...getConfig(apiKey),\n })\n}\n\nfunction getUrl(apiUrl: string, postfix: string) {\n return `${apiUrl}/public/v1${postfix}`\n}\n","import { FlowStepData } from '../types'\nimport { FlowMetadata, FlowStatus } from './types'\n\nexport default class Flow {\n /**\n * THe Flow ID / slug of the flow\n */\n public readonly id: string\n /**\n * The status of the flow\n */\n public readonly status: FlowStatus\n /**\n * The raw data defined in `flow-data.yml` as a JSON decoded object\n */\n public readonly flowData: Record<any, any>\n /**\n * The steps contained in the `data` array in `flow-data.yml`\n */\n public readonly steps: FlowStepData[]\n /**\n * The user-facing title of the flow, if defined at the top level of `flow-data.yml`\n */\n public readonly title?: string\n /**\n * The user-facing description of the flow, if defined at the top level of `flow-data.yml`\n */\n public readonly subtitle?: string\n /**\n * The metadata of the flow.\n */\n public readonly metadata: FlowMetadata\n\n constructor(\n id: string,\n status: FlowStatus,\n rawData: Record<any, any>,\n steps: FlowStepData[],\n title?: string,\n subtitle?: string\n ) {\n this.id = id\n this.status = status\n this.flowData = rawData\n this.steps = steps\n this.title = title\n this.subtitle = subtitle\n }\n}\n","import { FrigadeConfig } from '../types'\nimport { fetcher } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowMetadata } from './types'\n\nexport default class Frigade {\n private apiKey?: string\n private userId?: string\n private organizationId?: string\n private config?: FrigadeConfig\n private hasInitialized = false\n\n private flows: Flow[] = []\n\n public async init(apiKey: string, config?: FrigadeConfig): Promise<void> {\n this.apiKey = apiKey\n this.config = config\n await this.refreshFlows()\n this.hasInitialized = true\n return Promise.any(null)\n }\n\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.userId = userId\n await fetcher(this.apiKey, '/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.userId,\n properties,\n }),\n })\n }\n\n public async group(organizationId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.organizationId = organizationId\n await fetcher(this.apiKey, '/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n properties,\n }),\n })\n }\n\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n await fetcher(this.apiKey, '/track', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n event,\n properties,\n }),\n })\n }\n\n public async getFlow(flowId: string) {\n this.errorOnUninitialized()\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n private errorOnUninitialized() {\n if (!this.hasInitialized) {\n throw new Error(\n 'Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.'\n )\n }\n }\n\n private async refreshFlows() {\n this.flows = []\n const flowDataRaw = await fetcher(this.apiKey, '/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowMetadatas = flowDataRaw.data as FlowMetadata[]\n flowMetadatas.forEach((flowMetadata) => {\n const rawData = JSON.parse(flowMetadata.data)\n this.flows.push(\n new Flow(\n flowMetadata.slug,\n flowMetadata.status,\n rawData,\n rawData?.data ?? [],\n rawData?.title,\n rawData?.subtitle\n )\n )\n })\n }\n }\n}\n","import Frigade from './core/frigade'\nimport Flow from './core/flow'\n\nexport { Flow }\nexport default Frigade\n"],"mappings":";AAAO,IAAMA,EAAiB,SCW9B,IAAMC,EAAoB,wBACpBC,EAAsB,0BAE5B,SAASC,EAAUC,EAAgB,CACjC,MAAO,CACL,OAAQ,CACN,QAAS,CACP,cAAe,UAAUA,IACzB,eAAgB,mBAChB,wBAAyBC,EACzB,yBAA0B,YAC5B,CACF,CACF,CACF,CAEA,SAASC,EAAgBC,EAAa,CACpC,OAAI,QAAU,OAAO,aACZ,OAAO,aAAa,QAAQA,CAAG,EAEjC,IACT,CAEA,SAASC,EAAgBD,EAAaE,EAAe,CAC/C,QAAU,OAAO,cACnB,OAAO,aAAa,QAAQF,EAAKE,CAAK,CAE1C,CAEA,eAAsBC,EAAcC,EAAaC,EAAc,CAC7D,IAAMC,EAAgBZ,EAAoBU,EACpCG,EAAkBZ,EAAsBS,EAC9C,GAAI,QAAU,OAAO,cAAgBC,GAAWA,EAAQ,MAAQA,EAAQ,SAAW,OAAQ,CACzF,IAAMG,EAAWT,EAAgBO,CAAa,EACxCG,EAAeV,EAAgBQ,CAAe,EACpD,GAAIC,GAAYC,GAAgBA,GAAgBJ,EAAQ,KAAM,CAC5D,IAAMK,EAAe,IAAI,KAAKF,CAAQ,EAItC,GAHY,IAAI,KAAK,EACJ,QAAQ,EAAIE,EAAa,QAAQ,EAEvC,IACT,OAAOC,EAAiB,EAG5BV,EAAgBK,EAAe,IAAI,KAAK,EAAE,YAAY,CAAC,EACvDL,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F,EAAiD,CAC1F,KAAK,qBAAqB,EAC1B,KAAK,eAAiBE,EACtB,MAAMD,EAAQ,KAAK,OAAQ,cAAe,CACxC,OAAQ,OACR,KAAM,KAAK,UAAU,CACnB,cAAe,KAAK,OACpB,mBAAoB,KAAK,eACzB,WAAAD,CACF,CAAC,CACH,CAAC,CACH,CAEA,MAAa,MAAMG,EAAeH,EAAiD,CACjF,KAAK,qBAAqB,EAC1B,MAAMC,EAAQ,KAAK,OAAQ,SAAU,CACnC,OAAQ,OACR,KAAM,KAAK,UAAU,CACnB,cAAe,KAAK,OACpB,mBAAoB,KAAK,eACzB,MAAAE,EACA,WAAAH,CACF,CAAC,CACH,CAAC,CACH,CAEA,MAAa,QAAQI,EAAgB,CACnC,YAAK,qBAAqB,EACnB,KAAK,MAAM,KAAMC,GAASA,EAAK,IAAMD,CAAM,CACpD,CAEQ,sBAAuB,CAC7B,GAAI,CAAC,KAAK,eACR,MAAM,IAAI,MACR,kGACF,CAEJ,CAEA,MAAc,cAAe,CAC3B,KAAK,MAAQ,CAAC,EACd,IAAME,EAAc,MAAML,EAAQ,KAAK,OAAQ,QAAQ,EACnDK,GAAeA,EAAY,MACTA,EAAY,KAClB,QAASC,GAAiB,CACtC,IAAMC,EAAU,KAAK,MAAMD,EAAa,IAAI,EAC5C,KAAK,MAAM,KACT,IAAIE,EACFF,EAAa,KACbA,EAAa,OACbC,GACAA,GAAA,YAAAA,EAAS,OAAQ,CAAC,EAClBA,GAAA,YAAAA,EAAS,MACTA,GAAA,YAAAA,EAAS,QACX,CACF,CACF,CAAC,CAEL,CACF,ECzFA,IAAOE,EAAQC","names":["VERSION_NUMBER","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","getConfig","apiKey","VERSION_NUMBER","getLocalStorage","key","setLocalStorage","value","gracefulFetch","url","options","lastCallAtKey","lastCallDataKey","lastCall","lastCallData","lastCallDate","getEmptyResponse","response","error","fetcher","getUrl","apiUrl","postfix","Flow","id","status","rawData","steps","title","subtitle","Frigade","apiKey","config","userId","properties","fetcher","organizationId","event","flowId","flow","flowDataRaw","flowMetadata","rawData","Flow","src_default","Frigade"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/version.ts","../src/shared/utils.ts","../src/shared/state.ts","../src/core/flow.ts","../src/core/frigade.ts","../src/index.ts"],"sourcesContent":["export const VERSION_NUMBER = '1.0.2 '\n","import { VERSION_NUMBER } from '../core/version'\nimport fetch from 'cross-fetch'\nimport { v4 as uuidv4 } from 'uuid'\n\nexport const NOT_STARTED_STEP = 'NOT_STARTED_STEP'\nexport const COMPLETED_FLOW = 'COMPLETED_FLOW'\nexport const ABORTED_FLOW = 'ABORTED_FLOW'\nexport const STARTED_FLOW = 'STARTED_FLOW'\nexport const NOT_STARTED_FLOW = 'NOT_STARTED_FLOW'\nexport const COMPLETED_STEP = 'COMPLETED_STEP'\nexport const STARTED_STEP = 'STARTED_STEP'\nexport type StepActionType = 'STARTED_STEP' | 'COMPLETED_STEP' | 'NOT_STARTED_STEP'\nexport type UserFlowStatus = 'NOT_STARTED_FLOW' | 'STARTED_FLOW' | 'COMPLETED_FLOW' | 'ABORTED_FLOW'\nconst LAST_POST_CALL_AT = 'frigade-last-call-at-'\nconst LAST_POST_CALL_DATA = 'frigade-last-call-data-'\nconst GUEST_KEY = 'frigade-guest-key'\nconst GUEST_PREFIX = 'guest_'\n\nfunction getConfig(apiKey: string) {\n return {\n config: {\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n 'X-Frigade-SDK-Version': VERSION_NUMBER,\n 'X-Frigade-SDK-Platform': 'Javascript',\n },\n },\n }\n}\n\nfunction getLocalStorage(key: string) {\n if (window && window.localStorage) {\n return window.localStorage.getItem(key)\n }\n return null\n}\n\nfunction setLocalStorage(key: string, value: string) {\n if (window && window.localStorage) {\n window.localStorage.setItem(key, value)\n }\n}\n\nexport function resetAllLocalStorage() {\n if (window && window.localStorage) {\n // Clear all local storage items that begin with `frigade-`\n Object.keys(window.localStorage).forEach((key) => {\n if (key.startsWith('frigade-')) {\n window.localStorage.removeItem(key)\n }\n })\n }\n}\n\nexport async function gracefulFetch(url: string, options: any) {\n const lastCallAtKey = LAST_POST_CALL_AT + url\n const lastCallDataKey = LAST_POST_CALL_DATA + url\n if (window && window.localStorage && options && options.body && options.method === 'POST') {\n const lastCall = getLocalStorage(lastCallAtKey)\n const lastCallData = getLocalStorage(lastCallDataKey)\n if (lastCall && lastCallData && lastCallData == options.body) {\n const lastCallDate = new Date(lastCall)\n const now = new Date()\n const diff = now.getTime() - lastCallDate.getTime()\n // Throttle consecutive POST calls to 1 second\n if (diff < 1000) {\n return getEmptyResponse()\n }\n }\n setLocalStorage(lastCallAtKey, new Date().toISOString())\n setLocalStorage(lastCallDataKey, options.body)\n }\n\n let response\n try {\n response = await fetch(url, options)\n } catch (error) {\n return getEmptyResponse(error)\n }\n\n if (!response) {\n return getEmptyResponse()\n }\n\n if (response.staus >= 400) {\n return getEmptyResponse(response.statusText)\n }\n\n return response.json()\n}\n\nfunction getEmptyResponse(error?: any) {\n if (error) {\n console.log('Call to Frigade failed', error)\n }\n\n // Create empty response that contains the .json method and returns an empty object\n return {\n json: () => ({}),\n }\n}\n\nexport function generateGuestId() {\n if (window && window.localStorage) {\n let guestId = getLocalStorage(GUEST_KEY)\n if (!guestId) {\n guestId = `${GUEST_PREFIX}${uuidv4()}`\n window.localStorage.setItem(GUEST_KEY, guestId)\n }\n return guestId\n }\n}\n\nexport function fetcher(apiKey: string, path: string, options?: Record<any, any>) {\n return gracefulFetch(`//api.frigade.com/v1/public${path}`, {\n ...(options ?? {}),\n ...getConfig(apiKey).config,\n })\n}\n","import { InternalConfig, UserFlowState } from '../types'\n\nexport interface FrigadeGlobalState {\n refreshUserFlowStates: () => Promise<void>\n userFlowStates: Record<string, UserFlowState>\n}\n\nexport let frigadeGlobalState: Record<string, FrigadeGlobalState> = {}\n\nexport function getGlobalStateKey(internalConfig: InternalConfig): string {\n return `${internalConfig.apiKey}:${internalConfig.userId ?? ''}:${\n internalConfig.organizationId ?? ''\n }`\n}\n","import { InternalConfig, UserFlowState } from '../types'\nimport { FlowDataRaw } from './types'\nimport {\n COMPLETED_FLOW,\n COMPLETED_STEP,\n fetcher,\n NOT_STARTED_FLOW,\n STARTED_FLOW,\n STARTED_STEP,\n} from '../shared/utils'\nimport { FlowStep } from './flow-step'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\n\nexport default class Flow {\n /**\n * THe Flow ID / slug of the flow\n */\n public id: string\n /**\n * The raw data defined in `flow-data.yml` as a JSON decoded object\n */\n public flowData: Record<any, any>\n /**\n * The steps contained in the `data` array in `flow-data.yml`\n */\n public steps: FlowStep[]\n /**\n * The user-facing title of the flow, if defined at the top level of `flow-data.yml`\n */\n public title?: string\n /**\n * The user-facing description of the flow, if defined at the top level of `flow-data.yml`\n */\n public subtitle?: string\n /**\n * The metadata of the flow.\n */\n public metadata: FlowDataRaw\n /**\n * Whether the flow is completed or not\n */\n public isCompleted: boolean\n /**\n * Whether the flow is started or not\n */\n public isStarted: boolean\n\n private flowDataRaw: FlowDataRaw\n\n private internalConfig: InternalConfig\n\n constructor(internalConfig: InternalConfig, flowDataRaw: FlowDataRaw) {\n this.internalConfig = internalConfig\n this.flowDataRaw = flowDataRaw\n this.initFromRawData(flowDataRaw)\n }\n\n private initFromRawData(flowDataRaw: FlowDataRaw) {\n const flowDataYml = JSON.parse(flowDataRaw.data)\n const steps = flowDataYml.data\n this.id = flowDataRaw.slug\n this.metadata = flowDataRaw\n this.flowData = flowDataYml\n this.title = this.flowData.title\n this.subtitle = this.flowData.subtitle\n\n const userFlowState = this.getUserFlowState()\n\n this.isCompleted = userFlowState.flowState == COMPLETED_FLOW\n this.isStarted = userFlowState.flowState == STARTED_FLOW\n this.steps = [\n ...steps.map((step) => {\n const userFlowStateStep = userFlowState.stepStates[step.id]\n const stepObj = {\n ...step,\n isCompleted: userFlowStateStep.actionType == COMPLETED_STEP,\n isStarted: userFlowStateStep.actionType == STARTED_STEP,\n } as FlowStep\n\n stepObj.start = async (properties?: Record<string | number, any>) => {\n stepObj.isCompleted = true\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: step.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_STEP,\n }),\n })\n await this.refreshUserFlowState()\n const updatedUserFlowState = this.getUserFlowState()\n stepObj.isCompleted =\n updatedUserFlowState.stepStates[step.id].actionType == COMPLETED_STEP\n stepObj.isStarted = updatedUserFlowState.stepStates[step.id].actionType == STARTED_STEP\n }\n\n stepObj.complete = async (properties?: Record<string | number, any>) => {\n stepObj.isCompleted = true\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: step.id,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_STEP,\n }),\n })\n await this.refreshUserFlowState()\n const updatedUserFlowState = this.getUserFlowState()\n stepObj.isCompleted =\n updatedUserFlowState.stepStates[step.id].actionType == COMPLETED_STEP\n stepObj.isStarted = updatedUserFlowState.stepStates[step.id].actionType == STARTED_STEP\n }\n\n return stepObj\n }),\n ]\n }\n\n /**\n * Function that marks the flow started\n */\n public async start(properties?: Record<string | number, any>) {\n const currentStepIndex = this.getCurrentStepIndex()\n const currentStepId = currentStepIndex != -1 ? this.steps[currentStepIndex].id : 'unknown'\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: currentStepId,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: STARTED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that marks the flow completed\n */\n public async complete(properties?: Record<string | number, any>) {\n const currentStepIndex = this.getCurrentStepIndex()\n const currentStepId = currentStepIndex != -1 ? this.steps[currentStepIndex].id : 'unknown'\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: currentStepId,\n data: properties ?? {},\n createdAt: new Date().toISOString(),\n actionType: COMPLETED_FLOW,\n }),\n })\n await this.refreshUserFlowState()\n this.initFromRawData(this.flowDataRaw)\n }\n\n /**\n * Function that restarts the flow/marks it not started\n */\n public async restart() {\n await fetcher(this.internalConfig.apiKey, `/flowResponses`, {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.internalConfig.userId,\n flowSlug: this.id,\n stepId: 'unknown',\n data: {},\n createdAt: new Date().toISOString(),\n actionType: NOT_STARTED_FLOW,\n }),\n })\n }\n\n /**\n * Function that gets current step index\n */\n public getCurrentStepIndex(): number {\n // Find the userFlowState with most recent timestamp\n const userFlowState = this.getUserFlowState()\n if (!userFlowState) {\n return 0\n }\n const currentStepId = userFlowState.lastStepId\n const index = this.steps.findIndex((step) => step.id === currentStepId)\n return index == -1 ? 0 : index\n }\n\n private getUserFlowState(): UserFlowState {\n const userFlowStates = frigadeGlobalState[getGlobalStateKey(this.internalConfig)].userFlowStates\n return userFlowStates[this.id]\n }\n\n private async refreshUserFlowState() {\n await frigadeGlobalState[getGlobalStateKey(this.internalConfig)].refreshUserFlowStates()\n }\n}\n","import { FrigadeConfig, InternalConfig, UserFlowState } from '../types'\nimport { fetcher, generateGuestId, resetAllLocalStorage } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowDataRaw } from './types'\nimport { frigadeGlobalState, getGlobalStateKey } from '../shared/state'\n\nexport class Frigade {\n private apiKey?: string\n private userId: string = generateGuestId()\n private organizationId?: string\n private config?: FrigadeConfig\n private hasInitialized = false\n private internalConfig?: InternalConfig\n\n private flows: Flow[] = []\n\n public async init(apiKey: string, config?: FrigadeConfig): Promise<void> {\n this.apiKey = apiKey\n this.config = config\n if (config?.userId) {\n this.userId = config.userId\n }\n if (config?.organizationId) {\n this.organizationId = config.organizationId\n }\n this.refreshInternalConfig()\n await this.refreshUserFlowStates()\n await this.refreshFlows()\n this.hasInitialized = true\n }\n\n public async identify(userId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.userId = userId\n this.refreshInternalConfig()\n await fetcher(this.apiKey, '/users', {\n method: 'POST',\n body: JSON.stringify({\n foreignId: this.userId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async group(organizationId: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n this.organizationId = organizationId\n this.refreshInternalConfig()\n await fetcher(this.apiKey, '/userGroups', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n properties,\n }),\n })\n await this.refreshUserFlowStates()\n }\n\n public async track(event: string, properties?: Record<string, any>): Promise<void> {\n this.errorOnUninitialized()\n await fetcher(this.apiKey, '/track', {\n method: 'POST',\n body: JSON.stringify({\n foreignUserId: this.userId,\n foreignUserGroupId: this.organizationId,\n event,\n properties,\n }),\n })\n }\n\n public async getFlow(flowId: string) {\n this.errorOnUninitialized()\n return this.flows.find((flow) => flow.id == flowId)\n }\n\n public async getFlows() {\n this.errorOnUninitialized()\n return this.flows\n }\n\n public async reset() {\n resetAllLocalStorage()\n this.userId = generateGuestId()\n this.organizationId = undefined\n }\n\n private errorOnUninitialized() {\n if (!this.hasInitialized) {\n throw new Error(\n 'Frigade has not been initialized yet. Please call Frigade.init() before using any other methods.'\n )\n }\n }\n\n private async refreshUserFlowStates(): Promise<void> {\n const globalStateKey = getGlobalStateKey(this.internalConfig)\n frigadeGlobalState[globalStateKey] = {\n refreshUserFlowStates: async () => {},\n userFlowStates: {},\n }\n frigadeGlobalState[globalStateKey].refreshUserFlowStates = async () => {\n const userFlowStatesRaw = await fetcher(\n this.apiKey,\n `/userFlowStates?foreignUserId=${this.userId}${\n this.organizationId ? `&foreignUserGroupId=${this.organizationId}` : ''\n }`\n )\n if (userFlowStatesRaw && userFlowStatesRaw.data) {\n let userFlowStates = userFlowStatesRaw.data as UserFlowState[]\n userFlowStates.forEach((userFlowState) => {\n frigadeGlobalState[globalStateKey].userFlowStates[userFlowState.flowId] = userFlowState\n })\n }\n }\n await frigadeGlobalState[globalStateKey].refreshUserFlowStates()\n }\n\n private async refreshFlows() {\n this.flows = []\n const flowDataRaw = await fetcher(this.apiKey, '/flows')\n if (flowDataRaw && flowDataRaw.data) {\n let flowDatas = flowDataRaw.data as FlowDataRaw[]\n flowDatas.forEach((flowData) => {\n this.flows.push(new Flow(this.internalConfig, flowData))\n })\n }\n }\n\n private refreshInternalConfig() {\n this.internalConfig = {\n apiKey: this.apiKey,\n userId: this.userId,\n organizationId: this.organizationId,\n }\n }\n}\n\nconst frigade = new Frigade()\nexport default frigade\n","import frigade from './core/frigade'\nimport Flow from './core/flow'\n\nexport { Flow }\n\nexport default frigade\n"],"mappings":";AAAO,IAAMA,EAAiB,SCC9B,OAAOC,MAAW,cAClB,OAAS,MAAMC,MAAc,OAGtB,IAAMC,EAAiB,iBAEvB,IAAMC,EAAe,eACfC,EAAmB,mBACnBC,EAAiB,iBACjBC,EAAe,eAGtBC,EAAoB,wBACpBC,EAAsB,0BACtBC,EAAY,oBACZC,EAAe,SAErB,SAASC,EAAUC,EAAgB,CACjC,MAAO,CACL,OAAQ,CACN,QAAS,CACP,cAAe,UAAUA,IACzB,eAAgB,mBAChB,wBAAyBC,EACzB,yBAA0B,YAC5B,CACF,CACF,CACF,CAEA,SAASC,EAAgBC,EAAa,CACpC,OAAI,QAAU,OAAO,aACZ,OAAO,aAAa,QAAQA,CAAG,EAEjC,IACT,CAEA,SAASC,EAAgBD,EAAaE,EAAe,CAC/C,QAAU,OAAO,cACnB,OAAO,aAAa,QAAQF,EAAKE,CAAK,CAE1C,CAEO,SAASC,GAAuB,CACjC,QAAU,OAAO,cAEnB,OAAO,KAAK,OAAO,YAAY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CAAc,EAAE,sBAAwB,SAAY,CACrE,IAAMG,EAAoB,MAAMT,EAC9B,KAAK,OACL,iCAAiC,KAAK,SACpC,KAAK,eAAiB,uBAAuB,KAAK,iBAAmB,IAEzE,EACIS,GAAqBA,EAAkB,MACpBA,EAAkB,KACxB,QAASC,GAAkB,CACxCF,EAAmBF,CAAc,EAAE,eAAeI,EAAc,MAAM,EAAIA,CAC5E,CAAC,CAEL,EACA,MAAMF,EAAmBF,CAAc,EAAE,sBAAsB,CACjE,CAEA,MAAc,cAAe,CAC3B,KAAK,MAAQ,CAAC,EACd,IAAMK,EAAc,MAAMX,EAAQ,KAAK,OAAQ,QAAQ,EACnDW,GAAeA,EAAY,MACbA,EAAY,KAClB,QAASC,GAAa,CAC9B,KAAK,MAAM,KAAK,IAAIC,EAAK,KAAK,eAAgBD,CAAQ,CAAC,CACzD,CAAC,CAEL,CAEQ,uBAAwB,CAC9B,KAAK,eAAiB,CACpB,OAAQ,KAAK,OACb,OAAQ,KAAK,OACb,eAAgB,KAAK,cACvB,CACF,CACF,EAEME,EAAU,IAAIpB,EACbqB,EAAQD,ECxIf,IAAOE,EAAQC","names":["VERSION_NUMBER","fetch","uuidv4","COMPLETED_FLOW","STARTED_FLOW","NOT_STARTED_FLOW","COMPLETED_STEP","STARTED_STEP","LAST_POST_CALL_AT","LAST_POST_CALL_DATA","GUEST_KEY","GUEST_PREFIX","getConfig","apiKey","VERSION_NUMBER","getLocalStorage","key","setLocalStorage","value","resetAllLocalStorage","gracefulFetch","url","options","lastCallAtKey","lastCallDataKey","lastCall","lastCallData","lastCallDate","getEmptyResponse","response","fetch","error","generateGuestId","guestId","uuidv4","fetcher","path","frigadeGlobalState","getGlobalStateKey","internalConfig","Flow","internalConfig","flowDataRaw","flowDataYml","steps","userFlowState","COMPLETED_FLOW","STARTED_FLOW","step","userFlowStateStep","stepObj","COMPLETED_STEP","STARTED_STEP","properties","fetcher","updatedUserFlowState","currentStepIndex","currentStepId","NOT_STARTED_FLOW","index","frigadeGlobalState","getGlobalStateKey","Frigade","generateGuestId","apiKey","config","userId","properties","fetcher","organizationId","event","flowId","flow","resetAllLocalStorage","globalStateKey","getGlobalStateKey","frigadeGlobalState","userFlowStatesRaw","userFlowState","flowDataRaw","flowData","Flow","frigade","frigade_default","src_default","frigade_default"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@frigade/js",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.2",
|
|
4
4
|
"description": "The official Javascript SDK for Frigade.",
|
|
5
5
|
"main": "./lib/index.js",
|
|
6
6
|
"types": "./lib/index.d.ts",
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
],
|
|
10
10
|
"scripts": {
|
|
11
11
|
"clean": "rimraf ./lib",
|
|
12
|
-
"test": "
|
|
12
|
+
"test": "jest",
|
|
13
13
|
"semantic-release": "semantic-release",
|
|
14
14
|
"lint": "eslint --fix --ext .ts,.tsx .",
|
|
15
15
|
"copy-files": "copyfiles -u 1 src/**/*.html src/**/*.css ./lib",
|
|
@@ -46,6 +46,7 @@
|
|
|
46
46
|
"@types/jest": "^23.3.1",
|
|
47
47
|
"babel-jest": "^29.4.1",
|
|
48
48
|
"copyfiles": "^2.4.1",
|
|
49
|
+
"husky": "^8.0.3",
|
|
49
50
|
"jest": "^29.4.1",
|
|
50
51
|
"jest-config": "^29.3.1",
|
|
51
52
|
"jest-environment-jsdom": "^29.4.1",
|
|
@@ -94,6 +95,7 @@
|
|
|
94
95
|
},
|
|
95
96
|
"homepage": "https://github.com/FrigadeHQ/frigade-js#readme",
|
|
96
97
|
"dependencies": {
|
|
98
|
+
"cross-fetch": "^4.0.0",
|
|
97
99
|
"uuid": "^9.0.0"
|
|
98
100
|
}
|
|
99
101
|
}
|