@epam/uui-db 4.5.1 → 4.6.0-alpha.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.
package/index.js CHANGED
@@ -91,7 +91,7 @@ module.exports =
91
91
  /*!******************************************!*\
92
92
  !*** ../node_modules/tslib/tslib.es6.js ***!
93
93
  \******************************************/
94
- /*! exports provided: __extends, __assign, __rest, __decorate, __param, __metadata, __awaiter, __generator, __createBinding, __exportStar, __values, __read, __spread, __spreadArrays, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault, __classPrivateFieldGet, __classPrivateFieldSet */
94
+ /*! exports provided: __extends, __assign, __rest, __decorate, __param, __metadata, __awaiter, __generator, __createBinding, __exportStar, __values, __read, __spread, __spreadArrays, __spreadArray, __await, __asyncGenerator, __asyncDelegator, __asyncValues, __makeTemplateObject, __importStar, __importDefault, __classPrivateFieldGet, __classPrivateFieldSet */
95
95
  /***/ (function(module, __webpack_exports__, __webpack_require__) {
96
96
 
97
97
  "use strict";
@@ -110,6 +110,7 @@ __webpack_require__.r(__webpack_exports__);
110
110
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; });
111
111
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; });
112
112
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; });
113
+ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArray", function() { return __spreadArray; });
113
114
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; });
114
115
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; });
115
116
  /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; });
@@ -138,11 +139,13 @@ PERFORMANCE OF THIS SOFTWARE.
138
139
  var extendStatics = function(d, b) {
139
140
  extendStatics = Object.setPrototypeOf ||
140
141
  ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
141
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
142
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
142
143
  return extendStatics(d, b);
143
144
  };
144
145
 
145
146
  function __extends(d, b) {
147
+ if (typeof b !== "function" && b !== null)
148
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
146
149
  extendStatics(d, b);
147
150
  function __() { this.constructor = d; }
148
151
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
@@ -224,13 +227,16 @@ function __generator(thisArg, body) {
224
227
  }
225
228
  }
226
229
 
227
- function __createBinding(o, m, k, k2) {
230
+ var __createBinding = Object.create ? (function(o, m, k, k2) {
231
+ if (k2 === undefined) k2 = k;
232
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
233
+ }) : (function(o, m, k, k2) {
228
234
  if (k2 === undefined) k2 = k;
229
235
  o[k2] = m[k];
230
- }
236
+ });
231
237
 
232
- function __exportStar(m, exports) {
233
- for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
238
+ function __exportStar(m, o) {
239
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
234
240
  }
235
241
 
236
242
  function __values(o) {
@@ -262,19 +268,31 @@ function __read(o, n) {
262
268
  return ar;
263
269
  }
264
270
 
271
+ /** @deprecated */
265
272
  function __spread() {
266
273
  for (var ar = [], i = 0; i < arguments.length; i++)
267
274
  ar = ar.concat(__read(arguments[i]));
268
275
  return ar;
269
276
  }
270
277
 
278
+ /** @deprecated */
271
279
  function __spreadArrays() {
272
280
  for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
273
281
  for (var r = Array(s), k = 0, i = 0; i < il; i++)
274
282
  for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
275
283
  r[k] = a[j];
276
284
  return r;
277
- };
285
+ }
286
+
287
+ function __spreadArray(to, from, pack) {
288
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
289
+ if (ar || !(i in from)) {
290
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
291
+ ar[i] = from[i];
292
+ }
293
+ }
294
+ return to.concat(ar || Array.prototype.slice.call(from));
295
+ }
278
296
 
279
297
  function __await(v) {
280
298
  return this instanceof __await ? (this.v = v, this) : new __await(v);
@@ -311,11 +329,17 @@ function __makeTemplateObject(cooked, raw) {
311
329
  return cooked;
312
330
  };
313
331
 
332
+ var __setModuleDefault = Object.create ? (function(o, v) {
333
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
334
+ }) : function(o, v) {
335
+ o["default"] = v;
336
+ };
337
+
314
338
  function __importStar(mod) {
315
339
  if (mod && mod.__esModule) return mod;
316
340
  var result = {};
317
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
318
- result.default = mod;
341
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
342
+ __setModuleDefault(result, mod);
319
343
  return result;
320
344
  }
321
345
 
@@ -323,19 +347,17 @@ function __importDefault(mod) {
323
347
  return (mod && mod.__esModule) ? mod : { default: mod };
324
348
  }
325
349
 
326
- function __classPrivateFieldGet(receiver, privateMap) {
327
- if (!privateMap.has(receiver)) {
328
- throw new TypeError("attempted to get private field on non-instance");
329
- }
330
- return privateMap.get(receiver);
350
+ function __classPrivateFieldGet(receiver, state, kind, f) {
351
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
352
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
353
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
331
354
  }
332
355
 
333
- function __classPrivateFieldSet(receiver, privateMap, value) {
334
- if (!privateMap.has(receiver)) {
335
- throw new TypeError("attempted to set private field on non-instance");
336
- }
337
- privateMap.set(receiver, value);
338
- return value;
356
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
357
+ if (kind === "m") throw new TypeError("Private method is not writable");
358
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
359
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
360
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
339
361
  }
340
362
 
341
363
 
@@ -349,10 +371,10 @@ function __classPrivateFieldSet(receiver, privateMap, value) {
349
371
  /***/ (function(module, exports, __webpack_require__) {
350
372
 
351
373
  "use strict";
352
-
353
- Object.defineProperty(exports, "__esModule", { value: true });
354
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
355
- tslib_1.__exportStar(__webpack_require__(/*! ./src */ "./src/index.ts"), exports);
374
+
375
+ Object.defineProperty(exports, "__esModule", { value: true });
376
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
377
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./src */ "./src/index.ts"), exports);
356
378
 
357
379
 
358
380
  /***/ }),
@@ -365,80 +387,80 @@ tslib_1.__exportStar(__webpack_require__(/*! ./src */ "./src/index.ts"), exports
365
387
  /***/ (function(module, exports, __webpack_require__) {
366
388
 
367
389
  "use strict";
368
-
369
- Object.defineProperty(exports, "__esModule", { value: true });
370
- exports.Db = void 0;
371
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
372
- var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
373
- var lodash_isequal_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.isequal */ "lodash.isequal"));
374
- var Db = /** @class */ (function () {
375
- function Db(tables, reusedCache) {
376
- this.tables = tables;
377
- this.viewCache = new Map();
378
- /* Views (cached db projections) */
379
- this.valueAbsent = Symbol("ValueAbsent");
380
- if (reusedCache) {
381
- this.viewCache = new Map(reusedCache);
382
- }
383
- else {
384
- this.viewCache = new Map();
385
- }
386
- }
387
- Db.prototype.update = function (mutate) {
388
- var clone = new this.constructor(tslib_1.__assign({}, this.tables), this.viewCache);
389
- mutate(clone);
390
- return clone;
391
- };
392
- Db.prototype.with = function (patch) {
393
- return this.update(function (db) {
394
- utils_1.objectKeys(db.tables).forEach(function (entityName) {
395
- if (patch[entityName]) {
396
- db.tables[entityName] = db.tables[entityName].with(patch[entityName]);
397
- }
398
- });
399
- });
400
- };
401
- Db.prototype.runView = function (view, params) {
402
- var cache = this.viewCache.get(view);
403
- if (!cache) {
404
- cache = new Map();
405
- this.viewCache.set(view, cache);
406
- }
407
- var key = view.getKey ? view.getKey(params) : JSON.stringify(params);
408
- var cacheItem = cache.get(key);
409
- if (!cacheItem) {
410
- cacheItem = {
411
- dependencies: this.valueAbsent,
412
- currentValue: this.valueAbsent,
413
- computedOnDb: this.valueAbsent,
414
- };
415
- cache.set(key, cacheItem);
416
- }
417
- var shouldUpdate = this !== cacheItem.computedOnDb;
418
- var dependencies = this.valueAbsent;
419
- if (view.getDependencies) {
420
- var compare = view.compareDependencies || utils_1.defaultCompareViewDependencies;
421
- dependencies = view.getDependencies(this, params);
422
- shouldUpdate = !compare(cacheItem.dependencies, dependencies);
423
- }
424
- var previousValue = cacheItem.currentValue;
425
- if (shouldUpdate) {
426
- cacheItem.dependencies = dependencies;
427
- var newValue = view.compute(this, params, dependencies);
428
- cacheItem.computedOnDb = this;
429
- var compareResults = view.compareResults || lodash_isequal_1.default;
430
- if (!compareResults(previousValue, newValue)) {
431
- if (view.traceDiff) {
432
- console.debug(utils_1.difference(previousValue, newValue));
433
- }
434
- cacheItem.currentValue = newValue;
435
- }
436
- }
437
- return cacheItem.currentValue;
438
- };
439
- return Db;
440
- }());
441
- exports.Db = Db;
390
+
391
+ Object.defineProperty(exports, "__esModule", { value: true });
392
+ exports.Db = void 0;
393
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
394
+ var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
395
+ var lodash_isequal_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.isequal */ "lodash.isequal"));
396
+ var Db = /** @class */ (function () {
397
+ function Db(tables, reusedCache) {
398
+ this.tables = tables;
399
+ this.viewCache = new Map();
400
+ /* Views (cached db projections) */
401
+ this.valueAbsent = Symbol("ValueAbsent");
402
+ if (reusedCache) {
403
+ this.viewCache = new Map(reusedCache);
404
+ }
405
+ else {
406
+ this.viewCache = new Map();
407
+ }
408
+ }
409
+ Db.prototype.update = function (mutate) {
410
+ var clone = new this.constructor((0, tslib_1.__assign)({}, this.tables), this.viewCache);
411
+ mutate(clone);
412
+ return clone;
413
+ };
414
+ Db.prototype.with = function (patch) {
415
+ return this.update(function (db) {
416
+ (0, utils_1.objectKeys)(db.tables).forEach(function (entityName) {
417
+ if (patch[entityName]) {
418
+ db.tables[entityName] = db.tables[entityName].with(patch[entityName]);
419
+ }
420
+ });
421
+ });
422
+ };
423
+ Db.prototype.runView = function (view, params) {
424
+ var cache = this.viewCache.get(view);
425
+ if (!cache) {
426
+ cache = new Map();
427
+ this.viewCache.set(view, cache);
428
+ }
429
+ var key = view.getKey ? view.getKey(params) : JSON.stringify(params);
430
+ var cacheItem = cache.get(key);
431
+ if (!cacheItem) {
432
+ cacheItem = {
433
+ dependencies: this.valueAbsent,
434
+ currentValue: this.valueAbsent,
435
+ computedOnDb: this.valueAbsent,
436
+ };
437
+ cache.set(key, cacheItem);
438
+ }
439
+ var shouldUpdate = this !== cacheItem.computedOnDb;
440
+ var dependencies = this.valueAbsent;
441
+ if (view.getDependencies) {
442
+ var compare = view.compareDependencies || utils_1.defaultCompareViewDependencies;
443
+ dependencies = view.getDependencies(this, params);
444
+ shouldUpdate = !compare(cacheItem.dependencies, dependencies);
445
+ }
446
+ var previousValue = cacheItem.currentValue;
447
+ if (shouldUpdate) {
448
+ cacheItem.dependencies = dependencies;
449
+ var newValue = view.compute(this, params, dependencies);
450
+ cacheItem.computedOnDb = this;
451
+ var compareResults = view.compareResults || lodash_isequal_1.default;
452
+ if (!compareResults(previousValue, newValue)) {
453
+ if (view.traceDiff) {
454
+ console.debug((0, utils_1.difference)(previousValue, newValue));
455
+ }
456
+ cacheItem.currentValue = newValue;
457
+ }
458
+ }
459
+ return cacheItem.currentValue;
460
+ };
461
+ return Db;
462
+ }());
463
+ exports.Db = Db;
442
464
 
443
465
 
444
466
  /***/ }),
