@frigade/js 1.0.1 → 1.0.3
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/README.md +66 -0
- package/lib/index.d.ts +109 -69
- 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 +1 -1
package/README.md
CHANGED
|
@@ -34,6 +34,72 @@ yarn add @frigade/js
|
|
|
34
34
|
```bash
|
|
35
35
|
npm install @frigade/js
|
|
36
36
|
```
|
|
37
|
+
|
|
38
|
+
## Usage
|
|
39
|
+
|
|
40
|
+
Simply `import frigade from '@frigade/js'` and use it. Example:
|
|
41
|
+
|
|
42
|
+
```js
|
|
43
|
+
import frigade from '@frigade/js'
|
|
44
|
+
|
|
45
|
+
await frigade.init('FRIGADE_API_KEY')
|
|
46
|
+
|
|
47
|
+
await frigade.identify('USER_ID', {
|
|
48
|
+
name: 'USER_NAME',
|
|
49
|
+
email: 'USER_EMAIL',
|
|
50
|
+
signed_up_at: 'USER_SIGNED_UP_AT' // ISO 8601 format
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
// Optional: send organization/group id
|
|
54
|
+
await frigade.group('ORGANIZATION_ID', {
|
|
55
|
+
name: 'COMPANY_NAME',
|
|
56
|
+
})
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## API Reference
|
|
60
|
+
|
|
61
|
+
#### Get a flow:
|
|
62
|
+
|
|
63
|
+
```js
|
|
64
|
+
const flow = await frigade.getFlow('FLOW_ID')
|
|
65
|
+
// Flow data defined in flow-data.yml in the Frigade dashboard
|
|
66
|
+
console.log('Flow status:', flow.isCompleted)
|
|
67
|
+
console.log('Flow data:', flow.rawData)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
#### Marking a flow as completed:
|
|
71
|
+
|
|
72
|
+
```js
|
|
73
|
+
const flow = await frigade.getFlow('FLOW_ID')
|
|
74
|
+
await flow.complete()
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
#### Marking a step in a flow as completed:
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
const flow = await frigade.getFlow('FLOW_ID')
|
|
81
|
+
const step = flow.getStep('STEP_ID')
|
|
82
|
+
await step.start()
|
|
83
|
+
await step.complete()
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
#### Sending tracking events:
|
|
87
|
+
|
|
88
|
+
```js
|
|
89
|
+
await frigade.track('EVENT_NAME', {
|
|
90
|
+
property1: 'value1',
|
|
91
|
+
property2: 'value2',
|
|
92
|
+
})
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Cross-platform support
|
|
96
|
+
|
|
97
|
+
All non-UI related functionality of the SDK works in all JavaScript environments (Node.js, browser, React Native, etc.).
|
|
98
|
+
|
|
99
|
+
## TypeScript support
|
|
100
|
+
|
|
101
|
+
This package contains TypeScript definitions of the `frigade` object.
|
|
102
|
+
|
|
37
103
|
### About Frigade
|
|
38
104
|
|
|
39
105
|
[Frigade](<https://frigade.com>) is a developer-first platform for building quality product onboarding. A powerful,
|
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,87 +147,79 @@ 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
|
-
|
|
153
|
+
[x: string | number | symbol]: unknown;
|
|
105
154
|
/**
|
|
106
|
-
*
|
|
155
|
+
* Function that marks the step started
|
|
107
156
|
*/
|
|
108
|
-
|
|
157
|
+
start: (properties?: Record<string | number, any>) => void;
|
|
109
158
|
/**
|
|
110
|
-
*
|
|
159
|
+
* Function that marks the step completed
|
|
111
160
|
*/
|
|
112
|
-
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
interface FlowMetadata {
|
|
116
|
-
id: number;
|
|
117
|
-
name: string;
|
|
118
|
-
description: string;
|
|
119
|
-
data: string;
|
|
120
|
-
createdAt: string;
|
|
121
|
-
modifiedAt: string;
|
|
122
|
-
slug: string;
|
|
123
|
-
targetingLogic: string;
|
|
124
|
-
type: FlowType;
|
|
125
|
-
triggerType: TriggerType;
|
|
126
|
-
status: FlowStatus;
|
|
127
|
-
version: number;
|
|
128
|
-
active: boolean;
|
|
129
|
-
}
|
|
130
|
-
declare enum FlowType {
|
|
131
|
-
CHECKLIST = "CHECKLIST",
|
|
132
|
-
FORM = "FORM",
|
|
133
|
-
TOUR = "TOUR",
|
|
134
|
-
SUPPORT = "SUPPORT",
|
|
135
|
-
CUSTOM = "CUSTOM",
|
|
136
|
-
BANNER = "BANNER",
|
|
137
|
-
EMBEDDED_TIP = "EMBEDDED_TIP",
|
|
138
|
-
NPS_SURVEY = "NPS_SURVEY"
|
|
139
|
-
}
|
|
140
|
-
declare enum TriggerType {
|
|
141
|
-
MANUAL = "MANUAL",
|
|
142
|
-
AUTOMATIC = "AUTOMATIC"
|
|
143
|
-
}
|
|
144
|
-
declare enum FlowStatus {
|
|
145
|
-
DRAFT = "DRAFT",
|
|
146
|
-
ACTIVE = "ACTIVE",
|
|
147
|
-
ARCHIVED = "ARCHIVED"
|
|
161
|
+
complete: (properties?: Record<string | number, any>) => void;
|
|
148
162
|
}
|
|
149
163
|
|
|
150
164
|
declare class Flow {
|
|
151
165
|
/**
|
|
152
166
|
* THe Flow ID / slug of the flow
|
|
153
167
|
*/
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* The status of the flow
|
|
157
|
-
*/
|
|
158
|
-
readonly status: FlowStatus;
|
|
168
|
+
id: string;
|
|
159
169
|
/**
|
|
160
170
|
* The raw data defined in `flow-data.yml` as a JSON decoded object
|
|
161
171
|
*/
|
|
162
|
-
|
|
172
|
+
rawData: Record<any, any>;
|
|
163
173
|
/**
|
|
164
174
|
* The steps contained in the `data` array in `flow-data.yml`
|
|
165
175
|
*/
|
|
166
|
-
|
|
176
|
+
steps: FlowStep[];
|
|
167
177
|
/**
|
|
168
178
|
* The user-facing title of the flow, if defined at the top level of `flow-data.yml`
|
|
169
179
|
*/
|
|
170
|
-
|
|
180
|
+
title?: string;
|
|
171
181
|
/**
|
|
172
182
|
* The user-facing description of the flow, if defined at the top level of `flow-data.yml`
|
|
173
183
|
*/
|
|
174
|
-
|
|
184
|
+
subtitle?: string;
|
|
175
185
|
/**
|
|
176
186
|
* The metadata of the flow.
|
|
177
187
|
*/
|
|
178
|
-
|
|
179
|
-
|
|
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
|
+
* Get a step by id
|
|
215
|
+
*/
|
|
216
|
+
getStep(id: string): FlowStep | undefined;
|
|
217
|
+
/**
|
|
218
|
+
* Function that gets current step index
|
|
219
|
+
*/
|
|
220
|
+
getCurrentStepIndex(): number;
|
|
221
|
+
private getUserFlowState;
|
|
222
|
+
private refreshUserFlowState;
|
|
180
223
|
}
|
|
181
224
|
|
|
182
225
|
declare class Frigade {
|
|
@@ -185,11 +228,7 @@ declare class Frigade {
|
|
|
185
228
|
private organizationId?;
|
|
186
229
|
private config?;
|
|
187
230
|
private hasInitialized;
|
|
188
|
-
|
|
189
|
-
* Map flow IDs to their current state
|
|
190
|
-
* @private
|
|
191
|
-
*/
|
|
192
|
-
private userFlowStatuses;
|
|
231
|
+
private internalConfig?;
|
|
193
232
|
private flows;
|
|
194
233
|
init(apiKey: string, config?: FrigadeConfig): Promise<void>;
|
|
195
234
|
identify(userId: string, properties?: Record<string, any>): Promise<void>;
|
|
@@ -201,6 +240,7 @@ declare class Frigade {
|
|
|
201
240
|
private errorOnUninitialized;
|
|
202
241
|
private refreshUserFlowStates;
|
|
203
242
|
private refreshFlows;
|
|
243
|
+
private refreshInternalConfig;
|
|
204
244
|
}
|
|
205
245
|
declare const frigade: Frigade;
|
|
206
246
|
|
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.3 ";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),f=y(r);if(s&&f&&f==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.rawData=e,this.title=this.rawData.title,this.subtitle=this.rawData.subtitle;let a=this.getUserFlowState();this.isCompleted=a.flowState==T,this.isStarted=a.flowState==I,this.steps=[...r.map(s=>{let f=a.stepStates[s.id],n={...s,isCompleted:f.actionType==S,isStarted:f.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 w=this.getUserFlowState();n.isCompleted=w.stepStates[s.id].actionType==S,n.isStarted=w.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 w=this.getUserFlowState();n.isCompleted=w.stepStates[s.id].actionType==S,n.isStarted=w.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})})}getStep(t){return this.steps.find(e=>e.id==t)}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 }\n\nexport default frigade\n","export const VERSION_NUMBER = '1.0.1 '\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 { 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 metadata?: FlowMetadata\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 this.metadata = metadata\n }\n}\n","import { FrigadeConfig, UserFlowState } from '../types'\nimport { fetcher, generateGuestId, resetAllLocalStorage } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowMetadata } from './types'\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 /**\n * Map flow IDs to their current state\n * @private\n */\n private userFlowStatuses: Record<string, UserFlowState> = {}\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 await Promise.all([this.refreshUserFlowStates(), 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 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 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() {\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 this.userFlowStatuses[userFlowState.flowId] = userFlowState\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 flowMetadata\n )\n )\n })\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,gBAW7B,IAAMC,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,EAAE,QAASH,GAAQ,CAC5CA,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,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,CAEA,MAAa,UAAW,CACtB,YAAK,qBAAqB,EACnB,KAAK,KACd,CAEA,MAAa,OAAQ,CACnBE,EAAqB,EACrB,KAAK,OAASV,EAAgB,EAC9B,KAAK,eAAiB,MACxB,CAEQ,sBAAuB,CAC7B,GAAI,CAAC,KAAK,eACR,MAAM,IAAI,MACR,kGACF,CAEJ,CAEA,MAAc,uBAAwB,CACpC,IAAMW,EAAoB,MAAMN,EAC9B,KAAK,OACL,iCAAiC,KAAK,SACpC,KAAK,eAAiB,uBAAuB,KAAK,iBAAmB,IAEzE,EACIM,GAAqBA,EAAkB,MACpBA,EAAkB,KACxB,QAASC,GAAkB,CACxC,KAAK,iBAAiBA,EAAc,MAAM,EAAIA,CAChD,CAAC,CAEL,CAEA,MAAc,cAAe,CAC3B,KAAK,MAAQ,CAAC,EACd,IAAMC,EAAc,MAAMR,EAAQ,KAAK,OAAQ,QAAQ,EACnDQ,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,SACTD,CACF,CACF,CACF,CAAC,CAEL,CACF,EAEMG,EAAU,IAAIlB,EACbmB,EAAQD,EJlIf,IAAOE,EAAQC","names":["src_exports","__export","Flow","src_default","__toCommonJS","VERSION_NUMBER","import_cross_fetch","import_uuid","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","Flow","id","status","rawData","steps","title","subtitle","metadata","Frigade","generateGuestId","apiKey","config","userId","properties","fetcher","organizationId","event","flowId","flow","resetAllLocalStorage","userFlowStatesRaw","userFlowState","flowDataRaw","flowMetadata","rawData","Flow","frigade","frigade_default","src_default","frigade_default"]}
|
|
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.3 '\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 rawData: 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.rawData = flowDataYml\n this.title = this.rawData.title\n this.subtitle = this.rawData.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 * Get a step by id\n */\n public getStep(id: string): FlowStep | undefined {\n return this.steps.find((step) => step.id == id)\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,EA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AQD,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","id","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.3 ";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),f=u(a);if(s&&f&&f==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 w=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.rawData=e,this.title=this.rawData.title,this.subtitle=this.rawData.subtitle;let r=this.getUserFlowState();this.isCompleted=r.flowState==y,this.isStarted=r.flowState==T,this.steps=[...a.map(s=>{let f=r.stepStates[s.id],n={...s,isCompleted:f.actionType==S,isStarted:f.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})})}getStep(t){return this.steps.find(e=>e.id==t)}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 w(this.internalConfig,a))})}refreshInternalConfig(){this.internalConfig={apiKey:this.apiKey,userId:this.userId,organizationId:this.organizationId}}},v=new F,b=v;var H=b;export{w 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.1 '\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 { 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 metadata?: FlowMetadata\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 this.metadata = metadata\n }\n}\n","import { FrigadeConfig, UserFlowState } from '../types'\nimport { fetcher, generateGuestId, resetAllLocalStorage } from '../shared/utils'\nimport Flow from './flow'\nimport { FlowMetadata } from './types'\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 /**\n * Map flow IDs to their current state\n * @private\n */\n private userFlowStatuses: Record<string, UserFlowState> = {}\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 await Promise.all([this.refreshUserFlowStates(), 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 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 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() {\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 this.userFlowStatuses[userFlowState.flowId] = userFlowState\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 flowMetadata\n )\n )\n })\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,OAW7B,IAAMC,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,EAAE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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","Flow","id","status","rawData","steps","title","subtitle","metadata","Frigade","generateGuestId","apiKey","config","userId","properties","fetcher","organizationId","event","flowId","flow","resetAllLocalStorage","userFlowStatesRaw","userFlowState","flowDataRaw","flowMetadata","rawData","Flow","frigade","frigade_default","src_default","frigade_default"]}
|
|
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.3 '\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 rawData: 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.rawData = flowDataYml\n this.title = this.rawData.title\n this.subtitle = this.rawData.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 * Get a step by id\n */\n public getStep(id: string): FlowStep | undefined {\n return this.steps.find((step) => step.id == id)\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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TED_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","id","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"]}
|