@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
@@ -1,246 +0,0 @@
1
- import ApiError from './ApiError';
2
- import Fetcher from './fetcher';
3
- import HTTPError from './HTTPError';
4
-
5
- it('should fetch', async () => {
6
- const fetcher = new Fetcher('http/');
7
- // @ts-ignore
8
- global.fetch = jest.fn(() => ({
9
- ok: true,
10
- headers: new Headers([['foo', 'bar']]),
11
- text() {
12
- return '';
13
- },
14
- clone() {
15
- return { ...this };
16
- },
17
- }));
18
- const o = await fetcher.get('url');
19
- expect(global.fetch).toHaveBeenCalledWith('http/url', {
20
- headers: expect.any(Headers),
21
- method: 'GET',
22
- });
23
- const headers = (global.fetch as jest.Mock).mock.calls[0][1].headers;
24
- expect(headers.get('Access-Control-Allow-Origin')).toBe('*');
25
- expect(headers.get('Content-Type')).toBe('application/json');
26
- });
27
-
28
- it('should fetch with auth', async () => {
29
- const fetcher = new Fetcher('http/');
30
- // @ts-ignore
31
- global.fetch = jest.fn(() => ({
32
- ok: true,
33
- headers: new Headers(),
34
- text() {
35
- return '';
36
- },
37
- clone() {
38
- return { ...this };
39
- },
40
- }));
41
- fetcher.token = 'token';
42
- await fetcher.get('url');
43
- expect(global.fetch).toHaveBeenCalledWith('http/url', {
44
- headers: expect.any(Headers),
45
- method: 'GET',
46
- });
47
- const headers = (global.fetch as jest.Mock).mock.calls[0][1].headers;
48
- expect(headers.get('Access-Control-Allow-Origin')).toBe('*');
49
- expect(headers.get('x-prismeai-token')).toBe('token');
50
- });
51
-
52
- it('should fetch with api key', async () => {
53
- const fetcher = new Fetcher('http/');
54
- // @ts-ignore
55
- global.fetch = jest.fn(() => ({
56
- ok: true,
57
- headers: new Headers(),
58
- text() {
59
- return '';
60
- },
61
- clone() {
62
- return { ...this };
63
- },
64
- }));
65
- fetcher.token = 'token';
66
- fetcher.apiKey = 'api-key';
67
- await fetcher.get('url');
68
- expect(global.fetch).toHaveBeenCalledWith('http/url', {
69
- headers: expect.any(Headers),
70
- method: 'GET',
71
- });
72
- const headers = (global.fetch as jest.Mock).mock.calls[0][1].headers;
73
- expect(headers.get('Access-Control-Allow-Origin')).toBe('*');
74
- expect(headers.get('x-prismeai-token')).toBe('token');
75
- expect(headers.get('x-prismeai-api-key')).toBe('api-key');
76
- });
77
-
78
- it('should fail to fetch', async () => {
79
- const fetcher = new Fetcher('http/');
80
- // @ts-ignore
81
- global.fetch = jest.fn(() => ({
82
- ok: false,
83
- json: () => ({
84
- error: 'error',
85
- message: 'message',
86
- }),
87
- status: 400,
88
- }));
89
- try {
90
- await fetcher.get('url');
91
- } catch (e) {
92
- expect(e).toBeInstanceOf(ApiError);
93
- if (e instanceof ApiError) {
94
- expect(e.error).toBe('error');
95
- expect(e.message).toBe('message');
96
- }
97
- }
98
- expect(global.fetch).toHaveBeenCalledWith('http/url', {
99
- headers: expect.any(Headers),
100
- method: 'GET',
101
- });
102
- });
103
-
104
- it('should fail to fetch with unformatted error', async () => {
105
- const fetcher = new Fetcher('http/');
106
- // @ts-ignore
107
- global.fetch = jest.fn(() => ({
108
- ok: false,
109
- statusText: 'error',
110
- status: 400,
111
- }));
112
- try {
113
- await fetcher.get('url');
114
- } catch (e) {
115
- expect(e).toBeInstanceOf(HTTPError);
116
- if (e instanceof ApiError) {
117
- expect(e.message).toBe('error');
118
- }
119
- }
120
- expect(global.fetch).toHaveBeenCalledWith('http/url', {
121
- headers: expect.any(Headers),
122
- method: 'GET',
123
- });
124
- });
125
-
126
- it('should post', async () => {
127
- const fetcher = new Fetcher('http/');
128
- // @ts-ignore
129
- global.fetch = jest.fn(() => ({
130
- ok: true,
131
- headers: new Headers([['content-type', 'application/json']]),
132
- json() {
133
- return {};
134
- },
135
- clone() {
136
- return { ...this };
137
- },
138
- }));
139
- await fetcher.post('url');
140
- expect(global.fetch).toHaveBeenCalledWith('http/url', {
141
- headers: expect.any(Headers),
142
- method: 'POST',
143
- });
144
- });
145
-
146
- it('should post with body', async () => {
147
- const fetcher = new Fetcher('http/');
148
- // @ts-ignore
149
- global.fetch = jest.fn(() => ({
150
- ok: true,
151
- headers: new Headers([['content-type', 'application/json']]),
152
- json() {
153
- return {};
154
- },
155
- clone() {
156
- return { ...this };
157
- },
158
- }));
159
- await fetcher.post('url', {});
160
- expect(global.fetch).toHaveBeenCalledWith('http/url', {
161
- headers: expect.any(Headers),
162
- method: 'POST',
163
- body: '{}',
164
- });
165
- });
166
-
167
- it('should put', async () => {
168
- const fetcher = new Fetcher('http/');
169
- // @ts-ignore
170
- global.fetch = jest.fn(() => ({
171
- ok: true,
172
- headers: new Headers([['content-type', 'application/json']]),
173
- json() {
174
- return {};
175
- },
176
- clone() {
177
- return { ...this };
178
- },
179
- }));
180
- await fetcher.put('url', {});
181
- expect(global.fetch).toHaveBeenCalledWith('http/url', {
182
- headers: expect.any(Headers),
183
- method: 'PUT',
184
- body: '{}',
185
- });
186
- });
187
-
188
- it('should patch', async () => {
189
- const fetcher = new Fetcher('http/');
190
- // @ts-ignore
191
- global.fetch = jest.fn(() => ({
192
- ok: true,
193
- headers: new Headers([['content-type', 'application/json']]),
194
- json() {
195
- return {};
196
- },
197
- clone() {
198
- return { ...this };
199
- },
200
- }));
201
- await fetcher.patch('url', {});
202
- expect(global.fetch).toHaveBeenCalledWith('http/url', {
203
- headers: expect.any(Headers),
204
- method: 'PATCH',
205
- body: '{}',
206
- });
207
- });
208
-
209
- it('should delete', async () => {
210
- const fetcher = new Fetcher('http/');
211
- // @ts-ignore
212
- global.fetch = jest.fn(() => ({
213
- ok: true,
214
- headers: new Headers([['content-type', 'application/json']]),
215
- json() {
216
- return {};
217
- },
218
- clone() {
219
- return { ...this };
220
- },
221
- }));
222
- await fetcher.delete('url');
223
- expect(global.fetch).toHaveBeenCalledWith('http/url', {
224
- headers: expect.any(Headers),
225
- method: 'DELETE',
226
- });
227
- });
228
-
229
- it('should use formData', async () => {
230
- const fetcher = new Fetcher('http/');
231
- // @ts-ignore
232
- global.fetch = jest.fn(() => ({
233
- ok: true,
234
- headers: new Headers([['content-type', 'application/json']]),
235
- json() {
236
- return {};
237
- },
238
- clone() {
239
- return { ...this };
240
- },
241
- }));
242
- const formData = new FormData();
243
- await fetcher.post('url', formData);
244
- const headers = (global.fetch as jest.Mock).mock.calls[0][1].headers;
245
- expect(headers.has('Content-Type')).toBe(false);
246
- });
package/lib/fetcher.ts DELETED
@@ -1,198 +0,0 @@
1
- import FormData from 'form-data';
2
- import ApiError from './ApiError';
3
- import HTTPError from './HTTPError';
4
- import { wait } from './utils';
5
-
6
- const headersAsObject = (headers: Headers) =>
7
- Array.from(headers).reduce(
8
- (prev, [k, v]) => ({
9
- ...prev,
10
- [k]: v,
11
- }),
12
- {}
13
- );
14
-
15
- export type Fetched<T> = T & {
16
- headers?: Record<string, any>;
17
- };
18
-
19
- function isFormData(data: any): data is FormData {
20
- return !!(data.append && typeof data.append === 'function');
21
- }
22
-
23
- const CSRF_TOKEN_HEADER = 'x-prismeai-csrf-token';
24
-
25
- export class Fetcher {
26
- public host: string;
27
- public token: string | null = null;
28
- public legacyToken: string | null = null;
29
- public overwriteClientId?: string;
30
- private clientIdHeader?: string;
31
- protected _apiKey: string | null = null;
32
- protected _csrfToken: string | null = null;
33
- public language: string | undefined;
34
- public lastReceivedHeaders?: Record<string, any>;
35
-
36
- constructor(host: string, clientIdHeader?: string) {
37
- this.host = host;
38
- this.clientIdHeader = clientIdHeader;
39
- }
40
-
41
- set apiKey(apiKey: string) {
42
- this._apiKey = apiKey;
43
- }
44
-
45
- prepareRequest(url: string, options: RequestInit = {}) {
46
- const headers = new Headers(options.headers || {});
47
-
48
- if (this.token && !headers.has('Authorization')) {
49
- headers.append('Authorization', `Bearer ${this.token}`);
50
- } else if (this.legacyToken && !headers.has('Authorization')) {
51
- headers.append('x-prismeai-token', this.legacyToken);
52
- }
53
-
54
- if (this._apiKey && !headers.has('x-prismeai-apikey')) {
55
- headers.append('x-prismeai-api-key', this._apiKey);
56
- }
57
-
58
- if (this._csrfToken && options.method && options.method !== 'GET') {
59
- headers.append(CSRF_TOKEN_HEADER, this._csrfToken);
60
- }
61
-
62
- if (this.language) {
63
- headers.append('accept-language', this.language);
64
- }
65
-
66
- if (options.body instanceof URLSearchParams) {
67
- headers.set('Content-Type', 'application/x-www-form-urlencoded');
68
- }
69
-
70
- if (
71
- (!options.body || !(options.body instanceof FormData)) &&
72
- !headers.has('Content-Type')
73
- ) {
74
- headers.append('Content-Type', 'application/json');
75
- }
76
-
77
- const fullUrl =
78
- url.startsWith('http://') || url.startsWith('https://')
79
- ? url
80
- : `${this.host}${url}`;
81
- return global.fetch(fullUrl, {
82
- credentials: headers.has('Authorization') ? 'omit' : 'include',
83
- ...options,
84
- headers,
85
- });
86
- }
87
-
88
- protected async _fetch<T>(
89
- url: string,
90
- options: RequestInit = {},
91
- maxRetries: number = 3
92
- ): Promise<T> {
93
- let res: Response;
94
- try {
95
- res = await this.prepareRequest(url, options);
96
- } catch (e: any) {
97
- if (maxRetries > 0 && e.message === 'Load failed') {
98
- await wait(20);
99
- return this._fetch(url, options, --maxRetries);
100
- }
101
- throw e;
102
- }
103
- if (options.redirect === 'manual' && res.status === 0) {
104
- return { redirected: true } as T;
105
- }
106
-
107
- this.lastReceivedHeaders = headersAsObject(res.headers);
108
- if (this.clientIdHeader && this.lastReceivedHeaders[this.clientIdHeader]) {
109
- this.overwriteClientId = this.lastReceivedHeaders[this.clientIdHeader];
110
- }
111
- if (this.lastReceivedHeaders[CSRF_TOKEN_HEADER]) {
112
- this._csrfToken = this.lastReceivedHeaders[CSRF_TOKEN_HEADER];
113
- }
114
- if (!res.ok) {
115
- if (
116
- res.statusText?.length &&
117
- res.statusText.includes('ECONNRESET') &&
118
- maxRetries > 0
119
- ) {
120
- console.log(
121
- `Retrying request towards ${url} as we received ECONNRESET error : ${res.statusText}`
122
- );
123
- await wait(20);
124
- return this._fetch(url, options, --maxRetries);
125
- }
126
- let error;
127
- try {
128
- error = new ApiError(await res.json(), res.status);
129
- } catch (e) {
130
- error = new HTTPError(res.statusText, res.status);
131
- }
132
- throw error;
133
- }
134
-
135
- const contentType = res.headers.get('content-type');
136
- if (contentType && contentType.includes('application/json')) {
137
- try {
138
- const response = (await res.json()) || {};
139
- Object.defineProperty(response, 'headers', {
140
- value: headersAsObject(res.headers),
141
- configurable: false,
142
- enumerable: false,
143
- writable: false,
144
- });
145
- return response as T;
146
- } catch (e) {
147
- return {} as T;
148
- }
149
- }
150
-
151
- const text = await res.text();
152
-
153
- try {
154
- return JSON.parse(text) as T;
155
- } catch {
156
- return text as T;
157
- }
158
- }
159
-
160
- async get<T = any>(url: string) {
161
- return this._fetch<T>(url, {
162
- method: 'GET',
163
- });
164
- }
165
-
166
- async post<T>(url: string, body?: Record<string, any>, opts?: RequestInit) {
167
- return this._fetch<T>(url, {
168
- method: 'POST',
169
- body:
170
- body && !isFormData(body) && !(body instanceof URLSearchParams)
171
- ? JSON.stringify(body)
172
- : (body as BodyInit),
173
- ...opts,
174
- });
175
- }
176
-
177
- async put<T>(url: string, body: Record<string, any>) {
178
- return this._fetch<T>(url, {
179
- method: 'PUT',
180
- body: JSON.stringify(body),
181
- });
182
- }
183
-
184
- async patch<T>(url: string, body: Record<string, any>) {
185
- return this._fetch<T>(url, {
186
- method: 'PATCH',
187
- body: JSON.stringify(body),
188
- });
189
- }
190
-
191
- async delete<T>(url: string) {
192
- return this._fetch<T>(url, {
193
- method: 'DELETE',
194
- });
195
- }
196
- }
197
-
198
- export default Fetcher;
package/lib/types.ts DELETED
@@ -1,21 +0,0 @@
1
- import '@prisme.ai/types';
2
-
3
- export interface Workspace extends Prismeai.Workspace {
4
- id: string;
5
- updatedAt: Date;
6
- updatedBy: string;
7
- createdAt: Date;
8
- createdBy: string;
9
- }
10
-
11
- export interface Event<DateType extends Date | string>
12
- extends Omit<Prismeai.PrismeEvent, 'createdAt'> {
13
- createdAt: DateType;
14
- }
15
-
16
- export type EventsFilters = Record<string, string> & {
17
- afterDate?: PrismeaiAPI.EventsLongpolling.Parameters.AfterDate;
18
- beforeDate?: PrismeaiAPI.EventsLongpolling.Parameters.BeforeDate;
19
- text?: PrismeaiAPI.EventsLongpolling.Parameters.Text;
20
- query?: PrismeaiAPI.EventsLongpolling.Parameters.Query;
21
- };
package/lib/utils.test.ts DELETED
@@ -1,38 +0,0 @@
1
- import { removedUndefinedProperties } from './utils';
2
-
3
- it('should remove undefined keys', () => {
4
- const myObject = {
5
- first: 'one',
6
- second: 'second',
7
- third: '',
8
- fourth: undefined,
9
- fifth: 5,
10
- };
11
-
12
- const newObject = removedUndefinedProperties(myObject);
13
-
14
- expect(newObject).toStrictEqual({
15
- first: 'one',
16
- second: 'second',
17
- third: '',
18
- fifth: 5,
19
- });
20
- });
21
-
22
- it('should remove empty strings if specified', () => {
23
- const myObject = {
24
- first: 'one',
25
- second: 'second',
26
- third: '',
27
- fourth: undefined,
28
- fifth: 5,
29
- };
30
-
31
- const newObject = removedUndefinedProperties(myObject, true);
32
-
33
- expect(newObject).toStrictEqual({
34
- first: 'one',
35
- second: 'second',
36
- fifth: 5,
37
- });
38
- });
package/lib/utils.ts DELETED
@@ -1,51 +0,0 @@
1
- export const removedUndefinedProperties = (
2
- obj: any,
3
- removeEmptyStrings: boolean = false
4
- ) =>
5
- Object.entries(obj).reduce((newObject: any, [key, value]) => {
6
- if (value !== undefined) {
7
- if (!(removeEmptyStrings && value === '')) {
8
- newObject[key] = value;
9
- }
10
- }
11
- return newObject;
12
- }, {});
13
-
14
- export function dataURItoBlob(dataURI: string): [Blob, string] {
15
- // convert base64/URLEncoded data component to raw binary data held in a string
16
- let byteString;
17
- if (dataURI.split(',')[0].indexOf('base64') >= 0)
18
- byteString = atob(dataURI.split(',')[1].split(';')[0]);
19
- else byteString = unescape(dataURI.split(',')[1]);
20
- // separate out the mime component
21
- const metadata = dataURI
22
- .split(';')
23
- .map((v) => v.split(/:/))
24
- .filter((pair) => pair.length === 2);
25
- const [, mimeString = ''] = metadata.find(([k, v]) => k === 'data') || [];
26
- const [, ext] = mimeString.split(/\//);
27
- const [, fileName = `file.${ext}`] =
28
- metadata.find(([k, v]) => k === 'filename') || [];
29
-
30
- const sanitizedFileName = encodeURIComponent(
31
- decodeURIComponent(fileName).replace(/[;,\s]/g, '-')
32
- );
33
-
34
- // write the bytes of the string to a typed array
35
- let ia = new Uint8Array(byteString.length);
36
- for (var i = 0; i < byteString.length; i++) {
37
- ia[i] = byteString.charCodeAt(i);
38
- }
39
-
40
- return [new Blob([ia], { type: mimeString }), sanitizedFileName];
41
- }
42
-
43
- export function isDataURL(file: any): file is string {
44
- return !!(typeof file === 'string' && file.match(/^data\:/));
45
- }
46
-
47
- export async function wait(delay: number = 0) {
48
- return new Promise((resolve) => {
49
- setTimeout(resolve, delay);
50
- });
51
- }
package/tsconfig.json DELETED
@@ -1,21 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "es5",
4
- "lib": ["dom", "dom.iterable", "esnext"],
5
- "allowJs": true,
6
- "skipLibCheck": true,
7
- "esModuleInterop": true,
8
- "allowSyntheticDefaultImports": true,
9
- "strict": true,
10
- "forceConsistentCasingInFileNames": true,
11
- "noFallthroughCasesInSwitch": true,
12
- "module": "ESNext",
13
- "moduleResolution": "node",
14
- "resolveJsonModule": true,
15
- "isolatedModules": false,
16
- "noEmit": true,
17
- "declaration": true
18
- },
19
- "include": ["./index.ts", "lib/**/*", "openapi/*"],
20
- "exclude": ["node_modules", "dist"]
21
- }