@@ -451,230 +473,230 @@ exports.Db = Db;
451
473
  /***/ (function(module, exports, __webpack_require__) {
452
474
 
453
475
  "use strict";
454
-
455
- Object.defineProperty(exports, "__esModule", { value: true });
456
- exports.DbRef = void 0;
457
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
458
- var patchHelpers_1 = __webpack_require__(/*! ./patchHelpers */ "./src/patchHelpers.ts");
459
- var tempIds_1 = __webpack_require__(/*! ./tempIds */ "./src/tempIds.tsx");
460
- var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
461
- var lodash_isempty_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.isempty */ "lodash.isempty"));
462
- var Loader_1 = __webpack_require__(/*! ./Loader */ "./src/Loader.ts");
463
- var SimpleLoadingTracker_1 = __webpack_require__(/*! ./SimpleLoadingTracker */ "./src/SimpleLoadingTracker.ts");
464
- var ListLoadingTracker_1 = __webpack_require__(/*! ./ListLoadingTracker */ "./src/ListLoadingTracker.ts");
465
- var DbRef = /** @class */ (function () {
466
- function DbRef(blank) {
467
- var _this = this;
468
- this.blank = blank;
469
- this.log = [];
470
- this.autoSave = true;
471
- this.savedPoint = 0;
472
- this.errors = [];
473
- this.throttleSaveMs = 1000;
474
- /* Update subscriptions (aka live views) */
475
- this.lastSubscriptionId = 1;
476
- this.subscriptions = new Map();
477
- this.updateHandlers = [];
478
- /* Error Subscriptions */
479
- this.saveErrorHandlers = [];
480
- /* Save scheduling */
481
- this.isSaveInProgress = false;
482
- this.isSaveThrottled = false;
483
- this.handleBeforeUnload = function (e) {
484
- if (_this.isSaveInProgress || _this.isSaveThrottled) {
485
- e.returnValue = false;
486
- return false;
487
- }
488
- };
489
- this.loaders = [];
490
- this.db = blank;
491
- this.base = blank;
492
- this.tempIdMap = new tempIds_1.TempIdMap(blank);
493
- this.idMap = this.tempIdMap;
494
- window.addEventListener('beforeunload', this.handleBeforeUnload);
495
- }
496
- /** Saves all committed patches. Useful only if autoSave is off. */
497
- DbRef.prototype.save = function () {
498
- this.enqueueSave();
499
- this.update();
500
- };
501
- DbRef.prototype.getAutoSave = function () {
502
- return this.autoSave;
503
- };
504
- DbRef.prototype.setAutoSave = function (val) {
505
- if (this.autoSave != val) {
506
- this.autoSave = val;
507
- this.enqueueSave();
508
- this.update();
509
- }
510
- };
511
- /** Concrete DbRef instances should override and implement their save logic in this method */
512
- DbRef.prototype.savePatch = function (patch) {
513
- return Promise.resolve({ submit: {} });
514
- };
515
- /* Db Update logic */
516
- DbRef.prototype.commit = function (patch) {
517
- try {
518
- var dbBeforeUpdate = this.db.with(patch);
519
- patch = this.beforeUpdate(patch, dbBeforeUpdate.tables, this.db.tables);
520
- patch = patchHelpers_1.mergeEntityPatches(this.db.tables, patch);
521
- this.log.push({ patch: patch });
522
- this.db = this.db.with(patch);
523
- this.autoSave && this.enqueueSave();
524
- this.update();
525
- }
526
- catch (e) {
527
- this.saveError(patch, e);
528
- }
529
- };
530
- DbRef.prototype.beforeUpdate = function (patch, tables, prevTables) {
531
- var _this = this;
532
- var patchAndDependencies = {};
533
- utils_1.objectKeys(tables).filter(function (entityName) { return patch[entityName] && !tables[entityName].schema.beforeUpdate; }).forEach(function (entityName) {
534
- patchAndDependencies[entityName] = patch[entityName];
535
- });
536
- utils_1.objectKeys(tables).filter(function (entityName) { return patch[entityName] && tables[entityName].schema.beforeUpdate; }).forEach(function (entityName) {
537
- var _a;
538
- var schema = tables[entityName].schema;
539
- var beforeUpdate = schema.beforeUpdate;
540
- var context = {
541
- clientIdsMap: _this.tempIdMap,
542
- schema: schema,
543
- tables: tables,
544
- prevTables: prevTables,
545
- };
546
- var results = patch[entityName].map(function (e) { return beforeUpdate(e, context); });
547
- var updatedPatch = (_a = {}, _a[entityName] = results.map(function (result) { return result.entity; }), _a);
548
- var dependentEntityPatchesForUpdate = patchHelpers_1.unionPatches(results.filter(function (result) { return result.dependentEntities; }).map(function (result) { return result.dependentEntities; }));
549
- var dependentEntityPatches = _this.beforeUpdate(dependentEntityPatchesForUpdate, tables, prevTables);
550
- patchAndDependencies = patchHelpers_1.mergeEntityPatches(tables, patchHelpers_1.unionPatches([patchAndDependencies, updatedPatch, dependentEntityPatches]));
551
- });
552
- return patchAndDependencies;
553
- };
554
- DbRef.prototype.commitFetch = function (patch) {
555
- patch = this.tempIdMap.serverToClientPatch(patch);
556
- this.rebase(this.base.with(patch));
557
- this.update();
558
- };
559
- DbRef.prototype.rebase = function (newBase) {
560
- this.base = newBase;
561
- this.db = newBase;
562
- for (var n = this.savedPoint; n < this.log.length; n++) {
563
- this.db = this.db.with(this.log[n].patch);
564
- }
565
- };
566
- DbRef.prototype.makeCumulativePatch = function () {
567
- var lastLogEntry = this.log.length;
568
- var logEntriesToSave = this.log.slice(this.savedPoint, lastLogEntry);
569
- var cumulativePatch = patchHelpers_1.makeCumulativePatch(this.db, logEntriesToSave.map(function (t) { return t.patch; }), this.tempIdMap);
570
- cumulativePatch = this.tempIdMap.clientToServerPatch(cumulativePatch);
571
- return cumulativePatch;
572
- };
573
- DbRef.prototype.applyResponse = function (response, newSavedPoint) {
574
- var _this = this;
575
- if (this.errors.length == 0) {
576
- this.tempIdMap.appendServerMapping(response);
577
- var serverPatch = patchHelpers_1.flattenResponse(response.submit, this.db.tables);
578
- serverPatch = patchHelpers_1.mergeEntityPatches(this.db.tables, serverPatch);
579
- this.savedPoint = newSavedPoint;
580
- this.base = this.db;
581
- this.commitFetch(serverPatch);
582
- if (this.autoSave) {
583
- this.isSaveThrottled = true;
584
- setTimeout(function () {
585
- _this.isSaveThrottled = false;
586
- if (_this.savedPoint < _this.log.length) {
587
- _this.enqueueSave();
588
- }
589
- }, this.throttleSaveMs);
590
- }
591
- }
592
- };
593
- DbRef.prototype.subscribe = function (view, params, onUpdate) {
594
- var _this = this;
595
- var id = this.lastSubscriptionId++;
596
- var subscription = {
597
- update: function (params) {
598
- subscription.currentParams = params;
599
- subscription.currentValue = _this.db.runView(view, params);
600
- return subscription.currentValue;
601
- },
602
- currentParams: null,
603
- currentValue: null,
604
- onUpdate: onUpdate,
605
- unsubscribe: function () { _this.subscriptions.delete(id); },
606
- };
607
- subscription.update(params);
608
- this.subscriptions.set(id, subscription);
609
- return subscription;
610
- };
611
- DbRef.prototype.onUpdate = function (handler) {
612
- this.subscribe({
613
- compute: function (db) { return db; },
614
- compareResults: function (a, b) { return a === b; },
615
- }, null, handler);
616
- };
617
- DbRef.prototype.update = function () {
618
- this.subscriptions.forEach(function (subscription) {
619
- var previousValue = subscription.currentValue;
620
- subscription.update(subscription.currentParams);
621
- if (subscription.currentValue !== previousValue && subscription.onUpdate) {
622
- subscription.onUpdate(subscription.currentValue);
623
- }
624
- });
625
- };
626
- DbRef.prototype.onSaveError = function (handler) {
627
- this.saveErrorHandlers.push(handler);
628
- };
629
- DbRef.prototype.saveError = function (request, error) {
630
- this.saveErrorHandlers.forEach(function (handler) { return handler(request, error); });
631
- };
632
- DbRef.prototype.enqueueSave = function () {
633
- var _this = this;
634
- if (!this.isSaveInProgress && !this.isSaveThrottled) {
635
- try {
636
- this.isSaveInProgress = true;
637
- var lastLogEntry_1 = this.log.length;
638
- var cumulativePatch_1 = this.makeCumulativePatch();
639
- if (lodash_isempty_1.default(cumulativePatch_1)) {
640
- this.isSaveInProgress = false;
641
- return;
642
- }
643
- this.savePatch(cumulativePatch_1)
644
- .then(function (response) {
645
- _this.applyResponse(response, lastLogEntry_1);
646
- _this.isSaveInProgress = false;
647
- _this.update();
648
- })
649
- .catch(function (reason) {
650
- _this.saveError(cumulativePatch_1, reason);
651
- _this.isSaveInProgress = false;
652
- _this.update();
653
- });
654
- }
655
- catch (e) {
656
- this.isSaveInProgress = false;
657
- this.isSaveThrottled = false;
658
- throw e;
659
- }
660
- }
661
- };
662
- DbRef.prototype.makeLoader = function (options) {
663
- var loader = new Loader_1.Loader(this, function () { return new SimpleLoadingTracker_1.SimpleLoadingTracker(); }, options);
664
- this.loaders.push(loader);
665
- return loader;
666
- };
667
- DbRef.prototype.makeListLoader = function (options) {
668
- var loader = new Loader_1.Loader(this, function () { return new ListLoadingTracker_1.ListLoadingTracker(); }, options);
669
- this.loaders.push(loader);
670
- return loader;
671
- };
672
- DbRef.prototype.reload = function () {
673
- this.loaders = [];
674
- };
675
- return DbRef;
676
- }());
677
- exports.DbRef = DbRef;
476
+
477
+ Object.defineProperty(exports, "__esModule", { value: true });
478
+ exports.DbRef = void 0;
479
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
480
+ var patchHelpers_1 = __webpack_require__(/*! ./patchHelpers */ "./src/patchHelpers.ts");
481
+ var tempIds_1 = __webpack_require__(/*! ./tempIds */ "./src/tempIds.tsx");
482
+ var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
483
+ var lodash_isempty_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.isempty */ "lodash.isempty"));
484
+ var Loader_1 = __webpack_require__(/*! ./Loader */ "./src/Loader.ts");
485
+ var SimpleLoadingTracker_1 = __webpack_require__(/*! ./SimpleLoadingTracker */ "./src/SimpleLoadingTracker.ts");
486
+ var ListLoadingTracker_1 = __webpack_require__(/*! ./ListLoadingTracker */ "./src/ListLoadingTracker.ts");
487
+ var DbRef = /** @class */ (function () {
488
+ function DbRef(blank) {
489
+ var _this = this;
490
+ this.blank = blank;
491
+ this.log = [];
492
+ this.autoSave = true;
493
+ this.savedPoint = 0;
494
+ this.errors = [];
495
+ this.throttleSaveMs = 1000;
496
+ /* Update subscriptions (aka live views) */
497
+ this.lastSubscriptionId = 1;
498
+ this.subscriptions = new Map();
499
+ this.updateHandlers = [];
500
+ /* Error Subscriptions */
501
+ this.saveErrorHandlers = [];
502
+ /* Save scheduling */
503
+ this.isSaveInProgress = false;
504
+ this.isSaveThrottled = false;
505
+ this.handleBeforeUnload = function (e) {
506
+ if (_this.isSaveInProgress || _this.isSaveThrottled) {
507
+ e.returnValue = false;
508
+ return false;
509
+ }
510
+ };
511
+ this.loaders = [];
512
+ this.db = blank;
513
+ this.base = blank;
514
+ this.tempIdMap = new tempIds_1.TempIdMap(blank);
515
+ this.idMap = this.tempIdMap;
516
+ window.addEventListener('beforeunload', this.handleBeforeUnload);
517
+ }
518
+ /** Saves all committed patches. Useful only if autoSave is off. */
519
+ DbRef.prototype.save = function () {
520
+ this.enqueueSave();
521
+ this.update();
522
+ };
523
+ DbRef.prototype.getAutoSave = function () {
524
+ return this.autoSave;
525
+ };
526
+ DbRef.prototype.setAutoSave = function (val) {
527
+ if (this.autoSave != val) {
528
+ this.autoSave = val;
529
+ this.enqueueSave();
530
+ this.update();
531
+ }
532
+ };
533
+ /** Concrete DbRef instances should override and implement their save logic in this method */
534
+ DbRef.prototype.savePatch = function (patch) {
535
+ return Promise.resolve({ submit: {} });
536
+ };
537
+ /* Db Update logic */
538
+ DbRef.prototype.commit = function (patch) {
539
+ try {
540
+ var dbBeforeUpdate = this.db.with(patch);
541
+ patch = this.beforeUpdate(patch, dbBeforeUpdate.tables, this.db.tables);
542
+ patch = (0, patchHelpers_1.mergeEntityPatches)(this.db.tables, patch);
543
+ this.log.push({ patch: patch });
544
+ this.db = this.db.with(patch);
545
+ this.autoSave && this.enqueueSave();
546
+ this.update();
547
+ }
548
+ catch (e) {
549
+ this.saveError(patch, e);
550
+ }
551
+ };
552
+ DbRef.prototype.beforeUpdate = function (patch, tables, prevTables) {
553
+ var _this = this;
554
+ var patchAndDependencies = {};
555
+ (0, utils_1.objectKeys)(tables).filter(function (entityName) { return patch[entityName] && !tables[entityName].schema.beforeUpdate; }).forEach(function (entityName) {
556
+ patchAndDependencies[entityName] = patch[entityName];
557
+ });
558
+ (0, utils_1.objectKeys)(tables).filter(function (entityName) { return patch[entityName] && tables[entityName].schema.beforeUpdate; }).forEach(function (entityName) {
559
+ var _a;
560
+ var schema = tables[entityName].schema;
561
+ var beforeUpdate = schema.beforeUpdate;
562
+ var context = {
563
+ clientIdsMap: _this.tempIdMap,
564
+ schema: schema,
565
+ tables: tables,
566
+ prevTables: prevTables,
567
+ };
568
+ var results = patch[entityName].map(function (e) { return beforeUpdate(e, context); });
569
+ var updatedPatch = (_a = {}, _a[entityName] = results.map(function (result) { return result.entity; }), _a);
570
+ var dependentEntityPatchesForUpdate = (0, patchHelpers_1.unionPatches)(results.filter(function (result) { return result.dependentEntities; }).map(function (result) { return result.dependentEntities; }));
571
+ var dependentEntityPatches = _this.beforeUpdate(dependentEntityPatchesForUpdate, tables, prevTables);
572
+ patchAndDependencies = (0, patchHelpers_1.mergeEntityPatches)(tables, (0, patchHelpers_1.unionPatches)([patchAndDependencies, updatedPatch, dependentEntityPatches]));
573
+ });
574
+ return patchAndDependencies;
575
+ };
576
+ DbRef.prototype.commitFetch = function (patch) {
577
+ patch = this.tempIdMap.serverToClientPatch(patch);
578
+ this.rebase(this.base.with(patch));
579
+ this.update();
580
+ };
581
+ DbRef.prototype.rebase = function (newBase) {
582
+ this.base = newBase;
583
+ this.db = newBase;
584
+ for (var n = this.savedPoint; n < this.log.length; n++) {
585
+ this.db = this.db.with(this.log[n].patch);
586
+ }
587
+ };
588
+ DbRef.prototype.makeCumulativePatch = function () {
589
+ var lastLogEntry = this.log.length;
590
+ var logEntriesToSave = this.log.slice(this.savedPoint, lastLogEntry);
591
+ var cumulativePatch = (0, patchHelpers_1.makeCumulativePatch)(this.db, logEntriesToSave.map(function (t) { return t.patch; }), this.tempIdMap);
592
+ cumulativePatch = this.tempIdMap.clientToServerPatch(cumulativePatch);
593
+ return cumulativePatch;
594
+ };
595
+ DbRef.prototype.applyResponse = function (response, newSavedPoint) {
596
+ var _this = this;
597
+ if (this.errors.length == 0) {
598
+ this.tempIdMap.appendServerMapping(response);
599
+ var serverPatch = (0, patchHelpers_1.flattenResponse)(response.submit, this.db.tables);
600
+ serverPatch = (0, patchHelpers_1.mergeEntityPatches)(this.db.tables, serverPatch);
601
+ this.savedPoint = newSavedPoint;
602
+ this.base = this.db;
603
+ this.commitFetch(serverPatch);
604
+ if (this.autoSave) {
605
+ this.isSaveThrottled = true;
606
+ setTimeout(function () {
607
+ _this.isSaveThrottled = false;
608
+ if (_this.savedPoint < _this.log.length) {
609
+ _this.enqueueSave();
610
+ }
611
+ }, this.throttleSaveMs);
612
+ }
613
+ }
614
+ };
615
+ DbRef.prototype.subscribe = function (view, params, onUpdate) {
616
+ var _this = this;
617
+ var id = this.lastSubscriptionId++;
618
+ var subscription = {
619
+ update: function (params) {
620
+ subscription.currentParams = params;
621
+ subscription.currentValue = _this.db.runView(view, params);
622
+ return subscription.currentValue;
623
+ },
624
+ currentParams: null,
625
+ currentValue: null,
626
+ onUpdate: onUpdate,
627
+ unsubscribe: function () { _this.subscriptions.delete(id); },
628
+ };
629
+ subscription.update(params);
630
+ this.subscriptions.set(id, subscription);
631
+ return subscription;
632
+ };
633
+ DbRef.prototype.onUpdate = function (handler) {
634
+ this.subscribe({
635
+ compute: function (db) { return db; },
636
+ compareResults: function (a, b) { return a === b; },
637
+ }, null, handler);
638
+ };
639
+ DbRef.prototype.update = function () {
640
+ this.subscriptions.forEach(function (subscription) {
641
+ var previousValue = subscription.currentValue;
642
+ subscription.update(subscription.currentParams);
643
+ if (subscription.currentValue !== previousValue && subscription.onUpdate) {
644
+ subscription.onUpdate(subscription.currentValue);
645
+ }
646
+ });
647
+ };
648
+ DbRef.prototype.onSaveError = function (handler) {
649
+ this.saveErrorHandlers.push(handler);
650
+ };
651
+ DbRef.prototype.saveError = function (request, error) {
652
+ this.saveErrorHandlers.forEach(function (handler) { return handler(request, error); });
653
+ };
654
+ DbRef.prototype.enqueueSave = function () {
655
+ var _this = this;
656
+ if (!this.isSaveInProgress && !this.isSaveThrottled) {
657
+ try {
658
+ this.isSaveInProgress = true;
659
+ var lastLogEntry_1 = this.log.length;
660
+ var cumulativePatch_1 = this.makeCumulativePatch();
661
+ if ((0, lodash_isempty_1.default)(cumulativePatch_1)) {
662
+ this.isSaveInProgress = false;
663
+ return;
664
+ }
665
+ this.savePatch(cumulativePatch_1)
666
+ .then(function (response) {
667
+ _this.applyResponse(response, lastLogEntry_1);
668
+ _this.isSaveInProgress = false;
669
+ _this.update();
670
+ })
671
+ .catch(function (reason) {
672
+ _this.saveError(cumulativePatch_1, reason);
673
+ _this.isSaveInProgress = false;
674
+ _this.update();
675
+ });
676
+ }
677
+ catch (e) {
678
+ this.isSaveInProgress = false;
679
+ this.isSaveThrottled = false;
680
+ throw e;
681
+ }
682
+ }
683
+ };
684
+ DbRef.prototype.makeLoader = function (options) {
685
+ var loader = new Loader_1.Loader(this, function () { return new SimpleLoadingTracker_1.SimpleLoadingTracker(); }, options);
686
+ this.loaders.push(loader);
687
+ return loader;
688
+ };
689
+ DbRef.prototype.makeListLoader = function (options) {
690
+ var loader = new Loader_1.Loader(this, function () { return new ListLoadingTracker_1.ListLoadingTracker(); }, options);
691
+ this.loaders.push(loader);
692
+ return loader;
693
+ };
694
+ DbRef.prototype.reload = function () {
695
+ this.loaders = [];
696
+ };
697
+ return DbRef;
698
+ }());
699
+ exports.DbRef = DbRef;
678
700
 
