@sv443-network/coreutils 2.0.3 → 3.0.0
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/CHANGELOG.md +32 -0
- package/README.md +4 -3
- package/dist/CoreUtils.cjs +168 -103
- package/dist/CoreUtils.min.cjs +5 -3
- package/dist/CoreUtils.min.mjs +5 -3
- package/dist/CoreUtils.min.umd.js +5 -3
- package/dist/CoreUtils.mjs +168 -103
- package/dist/CoreUtils.umd.js +174 -107
- package/dist/lib/DataStore.d.ts +21 -7
- package/dist/lib/DataStoreEngine.d.ts +8 -8
- package/dist/lib/DataStoreSerializer.d.ts +2 -0
- package/dist/lib/Errors.d.ts +15 -3
- package/dist/lib/NanoEmitter.d.ts +6 -5
- package/dist/lib/math.d.ts +1 -1
- package/dist/lib/misc.d.ts +6 -0
- package/dist/lib/{TestDataStore.d.ts → test/DirectAccessDataStore.d.ts} +4 -3
- package/dist/lib/test/softExpect.d.ts +11 -0
- package/dist/lib/types.d.ts +7 -0
- package/package.json +1 -1
package/dist/CoreUtils.umd.js
CHANGED
|
@@ -99,6 +99,7 @@ var lib_exports = {};
|
|
|
99
99
|
__export(lib_exports, {
|
|
100
100
|
BrowserStorageEngine: () => BrowserStorageEngine,
|
|
101
101
|
ChecksumMismatchError: () => ChecksumMismatchError,
|
|
102
|
+
CustomError: () => CustomError,
|
|
102
103
|
DataStore: () => DataStore,
|
|
103
104
|
DataStoreEngine: () => DataStoreEngine,
|
|
104
105
|
DataStoreSerializer: () => DataStoreSerializer,
|
|
@@ -107,6 +108,8 @@ __export(lib_exports, {
|
|
|
107
108
|
FileStorageEngine: () => FileStorageEngine,
|
|
108
109
|
MigrationError: () => MigrationError,
|
|
109
110
|
NanoEmitter: () => NanoEmitter,
|
|
111
|
+
NetworkError: () => NetworkError,
|
|
112
|
+
ScriptContextError: () => ScriptContextError,
|
|
110
113
|
ValidationError: () => ValidationError,
|
|
111
114
|
abtoa: () => abtoa,
|
|
112
115
|
atoab: () => atoab,
|
|
@@ -126,6 +129,7 @@ __export(lib_exports, {
|
|
|
126
129
|
digitCount: () => digitCount,
|
|
127
130
|
fetchAdvanced: () => fetchAdvanced,
|
|
128
131
|
formatNumber: () => formatNumber,
|
|
132
|
+
getCallStack: () => getCallStack,
|
|
129
133
|
getListLength: () => getListLength,
|
|
130
134
|
hexToRgb: () => hexToRgb,
|
|
131
135
|
insertValues: () => insertValues,
|
|
@@ -242,7 +246,7 @@ function roundFixed(num, fractionDigits) {
|
|
|
242
246
|
const scale = __pow(10, fractionDigits);
|
|
243
247
|
return Math.round(num * scale) / scale;
|
|
244
248
|
}
|
|
245
|
-
function valsWithin(a, b, dec =
|
|
249
|
+
function valsWithin(a, b, dec = 1, withinRange = 0.5) {
|
|
246
250
|
return Math.abs(roundFixed(a, dec) - roundFixed(b, dec)) <= withinRange;
|
|
247
251
|
}
|
|
248
252
|
|
|
@@ -400,6 +404,52 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
|
|
|
400
404
|
return arr.map((v) => caseArr[randRange(0, caseArr.length - 1, enhancedEntropy)] === 1 ? v.toUpperCase() : v).join("");
|
|
401
405
|
}
|
|
402
406
|
|
|
407
|
+
// lib/Errors.ts
|
|
408
|
+
var DatedError = class extends Error {
|
|
409
|
+
constructor(message, options) {
|
|
410
|
+
super(message, options);
|
|
411
|
+
__publicField(this, "date");
|
|
412
|
+
this.name = this.constructor.name;
|
|
413
|
+
this.date = /* @__PURE__ */ new Date();
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
var ChecksumMismatchError = class extends DatedError {
|
|
417
|
+
constructor(message, options) {
|
|
418
|
+
super(message, options);
|
|
419
|
+
this.name = "ChecksumMismatchError";
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
var CustomError = class extends DatedError {
|
|
423
|
+
constructor(name, message, options) {
|
|
424
|
+
super(message, options);
|
|
425
|
+
this.name = name;
|
|
426
|
+
}
|
|
427
|
+
};
|
|
428
|
+
var MigrationError = class extends DatedError {
|
|
429
|
+
constructor(message, options) {
|
|
430
|
+
super(message, options);
|
|
431
|
+
this.name = "MigrationError";
|
|
432
|
+
}
|
|
433
|
+
};
|
|
434
|
+
var ValidationError = class extends DatedError {
|
|
435
|
+
constructor(message, options) {
|
|
436
|
+
super(message, options);
|
|
437
|
+
this.name = "ValidationError";
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
var ScriptContextError = class extends DatedError {
|
|
441
|
+
constructor(message, options) {
|
|
442
|
+
super(message, options);
|
|
443
|
+
this.name = "ScriptContextError";
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
var NetworkError = class extends DatedError {
|
|
447
|
+
constructor(message, options) {
|
|
448
|
+
super(message, options);
|
|
449
|
+
this.name = "NetworkError";
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
|
|
403
453
|
// lib/misc.ts
|
|
404
454
|
function consumeGen(valGen) {
|
|
405
455
|
return __async(this, null, function* () {
|
|
@@ -430,7 +480,7 @@ function fetchAdvanced(_0) {
|
|
|
430
480
|
return res;
|
|
431
481
|
} catch (err) {
|
|
432
482
|
typeof id !== "undefined" && clearTimeout(id);
|
|
433
|
-
throw new
|
|
483
|
+
throw new NetworkError("Error while calling fetch", { cause: err });
|
|
434
484
|
}
|
|
435
485
|
});
|
|
436
486
|
}
|
|
@@ -442,7 +492,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
|
|
|
442
492
|
const timeout = setTimeout(() => res(), time);
|
|
443
493
|
signal == null ? void 0 : signal.addEventListener("abort", () => {
|
|
444
494
|
clearTimeout(timeout);
|
|
445
|
-
rejectOnAbort ? rej(new
|
|
495
|
+
rejectOnAbort ? rej(new CustomError("AbortError", "The pause was aborted")) : res();
|
|
446
496
|
});
|
|
447
497
|
});
|
|
448
498
|
}
|
|
@@ -477,14 +527,25 @@ function scheduleExit(code = 0, timeout = 0) {
|
|
|
477
527
|
if (timeout < 0)
|
|
478
528
|
throw new TypeError("Timeout must be a non-negative number");
|
|
479
529
|
let exit;
|
|
480
|
-
if (typeof process !== "undefined" && "exit" in process)
|
|
530
|
+
if (typeof process !== "undefined" && "exit" in process && typeof process.exit === "function")
|
|
481
531
|
exit = () => process.exit(code);
|
|
482
|
-
else if (typeof Deno !== "undefined" && "exit" in Deno)
|
|
532
|
+
else if (typeof Deno !== "undefined" && "exit" in Deno && typeof Deno.exit === "function")
|
|
483
533
|
exit = () => Deno.exit(code);
|
|
484
534
|
else
|
|
485
|
-
throw new
|
|
535
|
+
throw new ScriptContextError("Cannot exit the process, no exit method available");
|
|
486
536
|
setTimeout(exit, timeout);
|
|
487
537
|
}
|
|
538
|
+
function getCallStack(asArray, lines = Infinity) {
|
|
539
|
+
var _a;
|
|
540
|
+
if (typeof lines !== "number" || isNaN(lines) || lines < 0)
|
|
541
|
+
throw new TypeError("lines parameter must be a non-negative number");
|
|
542
|
+
try {
|
|
543
|
+
throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)");
|
|
544
|
+
} catch (err) {
|
|
545
|
+
const stack = ((_a = err.stack) != null ? _a : "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
|
|
546
|
+
return asArray !== false ? stack : stack.join("\n");
|
|
547
|
+
}
|
|
548
|
+
}
|
|
488
549
|
|
|
489
550
|
// lib/text.ts
|
|
490
551
|
function autoPlural(term, num, pluralType = "auto") {
|
|
@@ -554,16 +615,18 @@ function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
|
|
|
554
615
|
return arr.join(separators) + lastItm;
|
|
555
616
|
}
|
|
556
617
|
function secsToTimeStr(seconds) {
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
const
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
618
|
+
const isNegative = seconds < 0;
|
|
619
|
+
const s = Math.abs(seconds);
|
|
620
|
+
if (isNaN(s) || !isFinite(s))
|
|
621
|
+
throw new TypeError("The seconds argument must be a valid number");
|
|
622
|
+
const hrs = Math.floor(s / 3600);
|
|
623
|
+
const mins = Math.floor(s % 3600 / 60);
|
|
624
|
+
const secs = Math.floor(s % 60);
|
|
625
|
+
return (isNegative ? "-" : "") + [
|
|
626
|
+
hrs ? hrs + ":" : "",
|
|
627
|
+
String(mins).padStart(mins > 0 || hrs > 0 ? 2 : 1, "0"),
|
|
565
628
|
":",
|
|
566
|
-
String(secs).padStart(secs > 0 ||
|
|
629
|
+
String(secs).padStart(secs > 0 || mins > 0 || hrs > 0 || seconds === 0 ? 2 : 1, "0")
|
|
567
630
|
].join("");
|
|
568
631
|
}
|
|
569
632
|
function truncStr(input, length, endStr = "...") {
|
|
@@ -573,37 +636,10 @@ function truncStr(input, length, endStr = "...") {
|
|
|
573
636
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
574
637
|
}
|
|
575
638
|
|
|
576
|
-
// lib/Errors.ts
|
|
577
|
-
var DatedError = class extends Error {
|
|
578
|
-
constructor(message, options) {
|
|
579
|
-
super(message, options);
|
|
580
|
-
__publicField(this, "date");
|
|
581
|
-
this.name = this.constructor.name;
|
|
582
|
-
this.date = /* @__PURE__ */ new Date();
|
|
583
|
-
}
|
|
584
|
-
};
|
|
585
|
-
var ChecksumMismatchError = class extends DatedError {
|
|
586
|
-
constructor(message, options) {
|
|
587
|
-
super(message, options);
|
|
588
|
-
this.name = "ChecksumMismatchError";
|
|
589
|
-
}
|
|
590
|
-
};
|
|
591
|
-
var MigrationError = class extends DatedError {
|
|
592
|
-
constructor(message, options) {
|
|
593
|
-
super(message, options);
|
|
594
|
-
this.name = "MigrationError";
|
|
595
|
-
}
|
|
596
|
-
};
|
|
597
|
-
var ValidationError = class extends DatedError {
|
|
598
|
-
constructor(message, options) {
|
|
599
|
-
super(message, options);
|
|
600
|
-
this.name = "ValidationError";
|
|
601
|
-
}
|
|
602
|
-
};
|
|
603
|
-
|
|
604
639
|
// lib/DataStore.ts
|
|
605
640
|
var dsFmtVer = 1;
|
|
606
641
|
var DataStore = class {
|
|
642
|
+
//#region constructor
|
|
607
643
|
/**
|
|
608
644
|
* Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
|
|
609
645
|
* Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
|
|
@@ -620,6 +656,7 @@ var DataStore = class {
|
|
|
620
656
|
__publicField(this, "encodeData");
|
|
621
657
|
__publicField(this, "decodeData");
|
|
622
658
|
__publicField(this, "compressionFormat", "deflate-raw");
|
|
659
|
+
__publicField(this, "memoryCache", true);
|
|
623
660
|
__publicField(this, "engine");
|
|
624
661
|
__publicField(this, "options");
|
|
625
662
|
/**
|
|
@@ -632,11 +669,12 @@ var DataStore = class {
|
|
|
632
669
|
__publicField(this, "cachedData");
|
|
633
670
|
__publicField(this, "migrations");
|
|
634
671
|
__publicField(this, "migrateIds", []);
|
|
635
|
-
var _a, _b, _c;
|
|
672
|
+
var _a, _b, _c, _d;
|
|
636
673
|
this.id = opts.id;
|
|
637
674
|
this.formatVersion = opts.formatVersion;
|
|
638
675
|
this.defaultData = opts.defaultData;
|
|
639
|
-
this.
|
|
676
|
+
this.memoryCache = Boolean((_a = opts.memoryCache) != null ? _a : true);
|
|
677
|
+
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
640
678
|
this.migrations = opts.migrations;
|
|
641
679
|
if (opts.migrateIds)
|
|
642
680
|
this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
|
|
@@ -645,7 +683,7 @@ var DataStore = class {
|
|
|
645
683
|
this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
|
|
646
684
|
this.options = opts;
|
|
647
685
|
if (typeof opts.compressionFormat === "undefined")
|
|
648
|
-
this.compressionFormat = opts.compressionFormat = (
|
|
686
|
+
this.compressionFormat = opts.compressionFormat = (_c = (_b = opts.encodeData) == null ? void 0 : _b[0]) != null ? _c : "deflate-raw";
|
|
649
687
|
if (typeof opts.compressionFormat === "string") {
|
|
650
688
|
this.encodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
|
|
651
689
|
return yield compress(data, opts.compressionFormat, "string");
|
|
@@ -656,7 +694,7 @@ var DataStore = class {
|
|
|
656
694
|
} else if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
|
|
657
695
|
this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
|
|
658
696
|
this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
|
|
659
|
-
this.compressionFormat = (
|
|
697
|
+
this.compressionFormat = (_d = opts.encodeData[0]) != null ? _d : null;
|
|
660
698
|
} else if (opts.compressionFormat === null) {
|
|
661
699
|
this.encodeData = void 0;
|
|
662
700
|
this.decodeData = void 0;
|
|
@@ -665,7 +703,7 @@ var DataStore = class {
|
|
|
665
703
|
throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");
|
|
666
704
|
this.engine.setDataStoreOptions(opts);
|
|
667
705
|
}
|
|
668
|
-
//#region
|
|
706
|
+
//#region loadData
|
|
669
707
|
/**
|
|
670
708
|
* Loads the data saved in persistent storage into the in-memory cache and also returns a copy of it.
|
|
671
709
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
@@ -673,32 +711,33 @@ var DataStore = class {
|
|
|
673
711
|
*/
|
|
674
712
|
loadData() {
|
|
675
713
|
return __async(this, null, function* () {
|
|
714
|
+
var _a;
|
|
676
715
|
try {
|
|
677
716
|
if (this.firstInit) {
|
|
678
717
|
this.firstInit = false;
|
|
679
718
|
const dsVer = Number(yield this.engine.getValue("__ds_fmt_ver", 0));
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
|
|
698
|
-
yield Promise.allSettled(promises);
|
|
719
|
+
const oldData = yield this.engine.getValue(`_uucfg-${this.id}`, null);
|
|
720
|
+
if (oldData) {
|
|
721
|
+
const oldVer = Number(yield this.engine.getValue(`_uucfgver-${this.id}`, NaN));
|
|
722
|
+
const oldEnc = yield this.engine.getValue(`_uucfgenc-${this.id}`, null);
|
|
723
|
+
const promises = [];
|
|
724
|
+
const migrateFmt = (oldKey, newKey, value) => {
|
|
725
|
+
promises.push(this.engine.setValue(newKey, value));
|
|
726
|
+
promises.push(this.engine.deleteValue(oldKey));
|
|
727
|
+
};
|
|
728
|
+
migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
|
|
729
|
+
if (!isNaN(oldVer))
|
|
730
|
+
migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
|
|
731
|
+
if (typeof oldEnc === "boolean")
|
|
732
|
+
migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? (_a = this.compressionFormat) != null ? _a : null : null);
|
|
733
|
+
else {
|
|
734
|
+
promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
|
|
735
|
+
promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
|
|
699
736
|
}
|
|
700
|
-
yield
|
|
737
|
+
yield Promise.allSettled(promises);
|
|
701
738
|
}
|
|
739
|
+
if (isNaN(dsVer) || dsVer < dsFmtVer)
|
|
740
|
+
yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
702
741
|
}
|
|
703
742
|
if (this.migrateIds.length > 0) {
|
|
704
743
|
yield this.migrateId(this.migrateIds);
|
|
@@ -708,7 +747,7 @@ var DataStore = class {
|
|
|
708
747
|
let storedFmtVer = Number(yield this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
709
748
|
if (typeof storedDataRaw !== "string") {
|
|
710
749
|
yield this.saveDefaultData();
|
|
711
|
-
return
|
|
750
|
+
return this.engine.deepCopy(this.defaultData);
|
|
712
751
|
}
|
|
713
752
|
const storedData = storedDataRaw != null ? storedDataRaw : JSON.stringify(this.defaultData);
|
|
714
753
|
const encodingFmt = String(yield this.engine.getValue(`__ds-${this.id}-enf`, null));
|
|
@@ -723,7 +762,10 @@ var DataStore = class {
|
|
|
723
762
|
parsed = yield this.runMigrations(parsed, storedFmtVer);
|
|
724
763
|
if (saveData)
|
|
725
764
|
yield this.setData(parsed);
|
|
726
|
-
|
|
765
|
+
if (this.memoryCache)
|
|
766
|
+
return this.cachedData = this.engine.deepCopy(parsed);
|
|
767
|
+
else
|
|
768
|
+
return this.engine.deepCopy(parsed);
|
|
727
769
|
} catch (err) {
|
|
728
770
|
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
729
771
|
yield this.saveDefaultData();
|
|
@@ -731,16 +773,22 @@ var DataStore = class {
|
|
|
731
773
|
}
|
|
732
774
|
});
|
|
733
775
|
}
|
|
776
|
+
//#region getData
|
|
734
777
|
/**
|
|
735
778
|
* Returns a copy of the data from the in-memory cache.
|
|
736
|
-
* Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
|
|
779
|
+
* Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
|
|
780
|
+
* ⚠️ If `memoryCache` was set to `false` in the constructor options, this method will throw an error.
|
|
737
781
|
*/
|
|
738
782
|
getData() {
|
|
783
|
+
if (!this.memoryCache)
|
|
784
|
+
throw new DatedError("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");
|
|
739
785
|
return this.engine.deepCopy(this.cachedData);
|
|
740
786
|
}
|
|
787
|
+
//#region setData
|
|
741
788
|
/** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
|
|
742
789
|
setData(data) {
|
|
743
|
-
this.
|
|
790
|
+
if (this.memoryCache)
|
|
791
|
+
this.cachedData = data;
|
|
744
792
|
return new Promise((resolve) => __async(this, null, function* () {
|
|
745
793
|
yield Promise.allSettled([
|
|
746
794
|
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(data, this.encodingEnabled())),
|
|
@@ -750,10 +798,12 @@ var DataStore = class {
|
|
|
750
798
|
resolve();
|
|
751
799
|
}));
|
|
752
800
|
}
|
|
801
|
+
//#region saveDefaultData
|
|
753
802
|
/** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
|
|
754
803
|
saveDefaultData() {
|
|
755
804
|
return __async(this, null, function* () {
|
|
756
|
-
|
|
805
|
+
if (this.memoryCache)
|
|
806
|
+
this.cachedData = this.defaultData;
|
|
757
807
|
yield Promise.allSettled([
|
|
758
808
|
this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(this.defaultData, this.encodingEnabled())),
|
|
759
809
|
this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
|
|
@@ -761,6 +811,7 @@ var DataStore = class {
|
|
|
761
811
|
]);
|
|
762
812
|
});
|
|
763
813
|
}
|
|
814
|
+
//#region deleteData
|
|
764
815
|
/**
|
|
765
816
|
* Call this method to clear all persistently stored data associated with this DataStore instance, including the storage container (if supported by the DataStoreEngine).
|
|
766
817
|
* The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
|
|
@@ -777,11 +828,12 @@ var DataStore = class {
|
|
|
777
828
|
yield (_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a);
|
|
778
829
|
});
|
|
779
830
|
}
|
|
831
|
+
//#region encodingEnabled
|
|
780
832
|
/** Returns whether encoding and decoding are enabled for this DataStore instance */
|
|
781
833
|
encodingEnabled() {
|
|
782
834
|
return Boolean(this.encodeData && this.decodeData) && this.compressionFormat !== null || Boolean(this.compressionFormat);
|
|
783
835
|
}
|
|
784
|
-
//#region
|
|
836
|
+
//#region runMigrations
|
|
785
837
|
/**
|
|
786
838
|
* Runs all necessary migration functions consecutively and saves the result to the in-memory cache and persistent storage and also returns it.
|
|
787
839
|
* This method is automatically called by {@linkcode loadData()} if the data format has changed since the last time the data was saved.
|
|
@@ -816,9 +868,13 @@ var DataStore = class {
|
|
|
816
868
|
this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
|
|
817
869
|
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
|
|
818
870
|
]);
|
|
819
|
-
|
|
871
|
+
if (this.memoryCache)
|
|
872
|
+
return this.cachedData = this.engine.deepCopy(newData);
|
|
873
|
+
else
|
|
874
|
+
return this.engine.deepCopy(newData);
|
|
820
875
|
});
|
|
821
876
|
}
|
|
877
|
+
//#region migrateId
|
|
822
878
|
/**
|
|
823
879
|
* Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
|
|
824
880
|
* If no data exist for the old ID(s), nothing will be done, but some time may still pass trying to fetch the non-existent data.
|
|
@@ -864,7 +920,7 @@ var DataStoreEngine = class {
|
|
|
864
920
|
this.dataStoreOptions = dataStoreOptions;
|
|
865
921
|
}
|
|
866
922
|
//#region serialization api
|
|
867
|
-
/** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is set to
|
|
923
|
+
/** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is not set to false and the `encodeData` and `decodeData` options are set */
|
|
868
924
|
serializeData(data, useEncoding) {
|
|
869
925
|
return __async(this, null, function* () {
|
|
870
926
|
var _a, _b, _c, _d, _e;
|
|
@@ -915,7 +971,7 @@ var BrowserStorageEngine = class extends DataStoreEngine {
|
|
|
915
971
|
* Creates an instance of `BrowserStorageEngine`.
|
|
916
972
|
*
|
|
917
973
|
* - ⚠️ Requires a DOM environment
|
|
918
|
-
* - ⚠️ Don't reuse
|
|
974
|
+
* - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
|
|
919
975
|
*/
|
|
920
976
|
constructor(options) {
|
|
921
977
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
@@ -957,7 +1013,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
957
1013
|
* Creates an instance of `FileStorageEngine`.
|
|
958
1014
|
*
|
|
959
1015
|
* - ⚠️ Requires Node.js or Deno with Node compatibility (v1.31+)
|
|
960
|
-
* - ⚠️ Don't reuse
|
|
1016
|
+
* - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
|
|
961
1017
|
*/
|
|
962
1018
|
constructor(options) {
|
|
963
1019
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
@@ -977,7 +1033,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
977
1033
|
if (!fs)
|
|
978
1034
|
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
979
1035
|
if (!fs)
|
|
980
|
-
throw new
|
|
1036
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
981
1037
|
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
982
1038
|
const data = yield fs.readFile(path, "utf-8");
|
|
983
1039
|
return data ? JSON.parse((_e = yield (_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, data)) != null ? _e : data) : void 0;
|
|
@@ -995,7 +1051,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
995
1051
|
if (!fs)
|
|
996
1052
|
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
997
1053
|
if (!fs)
|
|
998
|
-
throw new
|
|
1054
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
999
1055
|
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
1000
1056
|
yield fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
|
|
1001
1057
|
yield fs.writeFile(path, (_e = yield (_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.encodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, JSON.stringify(data))) != null ? _e : JSON.stringify(data, void 0, 2), "utf-8");
|
|
@@ -1062,9 +1118,9 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1062
1118
|
if (!fs)
|
|
1063
1119
|
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
1064
1120
|
if (!fs)
|
|
1065
|
-
throw new
|
|
1121
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1066
1122
|
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
1067
|
-
yield fs.unlink(path);
|
|
1123
|
+
return yield fs.unlink(path);
|
|
1068
1124
|
} catch (err) {
|
|
1069
1125
|
console.error("Error deleting file:", err);
|
|
1070
1126
|
}
|
|
@@ -1078,11 +1134,12 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1078
1134
|
__publicField(this, "stores");
|
|
1079
1135
|
__publicField(this, "options");
|
|
1080
1136
|
if (!crypto || !crypto.subtle)
|
|
1081
|
-
throw new
|
|
1137
|
+
throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
|
|
1082
1138
|
this.stores = stores;
|
|
1083
1139
|
this.options = __spreadValues({
|
|
1084
1140
|
addChecksum: true,
|
|
1085
|
-
ensureIntegrity: true
|
|
1141
|
+
ensureIntegrity: true,
|
|
1142
|
+
remapIds: {}
|
|
1086
1143
|
}, options);
|
|
1087
1144
|
}
|
|
1088
1145
|
/** Calculates the checksum of a string */
|
|
@@ -1101,9 +1158,11 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1101
1158
|
return __async(this, null, function* () {
|
|
1102
1159
|
var _a;
|
|
1103
1160
|
const serData = [];
|
|
1104
|
-
|
|
1161
|
+
const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
|
|
1162
|
+
for (const storeInst of filteredStores) {
|
|
1105
1163
|
const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
|
|
1106
|
-
const
|
|
1164
|
+
const rawData = storeInst.memoryCache ? storeInst.getData() : yield storeInst.loadData();
|
|
1165
|
+
const data = encoded ? yield storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
|
|
1107
1166
|
serData.push({
|
|
1108
1167
|
id: storeInst.id,
|
|
1109
1168
|
data,
|
|
@@ -1134,10 +1193,18 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1134
1193
|
const deserStores = typeof data === "string" ? JSON.parse(data) : data;
|
|
1135
1194
|
if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
|
|
1136
1195
|
throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
|
|
1137
|
-
|
|
1138
|
-
|
|
1196
|
+
const resolveStoreId = (id) => {
|
|
1197
|
+
var _a, _b;
|
|
1198
|
+
return (_b = (_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) != null ? _b : id;
|
|
1199
|
+
};
|
|
1200
|
+
const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
|
|
1201
|
+
for (const storeData of deserStores) {
|
|
1202
|
+
const effectiveId = resolveStoreId(storeData.id);
|
|
1203
|
+
if (!matchesFilter(effectiveId))
|
|
1204
|
+
continue;
|
|
1205
|
+
const storeInst = this.stores.find((s) => s.id === effectiveId);
|
|
1139
1206
|
if (!storeInst)
|
|
1140
|
-
throw new
|
|
1207
|
+
throw new DatedError(`Can't deserialize data because no DataStore instance with the ID "${effectiveId}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);
|
|
1141
1208
|
if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
|
|
1142
1209
|
const checksum = yield this.calcChecksum(storeData.data);
|
|
1143
1210
|
if (checksum !== storeData.checksum)
|
|
@@ -1319,11 +1386,12 @@ var NanoEmitter = class {
|
|
|
1319
1386
|
* `callback` (required) is the function that will be called when the conditions are met.
|
|
1320
1387
|
*
|
|
1321
1388
|
* Set `once` to true to call the callback only once for the first event (or set of events) that match the criteria, then stop listening.
|
|
1322
|
-
* If `signal` is provided, the subscription will be
|
|
1389
|
+
* If `signal` is provided, the subscription will be canceled when the given signal is aborted.
|
|
1323
1390
|
*
|
|
1324
1391
|
* If `oneOf` is used, the callback will be called when any of the matching events are emitted.
|
|
1325
1392
|
* If `allOf` is used, the callback will be called after all of the matching events are emitted at least once, then any time any of them are emitted.
|
|
1326
|
-
*
|
|
1393
|
+
* If both `oneOf` and `allOf` are used together, the callback will be called when any of the `oneOf` events are emitted AND all of the `allOf` events have been emitted at least once.
|
|
1394
|
+
* At least one of `oneOf` or `allOf` must be provided.
|
|
1327
1395
|
*
|
|
1328
1396
|
* @returns Returns a function that can be called to unsubscribe all listeners created by this call. Alternatively, pass an `AbortSignal` to all options objects to achieve the same effect or for finer control.
|
|
1329
1397
|
*/
|
|
@@ -1350,6 +1418,8 @@ var NanoEmitter = class {
|
|
|
1350
1418
|
} = optsWithDefaults;
|
|
1351
1419
|
if (signal == null ? void 0 : signal.aborted)
|
|
1352
1420
|
return unsubAll;
|
|
1421
|
+
if (oneOf.length === 0 && allOf.length === 0)
|
|
1422
|
+
throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
|
|
1353
1423
|
const curEvtUnsubs = [];
|
|
1354
1424
|
const checkUnsubAllEvt = (force = false) => {
|
|
1355
1425
|
if (!(signal == null ? void 0 : signal.aborted) && !force)
|
|
@@ -1359,34 +1429,31 @@ var NanoEmitter = class {
|
|
|
1359
1429
|
curEvtUnsubs.splice(0, curEvtUnsubs.length);
|
|
1360
1430
|
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
|
|
1361
1431
|
};
|
|
1432
|
+
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
1433
|
+
const allOfConditionMet = () => allOf.length === 0 || allOfEmitted.size === allOf.length;
|
|
1362
1434
|
for (const event of oneOf) {
|
|
1363
1435
|
const unsub = this.events.on(event, ((...args) => {
|
|
1364
1436
|
checkUnsubAllEvt();
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1437
|
+
if (allOfConditionMet()) {
|
|
1438
|
+
callback(event, ...args);
|
|
1439
|
+
if (once)
|
|
1440
|
+
checkUnsubAllEvt(true);
|
|
1441
|
+
}
|
|
1368
1442
|
}));
|
|
1369
1443
|
curEvtUnsubs.push(unsub);
|
|
1370
1444
|
}
|
|
1371
|
-
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
1372
|
-
const checkAllOf = (event, ...args) => {
|
|
1373
|
-
checkUnsubAllEvt();
|
|
1374
|
-
allOfEmitted.add(event);
|
|
1375
|
-
if (allOfEmitted.size === allOf.length) {
|
|
1376
|
-
callback(event, ...args);
|
|
1377
|
-
if (once)
|
|
1378
|
-
checkUnsubAllEvt(true);
|
|
1379
|
-
}
|
|
1380
|
-
};
|
|
1381
1445
|
for (const event of allOf) {
|
|
1382
1446
|
const unsub = this.events.on(event, ((...args) => {
|
|
1383
1447
|
checkUnsubAllEvt();
|
|
1384
|
-
|
|
1448
|
+
allOfEmitted.add(event);
|
|
1449
|
+
if (allOfConditionMet() && (oneOf.length === 0 || oneOf.includes(event))) {
|
|
1450
|
+
callback(event, ...args);
|
|
1451
|
+
if (once)
|
|
1452
|
+
checkUnsubAllEvt(true);
|
|
1453
|
+
}
|
|
1385
1454
|
}));
|
|
1386
1455
|
curEvtUnsubs.push(unsub);
|
|
1387
1456
|
}
|
|
1388
|
-
if (oneOf.length === 0 && allOf.length === 0)
|
|
1389
|
-
throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
|
|
1390
1457
|
allUnsubs.push(() => checkUnsubAllEvt(true));
|
|
1391
1458
|
}
|
|
1392
1459
|
return unsubAll;
|