roboto-js 1.7.0 → 1.7.1

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