679
701
 
680
702
  /***/ }),
@@ -687,209 +709,209 @@ exports.DbRef = DbRef;
687
709
  /***/ (function(module, exports, __webpack_require__) {
688
710
 
689
711
  "use strict";
690
-
691
- Object.defineProperty(exports, "__esModule", { value: true });
692
- exports.DbTable = void 0;
693
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
694
- var I = tslib_1.__importStar(__webpack_require__(/*! immutable */ "immutable"));
695
- var uui_1 = __webpack_require__(/*! @epam/uui */ "@epam/uui");
696
- var immutable_1 = __webpack_require__(/*! immutable */ "immutable");
697
- var DbTable = /** @class */ (function () {
698
- function DbTable(schema, state, q) {
699
- this.schema = schema;
700
- this.state = state;
701
- this.q = q;
702
- if (!state) {
703
- var indexes = (schema.indexes || []).map(function (indexDef) {
704
- return {
705
- field: indexDef,
706
- map: I.Map(),
707
- };
708
- });
709
- this.state = { pk: I.Map(), indexes: indexes };
710
- }
711
- if (!q) {
712
- this.q = {};
713
- }
714
- }
715
- DbTable.prototype.keyToImmutable = function (id) {
716
- if (Array.isArray(id)) {
717
- return I.List(id);
718
- }
719
- else {
720
- return id;
721
- }
722
- };
723
- DbTable.prototype.byId = function (id) {
724
- return this.state.pk.get(this.keyToImmutable(id));
725
- };
726
- DbTable.prototype.getId = function (entity) {
727
- if (Array.isArray(this.schema.primaryKey)) {
728
- return this.schema.primaryKey.map(function (key) { return entity[key]; });
729
- }
730
- return entity[this.schema.primaryKey];
731
- };
732
- DbTable.prototype.update = function (mutate) {
733
- var clone = new this.constructor(this.schema, this.state, this.q);
734
- mutate(clone);
735
- return clone;
736
- };
737
- /* Mutation */
738
- DbTable.prototype.with = function (patch) {
739
- var _this = this;
740
- var updates = patch.map(function (entityPatch) {
741
- var id = _this.getId(entityPatch);
742
- var immId = _this.keyToImmutable(id);
743
- var existing = _this.state.pk.get(immId);
744
- var updated = entityPatch;
745
- if (existing) {
746
- updated = tslib_1.__assign(tslib_1.__assign({}, existing), entityPatch);
747
- }
748
- return { id: id, immId: immId, patch: entityPatch, existing: existing, updated: updated, updatedFieldsisNew: !existing };
749
- });
750
- var idVal = immutable_1.Seq.Keyed(updates.map(function (entity) { return [entity.immId, entity.updated]; }));
751
- var newPk = this.state.pk.merge(idVal);
752
- var newIndexes = this.state.indexes.map(function (index) {
753
- var newMap = index.map;
754
- var _loop_1 = function (n) {
755
- var update = updates[n];
756
- var newKey = update.updated[index.field];
757
- if (update.existing) {
758
- var oldKey = update.existing[index.field];
759
- if (oldKey !== newKey) {
760
- newMap = newMap.update(oldKey, function (set) { return set.remove(update.immId); });
761
- }
762
- }
763
- newMap = newMap.update(newKey, I.Set(), function (set) { return set.add(update.immId); });
764
- };
765
- for (var n = 0; n < updates.length; n++) {
766
- _loop_1(n);
767
- }
768
- return tslib_1.__assign(tslib_1.__assign({}, index), { map: newMap });
769
- });
770
- var newState = { pk: newPk, indexes: newIndexes };
771
- return this.update(function (t) { return t.state = newState; });
772
- };
773
- /* Query */
774
- DbTable.prototype.find = function (filter) {
775
- var _this = this;
776
- return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { filter: tslib_1.__assign(tslib_1.__assign({}, _this.q.filter), filter) }); });
777
- };
778
- DbTable.prototype.order = function (order) {
779
- return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { sorting: order }); });
780
- };
781
- DbTable.prototype.orderBy = function (field, direction) {
782
- if (direction === void 0) { direction = 'asc'; }
783
- return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { sorting: [{ field: field, direction: direction }] }); });
784
- };
785
- DbTable.prototype.thenBy = function (field, direction) {
786
- return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { sorting: tslib_1.__spreadArrays(t.q.sorting, [{ field: field, direction: direction }]) }); });
787
- };
788
- DbTable.prototype.search = function (text) {
789
- if (!this.schema.searchBy) {
790
- throw new Error("Can't search in the " + this.schema.typeName + " table - searchBy is not defined in the schema.");
791
- }
792
- return this.update(function (t) { return t.q = tslib_1.__assign(tslib_1.__assign({}, t.q), { search: text }); });
793
- };
794
- /* Materializing */
795
- DbTable.prototype.range = function (from, count) {
796
- return this.runQuery(tslib_1.__assign(tslib_1.__assign({}, this.q), { range: { from: from, count: count } }));
797
- };
798
- DbTable.prototype.count = function () {
799
- return this.runQuery(this.q).length;
800
- };
801
- DbTable.prototype.one = function () {
802
- return this.runQuery(this.q)[0] || null;
803
- };
804
- DbTable.prototype.toArray = function () {
805
- return this.runQuery(this.q);
806
- };
807
- DbTable.prototype.map = function (fn) {
808
- return this.toArray().map(fn);
809
- };
810
- /* Query implementation */
811
- DbTable.prototype.runQuery = function (q) {
812
- var _this = this;
813
- var result = null;
814
- var filter = q.filter;
815
- if (filter) {
816
- var indexes = this.state.indexes;
817
- // Try to use indexes to fulfill filter conditions
818
- for (var n = 0; n < indexes.length; n++) {
819
- var index = indexes[n];
820
- if (index.field in filter) {
821
- var _a = filter, _b = index.field, condition = _a[_b], rest = tslib_1.__rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
822
- var conditionValues = null;
823
- if (condition != null && typeof condition === "object") {
824
- // Attempt to use index for 'in' and 'isNull' criteria.
825
- // We need to be very conservative here, indexed field should work the same way as getPatternPredicate. So
826
- // - it's better to leave corner cases to getPatternPredicate
827
- var _c = condition, inCriteria = _c.in, nullCriteria = _c.isNull, restCriteria = tslib_1.__rest(_c, ["in", "isNull"]);
828
- if (inCriteria && Array.isArray(inCriteria)) {
829
- conditionValues = inCriteria;
830
- }
831
- else {
832
- restCriteria.in = inCriteria;
833
- }
834
- // Conditions in getPatternPredicate are composed with 'and' logic,
835
- // For now, let's not attempt to handle tricky cases like { in: [1,2] isNull: true }, or { in: [1, null] isNull: false }
836
- // - just leave this to getPatternPredicate.
837
- // Let's just handle the a most common case { isNull: true } - find all null and undefined
838
- if (nullCriteria === true && !conditionValues) {
839
- conditionValues = [null, undefined];
840
- }
841
- else {
842
- restCriteria.in = inCriteria;
843
- }
844
- // Keep other conditions, e.g. { in: [1,2,3], isNull: true } - in works via index, isNull - via filter
845
- if (Object.keys(restCriteria).length > 0) {
846
- rest[index.field] = restCriteria;
847
- }
848
- }
849
- else {
850
- conditionValues = [condition];
851
- }
852
- if (conditionValues) {
853
- result = [];
854
- for (var i = 0; i < conditionValues.length; i++) {
855
- var idsSet = index.map.get(conditionValues[i]);
856
- if (idsSet) {
857
- var idsArray = idsSet.toArray();
858
- for (var j = 0; j < idsArray.length; j++) {
859
- var item = this.state.pk.get(idsArray[j]);
860
- result.push(item);
861
- }
862
- }
863
- }
864
- filter = Object.keys(rest).length > 0 ? rest : null;
865
- break;
866
- }
867
- }
868
- }
869
- }
870
- if (!result) {
871
- result = this.state.pk.toArray();
872
- }
873
- if (filter) {
874
- var predicate = uui_1.getPatternPredicate(q.filter);
875
- result = result.filter(predicate);
876
- }
877
- if (q.search) {
878
- var searchFilter_1 = uui_1.getSearchFilter(q.search);
879
- result = result.filter(function (item) { return searchFilter_1(_this.schema.searchBy.map(function (field) { return item[field]; })); });
880
- }
881
- if (q.sorting) {
882
- var comparer = uui_1.getOrderComparer(q.sorting);
883
- result = result.sort(comparer);
884
- }
885
- if (q.range) {
886
- result = result.slice(q.range.from, q.range.from + q.range.count);
887
- }
888
- return result;
889
- };
890
- return DbTable;
891
- }());
892
- exports.DbTable = DbTable;
712
+
713
+ Object.defineProperty(exports, "__esModule", { value: true });
714
+ exports.DbTable = void 0;
715
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
716
+ var I = (0, tslib_1.__importStar)(__webpack_require__(/*! immutable */ "immutable"));
717
+ var uui_core_1 = __webpack_require__(/*! @epam/uui-core */ "@epam/uui-core");
718
+ var immutable_1 = __webpack_require__(/*! immutable */ "immutable");
719
+ var DbTable = /** @class */ (function () {
720
+ function DbTable(schema, state, q) {
721
+ this.schema = schema;
722
+ this.state = state;
723
+ this.q = q;
724
+ if (!state) {
725
+ var indexes = (schema.indexes || []).map(function (indexDef) {
726
+ return {
727
+ field: indexDef,
728
+ map: I.Map(),
729
+ };
730
+ });
731
+ this.state = { pk: I.Map(), indexes: indexes };
732
+ }
733
+ if (!q) {
734
+ this.q = {};
735
+ }
736
+ }
737
+ DbTable.prototype.keyToImmutable = function (id) {
738
+ if (Array.isArray(id)) {
739
+ return I.List(id);
740
+ }
741
+ else {
742
+ return id;
743
+ }
744
+ };
745
+ DbTable.prototype.byId = function (id) {
746
+ return this.state.pk.get(this.keyToImmutable(id));
747
+ };
748
+ DbTable.prototype.getId = function (entity) {
749
+ if (Array.isArray(this.schema.primaryKey)) {
750
+ return this.schema.primaryKey.map(function (key) { return entity[key]; });
751
+ }
752
+ return entity[this.schema.primaryKey];
753
+ };
754
+ DbTable.prototype.update = function (mutate) {
755
+ var clone = new this.constructor(this.schema, this.state, this.q);
756
+ mutate(clone);
757
+ return clone;
758
+ };
759
+ /* Mutation */
760
+ DbTable.prototype.with = function (patch) {
761
+ var _this = this;
762
+ var updates = patch.map(function (entityPatch) {
763
+ var id = _this.getId(entityPatch);
764
+ var immId = _this.keyToImmutable(id);
765
+ var existing = _this.state.pk.get(immId);
766
+ var updated = entityPatch;
767
+ if (existing) {
768
+ updated = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, existing), entityPatch);
769
+ }
770
+ return { id: id, immId: immId, patch: entityPatch, existing: existing, updated: updated, updatedFieldsisNew: !existing };
771
+ });
772
+ var idVal = immutable_1.Seq.Keyed(updates.map(function (entity) { return [entity.immId, entity.updated]; }));
773
+ var newPk = this.state.pk.merge(idVal);
774
+ var newIndexes = this.state.indexes.map(function (index) {
775
+ var newMap = index.map;
776
+ var _loop_1 = function (n) {
777
+ var update = updates[n];
778
+ var newKey = update.updated[index.field];
779
+ if (update.existing) {
780
+ var oldKey = update.existing[index.field];
781
+ if (oldKey !== newKey) {
782
+ newMap = newMap.update(oldKey, function (set) { return set.remove(update.immId); });
783
+ }
784
+ }
785
+ newMap = newMap.update(newKey, I.Set(), function (set) { return set.add(update.immId); });
786
+ };
787
+ for (var n = 0; n < updates.length; n++) {
788
+ _loop_1(n);
789
+ }
790
+ return (0, tslib_1.__assign)((0, tslib_1.__assign)({}, index), { map: newMap });
791
+ });
792
+ var newState = { pk: newPk, indexes: newIndexes };
793
+ return this.update(function (t) { return t.state = newState; });
794
+ };
795
+ /* Query */
796
+ DbTable.prototype.find = function (filter) {
797
+ var _this = this;
798
+ return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { filter: (0, tslib_1.__assign)((0, tslib_1.__assign)({}, _this.q.filter), filter) }); });
799
+ };
800
+ DbTable.prototype.order = function (order) {
801
+ return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { sorting: order }); });
802
+ };
803
+ DbTable.prototype.orderBy = function (field, direction) {
804
+ if (direction === void 0) { direction = 'asc'; }
805
+ return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { sorting: [{ field: field, direction: direction }] }); });
806
+ };
807
+ DbTable.prototype.thenBy = function (field, direction) {
808
+ return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { sorting: (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], t.q.sorting, true), [{ field: field, direction: direction }], false) }); });
809
+ };
810
+ DbTable.prototype.search = function (text) {
811
+ if (!this.schema.searchBy) {
812
+ throw new Error("Can't search in the ".concat(this.schema.typeName, " table - searchBy is not defined in the schema."));
813
+ }
814
+ return this.update(function (t) { return t.q = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, t.q), { search: text }); });
815
+ };
816
+ /* Materializing */
817
+ DbTable.prototype.range = function (from, count) {
818
+ return this.runQuery((0, tslib_1.__assign)((0, tslib_1.__assign)({}, this.q), { range: { from: from, count: count } }));
819
+ };
820
+ DbTable.prototype.count = function () {
821
+ return this.runQuery(this.q).length;
822
+ };
823
+ DbTable.prototype.one = function () {
824
+ return this.runQuery(this.q)[0] || null;
825
+ };
826
+ DbTable.prototype.toArray = function () {
827
+ return this.runQuery(this.q);
828
+ };
829
+ DbTable.prototype.map = function (fn) {
830
+ return this.toArray().map(fn);
831
+ };
832
+ /* Query implementation */
833
+ DbTable.prototype.runQuery = function (q) {
834
+ var _this = this;
835
+ var result = null;
836
+ var filter = q.filter;
837
+ if (filter) {
838
+ var indexes = this.state.indexes;
839
+ // Try to use indexes to fulfill filter conditions
840
+ for (var n = 0; n < indexes.length; n++) {
841
+ var index = indexes[n];
842
+ if (index.field in filter) {
843
+ var _a = filter, _b = index.field, condition = _a[_b], rest = (0, tslib_1.__rest)(_a, [typeof _b === "symbol" ? _b : _b + ""]);
844
+ var conditionValues = null;
845
+ if (condition != null && typeof condition === "object") {
846
+ // Attempt to use index for 'in' and 'isNull' criteria.
847
+ // We need to be very conservative here, indexed field should work the same way as getPatternPredicate. So
848
+ // - it's better to leave corner cases to getPatternPredicate
849
+ var _c = condition, inCriteria = _c.in, nullCriteria = _c.isNull, restCriteria = (0, tslib_1.__rest)(_c, ["in", "isNull"]);
850
+ if (inCriteria && Array.isArray(inCriteria)) {
851
+ conditionValues = inCriteria;
852
+ }
853
+ else {
854
+ restCriteria.in = inCriteria;
855
+ }
856
+ // Conditions in getPatternPredicate are composed with 'and' logic,
857
+ // For now, let's not attempt to handle tricky cases like { in: [1,2] isNull: true }, or { in: [1, null] isNull: false }
858
+ // - just leave this to getPatternPredicate.
859
+ // Let's just handle the a most common case { isNull: true } - find all null and undefined
860
+ if (nullCriteria === true && !conditionValues) {
861
+ conditionValues = [null, undefined];
862
+ }
863
+ else {
864
+ restCriteria.in = inCriteria;
865
+ }
866
+ // Keep other conditions, e.g. { in: [1,2,3], isNull: true } - in works via index, isNull - via filter
867
+ if (Object.keys(restCriteria).length > 0) {
868
+ rest[index.field] = restCriteria;
869
+ }
870
+ }
871
+ else {
872
+ conditionValues = [condition];
873
+ }
874
+ if (conditionValues) {
875
+ result = [];
876
+ for (var i = 0; i < conditionValues.length; i++) {
877
+ var idsSet = index.map.get(conditionValues[i]);
878
+ if (idsSet) {
879
+ var idsArray = idsSet.toArray();
880
+ for (var j = 0; j < idsArray.length; j++) {
881
+ var item = this.state.pk.get(idsArray[j]);
882
+ result.push(item);
883
+ }
884
+ }
885
+ }
886
+ filter = Object.keys(rest).length > 0 ? rest : null;
887
+ break;
888
+ }
889
+ }
890
+ }
891
+ }
892
+ if (!result) {
893
+ result = this.state.pk.toArray();
894
+ }
895
+ if (filter) {
896
+ var predicate = (0, uui_core_1.getPatternPredicate)(q.filter);
897
+ result = result.filter(predicate);
898
+ }
899
+ if (q.search) {
900
+ var searchFilter_1 = (0, uui_core_1.getSearchFilter)(q.search);
901
+ result = result.filter(function (item) { return searchFilter_1(_this.schema.searchBy.map(function (field) { return item[field]; })); });
902
+ }
903
+ if (q.sorting) {
904
+ var comparer = (0, uui_core_1.getOrderComparer)(q.sorting);
905
+ result = result.sort(comparer);
906
+ }
907
+ if (q.range) {
908
+ result = result.slice(q.range.from, q.range.from + q.range.count);
909
+ }
910
+ return result;
911
+ };
912
+ return DbTable;
913
+ }());
914
+ exports.DbTable = DbTable;
893
915
 
