roboto-js 1.8.2 → 1.8.4

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.
package/dist/rbt_api.js DELETED
@@ -1,2063 +0,0 @@
1
- var _excluded = ["enableRealtime"],
2
- _excluded2 = ["enableRealtime"];
3
- function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
4
- function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
5
- function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; }
6
- function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
7
- function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
8
- function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
9
- function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
10
- function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
11
- function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
12
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
13
- function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
14
- function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
15
- function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
16
- function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
17
- function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
18
- function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
19
- function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
20
- function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
21
- function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
22
- function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
23
- function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
24
- function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
25
- import axios from 'axios';
26
- import CryptoJS from 'crypto-js';
27
- import RbtObject from './rbt_object.js';
28
- import RbtUser from './rbt_user.js';
29
- import RbtFile from './rbt_file.js';
30
- import _ from 'lodash';
31
- import { openDB } from 'idb';
32
- var RbtApi = /*#__PURE__*/function () {
33
- function RbtApi(_ref) {
34
- var baseUrl = _ref.baseUrl,
35
- accesskey = _ref.accesskey,
36
- _ref$authtoken = _ref.authtoken,
37
- authtoken = _ref$authtoken === void 0 ? null : _ref$authtoken,
38
- _ref$apikey = _ref.apikey,
39
- apikey = _ref$apikey === void 0 ? null : _ref$apikey,
40
- _ref$localStorageAdap = _ref.localStorageAdaptor,
41
- localStorageAdaptor = _ref$localStorageAdap === void 0 ? null : _ref$localStorageAdap;
42
- _classCallCheck(this, RbtApi);
43
- this.websocketClient = null;
44
-
45
- // Object cache for sharing instances across multiple load() calls
46
- this._objectCache = new Map();
47
-
48
- // Track pending requests to prevent duplicate loads
49
- this._pendingLoads = new Map();
50
-
51
- // Track what we've already logged to reduce console spam
52
- this._loggedCacheEvents = new Set();
53
- this.axios = axios.create({
54
- baseURL: baseUrl,
55
- headers: {
56
- 'accesskey': accesskey
57
- }
58
- });
59
- this.axios.__rbtApiInstance = this;
60
- if (localStorageAdaptor) {
61
- // must implement getItem, setItem interface
62
- this.localStorageAdaptor = localStorageAdaptor;
63
- } else if (typeof localStorage != 'undefined') {
64
- // browser based local storage
65
- this.localStorageAdaptor = {
66
- getItem: function getItem(key) {
67
- return Promise.resolve(localStorage.getItem(key));
68
- },
69
- setItem: function setItem(key, value) {
70
- return Promise.resolve(localStorage.setItem(key, value));
71
- },
72
- removeItem: function removeItem(key) {
73
- return Promise.resolve(localStorage.removeItem(key));
74
- }
75
- };
76
- }
77
-
78
- // Asynchronous browser hydration: set auth header and in-memory user
79
- // Use storage adaptor if available, otherwise fallback to localStorage
80
- this._initializeFromStorage()["catch"](function (e) {
81
- return console.warn('[RbtApi] Storage initialization failed:', e);
82
- });
83
- this.localDb = null;
84
- this.iac_session = null;
85
- this.appServiceHost = baseUrl;
86
- this.requestCache = {};
87
- this._loadCurrentUserPromise = null;
88
- this._loadCurrentUserExtendedPromise = null;
89
-
90
- // Use the storageAdaptor to get the authToken, if available
91
- this.initAuthToken(authtoken);
92
- this.initApiKey(apikey);
93
- }
94
-
95
- // Initialize authtoken and user from storage (cookies or localStorage)
96
- return _createClass(RbtApi, [{
97
- key: "_initializeFromStorage",
98
- value: function () {
99
- var _initializeFromStorage2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
100
- var token, cookies, _iterator, _step, cookie, _cookie$trim$split, _cookie$trim$split2, name, value, cachedUser, parsed, _t, _t2, _t3;
101
- return _regenerator().w(function (_context) {
102
- while (1) switch (_context.p = _context.n) {
103
- case 0:
104
- if (this.localStorageAdaptor) {
105
- _context.n = 1;
106
- break;
107
- }
108
- return _context.a(2);
109
- case 1:
110
- _context.p = 1;
111
- _context.n = 2;
112
- return this.localStorageAdaptor.getItem('authtoken');
113
- case 2:
114
- token = _context.v;
115
- if (!(!token && typeof document !== 'undefined')) {
116
- _context.n = 9;
117
- break;
118
- }
119
- // Try to get from raw cookie
120
- cookies = document.cookie.split(';');
121
- _iterator = _createForOfIteratorHelper(cookies);
122
- _context.p = 3;
123
- _iterator.s();
124
- case 4:
125
- if ((_step = _iterator.n()).done) {
126
- _context.n = 6;
127
- break;
128
- }
129
- cookie = _step.value;
130
- _cookie$trim$split = cookie.trim().split('='), _cookie$trim$split2 = _slicedToArray(_cookie$trim$split, 2), name = _cookie$trim$split2[0], value = _cookie$trim$split2[1];
131
- if (!(name === 'authtoken')) {
132
- _context.n = 5;
133
- break;
134
- }
135
- token = decodeURIComponent(value);
136
- return _context.a(3, 6);
137
- case 5:
138
- _context.n = 4;
139
- break;
140
- case 6:
141
- _context.n = 8;
142
- break;
143
- case 7:
144
- _context.p = 7;
145
- _t = _context.v;
146
- _iterator.e(_t);
147
- case 8:
148
- _context.p = 8;
149
- _iterator.f();
150
- return _context.f(8);
151
- case 9:
152
- if (token) {
153
- this.authtoken = token;
154
- this.axios.defaults.headers.common['authtoken'] = token;
155
- console.log('[RbtApi] Loaded authtoken from storage adaptor');
156
- }
157
- _context.n = 11;
158
- break;
159
- case 10:
160
- _context.p = 10;
161
- _t2 = _context.v;
162
- console.warn('[RbtApi] Failed to load authtoken from storage adaptor:', _t2);
163
- case 11:
164
- _context.p = 11;
165
- _context.n = 12;
166
- return this.localStorageAdaptor.getItem('rbtUser');
167
- case 12:
168
- cachedUser = _context.v;
169
- if (cachedUser) {
170
- parsed = typeof cachedUser === 'string' ? JSON.parse(cachedUser) : cachedUser;
171
- if (parsed && parsed.id) {
172
- this.currentUser = new RbtUser({
173
- id: parsed.id
174
- }, this.axios);
175
- this.currentUser.setData(parsed);
176
- console.log('[RbtApi] Loaded user from storage adaptor');
177
- }
178
- }
179
- _context.n = 14;
180
- break;
181
- case 13:
182
- _context.p = 13;
183
- _t3 = _context.v;
184
- console.warn('[RbtApi] Failed to load user from storage adaptor:', _t3);
185
- case 14:
186
- return _context.a(2);
187
- }
188
- }, _callee, this, [[11, 13], [3, 7, 8, 9], [1, 10]]);
189
- }));
190
- function _initializeFromStorage() {
191
- return _initializeFromStorage2.apply(this, arguments);
192
- }
193
- return _initializeFromStorage;
194
- }()
195
- }, {
196
- key: "getWebSocketClient",
197
- value: function getWebSocketClient() {
198
- // Reuse existing WebSocket if it's OPEN or CONNECTING (to prevent race condition)
199
- if (this.websocketClient && (this.websocketClient.readyState === WebSocket.OPEN || this.websocketClient.readyState === WebSocket.CONNECTING)) {
200
- return this.websocketClient;
201
- }
202
- var baseUrl = this.axios.defaults.baseURL;
203
- var wsProtocol = baseUrl.startsWith('https') ? 'wss://' : 'ws://';
204
- var wsUrl = baseUrl.replace(/^https?:\/\//, wsProtocol);
205
- console.log('[RbtApi] Creating new WebSocket connection to:', wsUrl + '/realtime');
206
- this.websocketClient = new WebSocket("".concat(wsUrl, "/realtime"));
207
- this._setupWebSocketHandlers(this.websocketClient);
208
- return this.websocketClient;
209
- }
210
- }, {
211
- key: "_setupWebSocketHandlers",
212
- value: function _setupWebSocketHandlers(ws) {
213
- var _this = this;
214
- ws.onopen = function () {
215
- console.log('[RbtApi] WebSocket connected.');
216
- _this._wsReconnectAttempts = 0;
217
- _this._wsConnected = true;
218
-
219
- // Re-subscribe to all objects that were previously subscribed
220
- if (_this._wsSubscriptions) {
221
- var _iterator2 = _createForOfIteratorHelper(_this._wsSubscriptions),
222
- _step2;
223
- try {
224
- for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
225
- var objectId = _step2.value;
226
- ws.send(JSON.stringify({
227
- type: 'subscribe',
228
- objectId: objectId
229
- }));
230
- }
231
- } catch (err) {
232
- _iterator2.e(err);
233
- } finally {
234
- _iterator2.f();
235
- }
236
- }
237
- };
238
- ws.onclose = function (event) {
239
- console.warn('[RbtApi] WebSocket closed:', event.code, event.reason);
240
- _this._wsConnected = false;
241
-
242
- // Attempt reconnection with exponential backoff
243
- if (!_this._wsManualClose && _this._wsReconnectAttempts < 5) {
244
- var delay = Math.min(1000 * Math.pow(2, _this._wsReconnectAttempts), 30000);
245
- console.log("[RbtApi] Attempting reconnection in ".concat(delay, "ms (attempt ").concat(_this._wsReconnectAttempts + 1, "/5)"));
246
- setTimeout(function () {
247
- _this._wsReconnectAttempts++;
248
- _this.websocketClient = null; // Clear the old connection
249
- _this.getWebSocketClient(); // Create new connection
250
- }, delay);
251
- }
252
- };
253
- ws.onerror = function (err) {
254
- console.error('[RbtApi] WebSocket error:', err);
255
- _this._wsConnected = false;
256
- };
257
-
258
- // Handle ping/pong for keep-alive
259
- ws.addEventListener('ping', function () {
260
- if (ws.readyState === WebSocket.OPEN) {
261
- ws.pong();
262
- }
263
- });
264
-
265
- // Initialize connection tracking
266
- this._wsReconnectAttempts = this._wsReconnectAttempts || 0;
267
- this._wsConnected = false;
268
- this._wsManualClose = false;
269
- this._wsSubscriptions = this._wsSubscriptions || new Set();
270
- }
271
-
272
- // Method to track subscriptions for reconnection
273
- }, {
274
- key: "_trackSubscription",
275
- value: function _trackSubscription(objectId) {
276
- if (!this._wsSubscriptions) this._wsSubscriptions = new Set();
277
- this._wsSubscriptions.add(objectId);
278
- }
279
- }, {
280
- key: "_untrackSubscription",
281
- value: function _untrackSubscription(objectId) {
282
- if (this._wsSubscriptions) {
283
- this._wsSubscriptions["delete"](objectId);
284
- }
285
- }
286
-
287
- // Method to gracefully close WebSocket
288
- }, {
289
- key: "closeWebSocket",
290
- value: function closeWebSocket() {
291
- if (this.websocketClient) {
292
- this._wsManualClose = true;
293
- this.websocketClient.close();
294
- this.websocketClient = null;
295
- }
296
- }
297
- }, {
298
- key: "initAuthToken",
299
- value: function () {
300
- var _initAuthToken = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(authtoken) {
301
- return _regenerator().w(function (_context2) {
302
- while (1) switch (_context2.n) {
303
- case 0:
304
- if (!(!authtoken && this.localStorageAdaptor)) {
305
- _context2.n = 2;
306
- break;
307
- }
308
- _context2.n = 1;
309
- return this.localStorageAdaptor.getItem('authtoken');
310
- case 1:
311
- authtoken = _context2.v;
312
- case 2:
313
- if (authtoken) {
314
- this.authtoken = authtoken;
315
- this.axios.defaults.headers.common['authtoken'] = this.authtoken;
316
- }
317
- case 3:
318
- return _context2.a(2);
319
- }
320
- }, _callee2, this);
321
- }));
322
- function initAuthToken(_x) {
323
- return _initAuthToken.apply(this, arguments);
324
- }
325
- return initAuthToken;
326
- }()
327
- }, {
328
- key: "initApiKey",
329
- value: function () {
330
- var _initApiKey = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3(apikey) {
331
- return _regenerator().w(function (_context3) {
332
- while (1) switch (_context3.n) {
333
- case 0:
334
- if (!(!apikey && this.localStorageAdaptor)) {
335
- _context3.n = 2;
336
- break;
337
- }
338
- _context3.n = 1;
339
- return this.localStorageAdaptor.getItem('apikey');
340
- case 1:
341
- apikey = _context3.v;
342
- case 2:
343
- if (apikey) {
344
- this.apikey = apikey;
345
- this.axios.defaults.headers.common['apikey'] = this.apikey;
346
- }
347
- case 3:
348
- return _context3.a(2);
349
- }
350
- }, _callee3, this);
351
- }));
352
- function initApiKey(_x2) {
353
- return _initApiKey.apply(this, arguments);
354
- }
355
- return initApiKey;
356
- }()
357
- }, {
358
- key: "initLocalDb",
359
- value: function () {
360
- var _initLocalDb = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4() {
361
- return _regenerator().w(function (_context4) {
362
- while (1) switch (_context4.n) {
363
- case 0:
364
- _context4.n = 1;
365
- return openDB('RBTFileDatabase', 1, {
366
- upgrade: function upgrade(db) {
367
- if (!db.objectStoreNames.contains('files')) {
368
- db.createObjectStore('files', {
369
- autoIncrement: true
370
- });
371
- }
372
- }
373
- });
374
- case 1:
375
- this.localDb = _context4.v;
376
- case 2:
377
- return _context4.a(2);
378
- }
379
- }, _callee4, this);
380
- }));
381
- function initLocalDb() {
382
- return _initLocalDb.apply(this, arguments);
383
- }
384
- return initLocalDb;
385
- }()
386
- }, {
387
- key: "setAppServiceHost",
388
- value: function setAppServiceHost(host) {
389
- this.appServiceHost = host;
390
- this.axios.defaults.baseURL = host;
391
- }
392
- }, {
393
- key: "setSiteEnv",
394
- value: function setSiteEnv(siteEnv) {
395
- this.siteEnv = siteEnv;
396
- }
397
- }, {
398
- key: "getSiteEnv",
399
- value: function getSiteEnv() {
400
- var key = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
401
- if (key) {
402
- return this.siteEnv[key];
403
- }
404
- return this.siteEnv;
405
- }
406
- }, {
407
- key: "registerTypedefs",
408
- value: function () {
409
- var _registerTypedefs = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee5(typedefs) {
410
- var response, _t4;
411
- return _regenerator().w(function (_context5) {
412
- while (1) switch (_context5.p = _context5.n) {
413
- case 0:
414
- _context5.p = 0;
415
- _context5.n = 1;
416
- return this.axios.post('/api/doctree/registerTypedefs', [{
417
- typedefs: typedefs
418
- }]);
419
- case 1:
420
- response = _context5.v;
421
- return _context5.a(2, response.data);
422
- case 2:
423
- _context5.p = 2;
424
- _t4 = _context5.v;
425
- this._handleError(_t4);
426
- case 3:
427
- return _context5.a(2);
428
- }
429
- }, _callee5, this, [[0, 2]]);
430
- }));
431
- function registerTypedefs(_x3) {
432
- return _registerTypedefs.apply(this, arguments);
433
- }
434
- return registerTypedefs;
435
- }()
436
- /**
437
- * Logs in a user and stores the authToken.
438
- *
439
- * @param {Object} params - The login parameters.
440
- * @param {string} params.email - The email of the user.
441
- * @param {string} params.password - The password of the user.
442
- * @param {string} params.code - The password of the user.
443
- * @returns {Promise<Object>} - The response data from the API.
444
- */
445
- }, {
446
- key: "login",
447
- value: (function () {
448
- var _login = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee6(params) {
449
- var response, _this$iac_session, _t5;
450
- return _regenerator().w(function (_context6) {
451
- while (1) switch (_context6.p = _context6.n) {
452
- case 0:
453
- _context6.p = 0;
454
- _context6.n = 1;
455
- return this.axios.post('/user_service/loginUser', [{
456
- email: params.email,
457
- password: params.password ? CryptoJS.MD5(params.password).toString(CryptoJS.enc.Hex) : null,
458
- // legacy hash password (md5)
459
- passwd: params.password || null,
460
- // current password
461
- code: params.code || null // single-use signon code (password resets)
462
- }]);
463
- case 1:
464
- response = _context6.v;
465
- if (!(response.data.ok === false)) {
466
- _context6.n = 2;
467
- break;
468
- }
469
- return _context6.a(2, this._handleError(response));
470
- case 2:
471
- this.iac_session = response.data;
472
- this.currentUser = this.iac_session ? new RbtUser(this.iac_session.user, this.axios) : null;
473
- // update axios instance headers with authtoken
474
- this.axios.defaults.headers.common['authtoken'] = response.data.authToken;
475
- this.authtoken = response.data.authToken;
476
- if (!this.localStorageAdaptor) {
477
- _context6.n = 4;
478
- break;
479
- }
480
- _context6.n = 3;
481
- return this.localStorageAdaptor.setItem('authtoken', response.data.authToken);
482
- case 3:
483
- if (!((_this$iac_session = this.iac_session) !== null && _this$iac_session !== void 0 && _this$iac_session.user)) {
484
- _context6.n = 4;
485
- break;
486
- }
487
- _context6.n = 4;
488
- return this.localStorageAdaptor.setItem('rbtUser', JSON.stringify(this.iac_session.user));
489
- case 4:
490
- return _context6.a(2, response.data);
491
- case 5:
492
- _context6.p = 5;
493
- _t5 = _context6.v;
494
- this._handleError(_t5);
495
- case 6:
496
- return _context6.a(2);
497
- }
498
- }, _callee6, this, [[0, 5]]);
499
- }));
500
- function login(_x4) {
501
- return _login.apply(this, arguments);
502
- }
503
- return login;
504
- }())
505
- }, {
506
- key: "loginWithOauth",
507
- value: function () {
508
- var _loginWithOauth = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee7(userData) {
509
- var response, _t6;
510
- return _regenerator().w(function (_context7) {
511
- while (1) switch (_context7.p = _context7.n) {
512
- case 0:
513
- _context7.p = 0;
514
- _context7.n = 1;
515
- return this.post('/api/account/registerOrSigninOauth', userData);
516
- case 1:
517
- response = _context7.v;
518
- if (!(response.ok === false)) {
519
- _context7.n = 2;
520
- break;
521
- }
522
- return _context7.a(2, this._handleError(response));
523
- case 2:
524
- this.iac_session = response;
525
- this.currentUser = this.iac_session ? new RbtUser(this.iac_session.user, this.axios) : null;
526
- // update axios instance headers with authtoken
527
- this.axios.defaults.headers.common['authtoken'] = response.authToken;
528
- this.authtoken = response.authToken;
529
- if (!this.localStorageAdaptor) {
530
- _context7.n = 3;
531
- break;
532
- }
533
- _context7.n = 3;
534
- return this.localStorageAdaptor.setItem('authtoken', response.authToken);
535
- case 3:
536
- return _context7.a(2, response);
537
- case 4:
538
- _context7.p = 4;
539
- _t6 = _context7.v;
540
- this._handleError(_t6);
541
- case 5:
542
- return _context7.a(2);
543
- }
544
- }, _callee7, this, [[0, 4]]);
545
- }));
546
- function loginWithOauth(_x5) {
547
- return _loginWithOauth.apply(this, arguments);
548
- }
549
- return loginWithOauth;
550
- }()
551
- }, {
552
- key: "logout",
553
- value: function () {
554
- var _logout = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee8() {
555
- var response, _t7;
556
- return _regenerator().w(function (_context8) {
557
- while (1) switch (_context8.p = _context8.n) {
558
- case 0:
559
- _context8.p = 0;
560
- _context8.n = 1;
561
- return this.axios.post('/user_service/logoutUser');
562
- case 1:
563
- response = _context8.v;
564
- if (!(response.data.ok === false)) {
565
- _context8.n = 2;
566
- break;
567
- }
568
- return _context8.a(2, this._handleError(response));
569
- case 2:
570
- // Clear the iac_session and remove the auth token from axios headers
571
- this.iac_session = null;
572
- this.currentUser = null;
573
- this.authtoken = null;
574
- if (this.axios.defaults.headers.common['authtoken']) {
575
- delete this.axios.defaults.headers.common['authtoken'];
576
- }
577
-
578
- // Clear localStorage if it's being used
579
- if (!this.localStorageAdaptor) {
580
- _context8.n = 3;
581
- break;
582
- }
583
- _context8.n = 3;
584
- return this.localStorageAdaptor.removeItem('authtoken');
585
- case 3:
586
- return _context8.a(2, response.data);
587
- case 4:
588
- _context8.p = 4;
589
- _t7 = _context8.v;
590
- this._handleError(_t7);
591
- case 5:
592
- return _context8.a(2);
593
- }
594
- }, _callee8, this, [[0, 4]]);
595
- }));
596
- function logout() {
597
- return _logout.apply(this, arguments);
598
- }
599
- return logout;
600
- }()
601
- }, {
602
- key: "getCurrentUser",
603
- value: function getCurrentUser() {
604
- if (this.currentUser) {
605
- return this.currentUser;
606
- }
607
- }
608
- }, {
609
- key: "loadCurrentUser",
610
- value: function () {
611
- var _loadCurrentUser = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee0() {
612
- var _this2 = this;
613
- var result, _t8;
614
- return _regenerator().w(function (_context0) {
615
- while (1) switch (_context0.p = _context0.n) {
616
- case 0:
617
- _context0.p = 0;
618
- if (!this._loadCurrentUserPromise) {
619
- _context0.n = 1;
620
- break;
621
- }
622
- return _context0.a(2, this._loadCurrentUserPromise);
623
- case 1:
624
- if (!this.currentUser) {
625
- _context0.n = 2;
626
- break;
627
- }
628
- return _context0.a(2, this.currentUser);
629
- case 2:
630
- if (!this.apikey) {
631
- _context0.n = 3;
632
- break;
633
- }
634
- return _context0.a(2, null);
635
- case 3:
636
- if (!this.authtoken) {
637
- _context0.n = 5;
638
- break;
639
- }
640
- this._loadCurrentUserPromise = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee9() {
641
- var response, _response$user;
642
- return _regenerator().w(function (_context9) {
643
- while (1) switch (_context9.n) {
644
- case 0:
645
- _context9.n = 1;
646
- return _this2.refreshAuthToken(_this2.authtoken);
647
- case 1:
648
- response = _context9.v;
649
- if (response) {
650
- _context9.n = 2;
651
- break;
652
- }
653
- return _context9.a(2, null);
654
- case 2:
655
- if (!(response !== null && response !== void 0 && response.user)) {
656
- _context9.n = 3;
657
- break;
658
- }
659
- _this2.currentUser = new RbtUser({
660
- id: response === null || response === void 0 || (_response$user = response.user) === null || _response$user === void 0 ? void 0 : _response$user.id
661
- }, _this2.axios);
662
- _this2.currentUser.setData(response.user);
663
- if (!_this2.localStorageAdaptor) {
664
- _context9.n = 3;
665
- break;
666
- }
667
- _context9.n = 3;
668
- return _this2.localStorageAdaptor.setItem('rbtUser', JSON.stringify(response.user));
669
- case 3:
670
- return _context9.a(2, _this2.currentUser);
671
- }
672
- }, _callee9);
673
- }))();
674
- _context0.n = 4;
675
- return this._loadCurrentUserPromise;
676
- case 4:
677
- result = _context0.v;
678
- this._loadCurrentUserPromise = null;
679
- return _context0.a(2, result);
680
- case 5:
681
- this.currentUser = null;
682
- case 6:
683
- return _context0.a(2, null);
684
- case 7:
685
- _context0.p = 7;
686
- _t8 = _context0.v;
687
- return _context0.a(2, this._handleError(_t8));
688
- }
689
- }, _callee0, this, [[0, 7]]);
690
- }));
691
- function loadCurrentUser() {
692
- return _loadCurrentUser.apply(this, arguments);
693
- }
694
- return loadCurrentUser;
695
- }()
696
- }, {
697
- key: "confirmUserEmail",
698
- value: function () {
699
- var _confirmUserEmail = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee1(confirmCode) {
700
- var params, response, _t9;
701
- return _regenerator().w(function (_context1) {
702
- while (1) switch (_context1.p = _context1.n) {
703
- case 0:
704
- params = {
705
- emailConfirmCode: confirmCode
706
- };
707
- _context1.p = 1;
708
- _context1.n = 2;
709
- return this.axios.post('/user_service/confirmUserEmail', [params]);
710
- case 2:
711
- response = _context1.v;
712
- if (!(response.data.ok === false)) {
713
- _context1.n = 3;
714
- break;
715
- }
716
- return _context1.a(2, this._handleError(response));
717
- case 3:
718
- return _context1.a(2, response.data);
719
- case 4:
720
- _context1.p = 4;
721
- _t9 = _context1.v;
722
- return _context1.a(2, this._handleError(_t9));
723
- }
724
- }, _callee1, this, [[1, 4]]);
725
- }));
726
- function confirmUserEmail(_x6) {
727
- return _confirmUserEmail.apply(this, arguments);
728
- }
729
- return confirmUserEmail;
730
- }()
731
- }, {
732
- key: "loadCurrentUserExtended",
733
- value: function () {
734
- var _loadCurrentUserExtended = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee11() {
735
- var _this3 = this;
736
- return _regenerator().w(function (_context11) {
737
- while (1) switch (_context11.p = _context11.n) {
738
- case 0:
739
- if (!this._loadCurrentUserExtendedPromise) {
740
- _context11.n = 1;
741
- break;
742
- }
743
- return _context11.a(2, this._loadCurrentUserExtendedPromise);
744
- case 1:
745
- this._loadCurrentUserExtendedPromise = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee10() {
746
- var currentUser;
747
- return _regenerator().w(function (_context10) {
748
- while (1) switch (_context10.n) {
749
- case 0:
750
- _context10.n = 1;
751
- return _this3.loadCurrentUser();
752
- case 1:
753
- currentUser = _context10.v;
754
- if (!currentUser) {
755
- _context10.n = 2;
756
- break;
757
- }
758
- return _context10.a(2, _this3.loadUser(currentUser.id));
759
- case 2:
760
- return _context10.a(2, null);
761
- case 3:
762
- return _context10.a(2);
763
- }
764
- }, _callee10);
765
- }))();
766
- _context11.p = 2;
767
- _context11.n = 3;
768
- return this._loadCurrentUserExtendedPromise;
769
- case 3:
770
- return _context11.a(2, _context11.v);
771
- case 4:
772
- _context11.p = 4;
773
- this._loadCurrentUserExtendedPromise = null;
774
- return _context11.f(4);
775
- case 5:
776
- return _context11.a(2);
777
- }
778
- }, _callee11, this, [[2,, 4, 5]]);
779
- }));
780
- function loadCurrentUserExtended() {
781
- return _loadCurrentUserExtended.apply(this, arguments);
782
- }
783
- return loadCurrentUserExtended;
784
- }()
785
- }, {
786
- key: "loadUser",
787
- value: function () {
788
- var _loadUser = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee13(userId) {
789
- var _this4 = this;
790
- var params, cacheKey, now, existing, p, _t0;
791
- return _regenerator().w(function (_context13) {
792
- while (1) switch (_context13.p = _context13.n) {
793
- case 0:
794
- params = {
795
- id: userId
796
- };
797
- cacheKey = "loadUser:".concat(userId);
798
- now = Date.now();
799
- existing = this.requestCache[cacheKey];
800
- if (!(existing && now - existing.time < 10000)) {
801
- _context13.n = 1;
802
- break;
803
- }
804
- return _context13.a(2, existing.val);
805
- case 1:
806
- _context13.p = 1;
807
- p = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee12() {
808
- var _response$data;
809
- var response, userData, User;
810
- return _regenerator().w(function (_context12) {
811
- while (1) switch (_context12.n) {
812
- case 0:
813
- _context12.n = 1;
814
- return _this4.axios.post('/user_service/loadUser', [params]);
815
- case 1:
816
- response = _context12.v;
817
- userData = response === null || response === void 0 || (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.user;
818
- User = new RbtUser({
819
- id: userData.id
820
- }, _this4.axios);
821
- User.setData(userData);
822
- return _context12.a(2, User);
823
- }
824
- }, _callee12);
825
- }))();
826
- this.requestCache[cacheKey] = {
827
- val: p,
828
- time: now
829
- };
830
- _context13.n = 2;
831
- return p;
832
- case 2:
833
- return _context13.a(2, _context13.v);
834
- case 3:
835
- _context13.p = 3;
836
- _t0 = _context13.v;
837
- return _context13.a(2, this._handleError(_t0));
838
- }
839
- }, _callee13, this, [[1, 3]]);
840
- }));
841
- function loadUser(_x7) {
842
- return _loadUser.apply(this, arguments);
843
- }
844
- return loadUser;
845
- }()
846
- }, {
847
- key: "refreshAuthToken",
848
- value: function () {
849
- var _refreshAuthToken = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee14(authtoken) {
850
- var promise, response, _t1;
851
- return _regenerator().w(function (_context14) {
852
- while (1) switch (_context14.p = _context14.n) {
853
- case 0:
854
- if (this.appServiceHost) {
855
- _context14.n = 1;
856
- break;
857
- }
858
- console.warn('RBTTOK not initialized');
859
- return _context14.a(2, false);
860
- case 1:
861
- if (!this.requestCache[authtoken]) {
862
- _context14.n = 2;
863
- break;
864
- }
865
- return _context14.a(2, this.requestCache[authtoken]);
866
- case 2:
867
- _context14.p = 2;
868
- //console.log('RBTTOK Req', authtoken);
869
- // Create a new promise for the token refresh and store it in the cache
870
- promise = this.axios.post('/user_service/refreshAuthToken', [authtoken]);
871
- this.requestCache[authtoken] = promise;
872
-
873
- // Await the promise to get the response
874
- _context14.n = 3;
875
- return promise;
876
- case 3:
877
- response = _context14.v;
878
- //console.log('RBTTOK Response ',response);
879
- // Once the promise resolves, delete it from the cache to allow future refreshes
880
- delete this.requestCache[authtoken];
881
-
882
- // Return the response data
883
- return _context14.a(2, response.data);
884
- case 4:
885
- _context14.p = 4;
886
- _t1 = _context14.v;
887
- // On error, remove the cached promise to allow retries
888
- delete this.requestCache[authtoken];
889
- this._handleError(_t1);
890
- case 5:
891
- return _context14.a(2);
892
- }
893
- }, _callee14, this, [[2, 4]]);
894
- }));
895
- function refreshAuthToken(_x8) {
896
- return _refreshAuthToken.apply(this, arguments);
897
- }
898
- return refreshAuthToken;
899
- }() // async refreshAuthToken(authtoken){
900
- //
901
- // if(!this.appServiceHost){
902
- // console.warn('appServiceHost not initialized');
903
- // return false;
904
- // }
905
- //
906
- // try {
907
- //
908
- // const response = await this.axios.post('/user_service/refreshAuthToken', [authtoken]);
909
- // return response.data;
910
- //
911
- // } catch (e) {
912
- //
913
- // this._handleError(e);
914
- // }
915
- // }
916
- /**
917
- * Registers a new user.
918
- *
919
- * @param {Object} dataHash - The data for the new user.
920
- * @returns {Promise<RbtObject>} - The newly created user as an RbtObject.
921
- *
922
- */
923
- }, {
924
- key: "registerUser",
925
- value: function () {
926
- var _registerUser = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee15() {
927
- var dataHash,
928
- response,
929
- record,
930
- _args15 = arguments,
931
- _t10;
932
- return _regenerator().w(function (_context15) {
933
- while (1) switch (_context15.p = _context15.n) {
934
- case 0:
935
- dataHash = _args15.length > 0 && _args15[0] !== undefined ? _args15[0] : {};
936
- _context15.p = 1;
937
- _context15.n = 2;
938
- return this.axios.post('/user_service/registerUser', [dataHash]);
939
- case 2:
940
- response = _context15.v;
941
- record = response.data;
942
- return _context15.a(2, new RbtUser(record, this.axios));
943
- case 3:
944
- _context15.p = 3;
945
- _t10 = _context15.v;
946
- return _context15.a(2, this._handleError(_t10));
947
- }
948
- }, _callee15, this, [[1, 3]]);
949
- }));
950
- function registerUser() {
951
- return _registerUser.apply(this, arguments);
952
- }
953
- return registerUser;
954
- }()
955
- /**
956
- * Creates a new file in the system.
957
- *
958
- * @param {Object} dataHash - The data for the new file.
959
- * @returns {Promise<RbtFile>} - The newly created file as an RbtFile.
960
- *
961
- */
962
- }, {
963
- key: "createFile",
964
- value: (function () {
965
- var _createFile = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee16(dataHash) {
966
- var response, record, _t11;
967
- return _regenerator().w(function (_context16) {
968
- while (1) switch (_context16.p = _context16.n) {
969
- case 0:
970
- _context16.p = 0;
971
- _context16.n = 1;
972
- return this.axios.post('/object_service/createObject', ['<@filekit.file>', dataHash]);
973
- case 1:
974
- response = _context16.v;
975
- record = response.data;
976
- if (dataHash) {
977
- record.data = dataHash;
978
- }
979
- return _context16.a(2, new RbtFile(record, this.axios, this.localDb));
980
- case 2:
981
- _context16.p = 2;
982
- _t11 = _context16.v;
983
- return _context16.a(2, this._handleError(_t11));
984
- }
985
- }, _callee16, this, [[0, 2]]);
986
- }));
987
- function createFile(_x9) {
988
- return _createFile.apply(this, arguments);
989
- }
990
- return createFile;
991
- }())
992
- }, {
993
- key: "loadFile",
994
- value: function () {
995
- var _loadFile = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee17(id) {
996
- var response, record, _t12;
997
- return _regenerator().w(function (_context17) {
998
- while (1) switch (_context17.p = _context17.n) {
999
- case 0:
1000
- _context17.p = 0;
1001
- _context17.n = 1;
1002
- return this.load('<@filekit.file>', id);
1003
- case 1:
1004
- response = _context17.v;
1005
- if (response) {
1006
- _context17.n = 2;
1007
- break;
1008
- }
1009
- return _context17.a(2, null);
1010
- case 2:
1011
- record = response.toRecord();
1012
- return _context17.a(2, new RbtFile(record, this.axios, this.localDb));
1013
- case 3:
1014
- _context17.p = 3;
1015
- _t12 = _context17.v;
1016
- return _context17.a(2, this._handleError(_t12));
1017
- }
1018
- }, _callee17, this, [[0, 3]]);
1019
- }));
1020
- function loadFile(_x0) {
1021
- return _loadFile.apply(this, arguments);
1022
- }
1023
- return loadFile;
1024
- }()
1025
- }, {
1026
- key: "loadFiles",
1027
- value: function () {
1028
- var _loadFiles = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee18(ids) {
1029
- var _this5 = this;
1030
- var responses, _t13;
1031
- return _regenerator().w(function (_context18) {
1032
- while (1) switch (_context18.p = _context18.n) {
1033
- case 0:
1034
- _context18.p = 0;
1035
- _context18.n = 1;
1036
- return this.load('<@filekit.file>', ids);
1037
- case 1:
1038
- responses = _context18.v;
1039
- if (!(!responses || !Array.isArray(responses))) {
1040
- _context18.n = 2;
1041
- break;
1042
- }
1043
- return _context18.a(2, []);
1044
- case 2:
1045
- return _context18.a(2, responses.map(function (response) {
1046
- var record = response.toRecord();
1047
- return new RbtFile(record, _this5.axios, _this5.localDb);
1048
- }));
1049
- case 3:
1050
- _context18.p = 3;
1051
- _t13 = _context18.v;
1052
- this._handleError(_t13); // Handle errors (log or process as needed)
1053
- return _context18.a(2, []);
1054
- }
1055
- }, _callee18, this, [[0, 3]]);
1056
- }));
1057
- function loadFiles(_x1) {
1058
- return _loadFiles.apply(this, arguments);
1059
- }
1060
- return loadFiles;
1061
- }()
1062
- /**
1063
- * Creates a new object of the given type.
1064
- *
1065
- * @param {string} type - The type of object to create.
1066
- * @param {Object} dataHash - The data for the new object.
1067
- * @param {Object} options - Additional options including enableRealtime.
1068
- * @returns {Promise<RbtObject>} - The newly created object as an RbtObject.
1069
- */
1070
- }, {
1071
- key: "create",
1072
- value: (function () {
1073
- var _create = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee19(type) {
1074
- var dataHash,
1075
- options,
1076
- response,
1077
- record,
1078
- _args19 = arguments,
1079
- _t14;
1080
- return _regenerator().w(function (_context19) {
1081
- while (1) switch (_context19.p = _context19.n) {
1082
- case 0:
1083
- dataHash = _args19.length > 1 && _args19[1] !== undefined ? _args19[1] : {};
1084
- options = _args19.length > 2 && _args19[2] !== undefined ? _args19[2] : {};
1085
- _context19.p = 1;
1086
- _context19.n = 2;
1087
- return this.axios.post('/object_service/createObject', [type, dataHash]);
1088
- case 2:
1089
- response = _context19.v;
1090
- record = response.data;
1091
- if (dataHash) {
1092
- record.data = dataHash;
1093
- }
1094
- return _context19.a(2, new RbtObject(record, this.axios, {
1095
- isNew: true,
1096
- websocketClient: this.websocketClient,
1097
- enableRealtime: options.enableRealtime || false
1098
- }));
1099
- case 3:
1100
- _context19.p = 3;
1101
- _t14 = _context19.v;
1102
- return _context19.a(2, this._handleError(_t14));
1103
- }
1104
- }, _callee19, this, [[1, 3]]);
1105
- }));
1106
- function create(_x10) {
1107
- return _create.apply(this, arguments);
1108
- }
1109
- return create;
1110
- }()
1111
- /**
1112
- * Queries objects of a given type based on specified parameters.
1113
- *
1114
- * @param {string} type - The type of object to query, specified as a doctree.typedef.
1115
- * @param {Object} params - The query parameters, including optional filters and configurations.
1116
- * @returns {Promise<Array<RbtObject>>} - An array of queried objects as RbtObjects.
1117
- *
1118
- * The `params` object can include the following properties:
1119
- * - where: A SQL-like where clause string for filtering the results.
1120
- * - orderBy: An object specifying the ordering of the results. It should include:
1121
- * - column: The attribute name to sort by. This must be either a column in the @doctree.model schema or an indexed type attribute.
1122
- * - direction: The sort direction, either 'ASC' for ascending or 'DESC' for descending.
1123
- * - limit: An object to control the pagination of results. It includes:
1124
- * - offset: The starting point from where to fetch the results.
1125
- * - results: The maximum number of results to return.
1126
- * - requestAttrs: An array of attribute paths to include in the response (e.g., ['id', 'configs.title', 'configs.description']).
1127
- * If not provided, all attributes are returned.
1128
- * - excludeAttrs: An array of attribute paths to exclude from the response (e.g., ['details.log', 'internalData']).
1129
- * Excludes the specified paths and all their subpaths.
1130
- * - resolveReferences: An array of attribute names whose references should be resolved in the returned objects.
1131
- * - timeout: A numerical value in milliseconds to set a maximum time limit for the query execution.
1132
- *
1133
- * Example usage:
1134
- * query("<@testuser>", {
1135
- * where: 'email="tom@pospa.com"',
1136
- * orderBy: { column: 'timeCreated', direction: 'DESC' },
1137
- * limit: { offset: 0, results: 50 },
1138
- * requestAttrs: ['id', 'configs.title'],
1139
- * excludeAttrs: ['details.log'],
1140
- * resolveReferences: ['translatableContent']
1141
- * });
1142
- *
1143
- * Note: A default orderBy is applied if none is provided, ordering items by 'timeCreated' in descending order.
1144
- */
1145
- )
1146
- }, {
1147
- key: "query",
1148
- value: (function () {
1149
- var _query = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee20(type) {
1150
- var _this6 = this;
1151
- var params,
1152
- paramsKey,
1153
- validParams,
1154
- invalidParams,
1155
- defaultOrderBy,
1156
- defaultLimit,
1157
- mergedParams,
1158
- currentTime,
1159
- cacheEntry,
1160
- responsePromise,
1161
- processingPromise,
1162
- _args20 = arguments,
1163
- _t15;
1164
- return _regenerator().w(function (_context20) {
1165
- while (1) switch (_context20.p = _context20.n) {
1166
- case 0:
1167
- params = _args20.length > 1 && _args20[1] !== undefined ? _args20[1] : {};
1168
- _context20.p = 1;
1169
- //console.log('RBTAPI.query INIT', type, params);
1170
- // Validate parameters - reject invalid parameter names
1171
- validParams = ['type', 'where', 'orderBy', 'limit', 'resolveReferences', 'requestAttrs', 'excludeAttrs', 'timeout', 'enableRealtime'];
1172
- invalidParams = Object.keys(params).filter(function (key) {
1173
- return !validParams.includes(key);
1174
- });
1175
- if (!(invalidParams.length > 0)) {
1176
- _context20.n = 2;
1177
- break;
1178
- }
1179
- throw new Error("Invalid query parameter(s): ".concat(invalidParams.join(', '), ". Valid parameters are: ").concat(validParams.join(', ')));
1180
- case 2:
1181
- // Warn if enableRealtime is passed to query() - it should only be used by load()
1182
- if (params.enableRealtime) {
1183
- console.warn('[roboto-js] enableRealtime should not be passed to query(), only to load(). This parameter will be ignored.');
1184
- }
1185
- params.type = type;
1186
-
1187
- // Default ordering and pagination
1188
- defaultOrderBy = {
1189
- orderBy: {
1190
- column: 'timeCreated',
1191
- direction: 'DESC'
1192
- }
1193
- };
1194
- defaultLimit = {
1195
- limit: {
1196
- offset: 0,
1197
- results: 50
1198
- }
1199
- }; // Merge defaults with provided params
1200
- mergedParams = _objectSpread(_objectSpread(_objectSpread({}, defaultOrderBy), defaultLimit), params); // Check cache for an existing request
1201
- currentTime = Date.now();
1202
- paramsKey = JSON.stringify(mergedParams);
1203
- cacheEntry = this.requestCache[paramsKey];
1204
- if (!(cacheEntry && currentTime - cacheEntry.time < 10000)) {
1205
- _context20.n = 3;
1206
- break;
1207
- }
1208
- return _context20.a(2, cacheEntry.val);
1209
- case 3:
1210
- // Create the response promise
1211
- responsePromise = this.axios.post('/object_service/queryObjects', [mergedParams]); // Cache the promise of processing data, not just the raw response
1212
- processingPromise = responsePromise.then(function (response) {
1213
- return _this6._processResponseData(response, params);
1214
- })["catch"](function (e) {
1215
- delete _this6.requestCache[paramsKey]; // Ensure cache cleanup on failure
1216
- //console.log('RBTAPI.query ERROR (Processing)', paramsKey, e);
1217
- return _this6._handleError(e);
1218
- }); // Store the promise of the processed data in the cache
1219
- this.requestCache[paramsKey] = {
1220
- val: processingPromise,
1221
- time: currentTime
1222
- };
1223
-
1224
- // Await the processing promise for this call to get processed data
1225
- _context20.n = 4;
1226
- return processingPromise;
1227
- case 4:
1228
- return _context20.a(2, _context20.v);
1229
- case 5:
1230
- _context20.p = 5;
1231
- _t15 = _context20.v;
1232
- delete this.requestCache[paramsKey]; // Ensure cache cleanup on error
1233
- //console.log('RBTAPI.query ERROR', paramsKey, e);
1234
- return _context20.a(2, this._handleError(_t15));
1235
- }
1236
- }, _callee20, this, [[1, 5]]);
1237
- }));
1238
- function query(_x11) {
1239
- return _query.apply(this, arguments);
1240
- }
1241
- return query;
1242
- }())
1243
- }, {
1244
- key: "_processResponseData",
1245
- value: function _processResponseData(response) {
1246
- var _this7 = this;
1247
- var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1248
- if (response.data.ok === false) {
1249
- return this._handleError(response);
1250
- }
1251
- if (Array.isArray(response.data.items)) {
1252
- //console.log('RBTAPI.query RESPONSE PRE', response.data.items);
1253
-
1254
- // Ensure WebSocket client is available if realtime is requested
1255
- var websocketClient = this.websocketClient;
1256
- if (options.enableRealtime && !websocketClient) {
1257
- console.log('[AgentProviderSync] Creating WebSocket client for realtime objects');
1258
- websocketClient = this.getWebSocketClient();
1259
- }
1260
- console.log('[AgentProviderSync] _processResponseData creating objects with:', {
1261
- enableRealtime: options.enableRealtime || false,
1262
- hasWebSocketClient: !!websocketClient,
1263
- itemCount: response.data.items.length
1264
- });
1265
- response.data.items = response.data.items.map(function (record) {
1266
- return new RbtObject(record, _this7.axios, {
1267
- websocketClient: websocketClient,
1268
- enableRealtime: options.enableRealtime || false
1269
- });
1270
- });
1271
- }
1272
-
1273
- //console.log('RBTAPI.query RESPONSE POST', response.data.items);
1274
- return response.data.items;
1275
- }
1276
-
1277
- /**
1278
- * Loads one or multiple objects of a given type by their IDs.
1279
- *
1280
- * @param {string} type - The type of object to load.
1281
- * @param {Array<string>|string} ids - The ID(s) of the object(s) to load.
1282
- *
1283
- * @returns {Promise<RbtObject|RbtObject[]>} - The loaded object(s) as RbtObject(s).
1284
- */
1285
- }, {
1286
- key: "load",
1287
- value: (function () {
1288
- var _load = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee22(type, ids) {
1289
- var _this8 = this;
1290
- var params,
1291
- mergedParams,
1292
- cachedObjects,
1293
- missingIds,
1294
- _iterator3,
1295
- _step3,
1296
- id,
1297
- _cacheKey,
1298
- cached,
1299
- hitLogKey,
1300
- loadedObjects,
1301
- bulkMissLogKey,
1302
- enableRealtime,
1303
- queryParams,
1304
- _iterator4,
1305
- _step4,
1306
- obj,
1307
- cacheKey,
1308
- setLogKey,
1309
- result,
1310
- _iterator5,
1311
- _step5,
1312
- _id,
1313
- _cacheKey2,
1314
- _obj,
1315
- _cacheKey3,
1316
- _cached,
1317
- _hitLogKey,
1318
- pendingKey,
1319
- missLogKey,
1320
- loadPromise,
1321
- _args22 = arguments,
1322
- _t16;
1323
- return _regenerator().w(function (_context22) {
1324
- while (1) switch (_context22.p = _context22.n) {
1325
- case 0:
1326
- params = _args22.length > 2 && _args22[2] !== undefined ? _args22[2] : {};
1327
- if (type == '<@iac.user>') {
1328
- debugger;
1329
- }
1330
- _context22.p = 1;
1331
- if (!Array.isArray(ids)) {
1332
- _context22.n = 4;
1333
- break;
1334
- }
1335
- // For array requests, check cache for each ID and only load missing ones
1336
- cachedObjects = [];
1337
- missingIds = [];
1338
- _iterator3 = _createForOfIteratorHelper(ids);
1339
- try {
1340
- for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
1341
- id = _step3.value;
1342
- _cacheKey = "".concat(type, ":").concat(id);
1343
- cached = this._objectCache.get(_cacheKey);
1344
- if (cached) {
1345
- // Only log cache hits once per object to reduce spam
1346
- hitLogKey = "hit:".concat(_cacheKey);
1347
- if (!this._loggedCacheEvents.has(hitLogKey)) {
1348
- console.log('[AgentProviderSync] 🎯 roboto.load cache HIT:', {
1349
- type: type,
1350
- id: id,
1351
- hasRealtime: !!cached._realtime,
1352
- requestedRealtime: !!params.enableRealtime
1353
- });
1354
- this._loggedCacheEvents.add(hitLogKey);
1355
- }
1356
-
1357
- // If realtime is requested but cached object doesn't have it, upgrade it
1358
- if (params.enableRealtime && !cached._realtime) {
1359
- console.log('[AgentProviderSync] 🔄 Upgrading cached object to realtime:', {
1360
- type: type,
1361
- id: id
1362
- });
1363
- cached._initRealtime();
1364
- }
1365
- cachedObjects.push(cached);
1366
- } else {
1367
- missingIds.push(id);
1368
- }
1369
- }
1370
-
1371
- // Load missing objects
1372
- } catch (err) {
1373
- _iterator3.e(err);
1374
- } finally {
1375
- _iterator3.f();
1376
- }
1377
- loadedObjects = [];
1378
- if (!(missingIds.length > 0)) {
1379
- _context22.n = 3;
1380
- break;
1381
- }
1382
- // Only log bulk cache miss once
1383
- bulkMissLogKey = "bulk-miss:".concat(type, ":").concat(missingIds.join(','));
1384
- if (!this._loggedCacheEvents.has(bulkMissLogKey)) {
1385
- console.log('[AgentProviderSync] 📦 roboto.load cache MISS, loading:', {
1386
- type: type,
1387
- ids: missingIds
1388
- });
1389
- this._loggedCacheEvents.add(bulkMissLogKey);
1390
- }
1391
-
1392
- // Remove load-specific params that shouldn't be passed to query
1393
- enableRealtime = params.enableRealtime, queryParams = _objectWithoutProperties(params, _excluded);
1394
- mergedParams = _objectSpread(_objectSpread({}, queryParams), {}, {
1395
- where: "id IN (\"".concat(missingIds.join("\",\""), "\")")
1396
- });
1397
- _context22.n = 2;
1398
- return this.query(type, mergedParams);
1399
- case 2:
1400
- loadedObjects = _context22.v;
1401
- // Cache the newly loaded objects
1402
- _iterator4 = _createForOfIteratorHelper(loadedObjects);
1403
- try {
1404
- for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
1405
- obj = _step4.value;
1406
- cacheKey = "".concat(type, ":").concat(obj.id);
1407
- this._objectCache.set(cacheKey, obj);
1408
-
1409
- // Only log cache set once per object to reduce spam
1410
- setLogKey = "set:".concat(cacheKey);
1411
- if (!this._loggedCacheEvents.has(setLogKey)) {
1412
- console.log('[AgentProviderSync] 💾 roboto.load cached object:', {
1413
- type: type,
1414
- id: obj.id
1415
- });
1416
- this._loggedCacheEvents.add(setLogKey);
1417
- }
1418
- }
1419
- } catch (err) {
1420
- _iterator4.e(err);
1421
- } finally {
1422
- _iterator4.f();
1423
- }
1424
- case 3:
1425
- // Return combined results in original order
1426
- result = [];
1427
- _iterator5 = _createForOfIteratorHelper(ids);
1428
- try {
1429
- for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
1430
- _id = _step5.value;
1431
- _cacheKey2 = "".concat(type, ":").concat(_id);
1432
- _obj = this._objectCache.get(_cacheKey2);
1433
- if (_obj) {
1434
- // Ensure realtime is enabled if requested
1435
- if (params.enableRealtime && !_obj._realtime) {
1436
- _obj._initRealtime();
1437
- }
1438
- result.push(_obj);
1439
- }
1440
- }
1441
- } catch (err) {
1442
- _iterator5.e(err);
1443
- } finally {
1444
- _iterator5.f();
1445
- }
1446
- return _context22.a(2, result);
1447
- case 4:
1448
- // For single object requests, check cache first
1449
- _cacheKey3 = "".concat(type, ":").concat(ids);
1450
- _cached = this._objectCache.get(_cacheKey3);
1451
- if (!_cached) {
1452
- _context22.n = 5;
1453
- break;
1454
- }
1455
- // Only log cache hits once per object to reduce spam
1456
- _hitLogKey = "hit:".concat(_cacheKey3);
1457
- if (!this._loggedCacheEvents.has(_hitLogKey) || console.log('[AgentProviderSync] 🎯 roboto.load cache HIT:', {
1458
- type: type,
1459
- id: ids,
1460
- hasRealtime: !!_cached._realtime,
1461
- requestedRealtime: !!params.enableRealtime
1462
- })) {
1463
- this._loggedCacheEvents.add(_hitLogKey);
1464
- }
1465
-
1466
- // If realtime is requested but cached object doesn't have it, upgrade it
1467
- if (params.enableRealtime && !_cached._realtime) {
1468
- console.log('[AgentProviderSync] 🔄 Upgrading cached object to realtime:', {
1469
- type: type,
1470
- id: ids
1471
- });
1472
- _cached._initRealtime();
1473
- }
1474
- return _context22.a(2, _cached);
1475
- case 5:
1476
- // Check if we're already loading this object
1477
- pendingKey = "".concat(type, ":").concat(ids);
1478
- if (!this._pendingLoads.has(pendingKey)) {
1479
- _context22.n = 7;
1480
- break;
1481
- }
1482
- _context22.n = 6;
1483
- return this._pendingLoads.get(pendingKey);
1484
- case 6:
1485
- return _context22.a(2, _context22.v);
1486
- case 7:
1487
- // Only log cache miss once per object to reduce spam
1488
- missLogKey = "miss:".concat(_cacheKey3);
1489
- if (!this._loggedCacheEvents.has(missLogKey)) {
1490
- console.log('[AgentProviderSync] 📦 roboto.load cache MISS, loading:', {
1491
- type: type,
1492
- id: ids
1493
- });
1494
- this._loggedCacheEvents.add(missLogKey);
1495
- }
1496
-
1497
- // Create the loading promise and store it to prevent duplicate requests
1498
- loadPromise = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee21() {
1499
- var _enableRealtime, _queryParams, res, _obj2, _setLogKey;
1500
- return _regenerator().w(function (_context21) {
1501
- while (1) switch (_context21.p = _context21.n) {
1502
- case 0:
1503
- _context21.p = 0;
1504
- // Remove load-specific params that shouldn't be passed to query
1505
- _enableRealtime = params.enableRealtime, _queryParams = _objectWithoutProperties(params, _excluded2);
1506
- mergedParams = _objectSpread(_objectSpread({}, _queryParams), {}, {
1507
- where: "id=\"".concat(ids, "\"")
1508
- });
1509
- _context21.n = 1;
1510
- return _this8.query(type, mergedParams);
1511
- case 1:
1512
- res = _context21.v;
1513
- _obj2 = res[0];
1514
- if (_obj2) {
1515
- // Cache the loaded object
1516
- _this8._objectCache.set(_cacheKey3, _obj2);
1517
-
1518
- // Only log cache set once per object to reduce spam
1519
- _setLogKey = "set:".concat(_cacheKey3);
1520
- if (!_this8._loggedCacheEvents.has(_setLogKey)) {
1521
- console.log('[AgentProviderSync] 💾 roboto.load cached object:', {
1522
- type: type,
1523
- id: ids
1524
- });
1525
- _this8._loggedCacheEvents.add(_setLogKey);
1526
- }
1527
- }
1528
- return _context21.a(2, _obj2);
1529
- case 2:
1530
- _context21.p = 2;
1531
- // Remove from pending loads
1532
- _this8._pendingLoads["delete"](pendingKey);
1533
- return _context21.f(2);
1534
- case 3:
1535
- return _context21.a(2);
1536
- }
1537
- }, _callee21, null, [[0,, 2, 3]]);
1538
- }))(); // Store the promise so other concurrent requests can await it
1539
- this._pendingLoads.set(pendingKey, loadPromise);
1540
- _context22.n = 8;
1541
- return loadPromise;
1542
- case 8:
1543
- return _context22.a(2, _context22.v);
1544
- case 9:
1545
- _context22.n = 11;
1546
- break;
1547
- case 10:
1548
- _context22.p = 10;
1549
- _t16 = _context22.v;
1550
- return _context22.a(2, this._handleError(_t16));
1551
- case 11:
1552
- return _context22.a(2);
1553
- }
1554
- }, _callee22, this, [[1, 10]]);
1555
- }));
1556
- function load(_x12, _x13) {
1557
- return _load.apply(this, arguments);
1558
- }
1559
- return load;
1560
- }()
1561
- /**
1562
- * Clears the object cache. Useful for cache invalidation.
1563
- * @param {string} type - Optional object type to clear. If not provided, clears all.
1564
- * @param {string} id - Optional object ID to clear. If not provided with type, clears all objects of that type.
1565
- */
1566
- )
1567
- }, {
1568
- key: "clearCache",
1569
- value: function clearCache() {
1570
- var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
1571
- var id = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
1572
- if (type && id) {
1573
- // Clear specific object
1574
- var cacheKey = "".concat(type, ":").concat(id);
1575
- var removed = this._objectCache["delete"](cacheKey);
1576
-
1577
- // Clear related log tracking
1578
- this._loggedCacheEvents["delete"]("hit:".concat(cacheKey));
1579
- this._loggedCacheEvents["delete"]("miss:".concat(cacheKey));
1580
- this._loggedCacheEvents["delete"]("set:".concat(cacheKey));
1581
- console.log('[AgentProviderSync] 🗑️ roboto.clearCache specific object:', {
1582
- type: type,
1583
- id: id,
1584
- removed: removed
1585
- });
1586
- } else if (type) {
1587
- // Clear all objects of a specific type
1588
- var removedCount = 0;
1589
- var _iterator6 = _createForOfIteratorHelper(this._objectCache),
1590
- _step6;
1591
- try {
1592
- for (_iterator6.s(); !(_step6 = _iterator6.n()).done;) {
1593
- var _step6$value = _slicedToArray(_step6.value, 1),
1594
- key = _step6$value[0];
1595
- if (key.startsWith("".concat(type, ":"))) {
1596
- this._objectCache["delete"](key);
1597
- removedCount++;
1598
- }
1599
- }
1600
-
1601
- // Clear related log tracking for this type
1602
- } catch (err) {
1603
- _iterator6.e(err);
1604
- } finally {
1605
- _iterator6.f();
1606
- }
1607
- var _iterator7 = _createForOfIteratorHelper(this._loggedCacheEvents),
1608
- _step7;
1609
- try {
1610
- for (_iterator7.s(); !(_step7 = _iterator7.n()).done;) {
1611
- var logKey = _step7.value;
1612
- if (logKey.includes("".concat(type, ":"))) {
1613
- this._loggedCacheEvents["delete"](logKey);
1614
- }
1615
- }
1616
- } catch (err) {
1617
- _iterator7.e(err);
1618
- } finally {
1619
- _iterator7.f();
1620
- }
1621
- console.log('[AgentProviderSync] 🗑️ roboto.clearCache by type:', {
1622
- type: type,
1623
- removedCount: removedCount
1624
- });
1625
- } else {
1626
- // Clear all cached objects
1627
- var size = this._objectCache.size;
1628
- this._objectCache.clear();
1629
- this._loggedCacheEvents.clear();
1630
- this._pendingLoads.clear();
1631
- console.log('[AgentProviderSync] 🗑️ roboto.clearCache all objects:', {
1632
- clearedCount: size
1633
- });
1634
- }
1635
- }
1636
-
1637
- /**
1638
- * Gets cache status for debugging
1639
- * @returns {Object} Cache status information
1640
- */
1641
- }, {
1642
- key: "getCacheStatus",
1643
- value: function getCacheStatus() {
1644
- var cacheEntries = Array.from(this._objectCache.entries()).map(function (_ref6) {
1645
- var _obj$_internalData;
1646
- var _ref7 = _slicedToArray(_ref6, 2),
1647
- key = _ref7[0],
1648
- obj = _ref7[1];
1649
- return {
1650
- key: key,
1651
- id: obj.id,
1652
- type: ((_obj$_internalData = obj._internalData) === null || _obj$_internalData === void 0 ? void 0 : _obj$_internalData.type) || 'unknown'
1653
- };
1654
- });
1655
- var pendingLoads = Array.from(this._pendingLoads.keys());
1656
- return {
1657
- cacheSize: this._objectCache.size,
1658
- pendingLoads: pendingLoads.length,
1659
- loggedEvents: this._loggedCacheEvents.size,
1660
- entries: cacheEntries,
1661
- pendingKeys: pendingLoads
1662
- };
1663
- }
1664
-
1665
- /**
1666
- * Makes a POST request to a specific endpoint to run a task and handle progress updates.
1667
- *
1668
- * @param params.id (optional) IF the client is MONITORING the job with WS ClientMonitor,
1669
- * the client should generate a jobId and connect to the ClientMonitor
1670
- * BEFORE starting the job, to make sure no messages are missed -
1671
- * otherwise we'd have to delay the task start.
1672
- *
1673
- * @param {Object} params - The parameters to be sent in the POST request.
1674
- * @param {Object} callbacks - An object containing callback functions for progress and error handling.
1675
- *
1676
- * The function expects a response in the following format:
1677
- * {
1678
- * ok: boolean, // Indicates if the request was successful or not
1679
- * jobId: string, // The job identifier
1680
- * status: string // Can be 'RUNNING', 'DONE', or 'ERROR'
1681
- * }
1682
- */
1683
- }, {
1684
- key: "runTask",
1685
- value: (function () {
1686
- var _runTask = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee23() {
1687
- var params,
1688
- callbacks,
1689
- onProgress,
1690
- onError,
1691
- onStopped,
1692
- onWaiting,
1693
- onDone,
1694
- response,
1695
- ok,
1696
- jobId,
1697
- status,
1698
- message,
1699
- output,
1700
- _args23 = arguments,
1701
- _t17;
1702
- return _regenerator().w(function (_context23) {
1703
- while (1) switch (_context23.p = _context23.n) {
1704
- case 0:
1705
- params = _args23.length > 0 && _args23[0] !== undefined ? _args23[0] : {};
1706
- callbacks = _args23.length > 1 && _args23[1] !== undefined ? _args23[1] : {};
1707
- onProgress = callbacks.onProgress, onError = callbacks.onError, onStopped = callbacks.onStopped, onWaiting = callbacks.onWaiting, onDone = callbacks.onDone;
1708
- _context23.p = 1;
1709
- _context23.n = 2;
1710
- return this.post('/task_service/runChain', params);
1711
- case 2:
1712
- response = _context23.v;
1713
- if (response) {
1714
- _context23.n = 3;
1715
- break;
1716
- }
1717
- throw new Error('Invalid server response');
1718
- case 3:
1719
- // Validate response structure
1720
- ok = response.ok, jobId = response.jobId, status = response.status, message = response.message, output = response.output;
1721
- if (!(!ok || typeof jobId !== 'string' || typeof status !== 'string')) {
1722
- _context23.n = 4;
1723
- break;
1724
- }
1725
- throw new Error('Invalid response structure');
1726
- case 4:
1727
- // If the task is still in progress, start polling for updates
1728
- if (status === 'RUNNING' || status === 'SCHEDULED' || status === 'QUEUED' || status === 'STOPPING') {
1729
- this.pollTaskProgress(jobId, callbacks);
1730
- }
1731
- if (status === 'ERROR' && onError) {
1732
- // Provide the current progress to the callback function
1733
- onError(response);
1734
- }
1735
- if (status === 'STOPPED' && onStopped) {
1736
- // Provide the current progress to the callback function
1737
- onStopped(response);
1738
- }
1739
- if (status === 'WAITING' && onWaiting) {
1740
- // Provide the current progress to the callback function
1741
- onWaiting(response);
1742
- }
1743
- if (status === 'DONE' && onDone) {
1744
- // Provide the current progress to the callback function
1745
- //console.log('Finish (request) ',response);
1746
- onDone(response);
1747
- }
1748
- return _context23.a(2, {
1749
- ok: ok,
1750
- jobId: jobId,
1751
- status: status,
1752
- message: message,
1753
- output: output
1754
- });
1755
- case 5:
1756
- _context23.p = 5;
1757
- _t17 = _context23.v;
1758
- if (typeof onError === 'function') {
1759
- onError(_t17);
1760
- } else {
1761
- console.error('Error in runTask:', _t17);
1762
- }
1763
- return _context23.a(2, {
1764
- ok: false,
1765
- jobId: null,
1766
- status: 'ERROR',
1767
- error: _t17.message
1768
- });
1769
- }
1770
- }, _callee23, this, [[1, 5]]);
1771
- }));
1772
- function runTask() {
1773
- return _runTask.apply(this, arguments);
1774
- }
1775
- return runTask;
1776
- }())
1777
- }, {
1778
- key: "stopJob",
1779
- value: function () {
1780
- var _stopJob = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee24() {
1781
- var params,
1782
- callbacks,
1783
- response,
1784
- _args24 = arguments,
1785
- _t18;
1786
- return _regenerator().w(function (_context24) {
1787
- while (1) switch (_context24.p = _context24.n) {
1788
- case 0:
1789
- params = _args24.length > 0 && _args24[0] !== undefined ? _args24[0] : {};
1790
- callbacks = _args24.length > 1 && _args24[1] !== undefined ? _args24[1] : {};
1791
- _context24.p = 1;
1792
- _context24.n = 2;
1793
- return this.post('/task_service/stopJob', params);
1794
- case 2:
1795
- response = _context24.v;
1796
- if (response) {
1797
- _context24.n = 3;
1798
- break;
1799
- }
1800
- throw new Error('Invalid server response');
1801
- case 3:
1802
- return _context24.a(2, true);
1803
- case 4:
1804
- _context24.p = 4;
1805
- _t18 = _context24.v;
1806
- throw 'Error in stopJob';
1807
- case 5:
1808
- return _context24.a(2);
1809
- }
1810
- }, _callee24, this, [[1, 4]]);
1811
- }));
1812
- function stopJob() {
1813
- return _stopJob.apply(this, arguments);
1814
- }
1815
- return stopJob;
1816
- }()
1817
- /**
1818
- * Polls the progress of a long-running task.
1819
- *
1820
- * @param {string} jobId - The ID of the job to poll for progress.
1821
- * @param {function} onProgress - Callback function that receives progress updates.
1822
- *
1823
- * The function periodically sends GET requests to check the task's progress
1824
- * and reports back via the provided callback function . The polling stops when
1825
- * the task is completed or an error occurs.
1826
- */
1827
- }, {
1828
- key: "pollTaskProgress",
1829
- value: (function () {
1830
- var _pollTaskProgress = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee26(jobId, callbacks) {
1831
- var _this9 = this;
1832
- var onProgress, onError, onStopped, onWaiting, onDone, _callbacks$pollingInt, pollingInterval, _checkProgress, _t19;
1833
- return _regenerator().w(function (_context26) {
1834
- while (1) switch (_context26.p = _context26.n) {
1835
- case 0:
1836
- onProgress = callbacks.onProgress, onError = callbacks.onError, onStopped = callbacks.onStopped, onWaiting = callbacks.onWaiting, onDone = callbacks.onDone, _callbacks$pollingInt = callbacks.pollingInterval, pollingInterval = _callbacks$pollingInt === void 0 ? 2000 : _callbacks$pollingInt;
1837
- _context26.p = 1;
1838
- _checkProgress = /*#__PURE__*/function () {
1839
- var _ref8 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee25() {
1840
- var response;
1841
- return _regenerator().w(function (_context25) {
1842
- while (1) switch (_context25.n) {
1843
- case 0:
1844
- _context25.n = 1;
1845
- return _this9.get("/task_service/pollChainProgress", {
1846
- jobId: jobId
1847
- });
1848
- case 1:
1849
- response = _context25.v;
1850
- // If the task is still in progress, start polling for updates
1851
- if (response.status === 'DONE' && onDone) {
1852
- // Provide the current progress to the callback function
1853
- //console.log('Finish (progress) ',response);
1854
- onDone(response);
1855
- }
1856
- if (response.status === 'ERROR' && onError) {
1857
- // Provide the current progress to the callback function
1858
- onError(response);
1859
- }
1860
- if (response.status === 'STOPPED' && onStopped) {
1861
- // Provide the current progress to the callback function
1862
- onStopped(response);
1863
- }
1864
- if (response.status === 'WAITING' && onWaiting) {
1865
- // Provide the current progress to the callback function
1866
- onWaiting(response);
1867
- }
1868
-
1869
- // Provide the current progress to the callback function
1870
- if (response.status == 'RUNNING') {
1871
- onProgress(response);
1872
- }
1873
-
1874
- // Continue polling if the status is 'RUNNING' or STOPPING
1875
- if (['RUNNING', 'STOPPING'].includes(response.status)) {
1876
- setTimeout(_checkProgress, pollingInterval); // Poll every 2 seconds
1877
- }
1878
- case 2:
1879
- return _context25.a(2);
1880
- }
1881
- }, _callee25);
1882
- }));
1883
- return function checkProgress() {
1884
- return _ref8.apply(this, arguments);
1885
- };
1886
- }();
1887
- _checkProgress();
1888
- _context26.n = 3;
1889
- break;
1890
- case 2:
1891
- _context26.p = 2;
1892
- _t19 = _context26.v;
1893
- return _context26.a(2, this._handleError(_t19));
1894
- case 3:
1895
- return _context26.a(2);
1896
- }
1897
- }, _callee26, this, [[1, 2]]);
1898
- }));
1899
- function pollTaskProgress(_x14, _x15) {
1900
- return _pollTaskProgress.apply(this, arguments);
1901
- }
1902
- return pollTaskProgress;
1903
- }()
1904
- /**
1905
- * Performs a GET request to the specified endpoint.
1906
- *
1907
- * This method uses the Axios instance to make an authenticated GET request.
1908
- * The `authtoken` stored in the class instance is included in the request headers
1909
- * for authorization. It handles any errors and returns the response data.
1910
- *
1911
- * @param {string} endpoint - The endpoint URL to which the GET request is made.
1912
- * @param {Object} [params={}] - Optional parameters to be sent with the request.
1913
- * @returns {Promise<Object>} - The response data from the API.
1914
- */
1915
- )
1916
- }, {
1917
- key: "get",
1918
- value: (function () {
1919
- var _get = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee27(endpoint) {
1920
- var params,
1921
- headers,
1922
- response,
1923
- _args27 = arguments,
1924
- _t20;
1925
- return _regenerator().w(function (_context27) {
1926
- while (1) switch (_context27.p = _context27.n) {
1927
- case 0:
1928
- params = _args27.length > 1 && _args27[1] !== undefined ? _args27[1] : {};
1929
- _context27.p = 1;
1930
- // Add the authToken to the headers
1931
- headers = {
1932
- authtoken: this.authtoken
1933
- }; // Make the GET request using Axios
1934
- _context27.n = 2;
1935
- return this.axios.get(endpoint, {
1936
- params: params,
1937
- headers: headers
1938
- });
1939
- case 2:
1940
- response = _context27.v;
1941
- if (!(response.data.ok === false)) {
1942
- _context27.n = 3;
1943
- break;
1944
- }
1945
- return _context27.a(2, this._handleError(response));
1946
- case 3:
1947
- return _context27.a(2, response.data);
1948
- case 4:
1949
- _context27.p = 4;
1950
- _t20 = _context27.v;
1951
- return _context27.a(2, this._handleError(_t20));
1952
- }
1953
- }, _callee27, this, [[1, 4]]);
1954
- }));
1955
- function get(_x16) {
1956
- return _get.apply(this, arguments);
1957
- }
1958
- return get;
1959
- }()
1960
- /**
1961
- * Performs a POST request to the specified endpoint.
1962
- *
1963
- * This method uses the Axios instance to make an authenticated POST request.
1964
- * It includes the `authtoken` in the request headers for authorization. The method
1965
- * sends the provided data as the request body. It handles any errors and returns
1966
- * the response data.
1967
- *
1968
- * @param {string} endpoint - The endpoint URL to which the POST request is made.
1969
- * @param {Object} [data={}] - Data to be sent in the body of the POST request.
1970
- * @returns {Promise<Object>} - The response data from the API.
1971
- */
1972
- )
1973
- }, {
1974
- key: "post",
1975
- value: (function () {
1976
- var _post = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee28(endpoint) {
1977
- var data,
1978
- headers,
1979
- response,
1980
- _args28 = arguments,
1981
- _t21;
1982
- return _regenerator().w(function (_context28) {
1983
- while (1) switch (_context28.p = _context28.n) {
1984
- case 0:
1985
- data = _args28.length > 1 && _args28[1] !== undefined ? _args28[1] : {};
1986
- _context28.p = 1;
1987
- // Add the authToken to the headers
1988
- headers = {
1989
- authtoken: this.authtoken
1990
- }; // Make the POST request using Axios
1991
- _context28.n = 2;
1992
- return this.axios.post(endpoint, data, {
1993
- headers: headers
1994
- });
1995
- case 2:
1996
- response = _context28.v;
1997
- if (!(response.data.ok === false)) {
1998
- _context28.n = 3;
1999
- break;
2000
- }
2001
- return _context28.a(2, this._handleError(response));
2002
- case 3:
2003
- return _context28.a(2, response.data);
2004
- case 4:
2005
- _context28.p = 4;
2006
- _t21 = _context28.v;
2007
- return _context28.a(2, this._handleError(_t21));
2008
- }
2009
- }, _callee28, this, [[1, 4]]);
2010
- }));
2011
- function post(_x17) {
2012
- return _post.apply(this, arguments);
2013
- }
2014
- return post;
2015
- }())
2016
- }, {
2017
- key: "setErrorHandler",
2018
- value: function setErrorHandler(customErrorHandler) {
2019
- this.customErrorHandler = customErrorHandler;
2020
- }
2021
- }, {
2022
- key: "_handleError",
2023
- value: function _handleError(err) {
2024
- // Invoke the custom error handler if provided
2025
- if (this.customErrorHandler) {
2026
- var res = this.customErrorHandler(err);
2027
- if (res) return;
2028
- }
2029
- if (_.isObject(err) && _.get(err, 'response')) {
2030
- if (err.response) {
2031
- console.log('Error response:', {
2032
- data: err.response.data,
2033
- status: err.response.status,
2034
- headers: err.response.headers
2035
- });
2036
- }
2037
- var msg = _.get(err, 'response.data.message', 'Error in API response');
2038
- if (msg.key) {
2039
- //throw new Error(msg.key);
2040
- throw {
2041
- message: msg.key
2042
- };
2043
- } else {
2044
- //throw new Error(msg);
2045
- throw {
2046
- message: msg
2047
- };
2048
- }
2049
- } else {
2050
- //throw new Error(err.message || 'Unknown error');
2051
- throw {
2052
- code: err.code,
2053
- message: err.message
2054
- } || {
2055
- message: err
2056
- } || {
2057
- message: 'Unknown error'
2058
- };
2059
- }
2060
- }
2061
- }]);
2062
- }();
2063
- export { RbtApi as default };