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