894
916
 
895
917
  /***/ }),
@@ -902,99 +924,99 @@ exports.DbTable = DbTable;
902
924
  /***/ (function(module, exports, __webpack_require__) {
903
925
 
904
926
  "use strict";
905
-
906
- Object.defineProperty(exports, "__esModule", { value: true });
907
- exports.ListLoadingTracker = void 0;
908
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
909
- var ListLoadingTracker = /** @class */ (function () {
910
- function ListLoadingTracker(options) {
911
- this.options = options;
912
- this.cache = new Map();
913
- this.extractList = (options === null || options === void 0 ? void 0 : options.extractList) || (function (r) { return r; });
914
- }
915
- ListLoadingTracker.prototype.prepare = function (request) {
916
- var filter = request.filter, sorting = request.sorting, search = request.search, range = request.range, unknownFields = tslib_1.__rest(request, ["filter", "sorting", "search", "range"]);
917
- var options = {};
918
- if (filter) {
919
- options.filter = filter;
920
- }
921
- if (sorting) {
922
- options.sorting = sorting;
923
- }
924
- if (search) {
925
- options.search = search;
926
- }
927
- var keyObject = tslib_1.__assign(tslib_1.__assign({}, options), unknownFields);
928
- var key = JSON.stringify(keyObject);
929
- var entry = this.cache.get(key);
930
- if (!entry) {
931
- entry = { options: options, count: 0, maxCount: null, isComplete: false };
932
- this.cache.set(key, entry);
933
- }
934
- return { options: options, range: range, unknownFields: unknownFields, entry: entry };
935
- };
936
- ListLoadingTracker.prototype.diff = function (request) {
937
- var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
938
- if (entry.isComplete) {
939
- return null;
940
- }
941
- if (!request.range) {
942
- return request;
943
- }
944
- else {
945
- var requestedMax = request.range.from + request.range.count;
946
- var missingCount = requestedMax - entry.count;
947
- if (entry.maxCount) {
948
- missingCount = Math.min(missingCount, entry.maxCount);
949
- }
950
- if (missingCount > 0) {
951
- return tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, options), unknownFields), { range: { from: entry.count, count: requestedMax - entry.count } });
952
- }
953
- else {
954
- return null;
955
- }
956
- }
957
- };
958
- ListLoadingTracker.prototype.count = function (request) {
959
- var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
960
- return { knownCount: Math.max(entry.count, entry.maxCount), exactCount: entry.maxCount };
961
- };
962
- ListLoadingTracker.prototype.append = function (request, response) {
963
- var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
964
- if (response) {
965
- var list = this.extractList(response);
966
- if (list.count) {
967
- entry.maxCount = list.count;
968
- }
969
- if (!range) {
970
- entry.count = list.items.length;
971
- entry.maxCount = list.items.length;
972
- entry.isComplete = true;
973
- }
974
- else {
975
- var from = (list.from == null) ? range.from : list.from;
976
- if (list.items.length > 0) {
977
- entry.count = Math.max(entry.count, from + list.items.length);
978
- }
979
- if (list.items.length < range.count) {
980
- entry.maxCount = from + list.items.length;
981
- entry.count = entry.maxCount;
982
- entry.isComplete = true;
983
- }
984
- }
985
- }
986
- else {
987
- if (range) {
988
- entry.count = Math.max(entry.count, request.range.from + request.range.count);
989
- }
990
- else {
991
- entry.isComplete = true;
992
- }
993
- }
994
- };
995
- return ListLoadingTracker;
996
- }());
997
- exports.ListLoadingTracker = ListLoadingTracker;
927
+
928
+ Object.defineProperty(exports, "__esModule", { value: true });
929
+ exports.ListLoadingTracker = void 0;
930
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
931
+ var ListLoadingTracker = /** @class */ (function () {
932
+ function ListLoadingTracker(options) {
933
+ this.options = options;
934
+ this.cache = new Map();
935
+ this.extractList = (options === null || options === void 0 ? void 0 : options.extractList) || (function (r) { return r; });
936
+ }
937
+ ListLoadingTracker.prototype.prepare = function (request) {
938
+ var filter = request.filter, sorting = request.sorting, search = request.search, range = request.range, unknownFields = (0, tslib_1.__rest)(request, ["filter", "sorting", "search", "range"]);
939
+ var options = {};
940
+ if (filter) {
941
+ options.filter = filter;
942
+ }
943
+ if (sorting) {
944
+ options.sorting = sorting;
945
+ }
946
+ if (search) {
947
+ options.search = search;
948
+ }
949
+ var keyObject = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, options), unknownFields);
950
+ var key = JSON.stringify(keyObject);
951
+ var entry = this.cache.get(key);
952
+ if (!entry) {
953
+ entry = { options: options, count: 0, maxCount: null, isComplete: false };
954
+ this.cache.set(key, entry);
955
+ }
956
+ return { options: options, range: range, unknownFields: unknownFields, entry: entry };
957
+ };
958
+ ListLoadingTracker.prototype.diff = function (request) {
959
+ var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
960
+ if (entry.isComplete) {
961
+ return null;
962
+ }
963
+ if (!request.range) {
964
+ return request;
965
+ }
966
+ else {
967
+ var requestedMax = request.range.from + request.range.count;
968
+ var missingCount = requestedMax - entry.count;
969
+ if (entry.maxCount) {
970
+ missingCount = Math.min(missingCount, entry.maxCount);
971
+ }
972
+ if (missingCount > 0) {
973
+ return (0, tslib_1.__assign)((0, tslib_1.__assign)((0, tslib_1.__assign)({}, options), unknownFields), { range: { from: entry.count, count: requestedMax - entry.count } });
974
+ }
975
+ else {
976
+ return null;
977
+ }
978
+ }
979
+ };
980
+ ListLoadingTracker.prototype.count = function (request) {
981
+ var entry = this.prepare(request).entry;
982
+ return { knownCount: Math.max(entry.count, entry.maxCount), exactCount: entry.maxCount };
983
+ };
984
+ ListLoadingTracker.prototype.append = function (request, response) {
985
+ var _a = this.prepare(request), options = _a.options, range = _a.range, unknownFields = _a.unknownFields, entry = _a.entry;
986
+ if (response) {
987
+ var list = this.extractList(response);
988
+ if (list.count) {
989
+ entry.maxCount = list.count;
990
+ }
991
+ if (!range) {
992
+ entry.count = list.items.length;
993
+ entry.maxCount = list.items.length;
994
+ entry.isComplete = true;
995
+ }
996
+ else {
997
+ var from = (list.from == null) ? range.from : list.from;
998
+ if (list.items.length > 0) {
999
+ entry.count = Math.max(entry.count, from + list.items.length);
1000
+ }
1001
+ if (list.items.length < range.count) {
1002
+ entry.maxCount = from + list.items.length;
1003
+ entry.count = entry.maxCount;
1004
+ entry.isComplete = true;
1005
+ }
1006
+ }
1007
+ }
1008
+ else {
1009
+ if (range) {
1010
+ entry.count = Math.max(entry.count, request.range.from + request.range.count);
1011
+ }
1012
+ else {
1013
+ entry.isComplete = true;
1014
+ }
1015
+ }
1016
+ };
1017
+ return ListLoadingTracker;
1018
+ }());
1019
+ exports.ListLoadingTracker = ListLoadingTracker;
998
1020
 
