@prisme.ai/sdk 1.0.1 → 2.0.1

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.
Files changed (54) hide show
  1. package/README.md +250 -0
  2. package/dist/index.d.mts +1129 -0
  3. package/dist/index.d.ts +1129 -7
  4. package/dist/index.js +1326 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/index.mjs +1287 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/package.json +50 -11
  9. package/Readme.md +0 -28
  10. package/dist/_virtual/_tslib.js +0 -107
  11. package/dist/lib/ApiError.d.ts +0 -8
  12. package/dist/lib/ApiError.test.d.ts +0 -1
  13. package/dist/lib/HTTPError.d.ts +0 -6
  14. package/dist/lib/HTTPError.test.d.ts +0 -1
  15. package/dist/lib/api.d.ts +0 -140
  16. package/dist/lib/api.test.d.ts +0 -1
  17. package/dist/lib/endpoints/users.d.ts +0 -9
  18. package/dist/lib/endpoints/workspaces.d.ts +0 -9
  19. package/dist/lib/endpoints/workspacesVersions.d.ts +0 -10
  20. package/dist/lib/events.d.ts +0 -38
  21. package/dist/lib/events.test.d.ts +0 -1
  22. package/dist/lib/fetcher.d.ts +0 -23
  23. package/dist/lib/fetcher.test.d.ts +0 -1
  24. package/dist/lib/types.d.ts +0 -17
  25. package/dist/lib/utils.d.ts +0 -1
  26. package/dist/lib/utils.test.d.ts +0 -1
  27. package/dist/sdk/index.js +0 -19
  28. package/dist/sdk/lib/ApiError.js +0 -24
  29. package/dist/sdk/lib/HTTPError.js +0 -21
  30. package/dist/sdk/lib/api.js +0 -956
  31. package/dist/sdk/lib/endpoints/users.js +0 -43
  32. package/dist/sdk/lib/endpoints/workspaces.js +0 -23
  33. package/dist/sdk/lib/endpoints/workspacesVersions.js +0 -40
  34. package/dist/sdk/lib/events.js +0 -142
  35. package/dist/sdk/lib/fetcher.js +0 -175
  36. package/dist/sdk/lib/utils.js +0 -18
  37. package/index.ts +0 -7
  38. package/lib/ApiError.test.ts +0 -13
  39. package/lib/ApiError.ts +0 -21
  40. package/lib/HTTPError.test.ts +0 -8
  41. package/lib/HTTPError.ts +0 -13
  42. package/lib/api.test.ts +0 -772
  43. package/lib/api.ts +0 -871
  44. package/lib/endpoints/users.ts +0 -22
  45. package/lib/endpoints/workspaces.ts +0 -18
  46. package/lib/endpoints/workspacesVersions.ts +0 -34
  47. package/lib/events.test.ts +0 -89
  48. package/lib/events.ts +0 -180
  49. package/lib/fetcher.test.ts +0 -246
  50. package/lib/fetcher.ts +0 -163
  51. package/lib/types.ts +0 -21
  52. package/lib/utils.test.ts +0 -38
  53. package/lib/utils.ts +0 -12
  54. package/tsconfig.json +0 -21
