@azrico/webobject 1.4.6 → 1.4.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,1117 +1,784 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports["default"] = exports.SimpleObject = void 0;
7
- var _global = require("@azrico/global");
8
- var _object = require("@azrico/object");
9
- var _MapableObject2 = require("./MapableObject");
10
- var _ObjectManager = _interopRequireDefault(require("./ObjectManager"));
11
- var _WebObjectManager = _interopRequireDefault(require("../WebObjects/WebObjectManager"));
12
- var _string = require("@azrico/string");
13
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
14
- function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
15
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
16
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
17
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
18
- 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."); }
19
- 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); }
20
- function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
21
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
22
- 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; }
23
- 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 exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator["return"] && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
24
- 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); } }
25
- 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); }); }; }
26
- function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
27
- 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); } }
28
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
29
- function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
30
- function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
31
- function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
32
- function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
33
- function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
34
- function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
35
- function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
36
- function _classPrivateMethodInitSpec(obj, privateSet) { _checkPrivateRedeclaration(obj, privateSet); privateSet.add(obj); }
37
- function _checkPrivateRedeclaration(obj, privateCollection) { if (privateCollection.has(obj)) { throw new TypeError("Cannot initialize the same private elements twice on an object"); } }
38
- 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; }
39
- function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
40
- function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
41
- function _classPrivateMethodGet(receiver, privateSet, fn) { if (!privateSet.has(receiver)) { throw new TypeError("attempted to get private field on non-instance"); } return fn; }
42
- var _setSubProperty = /*#__PURE__*/new WeakSet();
43
- var _getSubProperty = /*#__PURE__*/new WeakSet();
44
- var _setProperty = /*#__PURE__*/new WeakSet();
45
- var _setDefaultProperty = /*#__PURE__*/new WeakSet();
46
- var _getProperty = /*#__PURE__*/new WeakSet();
47
- var _getTempProperty = /*#__PURE__*/new WeakSet();
48
- var _setTempProperty = /*#__PURE__*/new WeakSet();
49
- var _setSaveResultObject = /*#__PURE__*/new WeakSet();
50
- var SimpleObject = /*#__PURE__*/function (_MapableObject) {
51
- _inherits(SimpleObject, _MapableObject);
52
- var _super = _createSuper(SimpleObject);
53
- function SimpleObject() {
54
- var _this;
55
- var is_readonly = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
56
- _classCallCheck(this, SimpleObject);
57
- _this = _super.call(this);
1
+ import { gcache, gfunc } from "@azrico/global";
2
+ import { object_clone, object_equals, object_getStatic, object_isEmpty, object_isTrue, object_removeKeys, } from "@azrico/object";
3
+ import { MapableObject } from "./MapableObject";
4
+ import ObjectManager from "./ObjectManager";
5
+ import WebObjectManager from "../WebObjects/WebObjectManager";
6
+ import { combine_if_not_blank } from "@azrico/string";
7
+ export class SimpleObject extends MapableObject {
8
+ static __cache_name;
9
+ //these properties should not be changed and are usually set by server
10
+ static __unchangeables;
11
+ //these properties can be directly changed and are included in deltaObject
12
+ static __changeables;
13
+ //these properties can only be changed by the _creator
14
+ static __protectedProperties;
15
+ //these properties usually are not directly changed and sometimes are included in deltaObject
16
+ static __extraProperties;
17
+ static __use_delta = true;
18
+ _static() {
19
+ return this.constructor;
20
+ }
21
+ //an exact copy of this object is stored here
22
+ __originalobject;
23
+ //changes are saved here
24
+ __delta = {};
25
+ __temp = undefined;
26
+ __changed = false;
27
+ //the last thing that was changed on this object
28
+ __lastChanged;
29
+ //is the object read only
30
+ __is_readonly;
31
+ //should we throw errors when encountering an error?
32
+ //is TRUE by default
33
+ __throw_errors;
34
+ //is this object marked as deleted?
35
+ _deleted;
36
+ _deletedBy;
37
+ //errors
38
+ __errors;
39
+ __showErrors;
40
+ //save results
41
+ __saveResultObject;
42
+ __saveResultIsSuccess = true;
43
+ __saveResultType;
44
+ //sequence key (usually managed by the database)
45
+ _index_key = "";
46
+ //sequence value , used to index the object with increasing numbers
47
+ _index_value = -1;
48
+ constructor(is_readonly = false) {
49
+ super();
50
+ this.__is_readonly = is_readonly;
51
+ this.clear_changes();
52
+ }
53
+ #setSubProperty(key, subkey, value) {
54
+ let subobj = this.#getProperty(key);
55
+ //@ts-ignore
56
+ if (subobj == null || typeof subobj !== "object")
57
+ subobj = {};
58
+ subobj[subkey] = value;
59
+ this.#setProperty(key, subobj);
60
+ }
61
+ #getSubProperty(key, subkey, original = false) {
62
+ let subobj = this.#getProperty(key, original);
63
+ if (subobj == null || typeof subobj !== "object")
64
+ return undefined;
65
+ return subobj[subkey];
66
+ }
67
+ #setProperty(key, value) {
68
+ if (this[key] === value) {
69
+ /**
70
+ * We set something back to its original value so no need to save it as Delta
71
+ */
72
+ delete this.__delta[key];
73
+ return false;
74
+ }
75
+ else {
76
+ this.__delta[key] = value; //always update delta to keep track of changes
77
+ if (!this.__use_delta)
78
+ this[key] = value; //on noDelta mode, also update the obj
79
+ return true;
80
+ }
81
+ }
82
+ #setDefaultProperty(key, value) {
83
+ //@ts-ignore
84
+ if (this[key] == undefined || this[key] === "" || this[key] === 0) {
85
+ this[key] = value;
86
+ return true;
87
+ }
88
+ return false;
89
+ }
90
+ #getProperty(key, original = false) {
91
+ //check if we should use delta version or normal version for this property
92
+ if (original || !this.__use_delta || !(key in this.__delta))
93
+ return this[key];
94
+ //@ts-ignore
95
+ return this.__delta[key];
96
+ }
97
+ #getTempProperty(key) {
98
+ if (this.__temp == null)
99
+ return undefined;
100
+ return this.__temp[key];
101
+ }
102
+ #setTempProperty(key, value) {
103
+ if (this.__temp == null)
104
+ this.__temp = {};
105
+ this.__temp[key] = value;
106
+ }
107
+ /* -------------------------------------------------------------------------- */
108
+ /* Load */
109
+ /* -------------------------------------------------------------------------- */
110
+ loadValues(initObject, fullUpdate = false) {
111
+ return SimpleObject.loadValues(this, initObject, fullUpdate);
112
+ }
113
+ static loadValues(obj, initObject, fullUpdate = false) {
114
+ SimpleObject.factoryClear(obj);
115
+ if (initObject == null) {
116
+ for (const key in obj) {
117
+ if (typeof obj[key] === "function")
118
+ continue;
119
+ if (key.startsWith("__"))
120
+ continue;
121
+ delete obj[key];
122
+ }
123
+ }
124
+ else if (typeof initObject == "object") {
125
+ for (const key in initObject) {
126
+ if (key.startsWith("__"))
127
+ continue;
128
+ if (fullUpdate ||
129
+ Object.prototype.hasOwnProperty.call(obj, key)) {
130
+ obj[key] = initObject[key];
131
+ }
132
+ }
133
+ }
134
+ return true;
135
+ }
136
+ /* -------------------------------------------------------------------------- */
137
+ static getValue(o, key, original = false) {
138
+ if (o == null)
139
+ return undefined;
140
+ if (o instanceof SimpleObject && typeof o.getValue === "function")
141
+ return o.getValue(key, original);
142
+ if (!original &&
143
+ o.__use_delta != false &&
144
+ typeof o.__delta === "object" &&
145
+ key in o.__delta) {
146
+ //@ts-ignore
147
+ return o.__delta[key];
148
+ }
149
+ return o[key];
150
+ }
151
+ getValue = this.#getProperty;
152
+ get = this.#getProperty;
153
+ getTemp = this.#getTempProperty;
58
154
  /**
59
- * set the response of last save from site
60
- * @param toObj
61
- */
62
- _classPrivateMethodInitSpec(_assertThisInitialized(_this), _setSaveResultObject);
63
- _classPrivateMethodInitSpec(_assertThisInitialized(_this), _setTempProperty);
64
- _classPrivateMethodInitSpec(_assertThisInitialized(_this), _getTempProperty);
65
- _classPrivateMethodInitSpec(_assertThisInitialized(_this), _getProperty);
66
- _classPrivateMethodInitSpec(_assertThisInitialized(_this), _setDefaultProperty);
67
- _classPrivateMethodInitSpec(_assertThisInitialized(_this), _setProperty);
68
- _classPrivateMethodInitSpec(_assertThisInitialized(_this), _getSubProperty);
69
- _classPrivateMethodInitSpec(_assertThisInitialized(_this), _setSubProperty);
70
- //an exact copy of this object is stored here
71
- _defineProperty(_assertThisInitialized(_this), "__originalobject", void 0);
72
- //changes are saved here
73
- _defineProperty(_assertThisInitialized(_this), "__delta", {});
74
- _defineProperty(_assertThisInitialized(_this), "__temp", undefined);
75
- _defineProperty(_assertThisInitialized(_this), "__changed", false);
76
- //the last thing that was changed on this object
77
- _defineProperty(_assertThisInitialized(_this), "__lastChanged", void 0);
78
- //is the object read only
79
- _defineProperty(_assertThisInitialized(_this), "__is_readonly", void 0);
80
- //should we throw errors when encountering an error?
81
- //is TRUE by default
82
- _defineProperty(_assertThisInitialized(_this), "__throw_errors", void 0);
83
- //is this object marked as deleted?
84
- _defineProperty(_assertThisInitialized(_this), "_deleted", void 0);
85
- _defineProperty(_assertThisInitialized(_this), "_deletedBy", void 0);
86
- //errors
87
- _defineProperty(_assertThisInitialized(_this), "__errors", void 0);
88
- _defineProperty(_assertThisInitialized(_this), "__showErrors", void 0);
89
- //save results
90
- _defineProperty(_assertThisInitialized(_this), "__saveResultObject", void 0);
91
- _defineProperty(_assertThisInitialized(_this), "__saveResultIsSuccess", true);
92
- _defineProperty(_assertThisInitialized(_this), "__saveResultType", void 0);
93
- //sequence key (usually managed by the database)
94
- _defineProperty(_assertThisInitialized(_this), "_index_key", "");
95
- //sequence value , used to index the object with increasing numbers
96
- _defineProperty(_assertThisInitialized(_this), "_index_value", -1);
97
- _defineProperty(_assertThisInitialized(_this), "getValue", _classPrivateMethodGet(_assertThisInitialized(_this), _getProperty, _getProperty2));
98
- _defineProperty(_assertThisInitialized(_this), "get", _classPrivateMethodGet(_assertThisInitialized(_this), _getProperty, _getProperty2));
99
- _defineProperty(_assertThisInitialized(_this), "getTemp", _classPrivateMethodGet(_assertThisInitialized(_this), _getTempProperty, _getTempProperty2));
100
- _defineProperty(_assertThisInitialized(_this), "set", _this.setValue);
101
- _defineProperty(_assertThisInitialized(_this), "setTemp", _classPrivateMethodGet(_assertThisInitialized(_this), _setTempProperty, _setTempProperty2));
102
- /**
103
- * set value of a key only if the value is empty
155
+ * set value
104
156
  * @param key
105
157
  * @param value
106
- * @returns
107
- */
108
- _defineProperty(_assertThisInitialized(_this), "setDefault", _this.setDefaultValue);
109
- _defineProperty(_assertThisInitialized(_this), "get_managerClass", function () {
110
- return undefined;
111
- });
112
- _this.__is_readonly = is_readonly;
113
- _this.clear_changes();
114
- return _this;
115
- }
116
- _createClass(SimpleObject, [{
117
- key: "_static",
118
- value: function _static() {
119
- return this.constructor;
120
- }
121
- }, {
122
- key: "loadValues",
123
- value: /* -------------------------------------------------------------------------- */
124
- /* Load */
125
- /* -------------------------------------------------------------------------- */
126
- function loadValues(initObject) {
127
- var fullUpdate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
128
- return SimpleObject.loadValues(this, initObject, fullUpdate);
129
- }
130
- }, {
131
- key: "setValue",
132
- value:
158
+ * @return true if changed , false otherwise
159
+ */
160
+ async setValue(key, value, sendChanges = "auto") {
161
+ if (!this.canModify) {
162
+ if (this.__throw_errors !== false)
163
+ throw Error("Cant use setValue when on readonly mode");
164
+ else
165
+ return false;
166
+ }
167
+ let isValueChanged = false;
168
+ try {
169
+ const oldval = this.getValue(key);
170
+ if (!object_equals(oldval, value, { ignoredStartingWords: "_" })) {
171
+ this.#setProperty(key, value);
172
+ isValueChanged = true;
173
+ }
174
+ else
175
+ isValueChanged = false;
176
+ //console.log("SV:", isValueChanged, oldval, key, value);
177
+ }
178
+ finally {
179
+ if (sendChanges === true ||
180
+ (sendChanges === "auto" && isValueChanged)) {
181
+ await this.notifyChanged("", key, value);
182
+ }
183
+ }
184
+ return isValueChanged;
185
+ }
186
+ set = this.setValue;
187
+ setTemp = this.#setTempProperty;
133
188
  /**
134
- * set value
189
+ * set value of a key only if the value is empty
135
190
  * @param key
136
191
  * @param value
137
- * @return true if changed , false otherwise
138
- */
139
- function () {
140
- var _setValue = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(key, value) {
141
- var sendChanges,
142
- isValueChanged,
143
- oldval,
144
- _args = arguments;
145
- return _regeneratorRuntime().wrap(function _callee$(_context) {
146
- while (1) switch (_context.prev = _context.next) {
147
- case 0:
148
- sendChanges = _args.length > 2 && _args[2] !== undefined ? _args[2] : "auto";
149
- if (this.canModify) {
150
- _context.next = 7;
151
- break;
152
- }
153
- if (!(this.__throw_errors !== false)) {
154
- _context.next = 6;
155
- break;
156
- }
157
- throw Error("Cant use setValue when on readonly mode");
158
- case 6:
159
- return _context.abrupt("return", false);
160
- case 7:
161
- isValueChanged = false;
162
- _context.prev = 8;
163
- oldval = this.getValue(key);
164
- if (!(0, _object.object_equals)(oldval, value, {
165
- ignoredStartingWords: "_"
166
- })) {
167
- _classPrivateMethodGet(this, _setProperty, _setProperty2).call(this, key, value);
168
- isValueChanged = true;
169
- } else isValueChanged = false;
170
- //console.log("SV:", isValueChanged, oldval, key, value);
171
- case 11:
172
- _context.prev = 11;
173
- if (!(sendChanges === true || sendChanges === "auto" && isValueChanged)) {
174
- _context.next = 15;
175
- break;
176
- }
177
- _context.next = 15;
178
- return this.notifyChanged("", key, value);
179
- case 15:
180
- return _context.finish(11);
181
- case 16:
182
- return _context.abrupt("return", isValueChanged);
183
- case 17:
184
- case "end":
185
- return _context.stop();
186
- }
187
- }, _callee, this, [[8,, 11, 16]]);
188
- }));
189
- function setValue(_x, _x2) {
190
- return _setValue.apply(this, arguments);
191
- }
192
- return setValue;
193
- }()
194
- }, {
195
- key: "setDefaultValue",
196
- value:
192
+ * @returns
193
+ */
194
+ setDefaultValue(key, value) {
195
+ return this.#setDefaultProperty(key, value);
196
+ }
197
197
  /**
198
198
  * set value of a key only if the value is empty
199
199
  * @param key
200
200
  * @param value
201
201
  * @returns
202
- */
203
- function setDefaultValue(key, value) {
204
- return _classPrivateMethodGet(this, _setDefaultProperty, _setDefaultProperty2).call(this, key, value);
205
- }
206
- }, {
207
- key: "reset",
208
- value:
202
+ */
203
+ setDefault = this.setDefaultValue;
209
204
  /**
210
205
  * set the value to its original
211
206
  * @param key
212
- */
213
- function () {
214
- var _reset = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(key) {
215
- var notifyChanged,
216
- _args2 = arguments;
217
- return _regeneratorRuntime().wrap(function _callee2$(_context2) {
218
- while (1) switch (_context2.prev = _context2.next) {
219
- case 0:
220
- notifyChanged = _args2.length > 1 && _args2[1] !== undefined ? _args2[1] : "auto";
221
- _context2.next = 3;
222
- return this.setValue(key, this[key], notifyChanged);
223
- case 3:
224
- return _context2.abrupt("return", _context2.sent);
225
- case 4:
226
- case "end":
227
- return _context2.stop();
228
- }
229
- }, _callee2, this);
230
- }));
231
- function reset(_x3) {
232
- return _reset.apply(this, arguments);
233
- }
234
- return reset;
235
- }()
207
+ */
208
+ async reset(key, notifyChanged = "auto") {
209
+ return await this.setValue(key, this[key], notifyChanged);
210
+ }
236
211
  /**
237
212
  * reset all values back to their original
238
213
  * @param key
239
- */
240
- }, {
241
- key: "resetAll",
242
- value: function () {
243
- var _resetAll = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
244
- var notifyChanged,
245
- fr,
246
- key,
247
- _args3 = arguments;
248
- return _regeneratorRuntime().wrap(function _callee3$(_context3) {
249
- while (1) switch (_context3.prev = _context3.next) {
250
- case 0:
251
- notifyChanged = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : "auto";
252
- fr = true;
253
- _context3.t0 = _regeneratorRuntime().keys(this.__delta);
254
- case 3:
255
- if ((_context3.t1 = _context3.t0()).done) {
256
- _context3.next = 13;
257
- break;
258
- }
259
- key = _context3.t1.value;
260
- _context3.t2 = fr;
261
- if (!_context3.t2) {
262
- _context3.next = 10;
263
- break;
264
- }
265
- _context3.next = 9;
266
- return this.reset(key, notifyChanged);
267
- case 9:
268
- _context3.t2 = _context3.sent;
269
- case 10:
270
- fr = _context3.t2;
271
- _context3.next = 3;
272
- break;
273
- case 13:
274
- return _context3.abrupt("return", fr);
275
- case 14:
276
- case "end":
277
- return _context3.stop();
278
- }
279
- }, _callee3, this);
280
- }));
281
- function resetAll() {
282
- return _resetAll.apply(this, arguments);
283
- }
284
- return resetAll;
285
- }()
214
+ */
215
+ async resetAll(notifyChanged = "auto") {
216
+ let fr = true;
217
+ for (const key in this.__delta) {
218
+ fr = fr && (await this.reset(key, notifyChanged));
219
+ }
220
+ return fr;
221
+ }
286
222
  /**
287
223
  * set key of subObject
288
224
  * @param key
289
225
  * @param value
290
226
  * @param subvalue
291
227
  * @return true if changed , false otherwise
292
- */
293
- }, {
294
- key: "setSubValue",
295
- value: function () {
296
- var _setSubValue = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(key, objKey, subvalue) {
297
- var sendChanges,
298
- isValueChanged,
299
- subval,
300
- _args4 = arguments;
301
- return _regeneratorRuntime().wrap(function _callee4$(_context4) {
302
- while (1) switch (_context4.prev = _context4.next) {
303
- case 0:
304
- sendChanges = _args4.length > 3 && _args4[3] !== undefined ? _args4[3] : "auto";
305
- if (this.canModify) {
306
- _context4.next = 7;
307
- break;
308
- }
309
- if (!(this.__throw_errors !== false)) {
310
- _context4.next = 6;
311
- break;
312
- }
313
- throw Error("Cant use setValue when on readonly mode");
314
- case 6:
315
- return _context4.abrupt("return", false);
316
- case 7:
317
- isValueChanged = false;
318
- _context4.prev = 8;
319
- //if accessing subval of an object, make sure the object is not null
320
- subval = _classPrivateMethodGet(this, _getSubProperty, _getSubProperty2).call(this, key, objKey);
321
- if (!(0, _object.object_equals)(subval, subvalue, {
322
- ignoredStartingWords: "_"
323
- })) {
324
- _classPrivateMethodGet(this, _setSubProperty, _setSubProperty2).call(this, key, objKey, subvalue);
325
- isValueChanged = true;
326
- } else isValueChanged = false;
327
- case 11:
328
- _context4.prev = 11;
329
- if (!(sendChanges === true || sendChanges === "auto" && isValueChanged)) {
330
- _context4.next = 15;
331
- break;
332
- }
333
- _context4.next = 15;
334
- return this.notifyChanged("", key, objKey, subvalue);
335
- case 15:
336
- return _context4.finish(11);
337
- case 16:
338
- return _context4.abrupt("return", isValueChanged);
339
- case 17:
340
- case "end":
341
- return _context4.stop();
342
- }
343
- }, _callee4, this, [[8,, 11, 16]]);
344
- }));
345
- function setSubValue(_x4, _x5, _x6) {
346
- return _setSubValue.apply(this, arguments);
347
- }
348
- return setSubValue;
349
- }()
228
+ */
229
+ async setSubValue(key, objKey, subvalue, sendChanges = "auto") {
230
+ if (!this.canModify) {
231
+ if (this.__throw_errors !== false)
232
+ throw Error("Cant use setValue when on readonly mode");
233
+ else
234
+ return false;
235
+ }
236
+ let isValueChanged = false;
237
+ try {
238
+ //if accessing subval of an object, make sure the object is not null
239
+ const subval = this.#getSubProperty(key, objKey);
240
+ if (!object_equals(subval, subvalue, {
241
+ ignoredStartingWords: "_",
242
+ })) {
243
+ this.#setSubProperty(key, objKey, subvalue);
244
+ isValueChanged = true;
245
+ }
246
+ else
247
+ isValueChanged = false;
248
+ }
249
+ finally {
250
+ if (sendChanges === true ||
251
+ (sendChanges === "auto" && isValueChanged)) {
252
+ await this.notifyChanged("", key, objKey, subvalue);
253
+ }
254
+ }
255
+ return isValueChanged;
256
+ }
350
257
  /**
351
258
  * Push value on array
352
259
  * @param key
353
260
  * @param value
354
261
  * @param sendChanges
355
262
  * @returns
356
- */
357
- }, {
358
- key: "pushValue",
359
- value: function () {
360
- var _pushValue = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(key, value) {
361
- var sendChanges,
362
- tempArray,
363
- _args5 = arguments;
364
- return _regeneratorRuntime().wrap(function _callee5$(_context5) {
365
- while (1) switch (_context5.prev = _context5.next) {
366
- case 0:
367
- sendChanges = _args5.length > 2 && _args5[2] !== undefined ? _args5[2] : "auto";
368
- if (!(value == null)) {
369
- _context5.next = 3;
370
- break;
371
- }
372
- return _context5.abrupt("return", false);
373
- case 3:
374
- if (this.canModify) {
375
- _context5.next = 9;
376
- break;
377
- }
378
- if (!(this.__throw_errors !== false)) {
379
- _context5.next = 8;
380
- break;
381
- }
382
- throw Error("Cant use pushValue when on readonly mode");
383
- case 8:
384
- return _context5.abrupt("return", false);
385
- case 9:
386
- if (_classPrivateMethodGet(this, _getProperty, _getProperty2).call(this, key) == null) {
387
- _classPrivateMethodGet(this, _setProperty, _setProperty2).call(this, key, []);
388
- }
389
- tempArray = _classPrivateMethodGet(this, _getProperty, _getProperty2).call(this, key);
390
- if (Array.isArray(tempArray)) {
391
- _context5.next = 17;
392
- break;
393
- }
394
- if (!(this.__throw_errors !== false)) {
395
- _context5.next = 16;
396
- break;
397
- }
398
- throw Error("Cant use pushValue on non Array keys");
399
- case 16:
400
- return _context5.abrupt("return", false);
401
- case 17:
402
- _classPrivateMethodGet(this, _setProperty, _setProperty2).call(this, key, [].concat(_toConsumableArray(tempArray), [value]));
403
- if (!(sendChanges === true || sendChanges === "auto")) {
404
- _context5.next = 21;
405
- break;
406
- }
407
- _context5.next = 21;
408
- return this.notifyChanged("", key, value);
409
- case 21:
410
- return _context5.abrupt("return", tempArray);
411
- case 22:
412
- case "end":
413
- return _context5.stop();
414
- }
415
- }, _callee5, this);
416
- }));
417
- function pushValue(_x7, _x8) {
418
- return _pushValue.apply(this, arguments);
419
- }
420
- return pushValue;
421
- }()
422
- }, {
423
- key: "notifyChanged",
424
- value: function () {
425
- var _notifyChanged = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6(type, key, value, subvalue) {
426
- var lc, manager_class;
427
- return _regeneratorRuntime().wrap(function _callee6$(_context6) {
428
- while (1) switch (_context6.prev = _context6.next) {
429
- case 0:
430
- if (value === undefined && type != "meta") value = this.getValue(key);
431
- this.__changed = true;
432
- lc = "";
433
- if (type) lc += "$".concat(String(type), "$");
434
- if (subvalue) {
435
- lc += "".concat(String(key), ".").concat(value);
436
- } else {
437
- lc += "".concat(String(key));
438
- }
439
- this.__lastChanged = lc;
440
- /* --------------------------- notify the manager --------------------------- */
441
- manager_class = this.manager;
442
- if (!(manager_class instanceof _ObjectManager["default"])) {
443
- _context6.next = 10;
444
- break;
445
- }
446
- _context6.next = 10;
447
- return manager_class.notifyChanged(type, key, value, subvalue);
448
- case 10:
449
- case "end":
450
- return _context6.stop();
451
- }
452
- }, _callee6, this);
453
- }));
454
- function notifyChanged(_x9, _x10, _x11, _x12) {
455
- return _notifyChanged.apply(this, arguments);
456
- }
457
- return notifyChanged;
458
- }()
263
+ */
264
+ async pushValue(key, value, sendChanges = "auto") {
265
+ if (value == null)
266
+ return false;
267
+ if (!this.canModify) {
268
+ if (this.__throw_errors !== false)
269
+ throw Error("Cant use pushValue when on readonly mode");
270
+ else
271
+ return false;
272
+ }
273
+ if (this.#getProperty(key) == null) {
274
+ this.#setProperty(key, []);
275
+ }
276
+ let tempArray = this.#getProperty(key);
277
+ if (!Array.isArray(tempArray)) {
278
+ if (this.__throw_errors !== false)
279
+ throw Error("Cant use pushValue on non Array keys");
280
+ else
281
+ return false;
282
+ }
283
+ this.#setProperty(key, [...tempArray, value]);
284
+ if (sendChanges === true || sendChanges === "auto") {
285
+ await this.notifyChanged("", key, value);
286
+ }
287
+ return tempArray;
288
+ }
289
+ async notifyChanged(type, key, value, subvalue) {
290
+ if (value === undefined && type != "meta")
291
+ value = this.getValue(key);
292
+ this.__changed = true;
293
+ let lc = "";
294
+ if (type)
295
+ lc += `$${String(type)}$`;
296
+ if (subvalue) {
297
+ lc += `${String(key)}.${value}`;
298
+ }
299
+ else {
300
+ lc += `${String(key)}`;
301
+ }
302
+ this.__lastChanged = lc;
303
+ /* --------------------------- notify the manager --------------------------- */
304
+ const manager_class = this.manager;
305
+ if (manager_class instanceof ObjectManager) {
306
+ await manager_class.notifyChanged(type, key, value, subvalue);
307
+ }
308
+ }
459
309
  /**
460
310
  * check if a key can be changed on an object
461
- * @param object
462
- * @param key
463
- * @param useExtraProps
311
+ * @param object the object we are checking
312
+ * @param key key of the object
313
+ * @param useExtraProps should we check extra props?
464
314
  * @returns
465
- */
466
- }, {
467
- key: "apply_changes",
468
- value: /* -------------------------------------------------------------------------- */
469
- /* Changes */
470
- /* -------------------------------------------------------------------------- */
315
+ */
316
+ static canChangeKey(object, key, useExtraProps) {
317
+ if (!object || !key)
318
+ return false;
319
+ if (useExtraProps) {
320
+ const __extraProperties = object.constructor["__extraProperties"];
321
+ if (__extraProperties != null && __extraProperties.includes(key))
322
+ return true;
323
+ }
324
+ /* -------------------------------------------------------------------------- */
325
+ const __changeables = object.constructor["__changeables"];
326
+ const __unchangeables = object.constructor["__unchangeables"];
327
+ const __protectedProperties = object.constructor["__protectedProperties"];
328
+ /* -------------------------------------------------------------------------- */
329
+ if (__changeables != null && !__changeables.includes(key))
330
+ return false;
331
+ if (__unchangeables != null && __unchangeables.includes(key))
332
+ return false;
333
+ //protected keys can only be changed by the creator of this object
334
+ //make sure you set the is_current_user function correctly
335
+ if (__protectedProperties != null &&
336
+ __protectedProperties.includes(key)) {
337
+ if (object.isNew)
338
+ return true;
339
+ const creatorOfObject = object.get("_creator");
340
+ return Boolean(gfunc.run_action_sync("is_current_user", creatorOfObject));
341
+ }
342
+ return true;
343
+ }
344
+ static hasIllegalChanges(referenceObject, changesObject, userObject) {
345
+ const __protectedProperties = object_getStatic(referenceObject, "__protectedProperties");
346
+ if (__protectedProperties == null)
347
+ return false;
348
+ if (Boolean(gfunc.run_action_sync("is_current_user", userObject ||
349
+ changesObject.__user ||
350
+ changesObject._creator)))
351
+ return false;
352
+ for (const key in changesObject) {
353
+ if (__protectedProperties.includes(key)) {
354
+ return false;
355
+ }
356
+ }
357
+ return true;
358
+ }
359
+ /* -------------------------------------------------------------------------- */
360
+ /* Changes */
361
+ /* -------------------------------------------------------------------------- */
471
362
  /**
472
363
  * Apply the changes and empty the delta object
473
- */
474
- function apply_changes() {
475
- try {
476
- if (!this.__use_delta) {
477
- //in this mode , we track changes by updating the original product
478
- this.setOriginal();
479
- return true;
480
- }
481
- if (!this.isChanged) {
482
- console.warn("No changes to apply");
483
- return false;
484
- }
485
- for (var key in this.__delta) {
486
- var nv = this.__delta[key];
487
- this[key] = nv;
488
- }
489
- return true;
490
- } finally {
491
- this.clear_changes();
492
- }
493
- }
364
+ */
365
+ apply_changes() {
366
+ try {
367
+ if (!this.__use_delta) {
368
+ //in this mode , we track changes by updating the original product
369
+ this.setOriginal();
370
+ return true;
371
+ }
372
+ if (!this.isChanged) {
373
+ console.warn("No changes to apply");
374
+ return false;
375
+ }
376
+ for (const key in this.__delta) {
377
+ const nv = this.__delta[key];
378
+ this[key] = nv;
379
+ }
380
+ return true;
381
+ }
382
+ finally {
383
+ this.clear_changes();
384
+ }
385
+ }
494
386
  /**
495
387
  * clear and discard all changes
496
388
  * @returns
497
- */
498
- }, {
499
- key: "clear_changes",
500
- value: function clear_changes() {
501
- this.__delta = {};
502
- this.__changed = false;
503
- return true;
504
- }
389
+ */
390
+ clear_changes() {
391
+ this.__delta = {};
392
+ this.__changed = false;
393
+ return true;
394
+ }
505
395
  /**
506
396
  * clear and discard all temp values
507
397
  * @returns
508
- */
509
- }, {
510
- key: "clear_cache",
511
- value: function clear_cache() {
512
- delete this.__temp;
513
- return true;
514
- }
398
+ */
399
+ clear_cache() {
400
+ delete this.__temp;
401
+ return true;
402
+ }
515
403
  /**
516
404
  * Sets readonly property on given objects
517
405
  * @param objs array of given objects or a single object
518
406
  * @param readonlyval readonly
519
407
  * @param clearChanges should we clean the changes after setting readonly
520
- */
521
- }, {
522
- key: "isChanged",
523
- get: /* -------------------------------------------------------------------------- */
524
- /* Get/Check */
525
- /* -------------------------------------------------------------------------- */
526
- function get() {
527
- var _this2 = this;
528
- ////const deltaIsBlank = object_isEmpty(this.__delta);
529
- ////if (!deltaIsBlank) return true; //delta is not blank, definitely changed
530
- ////if (this.__use_delta) return !deltaIsBlank; //trust the delta.
531
- if (this.__use_delta) return !(0, _object.object_isEmpty)(this.__delta);
532
- /* -------------------------------------------------------------------------- */
533
- /* check the properties one by one */
534
- /* -------------------------------------------------------------------------- */
535
- var orig = this.getOriginal();
536
- if (!orig) return false; //we dont know if anything has changed
537
- /* if object is not using delta mode, check changes by comparing changable fields with original object */
538
- if (Array.isArray(this.__changeables)) {
539
- //console.log("chk", this.__changeables, "for changes");
540
- return this.__changeables.find(function (c) {
541
- return !(0, _object.object_equals)(_this2[c], orig[c]);
542
- }) != undefined;
543
- } else {
544
- /* check all fields */
545
- for (var key in this) {
546
- if (key.startsWith("__")) continue;
547
- if (!(0, _object.object_equals)(this[key], orig[key])) return true;
548
- }
549
- return false;
550
- }
551
- return false;
552
- }
553
- }, {
554
- key: "isDeleted",
555
- get: function get() {
556
- return this._deleted || false;
557
- },
558
- set: function set(v) {
559
- this._deleted = v;
560
- }
561
- }, {
562
- key: "d",
563
- get: function get() {
564
- return this.__use_delta ? this.__delta : this;
565
- }
566
- /* all updated properties */
567
- }, {
568
- key: "allproperties",
569
- get: function get() {
570
- var result = _objectSpread(_objectSpread({}, this), this.__delta);
571
- result.__delta = {};
572
- return result;
573
- }
574
- }, {
575
- key: "canModify",
576
- get: function get() {
577
- return !Boolean(this.__is_readonly);
578
- }
579
- }, {
580
- key: "__cache_name",
581
- get: function get() {
582
- return this.constructor["__cache_name"];
583
- }
584
- }, {
585
- key: "__changeables",
586
- get: function get() {
587
- return this.constructor["__changeables"];
588
- }
589
- }, {
590
- key: "__unchangeables",
591
- get: function get() {
592
- return this.constructor["__unchangeables"];
593
- }
594
- }, {
595
- key: "__use_delta",
596
- get: function get() {
597
- return this.constructor["__use_delta"];
598
- }
599
- }, {
600
- key: "isSaved",
601
- get: function get() {
602
- var _this$__saveResultIsS;
603
- return Boolean((_this$__saveResultIsS = this.__saveResultIsSuccess) !== null && _this$__saveResultIsS !== void 0 ? _this$__saveResultIsS : false);
604
- }
605
- }, {
606
- key: "isNew",
607
- get: function get() {
608
- var mid = this.getID();
609
- if (!mid) return true;
610
- if (typeof mid === "string") return mid === "" || mid === "-1";
611
- if (typeof mid === "number") return mid === -1;
612
- return false;
613
- }
614
- }, {
615
- key: "lastChanged",
616
- get: function get() {
617
- return this.__lastChanged || "";
618
- }
619
- }, {
620
- key: "manager",
621
- get: function get() {
622
- return this.get_managerClass() || undefined;
623
- }
624
- }, {
625
- key: "set_managerClass",
626
- value: function set_managerClass(mng) {
627
- if ((mng instanceof _ObjectManager["default"] || mng instanceof _WebObjectManager["default"]) && typeof mng.event_run === "function") this.get_managerClass = function () {
628
- return mng;
629
- };else {
630
- console.error("set_managerClass was used with a bad manager. make sure the input to this function is a correct ObjectManager");
631
- }
632
- }
633
- }, {
634
- key: "getIndexOrID",
635
- value: function getIndexOrID() {
636
- return SimpleObject.getIndexOrID(this);
637
- }
638
- }, {
639
- key: "getIndex",
640
- value: function getIndex() {
641
- return SimpleObject.getIndex(this);
642
- }
643
- }, {
644
- key: "getID",
645
- value: function getID() {
646
- return SimpleObject.getID(this);
647
- }
648
- }, {
649
- key: "event_run",
650
- value:
651
- /* -------------------------------------------------------------------------- */
652
- /* Events */
653
- /* -------------------------------------------------------------------------- */
654
- function () {
655
- var _event_run = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(eventName) {
656
- var _this$manager;
657
- var _len,
658
- params,
659
- _key,
660
- _args7 = arguments;
661
- return _regeneratorRuntime().wrap(function _callee7$(_context7) {
662
- while (1) switch (_context7.prev = _context7.next) {
663
- case 0:
664
- if (this.manager) {
665
- _context7.next = 3;
666
- break;
667
- }
668
- console.error("you cant use events if your object has no manager");
669
- return _context7.abrupt("return");
670
- case 3:
671
- for (_len = _args7.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
672
- params[_key - 1] = _args7[_key];
673
- }
674
- _context7.next = 6;
675
- return (_this$manager = this.manager).event_run.apply(_this$manager, [eventName].concat(params));
676
- case 6:
677
- return _context7.abrupt("return", _context7.sent);
678
- case 7:
679
- case "end":
680
- return _context7.stop();
681
- }
682
- }, _callee7, this);
683
- }));
684
- function event_run(_x13) {
685
- return _event_run.apply(this, arguments);
686
- }
687
- return event_run;
688
- }()
689
- }, {
690
- key: "event_use",
691
- value: function event_use(name, runEvent) {
692
- var onlyOn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
693
- var runOnce = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
694
- if (!this.manager) {
695
- console.error("you cant use events if your object has no manager");
696
- return;
697
- }
698
- return this.manager.event_use(name, runEvent, onlyOn, runOnce);
699
- }
700
- }, {
701
- key: "event_remove",
702
- value: function event_remove(name, uname) {
703
- if (!this.manager) {
704
- console.error("you cant use events if your object has no manager");
705
- return;
706
- }
707
- return this.manager.event_remove(name, uname);
708
- }
709
- }, {
710
- key: "event_add",
711
- value: function () {
712
- var _event_add = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(name, uname, runEvent) {
713
- var onlyOn,
714
- runOnce,
715
- _args8 = arguments;
716
- return _regeneratorRuntime().wrap(function _callee8$(_context8) {
717
- while (1) switch (_context8.prev = _context8.next) {
718
- case 0:
719
- onlyOn = _args8.length > 3 && _args8[3] !== undefined ? _args8[3] : null;
720
- runOnce = _args8.length > 4 && _args8[4] !== undefined ? _args8[4] : false;
721
- if (this.manager) {
722
- _context8.next = 5;
723
- break;
724
- }
725
- console.error("you cant use events if your object has no manager");
726
- return _context8.abrupt("return");
727
- case 5:
728
- _context8.next = 7;
729
- return this.manager.event_add(name, uname, runEvent, onlyOn, runOnce);
730
- case 7:
731
- case "end":
732
- return _context8.stop();
733
- }
734
- }, _callee8, this);
735
- }));
736
- function event_add(_x14, _x15, _x16) {
737
- return _event_add.apply(this, arguments);
738
- }
739
- return event_add;
740
- }()
741
- /* -------------------------------------------------------------------------- */
742
- /* Original */
743
- /* -------------------------------------------------------------------------- */
744
- }, {
745
- key: "getOriginal",
746
- value: function getOriginal() {
747
- return this.__originalobject || undefined;
748
- }
749
- }, {
750
- key: "setOriginal",
751
- value: function setOriginal() {
752
- var toObj = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
753
- if (toObj === null) {
754
- delete this.__originalobject;
755
- return;
756
- }
757
- if (!this.canModify) {
758
- console.warn("Cant use setOriginal on non original OR readonly objects ! this will create an infinite loop");
759
- delete this.__originalobject;
760
- return;
761
- }
762
- if (toObj === 0) {
763
- toObj = this;
764
- }
765
- var cloneObject = (0, _object.object_clone)(toObj);
766
- SimpleObject.setReadonly(cloneObject, true);
767
- this.__originalobject = (0, _object.object_removeKeys)(cloneObject, ["__"]);
768
- return this;
769
- }
770
- }, {
771
- key: "setSaveResult",
772
- value:
773
- /**
774
- * set the response of last save from site
775
- * and its type
776
- * @param toObj
777
- */
778
- function setSaveResult(toObj, type) {
779
- if (toObj != null) {
780
- _classPrivateMethodGet(this, _setSaveResultObject, _setSaveResultObject2).call(this, toObj);
781
- } else {
782
- _classPrivateMethodGet(this, _setSaveResultObject, _setSaveResultObject2).call(this, null);
783
- }
784
- //check if the given object is a valid save result
785
- if (type === "error") this.__saveResultIsSuccess = false;else this.__saveResultIsSuccess = Boolean(type === "nothing" || this.constructor["isResultValid"](toObj));
786
- if (type === "auto") {
787
- type = this.__saveResultIsSuccess ? "normal" : "error";
788
- }
789
- this.__saveResultType = type;
790
- }
791
- }, {
792
- key: "getSaveResult",
793
- value: function getSaveResult() {
794
- var original = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
795
- if (this.isSaved) return this.__saveResultObject;
796
- return false;
797
- }
798
- }, {
799
- key: "getSaveResultType",
800
- value: function getSaveResultType() {
801
- return this.__saveResultType || "nothing";
802
- }
803
- /* -------------------------------------------------------------------------- */
804
- /* statics */
805
- /* -------------------------------------------------------------------------- */
806
- }], [{
807
- key: "loadValues",
808
- value: function loadValues(obj, initObject) {
809
- var fullUpdate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
810
- SimpleObject.factoryClear(obj);
811
- if (initObject == null) {
812
- for (var key in obj) {
813
- if (typeof obj[key] === "function") continue;
814
- if (key.startsWith("__")) continue;
815
- delete obj[key];
816
- }
817
- } else if (_typeof(initObject) == "object") {
818
- for (var _key2 in initObject) {
819
- if (_key2.startsWith("__")) continue;
820
- if (fullUpdate || Object.prototype.hasOwnProperty.call(obj, _key2)) {
821
- obj[_key2] = initObject[_key2];
822
- }
823
- }
824
- }
825
- return true;
826
- }
827
- /* -------------------------------------------------------------------------- */
828
- }, {
829
- key: "getValue",
830
- value: function getValue(o, key) {
831
- var original = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
832
- if (o == null) return undefined;
833
- if (o instanceof SimpleObject && typeof o.getValue === "function") return o.getValue(key, original);
834
- if (!original && o.__use_delta != false && _typeof(o.__delta) === "object" && key in o.__delta) {
835
- //@ts-ignore
836
- return o.__delta[key];
837
- }
838
- return o[key];
839
- }
840
- }, {
841
- key: "canChangeKey",
842
- value: function canChangeKey(object, key, useExtraProps) {
843
- if (!object || !key) return false;
844
- if (useExtraProps) {
845
- var __extraProperties = object.constructor["__extraProperties"];
846
- if (__extraProperties != null && __extraProperties.includes(key)) return true;
847
- }
848
- /* -------------------------------------------------------------------------- */
849
- var __changeables = object.constructor["__changeables"];
850
- var __unchangeables = object.constructor["__unchangeables"];
851
- var __protectedProperties = object.constructor["__protectedProperties"];
852
- /* -------------------------------------------------------------------------- */
853
- if (__changeables != null && !__changeables.includes(key)) return false;
854
- if (__unchangeables != null && __unchangeables.includes(key)) return false;
855
- //protected keys can only be changed by the creator of this object
856
- if (__protectedProperties != null && __protectedProperties.includes(key)) {
857
- if (object.isNew) return true;
858
- var creatorOfObject = object.get("_creator");
859
- return _global.gfunc.run_action_sync("is_current_user", creatorOfObject);
860
- }
861
- return true;
862
- }
863
- }, {
864
- key: "setReadonly",
865
- value: function setReadonly(objs) {
866
- var readonlyval = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
867
- var clearChanges = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
868
- var checkObjs = [];
869
- if (!objs) objs = [];
870
- if (!Array.isArray(objs)) checkObjs = [objs];else checkObjs = objs;
871
- for (var index = 0; index < checkObjs.length; index++) {
872
- var obj = checkObjs[index];
873
- obj.__is_readonly = readonlyval;
874
- if (obj instanceof SimpleObject) {
875
- if (obj.canModify) {
876
- if (!obj.getOriginal()) obj.setOriginal();
877
- } else {
878
- if (clearChanges) obj.clear_changes();
879
- //we dont need the original object in readonly mode
880
- obj.setOriginal(null);
881
- }
882
- }
883
- }
884
- }
885
- }, {
886
- key: "setThrowErrors",
887
- value: function setThrowErrors(objs) {
888
- var throwErr = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
889
- var checkObjs = [];
890
- if (!objs) objs = [];
891
- if (!Array.isArray(objs)) checkObjs = [objs];else checkObjs = objs;
892
- for (var index = 0; index < checkObjs.length; index++) {
893
- var element = checkObjs[index];
894
- element.__throw_errors = throwErr;
895
- }
896
- }
897
- }, {
898
- key: "isDeleted",
899
- value: function isDeleted(obj) {
900
- if (obj instanceof SimpleObject) return obj.isDeleted === true;
901
- return false;
902
- }
903
- }, {
904
- key: "getIndexOrID",
905
- value: function getIndexOrID(o) {
906
- var res = SimpleObject.getIndex(o);
907
- if (!res || res == -1) res = SimpleObject.getID(o);
908
- return res || -1;
909
- }
910
- }, {
911
- key: "getIndex",
912
- value: function getIndex(o) {
913
- if (o == null || o == undefined) return -1;
914
- switch (_typeof(o)) {
915
- case "object":
916
- return o._index_value || -1;
917
- case "number":
918
- case "string":
919
- return Number(o);
920
- }
921
- return -1;
922
- }
923
- }, {
924
- key: "getID",
925
- value: function getID(o) {
926
- if (o == null || o == undefined) return "";
927
- switch (_typeof(o)) {
928
- case "object":
929
- if (o._bsontype == "ObjectID" && typeof o.toString === "function") {
930
- return o.toString();
931
- }
932
- return String(o._id || o.ID || o.id || o.__data_id || "");
933
- case "string":
934
- case "number":
935
- return String(o);
936
- }
937
- return "";
938
- }
939
- }, {
940
- key: "setOriginal",
941
- value: function setOriginal(obj) {
942
- var toObj = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
943
- if (!(obj instanceof SimpleObject)) return undefined;
944
- return obj.setOriginal(toObj);
945
- }
946
- }, {
947
- key: "getOriginal",
948
- value: function getOriginal(obj) {
949
- if (obj instanceof SimpleObject) return obj.getOriginal();
950
- return obj === null || obj === void 0 ? void 0 : obj.__originalobject;
951
- }
952
- /* -------------------------------------------------------------------------- */
953
- /* Errors */
954
- /* -------------------------------------------------------------------------- */
955
- }, {
956
- key: "addError",
957
- value: function addError(o, title, message) {
958
- var sendToRegister = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : "auto";
959
- var errStr = (0, _string.combine_if_not_blank)(title, " : ", message);
960
- if (o) {
961
- if (!Array.isArray(o.__errors)) o.__errors = [];
962
- o.__errors.push(errStr);
963
- if (o.__showErrors === false) return;
964
- } else if (sendToRegister === "auto") sendToRegister = true;
965
- if (sendToRegister === true) {
966
- console.error("[REGISTER-ERROR]", errStr);
967
- _global.gfunc.run_action("add_error", {
968
- title: title,
969
- message: message,
970
- type: "error"
971
- });
972
- } else {
973
- console.error("[ERROR]", errStr);
974
- }
975
- return (o === null || o === void 0 ? void 0 : o.__errors) || [];
976
- }
977
- }, {
978
- key: "getErrors",
979
- value: function getErrors(o) {
980
- return (o === null || o === void 0 ? void 0 : o.__errors) || [];
981
- }
982
- }, {
983
- key: "clearErrors",
984
- value: function clearErrors(o) {
985
- if (o) o.__errors = [];
986
- return true;
987
- }
988
- /* -------------------------------------------------------------------------- */
989
- /* Save Results */
990
- /* -------------------------------------------------------------------------- */
408
+ */
409
+ static setReadonly(objs, readonlyval = true, clearChanges = false) {
410
+ let checkObjs = [];
411
+ if (!objs)
412
+ objs = [];
413
+ if (!Array.isArray(objs))
414
+ checkObjs = [objs];
415
+ else
416
+ checkObjs = objs;
417
+ for (let index = 0; index < checkObjs.length; index++) {
418
+ const obj = checkObjs[index];
419
+ obj.__is_readonly = readonlyval;
420
+ if (obj instanceof SimpleObject) {
421
+ if (obj.canModify) {
422
+ if (!obj.getOriginal())
423
+ obj.setOriginal();
424
+ }
425
+ else {
426
+ if (clearChanges)
427
+ obj.clear_changes();
428
+ //we dont need the original object in readonly mode
429
+ obj.setOriginal(null);
430
+ }
431
+ }
432
+ }
433
+ }
434
+ static setThrowErrors(objs, throwErr = true) {
435
+ let checkObjs = [];
436
+ if (!objs)
437
+ objs = [];
438
+ if (!Array.isArray(objs))
439
+ checkObjs = [objs];
440
+ else
441
+ checkObjs = objs;
442
+ for (let index = 0; index < checkObjs.length; index++) {
443
+ const element = checkObjs[index];
444
+ element.__throw_errors = throwErr;
445
+ }
446
+ }
447
+ /* -------------------------------------------------------------------------- */
448
+ /* Get/Check */
449
+ /* -------------------------------------------------------------------------- */
450
+ get isChanged() {
451
+ ////const deltaIsBlank = object_isEmpty(this.__delta);
452
+ ////if (!deltaIsBlank) return true; //delta is not blank, definitely changed
453
+ ////if (this.__use_delta) return !deltaIsBlank; //trust the delta.
454
+ if (this.__use_delta)
455
+ return !object_isEmpty(this.__delta);
456
+ /* -------------------------------------------------------------------------- */
457
+ /* check the properties one by one */
458
+ /* -------------------------------------------------------------------------- */
459
+ const orig = this.getOriginal();
460
+ if (!orig)
461
+ return false; //we dont know if anything has changed
462
+ /* if object is not using delta mode, check changes by comparing changable fields with original object */
463
+ if (Array.isArray(this.__changeables)) {
464
+ //console.log("chk", this.__changeables, "for changes");
465
+ return (this.__changeables.find((c) => {
466
+ return !object_equals(this[c], orig[c]);
467
+ }) != undefined);
468
+ }
469
+ else {
470
+ /* check all fields */
471
+ for (const key in this) {
472
+ if (key.startsWith("__"))
473
+ continue;
474
+ if (!object_equals(this[key], orig[key]))
475
+ return true;
476
+ }
477
+ return false;
478
+ }
479
+ return false;
480
+ }
481
+ get isDeleted() {
482
+ return this._deleted || false;
483
+ }
484
+ set isDeleted(v) {
485
+ this._deleted = v;
486
+ }
487
+ get d() {
488
+ return this.__use_delta ? this.__delta : this;
489
+ }
490
+ /* all updated properties */
491
+ get allproperties() {
492
+ const result = { ...this, ...this.__delta };
493
+ result.__delta = {};
494
+ return result;
495
+ }
496
+ get canModify() {
497
+ return !Boolean(this.__is_readonly);
498
+ }
499
+ get __cache_name() {
500
+ return this.constructor["__cache_name"];
501
+ }
502
+ get __changeables() {
503
+ return this.constructor["__changeables"];
504
+ }
505
+ get __unchangeables() {
506
+ return this.constructor["__unchangeables"];
507
+ }
508
+ get __use_delta() {
509
+ return this.constructor["__use_delta"];
510
+ }
511
+ get isSaved() {
512
+ return Boolean(this.__saveResultIsSuccess ?? false);
513
+ }
514
+ get isNew() {
515
+ const mid = this.getID();
516
+ if (!mid)
517
+ return true;
518
+ if (typeof mid === "string")
519
+ return mid === "" || mid === "-1";
520
+ if (typeof mid === "number")
521
+ return mid === -1;
522
+ return false;
523
+ }
524
+ get lastChanged() {
525
+ return this.__lastChanged || "";
526
+ }
527
+ get manager() {
528
+ return this.get_managerClass() || undefined;
529
+ }
530
+ get_managerClass = () => undefined;
531
+ set_managerClass(mng) {
532
+ if ((mng instanceof ObjectManager || mng instanceof WebObjectManager) &&
533
+ typeof mng.event_run === "function")
534
+ this.get_managerClass = () => mng;
535
+ else {
536
+ console.error("set_managerClass was used with a bad manager. make sure the input to this function is a correct ObjectManager");
537
+ }
538
+ }
539
+ static isDeleted(obj) {
540
+ if (obj instanceof SimpleObject)
541
+ return obj.isDeleted === true;
542
+ return false;
543
+ }
544
+ getIndexOrID() {
545
+ return SimpleObject.getIndexOrID(this);
546
+ }
547
+ getIndex() {
548
+ return SimpleObject.getIndex(this);
549
+ }
550
+ getID() {
551
+ return SimpleObject.getID(this);
552
+ }
553
+ static getIndexOrID(o) {
554
+ let res = SimpleObject.getIndex(o);
555
+ if (!res || res == -1)
556
+ res = SimpleObject.getID(o);
557
+ return res || -1;
558
+ }
559
+ static getIndex(o) {
560
+ if (o == null || o == undefined)
561
+ return -1;
562
+ switch (typeof o) {
563
+ case "object":
564
+ return o._index_value || -1;
565
+ case "number":
566
+ case "string":
567
+ return Number(o);
568
+ }
569
+ return -1;
570
+ }
571
+ static getID(o) {
572
+ if (o == null || o == undefined)
573
+ return "";
574
+ switch (typeof o) {
575
+ case "object":
576
+ if (o._bsontype == "ObjectID" &&
577
+ typeof o.toString === "function") {
578
+ return o.toString();
579
+ }
580
+ return String(o._id || o.ID || o.id || o.__data_id || "");
581
+ case "string":
582
+ case "number":
583
+ return String(o);
584
+ }
585
+ return "";
586
+ }
587
+ /* -------------------------------------------------------------------------- */
588
+ /* Events */
589
+ /* -------------------------------------------------------------------------- */
590
+ async event_run(eventName, ...params) {
591
+ if (!this.manager) {
592
+ console.error("you cant use events if your object has no manager");
593
+ return;
594
+ }
595
+ return await this.manager.event_run(eventName, ...params);
596
+ }
597
+ event_use(name, runEvent, onlyOn = null, runOnce = false) {
598
+ if (!this.manager) {
599
+ console.error("you cant use events if your object has no manager");
600
+ return;
601
+ }
602
+ return this.manager.event_use(name, runEvent, onlyOn, runOnce);
603
+ }
604
+ event_remove(name, uname) {
605
+ if (!this.manager) {
606
+ console.error("you cant use events if your object has no manager");
607
+ return;
608
+ }
609
+ return this.manager.event_remove(name, uname);
610
+ }
611
+ async event_add(name, uname, runEvent, onlyOn = null, runOnce = false) {
612
+ if (!this.manager) {
613
+ console.error("you cant use events if your object has no manager");
614
+ return;
615
+ }
616
+ await this.manager.event_add(name, uname, runEvent, onlyOn, runOnce);
617
+ }
618
+ /* -------------------------------------------------------------------------- */
619
+ /* Original */
620
+ /* -------------------------------------------------------------------------- */
621
+ getOriginal() {
622
+ return this.__originalobject || undefined;
623
+ }
624
+ setOriginal(toObj = 0) {
625
+ if (toObj === null) {
626
+ delete this.__originalobject;
627
+ return;
628
+ }
629
+ if (!this.canModify) {
630
+ console.warn("Cant use setOriginal on non original OR readonly objects ! this will create an infinite loop");
631
+ delete this.__originalobject;
632
+ return;
633
+ }
634
+ if (toObj === 0) {
635
+ toObj = this;
636
+ }
637
+ const cloneObject = object_clone(toObj);
638
+ SimpleObject.setReadonly(cloneObject, true);
639
+ this.__originalobject = object_removeKeys(cloneObject, ["__"]);
640
+ return this;
641
+ }
642
+ static setOriginal(obj, toObj = 0) {
643
+ if (!(obj instanceof SimpleObject))
644
+ return undefined;
645
+ return obj.setOriginal(toObj);
646
+ }
647
+ static getOriginal(obj) {
648
+ if (obj instanceof SimpleObject)
649
+ return obj.getOriginal();
650
+ return obj?.__originalobject;
651
+ }
652
+ /* -------------------------------------------------------------------------- */
653
+ /* Errors */
654
+ /* -------------------------------------------------------------------------- */
655
+ static addError(o, title, message, sendToRegister = "auto") {
656
+ const errStr = combine_if_not_blank(title, " : ", message);
657
+ if (o) {
658
+ if (!Array.isArray(o.__errors))
659
+ o.__errors = [];
660
+ o.__errors.push(errStr);
661
+ if (o.__showErrors === false)
662
+ return;
663
+ }
664
+ else if (sendToRegister === "auto")
665
+ sendToRegister = true;
666
+ if (sendToRegister === true) {
667
+ console.error("[REGISTER-ERROR]", errStr);
668
+ gfunc.run_action("add_error", {
669
+ title: title,
670
+ message: message,
671
+ type: "error",
672
+ });
673
+ }
674
+ else {
675
+ console.error("[ERROR]", errStr);
676
+ }
677
+ return o?.__errors || [];
678
+ }
679
+ static getErrors(o) {
680
+ return o?.__errors || [];
681
+ }
682
+ static clearErrors(o) {
683
+ if (o)
684
+ o.__errors = [];
685
+ return true;
686
+ }
687
+ /* -------------------------------------------------------------------------- */
688
+ /* Save Results */
689
+ /* -------------------------------------------------------------------------- */
991
690
  /**
992
691
  * Checks if the given object is a valid and truthy save result
993
692
  * @param result_object
994
693
  * @returns
995
- */
996
- }, {
997
- key: "isResultValid",
998
- value: function isResultValid(result_object) {
999
- var sub = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
1000
- if ((0, _object.object_isEmpty)(result_object)) return false;
1001
- switch (_typeof(result_object)) {
1002
- case "string":
1003
- try {
1004
- result_object = JSON.parse(result_object);
1005
- return this.isResultValid(result_object);
1006
- } catch (_unused) {
1007
- return false;
1008
- }
1009
- case "object":
1010
- if ((0, _object.object_isTrue)(result_object.acknowledged)) {
1011
- return true;
1012
- }
1013
- if (result_object.expected && result_object.result) {
1014
- return (0, _object.object_equals)(result_object.expected, result_object.result);
1015
- }
1016
- return Number(this.getID(result_object)) >= 0;
1017
- case "number":
1018
- return result_object > 0;
1019
- case "boolean":
1020
- return result_object === true;
1021
- }
1022
- return false;
1023
- }
1024
- }, {
1025
- key: "factoryClear",
1026
- value: function factoryClear(obj) {
1027
- obj.clear_changes();
1028
- SimpleObject.clearErrors(obj);
1029
- }
1030
- }, {
1031
- key: "delete_cache",
1032
- value: function delete_cache() {
1033
- if (!this.__cache_name) return;
1034
- _global.gcache.delete_cache(this.__cache_name);
1035
- }
1036
- }, {
1037
- key: "get_canModify",
1038
- value: function get_canModify(o) {
1039
- if (o instanceof SimpleObject) return o.canModify;
1040
- return false;
1041
- }
1042
- /* -------------------------------------------------------------------------- */
1043
- }, {
1044
- key: "equals",
1045
- value: function equals(a, b) {
1046
- console.warn("Dont use the default equals method !");
1047
- if (a == undefined || b == undefined) return false;
1048
- return a === b;
1049
- }
1050
- }]);
1051
- return SimpleObject;
1052
- }(_MapableObject2.MapableObject);
1053
- exports.SimpleObject = SimpleObject;
1054
- function _setSubProperty2(key, subkey, value) {
1055
- var subobj = _classPrivateMethodGet(this, _getProperty, _getProperty2).call(this, key);
1056
- //@ts-ignore
1057
- if (subobj == null || _typeof(subobj) !== "object") subobj = {};
1058
- subobj[subkey] = value;
1059
- _classPrivateMethodGet(this, _setProperty, _setProperty2).call(this, key, subobj);
1060
- }
1061
- function _getSubProperty2(key, subkey) {
1062
- var original = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
1063
- var subobj = _classPrivateMethodGet(this, _getProperty, _getProperty2).call(this, key, original);
1064
- if (subobj == null || _typeof(subobj) !== "object") return undefined;
1065
- return subobj[subkey];
1066
- }
1067
- function _setProperty2(key, value) {
1068
- if (this[key] === value) {
694
+ */
695
+ static isResultValid(result_object, sub = false) {
696
+ if (object_isEmpty(result_object))
697
+ return false;
698
+ switch (typeof result_object) {
699
+ case "string":
700
+ try {
701
+ result_object = JSON.parse(result_object);
702
+ return this.isResultValid(result_object);
703
+ }
704
+ catch {
705
+ return false;
706
+ }
707
+ case "object":
708
+ if (object_isTrue(result_object.acknowledged)) {
709
+ return true;
710
+ }
711
+ if (result_object.expected && result_object.result) {
712
+ return object_equals(result_object.expected, result_object.result);
713
+ }
714
+ return Number(this.getID(result_object)) >= 0;
715
+ case "number":
716
+ return result_object > 0;
717
+ case "boolean":
718
+ return result_object === true;
719
+ }
720
+ return false;
721
+ }
1069
722
  /**
1070
- * We set something back to its original value so no need to save it as Delta
1071
- */
1072
- delete this.__delta[key];
1073
- return false;
1074
- } else {
1075
- this.__delta[key] = value; //always update delta to keep track of changes
1076
- if (!this.__use_delta) this[key] = value; //on noDelta mode, also update the obj
1077
- return true;
1078
- }
1079
- }
1080
- function _setDefaultProperty2(key, value) {
1081
- //@ts-ignore
1082
- if (this[key] == undefined || this[key] === "" || this[key] === 0) {
1083
- this[key] = value;
1084
- return true;
1085
- }
1086
- return false;
1087
- }
1088
- function _getProperty2(key) {
1089
- var original = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
1090
- //check if we should use delta version or normal version for this property
1091
- if (original || !this.__use_delta || !(key in this.__delta)) return this[key];
1092
- //@ts-ignore
1093
- return this.__delta[key];
1094
- }
1095
- function _getTempProperty2(key) {
1096
- if (this.__temp == null) return undefined;
1097
- return this.__temp[key];
1098
- }
1099
- function _setTempProperty2(key, value) {
1100
- if (this.__temp == null) this.__temp = {};
1101
- this.__temp[key] = value;
1102
- }
1103
- function _setSaveResultObject2(toObj) {
1104
- this.__saveResultObject = toObj;
1105
- }
1106
- _defineProperty(SimpleObject, "__cache_name", void 0);
1107
- //these properties should not be changed and are usually set by server
1108
- _defineProperty(SimpleObject, "__unchangeables", void 0);
1109
- //these properties can be directly changed and are included in deltaObject
1110
- _defineProperty(SimpleObject, "__changeables", void 0);
1111
- //these properties can only be changed by the _creator
1112
- _defineProperty(SimpleObject, "__protectedProperties", void 0);
1113
- //these properties usually are not directly changed and sometimes are included in deltaObject
1114
- _defineProperty(SimpleObject, "__extraProperties", void 0);
1115
- _defineProperty(SimpleObject, "__use_delta", true);
1116
- var _default = SimpleObject;
1117
- exports["default"] = _default;
723
+ * set the response of last save from site
724
+ * and its type
725
+ * @param toObj
726
+ */
727
+ setSaveResult(toObj, type) {
728
+ if (toObj != null) {
729
+ this.#setSaveResultObject(toObj);
730
+ }
731
+ else {
732
+ this.#setSaveResultObject(null);
733
+ }
734
+ //check if the given object is a valid save result
735
+ if (type === "error")
736
+ this.__saveResultIsSuccess = false;
737
+ else
738
+ this.__saveResultIsSuccess = Boolean(type === "nothing" || this.constructor["isResultValid"](toObj));
739
+ if (type === "auto") {
740
+ type = this.__saveResultIsSuccess ? "normal" : "error";
741
+ }
742
+ this.__saveResultType = type;
743
+ }
744
+ /**
745
+ * set the response of last save from site
746
+ * @param toObj
747
+ */
748
+ #setSaveResultObject(toObj) {
749
+ this.__saveResultObject = toObj;
750
+ }
751
+ getSaveResult(original = false) {
752
+ if (this.isSaved)
753
+ return this.__saveResultObject;
754
+ return false;
755
+ }
756
+ getSaveResultType() {
757
+ return this.__saveResultType || "nothing";
758
+ }
759
+ /* -------------------------------------------------------------------------- */
760
+ /* statics */
761
+ /* -------------------------------------------------------------------------- */
762
+ static factoryClear(obj) {
763
+ obj.clear_changes();
764
+ SimpleObject.clearErrors(obj);
765
+ }
766
+ static delete_cache() {
767
+ if (!this.__cache_name)
768
+ return;
769
+ gcache.delete_cache(this.__cache_name);
770
+ }
771
+ static get_canModify(o) {
772
+ if (o instanceof SimpleObject)
773
+ return o.canModify;
774
+ return false;
775
+ }
776
+ /* -------------------------------------------------------------------------- */
777
+ static equals(a, b) {
778
+ console.warn("Dont use the default equals method !");
779
+ if (a == undefined || b == undefined)
780
+ return false;
781
+ return a === b;
782
+ }
783
+ }
784
+ export default SimpleObject;