999
1021
 
1000
1022
  /***/ }),
@@ -1007,84 +1029,84 @@ exports.ListLoadingTracker = ListLoadingTracker;
1007
1029
  /***/ (function(module, exports, __webpack_require__) {
1008
1030
 
1009
1031
  "use strict";
1010
-
1011
- Object.defineProperty(exports, "__esModule", { value: true });
1012
- exports.Loader = void 0;
1013
- var Loader = /** @class */ (function () {
1014
- function Loader(dbRef, getTracker, options) {
1015
- var _this = this;
1016
- this.dbRef = dbRef;
1017
- this.getTracker = getTracker;
1018
- this.options = options;
1019
- this.currentRequests = new Set();
1020
- this.load = function (inputRequest) {
1021
- var result = {
1022
- isComplete: _this.loaded.diff(inputRequest) == null,
1023
- isLoading: false,
1024
- request: inputRequest,
1025
- missing: _this.loadedAndLoading.diff(inputRequest),
1026
- promise: null,
1027
- reload: null,
1028
- };
1029
- result.reload = function () {
1030
- result.missing = inputRequest;
1031
- _this.loadImpl(result);
1032
- };
1033
- if (result.isComplete) {
1034
- // Everything requested is already loaded
1035
- result.isComplete = true;
1036
- result.isLoading = false;
1037
- result.promise = Promise.resolve();
1038
- return result;
1039
- }
1040
- else {
1041
- if (result.missing == null) {
1042
- // Everything requested is either loaded already, or being loaded
1043
- result.isComplete = false;
1044
- result.isLoading = true;
1045
- // There's no good way to tell which of current requests is querying requested data - there actually can be 2 of them.
1046
- // So we track all running requests, and await all of them in such case.
1047
- result.promise = Promise.all(_this.currentRequests.entries()).then(function () { });
1048
- return result;
1049
- }
1050
- else {
1051
- // Something requested is not loaded, nor being loaded. Need to perform a new request.
1052
- _this.loadImpl(result);
1053
- return result;
1054
- }
1055
- }
1056
- };
1057
- this.loaded = getTracker();
1058
- this.loadedAndLoading = getTracker();
1059
- }
1060
- Loader.prototype.loadImpl = function (state) {
1061
- var _this = this;
1062
- this.loadedAndLoading.append(state.missing);
1063
- state.isLoading = true;
1064
- var serverRequest = state.missing;
1065
- if (this.options.clientToServerRequest) {
1066
- serverRequest = this.options.clientToServerRequest(serverRequest);
1067
- }
1068
- state.promise = this.options.api(serverRequest).then(function (result) {
1069
- _this.loaded.append(state.missing, result);
1070
- _this.loadedAndLoading.append(state.missing, result);
1071
- state.missing = null;
1072
- state.isLoading = false;
1073
- state.isComplete = true;
1074
- state.promise = Promise.resolve();
1075
- var flatten = _this.options.convertToPatch(result);
1076
- _this.options.postProcess && _this.options.postProcess(flatten);
1077
- _this.dbRef.commitFetch(flatten);
1078
- });
1079
- this.currentRequests.add(state.promise);
1080
- state.promise.finally(function () {
1081
- _this.currentRequests.delete(state.promise);
1082
- });
1083
- return state.promise;
1084
- };
1085
- return Loader;
1086
- }());
1087
- exports.Loader = Loader;
1032
+
1033
+ Object.defineProperty(exports, "__esModule", { value: true });
1034
+ exports.Loader = void 0;
1035
+ var Loader = /** @class */ (function () {
1036
+ function Loader(dbRef, getTracker, options) {
1037
+ var _this = this;
1038
+ this.dbRef = dbRef;
1039
+ this.getTracker = getTracker;
1040
+ this.options = options;
1041
+ this.currentRequests = new Set();
1042
+ this.load = function (inputRequest) {
1043
+ var result = {
1044
+ isComplete: _this.loaded.diff(inputRequest) == null,
1045
+ isLoading: false,
1046
+ request: inputRequest,
1047
+ missing: _this.loadedAndLoading.diff(inputRequest),
1048
+ promise: null,
1049
+ reload: null,
1050
+ };
1051
+ result.reload = function () {
1052
+ result.missing = inputRequest;
1053
+ _this.loadImpl(result);
1054
+ };
1055
+ if (result.isComplete) {
1056
+ // Everything requested is already loaded
1057
+ result.isComplete = true;
1058
+ result.isLoading = false;
1059
+ result.promise = Promise.resolve();
1060
+ return result;
1061
+ }
1062
+ else {
1063
+ if (result.missing == null) {
1064
+ // Everything requested is either loaded already, or being loaded
1065
+ result.isComplete = false;
1066
+ result.isLoading = true;
1067
+ // There's no good way to tell which of current requests is querying requested data - there actually can be 2 of them.
1068
+ // So we track all running requests, and await all of them in such case.
1069
+ result.promise = Promise.all(_this.currentRequests.entries()).then(function () { });
1070
+ return result;
1071
+ }
1072
+ else {
1073
+ // Something requested is not loaded, nor being loaded. Need to perform a new request.
1074
+ _this.loadImpl(result);
1075
+ return result;
1076
+ }
1077
+ }
1078
+ };
1079
+ this.loaded = getTracker();
1080
+ this.loadedAndLoading = getTracker();
1081
+ }
1082
+ Loader.prototype.loadImpl = function (state) {
1083
+ var _this = this;
1084
+ this.loadedAndLoading.append(state.missing);
1085
+ state.isLoading = true;
1086
+ var serverRequest = state.missing;
1087
+ if (this.options.clientToServerRequest) {
1088
+ serverRequest = this.options.clientToServerRequest(serverRequest);
1089
+ }
1090
+ state.promise = this.options.api(serverRequest).then(function (result) {
1091
+ _this.loaded.append(state.missing, result);
1092
+ _this.loadedAndLoading.append(state.missing, result);
1093
+ state.missing = null;
1094
+ state.isLoading = false;
1095
+ state.isComplete = true;
1096
+ state.promise = Promise.resolve();
1097
+ var flatten = _this.options.convertToPatch(result);
1098
+ _this.options.postProcess && _this.options.postProcess(flatten);
1099
+ _this.dbRef.commitFetch(flatten);
1100
+ });
1101
+ this.currentRequests.add(state.promise);
1102
+ state.promise.finally(function () {
1103
+ _this.currentRequests.delete(state.promise);
1104
+ });
1105
+ return state.promise;
1106
+ };
1107
+ return Loader;
1108
+ }());
1109
+ exports.Loader = Loader;
1088
1110
 
1089
1111
 
1090
1112
  /***/ }),
@@ -1097,25 +1119,25 @@ exports.Loader = Loader;
1097
1119
  /***/ (function(module, exports, __webpack_require__) {
1098
1120
 
1099
1121
  "use strict";
1100
-
1101
- Object.defineProperty(exports, "__esModule", { value: true });
1102
- exports.SimpleLoadingTracker = void 0;
1103
- var SimpleLoadingTracker = /** @class */ (function () {
1104
- function SimpleLoadingTracker() {
1105
- this.set = new Set();
1106
- }
1107
- SimpleLoadingTracker.prototype.getKey = function (request) {
1108
- return JSON.stringify(request);
1109
- };
1110
- SimpleLoadingTracker.prototype.diff = function (request) {
1111
- return this.set.has(this.getKey(request)) ? null : request;
1112
- };
1113
- SimpleLoadingTracker.prototype.append = function (request, result) {
1114
- this.set.add(this.getKey(request));
1115
- };
1116
- return SimpleLoadingTracker;
1117
- }());
1118
- exports.SimpleLoadingTracker = SimpleLoadingTracker;
1122
+
1123
+ Object.defineProperty(exports, "__esModule", { value: true });
1124
+ exports.SimpleLoadingTracker = void 0;
1125
+ var SimpleLoadingTracker = /** @class */ (function () {
1126
+ function SimpleLoadingTracker() {
1127
+ this.set = new Set();
1128
+ }
1129
+ SimpleLoadingTracker.prototype.getKey = function (request) {
1130
+ return JSON.stringify(request);
1131
+ };
1132
+ SimpleLoadingTracker.prototype.diff = function (request) {
1133
+ return this.set.has(this.getKey(request)) ? null : request;
1134
+ };
1135
+ SimpleLoadingTracker.prototype.append = function (request, result) {
1136
+ this.set.add(this.getKey(request));
1137
+ };
1138
+ return SimpleLoadingTracker;
1139
+ }());
1140
+ exports.SimpleLoadingTracker = SimpleLoadingTracker;
1119
1141
 
1120
1142
 
1121
1143
  /***/ }),
@@ -1128,17 +1150,17 @@ exports.SimpleLoadingTracker = SimpleLoadingTracker;
1128
1150
  /***/ (function(module, exports, __webpack_require__) {
1129
1151
 
1130
1152
  "use strict";
1131
-
1132
- Object.defineProperty(exports, "__esModule", { value: true });
1133
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1134
- tslib_1.__exportStar(__webpack_require__(/*! ./types */ "./src/types.ts"), exports);
1135
- tslib_1.__exportStar(__webpack_require__(/*! ./Db */ "./src/Db.ts"), exports);
1136
- tslib_1.__exportStar(__webpack_require__(/*! ./DbTable */ "./src/DbTable.ts"), exports);
1137
- tslib_1.__exportStar(__webpack_require__(/*! ./DbRef */ "./src/DbRef.ts"), exports);
1138
- tslib_1.__exportStar(__webpack_require__(/*! ./tempIds */ "./src/tempIds.tsx"), exports);
1139
- tslib_1.__exportStar(__webpack_require__(/*! ./utils */ "./src/utils.ts"), exports);
1140
- tslib_1.__exportStar(__webpack_require__(/*! ./patchHelpers */ "./src/patchHelpers.ts"), exports);
1141
- tslib_1.__exportStar(__webpack_require__(/*! ./reactHooks */ "./src/reactHooks.ts"), exports);
1153
+
1154
+ Object.defineProperty(exports, "__esModule", { value: true });
1155
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1156
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./types */ "./src/types.ts"), exports);
1157
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./Db */ "./src/Db.ts"), exports);
1158
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./DbTable */ "./src/DbTable.ts"), exports);
1159
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./DbRef */ "./src/DbRef.ts"), exports);
1160
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./tempIds */ "./src/tempIds.tsx"), exports);
1161
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./utils */ "./src/utils.ts"), exports);
1162
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./patchHelpers */ "./src/patchHelpers.ts"), exports);
1163
+ (0, tslib_1.__exportStar)(__webpack_require__(/*! ./reactHooks */ "./src/reactHooks.ts"), exports);
1142
1164
 
1143
1165
 
1144
1166
  /***/ }),
