roboto-js 1.7.0 → 1.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,665 @@
1
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
2
+ 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."); }
3
+ 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; } }
4
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
5
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
6
+ function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = !1, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = !0, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), !0), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
7
+ function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
8
+ function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); }
9
+ function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; }
10
+ function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
11
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
12
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
13
+ function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
14
+ function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
15
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
16
+ 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); }
17
+ 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; }
18
+ 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; }
19
+ function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
20
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
21
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
22
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
23
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
24
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
25
+ import _ from 'lodash';
26
+ var RbtObject = /*#__PURE__*/function () {
27
+ function RbtObject(record, axiosInstance) {
28
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
29
+ _classCallCheck(this, RbtObject);
30
+ this._axios = axiosInstance;
31
+ this._internalData = record;
32
+ this.isRbtObject = true;
33
+ this.id = record.id;
34
+ this.id_revision = record.id_revision;
35
+ this.rpcMeta = record.rpcMeta || {
36
+ changes: [],
37
+ isNew: options.isNew || record.revision == 0 || false
38
+ };
39
+ if (record.data) {
40
+ this._data = this._deepUnpackJson(record.data);
41
+ } else {
42
+ this._data = record.dataJson ? this._deepUnpackJson(record.dataJson) : {};
43
+ }
44
+ if (options.websocketClient && this.id && options.enableRealtime) {
45
+ this._realtime = true;
46
+ this._ws = options.websocketClient;
47
+ this._subscribeToRealtime(this._ws);
48
+ } else if (options.websocketClient && this.id) {
49
+ // Store websocket client for potential later use, but don't auto-subscribe
50
+ this._ws = options.websocketClient;
51
+ }
52
+
53
+ // If enableRealtime is requested but no websocketClient provided, try to initialize lazily
54
+ if (options.enableRealtime && this.id && !this._realtime) {
55
+ this._initRealtime();
56
+ }
57
+ this._eventHandlers = {
58
+ change: [],
59
+ save: []
60
+ };
61
+
62
+ // Debounce properties for WebSocket broadcasting
63
+ this._broadcastDebounceTimer = null;
64
+ this._pendingBroadcasts = new Map(); // path -> value
65
+ }
66
+ return _createClass(RbtObject, [{
67
+ key: "get",
68
+ value: function get(path) {
69
+ return _.get(this._data, path);
70
+ }
71
+ }, {
72
+ key: "getData",
73
+ value: function getData() {
74
+ var _this = this;
75
+ var keys = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
76
+ // Check if keys are provided
77
+ if (keys && Array.isArray(keys)) {
78
+ // Return an object with only the specified keys
79
+ return keys.reduce(function (result, key) {
80
+ // Use lodash.get to handle deep key paths
81
+ var value = _.get(_this._data, key);
82
+ // If the value exists, add it to the result object using the key path as the property name
83
+ if (value !== undefined) {
84
+ // Create nested structure based on the key path
85
+ _.set(result, key, value);
86
+ }
87
+ return result;
88
+ }, {});
89
+ } else {
90
+ // Return a shallow copy of the full data if no keys are provided
91
+ return _objectSpread({}, this._data);
92
+ }
93
+ }
94
+ }, {
95
+ key: "_addChange",
96
+ value: function _addChange(path) {
97
+ // Ensure no duplicate paths
98
+ if (!this.rpcMeta.changes.includes(path)) {
99
+ this.rpcMeta.changes.push(path);
100
+ }
101
+ }
102
+ }, {
103
+ key: "set",
104
+ value: function set(path, value) {
105
+ var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
106
+ var currentValue = _.get(this._data, path); // Fetch current value at deep path
107
+
108
+ if (options.merge) {
109
+ var mergedValue = _.mergeWith({}, currentValue, value, function (objValue, srcValue) {
110
+ if (srcValue === undefined) {
111
+ return undefined; // Indicate to delete when merging
112
+ }
113
+ if (_.isArray(objValue)) {
114
+ return srcValue; // Customize merging behavior for arrays
115
+ }
116
+ // Handle null, 0, and "" explicitly
117
+ if (srcValue === null || srcValue === 0 || srcValue === "") {
118
+ return srcValue;
119
+ }
120
+ });
121
+ // Process merged object to remove any keys set explicitly to undefined
122
+ Object.keys(mergedValue).forEach(function (key) {
123
+ if (mergedValue[key] === undefined) {
124
+ _.unset(mergedValue, key);
125
+ }
126
+ });
127
+ if (!_.isEqual(currentValue, mergedValue)) {
128
+ _.set(this._data, path, mergedValue); // Set the merged value at the deep path
129
+ this._addChange(path);
130
+ // Trigger local change events for any registered handlers
131
+ this._trigger('change', {
132
+ path: path,
133
+ value: mergedValue,
134
+ options: options
135
+ });
136
+ }
137
+ } else {
138
+ // If value is undefined and not merging, delete the key
139
+ if (value === undefined) {
140
+ _.unset(this._data, path);
141
+ this._addChange(path);
142
+ // Trigger local change events for any registered handlers
143
+ this._trigger('change', {
144
+ path: path,
145
+ value: undefined,
146
+ options: options
147
+ });
148
+ } else if (!_.isEqual(currentValue, value)) {
149
+ _.set(this._data, path, value); // Set the value directly at the deep path
150
+ this._addChange(path);
151
+ this._broadcastChange(path, value);
152
+ // Trigger local change events for any registered handlers
153
+ this._trigger('change', {
154
+ path: path,
155
+ value: value,
156
+ options: options
157
+ });
158
+ }
159
+ }
160
+ }
161
+ }, {
162
+ key: "setData",
163
+ value: function setData(newData) {
164
+ var _this2 = this;
165
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
166
+ if (_typeof(newData) !== 'object' || newData === null) {
167
+ throw new Error('setData expects an object');
168
+ }
169
+ var _options$merge = options.merge,
170
+ merge = _options$merge === void 0 ? false : _options$merge;
171
+ Object.keys(newData).forEach(function (path) {
172
+ var currentValue = _.get(_this2._data, path);
173
+ var newValue = newData[path];
174
+ if (merge && _.isObject(currentValue) && _.isObject(newValue)) {
175
+ var mergedValue = _.mergeWith({}, currentValue, newValue, function (objValue, srcValue) {
176
+ if (_.isArray(srcValue)) {
177
+ return _toConsumableArray(srcValue); // Customize merging behavior for arrays
178
+ }
179
+ // Handle null, 0, and "" explicitly
180
+ if (srcValue === null || srcValue === 0 || srcValue === "") {
181
+ return srcValue;
182
+ }
183
+ });
184
+ if (!_.isEqual(currentValue, mergedValue)) {
185
+ _.set(_this2._data, path, mergedValue);
186
+ _this2._addChange(path);
187
+ // Trigger change event for this path
188
+ _this2._trigger('change', {
189
+ path: path,
190
+ value: mergedValue,
191
+ options: options
192
+ });
193
+ }
194
+ } else if (!_.isEqual(currentValue, newValue)) {
195
+ _.setWith(_this2._data, path, newValue, function (nsValue, key, nsObject, nsPath) {
196
+ if (key === nsPath.split('.').pop() && !_.has(nsObject, key)) {
197
+ return nsObject[key] = {}; // Create any missing parts of the path as plain objects
198
+ }
199
+ return nsValue;
200
+ });
201
+ _this2._addChange(path);
202
+ // Trigger change event for this path
203
+ _this2._trigger('change', {
204
+ path: path,
205
+ value: newValue,
206
+ options: options
207
+ });
208
+ }
209
+ });
210
+ }
211
+
212
+ //
213
+ // For Arrays
214
+ //
215
+ }, {
216
+ key: "setAppend",
217
+ value: function () {
218
+ var _setAppend = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(key, value) {
219
+ var options,
220
+ existingValue,
221
+ valuesToAdd,
222
+ mergedValues,
223
+ _args = arguments;
224
+ return _regenerator().w(function (_context) {
225
+ while (1) switch (_context.n) {
226
+ case 0:
227
+ options = _args.length > 2 && _args[2] !== undefined ? _args[2] : {};
228
+ existingValue = this.get(key) || []; // Get the existing value or default to an empty array
229
+ if (!Array.isArray(existingValue)) {
230
+ existingValue = []; // Ensure existingValue is an array if not already
231
+ }
232
+ valuesToAdd = Array.isArray(value) ? value : [value]; // Convert value to an array if it's not one
233
+ // Combine existingValue and valuesToAdd, filtering out duplicates
234
+ mergedValues = Array.from(new Set([].concat(_toConsumableArray(existingValue), _toConsumableArray(valuesToAdd))));
235
+ this.set(key, mergedValues, options); // Set the updated array back to the user data
236
+ case 1:
237
+ return _context.a(2);
238
+ }
239
+ }, _callee, this);
240
+ }));
241
+ function setAppend(_x, _x2) {
242
+ return _setAppend.apply(this, arguments);
243
+ }
244
+ return setAppend;
245
+ }()
246
+ }, {
247
+ key: "setRemove",
248
+ value: function () {
249
+ var _setRemove = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee2(key, value) {
250
+ var options,
251
+ existingValue,
252
+ valuesToRemove,
253
+ filteredValues,
254
+ _args2 = arguments;
255
+ return _regenerator().w(function (_context2) {
256
+ while (1) switch (_context2.n) {
257
+ case 0:
258
+ options = _args2.length > 2 && _args2[2] !== undefined ? _args2[2] : {};
259
+ existingValue = this.get(key) || []; // Get the existing value or default to an empty array
260
+ if (Array.isArray(existingValue)) {
261
+ _context2.n = 1;
262
+ break;
263
+ }
264
+ return _context2.a(2);
265
+ case 1:
266
+ valuesToRemove = Array.isArray(value) ? value : [value]; // Convert value to an array if it's not one
267
+ // Filter out the values to remove from the existing value array
268
+ filteredValues = existingValue.filter(function (item) {
269
+ return !valuesToRemove.includes(item);
270
+ });
271
+ this.set(key, filteredValues); // Set the updated array back to the user data
272
+ case 2:
273
+ return _context2.a(2);
274
+ }
275
+ }, _callee2, this);
276
+ }));
277
+ function setRemove(_x3, _x4) {
278
+ return _setRemove.apply(this, arguments);
279
+ }
280
+ return setRemove;
281
+ }()
282
+ }, {
283
+ key: "getMetaData",
284
+ value: function getMetaData() {
285
+ var meta = {
286
+ timeCreated: this._internalData.timeCreated,
287
+ timeModified: this._internalData.timeModified,
288
+ timeDeleted: this._internalData.timeDeleted,
289
+ revision: this._internalData.revision
290
+ };
291
+ return meta;
292
+ }
293
+ }, {
294
+ key: "toRecord",
295
+ value: function toRecord() {
296
+ return _objectSpread(_objectSpread({}, this._internalData), {}, {
297
+ dataJson: JSON.stringify(this._data),
298
+ rpcMeta: this.rpcMeta
299
+ });
300
+ }
301
+ }, {
302
+ key: "toDeltaRecord",
303
+ value: function toDeltaRecord() {
304
+ var changes = this.rpcMeta.changes;
305
+
306
+ // Initialize deltaData as an empty object
307
+ var sourceData = this._data;
308
+ var deltaData = {};
309
+
310
+ // Populate deltaData only with keys specified in changes
311
+ changes.forEach(function (path) {
312
+ // default value explicitly set to undefined
313
+ var value = _.get(sourceData, path, undefined);
314
+ // Use _.set to ensure nested keys are correctly assigned
315
+ _.set(deltaData, path, value);
316
+ });
317
+
318
+ // mark as delta
319
+ this.rpcMeta.delta = true;
320
+ var clonedData = _.cloneDeep(this._internalData);
321
+ clonedData.data = deltaData;
322
+ return _objectSpread(_objectSpread({}, clonedData), {}, {
323
+ dataJson: JSON.stringify(deltaData),
324
+ rpcMeta: this.rpcMeta
325
+ });
326
+ }
327
+ }, {
328
+ key: "clone",
329
+ value: function clone() {
330
+ // Create a deep copy of the current object's data
331
+ var clonedData = _.cloneDeep(this._internalData);
332
+
333
+ // Reset unique identifiers to ensure a new ID is generated upon saving
334
+ delete clonedData.id;
335
+ delete clonedData.id_revision;
336
+ delete clonedData.rpcMeta;
337
+ if (clonedData.data) {
338
+ delete clonedData.data.id;
339
+ delete clonedData.data.id_revision;
340
+ }
341
+
342
+ // Create a new instance of RbtObject with the cloned data
343
+ var clonedObject = new RbtObject(clonedData, this._axios, {
344
+ isNew: true
345
+ });
346
+ return clonedObject;
347
+ }
348
+ }, {
349
+ key: "save",
350
+ value: function () {
351
+ var _save = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee3() {
352
+ var _response$data, _response$data2, record, response, _e$response, _t;
353
+ return _regenerator().w(function (_context3) {
354
+ while (1) switch (_context3.p = _context3.n) {
355
+ case 0:
356
+ if (this._internalData.type) {
357
+ _context3.n = 1;
358
+ break;
359
+ }
360
+ throw new Error('Cannot save object without type');
361
+ case 1:
362
+ _context3.p = 1;
363
+ if (this.rpcMeta.isNew) {
364
+ record = this.toRecord();
365
+ } else {
366
+ record = this.toDeltaRecord();
367
+ }
368
+ _context3.n = 2;
369
+ return this._axios.post('/object_service/saveObject', [record]);
370
+ case 2:
371
+ response = _context3.v;
372
+ if (!(response.data.ok === false)) {
373
+ _context3.n = 3;
374
+ break;
375
+ }
376
+ throw new Error(response.data.message);
377
+ case 3:
378
+ if (!(((_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.result) == 'NO_CHANGES')) {
379
+ _context3.n = 4;
380
+ break;
381
+ }
382
+ this.rpcMeta.isNew = false;
383
+ return _context3.a(2, this);
384
+ case 4:
385
+ if ((_response$data2 = response.data) !== null && _response$data2 !== void 0 && _response$data2.newData) {
386
+ // apply new incoming data
387
+ this.setData(response.newData);
388
+ }
389
+ this.id = response.data.id;
390
+ this.id_revision = response.data.id_revision;
391
+ this.type = response.data.type;
392
+ this.rpcMeta.isNew = false;
393
+ return _context3.a(2, this);
394
+ case 5:
395
+ _context3.p = 5;
396
+ _t = _context3.v;
397
+ console.log('RbtObject.save.error:', _t === null || _t === void 0 || (_e$response = _t.response) === null || _e$response === void 0 ? void 0 : _e$response.data);
398
+ this._error = _t;
399
+ //console.log(e.response.data);
400
+ throw _t;
401
+ case 6:
402
+ return _context3.a(2);
403
+ }
404
+ }, _callee3, this, [[1, 5]]);
405
+ }));
406
+ function save() {
407
+ return _save.apply(this, arguments);
408
+ }
409
+ return save;
410
+ }()
411
+ }, {
412
+ key: "delete",
413
+ value: function () {
414
+ var _delete2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee4() {
415
+ var record, response, _t2;
416
+ return _regenerator().w(function (_context4) {
417
+ while (1) switch (_context4.p = _context4.n) {
418
+ case 0:
419
+ if (this._internalData.type) {
420
+ _context4.n = 1;
421
+ break;
422
+ }
423
+ throw new Error('Cannot delete object without type');
424
+ case 1:
425
+ _context4.p = 1;
426
+ record = this.toRecord();
427
+ _context4.n = 2;
428
+ return this._axios.post('/object_service/deleteObject', {
429
+ id: record.id,
430
+ type: record.type
431
+ });
432
+ case 2:
433
+ response = _context4.v;
434
+ if (!(response.data.ok === false)) {
435
+ _context4.n = 3;
436
+ break;
437
+ }
438
+ throw new Error(response.data.message);
439
+ case 3:
440
+ this._internalData = response.data;
441
+ return _context4.a(2, this);
442
+ case 4:
443
+ _context4.p = 4;
444
+ _t2 = _context4.v;
445
+ console.log('RbtObject.delete.error:');
446
+ console.log(_t2.response.data);
447
+ throw _t2;
448
+ case 5:
449
+ return _context4.a(2);
450
+ }
451
+ }, _callee4, this, [[1, 4]]);
452
+ }));
453
+ function _delete() {
454
+ return _delete2.apply(this, arguments);
455
+ }
456
+ return _delete;
457
+ }()
458
+ }, {
459
+ key: "_deepUnpackJson",
460
+ value: function _deepUnpackJson(value) {
461
+ if (typeof value === 'string') {
462
+ try {
463
+ // Only parse as JSON if it's not a large number
464
+ // https://chatgpt.com/c/6745902c-edf4-800c-ab52-31bf27dde2bd
465
+ //
466
+ if (!/^\d{16,}$/.test(value)) {
467
+ var parsed = JSON.parse(value);
468
+ // Recursively parse if the result is a string, object, or array
469
+ return this._deepUnpackJson(parsed);
470
+ }
471
+ } catch (e) {
472
+ return value; // Return the original string if parsing fails
473
+ }
474
+ } else if (value !== null && _typeof(value) === 'object') {
475
+ // If it's an object (including arrays), recursively parse each value
476
+ for (var key in value) {
477
+ value[key] = this._deepUnpackJson(value[key]);
478
+ }
479
+ }
480
+ return value;
481
+ }
482
+
483
+ //
484
+ // Realtime WebSocket
485
+ //
486
+ //
487
+ }, {
488
+ key: "_initRealtime",
489
+ value: function _initRealtime() {
490
+ if (this._realtime || !this._axios) return;
491
+
492
+ // Use stored websocket client if available
493
+ var ws = this._ws;
494
+
495
+ // Otherwise, lazily pull WebSocket from parent API (injected via axios instance)
496
+ if (!ws) {
497
+ var _this$_axios;
498
+ var api = (_this$_axios = this._axios) === null || _this$_axios === void 0 ? void 0 : _this$_axios.__rbtApiInstance;
499
+ if (!api || typeof api.getWebSocketClient !== 'function') return;
500
+ ws = api.getWebSocketClient();
501
+ }
502
+ if (!ws || this._realtime) return;
503
+ this._ws = ws;
504
+ this._realtime = true;
505
+ this._subscribeToRealtime(ws);
506
+ }
507
+ }, {
508
+ key: "_subscribeToRealtime",
509
+ value: function _subscribeToRealtime(ws) {
510
+ var _this$_axios2,
511
+ _this3 = this;
512
+ // Track subscription for reconnection
513
+ var api = (_this$_axios2 = this._axios) === null || _this$_axios2 === void 0 ? void 0 : _this$_axios2.__rbtApiInstance;
514
+ if (api && typeof api._trackSubscription === 'function') {
515
+ api._trackSubscription(this.id);
516
+ }
517
+ if (ws.readyState === 1) {
518
+ ws.send(JSON.stringify({
519
+ type: 'subscribe',
520
+ objectId: this.id
521
+ }));
522
+ } else {
523
+ ws.addEventListener('open', function () {
524
+ ws.send(JSON.stringify({
525
+ type: 'subscribe',
526
+ objectId: _this3.id
527
+ }));
528
+ });
529
+ }
530
+ ws.addEventListener('message', function (event) {
531
+ try {
532
+ var msg = JSON.parse(event.data);
533
+ if (msg.objectId !== _this3.id) return;
534
+ if (msg.type === 'update') {
535
+ if (msg.delta && msg.delta.path !== undefined) {
536
+ _.set(_this3._data, msg.delta.path, msg.delta.value);
537
+
538
+ // Add metadata to indicate if this is state sync vs live update
539
+ var changeData = _objectSpread(_objectSpread({}, msg.delta), {}, {
540
+ isStateSync: msg.isStateSync || false,
541
+ source: msg.isStateSync ? 'state-sync' : 'realtime',
542
+ userId: msg.userId || msg.delta.userId || null
543
+ });
544
+ _this3._trigger('change', changeData);
545
+ if (msg.isStateSync) {
546
+ console.log('[RbtObject] Applied state sync:', msg.delta.path, '=', msg.delta.value);
547
+ }
548
+ } else {
549
+ console.warn('[RbtObject] Received update message without valid delta:', msg);
550
+ }
551
+ } else if (msg.type === 'save') {
552
+ _this3._trigger('save', msg.revision || {});
553
+ }
554
+ } catch (error) {
555
+ console.error('[RbtObject] Error processing WebSocket message:', error, event.data);
556
+ }
557
+ });
558
+ }
559
+
560
+ // General change handler for both local and remote changes
561
+ }, {
562
+ key: "onChange",
563
+ value: function onChange(cb) {
564
+ this._eventHandlers.change.push(cb);
565
+ // Auto-initialize realtime if this object has WebSocket capability
566
+ if (this._ws && !this._realtime) {
567
+ this._initRealtime();
568
+ }
569
+ }
570
+
571
+ // General save handler for both local and remote saves
572
+ }, {
573
+ key: "onSave",
574
+ value: function onSave(cb) {
575
+ this._eventHandlers.save.push(cb);
576
+ // Note: Does not initialize realtime connection
577
+ }
578
+ }, {
579
+ key: "_trigger",
580
+ value: function _trigger(type, data) {
581
+ var _this$_eventHandlers$;
582
+ console.log('[AgentProviderSync] _trigger called:', type, 'handlers:', (_this$_eventHandlers$ = this._eventHandlers[type]) === null || _this$_eventHandlers$ === void 0 ? void 0 : _this$_eventHandlers$.length, 'data:', data);
583
+ var _iterator = _createForOfIteratorHelper(this._eventHandlers[type] || []),
584
+ _step;
585
+ try {
586
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
587
+ var fn = _step.value;
588
+ fn(data);
589
+ }
590
+ } catch (err) {
591
+ _iterator.e(err);
592
+ } finally {
593
+ _iterator.f();
594
+ }
595
+ }
596
+ }, {
597
+ key: "_broadcastChange",
598
+ value: function _broadcastChange(path, value) {
599
+ var _this4 = this;
600
+ if (!this._realtime || !this._ws || this._ws.readyState !== 1) {
601
+ return;
602
+ }
603
+
604
+ // Store the pending broadcast
605
+ this._pendingBroadcasts.set(path, value);
606
+
607
+ // Clear existing timer if any
608
+ if (this._broadcastDebounceTimer) {
609
+ clearTimeout(this._broadcastDebounceTimer);
610
+ }
611
+
612
+ // Set new debounced timer
613
+ this._broadcastDebounceTimer = setTimeout(function () {
614
+ _this4._flushPendingBroadcasts();
615
+ }, 300);
616
+ }
617
+ }, {
618
+ key: "_flushPendingBroadcasts",
619
+ value: function _flushPendingBroadcasts() {
620
+ if (!this._realtime || !this._ws || this._ws.readyState !== 1) {
621
+ this._pendingBroadcasts.clear();
622
+ return;
623
+ }
624
+
625
+ // Send all pending broadcasts
626
+ var _iterator2 = _createForOfIteratorHelper(this._pendingBroadcasts),
627
+ _step2;
628
+ try {
629
+ for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
630
+ var _step2$value = _slicedToArray(_step2.value, 2),
631
+ path = _step2$value[0],
632
+ value = _step2$value[1];
633
+ this._ws.send(JSON.stringify({
634
+ type: 'update',
635
+ objectId: this.id,
636
+ delta: {
637
+ path: path,
638
+ value: value
639
+ }
640
+ }));
641
+ }
642
+
643
+ // Clear pending broadcasts and timer
644
+ } catch (err) {
645
+ _iterator2.e(err);
646
+ } finally {
647
+ _iterator2.f();
648
+ }
649
+ this._pendingBroadcasts.clear();
650
+ this._broadcastDebounceTimer = null;
651
+ }
652
+
653
+ // Cleanup method to clear any pending debounced broadcasts
654
+ }, {
655
+ key: "_cleanup",
656
+ value: function _cleanup() {
657
+ if (this._broadcastDebounceTimer) {
658
+ clearTimeout(this._broadcastDebounceTimer);
659
+ this._broadcastDebounceTimer = null;
660
+ }
661
+ this._pendingBroadcasts.clear();
662
+ }
663
+ }]);
664
+ }();
665
+ export { RbtObject as default };