roboto-js 1.8.5 → 1.8.7

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