package/lib/api.ts DELETED
@@ -1,871 +0,0 @@
1
- import QueryString from 'qs';
2
- import pkceChallenge from 'pkce-challenge';
3
- import Fetcher, { Fetched } from './fetcher';
4
- import { Event, Workspace } from './types';
5
- import { Events } from './events';
6
- import { removedUndefinedProperties } from './utils';
7
- import WorkspacesEndpoint from './endpoints/workspaces';
8
- import ApiError from './ApiError';
9
- import UsersEndpoint from './endpoints/users';
10
-
11
- interface PageWithMetadata extends Prismeai.Page {
12
- createdAt: string;
13
- createdBy: string;
14
- updatedAt: string;
15
- updatedBy: string;
16
- }
17
-
18
- export type UserPermissions = {
19
- permissions: Prismeai.UserPermissions['permissions'];
20
- target: {
21
- id?: string;
22
- email?: string;
23
- public?: boolean;
24
- role?: string;
25
- displayName?: string;
26
- };
27
- };
28
-
29
- export interface ApiOptions {
30
- host: string;
31
- oidc?: {
32
- url: string;
33
- clientId: string;
34
- clientIdHeader?: string;
35
- redirectUri: string;
36
- };
37
- }
38
-
39
- export interface AccessToken {
40
- access_token: string;
41
- id_token: string;
42
- scope: string;
43
- expiresIn: number;
44
- token_type: 'Bearer';
45
- }
46
-
47
- export interface InteractiveSignin {
48
- interaction: string;
49
- login: string;
50
- password: string;
51
- remember?: boolean;
52
- }
53
-
54
- function dataURItoBlob(dataURI: string): [Blob, string] {
55
- // convert base64/URLEncoded data component to raw binary data held in a string
56
- let byteString;
57
- if (dataURI.split(',')[0].indexOf('base64') >= 0)
58
- byteString = atob(dataURI.split(',')[1]);
59
- else byteString = unescape(dataURI.split(',')[1]);
60
- // separate out the mime component
61
- const metadata = dataURI
62
- .split(';')
63
- .filter((v, k, all) => k < all.length - 1)
64
- .map((v) => v.split(/:/));
65
- const [, mimeString = ''] = metadata.find(([k, v]) => k === 'data') || [];
66
- const [, ext] = mimeString.split(/\//);
67
- const [, fileName = `file.${ext}`] =
68
- metadata.find(([k, v]) => k === 'filename') || [];
69
-
70
- // write the bytes of the string to a typed array
71
- let ia = new Uint8Array(byteString.length);
72
- for (var i = 0; i < byteString.length; i++) {
73
- ia[i] = byteString.charCodeAt(i);
74
- }
75
-
76
- return [new Blob([ia], { type: mimeString }), fileName];
77
- }
78
-
79
- export class Api extends Fetcher {
80
- public opts: Required<ApiOptions>;
81
- private sessionId?: string;
82
- private _user?: Prismeai.User & { sessionId?: string };
83
-
84
- constructor(opts: ApiOptions) {
85
- super(opts.host, opts?.oidc?.clientIdHeader);
86
- this.opts = {
87
- ...opts,
88
- oidc: {
89
- url: 'http://studio.local.prisme.ai:3001',
90
- clientId: 'local-client-id',
91
- redirectUri: 'http://studio.local.prisme.ai:3000/signin',
92
- ...opts.oidc,
93
- },
94
- };
95
- }
96
-
97
- get user() {
98
- return this._user;
99
- }
100
-
101
- async me() {
102
- const me = await this.get('/me');
103
- this.sessionId = me.sessionId;
104
- this._user = me;
105
- return me;
106
- }
107
-
108
- clientId(): string {
109
- return this.overwriteClientId || this.opts?.oidc?.clientId;
110
- }
111
-
112
- async getAuthorizationURL(
113
- overrideRedirectUri?: string,
114
- authParams?: { max_age?: string; acr_values?: string },
115
- locale = window?.navigator?.language
116
- ? window.navigator.language.substring(0, 2)
117
- : undefined
118
- ) {
119
- const url = new URL('/oidc/auth', this.opts.oidc.url);
120
- url.searchParams.set('response_type', 'code');
121
- url.searchParams.set('response_mode', 'query'); // Send the final authorization code as a query param to the redirect uri
122
- url.searchParams.set(
123
- 'redirect_uri',
124
- overrideRedirectUri || this.opts.oidc?.redirectUri || ''
125
- );
126
- url.searchParams.set(
127
- 'scope',
128
- 'openid profile email settings offline_access events:write events:read webhooks pages:read files:write files:read'
129
- );
130
- const clientId = this.clientId();
131
- url.searchParams.set('client_id', clientId);
132
-
133
- url.searchParams.set('code_challenge_method', 'S256');
134
- const { code_verifier: codeVerifier, code_challenge: codeChallenge } =
135
- await pkceChallenge(64);
136
- url.searchParams.set('code_challenge', codeChallenge);
137
- if (locale) {
138
- url.searchParams.set('locale', locale);
139
- }
140
-
141
- Object.entries(authParams || {}).forEach(([k, v]) => {
142
- url.searchParams.set(k, v);
143
- });
144
-
145
- return {
146
- url: url.toString(),
147
- codeVerifier,
148
- clientId,
149
- };
150
- }
151
-
152
- async signin(body: InteractiveSignin): Promise<{ redirectTo: string }> {
153
- const url = new URL(
154
- `/oidc/interaction/${body.interaction}/login`,
155
- this.opts.oidc.url
156
- );
157
-
158
- // Do not follow redirects as we need to get redirected from browser itself to save final token in local storage
159
- await this.post(url.toString(), new URLSearchParams(body as any), {
160
- redirect: 'manual',
161
- });
162
- const redirectTo = new URL(
163
- `/oidc/auth/${body.interaction}`,
164
- this.opts.oidc.url
165
- );
166
- return { redirectTo: redirectTo.toString() };
167
- }
168
-
169
- async getToken(
170
- authorizationCode: string,
171
- codeVerifier: string,
172
- overrideRedirectUri?: string
173
- ): Promise<AccessToken> {
174
- this.token = null;
175
- const url = new URL('/oidc/token', this.opts.oidc.url);
176
- const token = await this.post<AccessToken>(
177
- url.toString(),
178
- new URLSearchParams({
179
- grant_type: 'authorization_code',
180
- code: authorizationCode,
181
- code_verifier: codeVerifier,
182
- client_id: this.clientId(),
183
- redirect_uri: overrideRedirectUri || this.opts.oidc.redirectUri,
184
- })
185
- );
186
- return token;
187
- }
188
-
189
- async createAnonymousSession(): Promise<
190
- Prismeai.User & {
191
- token: string;
192
- }
193
- > {
194
- const user = await this.post<
195
- Prismeai.User & {
196
- token: string;
197
- }
198
- >(
199
- '/login/anonymous',
200
- {},
201
- {
202
- credentials: 'omit',
203
- }
204
- );
205
- this._user = user;
206
- return user;
207
- }
208
-
209
- async signup(
210
- email: string,
211
- password: string,
212
- firstName: string,
213
- lastName: string,
214
- language: string
215
- ): Promise<
216
- Prismeai.User & {
217
- token: string;
218
- }
219
- > {
220
- return await this.post('/signup', {
221
- email: email,
222
- password,
223
- firstName,
224
- lastName,
225
- language,
226
- });
227
- }
228
-
229
- getSignoutURL(redirectUri?: string) {
230
- const params = new URLSearchParams();
231
- params.set('client_id', this.clientId());
232
- if (redirectUri) {
233
- params.set('post_logout_redirect_uri', redirectUri);
234
- }
235
- const url = new URL(
236
- `/oidc/session/end?${params.toString()}`,
237
- this.opts.oidc.url
238
- );
239
- return url.toString();
240
- }
241
-
242
- // Mail validation
243
- async sendValidationMail(email: string, language: string) {
244
- return await this.post('/user/validate', { email, language });
245
- }
246
-
247
- async validateMail(token: string) {
248
- return await this.post('/user/validate', { token });
249
- }
250
-
251
- // Password reset
252
- async sendPasswordResetMail(email: string, language: string) {
253
- return await this.post('/user/password', { email, language });
254
- }
255
-
256
- async passwordReset(token: string, password: string) {
257
- return await this.post('/user/password', { token, password });
258
- }
259
-
260
- // Workspaces
261
- async getWorkspaces(): Promise<Workspace[]> {
262
- return await this.get('/workspaces?limit=600');
263
- }
264
-
265
- async getWorkspace(
266
- id: string
267
- ): Promise<PrismeaiAPI.GetWorkspace.Responses.$200> {
268
- return await this.get(`/workspaces/${id}`);
269
- }
270
-
271
- async getWorkspaceSecurity(
272
- id: string
273
- ): Promise<PrismeaiAPI.GetSecurity.Responses.$200> {
274
- return await this.get(`/workspaces/${id}/security`);
275
- }
276
-
277
- async updateWorkspaceSecurity(
278
- workspaceId: string,
279
- security: Prismeai.WorkspaceSecurity
280
- ): Promise<Fetched<PrismeaiAPI.UpdateSecurity.Responses.$200>> {
281
- return await this.put(`/workspaces/${workspaceId}/security`, security);
282
- }
283
-
284
- async getWorkspaceRoles(
285
- id: string
286
- ): Promise<Fetched<PrismeaiAPI.GetRoles.Responses.$200>> {
287
- return await this.get(`/workspaces/${id}/security/roles`);
288
- }
289
-
290
- async createWorkspace(name: string): Promise<Workspace> {
291
- return await this.post('/workspaces', { name });
292
- }
293
-
294
- async duplicateWorkspace({ id }: { id: string }): Promise<Workspace | null> {
295
- return await this.post(`/workspaces/${id}/versions/current/duplicate`, {});
296
- }
297
-
298
- async updateWorkspace(
299
- workspace: Prismeai.DSULPatch
300
- ): Promise<Fetched<PrismeaiAPI.UpdateWorkspace.Responses.$200> | null> {
301
- if (!workspace.id) return null;
302
- return await this.patch(
303
- `/workspaces/${workspace.id}`,
304
- await this.replaceAllImagesData(workspace, workspace.id)
305
- );
306
- }
307
-
308
- async deleteWorkspace(workspaceId: Workspace['id']): Promise<Workspace> {
309
- return await this.delete(`/workspaces/${workspaceId}`);
310
- }
311
-
312
- async generateApiKey(
313
- workspaceId: Workspace['id'],
314
- events: string[],
315
- uploads?: string[]
316
- ) {
317
- const { apiKey } = await this.post<{ apiKey: string }>(
318
- `/workspaces/${workspaceId}/apiKeys`,
319
- {
320
- rules: {
321
- events: {
322
- types: events,
323
- filters: {
324
- 'source.sessionId': '${user.sessionId}',
325
- },
326
- },
327
- uploads: uploads
328
- ? {
329
- mimetypes: uploads,
330
- }
331
- : undefined,
332
- },
333
- }
334
- );
335
-
336
- return apiKey;
337
- }
338
- async updateApiKey(
339
- workspaceId: Workspace['id'],
340
- apiKey: string,
341
- events: string[],
342
- uploads?: string[]
343
- ) {
344
- await this.put(`/workspaces/${workspaceId}/apiKeys/${apiKey}`, {
345
- rules: {
346
- events: {
347
- types: events,
348
- filters: {
349
- 'source.sessionId': '${user.sessionId}',
350
- },
351
- },
352
- uploads: uploads
353
- ? {
354
- mimetypes: uploads,
355
- }
356
- : undefined,
357
- },
358
- });
359
-
360
- return apiKey;
361
- }
362
-
363
- // Automations
364
- async getAutomation(
365
- workspaceId: string,
366
- automationSlug: string
367
- ): Promise<Fetched<PrismeaiAPI.GetAutomation.Responses.$200>> {
368
- return await this.get(
369
- `/workspaces/${workspaceId}/automations/${automationSlug}`
370
- );
371
- }
372
-
373
- async createAutomation(
374
- workspaceId: Workspace['id'],
375
- automation: Prismeai.Automation
376
- ): Promise<Fetched<Prismeai.Automation & { slug: string }>> {
377
- return await this.post(`/workspaces/${workspaceId}/automations`, {
378
- ...automation,
379
- });
380
- }
381
-
382
- async updateAutomation(
383
- workspaceId: string,
384
- slug: string,
385
- automation: Prismeai.Automation
386
- ): Promise<Fetched<Prismeai.Automation & { slug: string }>> {
387
- return await this.patch(
388
- `/workspaces/${workspaceId}/automations/${slug}`,
389
- await this.replaceAllImagesData(automation, workspaceId)
390
- );
391
- }
392
-
393
- async deleteAutomation(workspaceId: string, slug: string): Promise<string> {
394
- return await this.delete(`/workspaces/${workspaceId}/automations/${slug}`);
395
- }
396
-
397
- // Pages
398
- async getPages(
399
- workspaceId: NonNullable<Workspace['id']>
400
- ): Promise<Prismeai.Page[]> {
401
- try {
402
- const pages = await this.get<PageWithMetadata[]>(
403
- `/workspaces/${workspaceId}/pages`
404
- );
405
- return pages.map(
406
- ({ createdAt, createdBy, updatedAt, updatedBy, ...page }: any) => page
407
- );
408
- } catch (e) {
409
- return [];
410
- }
411
- }
412
-
413
- async getPage(
414
- workspaceId: PrismeaiAPI.GetPage.Parameters.WorkspaceId,
415
- pageSlug: PrismeaiAPI.GetPage.Parameters.Slug
416
- ): Promise<Fetched<Prismeai.DetailedPage>> {
417
- return await this.get(
418
- `/workspaces/${workspaceId}/pages/${encodeURIComponent(pageSlug)}`
419
- );
420
- }
421
-
422
- async getPageBySlug(
423
- workspaceSlug: PrismeaiAPI.GetPageBySlug.Parameters.WorkspaceSlug,
424
- pageSlug: PrismeaiAPI.GetPageBySlug.Parameters.PageSlug
425
- ): Promise<Fetched<Prismeai.DetailedPage>> {
426
- return await this.get(
427
- `/pages/${workspaceSlug}/${encodeURIComponent(pageSlug)}`
428
- );
429
- }
430
-
431
- async createPage(
432
- workspaceId: PrismeaiAPI.CreatePage.Parameters.WorkspaceId,
433
- page: PrismeaiAPI.CreatePage.RequestBody
434
- ): Promise<Prismeai.Page> {
435
- const { createdAt, createdBy, updatedAt, updatedBy, ...newPage } =
436
- await this.post<PageWithMetadata>(
437
- `/workspaces/${workspaceId}/pages`,
438
- page
439
- );
440
- return newPage;
441
- }
442
-
443
- async updatePage(
444
- workspaceId: PrismeaiAPI.UpdatePage.Parameters.WorkspaceId,
445
- page: PrismeaiAPI.UpdatePage.RequestBody,
446
- prevSlug: PrismeaiAPI.DeletePage.Parameters.Slug = page.slug || ''
447
- ): Promise<Prismeai.Page> {
448
- const { createdAt, createdBy, updatedAt, updatedBy, ...updatedPage } =
449
- await this.patch<PageWithMetadata>(
450
- `/workspaces/${workspaceId}/pages/${encodeURIComponent(prevSlug)}`,
451
- // Replace images as dataurl to uploaded url in any type of data
452
- await this.replaceAllImagesData(page, workspaceId)
453
- );
454
- return updatedPage;
455
- }
456
-
457
- async deletePage(
458
- workspaceId: PrismeaiAPI.DeletePage.Parameters.WorkspaceId,
459
- pageSlug: PrismeaiAPI.DeletePage.Parameters.Slug
460
- ): Promise<Fetched<PrismeaiAPI.DeletePage.Responses.$200>> {
461
- return await this.delete(
462
- `/workspaces/${workspaceId}/pages/${encodeURIComponent(pageSlug)}`
463
- );
464
- }
465
-
466
- // Events
467
- streamEvents(
468
- workspaceId: string,
469
- filters?: Record<string, any>
470
- ): Promise<Events> {
471
- if (filters && filters['source.sessionId'] === true) {
472
- if (this.sessionId) {
473
- filters['source.sessionId'] = this.sessionId;
474
- } else {
475
- delete filters['source.sessionId'];
476
- }
477
- }
478
- const events = new Events({
479
- workspaceId,
480
- token: this.token || '',
481
- legacyToken: this.legacyToken || '',
482
- apiKey: this._apiKey ? this._apiKey : undefined,
483
- apiHost: this.host,
484
- filters,
485
- api: this,
486
- });
487
- return new Promise((resolve, reject) => {
488
- const off = events.once('connect_error', () => {
489
- reject();
490
- events.close();
491
- });
492
- events.once('connect', () => {
493
- off();
494
- resolve(events);
495
- });
496
- });
497
- }
498
-
499
- async getEvents(
500
- workspaceId: string,
501
- options: Record<string, any> = {}
502
- ): Promise<Event<Date>[]> {
503
- try {
504
- const query = QueryString.stringify(options);
505
- const {
506
- result: { events },
507
- } = await this.get<{
508
- result: {
509
- events: Event<string>[];
510
- };
511
- }>(`/workspaces/${workspaceId}/events${query && `?${query}`}`);
512
- return events.map(({ createdAt, ...event }) => ({
513
- ...event,
514
- createdAt: new Date(createdAt),
515
- }));
516
- } catch (e) {
517
- return [];
518
- }
519
- }
520
-
521
- async postEvents(
522
- workspaceId: PrismeaiAPI.SendWorkspaceEvent.Parameters.WorkspaceId,
523
- events: PrismeaiAPI.SendWorkspaceEvent.RequestBody['events']
524
- ): Promise<boolean> {
525
- try {
526
- await this.post<PrismeaiAPI.SendWorkspaceEvent.Responses.$200>(
527
- `/workspaces/${workspaceId}/events`,
528
- {
529
- events,
530
- }
531
- );
532
- return true;
533
- } catch (e) {
534
- return false;
535
- }
536
- }
537
-
538
- async findContacts(
539
- query: PrismeaiAPI.FindContacts.RequestBody
540
- ): Promise<PrismeaiAPI.FindContacts.Responses.$200> {
541
- return await this.post(`/contacts`, query);
542
- }
543
-
544
- async getPermissions(
545
- subjectType: PrismeaiAPI.GetPermissions.Parameters.SubjectType,
546
- subjectId: string
547
- ): Promise<{ result: UserPermissions[] }> {
548
- const permissions: PrismeaiAPI.GetPermissions.Responses.$200 =
549
- await this.get(`/${subjectType}/${subjectId}/permissions`);
550
- const contacts = await this.findContacts({
551
- ids: permissions.result
552
- .filter((cur) => cur.target.id && !cur.target.displayName)
553
- .map((cur) => cur.target.id!),
554
- });
555
- return {
556
- result: permissions.result.map((perm) => {
557
- const user =
558
- perm.target.id && !perm.target.displayName
559
- ? contacts.contacts.find((cur) => cur.id === perm.target.id)
560
- : undefined;
561
- const displayName =
562
- perm.target.displayName || `${user?.firstName} ${user?.lastName}`;
563
- return {
564
- ...perm,
565
- target: {
566
- ...perm.target,
567
- id: perm.target.id!,
568
- displayName,
569
- },
570
- };
571
- }),
572
- };
573
- }
574
-
575
- async addPermissions(
576
- subjectType: PrismeaiAPI.GetPermissions.Parameters.SubjectType,
577
- subjectId: string,
578
- permissions: UserPermissions
579
- ): Promise<UserPermissions> {
580
- const body = { ...permissions };
581
- const { email } = permissions.target;
582
-
583
- if (email) {
584
- const contacts = await this.findContacts({
585
- email,
586
- });
587
-
588
- if (!contacts.contacts.length) {
589
- throw new ApiError(
590
- {
591
- error: 'CollaboratorNotFound',
592
- message: 'This user does not exist',
593
- details: { email },
594
- },
595
- 404
596
- );
597
- }
598
- body.target = { id: contacts.contacts[0].id };
599
- }
600
-
601
- const result: PrismeaiAPI.Share.Responses.$200 = await this.post(
602
- `/${subjectType}/${subjectId}/permissions`,
603
- body
604
- );
605
- return {
606
- ...result,
607
- target: {
608
- ...result.target,
609
- id: result.target.id!,
610
- email,
611
- },
612
- };
613
- }
614
-
615
- async deletePermissions(
616
- subjectType: PrismeaiAPI.GetPermissions.Parameters.SubjectType,
617
- subjectId: string,
618
- id: string
619
- ): Promise<Fetched<PrismeaiAPI.RevokePermissions.Responses.$200>> {
620
- return await this.delete(`/${subjectType}/${subjectId}/permissions/${id}`);
621
- }
622
-
623
- async getApps({
624
- query,
625
- page,
626
- limit,
627
- workspaceId,
628
- }: {
629
- query?: PrismeaiAPI.SearchApps.QueryParameters['text'];
630
- page?: PrismeaiAPI.SearchApps.QueryParameters['page'];
631
- limit?: PrismeaiAPI.SearchApps.QueryParameters['limit'];
632
- workspaceId?: PrismeaiAPI.SearchApps.QueryParameters['workspaceId'];
633
- }): Promise<Fetched<PrismeaiAPI.SearchApps.Responses.$200>> {
634
- const params = new URLSearchParams(
635
- removedUndefinedProperties(
636
- {
637
- text: `${encodeURIComponent(query || '')}`,
638
- page: `${page || ''}`,
639
- limit: `${limit || ''}`,
640
- workspaceId: `${workspaceId || ''}`,
641
- },
642
- true
643
- )
644
- );
645
- return await this.get(`/apps?${params.toString()}`);
646
- }
647
-
648
- async installApp(
649
- workspaceId: PrismeaiAPI.InstallAppInstance.PathParameters['workspaceId'],
650
- body: PrismeaiAPI.InstallAppInstance.RequestBody
651
- ): Promise<Fetched<PrismeaiAPI.InstallAppInstance.Responses.$200>> {
652
- return await this.post(`/workspaces/${workspaceId}/apps`, body);
653
- }
654
-
655
- async updateApp(
656
- workspaceId: PrismeaiAPI.ConfigureAppInstance.PathParameters['workspaceId'],
657
- slug: PrismeaiAPI.ConfigureAppInstance.PathParameters['slug'],
658
- body: PrismeaiAPI.ConfigureAppInstance.RequestBody
659
- ): Promise<Fetched<PrismeaiAPI.ConfigureAppInstance.Responses.$200>> {
660
- return await this.patch(`/workspaces/${workspaceId}/apps/${slug}`, body);
661
- }
662
-
663
- async uninstallApp(
664
- workspaceId: PrismeaiAPI.UninstallAppInstance.PathParameters['workspaceId'],
665
- slug: PrismeaiAPI.ConfigureAppInstance.PathParameters['slug']
666
- ): Promise<Fetched<PrismeaiAPI.UninstallAppInstance.Responses.$200>> {
667
- return await this.delete(`/workspaces/${workspaceId}/apps/${slug}`);
668
- }
669
-
670
- async publishApp(
671
- body: PrismeaiAPI.PublishApp.RequestBody
672
- ): Promise<Fetched<PrismeaiAPI.PublishApp.Responses.$200>> {
673
- return await this.post(`/apps`, body);
674
- }
675
-
676
- async listAppInstances(
677
- workspaceId: PrismeaiAPI.ListAppInstances.PathParameters['workspaceId']
678
- ): Promise<Fetched<PrismeaiAPI.ListAppInstances.Responses.$200>> {
679
- return await this.get(`/workspaces/${workspaceId}/apps`);
680
- }
681
-
682
- async getAppConfig<T>(
683
- workspaceId: PrismeaiAPI.GetAppInstanceConfig.Parameters.WorkspaceId,
684
- slug: PrismeaiAPI.GetAppInstanceConfig.Parameters.Slug
685
- ): Promise<T> {
686
- const config = await this.get<T>(
687
- `/workspaces/${workspaceId}/apps/${slug}/config`
688
- );
689
- return config as T;
690
- }
691
-
692
- async updateAppConfig(
693
- workspaceId: PrismeaiAPI.UpdateAppInstanceConfig.Parameters.WorkspaceId,
694
- slug: PrismeaiAPI.UpdateAppInstanceConfig.Parameters.Slug,
695
- config: any
696
- ): Promise<PrismeaiAPI.UpdateAppInstanceConfig.Responses.$200['config']> {
697
- await this.patch<Prismeai.AppInstance>(
698
- `/workspaces/${workspaceId}/apps/${slug}/config`,
699
- { ...config }
700
- );
701
- return config;
702
- }
703
-
704
- async getAppInstance(
705
- workspaceId: string,
706
- slug: string
707
- ): Promise<Fetched<PrismeaiAPI.GetAppInstance.Responses.$200>> {
708
- return this.get(`/workspaces/${workspaceId}/apps/${slug}`);
709
- }
710
-
711
- async saveAppInstance(
712
- workspaceId: PrismeaiAPI.ConfigureAppInstance.Parameters.WorkspaceId,
713
- slug: PrismeaiAPI.ConfigureAppInstance.Parameters.Slug,
714
- appInstance: PrismeaiAPI.ConfigureAppInstance.RequestBody
715
- ): Promise<Fetched<PrismeaiAPI.ConfigureAppInstance.Responses.$200>> {
716
- const response = await this.patch<Prismeai.DetailedAppInstance>(
717
- `/workspaces/${workspaceId}/apps/${slug}`,
718
- { ...appInstance }
719
- );
720
- return response;
721
- }
722
-
723
- async uploadFiles(files: string | string[], workspaceId: string) {
724
- const formData = new FormData();
725
- (Array.isArray(files) ? files : [files]).forEach((file) => {
726
- try {
727
- formData.append('file', ...dataURItoBlob(file));
728
- } catch {}
729
- });
730
- try {
731
- return await this._fetch<PrismeaiAPI.UploadFile.Responses.$200>(
732
- `/workspaces/${workspaceId}/files`,
733
- {
734
- method: 'POST',
735
- body: formData,
736
- }
737
- );
738
- } catch (e) {}
739
- return [];
740
- }
741
-
742
- async replaceAllImagesData(original: any, workspaceId: string) {
743
- const key = '…uploading-';
744
- const toUpload: string[] = [];
745
- const searchImages = (mayHaveImage: any, uploaded?: string[]) => {
746
- switch (typeof mayHaveImage) {
747
- case 'string':
748
- if (uploaded && mayHaveImage.match(key)) {
749
- // Replace with url
750
- const [, index] = mayHaveImage.split(key);
751
- return uploaded[+index];
752
- }
753
- if (mayHaveImage.match(/^data:/)) {
754
- toUpload.push(mayHaveImage);
755
- return `${key}${toUpload.length - 1}`;
756
- }
757
- return mayHaveImage;
758
- case 'object':
759
- const isArray = Array.isArray(mayHaveImage);
760
- const withImagesUrl = isArray
761
- ? [...mayHaveImage]
762
- : { ...mayHaveImage };
763
- for (const key of Object.keys(withImagesUrl)) {
764
- withImagesUrl[key] = searchImages(withImagesUrl[key], uploaded);
765
- }
766
- return withImagesUrl;
767
- default:
768
- return mayHaveImage;
769
- }
770
- };
771
-
772
- const searching = searchImages(original);
773
-
774
- if (toUpload.length === 0) return original;
775
-
776
- const uploaded = await this.uploadFiles(toUpload, workspaceId);
777
-
778
- const replaced = searchImages(
779
- searching,
780
- uploaded.map(({ url }) => url)
781
- );
782
-
783
- return replaced;
784
- }
785
-
786
- async callAutomation(
787
- workspaceId: string,
788
- automation: string,
789
- params?: any
790
- ): Promise<Fetched<any>> {
791
- return this.post(
792
- `/workspaces/${workspaceId}/webhooks/${automation}`,
793
- params
794
- );
795
- }
796
-
797
- async testAutomation({
798
- workspaceId,
799
- automation,
800
- payload,
801
- }: {
802
- workspaceId: string;
803
- automation: string;
804
- payload?: Record<string, any>;
805
- }): Promise<Fetched<any>> {
806
- return this.post(`/workspaces/${workspaceId}/test/${automation}`, {
807
- payload,
808
- });
809
- }
810
-
811
- async getWorkspaceUsage(
812
- workspaceId: PrismeaiAPI.WorkspaceUsage.Parameters.WorkspaceId,
813
- {
814
- afterDate,
815
- beforeDate,
816
- details,
817
- }: {
818
- afterDate?: PrismeaiAPI.WorkspaceUsage.Parameters.AfterDate;
819
- beforeDate?: PrismeaiAPI.WorkspaceUsage.Parameters.BeforeDate;
820
- details?: PrismeaiAPI.WorkspaceUsage.Parameters.Details;
821
- } = {}
822
- ): Promise<Fetched<PrismeaiAPI.WorkspaceUsage.Responses.$200>> {
823
- const params = new URLSearchParams(
824
- removedUndefinedProperties(
825
- {
826
- afterDate: `${afterDate || ''}`,
827
- beforeDate: `${beforeDate || ''}`,
828
- details: `${details || ''}`,
829
- },
830
- true
831
- )
832
- );
833
-
834
- return this.get(`/workspaces/${workspaceId}/usage?${params.toString()}`);
835
- }
836
-
837
- async importArchive(
838
- archive: File
839
- ): Promise<PrismeaiAPI.ImportNewWorkspace.Responses.$200> {
840
- return new Promise((resolve) => {
841
- const fileReader = new FileReader();
842
- fileReader.addEventListener('load', async ({ target }) => {
843
- const file = target?.result as string;
844
- const formData = new FormData();
845
- formData.append('archive', ...dataURItoBlob(file));
846
- resolve(
847
- await this._fetch<PrismeaiAPI.ImportNewWorkspace.Responses.$200>(
848
- `/workspaces/import`,
849
- {
850
- method: 'POST',
851
- body: formData,
852
- }
853
- )
854
- );
855
- });
856
- fileReader.readAsDataURL(archive);
857
- });
858
- }
859
-
860
- users(id: string = this.user?.id || '') {
861
- if (!id) {
862
- throw new Error();
863
- }
864
- return new UsersEndpoint(id, this);
865
- }
866
- workspaces(id: string) {
867
- return new WorkspacesEndpoint(id, this);
868
- }
869
- }
870
-
871
- export default new Api({ host: 'https://api.eda.prisme.ai' });