@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,94 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var _tslib = require('../../../_virtual/_tslib.js');
6
- var utils = require('../utils.js');
7
-
8
- var UsersEndpoint = /** @class */ (function () {
9
- function UsersEndpoint(id, api) {
10
- this.id = id;
11
- this.api = api;
12
- }
13
- UsersEndpoint.prototype.update = function (data) {
14
- return _tslib.__awaiter(this, void 0, void 0, function () {
15
- return _tslib.__generator(this, function (_a) {
16
- switch (_a.label) {
17
- case 0:
18
- if (!utils.isDataURL(data.photo)) return [3 /*break*/, 2];
19
- return [4 /*yield*/, this.updatePhoto(data.photo)];
20
- case 1:
21
- _a.sent();
22
- delete data.photo;
23
- _a.label = 2;
24
- case 2: return [4 /*yield*/, this.api.patch('/user', data)];
25
- case 3: return [2 /*return*/, _a.sent()];
26
- }
27
- });
28
- });
29
- };
30
- UsersEndpoint.prototype.updatePhoto = function (photo) {
31
- return _tslib.__awaiter(this, void 0, void 0, function () {
32
- var formData;
33
- return _tslib.__generator(this, function (_a) {
34
- switch (_a.label) {
35
- case 0:
36
- if (!utils.isDataURL(photo)) {
37
- throw new Error('Photo must be a dataurl file');
38
- }
39
- formData = new FormData();
40
- formData.append.apply(formData, _tslib.__spreadArray(['photo'], utils.dataURItoBlob(photo), false));
41
- return [4 /*yield*/, this.api.post("/user/photo", formData)];
42
- case 1: return [2 /*return*/, _a.sent()];
43
- }
44
- });
45
- });
46
- };
47
- UsersEndpoint.prototype.setMeta = function (k, v) {
48
- return _tslib.__awaiter(this, void 0, void 0, function () {
49
- var _a;
50
- return _tslib.__generator(this, function (_b) {
51
- switch (_b.label) {
52
- case 0: return [4 /*yield*/, this.api.post("/user/meta", (_a = {},
53
- _a[k] = v,
54
- _a))];
55
- case 1: return [2 /*return*/, _b.sent()];
56
- }
57
- });
58
- });
59
- };
60
- UsersEndpoint.prototype.deleteMeta = function (k) {
61
- return _tslib.__awaiter(this, void 0, void 0, function () {
62
- return _tslib.__generator(this, function (_a) {
63
- switch (_a.label) {
64
- case 0: return [4 /*yield*/, this.api.delete("/user/meta/".concat(k))];
65
- case 1: return [2 /*return*/, _a.sent()];
66
- }
67
- });
68
- });
69
- };
70
- UsersEndpoint.prototype.sendDeleteValidation = function () {
71
- return _tslib.__awaiter(this, void 0, void 0, function () {
72
- return _tslib.__generator(this, function (_a) {
73
- switch (_a.label) {
74
- case 0: return [4 /*yield*/, this.api.delete("/user")];
75
- case 1: return [2 /*return*/, _a.sent()];
76
- }
77
- });
78
- });
79
- };
80
- UsersEndpoint.prototype.delete = function (token) {
81
- return _tslib.__awaiter(this, void 0, void 0, function () {
82
- return _tslib.__generator(this, function (_a) {
83
- switch (_a.label) {
84
- case 0: return [4 /*yield*/, this.api.delete("/users/".concat(this.id, "?token=").concat(token))];
85
- case 1: return [2 /*return*/, _a.sent()];
86
- }
87
- });
88
- });
89
- };
90
- return UsersEndpoint;
91
- }());
92
-
93
- exports.UsersEndpoint = UsersEndpoint;
94
- exports["default"] = UsersEndpoint;
@@ -1,144 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var _tslib = require('../../../_virtual/_tslib.js');
6
- var ImportProcessing = require('../ImportProcessing.js');
7
- var utils = require('../utils.js');
8
- var workspacesVersions = require('./workspacesVersions.js');
9
-
10
- var WorkspacesEndpoint = /** @class */ (function () {
11
- function WorkspacesEndpoint(id, api) {
12
- this.id = id;
13
- this.api = api;
14
- }
15
- Object.defineProperty(WorkspacesEndpoint.prototype, "versions", {
16
- get: function () {
17
- return new workspacesVersions.WorkspacesVersionsEndpoint(this.id, this.api);
18
- },
19
- enumerable: false,
20
- configurable: true
21
- });
22
- WorkspacesEndpoint.prototype.update = function (workspace) {
23
- return _tslib.__awaiter(this, void 0, void 0, function () {
24
- var _a, _b, _c;
25
- return _tslib.__generator(this, function (_d) {
26
- switch (_d.label) {
27
- case 0:
28
- _b = (_a = this.api).patch;
29
- _c = ["/workspaces/".concat(this.id)];
30
- return [4 /*yield*/, this.api.replaceAllImagesData(workspace, this.id)];
31
- case 1: return [4 /*yield*/, _b.apply(_a, _c.concat([_d.sent()]))];
32
- case 2: return [2 /*return*/, _d.sent()];
33
- }
34
- });
35
- });
36
- };
37
- WorkspacesEndpoint.prototype.delete = function () {
38
- return _tslib.__awaiter(this, void 0, void 0, function () {
39
- return _tslib.__generator(this, function (_a) {
40
- switch (_a.label) {
41
- case 0: return [4 /*yield*/, this.api.delete("/workspaces/".concat(this.id))];
42
- case 1: return [2 /*return*/, _a.sent()];
43
- }
44
- });
45
- });
46
- };
47
- WorkspacesEndpoint.prototype.uploadFiles = function (files, opts) {
48
- return _tslib.__awaiter(this, void 0, void 0, function () {
49
- var formData, e_1;
50
- return _tslib.__generator(this, function (_a) {
51
- switch (_a.label) {
52
- case 0:
53
- formData = new FormData();
54
- (Array.isArray(files) ? files : [files]).forEach(function (file) {
55
- try {
56
- formData.append.apply(formData, _tslib.__spreadArray(['file'], utils.dataURItoBlob(file), false));
57
- }
58
- catch (_a) { }
59
- });
60
- if (opts === null || opts === void 0 ? void 0 : opts.expiresAfter) {
61
- formData.append('expiresAfter', "".concat(opts === null || opts === void 0 ? void 0 : opts.expiresAfter));
62
- }
63
- if (typeof (opts === null || opts === void 0 ? void 0 : opts.public) === 'boolean') {
64
- formData.append('public', "".concat(opts === null || opts === void 0 ? void 0 : opts.public));
65
- }
66
- if (typeof (opts === null || opts === void 0 ? void 0 : opts.shareToken) === 'boolean') {
67
- formData.append('shareToken', "".concat(opts === null || opts === void 0 ? void 0 : opts.shareToken));
68
- }
69
- _a.label = 1;
70
- case 1:
71
- _a.trys.push([1, 3, , 4]);
72
- return [4 /*yield*/, this.api.post("/workspaces/".concat(this.id, "/files"), formData)];
73
- case 2: return [2 /*return*/, _a.sent()];
74
- case 3:
75
- e_1 = _a.sent();
76
- console.error(e_1);
77
- return [3 /*break*/, 4];
78
- case 4: return [2 /*return*/, []];
79
- }
80
- });
81
- });
82
- };
83
- WorkspacesEndpoint.prototype.listAppInstances = function () {
84
- return _tslib.__awaiter(this, void 0, void 0, function () {
85
- return _tslib.__generator(this, function (_a) {
86
- switch (_a.label) {
87
- case 0: return [4 /*yield*/, this.api.get("/workspaces/".concat(this.id, "/apps"))];
88
- case 1: return [2 /*return*/, _a.sent()];
89
- }
90
- });
91
- });
92
- };
93
- WorkspacesEndpoint.prototype.getUsage = function (_a) {
94
- var _b = _a === void 0 ? {} : _a, afterDate = _b.afterDate, beforeDate = _b.beforeDate, details = _b.details;
95
- return _tslib.__awaiter(this, void 0, void 0, function () {
96
- var params;
97
- return _tslib.__generator(this, function (_c) {
98
- params = new URLSearchParams(utils.removedUndefinedProperties({
99
- afterDate: "".concat(afterDate || ''),
100
- beforeDate: "".concat(beforeDate || ''),
101
- details: "".concat(details || ''),
102
- }, true));
103
- return [2 /*return*/, this.api.get("/workspaces/".concat(this.id, "/usage?").concat(params.toString()))];
104
- });
105
- });
106
- };
107
- WorkspacesEndpoint.prototype.importArchive = function (archive) {
108
- return _tslib.__awaiter(this, void 0, void 0, function () {
109
- var _this = this;
110
- return _tslib.__generator(this, function (_a) {
111
- return [2 /*return*/, new Promise(function (resolve) {
112
- var fileReader = new FileReader();
113
- fileReader.addEventListener('load', function (_a) {
114
- var target = _a.target;
115
- return _tslib.__awaiter(_this, void 0, void 0, function () {
116
- var file, formData, result;
117
- return _tslib.__generator(this, function (_b) {
118
- switch (_b.label) {
119
- case 0:
120
- file = target === null || target === void 0 ? void 0 : target.result;
121
- formData = new FormData();
122
- formData.append.apply(formData, _tslib.__spreadArray(['archive'], utils.dataURItoBlob(file), false));
123
- return [4 /*yield*/, this.api.post("/workspaces/".concat(this.id, "/import"), formData)];
124
- case 1:
125
- result = _b.sent();
126
- if (result.processing) {
127
- throw new ImportProcessing.ImportProcessingError(result);
128
- }
129
- resolve(result);
130
- return [2 /*return*/];
131
- }
132
- });
133
- });
134
- });
135
- fileReader.readAsDataURL(archive);
136
- })];
137
- });
138
- });
139
- };
140
- return WorkspacesEndpoint;
141
- }());
142
-
143
- exports.WorkspacesEndpoint = WorkspacesEndpoint;
144
- exports["default"] = WorkspacesEndpoint;
@@ -1,40 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var _tslib = require('../../../_virtual/_tslib.js');
6
-
7
- var WorkspacesVersionsEndpoint = /** @class */ (function () {
8
- function WorkspacesVersionsEndpoint(workspaceId, api) {
9
- this.workspaceId = workspaceId;
10
- this.api = api;
11
- }
12
- WorkspacesVersionsEndpoint.prototype.create = function (version) {
13
- return this.api.post("/workspaces/".concat(this.workspaceId, "/versions"), version);
14
- };
15
- WorkspacesVersionsEndpoint.prototype.rollback = function (versionId, opts) {
16
- return this.api.post("/workspaces/".concat(this.workspaceId, "/versions/").concat(versionId, "/pull"), opts);
17
- };
18
- WorkspacesVersionsEndpoint.prototype.export = function (version) {
19
- if (version === void 0) { version = 'current'; }
20
- return _tslib.__awaiter(this, void 0, void 0, function () {
21
- var res, _a;
22
- return _tslib.__generator(this, function (_b) {
23
- switch (_b.label) {
24
- case 0: return [4 /*yield*/, this.api.prepareRequest("/workspaces/".concat(this.workspaceId, "/versions/").concat(version, "/export"), {
25
- method: 'post',
26
- })];
27
- case 1:
28
- res = _b.sent();
29
- _a = Blob.bind;
30
- return [4 /*yield*/, res.arrayBuffer()];
31
- case 2: return [2 /*return*/, new (_a.apply(Blob, [void 0, [_b.sent()], { type: 'application/zip' }]))()];
32
- }
33
- });
34
- });
35
- };
36
- return WorkspacesVersionsEndpoint;
37
- }());
38
-
39
- exports.WorkspacesVersionsEndpoint = WorkspacesVersionsEndpoint;
40
- exports["default"] = WorkspacesVersionsEndpoint;
@@ -1,169 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var _tslib = require('../../_virtual/_tslib.js');
6
- var io = require('socket.io-client');
7
-
8
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
-
10
- var io__default = /*#__PURE__*/_interopDefaultLegacy(io);
11
-
12
- var Events = /** @class */ (function () {
13
- function Events(_a) {
14
- var workspaceId = _a.workspaceId, token = _a.token, legacyToken = _a.legacyToken, apiKey = _a.apiKey, _b = _a.apiHost, apiHost = _b === void 0 ? 'https://api.eda.prisme.ai' : _b, filters = _a.filters, api = _a.api, transports = _a.transports;
15
- var _this = this;
16
- this.listeners = new Map();
17
- this.workspaceId = workspaceId;
18
- var queryString = new URLSearchParams(filters || {}).toString();
19
- var fullQueryString = queryString ? "?".concat(queryString) : '';
20
- var extraHeaders = token
21
- ? {
22
- authorization: "Bearer ".concat(token),
23
- }
24
- : { 'x-prismeai-token': legacyToken };
25
- this.lastReceivedEventDate = new Date();
26
- if (apiKey) {
27
- extraHeaders['x-prismeai-api-key'] = apiKey;
28
- }
29
- this.filters = [filters || {}];
30
- this.listenedUserTopics = new Map();
31
- this.client = io__default["default"]("".concat(apiHost, "/workspaces/").concat(workspaceId, "/events").concat(fullQueryString), {
32
- extraHeaders: extraHeaders,
33
- withCredentials: !extraHeaders.authorization,
34
- transports: transports || ['polling', 'websocket'],
35
- auth: function (cb) {
36
- cb({
37
- // Browser websockets cannot send extraHeaders, so we use socketio-client auth instead
38
- extraHeaders: transports && transports[0] === 'websocket' ? extraHeaders : {},
39
- filters: {
40
- payloadQuery: _this.filters,
41
- },
42
- reuseSocketId: _this.socketId,
43
- });
44
- },
45
- });
46
- this.client.on('connect_error', function (err) {
47
- console.error("Failed websocket connection : ", err);
48
- // revert to classic upgrade
49
- _this.client.io.opts.transports = ['polling', 'websocket'];
50
- });
51
- this.client.on('error', function (err) {
52
- _this.client.io.opts.transports = ['polling', 'websocket'];
53
- });
54
- var onConnect = function () {
55
- // First connection
56
- if (!_this.socketId) {
57
- _this.socketId = _this.client.id;
58
- return;
59
- }
60
- // Retrieve lost history on reconnection
61
- setTimeout(function () { return _tslib.__awaiter(_this, void 0, void 0, function () {
62
- var events;
63
- var _this = this;
64
- return _tslib.__generator(this, function (_a) {
65
- switch (_a.label) {
66
- case 0: return [4 /*yield*/, api.getEvents(workspaceId, _tslib.__assign(_tslib.__assign({}, this.filters[this.filters.length - 1]), { afterDate: this.lastReceivedEventDate.toISOString() }))];
67
- case 1:
68
- events = _a.sent();
69
- events.reverse().forEach(function (event) {
70
- (_this.listeners.get(event.type) || []).forEach(function (listener) {
71
- return listener(event);
72
- });
73
- });
74
- return [2 /*return*/];
75
- }
76
- });
77
- }); }, 2000);
78
- };
79
- this.client.on('connect', onConnect);
80
- this.client.on('disconnect', function () {
81
- if (!_this.lastReceivedEventDate) {
82
- _this.lastReceivedEventDate = new Date();
83
- }
84
- // Make sure we reconnect with current filters & socketId
85
- _this.client.auth = _tslib.__assign(_tslib.__assign({}, _this.client.auth), { filters: {
86
- payloadQuery: _this.filters,
87
- }, reuseSocketId: _this.socketId });
88
- _this.client.off('connect', onConnect);
89
- _this.client.on('connect', onConnect);
90
- });
91
- }
92
- Object.defineProperty(Events.prototype, "socket", {
93
- get: function () {
94
- return this.client;
95
- },
96
- enumerable: false,
97
- configurable: true
98
- });
99
- Events.prototype.destroy = function () {
100
- var _this = this;
101
- this.workspaceId = '';
102
- if (this.client.connected) {
103
- this.client.disconnect();
104
- return;
105
- }
106
- this.client.once('connect', function () {
107
- _this.client.disconnect();
108
- });
109
- };
110
- Events.prototype.all = function (listener) {
111
- var _this = this;
112
- var anyListener = function (eventName, eventData) {
113
- _this.lastReceivedEventDate = new Date(eventData === null || eventData === void 0 ? void 0 : eventData.createdAt);
114
- return listener(eventName, eventData);
115
- };
116
- this.client.onAny(anyListener);
117
- return function () { return _this.client.offAny(anyListener); };
118
- };
119
- Events.prototype.on = function (ev, listener) {
120
- var _this = this;
121
- this.listeners.set(ev, _tslib.__spreadArray(_tslib.__spreadArray([], (this.listeners.get(ev) || []), true), [listener], false));
122
- this.client.on(ev, listener);
123
- return function () {
124
- _this.listeners.set(ev, (_this.listeners.get(ev) || []).filter(function (l) { return l !== listener; }));
125
- _this.client.off(ev, listener);
126
- };
127
- };
128
- Events.prototype.emit = function (event, payload, options) {
129
- this.client.emit('event', {
130
- type: event,
131
- payload: payload,
132
- options: options,
133
- });
134
- };
135
- Events.prototype.listenTopics = function (_a) {
136
- var event = _a.event, topics = _a.topics;
137
- topics = Array.isArray(topics) ? topics : [topics];
138
- this.listenedUserTopics.set(event, topics);
139
- this.filters = [
140
- _tslib.__assign({}, this.filters[0]),
141
- {
142
- 'target.userTopic': Array.from(this.listenedUserTopics).flatMap(function (_a) {
143
- _a[0]; var topics = _a[1];
144
- return topics;
145
- }),
146
- },
147
- ];
148
- this.updateFilters({
149
- payloadQuery: this.filters,
150
- });
151
- };
152
- Events.prototype.updateFilters = function (filters) {
153
- this.client.emit('filters', filters);
154
- };
155
- Events.prototype.once = function (ev, listener) {
156
- var _this = this;
157
- this.client.once(ev, listener);
158
- return function () {
159
- _this.client.off(ev, listener);
160
- };
161
- };
162
- Events.prototype.close = function () {
163
- this.client.close();
164
- };
165
- return Events;
166
- }());
167
-
168
- exports.Events = Events;
169
- exports["default"] = Events;
@@ -1,12 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var fetch = global.fetch;
6
- console.log(fetch);
7
- // @ts-ignore
8
- delete global.fetch;
9
- // @ts-ignore
10
- delete global.XMLHttpRequest;
11
-
12
- exports["default"] = fetch;
@@ -1,213 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var _tslib = require('../../_virtual/_tslib.js');
6
- var FormData = require('form-data');
7
- var ApiError = require('./ApiError.js');
8
- var HTTPError = require('./HTTPError.js');
9
- var utils = require('./utils.js');
10
-
11
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
12
-
13
- var FormData__default = /*#__PURE__*/_interopDefaultLegacy(FormData);
14
-
15
- var headersAsObject = function (headers) {
16
- return Array.from(headers).reduce(function (prev, _a) {
17
- var _b;
18
- var k = _a[0], v = _a[1];
19
- return (_tslib.__assign(_tslib.__assign({}, prev), (_b = {}, _b[k] = v, _b)));
20
- }, {});
21
- };
22
- function isFormData(data) {
23
- return !!(data.append && typeof data.append === 'function');
24
- }
25
- var CSRF_TOKEN_HEADER = 'x-prismeai-csrf-token';
26
- var Fetcher = /** @class */ (function () {
27
- function Fetcher(host, clientIdHeader) {
28
- this.token = null;
29
- this.legacyToken = null;
30
- this._apiKey = null;
31
- this._csrfToken = null;
32
- this.host = host;
33
- this.clientIdHeader = clientIdHeader;
34
- }
35
- Object.defineProperty(Fetcher.prototype, "apiKey", {
36
- set: function (apiKey) {
37
- this._apiKey = apiKey;
38
- },
39
- enumerable: false,
40
- configurable: true
41
- });
42
- Fetcher.prototype.prepareRequest = function (url, options) {
43
- if (options === void 0) { options = {}; }
44
- var headers = new Headers(options.headers || {});
45
- if (this.token && !headers.has('Authorization')) {
46
- headers.append('Authorization', "Bearer ".concat(this.token));
47
- }
48
- else if (this.legacyToken && !headers.has('Authorization')) {
49
- headers.append('x-prismeai-token', this.legacyToken);
50
- }
51
- if (this._apiKey && !headers.has('x-prismeai-apikey')) {
52
- headers.append('x-prismeai-api-key', this._apiKey);
53
- }
54
- if (this._csrfToken && options.method && options.method !== 'GET') {
55
- headers.append(CSRF_TOKEN_HEADER, this._csrfToken);
56
- }
57
- if (this.language) {
58
- headers.append('accept-language', this.language);
59
- }
60
- if (options.body instanceof URLSearchParams) {
61
- headers.set('Content-Type', 'application/x-www-form-urlencoded');
62
- }
63
- if ((!options.body || !(options.body instanceof FormData__default["default"])) &&
64
- !headers.has('Content-Type')) {
65
- headers.append('Content-Type', 'application/json');
66
- }
67
- var fullUrl = url.startsWith('http://') || url.startsWith('https://')
68
- ? url
69
- : "".concat(this.host).concat(url);
70
- return global.fetch(fullUrl, _tslib.__assign(_tslib.__assign({ credentials: headers.has('Authorization') ? 'omit' : 'include' }, options), { headers: headers }));
71
- };
72
- Fetcher.prototype._fetch = function (url, options, maxRetries) {
73
- var _a;
74
- if (options === void 0) { options = {}; }
75
- if (maxRetries === void 0) { maxRetries = 3; }
76
- return _tslib.__awaiter(this, void 0, void 0, function () {
77
- var res, e_1, error, _b, contentType, response, text;
78
- return _tslib.__generator(this, function (_c) {
79
- switch (_c.label) {
80
- case 0:
81
- _c.trys.push([0, 2, , 5]);
82
- return [4 /*yield*/, this.prepareRequest(url, options)];
83
- case 1:
84
- res = _c.sent();
85
- return [3 /*break*/, 5];
86
- case 2:
87
- e_1 = _c.sent();
88
- if (!(maxRetries > 0 && e_1.message === 'Load failed')) return [3 /*break*/, 4];
89
- return [4 /*yield*/, utils.wait(20)];
90
- case 3:
91
- _c.sent();
92
- return [2 /*return*/, this._fetch(url, options, --maxRetries)];
93
- case 4: throw e_1;
94
- case 5:
95
- if (options.redirect === 'manual' && res.status === 0) {
96
- return [2 /*return*/, { redirected: true }];
97
- }
98
- this.lastReceivedHeaders = headersAsObject(res.headers);
99
- if (this.clientIdHeader && this.lastReceivedHeaders[this.clientIdHeader]) {
100
- this.overwriteClientId = this.lastReceivedHeaders[this.clientIdHeader];
101
- }
102
- if (this.lastReceivedHeaders[CSRF_TOKEN_HEADER]) {
103
- this._csrfToken = this.lastReceivedHeaders[CSRF_TOKEN_HEADER];
104
- }
105
- if (!!res.ok) return [3 /*break*/, 12];
106
- if (!(((_a = res.statusText) === null || _a === void 0 ? void 0 : _a.length) &&
107
- res.statusText.includes('ECONNRESET') &&
108
- maxRetries > 0)) return [3 /*break*/, 7];
109
- console.log("Retrying request towards ".concat(url, " as we received ECONNRESET error : ").concat(res.statusText));
110
- return [4 /*yield*/, utils.wait(20)];
111
- case 6:
112
- _c.sent();
113
- return [2 /*return*/, this._fetch(url, options, --maxRetries)];
114
- case 7:
115
- error = void 0;
116
- _c.label = 8;
117
- case 8:
118
- _c.trys.push([8, 10, , 11]);
119
- _b = ApiError.ApiError.bind;
120
- return [4 /*yield*/, res.json()];
121
- case 9:
122
- error = new (_b.apply(ApiError.ApiError, [void 0, _c.sent(), res.status]))();
123
- return [3 /*break*/, 11];
124
- case 10:
125
- _c.sent();
126
- error = new HTTPError.HTTPError(res.statusText, res.status);
127
- return [3 /*break*/, 11];
128
- case 11: throw error;
129
- case 12:
130
- contentType = res.headers.get('content-type');
131
- if (!(contentType && contentType.includes('application/json'))) return [3 /*break*/, 16];
132
- _c.label = 13;
133
- case 13:
134
- _c.trys.push([13, 15, , 16]);
135
- return [4 /*yield*/, res.json()];
136
- case 14:
137
- response = (_c.sent()) || {};
138
- Object.defineProperty(response, 'headers', {
139
- value: headersAsObject(res.headers),
140
- configurable: false,
141
- enumerable: false,
142
- writable: false,
143
- });
144
- return [2 /*return*/, response];
145
- case 15:
146
- _c.sent();
147
- return [2 /*return*/, {}];
148
- case 16: return [4 /*yield*/, res.text()];
149
- case 17:
150
- text = _c.sent();
151
- try {
152
- return [2 /*return*/, JSON.parse(text)];
153
- }
154
- catch (_d) {
155
- return [2 /*return*/, text];
156
- }
157
- return [2 /*return*/];
158
- }
159
- });
160
- });
161
- };
162
- Fetcher.prototype.get = function (url) {
163
- return _tslib.__awaiter(this, void 0, void 0, function () {
164
- return _tslib.__generator(this, function (_a) {
165
- return [2 /*return*/, this._fetch(url, {
166
- method: 'GET',
167
- })];
168
- });
169
- });
170
- };
171
- Fetcher.prototype.post = function (url, body, opts) {
172
- return _tslib.__awaiter(this, void 0, void 0, function () {
173
- return _tslib.__generator(this, function (_a) {
174
- return [2 /*return*/, this._fetch(url, _tslib.__assign({ method: 'POST', body: body && !isFormData(body) && !(body instanceof URLSearchParams)
175
- ? JSON.stringify(body)
176
- : body }, opts))];
177
- });
178
- });
179
- };
180
- Fetcher.prototype.put = function (url, body) {
181
- return _tslib.__awaiter(this, void 0, void 0, function () {
182
- return _tslib.__generator(this, function (_a) {
183
- return [2 /*return*/, this._fetch(url, {
184
- method: 'PUT',
185
- body: JSON.stringify(body),
186
- })];
187
- });
188
- });
189
- };
190
- Fetcher.prototype.patch = function (url, body) {
191
- return _tslib.__awaiter(this, void 0, void 0, function () {
192
- return _tslib.__generator(this, function (_a) {
193
- return [2 /*return*/, this._fetch(url, {
194
- method: 'PATCH',
195
- body: JSON.stringify(body),
196
- })];
197
- });
198
- });
199
- };
200
- Fetcher.prototype.delete = function (url) {
201
- return _tslib.__awaiter(this, void 0, void 0, function () {
202
- return _tslib.__generator(this, function (_a) {
203
- return [2 /*return*/, this._fetch(url, {
204
- method: 'DELETE',
205
- })];
206
- });
207
- });
208
- };
209
- return Fetcher;
210
- }());
211
-
212
- exports.Fetcher = Fetcher;
213
- exports["default"] = Fetcher;