@@ -1151,200 +1173,200 @@ tslib_1.__exportStar(__webpack_require__(/*! ./reactHooks */ "./src/reactHooks.t
1151
1173
  /***/ (function(module, exports, __webpack_require__) {
1152
1174
 
1153
1175
  "use strict";
1154
-
1155
- Object.defineProperty(exports, "__esModule", { value: true });
1156
- exports.getEntityParentDependencies = exports.getParentEntities = exports.hasServerFields = exports.isNew = exports.getId = exports.isClientOnly = exports.makeCumulativePatch = exports.isPatchBlank = exports.flattenResponse = exports.mergeEntityPatches = exports.unionPatches = void 0;
1157
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1158
- var types_1 = __webpack_require__(/*! ./types */ "./src/types.ts");
1159
- var I = tslib_1.__importStar(__webpack_require__(/*! immutable */ "immutable"));
1160
- var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
1161
- var lodash_groupby_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.groupby */ "lodash.groupby"));
1162
- var lodash_map_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.map */ "lodash.map"));
1163
- var lodash_merge_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.merge */ "lodash.merge"));
1164
- var lodash_countby_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.countby */ "lodash.countby"));
1165
- var lodash_filter_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.filter */ "lodash.filter"));
1166
- var lodash_foreach_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.foreach */ "lodash.foreach"));
1167
- var lodash_pick_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.pick */ "lodash.pick"));
1168
- function unionPatches(patches) {
1169
- var result = {};
1170
- patches.forEach(function (patch) {
1171
- utils_1.objectKeys(patch).forEach(function (tableName) {
1172
- result[tableName] = result[tableName] ? tslib_1.__spreadArrays(result[tableName], patch[tableName]) : patch[tableName];
1173
- });
1174
- });
1175
- return result;
1176
- }
1177
- exports.unionPatches = unionPatches;
1178
- function mergeEntityPatches(tables, patch) {
1179
- var result = {};
1180
- utils_1.objectKeys(patch).forEach(function (key) {
1181
- var table = tables[key];
1182
- var groupedEntities = lodash_groupby_1.default(patch[key], function (item) { return table.getId(item); });
1183
- var tablePatch = lodash_map_1.default(groupedEntities, function (entities) {
1184
- var result = lodash_merge_1.default.apply(void 0, tslib_1.__spreadArrays([{}], entities));
1185
- if (true) {
1186
- var props = utils_1.objectKeys(result).filter(function (prop) {
1187
- return Object.keys(lodash_countby_1.default(entities.filter(function (entity) {
1188
- return entity[prop] !== undefined;
1189
- }), function (entity) { return entity[prop]; })).length > 1;
1190
- });
1191
- if (props.length) {
1192
- console.warn.apply(console, tslib_1.__spreadArrays(['mergeEntityPatches: Different property values found for the same entity.\nProperty names:\n', props, '\nEntities:\n'], entities));
1193
- }
1194
- }
1195
- return result;
1196
- });
1197
- result[key] = tablePatch;
1198
- });
1199
- return result;
1200
- }
1201
- exports.mergeEntityPatches = mergeEntityPatches;
1202
- function flattenResponseHelper(result, object, tablesByTypeName) {
1203
- if (Array.isArray(object)) {
1204
- object.forEach(function (item) { return flattenResponseHelper(result, item, tablesByTypeName); });
1205
- }
1206
- else if (typeof object === 'object') {
1207
- var clone = {};
1208
- var tableKey = void 0;
1209
- var fields = {};
1210
- if ('__typename' in object) {
1211
- var table = tablesByTypeName[object.__typename];
1212
- if (table) {
1213
- tableKey = table.schema.tableName;
1214
- fields = table.schema.fields;
1215
- }
1216
- }
1217
- for (var key in object) {
1218
- var value = object[key];
1219
- var field = fields[key];
1220
- if ((field && !!field.disableFlatten)
1221
- || typeof value !== 'object'
1222
- || value === null
1223
- || (Array.isArray(value) && value.every(function (item) { return typeof item !== 'object'; }))) {
1224
- clone[key] = value;
1225
- }
1226
- else {
1227
- flattenResponseHelper(result, value, tablesByTypeName);
1228
- }
1229
- }
1230
- if (tableKey) {
1231
- result[tableKey].push(clone);
1232
- }
1233
- }
1234
- }
1235
- function flattenResponse(response, tables) {
1236
- var result = {};
1237
- var tablesByTypeName = {};
1238
- Object.values(tables).forEach(function (table) { return tablesByTypeName[table.schema.typeName] = table; });
1239
- utils_1.objectKeys(tables).forEach(function (tableName) { return tablesByTypeName; });
1240
- utils_1.objectKeys(tables).forEach(function (key) { return result[key] = []; });
1241
- flattenResponseHelper(result, response, tablesByTypeName);
1242
- return result;
1243
- }
1244
- exports.flattenResponse = flattenResponse;
1245
- function isPatchBlank(patch) {
1246
- return !utils_1.objectKeys(patch).some(function (key) { return patch[key].length > 0; });
1247
- }
1248
- exports.isPatchBlank = isPatchBlank;
1249
- /**
1250
- * Given several patches, creates a new single patch with all fields from all entities in all patches.
1251
- */
1252
- function makeCumulativePatch(updatedDb, patches, clientIdsMap) {
1253
- var result = {};
1254
- utils_1.objectKeys(updatedDb.tables).forEach(function (entityName) {
1255
- var table = updatedDb.tables[entityName];
1256
- var schema = table.schema;
1257
- var ids = I.Set();
1258
- patches.forEach(function (patch) {
1259
- var filteredPatch = (patch[entityName] || []).filter(function (entity) { return hasServerFields(entity, schema, clientIdsMap, updatedDb.tables); });
1260
- ids = ids.union(filteredPatch.map(function (e) { return table.getId(e); }));
1261
- });
1262
- var entities = ids
1263
- .map(function (id) { return table.byId(id); })
1264
- .filter(function (e) { return !isClientOnly(e, schema); })
1265
- .toArray();
1266
- if (entities.length > 0) {
1267
- result[entityName] = entities;
1268
- }
1269
- });
1270
- return result;
1271
- }
1272
- exports.makeCumulativePatch = makeCumulativePatch;
1273
- function isClientOnly(entity, schema) {
1274
- if (typeof schema.isClientOnly === 'function') {
1275
- return schema.isClientOnly(entity);
1276
- }
1277
- return !!schema.isClientOnly;
1278
- }
1279
- exports.isClientOnly = isClientOnly;
1280
- function getId(entity, schema) {
1281
- if (typeof schema.primaryKey == 'string') {
1282
- return entity[schema.primaryKey];
1283
- }
1284
- var result = [];
1285
- lodash_foreach_1.default(lodash_pick_1.default(entity, schema.primaryKey), function (value) {
1286
- result.push(value);
1287
- });
1288
- return result;
1289
- }
1290
- exports.getId = getId;
1291
- function isNew(entity, schema, clientIdsMap) {
1292
- var id = getId(entity, schema);
1293
- return !clientIdsMap.clientToServer(id);
1294
- }
1295
- exports.isNew = isNew;
1296
- function hasServerFields(entity, schema, clientIdsMap, tables) {
1297
- var fullEntity = tslib_1.__assign(tslib_1.__assign({}, tables[schema.tableName].byId(entity.id) || {}), entity);
1298
- if (isClientOnly(fullEntity, schema)) {
1299
- return false;
1300
- }
1301
- return utils_1.objectKeys(entity).some(function (fieldName) {
1302
- var fieldSchema = schema.fields[fieldName];
1303
- return !fieldSchema || !(fieldSchema.isClientOnly || fieldSchema.isReadOnly || (fieldSchema.isGenerated && !isNew(entity, schema, clientIdsMap)));
1304
- });
1305
- }
1306
- exports.hasServerFields = hasServerFields;
1307
- function getParentEntities(patch, tables) {
1308
- var dependenciesPatch = {};
1309
- utils_1.objectKeys(patch).forEach(function (key) {
1310
- var table = tables[key];
1311
- var tableSchema = table.schema;
1312
- var fields = lodash_filter_1.default(lodash_map_1.default(tableSchema.fields, function (field, name) { return (tslib_1.__assign(tslib_1.__assign({}, field), { name: name })); }), function (field) { return field.fk && field.fk.relationType == types_1.DbRelationType.Aggregation; });
1313
- var tablePatch = patch[key];
1314
- fields.forEach(function (field) {
1315
- var tableName = field.fk.tableName, name = field.name;
1316
- tablePatch.forEach(function (entity) {
1317
- var actualTableName = (typeof tableName == 'function' ? tableName(entity) : tableName);
1318
- var dbEntity = table.byId(table.getId(entity));
1319
- var parentEntity = tables[actualTableName].byId(dbEntity[name]);
1320
- var idFields = lodash_pick_1.default(parentEntity, tables[actualTableName].schema.primaryKey);
1321
- if (parentEntity) {
1322
- dependenciesPatch[actualTableName] = dependenciesPatch[actualTableName] || [];
1323
- dependenciesPatch[actualTableName].push(idFields);
1324
- }
1325
- });
1326
- });
1327
- });
1328
- return dependenciesPatch;
1329
- }
1330
- exports.getParentEntities = getParentEntities;
1331
- function getEntityParentDependencies(entity, entityName, tables) {
1332
- var _a;
1333
- var patch = (_a = {}, _a[entityName] = [entity], _a);
1334
- var resultPatches = [];
1335
- while (true) {
1336
- var parents = getParentEntities(patch, tables);
1337
- if (isPatchBlank(parents)) {
1338
- break;
1339
- }
1340
- resultPatches.push(parents);
1341
- patch = parents;
1342
- }
1343
- var result = unionPatches(tslib_1.__spreadArrays([patch], resultPatches));
1344
- result = mergeEntityPatches(tables, result);
1345
- return result;
1346
- }
1347
- exports.getEntityParentDependencies = getEntityParentDependencies;
1176
+
1177
+ Object.defineProperty(exports, "__esModule", { value: true });
1178
+ exports.getEntityParentDependencies = exports.getParentEntities = exports.hasServerFields = exports.isNew = exports.getId = exports.isClientOnly = exports.makeCumulativePatch = exports.isPatchBlank = exports.flattenResponse = exports.mergeEntityPatches = exports.unionPatches = void 0;
1179
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1180
+ var types_1 = __webpack_require__(/*! ./types */ "./src/types.ts");
1181
+ var I = (0, tslib_1.__importStar)(__webpack_require__(/*! immutable */ "immutable"));
1182
+ var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
1183
+ var lodash_groupby_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.groupby */ "lodash.groupby"));
1184
+ var lodash_map_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.map */ "lodash.map"));
1185
+ var lodash_merge_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.merge */ "lodash.merge"));
1186
+ var lodash_countby_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.countby */ "lodash.countby"));
1187
+ var lodash_filter_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.filter */ "lodash.filter"));
1188
+ var lodash_foreach_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.foreach */ "lodash.foreach"));
1189
+ var lodash_pick_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.pick */ "lodash.pick"));
1190
+ function unionPatches(patches) {
1191
+ var result = {};
1192
+ patches.forEach(function (patch) {
1193
+ (0, utils_1.objectKeys)(patch).forEach(function (tableName) {
1194
+ result[tableName] = result[tableName] ? (0, tslib_1.__spreadArray)((0, tslib_1.__spreadArray)([], result[tableName], true), patch[tableName], true) : patch[tableName];
1195
+ });
1196
+ });
1197
+ return result;
1198
+ }
1199
+ exports.unionPatches = unionPatches;
1200
+ function mergeEntityPatches(tables, patch) {
1201
+ var result = {};
1202
+ (0, utils_1.objectKeys)(patch).forEach(function (key) {
1203
+ var table = tables[key];
1204
+ var groupedEntities = (0, lodash_groupby_1.default)(patch[key], function (item) { return table.getId(item); });
1205
+ var tablePatch = (0, lodash_map_1.default)(groupedEntities, function (entities) {
1206
+ var result = lodash_merge_1.default.apply(void 0, (0, tslib_1.__spreadArray)([{}], entities, false));
1207
+ if (true) {
1208
+ var props = (0, utils_1.objectKeys)(result).filter(function (prop) {
1209
+ return Object.keys((0, lodash_countby_1.default)(entities.filter(function (entity) {
1210
+ return entity[prop] !== undefined;
1211
+ }), function (entity) { return entity[prop]; })).length > 1;
1212
+ });
1213
+ if (props.length) {
1214
+ console.warn.apply(console, (0, tslib_1.__spreadArray)(['mergeEntityPatches: Different property values found for the same entity.\nProperty names:\n', props, '\nEntities:\n'], entities, false));
1215
+ }
1216
+ }
1217
+ return result;
1218
+ });
1219
+ result[key] = tablePatch;
1220
+ });
1221
+ return result;
1222
+ }
1223
+ exports.mergeEntityPatches = mergeEntityPatches;
1224
+ function flattenResponseHelper(result, object, tablesByTypeName) {
1225
+ if (Array.isArray(object)) {
1226
+ object.forEach(function (item) { return flattenResponseHelper(result, item, tablesByTypeName); });
1227
+ }
1228
+ else if (typeof object === 'object') {
1229
+ var clone = {};
1230
+ var tableKey = void 0;
1231
+ var fields = {};
1232
+ if ('__typename' in object) {
1233
+ var table = tablesByTypeName[object.__typename];
1234
+ if (table) {
1235
+ tableKey = table.schema.tableName;
1236
+ fields = table.schema.fields;
1237
+ }
1238
+ }
1239
+ for (var key in object) {
1240
+ var value = object[key];
1241
+ var field = fields[key];
1242
+ if ((field && !!field.disableFlatten)
1243
+ || typeof value !== 'object'
1244
+ || value === null
1245
+ || (Array.isArray(value) && value.every(function (item) { return typeof item !== 'object'; }))) {
1246
+ clone[key] = value;
1247
+ }
1248
+ else {
1249
+ flattenResponseHelper(result, value, tablesByTypeName);
1250
+ }
1251
+ }
1252
+ if (tableKey) {
1253
+ result[tableKey].push(clone);
1254
+ }
1255
+ }
1256
+ }
1257
+ function flattenResponse(response, tables) {
1258
+ var result = {};
1259
+ var tablesByTypeName = {};
1260
+ Object.values(tables).forEach(function (table) { return tablesByTypeName[table.schema.typeName] = table; });
1261
+ (0, utils_1.objectKeys)(tables).forEach(function (tableName) { return tablesByTypeName; });
1262
+ (0, utils_1.objectKeys)(tables).forEach(function (key) { return result[key] = []; });
1263
+ flattenResponseHelper(result, response, tablesByTypeName);
1264
+ return result;
1265
+ }
1266
+ exports.flattenResponse = flattenResponse;
1267
+ function isPatchBlank(patch) {
1268
+ return !(0, utils_1.objectKeys)(patch).some(function (key) { return patch[key].length > 0; });
1269
+ }
1270
+ exports.isPatchBlank = isPatchBlank;
1271
+ /**
1272
+ * Given several patches, creates a new single patch with all fields from all entities in all patches.
1273
+ */
1274
+ function makeCumulativePatch(updatedDb, patches, clientIdsMap) {
1275
+ var result = {};
1276
+ (0, utils_1.objectKeys)(updatedDb.tables).forEach(function (entityName) {
1277
+ var table = updatedDb.tables[entityName];
1278
+ var schema = table.schema;
1279
+ var ids = I.Set();
1280
+ patches.forEach(function (patch) {
1281
+ var filteredPatch = (patch[entityName] || []).filter(function (entity) { return hasServerFields(entity, schema, clientIdsMap, updatedDb.tables); });
1282
+ ids = ids.union(filteredPatch.map(function (e) { return table.getId(e); }));
1283
+ });
1284
+ var entities = ids
1285
+ .map(function (id) { return table.byId(id); })
1286
+ .filter(function (e) { return !isClientOnly(e, schema); })
1287
+ .toArray();
1288
+ if (entities.length > 0) {
1289
+ result[entityName] = entities;
1290
+ }
1291
+ });
1292
+ return result;
1293
+ }
1294
+ exports.makeCumulativePatch = makeCumulativePatch;
1295
+ function isClientOnly(entity, schema) {
1296
+ if (typeof schema.isClientOnly === 'function') {
1297
+ return schema.isClientOnly(entity);
1298
+ }
1299
+ return !!schema.isClientOnly;
1300
+ }
1301
+ exports.isClientOnly = isClientOnly;
1302
+ function getId(entity, schema) {
1303
+ if (typeof schema.primaryKey == 'string') {
1304
+ return entity[schema.primaryKey];
1305
+ }
1306
+ var result = [];
1307
+ (0, lodash_foreach_1.default)((0, lodash_pick_1.default)(entity, schema.primaryKey), function (value) {
1308
+ result.push(value);
1309
+ });
1310
+ return result;
1311
+ }
1312
+ exports.getId = getId;
1313
+ function isNew(entity, schema, clientIdsMap) {
1314
+ var id = getId(entity, schema);
1315
+ return !clientIdsMap.clientToServer(id);
1316
+ }
1317
+ exports.isNew = isNew;
1318
+ function hasServerFields(entity, schema, clientIdsMap, tables) {
1319
+ var fullEntity = (0, tslib_1.__assign)((0, tslib_1.__assign)({}, tables[schema.tableName].byId(entity.id) || {}), entity);
1320
+ if (isClientOnly(fullEntity, schema)) {
1321
+ return false;
1322
+ }
1323
+ return (0, utils_1.objectKeys)(entity).some(function (fieldName) {
1324
+ var fieldSchema = schema.fields[fieldName];
1325
+ return !fieldSchema || !(fieldSchema.isClientOnly || fieldSchema.isReadOnly || (fieldSchema.isGenerated && !isNew(entity, schema, clientIdsMap)));
1326
+ });
1327
+ }
1328
+ exports.hasServerFields = hasServerFields;
1329
+ function getParentEntities(patch, tables) {
1330
+ var dependenciesPatch = {};
1331
+ (0, utils_1.objectKeys)(patch).forEach(function (key) {
1332
+ var table = tables[key];
1333
+ var tableSchema = table.schema;
1334
+ var fields = (0, lodash_filter_1.default)((0, lodash_map_1.default)(tableSchema.fields, function (field, name) { return ((0, tslib_1.__assign)((0, tslib_1.__assign)({}, field), { name: name })); }), function (field) { return field.fk && field.fk.relationType == types_1.DbRelationType.Aggregation; });
1335
+ var tablePatch = patch[key];
1336
+ fields.forEach(function (field) {
1337
+ var tableName = field.fk.tableName, name = field.name;
1338
+ tablePatch.forEach(function (entity) {
1339
+ var actualTableName = (typeof tableName == 'function' ? tableName(entity) : tableName);
1340
+ var dbEntity = table.byId(table.getId(entity));
1341
+ var parentEntity = tables[actualTableName].byId(dbEntity[name]);
1342
+ var idFields = (0, lodash_pick_1.default)(parentEntity, tables[actualTableName].schema.primaryKey);
1343
+ if (parentEntity) {
1344
+ dependenciesPatch[actualTableName] = dependenciesPatch[actualTableName] || [];
1345
+ dependenciesPatch[actualTableName].push(idFields);
1346
+ }
1347
+ });
1348
+ });
1349
+ });
1350
+ return dependenciesPatch;
1351
+ }
1352
+ exports.getParentEntities = getParentEntities;
1353
+ function getEntityParentDependencies(entity, entityName, tables) {
1354
+ var _a;
1355
+ var patch = (_a = {}, _a[entityName] = [entity], _a);
1356
+ var resultPatches = [];
1357
+ while (true) {
1358
+ var parents = getParentEntities(patch, tables);
1359
+ if (isPatchBlank(parents)) {
1360
+ break;
1361
+ }
1362
+ resultPatches.push(parents);
1363
+ patch = parents;
1364
+ }
1365
+ var result = unionPatches((0, tslib_1.__spreadArray)([patch], resultPatches, true));
1366
+ result = mergeEntityPatches(tables, result);
1367
+ return result;
1368
+ }
1369
+ exports.getEntityParentDependencies = getEntityParentDependencies;
1348
1370
 
