-
Notifications
You must be signed in to change notification settings - Fork 0
/
cobalt.ts
428 lines (380 loc) · 13.8 KB
/
cobalt.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
* Cobalt Frontend SDK
*/
/** An application in Cobalt. */
export interface Application {
/**The application name. */
name: string;
/**The application description. */
description: string;
/**The application icon. */
icon: string;
/**The application slug for native apps. */
type: string;
/** The application slug for custom apps. */
slug?: string;
/**The type of auth used by application. */
auth_type: "oauth2" | "keybased";
/** Whether the user has connected the application. */
connected?: boolean;
/** Whether the connection has expired and re-auth is required. */
reauth_required?: boolean;
/** The fields required from the user to connect the application (for `keybased` auth type). */
auth_input_map?: InputField[];
}
/** An Input field to take input from the user. */
export interface InputField {
/** Key name of the field. */
name: string;
/** Input type of the field. */
type: string;
/** Whether the field is required. */
required: string;
/** The placeholder of the field. */
placeholder: string;
/** The label of the field. */
label: string;
}
/** The payload object for config. */
export interface ConfigPayload {
/** The application slug. */
slug: string;
/** Unique ID for the config. */
config_id?: string;
/** The dynamic label mappings. */
labels: Label[];
}
/** Label Mapping */
export interface Label {
/** The label name. */
name: string;
/** The label value. */
value: string | number | boolean;
}
/** The configuration data for an application. */
export interface UpdateConfigPayload {
/** The application slug */
slug: string;
/** Unique ID for the config. */
config_id?: string;
/** A map of application fields and their values. */
fields: Record<string, string | number | boolean>;
/** The config workflows data. */
workflows: WorkflowPayload[];
}
/** The workflow. */
export interface WorkflowPayload {
/** The ID of the workflow. */
id: string;
/** Whether the workflow is enabled. */
enabled: boolean;
/** A map of workflow field names and their values. */
fields: Record<string, string | number | boolean>;
}
export interface CobaltOptions {
/** The base URL of the Cobalt API. You don't need to set this. */
baseUrl?: string;
/** The session token. */
token?: string;
}
export interface EcosystemLead {
_id: string;
name?: string;
email: string;
description?: string;
created_at: string;
}
export interface EcosystemLeadPayload {
slug: string;
name?: string;
email: string;
description?: string;
}
type Config = any;
class Cobalt {
private baseUrl: string;
public token: string;
/**
* Cobalt Frontend SDK
* @param {Object} options The options to configure the Cobalt SDK.
* @param {String} [options.token] The session token.
* @param {String} [options.baseUrl=https://api.gocobalt.io] The base URL of the Cobalt API.
*/
constructor(options: CobaltOptions = {}) {
this.baseUrl = options.baseUrl || "https://api.gocobalt.io";
this.token = options.token || "";
}
/**
* Returns the org & customer details for the associated token.
* @private
* @returns {Promise<unknown>}
*/
public async getAccountDetails(): Promise<unknown> {
const res = await fetch(`${this.baseUrl}/api/v3/org/basics`, {
headers: {
authorization: `Bearer ${this.token}`,
},
});
if (res.status >= 400 && res.status < 600) {
throw new Error(res.statusText);
}
const data = await res.json();
return data;
}
/**
* Returns the list of enabled applications and their details.
* @returns {Promise<Application[]>} The list of applications.
*/
public async getApp(): Promise<Application[]>;
/**
* Returns the application details for the specified application, provided
* the application is enabled in Cobalt.
* @param {String} slug The application slug.
* @returns {Promise<Application>} The application details.
*/
public async getApp(slug: string): Promise<Application>;
/**
* Returns the application details for the specified application, provided
* the application is enabled in Cobalt. If no application is specified,
* it returns all the enabled applications.
* @param {String} [slug] The application slug.
* @returns {Promise<Application | Application[]>} The application details.
*/
public async getApp(slug?: string): Promise<Application | Application[]> {
const res = await fetch(`${this.baseUrl}/api/v2/f-sdk/application${slug ? `/${slug}` : ""}`, {
headers: {
authorization: `Bearer ${this.token}`,
},
});
if (res.status >= 400 && res.status < 600) {
throw new Error(res.statusText);
}
const data = await res.json();
return data;
}
/**
* Returns all the enabled and ecosystem apps.
* @returns {Promise<Application[]>} The list of applications.
*/
public async getApps(): Promise<Application[]> {
const res = await fetch(`${this.baseUrl}/api/v2/f-sdk/application?ecosystem=true`, {
headers: {
authorization: `Bearer ${this.token}`,
},
});
if (res.status >= 400 && res.status < 600) {
throw new Error(res.statusText);
}
const data = await res.json();
return data;
}
/**
* Returns the auth URL that users can use to authenticate themselves to the
* specified application.
* @private
* @param {String} slug The application slug.
* @param {Object.<string, string>} [params] The key value pairs of auth data.
* @returns {Promise<String>} The auth URL where users can authenticate themselves.
*/
private async getOAuthUrl(slug: string, params?: Record<string, string>): Promise<string> {
const res = await fetch(`${this.baseUrl}/api/v1/${slug}/integrate?${new URLSearchParams(params).toString()}`, {
headers: {
authorization: `Bearer ${this.token}`,
},
});
if (res.status >= 400 && res.status < 600) {
throw new Error(res.statusText);
}
const data = await res.json();
return data.auth_url;
}
/**
* Handle OAuth for the specified native application.
* @private
* @param {String} slug The application slug.
* @param {Object.<string, string>} [params] The key value pairs of auth data.
* @returns {Promise<Boolean>} Whether the user authenticated.
*/
private async oauth(slug: string, params?: Record<string, string>): Promise<boolean> {
return new Promise((resolve, reject) => {
this.getOAuthUrl(slug, params)
.then(oauthUrl => {
const connectWindow = window.open(oauthUrl);
// keep checking connection status
const interval = setInterval(() => {
this.getApp(slug)
.then(app => {
if (app && app.connected === true && !app.reauth_required) {
// close auth window
connectWindow && connectWindow.close();
// clear interval
clearInterval(interval);
// resovle status
resolve(true);
} else {
// user closed oauth window without authenticating
if (connectWindow && connectWindow.closed) {
// clear interval
clearInterval(interval);
// resolve status
resolve(false);
}
}
})
.catch(e => {
console.error(e);
clearInterval(interval);
reject(e);
});
}, 3e3);
})
.catch(reject);
});
}
/**
* Connect the specified application, optionally with the auth data that user provides.
* @param {String} slug The application slug.
* @param {Object.<string, string>} [payload] The key value pairs of auth data.
* @returns {Promise<Boolean>} Whether the connection was successful.
*/
public async connect(slug: string, payload?: Record<string, string>): Promise<boolean> {
return new Promise(async (resolve, reject) => {
try {
const app = await this.getApp(slug);
// oauth
if (app && app.auth_type === "oauth2") {
const connected = await this.oauth(slug, payload);
resolve(connected);
// key based
} else {
const res = await fetch(`${this.baseUrl}/api/v2/app/${slug}/save`, {
method: "POST",
headers: {
authorization: `Bearer ${this.token}`,
"content-type": "application/json",
},
body: JSON.stringify({
...payload,
}),
});
if (res.status >= 400 && res.status < 600) {
reject(new Error(res.statusText));
}
const data = await res.json();
resolve(data.success);
}
} catch (error) {
reject(error);
}
});
}
/**
* Disconnect the specified application and remove any associated data from Cobalt.
* @param {String} slug The application slug.
* @returns {Promise<void>}
*/
public async disconnect(slug: string): Promise<void> {
const res = await fetch(`${this.baseUrl}/api/v1/linked-acc/integration/${slug}`, {
method: "DELETE",
headers: {
authorization: `Bearer ${this.token}`,
},
});
if (res.status >= 400 && res.status < 600) {
throw new Error(res.statusText);
}
}
/**
* Returns the specified config, or creates one if it doesn't exist.
* @param {ConfigPayload} payload The payload object for config.
* @returns {Promise<Config>} The specified config.
*/
public async config(payload: ConfigPayload): Promise<Config> {
const res = await fetch(`${this.baseUrl}/api/v2/f-sdk/config`, {
method: "POST",
headers: {
authorization: `Bearer ${this.token}`,
"content-type": "application/json",
},
body: JSON.stringify(payload),
});
if (res.status >= 400 && res.status < 600) {
throw new Error(res.statusText);
}
return await res.json();
}
/**
* Returns the specified config.
* @param {String} slug The application slug.
* @param {String} [configId] The unique ID of the config.
* @returns {Promise<Config>} The specified config.
*/
async getConfig(slug: string, configId: string): Promise<Config> {
const res = await fetch(`${this.baseUrl}/api/v2/f-sdk/slug/${slug}/config${configId ? `/${configId}` : ""}`, {
headers: {
authorization: `Bearer ${this.token}`,
},
});
if (res.status >= 400 && res.status < 600) {
throw new Error(res.statusText);
}
return await res.json();
}
/**
* Update the specified config.
* @param {UpdateConfigPayload} payload The update payload.
* @returns {Promise<Config>} The specified config.
*/
async updateConfig(payload: UpdateConfigPayload): Promise<Config> {
const res = await fetch(`${this.baseUrl}/api/v2/f-sdk/config`, {
method: "PUT",
headers: {
authorization: `Bearer ${this.token}`,
"content-type": "application/json",
},
body: JSON.stringify(payload),
});
if (res.status >= 400 && res.status < 600) {
throw new Error(res.statusText);
}
return await res.json();
}
/**
* Delete the specified config.
* @param {String} slug The application slug.
* @param {String} [configId] The unique ID of the config.
* @returns {Promise<unknown>}
*/
async deleteConfig(slug: string, configId: string): Promise<unknown> {
const res = await fetch(`${this.baseUrl}/api/v2/f-sdk/slug/${slug}/config${configId ? `/${configId}` : ""}`, {
method: "DELETE",
headers: {
authorization: `Bearer ${this.token}`,
},
});
if (res.status >= 400 && res.status < 600) {
throw new Error(res.statusText);
}
return await res.json();
}
/**
* Create a lead for an ecosystem app.
* @param {EcosystemLeadPayload} payload The payload object for the lead.
* @returns {Promise<EcosystemLead>}
*/
public async createEcosystemLead(payload: EcosystemLeadPayload): Promise<EcosystemLead> {
const res = await fetch(`${this.baseUrl}/api/v1/ecosystem/leads`, {
method: "POST",
headers: {
authorization: `Bearer ${this.token}`,
"content-type": "application/json",
},
body: JSON.stringify(payload),
});
if (res.status >= 400 && res.status < 600) {
throw new Error(res.statusText);
}
return await res.json();
}
}
export { Cobalt };