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