1349
1371
 
1350
1372
  /***/ }),
@@ -1357,27 +1379,27 @@ exports.getEntityParentDependencies = getEntityParentDependencies;
1357
1379
  /***/ (function(module, exports, __webpack_require__) {
1358
1380
 
1359
1381
  "use strict";
1360
-
1361
- Object.defineProperty(exports, "__esModule", { value: true });
1362
- exports.useDbView = exports.useDbRef = exports.DbContext = void 0;
1363
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1364
- var react_1 = __webpack_require__(/*! react */ "react");
1365
- exports.DbContext = react_1.createContext(null);
1366
- function useDbRef() {
1367
- return react_1.useContext(exports.DbContext);
1368
- }
1369
- exports.useDbRef = useDbRef;
1370
- function useDbView(fn, params, options) {
1371
- var dbRef = useDbRef();
1372
- var _a = react_1.useState(), state = _a[0], setState = _a[1];
1373
- var subscription = react_1.useMemo(function () { return dbRef.subscribe(tslib_1.__assign({ compute: fn }, options), params, setState); }, []);
1374
- subscription.update(params);
1375
- react_1.useEffect(function () {
1376
- return function () { return subscription.unsubscribe(); };
1377
- }, []);
1378
- return subscription.currentValue;
1379
- }
1380
- exports.useDbView = useDbView;
1382
+
1383
+ Object.defineProperty(exports, "__esModule", { value: true });
1384
+ exports.useDbView = exports.useDbRef = exports.DbContext = void 0;
1385
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1386
+ var react_1 = __webpack_require__(/*! react */ "react");
1387
+ exports.DbContext = (0, react_1.createContext)(null);
1388
+ function useDbRef() {
1389
+ return (0, react_1.useContext)(exports.DbContext);
1390
+ }
1391
+ exports.useDbRef = useDbRef;
1392
+ function useDbView(fn, params, options) {
1393
+ var dbRef = useDbRef();
1394
+ var _a = (0, react_1.useState)(), state = _a[0], setState = _a[1];
1395
+ var subscription = (0, react_1.useMemo)(function () { return dbRef.subscribe((0, tslib_1.__assign)({ compute: fn }, options), params, setState); }, []);
1396
+ subscription.update(params);
1397
+ (0, react_1.useEffect)(function () {
1398
+ return function () { return subscription.unsubscribe(); };
1399
+ }, []);
1400
+ return subscription.currentValue;
1401
+ }
1402
+ exports.useDbView = useDbView;
1381
1403
 
1382
1404
 
1383
1405
  /***/ }),
@@ -1390,190 +1412,190 @@ exports.useDbView = useDbView;
1390
1412
  /***/ (function(module, exports, __webpack_require__) {
1391
1413
 
1392
1414
  "use strict";
1393
-
1394
- Object.defineProperty(exports, "__esModule", { value: true });
1395
- exports.TempIdMap = exports.isTempId = exports.getTempId = void 0;
1396
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1397
- var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
1398
- var lastTempId = -1;
1399
- function getTempId() {
1400
- return --lastTempId;
1401
- }
1402
- exports.getTempId = getTempId;
1403
- function isTempId(val) {
1404
- return typeof val === 'number' && val < 0;
1405
- }
1406
- exports.isTempId = isTempId;
1407
- var TempIdMap = /** @class */ (function () {
1408
- function TempIdMap(db) {
1409
- var _this = this;
1410
- this.db = db;
1411
- this.serverToClientIds = new Map();
1412
- this.clientToServerIds = new Map();
1413
- this.clientToServer = function (id) { return _this.clientToServerIds.get(id); };
1414
- this.serverToClient = function (tableName, id) { return _this.getServerToClientMap(tableName).get(id); };
1415
- this.clientToServerRequest = function (request) {
1416
- request = tslib_1.__assign({}, request);
1417
- if (request.filter) {
1418
- request.filter = _this.clientToServerDataFilter(request.filter);
1419
- }
1420
- return request;
1421
- };
1422
- this.clientToServerDataFilter = function (filter) {
1423
- filter = tslib_1.__assign({}, filter);
1424
- var keys = Object.keys(filter);
1425
- // I hope that we can rely that there won't be any negative numbers, which are not IDs, in queries.
1426
- // We need to invent better heuristics or a schema otherwise.
1427
- var clientToServer = function (id) {
1428
- var found = _this.clientToServer(id);
1429
- if (found) {
1430
- return found;
1431
- }
1432
- else {
1433
- return id;
1434
- }
1435
- };
1436
- for (var n = 0; n < keys.length; n++) {
1437
- var key = keys[n];
1438
- var condition = filter[key];
1439
- if (condition != null && typeof condition === "object") {
1440
- condition = tslib_1.__assign({}, condition);
1441
- if ('in' in condition && Array.isArray(condition.in) && condition.in.length) {
1442
- condition.in = condition.in.map(clientToServer);
1443
- }
1444
- }
1445
- else {
1446
- condition = clientToServer(condition);
1447
- }
1448
- filter[key] = condition;
1449
- }
1450
- return filter;
1451
- };
1452
- }
1453
- TempIdMap.prototype.copyPatch = function (patch) {
1454
- var newPatch = tslib_1.__assign({}, patch);
1455
- utils_1.objectKeys(patch).forEach(function (tableName) {
1456
- var tablePatch = patch[tableName].map(function (entityPatch) { return (tslib_1.__assign({}, entityPatch)); });
1457
- newPatch[tableName] = tablePatch;
1458
- });
1459
- return newPatch;
1460
- };
1461
- // Iterate thru every field in every patch for every table, matching certain field criteria. The patch is mutated!
1462
- TempIdMap.prototype.mapFields = function (patch, filter, callback) {
1463
- var _this = this;
1464
- utils_1.objectKeys(patch).forEach(function (tableName) {
1465
- var schema = _this.db.tables[tableName].schema;
1466
- var fields = utils_1.objectKeys(schema.fields || [])
1467
- .map(function (fieldName) {
1468
- var fieldSchema = schema.fields[fieldName];
1469
- if (filter(fieldSchema, fieldName)) {
1470
- return { name: fieldName, schema: fieldSchema };
1471
- }
1472
- })
1473
- .filter(function (f) { return !!f; });
1474
- if (!fields.length) {
1475
- return;
1476
- }
1477
- patch[tableName].forEach(function (entityPatch) {
1478
- for (var n = 0; n < fields.length; n++) {
1479
- var field = fields[n];
1480
- var fieldValue = entityPatch[field.name];
1481
- callback(field.name, field.schema, fieldValue, entityPatch, tableName);
1482
- }
1483
- });
1484
- });
1485
- };
1486
- TempIdMap.prototype.getServerToClientMap = function (tableName) {
1487
- var existing = this.serverToClientIds.get(tableName);
1488
- if (existing) {
1489
- return existing;
1490
- }
1491
- else {
1492
- var newMap = new Map();
1493
- this.serverToClientIds.set(tableName, newMap);
1494
- return newMap;
1495
- }
1496
- };
1497
- TempIdMap.prototype.serverToClientPatch = function (patch) {
1498
- var _this = this;
1499
- patch = this.copyPatch(patch);
1500
- // We map PK in a separate pass, as we need to remap all PKs before re-mapping FKs
1501
- this.mapFields(patch, function (f) { return f.isGenerated; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1502
- var clientId = _this.getServerToClientMap(tableName).get(fieldValue);
1503
- if (!clientId) {
1504
- clientId = getTempId();
1505
- _this.clientToServerIds.set(clientId, fieldValue);
1506
- _this.getServerToClientMap(tableName).set(fieldValue, clientId);
1507
- }
1508
- entityPatch[fieldName] = clientId;
1509
- });
1510
- this.mapFields(patch, function (f) { return !!(f.fk || (f.default != null) || f.toClient); }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1511
- var isUndefined = typeof (fieldValue) === 'undefined';
1512
- if (fieldSchema.default != null && fieldValue == null) {
1513
- fieldValue = fieldSchema.default;
1514
- isUndefined = false;
1515
- }
1516
- if (fieldSchema.fk && fieldValue != null) {
1517
- var fkTableName = typeof fieldSchema.fk.tableName === 'function' ? fieldSchema.fk.tableName(entityPatch) : fieldSchema.fk.tableName;
1518
- var clientId = _this.getServerToClientMap(fkTableName).get(fieldValue);
1519
- if (!clientId) {
1520
- clientId = getTempId();
1521
- _this.clientToServerIds.set(clientId, fieldValue);
1522
- _this.getServerToClientMap(fkTableName).set(fieldValue, clientId);
1523
- }
1524
- fieldValue = clientId;
1525
- }
1526
- if (!isUndefined && fieldSchema.toClient) {
1527
- fieldValue = fieldSchema.toClient(fieldValue);
1528
- }
1529
- if (!isUndefined) {
1530
- entityPatch[fieldName] = fieldValue;
1531
- }
1532
- });
1533
- return patch;
1534
- };
1535
- TempIdMap.prototype.clientToServerPatch = function (patch) {
1536
- var _this = this;
1537
- patch = this.copyPatch(patch);
1538
- this.mapFields(patch, function (f) { return f.isGenerated || !!f.fk; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1539
- if (fieldValue != null) {
1540
- var existingId = _this.clientToServerIds.get(fieldValue);
1541
- if (existingId) {
1542
- entityPatch[fieldName] = existingId;
1543
- }
1544
- }
1545
- });
1546
- this.mapFields(patch, function (f) { return !(f.isClientOnly || f.isReadOnly) && !!f.toServer; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1547
- entityPatch[fieldName] = fieldSchema.toServer(entityPatch[fieldName]);
1548
- });
1549
- this.mapFields(patch, function (meta) { return meta.isClientOnly || meta.isReadOnly; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1550
- delete entityPatch[fieldName];
1551
- });
1552
- return patch;
1553
- };
1554
- TempIdMap.prototype.appendServerMapping = function (response) {
1555
- var _this = this;
1556
- utils_1.objectKeys(response.submit).forEach(function (tableName) {
1557
- if (_this.db.tables[tableName]) {
1558
- var tablePatch = response.submit[tableName];
1559
- if (tablePatch) {
1560
- var serverToClientIds_1 = _this.getServerToClientMap(tableName);
1561
- var table_1 = _this.db.tables[tableName];
1562
- tablePatch.forEach(function (patch) {
1563
- if (isTempId(patch.id)) {
1564
- var clientId = patch.id;
1565
- var serverId = table_1.getId(patch.payload);
1566
- serverToClientIds_1.set(serverId, clientId);
1567
- _this.clientToServerIds.set(clientId, serverId);
1568
- }
1569
- });
1570
- }
1571
- }
1572
- });
1573
- };
1574
- return TempIdMap;
1575
- }());
1576
- exports.TempIdMap = TempIdMap;
1415
+
1416
+ Object.defineProperty(exports, "__esModule", { value: true });
1417
+ exports.TempIdMap = exports.isTempId = exports.getTempId = void 0;
1418
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1419
+ var utils_1 = __webpack_require__(/*! ./utils */ "./src/utils.ts");
1420
+ var lastTempId = -1;
1421
+ function getTempId() {
1422
+ return --lastTempId;
1423
+ }
1424
+ exports.getTempId = getTempId;
1425
+ function isTempId(val) {
1426
+ return typeof val === 'number' && val < 0;
1427
+ }
1428
+ exports.isTempId = isTempId;
1429
+ var TempIdMap = /** @class */ (function () {
1430
+ function TempIdMap(db) {
1431
+ var _this = this;
1432
+ this.db = db;
1433
+ this.serverToClientIds = new Map();
1434
+ this.clientToServerIds = new Map();
1435
+ this.clientToServer = function (id) { return _this.clientToServerIds.get(id); };
1436
+ this.serverToClient = function (tableName, id) { return _this.getServerToClientMap(tableName).get(id); };
1437
+ this.clientToServerRequest = function (request) {
1438
+ request = (0, tslib_1.__assign)({}, request);
1439
+ if (request.filter) {
1440
+ request.filter = _this.clientToServerDataFilter(request.filter);
1441
+ }
1442
+ return request;
1443
+ };
1444
+ this.clientToServerDataFilter = function (filter) {
1445
+ filter = (0, tslib_1.__assign)({}, filter);
1446
+ var keys = Object.keys(filter);
1447
+ // I hope that we can rely that there won't be any negative numbers, which are not IDs, in queries.
1448
+ // We need to invent better heuristics or a schema otherwise.
1449
+ var clientToServer = function (id) {
1450
+ var found = _this.clientToServer(id);
1451
+ if (found) {
1452
+ return found;
1453
+ }
1454
+ else {
1455
+ return id;
1456
+ }
1457
+ };
1458
+ for (var n = 0; n < keys.length; n++) {
1459
+ var key = keys[n];
1460
+ var condition = filter[key];
1461
+ if (condition != null && typeof condition === "object") {
1462
+ condition = (0, tslib_1.__assign)({}, condition);
1463
+ if ('in' in condition && Array.isArray(condition.in) && condition.in.length) {
1464
+ condition.in = condition.in.map(clientToServer);
1465
+ }
1466
+ }
1467
+ else {
1468
+ condition = clientToServer(condition);
1469
+ }
1470
+ filter[key] = condition;
1471
+ }
1472
+ return filter;
1473
+ };
1474
+ }
1475
+ TempIdMap.prototype.copyPatch = function (patch) {
1476
+ var newPatch = (0, tslib_1.__assign)({}, patch);
1477
+ (0, utils_1.objectKeys)(patch).forEach(function (tableName) {
1478
+ var tablePatch = patch[tableName].map(function (entityPatch) { return ((0, tslib_1.__assign)({}, entityPatch)); });
1479
+ newPatch[tableName] = tablePatch;
1480
+ });
1481
+ return newPatch;
1482
+ };
1483
+ // Iterate thru every field in every patch for every table, matching certain field criteria. The patch is mutated!
1484
+ TempIdMap.prototype.mapFields = function (patch, filter, callback) {
1485
+ var _this = this;
1486
+ (0, utils_1.objectKeys)(patch).forEach(function (tableName) {
1487
+ var schema = _this.db.tables[tableName].schema;
1488
+ var fields = (0, utils_1.objectKeys)(schema.fields || [])
1489
+ .map(function (fieldName) {
1490
+ var fieldSchema = schema.fields[fieldName];
1491
+ if (filter(fieldSchema, fieldName)) {
1492
+ return { name: fieldName, schema: fieldSchema };
1493
+ }
1494
+ })
1495
+ .filter(function (f) { return !!f; });
1496
+ if (!fields.length) {
1497
+ return;
1498
+ }
1499
+ patch[tableName].forEach(function (entityPatch) {
1500
+ for (var n = 0; n < fields.length; n++) {
1501
+ var field = fields[n];
1502
+ var fieldValue = entityPatch[field.name];
1503
+ callback(field.name, field.schema, fieldValue, entityPatch, tableName);
1504
+ }
1505
+ });
1506
+ });
1507
+ };
1508
+ TempIdMap.prototype.getServerToClientMap = function (tableName) {
1509
+ var existing = this.serverToClientIds.get(tableName);
1510
+ if (existing) {
1511
+ return existing;
1512
+ }
1513
+ else {
1514
+ var newMap = new Map();
1515
+ this.serverToClientIds.set(tableName, newMap);
1516
+ return newMap;
1517
+ }
1518
+ };
1519
+ TempIdMap.prototype.serverToClientPatch = function (patch) {
1520
+ var _this = this;
1521
+ patch = this.copyPatch(patch);
1522
+ // We map PK in a separate pass, as we need to remap all PKs before re-mapping FKs
1523
+ this.mapFields(patch, function (f) { return f.isGenerated; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1524
+ var clientId = _this.getServerToClientMap(tableName).get(fieldValue);
1525
+ if (!clientId) {
1526
+ clientId = getTempId();
1527
+ _this.clientToServerIds.set(clientId, fieldValue);
1528
+ _this.getServerToClientMap(tableName).set(fieldValue, clientId);
1529
+ }
1530
+ entityPatch[fieldName] = clientId;
1531
+ });
1532
+ this.mapFields(patch, function (f) { return !!(f.fk || (f.default != null) || f.toClient); }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1533
+ var isUndefined = typeof (fieldValue) === 'undefined';
1534
+ if (fieldSchema.default != null && fieldValue == null) {
1535
+ fieldValue = fieldSchema.default;
1536
+ isUndefined = false;
1537
+ }
1538
+ if (fieldSchema.fk && fieldValue != null) {
1539
+ var fkTableName = typeof fieldSchema.fk.tableName === 'function' ? fieldSchema.fk.tableName(entityPatch) : fieldSchema.fk.tableName;
1540
+ var clientId = _this.getServerToClientMap(fkTableName).get(fieldValue);
1541
+ if (!clientId) {
1542
+ clientId = getTempId();
1543
+ _this.clientToServerIds.set(clientId, fieldValue);
1544
+ _this.getServerToClientMap(fkTableName).set(fieldValue, clientId);
1545
+ }
1546
+ fieldValue = clientId;
1547
+ }
1548
+ if (!isUndefined && fieldSchema.toClient) {
1549
+ fieldValue = fieldSchema.toClient(fieldValue);
1550
+ }
1551
+ if (!isUndefined) {
1552
+ entityPatch[fieldName] = fieldValue;
1553
+ }
1554
+ });
1555
+ return patch;
1556
+ };
1557
+ TempIdMap.prototype.clientToServerPatch = function (patch) {
1558
+ var _this = this;
1559
+ patch = this.copyPatch(patch);
1560
+ this.mapFields(patch, function (f) { return f.isGenerated || !!f.fk; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1561
+ if (fieldValue != null) {
1562
+ var existingId = _this.clientToServerIds.get(fieldValue);
1563
+ if (existingId) {
1564
+ entityPatch[fieldName] = existingId;
1565
+ }
1566
+ }
1567
+ });
1568
+ this.mapFields(patch, function (f) { return !(f.isClientOnly || f.isReadOnly) && !!f.toServer; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1569
+ entityPatch[fieldName] = fieldSchema.toServer(entityPatch[fieldName]);
1570
+ });
1571
+ this.mapFields(patch, function (meta) { return meta.isClientOnly || meta.isReadOnly; }, function (fieldName, fieldSchema, fieldValue, entityPatch, tableName) {
1572
+ delete entityPatch[fieldName];
1573
+ });
1574
+ return patch;
1575
+ };
1576
+ TempIdMap.prototype.appendServerMapping = function (response) {
1577
+ var _this = this;
1578
+ (0, utils_1.objectKeys)(response.submit).forEach(function (tableName) {
1579
+ if (_this.db.tables[tableName]) {
1580
+ var tablePatch = response.submit[tableName];
1581
+ if (tablePatch) {
1582
+ var serverToClientIds_1 = _this.getServerToClientMap(tableName);
1583
+ var table_1 = _this.db.tables[tableName];
1584
+ tablePatch.forEach(function (patch) {
1585
+ if (isTempId(patch.id)) {
1586
+ var clientId = patch.id;
1587
+ var serverId = table_1.getId(patch.payload);
1588
+ serverToClientIds_1.set(serverId, clientId);
1589
+ _this.clientToServerIds.set(clientId, serverId);
1590
+ }
1591
+ });
1592
+ }
1593
+ }
1594
+ });
1595
+ };
1596
+ return TempIdMap;
1597
+ }());
1598
+ exports.TempIdMap = TempIdMap;
1577
1599
 
1578
1600
 
1579
1601
  /***/ }),
@@ -1586,14 +1608,14 @@ exports.TempIdMap = TempIdMap;
1586
1608
  /***/ (function(module, exports, __webpack_require__) {
1587
1609
 
1588
1610
  "use strict";
1589
-
1590
- Object.defineProperty(exports, "__esModule", { value: true });
1591
- exports.DbRelationType = void 0;
1592
- var DbRelationType;
1593
- (function (DbRelationType) {
1594
- DbRelationType[DbRelationType["Aggregation"] = 0] = "Aggregation";
1595
- DbRelationType[DbRelationType["Association"] = 1] = "Association";
1596
- })(DbRelationType = exports.DbRelationType || (exports.DbRelationType = {}));
1611
+
1612
+ Object.defineProperty(exports, "__esModule", { value: true });
1613
+ exports.DbRelationType = void 0;
1614
+ var DbRelationType;
1615
+ (function (DbRelationType) {
1616
+ DbRelationType[DbRelationType["Aggregation"] = 0] = "Aggregation";
1617
+ DbRelationType[DbRelationType["Association"] = 1] = "Association";
1618
+ })(DbRelationType = exports.DbRelationType || (exports.DbRelationType = {}));
1597
1619
 
1598
1620
 
1599
1621
  /***/ }),
@@ -1606,46 +1628,46 @@ var DbRelationType;
1606
1628
  /***/ (function(module, exports, __webpack_require__) {
1607
1629
 
1608
1630
  "use strict";
1609
-
1610
- Object.defineProperty(exports, "__esModule", { value: true });
1611
- exports.difference = exports.defaultCompareViewDependencies = exports.objectKeys = void 0;
1612
- var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1613
- var shallowequal_1 = tslib_1.__importDefault(__webpack_require__(/*! shallowequal */ "shallowequal"));
1614
- var lodash_zip_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.zip */ "lodash.zip"));
1615
- var lodash_transform_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.transform */ "lodash.transform"));
1616
- var lodash_isequal_1 = tslib_1.__importDefault(__webpack_require__(/*! lodash.isequal */ "lodash.isequal"));
1617
- // TBD: New typescript would contain better typing for this. Remove this hack after update.
1618
- exports.objectKeys = Object.keys;
1619
- function defaultCompareViewDependencies(prev, next) {
1620
- if (Array.isArray(prev) && Array.isArray(next)) {
1621
- if (prev.length === next.length) {
1622
- return lodash_zip_1.default(prev, next).every(function (_a) {
1623
- var p = _a[0], n = _a[1];
1624
- return shallowequal_1.default(p, n);
1625
- });
1626
- }
1627
- return false;
1628
- }
1629
- return shallowequal_1.default(prev, next);
1630
- }
1631
- exports.defaultCompareViewDependencies = defaultCompareViewDependencies;
1632
- /**
1633
- * Deep diff between two object, using lodash
1634
- * @param {Object} object Object compared
1635
- * @param {Object} base Object to compare with
1636
- * @return {Object} Return a new object who represent the diff
1637
- */
1638
- function difference(object, base) {
1639
- function changes(object, base) {
1640
- return lodash_transform_1.default(object, function (result, value, key) {
1641
- if (!lodash_isequal_1.default(value, base[key])) {
1642
- result[key] = (typeof value === "object" && typeof base[key] === "object") ? changes(value, base[key]) : value;
1643
- }
1644
- });
1645
- }
1646
- return changes(object, base);
1647
- }
1648
- exports.difference = difference;
1631
+
1632
+ Object.defineProperty(exports, "__esModule", { value: true });
1633
+ exports.difference = exports.defaultCompareViewDependencies = exports.objectKeys = void 0;
1634
+ var tslib_1 = __webpack_require__(/*! tslib */ "../node_modules/tslib/tslib.es6.js");
1635
+ var shallowequal_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! shallowequal */ "shallowequal"));
1636
+ var lodash_zip_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.zip */ "lodash.zip"));
1637
+ var lodash_transform_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.transform */ "lodash.transform"));
1638
+ var lodash_isequal_1 = (0, tslib_1.__importDefault)(__webpack_require__(/*! lodash.isequal */ "lodash.isequal"));
1639
+ // TBD: New typescript would contain better typing for this. Remove this hack after update.
1640
+ exports.objectKeys = Object.keys;
1641
+ function defaultCompareViewDependencies(prev, next) {
1642
+ if (Array.isArray(prev) && Array.isArray(next)) {
1643
+ if (prev.length === next.length) {
1644
+ return (0, lodash_zip_1.default)(prev, next).every(function (_a) {
1645
+ var p = _a[0], n = _a[1];
1646
+ return (0, shallowequal_1.default)(p, n);
1647
+ });
1648
+ }
1649
+ return false;
1650
+ }
1651
+ return (0, shallowequal_1.default)(prev, next);
1652
+ }
1653
+ exports.defaultCompareViewDependencies = defaultCompareViewDependencies;
1654
+ /**
1655
+ * Deep diff between two object, using lodash
1656
+ * @param {Object} object Object compared
1657
+ * @param {Object} base Object to compare with
1658
+ * @return {Object} Return a new object who represent the diff
1659
+ */
1660
+ function difference(object, base) {
1661
+ function changes(object, base) {
1662
+ return (0, lodash_transform_1.default)(object, function (result, value, key) {
1663
+ if (!(0, lodash_isequal_1.default)(value, base[key])) {
1664
+ result[key] = (typeof value === "object" && typeof base[key] === "object") ? changes(value, base[key]) : value;
1665
+ }
1666
+ });
1667
+ }
1668
+ return changes(object, base);
1669
+ }
1670
+ exports.difference = difference;
1649
1671
 
1650
1672
 
1651
1673
  /***/ }),
@@ -1657,19 +1679,19 @@ exports.difference = difference;
1657
1679
  /*! no static exports found */
1658
1680
  /***/ (function(module, exports, __webpack_require__) {
1659
1681
 
1660
- module.exports = __webpack_require__(/*! C:\work\uui\uui-db\index.tsx */"./index.tsx");
1682
+ module.exports = __webpack_require__(/*! /Users/Aliaksei_Manetau/WebstormProjects/UUI/uui-db/index.tsx */"./index.tsx");
1661
1683
 
1662
1684
 
1663
1685
  /***/ }),
1664
1686
 
1665
- /***/ "@epam/uui":
1666
- /*!****************************!*\
1667
- !*** external "@epam/uui" ***!
1668
- \****************************/
1687
+ /***/ "@epam/uui-core":
1688
+ /*!*********************************!*\
1689
+ !*** external "@epam/uui-core" ***!
1690
+ \*********************************/
1669
1691
  /*! no static exports found */
1670
1692
  /***/ (function(module, exports) {
1671
1693
 
1672
- module.exports = require("@epam/uui");
1694
+ module.exports = require("@epam/uui-core");
1673
1695
 
1674
1696
  /***/ }),
1675
1697