@sv443-network/coreutils 3.1.0 → 3.3.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 +29 -0
- package/dist/CoreUtils.cjs +278 -252
- package/dist/CoreUtils.min.cjs +3 -3
- package/dist/CoreUtils.min.mjs +3 -3
- package/dist/CoreUtils.min.umd.js +3 -3
- package/dist/CoreUtils.mjs +278 -252
- package/dist/CoreUtils.umd.js +773 -631
- package/dist/lib/DataStore.d.ts +38 -4
- package/package.json +5 -5
package/dist/CoreUtils.umd.js
CHANGED
|
@@ -16,13 +16,41 @@
|
|
|
16
16
|
|
|
17
17
|
|
|
18
18
|
|
|
19
|
+
(function(g,f){if(typeof exports=="object"&&typeof module<"u"){module.exports=f()}else if("function"==typeof define && define.amd){define("CoreUtils",f)}else {g["CoreUtils"]=f()}}(typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : this,function(){var exports={};var __exports=exports;var module={exports};
|
|
19
20
|
"use strict";
|
|
20
21
|
var __create = Object.create;
|
|
21
22
|
var __defProp = Object.defineProperty;
|
|
22
23
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
23
24
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
25
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
24
26
|
var __getProtoOf = Object.getPrototypeOf;
|
|
25
27
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
28
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
29
|
+
var __pow = Math.pow;
|
|
30
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
31
|
+
var __spreadValues = (a, b) => {
|
|
32
|
+
for (var prop in b || (b = {}))
|
|
33
|
+
if (__hasOwnProp.call(b, prop))
|
|
34
|
+
__defNormalProp(a, prop, b[prop]);
|
|
35
|
+
if (__getOwnPropSymbols)
|
|
36
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
37
|
+
if (__propIsEnum.call(b, prop))
|
|
38
|
+
__defNormalProp(a, prop, b[prop]);
|
|
39
|
+
}
|
|
40
|
+
return a;
|
|
41
|
+
};
|
|
42
|
+
var __objRest = (source, exclude) => {
|
|
43
|
+
var target = {};
|
|
44
|
+
for (var prop in source)
|
|
45
|
+
if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
|
|
46
|
+
target[prop] = source[prop];
|
|
47
|
+
if (source != null && __getOwnPropSymbols)
|
|
48
|
+
for (var prop of __getOwnPropSymbols(source)) {
|
|
49
|
+
if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
|
|
50
|
+
target[prop] = source[prop];
|
|
51
|
+
}
|
|
52
|
+
return target;
|
|
53
|
+
};
|
|
26
54
|
var __export = (target, all) => {
|
|
27
55
|
for (var name in all)
|
|
28
56
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -44,6 +72,27 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
44
72
|
mod
|
|
45
73
|
));
|
|
46
74
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
75
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
76
|
+
var __async = (__this, __arguments, generator) => {
|
|
77
|
+
return new Promise((resolve, reject) => {
|
|
78
|
+
var fulfilled = (value) => {
|
|
79
|
+
try {
|
|
80
|
+
step(generator.next(value));
|
|
81
|
+
} catch (e) {
|
|
82
|
+
reject(e);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
var rejected = (value) => {
|
|
86
|
+
try {
|
|
87
|
+
step(generator.throw(value));
|
|
88
|
+
} catch (e) {
|
|
89
|
+
reject(e);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
93
|
+
step((generator = generator.apply(__this, __arguments)).next());
|
|
94
|
+
});
|
|
95
|
+
};
|
|
47
96
|
|
|
48
97
|
// lib/index.ts
|
|
49
98
|
var lib_exports = {};
|
|
@@ -194,7 +243,7 @@ function randRange(...args) {
|
|
|
194
243
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
195
244
|
}
|
|
196
245
|
function roundFixed(num, fractionDigits) {
|
|
197
|
-
const scale = 10
|
|
246
|
+
const scale = __pow(10, fractionDigits);
|
|
198
247
|
return Math.round(num * scale) / scale;
|
|
199
248
|
}
|
|
200
249
|
function valsWithin(a, b, dec = 1, withinRange = 0.5) {
|
|
@@ -258,7 +307,7 @@ function darkenColor(color, percent, upperCase = false) {
|
|
|
258
307
|
if (isHexCol)
|
|
259
308
|
return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
|
|
260
309
|
else if (color.startsWith("rgba"))
|
|
261
|
-
return `rgba(${r}, ${g}, ${b}, ${a
|
|
310
|
+
return `rgba(${r}, ${g}, ${b}, ${a != null ? a : NaN})`;
|
|
262
311
|
else
|
|
263
312
|
return `rgb(${r}, ${g}, ${b})`;
|
|
264
313
|
}
|
|
@@ -292,35 +341,43 @@ function abtoa(buf) {
|
|
|
292
341
|
function atoab(str) {
|
|
293
342
|
return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
|
|
294
343
|
}
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
344
|
+
function compress(input, compressionFormat, outputType = "string") {
|
|
345
|
+
return __async(this, null, function* () {
|
|
346
|
+
var _a;
|
|
347
|
+
const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
|
|
348
|
+
const comp = new CompressionStream(compressionFormat);
|
|
349
|
+
const writer = comp.writable.getWriter();
|
|
350
|
+
writer.write(byteArray);
|
|
351
|
+
writer.close();
|
|
352
|
+
const uintArr = new Uint8Array(yield new Response(comp.readable).arrayBuffer());
|
|
353
|
+
return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
|
|
354
|
+
});
|
|
303
355
|
}
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
356
|
+
function decompress(input, compressionFormat, outputType = "string") {
|
|
357
|
+
return __async(this, null, function* () {
|
|
358
|
+
var _a;
|
|
359
|
+
const byteArray = input instanceof Uint8Array ? input : atoab((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
|
|
360
|
+
const decomp = new DecompressionStream(compressionFormat);
|
|
361
|
+
const writer = decomp.writable.getWriter();
|
|
362
|
+
writer.write(byteArray);
|
|
363
|
+
writer.close();
|
|
364
|
+
const uintArr = new Uint8Array(yield new Response(decomp.readable).arrayBuffer());
|
|
365
|
+
return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
|
|
366
|
+
});
|
|
312
367
|
}
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
368
|
+
function computeHash(input, algorithm = "SHA-256") {
|
|
369
|
+
return __async(this, null, function* () {
|
|
370
|
+
let data;
|
|
371
|
+
if (typeof input === "string") {
|
|
372
|
+
const encoder = new TextEncoder();
|
|
373
|
+
data = encoder.encode(input);
|
|
374
|
+
} else
|
|
375
|
+
data = input;
|
|
376
|
+
const hashBuffer = yield crypto.subtle.digest(algorithm, data);
|
|
377
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
378
|
+
const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
379
|
+
return hashHex;
|
|
380
|
+
});
|
|
324
381
|
}
|
|
325
382
|
function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
|
|
326
383
|
if (length < 1)
|
|
@@ -349,9 +406,9 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
|
|
|
349
406
|
|
|
350
407
|
// lib/Errors.ts
|
|
351
408
|
var DatedError = class extends Error {
|
|
352
|
-
date;
|
|
353
409
|
constructor(message, options) {
|
|
354
410
|
super(message, options);
|
|
411
|
+
__publicField(this, "date");
|
|
355
412
|
this.name = this.constructor.name;
|
|
356
413
|
this.date = /* @__PURE__ */ new Date();
|
|
357
414
|
}
|
|
@@ -394,34 +451,37 @@ var NetworkError = class extends DatedError {
|
|
|
394
451
|
};
|
|
395
452
|
|
|
396
453
|
// lib/misc.ts
|
|
397
|
-
|
|
398
|
-
return
|
|
454
|
+
function consumeGen(valGen) {
|
|
455
|
+
return __async(this, null, function* () {
|
|
456
|
+
return yield typeof valGen === "function" ? valGen() : valGen;
|
|
457
|
+
});
|
|
399
458
|
}
|
|
400
|
-
|
|
401
|
-
return
|
|
402
|
-
typeof strGen === "
|
|
403
|
-
|
|
459
|
+
function consumeStringGen(strGen) {
|
|
460
|
+
return __async(this, null, function* () {
|
|
461
|
+
return typeof strGen === "string" ? strGen : String(
|
|
462
|
+
typeof strGen === "function" ? yield strGen() : strGen
|
|
463
|
+
);
|
|
464
|
+
});
|
|
404
465
|
}
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
}
|
|
466
|
+
function fetchAdvanced(_0) {
|
|
467
|
+
return __async(this, arguments, function* (input, options = {}) {
|
|
468
|
+
const _a = options, { timeout = 1e4, signal } = _a, restOpts = __objRest(_a, ["timeout", "signal"]);
|
|
469
|
+
const ctl = new AbortController();
|
|
470
|
+
signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
|
|
471
|
+
let sigOpts = {}, id = void 0;
|
|
472
|
+
if (timeout >= 0) {
|
|
473
|
+
id = setTimeout(() => ctl.abort(), timeout);
|
|
474
|
+
sigOpts = { signal: ctl.signal };
|
|
475
|
+
}
|
|
476
|
+
try {
|
|
477
|
+
const res = yield fetch(input, __spreadValues(__spreadValues({}, restOpts), sigOpts));
|
|
478
|
+
typeof id !== "undefined" && clearTimeout(id);
|
|
479
|
+
return res;
|
|
480
|
+
} catch (err) {
|
|
481
|
+
typeof id !== "undefined" && clearTimeout(id);
|
|
482
|
+
throw new NetworkError("Error while calling fetch", { cause: err });
|
|
483
|
+
}
|
|
484
|
+
});
|
|
425
485
|
}
|
|
426
486
|
function getListLength(listLike, zeroOnInvalid = true) {
|
|
427
487
|
return "length" in listLike ? listLike.length : "size" in listLike ? listLike.size : "count" in listLike ? listLike.count : zeroOnInvalid ? 0 : NaN;
|
|
@@ -436,7 +496,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
|
|
|
436
496
|
});
|
|
437
497
|
}
|
|
438
498
|
function pureObj(obj) {
|
|
439
|
-
return Object.assign(/* @__PURE__ */ Object.create(null), obj
|
|
499
|
+
return Object.assign(/* @__PURE__ */ Object.create(null), obj != null ? obj : {});
|
|
440
500
|
}
|
|
441
501
|
function setImmediateInterval(callback, interval, signal) {
|
|
442
502
|
let intervalId;
|
|
@@ -453,12 +513,12 @@ function setImmediateInterval(callback, interval, signal) {
|
|
|
453
513
|
function setImmediateTimeoutLoop(callback, interval, signal) {
|
|
454
514
|
let timeout;
|
|
455
515
|
const cleanup = () => clearTimeout(timeout);
|
|
456
|
-
const loop =
|
|
516
|
+
const loop = () => __async(null, null, function* () {
|
|
457
517
|
if (signal == null ? void 0 : signal.aborted)
|
|
458
518
|
return cleanup();
|
|
459
|
-
|
|
519
|
+
yield callback();
|
|
460
520
|
timeout = setTimeout(loop, interval);
|
|
461
|
-
};
|
|
521
|
+
});
|
|
462
522
|
signal == null ? void 0 : signal.addEventListener("abort", cleanup);
|
|
463
523
|
loop();
|
|
464
524
|
}
|
|
@@ -475,12 +535,13 @@ function scheduleExit(code = 0, timeout = 0) {
|
|
|
475
535
|
setTimeout(exit, timeout);
|
|
476
536
|
}
|
|
477
537
|
function getCallStack(asArray, lines = Infinity) {
|
|
538
|
+
var _a;
|
|
478
539
|
if (typeof lines !== "number" || isNaN(lines) || lines < 0)
|
|
479
540
|
throw new TypeError("lines parameter must be a non-negative number");
|
|
480
541
|
try {
|
|
481
542
|
throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)");
|
|
482
543
|
} catch (err) {
|
|
483
|
-
const stack = (err.stack
|
|
544
|
+
const stack = ((_a = err.stack) != null ? _a : "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
|
|
484
545
|
return asArray !== false ? stack : stack.join("\n");
|
|
485
546
|
}
|
|
486
547
|
}
|
|
@@ -535,9 +596,9 @@ function createProgressBar(percentage, barLength, chars = defaultPbChars) {
|
|
|
535
596
|
}
|
|
536
597
|
function insertValues(input, ...values) {
|
|
537
598
|
return input.replace(/%\d/gm, (match) => {
|
|
538
|
-
var _a;
|
|
599
|
+
var _a, _b;
|
|
539
600
|
const argIndex = Number(match.substring(1)) - 1;
|
|
540
|
-
return (_a = values[argIndex]
|
|
601
|
+
return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
|
|
541
602
|
});
|
|
542
603
|
}
|
|
543
604
|
function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
|
|
@@ -568,33 +629,213 @@ function secsToTimeStr(seconds) {
|
|
|
568
629
|
].join("");
|
|
569
630
|
}
|
|
570
631
|
function truncStr(input, length, endStr = "...") {
|
|
571
|
-
|
|
632
|
+
var _a;
|
|
633
|
+
const str = (_a = input == null ? void 0 : input.toString()) != null ? _a : String(input);
|
|
572
634
|
const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
|
|
573
635
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
574
636
|
}
|
|
575
637
|
|
|
576
|
-
//
|
|
577
|
-
var
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
638
|
+
// node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
|
|
639
|
+
var createNanoEvents = () => ({
|
|
640
|
+
emit(event, ...args) {
|
|
641
|
+
for (let callbacks = this.events[event] || [], i = 0, length = callbacks.length; i < length; i++) {
|
|
642
|
+
callbacks[i](...args);
|
|
643
|
+
}
|
|
644
|
+
},
|
|
645
|
+
events: {},
|
|
646
|
+
on(event, cb) {
|
|
647
|
+
var _a;
|
|
648
|
+
;
|
|
649
|
+
((_a = this.events)[event] || (_a[event] = [])).push(cb);
|
|
650
|
+
return () => {
|
|
651
|
+
var _a2;
|
|
652
|
+
this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
|
|
653
|
+
};
|
|
654
|
+
}
|
|
655
|
+
});
|
|
656
|
+
|
|
657
|
+
// lib/NanoEmitter.ts
|
|
658
|
+
var NanoEmitter = class {
|
|
659
|
+
/** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
|
|
660
|
+
constructor(options = {}) {
|
|
661
|
+
__publicField(this, "events", createNanoEvents());
|
|
662
|
+
__publicField(this, "eventUnsubscribes", []);
|
|
663
|
+
__publicField(this, "emitterOptions");
|
|
664
|
+
this.emitterOptions = __spreadValues({
|
|
665
|
+
publicEmit: false
|
|
666
|
+
}, options);
|
|
667
|
+
}
|
|
668
|
+
//#region on
|
|
669
|
+
/**
|
|
670
|
+
* Subscribes to an event and calls the callback when it's emitted.
|
|
671
|
+
* @param event The event to subscribe to. Use `as "_"` in case your event names aren't thoroughly typed (like when using a template literal, e.g. \`event-${val}\` as "_")
|
|
672
|
+
* @returns Returns a function that can be called to unsubscribe the event listener
|
|
673
|
+
* @example ```ts
|
|
674
|
+
* const emitter = new NanoEmitter<{
|
|
675
|
+
* foo: (bar: string) => void;
|
|
676
|
+
* }>({
|
|
677
|
+
* publicEmit: true,
|
|
678
|
+
* });
|
|
679
|
+
*
|
|
680
|
+
* let i = 0;
|
|
681
|
+
* const unsub = emitter.on("foo", (bar) => {
|
|
682
|
+
* // unsubscribe after 10 events:
|
|
683
|
+
* if(++i === 10) unsub();
|
|
684
|
+
* console.log(bar);
|
|
685
|
+
* });
|
|
686
|
+
*
|
|
687
|
+
* emitter.emit("foo", "bar");
|
|
688
|
+
* ```
|
|
689
|
+
*/
|
|
690
|
+
on(event, cb) {
|
|
691
|
+
let unsub;
|
|
692
|
+
const unsubProxy = () => {
|
|
693
|
+
if (!unsub)
|
|
694
|
+
return;
|
|
695
|
+
unsub();
|
|
696
|
+
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => u !== unsub);
|
|
697
|
+
};
|
|
698
|
+
unsub = this.events.on(event, cb);
|
|
699
|
+
this.eventUnsubscribes.push(unsub);
|
|
700
|
+
return unsubProxy;
|
|
701
|
+
}
|
|
702
|
+
//#region once
|
|
703
|
+
/**
|
|
704
|
+
* Subscribes to an event and calls the callback or resolves the Promise only once when it's emitted.
|
|
705
|
+
* @param event The event to subscribe to. Use `as "_"` in case your event names aren't thoroughly typed (like when using a template literal, e.g. \`event-${val}\` as "_")
|
|
706
|
+
* @param cb The callback to call when the event is emitted - if provided or not, the returned Promise will resolve with the event arguments
|
|
707
|
+
* @returns Returns a Promise that resolves with the event arguments when the event is emitted
|
|
708
|
+
* @example ```ts
|
|
709
|
+
* const emitter = new NanoEmitter<{
|
|
710
|
+
* foo: (bar: string) => void;
|
|
711
|
+
* }>();
|
|
712
|
+
*
|
|
713
|
+
* // Promise syntax:
|
|
714
|
+
* const [bar] = await emitter.once("foo");
|
|
715
|
+
* console.log(bar);
|
|
716
|
+
*
|
|
717
|
+
* // Callback syntax:
|
|
718
|
+
* emitter.once("foo", (bar) => console.log(bar));
|
|
719
|
+
* ```
|
|
720
|
+
*/
|
|
721
|
+
once(event, cb) {
|
|
722
|
+
return new Promise((resolve) => {
|
|
723
|
+
let unsub;
|
|
724
|
+
const onceProxy = ((...args) => {
|
|
725
|
+
cb == null ? void 0 : cb(...args);
|
|
726
|
+
unsub == null ? void 0 : unsub();
|
|
727
|
+
resolve(args);
|
|
728
|
+
});
|
|
729
|
+
unsub = this.events.on(event, onceProxy);
|
|
730
|
+
this.eventUnsubscribes.push(unsub);
|
|
731
|
+
});
|
|
732
|
+
}
|
|
733
|
+
//#region onMulti
|
|
734
|
+
/**
|
|
735
|
+
* Allows subscribing to multiple events and calling the callback only when one of, all of, or a subset of the events are emitted, either continuously or only once.
|
|
736
|
+
* @param options An object or array of objects with the following properties:
|
|
737
|
+
* `callback` (required) is the function that will be called when the conditions are met.
|
|
738
|
+
*
|
|
739
|
+
* 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.
|
|
740
|
+
* If `signal` is provided, the subscription will be canceled when the given signal is aborted.
|
|
741
|
+
*
|
|
742
|
+
* If `oneOf` is used, the callback will be called when any of the matching events are emitted.
|
|
743
|
+
* 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.
|
|
744
|
+
* 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.
|
|
745
|
+
* At least one of `oneOf` or `allOf` must be provided.
|
|
746
|
+
*
|
|
747
|
+
* @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.
|
|
748
|
+
*/
|
|
749
|
+
onMulti(options) {
|
|
750
|
+
const allUnsubs = [];
|
|
751
|
+
const unsubAll = () => {
|
|
752
|
+
for (const unsub of allUnsubs)
|
|
753
|
+
unsub();
|
|
754
|
+
allUnsubs.splice(0, allUnsubs.length);
|
|
755
|
+
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
|
|
756
|
+
};
|
|
757
|
+
for (const opts of Array.isArray(options) ? options : [options]) {
|
|
758
|
+
const optsWithDefaults = __spreadValues({
|
|
759
|
+
allOf: [],
|
|
760
|
+
oneOf: [],
|
|
761
|
+
once: false
|
|
762
|
+
}, opts);
|
|
763
|
+
const {
|
|
764
|
+
oneOf,
|
|
765
|
+
allOf,
|
|
766
|
+
once,
|
|
767
|
+
signal,
|
|
768
|
+
callback
|
|
769
|
+
} = optsWithDefaults;
|
|
770
|
+
if (signal == null ? void 0 : signal.aborted)
|
|
771
|
+
return unsubAll;
|
|
772
|
+
if (oneOf.length === 0 && allOf.length === 0)
|
|
773
|
+
throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
|
|
774
|
+
const curEvtUnsubs = [];
|
|
775
|
+
const checkUnsubAllEvt = (force = false) => {
|
|
776
|
+
if (!(signal == null ? void 0 : signal.aborted) && !force)
|
|
777
|
+
return;
|
|
778
|
+
for (const unsub of curEvtUnsubs)
|
|
779
|
+
unsub();
|
|
780
|
+
curEvtUnsubs.splice(0, curEvtUnsubs.length);
|
|
781
|
+
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
|
|
782
|
+
};
|
|
783
|
+
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
784
|
+
const allOfConditionMet = () => allOf.length === 0 || allOfEmitted.size === allOf.length;
|
|
785
|
+
for (const event of oneOf) {
|
|
786
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
787
|
+
checkUnsubAllEvt();
|
|
788
|
+
if (allOfConditionMet()) {
|
|
789
|
+
callback(event, ...args);
|
|
790
|
+
if (once)
|
|
791
|
+
checkUnsubAllEvt(true);
|
|
792
|
+
}
|
|
793
|
+
}));
|
|
794
|
+
curEvtUnsubs.push(unsub);
|
|
795
|
+
}
|
|
796
|
+
for (const event of allOf) {
|
|
797
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
798
|
+
checkUnsubAllEvt();
|
|
799
|
+
allOfEmitted.add(event);
|
|
800
|
+
if (allOfConditionMet() && (oneOf.length === 0 || oneOf.includes(event))) {
|
|
801
|
+
callback(event, ...args);
|
|
802
|
+
if (once)
|
|
803
|
+
checkUnsubAllEvt(true);
|
|
804
|
+
}
|
|
805
|
+
}));
|
|
806
|
+
curEvtUnsubs.push(unsub);
|
|
807
|
+
}
|
|
808
|
+
allUnsubs.push(() => checkUnsubAllEvt(true));
|
|
809
|
+
}
|
|
810
|
+
return unsubAll;
|
|
811
|
+
}
|
|
812
|
+
//#region emit
|
|
588
813
|
/**
|
|
589
|
-
*
|
|
590
|
-
*
|
|
591
|
-
*
|
|
814
|
+
* Emits an event on this instance.
|
|
815
|
+
* - ⚠️ Needs `publicEmit` to be set to true in the NanoEmitter constructor or super() call!
|
|
816
|
+
* @param event The event to emit
|
|
817
|
+
* @param args The arguments to pass to the event listeners
|
|
818
|
+
* @returns Returns true if `publicEmit` is true and the event was emitted successfully
|
|
592
819
|
*/
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
820
|
+
emit(event, ...args) {
|
|
821
|
+
if (this.emitterOptions.publicEmit) {
|
|
822
|
+
this.events.emit(event, ...args);
|
|
823
|
+
return true;
|
|
824
|
+
}
|
|
825
|
+
return false;
|
|
826
|
+
}
|
|
827
|
+
//#region unsubscribeAll
|
|
828
|
+
/** Unsubscribes all event listeners from this instance */
|
|
829
|
+
unsubscribeAll() {
|
|
830
|
+
for (const unsub of this.eventUnsubscribes)
|
|
831
|
+
unsub();
|
|
832
|
+
this.eventUnsubscribes = [];
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
|
|
836
|
+
// lib/DataStore.ts
|
|
837
|
+
var dsFmtVer = 1;
|
|
838
|
+
var DataStore = class extends NanoEmitter {
|
|
598
839
|
//#region constructor
|
|
599
840
|
/**
|
|
600
841
|
* Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
|
|
@@ -606,20 +847,43 @@ var DataStore = class {
|
|
|
606
847
|
* @param opts The options for this DataStore instance
|
|
607
848
|
*/
|
|
608
849
|
constructor(opts) {
|
|
850
|
+
var _a, _b, _c;
|
|
851
|
+
super(opts.nanoEmitterOptions);
|
|
852
|
+
__publicField(this, "id");
|
|
853
|
+
__publicField(this, "formatVersion");
|
|
854
|
+
__publicField(this, "defaultData");
|
|
855
|
+
__publicField(this, "encodeData");
|
|
856
|
+
__publicField(this, "decodeData");
|
|
857
|
+
__publicField(this, "compressionFormat", "deflate-raw");
|
|
858
|
+
__publicField(this, "memoryCache");
|
|
859
|
+
__publicField(this, "engine");
|
|
860
|
+
__publicField(this, "keyPrefix");
|
|
861
|
+
__publicField(this, "options");
|
|
862
|
+
/**
|
|
863
|
+
* Whether all first-init checks should be done.
|
|
864
|
+
* This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
|
|
865
|
+
* This is set to `true` by default. Create a subclass and set it to `false` before calling {@linkcode loadData()} if you want to explicitly skip these checks.
|
|
866
|
+
*/
|
|
867
|
+
__publicField(this, "firstInit", true);
|
|
868
|
+
/** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
|
|
869
|
+
__publicField(this, "cachedData");
|
|
870
|
+
__publicField(this, "migrations");
|
|
871
|
+
__publicField(this, "migrateIds", []);
|
|
609
872
|
this.id = opts.id;
|
|
610
873
|
this.formatVersion = opts.formatVersion;
|
|
611
874
|
this.defaultData = opts.defaultData;
|
|
612
|
-
this.memoryCache = opts.memoryCache
|
|
875
|
+
this.memoryCache = (_a = opts.memoryCache) != null ? _a : true;
|
|
613
876
|
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
614
877
|
this.migrations = opts.migrations;
|
|
615
878
|
if (opts.migrateIds)
|
|
616
879
|
this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
|
|
617
880
|
this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
|
|
881
|
+
this.keyPrefix = (_b = opts.keyPrefix) != null ? _b : "__ds-";
|
|
618
882
|
this.options = opts;
|
|
619
883
|
if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
|
|
620
884
|
this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
|
|
621
885
|
this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
|
|
622
|
-
this.compressionFormat = opts.encodeData[0]
|
|
886
|
+
this.compressionFormat = (_c = opts.encodeData[0]) != null ? _c : null;
|
|
623
887
|
} else if (opts.compressionFormat === null) {
|
|
624
888
|
this.encodeData = void 0;
|
|
625
889
|
this.decodeData = void 0;
|
|
@@ -627,8 +891,12 @@ var DataStore = class {
|
|
|
627
891
|
} else {
|
|
628
892
|
const fmt = typeof opts.compressionFormat === "string" ? opts.compressionFormat : "deflate-raw";
|
|
629
893
|
this.compressionFormat = fmt;
|
|
630
|
-
this.encodeData = [fmt,
|
|
631
|
-
|
|
894
|
+
this.encodeData = [fmt, (data) => __async(this, null, function* () {
|
|
895
|
+
return yield compress(data, fmt, "string");
|
|
896
|
+
})];
|
|
897
|
+
this.decodeData = [fmt, (data) => __async(this, null, function* () {
|
|
898
|
+
return yield decompress(data, fmt, "string");
|
|
899
|
+
})];
|
|
632
900
|
}
|
|
633
901
|
this.engine.setDataStoreOptions({
|
|
634
902
|
id: this.id,
|
|
@@ -642,66 +910,65 @@ var DataStore = class {
|
|
|
642
910
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
643
911
|
* Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
|
|
644
912
|
*/
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
const
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
promises
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
migrateFmt(`
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
913
|
+
loadData() {
|
|
914
|
+
return __async(this, null, function* () {
|
|
915
|
+
var _a;
|
|
916
|
+
try {
|
|
917
|
+
if (this.firstInit) {
|
|
918
|
+
this.firstInit = false;
|
|
919
|
+
const dsVer = Number(yield this.engine.getValue("__ds_fmt_ver", 0));
|
|
920
|
+
const oldData = yield this.engine.getValue(`_uucfg-${this.id}`, null);
|
|
921
|
+
if (oldData) {
|
|
922
|
+
const oldVer = Number(yield this.engine.getValue(`_uucfgver-${this.id}`, NaN));
|
|
923
|
+
const oldEnc = yield this.engine.getValue(`_uucfgenc-${this.id}`, null);
|
|
924
|
+
const promises = [];
|
|
925
|
+
const migrateFmt = (oldKey, newKey, value) => {
|
|
926
|
+
promises.push(this.engine.setValue(newKey, value));
|
|
927
|
+
promises.push(this.engine.deleteValue(oldKey));
|
|
928
|
+
};
|
|
929
|
+
migrateFmt(`_uucfg-${this.id}`, `${this.keyPrefix}${this.id}-dat`, oldData);
|
|
930
|
+
if (!isNaN(oldVer))
|
|
931
|
+
migrateFmt(`_uucfgver-${this.id}`, `${this.keyPrefix}${this.id}-ver`, oldVer);
|
|
932
|
+
if (typeof oldEnc === "boolean" || oldEnc === "true" || oldEnc === "false" || typeof oldEnc === "number" || oldEnc === "0" || oldEnc === "1")
|
|
933
|
+
migrateFmt(`_uucfgenc-${this.id}`, `${this.keyPrefix}${this.id}-enf`, [0, "0", true, "true"].includes(oldEnc) ? (_a = this.compressionFormat) != null ? _a : null : null);
|
|
934
|
+
else {
|
|
935
|
+
promises.push(this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat));
|
|
936
|
+
promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
|
|
937
|
+
}
|
|
938
|
+
yield Promise.allSettled(promises);
|
|
667
939
|
}
|
|
668
|
-
|
|
940
|
+
if (isNaN(dsVer) || dsVer < dsFmtVer)
|
|
941
|
+
yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
669
942
|
}
|
|
670
|
-
if (
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
this.
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
943
|
+
if (this.migrateIds.length > 0) {
|
|
944
|
+
yield this.migrateId(this.migrateIds);
|
|
945
|
+
this.migrateIds = [];
|
|
946
|
+
}
|
|
947
|
+
const storedDataRaw = yield this.engine.getValue(`${this.keyPrefix}${this.id}-dat`, null);
|
|
948
|
+
const storedFmtVer = Number(yield this.engine.getValue(`${this.keyPrefix}${this.id}-ver`, NaN));
|
|
949
|
+
if (typeof storedDataRaw !== "string" && typeof storedDataRaw !== "object" || storedDataRaw === null || isNaN(storedFmtVer)) {
|
|
950
|
+
yield this.saveDefaultData(false);
|
|
951
|
+
const data = this.engine.deepCopy(this.defaultData);
|
|
952
|
+
this.events.emit("loadData", data);
|
|
953
|
+
return data;
|
|
954
|
+
}
|
|
955
|
+
const storedData = storedDataRaw != null ? storedDataRaw : JSON.stringify(this.defaultData);
|
|
956
|
+
const encodingFmt = String(yield this.engine.getValue(`${this.keyPrefix}${this.id}-enf`, null));
|
|
957
|
+
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false" && encodingFmt !== "0" && encodingFmt !== "" && encodingFmt !== null;
|
|
958
|
+
let parsed = typeof storedData === "string" ? yield this.engine.deserializeData(storedData, isEncoded) : storedData;
|
|
959
|
+
if (storedFmtVer < this.formatVersion && this.migrations)
|
|
960
|
+
parsed = yield this.runMigrations(parsed, storedFmtVer);
|
|
961
|
+
const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(parsed) : this.engine.deepCopy(parsed);
|
|
962
|
+
this.events.emit("loadData", result);
|
|
963
|
+
return result;
|
|
964
|
+
} catch (err) {
|
|
965
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
966
|
+
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
967
|
+
this.events.emit("error", error);
|
|
968
|
+
yield this.saveDefaultData();
|
|
969
|
+
return this.defaultData;
|
|
690
970
|
}
|
|
691
|
-
|
|
692
|
-
if (storedFmtVer < this.formatVersion && this.migrations)
|
|
693
|
-
parsed = await this.runMigrations(parsed, storedFmtVer);
|
|
694
|
-
if (saveData)
|
|
695
|
-
await this.setData(parsed);
|
|
696
|
-
if (this.memoryCache)
|
|
697
|
-
return this.cachedData = this.engine.deepCopy(parsed);
|
|
698
|
-
else
|
|
699
|
-
return this.engine.deepCopy(parsed);
|
|
700
|
-
} catch (err) {
|
|
701
|
-
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
702
|
-
await this.saveDefaultData();
|
|
703
|
-
return this.defaultData;
|
|
704
|
-
}
|
|
971
|
+
});
|
|
705
972
|
}
|
|
706
973
|
//#region getData
|
|
707
974
|
/**
|
|
@@ -717,27 +984,49 @@ var DataStore = class {
|
|
|
717
984
|
//#region setData
|
|
718
985
|
/** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
|
|
719
986
|
setData(data) {
|
|
720
|
-
|
|
987
|
+
const dataCopy = this.engine.deepCopy(data);
|
|
988
|
+
if (this.memoryCache) {
|
|
721
989
|
this.cachedData = data;
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
this.engine.setValue(
|
|
990
|
+
this.events.emit("updateDataSync", dataCopy);
|
|
991
|
+
}
|
|
992
|
+
return new Promise((resolve) => __async(this, null, function* () {
|
|
993
|
+
const results = yield Promise.allSettled([
|
|
994
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, yield this.engine.serializeData(data, this.encodingEnabled())),
|
|
995
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
|
|
996
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
727
997
|
]);
|
|
998
|
+
if (results.every((r) => r.status === "fulfilled"))
|
|
999
|
+
this.events.emit("updateData", dataCopy);
|
|
1000
|
+
else {
|
|
1001
|
+
const error = new Error("Error while saving data to persistent storage: " + results.map((r) => r.status === "rejected" ? r.reason : null).filter(Boolean).join("; "));
|
|
1002
|
+
console.error(error);
|
|
1003
|
+
this.events.emit("error", error);
|
|
1004
|
+
}
|
|
728
1005
|
resolve();
|
|
729
|
-
});
|
|
1006
|
+
}));
|
|
730
1007
|
}
|
|
731
1008
|
//#region saveDefaultData
|
|
732
|
-
/**
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
1009
|
+
/**
|
|
1010
|
+
* Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage.
|
|
1011
|
+
* @param emitEvent Whether to emit the `setDefaultData` event - set to `false` to prevent event emission (used internally during initial population in {@linkcode loadData()})
|
|
1012
|
+
*/
|
|
1013
|
+
saveDefaultData(emitEvent = true) {
|
|
1014
|
+
return __async(this, null, function* () {
|
|
1015
|
+
if (this.memoryCache)
|
|
1016
|
+
this.cachedData = this.defaultData;
|
|
1017
|
+
const results = yield Promise.allSettled([
|
|
1018
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, yield this.engine.serializeData(this.defaultData, this.encodingEnabled())),
|
|
1019
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
|
|
1020
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
1021
|
+
]);
|
|
1022
|
+
if (results.every((r) => r.status === "fulfilled"))
|
|
1023
|
+
emitEvent && this.events.emit("setDefaultData", this.defaultData);
|
|
1024
|
+
else {
|
|
1025
|
+
const error = new Error("Error while saving default data to persistent storage: " + results.map((r) => r.status === "rejected" ? r.reason : null).filter(Boolean).join("; "));
|
|
1026
|
+
console.error(error);
|
|
1027
|
+
this.events.emit("error", error);
|
|
1028
|
+
}
|
|
1029
|
+
});
|
|
741
1030
|
}
|
|
742
1031
|
//#region deleteData
|
|
743
1032
|
/**
|
|
@@ -745,14 +1034,17 @@ var DataStore = class {
|
|
|
745
1034
|
* The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
|
|
746
1035
|
* Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
|
|
747
1036
|
*/
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
1037
|
+
deleteData() {
|
|
1038
|
+
return __async(this, null, function* () {
|
|
1039
|
+
var _a, _b;
|
|
1040
|
+
yield Promise.allSettled([
|
|
1041
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-dat`),
|
|
1042
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-ver`),
|
|
1043
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-enf`)
|
|
1044
|
+
]);
|
|
1045
|
+
yield (_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a);
|
|
1046
|
+
this.events.emit("deleteData");
|
|
1047
|
+
});
|
|
756
1048
|
}
|
|
757
1049
|
//#region encodingEnabled
|
|
758
1050
|
/** Returns whether encoding and decoding are enabled for this DataStore instance */
|
|
@@ -767,73 +1059,83 @@ var DataStore = class {
|
|
|
767
1059
|
*
|
|
768
1060
|
* If one of the migrations fails, the data will be reset to the default value if `resetOnError` is set to `true` (default). Otherwise, an error will be thrown and no data will be saved.
|
|
769
1061
|
*/
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
1062
|
+
runMigrations(oldData, oldFmtVer, resetOnError = true) {
|
|
1063
|
+
return __async(this, null, function* () {
|
|
1064
|
+
if (!this.migrations)
|
|
1065
|
+
return oldData;
|
|
1066
|
+
let newData = oldData;
|
|
1067
|
+
const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
|
|
1068
|
+
let lastFmtVer = oldFmtVer;
|
|
1069
|
+
for (let i = 0; i < sortedMigrations.length; i++) {
|
|
1070
|
+
const [fmtVer, migrationFunc] = sortedMigrations[i];
|
|
1071
|
+
const ver = Number(fmtVer);
|
|
1072
|
+
if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
|
|
1073
|
+
try {
|
|
1074
|
+
const migRes = migrationFunc(newData);
|
|
1075
|
+
newData = migRes instanceof Promise ? yield migRes : migRes;
|
|
1076
|
+
lastFmtVer = oldFmtVer = ver;
|
|
1077
|
+
const isFinal = ver >= this.formatVersion || i === sortedMigrations.length - 1;
|
|
1078
|
+
this.events.emit("migrateData", ver, newData, isFinal);
|
|
1079
|
+
} catch (err) {
|
|
1080
|
+
const migError = new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
|
|
1081
|
+
this.events.emit("migrationError", ver, migError);
|
|
1082
|
+
this.events.emit("error", migError);
|
|
1083
|
+
if (!resetOnError)
|
|
1084
|
+
throw migError;
|
|
1085
|
+
yield this.saveDefaultData();
|
|
1086
|
+
return this.engine.deepCopy(this.defaultData);
|
|
1087
|
+
}
|
|
788
1088
|
}
|
|
789
1089
|
}
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
return
|
|
798
|
-
|
|
799
|
-
return this.engine.deepCopy(newData);
|
|
1090
|
+
yield Promise.allSettled([
|
|
1091
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, yield this.engine.serializeData(newData, this.encodingEnabled())),
|
|
1092
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, lastFmtVer),
|
|
1093
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
1094
|
+
]);
|
|
1095
|
+
const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(newData) : this.engine.deepCopy(newData);
|
|
1096
|
+
this.events.emit("updateData", result);
|
|
1097
|
+
return result;
|
|
1098
|
+
});
|
|
800
1099
|
}
|
|
801
1100
|
//#region migrateId
|
|
802
1101
|
/**
|
|
803
1102
|
* Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
|
|
804
1103
|
* 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.
|
|
805
1104
|
*/
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
const [
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
1105
|
+
migrateId(oldIds) {
|
|
1106
|
+
return __async(this, null, function* () {
|
|
1107
|
+
const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
|
|
1108
|
+
yield Promise.all(ids.map((id) => __async(this, null, function* () {
|
|
1109
|
+
const [data, fmtVer, isEncoded] = yield (() => __async(this, null, function* () {
|
|
1110
|
+
const [d, f, e] = yield Promise.all([
|
|
1111
|
+
this.engine.getValue(`${this.keyPrefix}${id}-dat`, JSON.stringify(this.defaultData)),
|
|
1112
|
+
this.engine.getValue(`${this.keyPrefix}${id}-ver`, NaN),
|
|
1113
|
+
this.engine.getValue(`${this.keyPrefix}${id}-enf`, null)
|
|
1114
|
+
]);
|
|
1115
|
+
return [d, Number(f), Boolean(e) && String(e) !== "null"];
|
|
1116
|
+
}))();
|
|
1117
|
+
if (data === void 0 || isNaN(fmtVer))
|
|
1118
|
+
return;
|
|
1119
|
+
const parsed = yield this.engine.deserializeData(data, isEncoded);
|
|
1120
|
+
yield Promise.allSettled([
|
|
1121
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, yield this.engine.serializeData(parsed, this.encodingEnabled())),
|
|
1122
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, fmtVer),
|
|
1123
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat),
|
|
1124
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-dat`),
|
|
1125
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-ver`),
|
|
1126
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-enf`)
|
|
814
1127
|
]);
|
|
815
|
-
|
|
816
|
-
})
|
|
817
|
-
|
|
818
|
-
return;
|
|
819
|
-
const parsed = await this.engine.deserializeData(data, isEncoded);
|
|
820
|
-
await Promise.allSettled([
|
|
821
|
-
this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(parsed, this.encodingEnabled())),
|
|
822
|
-
this.engine.setValue(`__ds-${this.id}-ver`, fmtVer),
|
|
823
|
-
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat),
|
|
824
|
-
this.engine.deleteValue(`__ds-${id}-dat`),
|
|
825
|
-
this.engine.deleteValue(`__ds-${id}-ver`),
|
|
826
|
-
this.engine.deleteValue(`__ds-${id}-enf`)
|
|
827
|
-
]);
|
|
828
|
-
}));
|
|
1128
|
+
this.events.emit("migrateId", id, this.id);
|
|
1129
|
+
})));
|
|
1130
|
+
});
|
|
829
1131
|
}
|
|
830
1132
|
};
|
|
831
1133
|
|
|
832
1134
|
// lib/DataStoreEngine.ts
|
|
833
1135
|
var DataStoreEngine = class {
|
|
834
|
-
dataStoreOptions;
|
|
835
1136
|
// setDataStoreOptions() is called from inside the DataStore constructor to set this value
|
|
836
1137
|
constructor(options) {
|
|
1138
|
+
__publicField(this, "dataStoreOptions");
|
|
837
1139
|
if (options)
|
|
838
1140
|
this.dataStoreOptions = options;
|
|
839
1141
|
}
|
|
@@ -843,25 +1145,29 @@ var DataStoreEngine = class {
|
|
|
843
1145
|
}
|
|
844
1146
|
//#region serialization api
|
|
845
1147
|
/** 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 */
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
1148
|
+
serializeData(data, useEncoding) {
|
|
1149
|
+
return __async(this, null, function* () {
|
|
1150
|
+
var _a, _b, _c, _d, _e;
|
|
1151
|
+
this.ensureDataStoreOptions();
|
|
1152
|
+
const stringData = JSON.stringify(data);
|
|
1153
|
+
if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
|
|
1154
|
+
return stringData;
|
|
1155
|
+
const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
|
|
1156
|
+
if (encRes instanceof Promise)
|
|
1157
|
+
return yield encRes;
|
|
1158
|
+
return encRes;
|
|
1159
|
+
});
|
|
856
1160
|
}
|
|
857
1161
|
/** Deserializes the given string to a JSON object, optionally decoded with `options.decodeData` if {@linkcode useEncoding} is set to true */
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
decRes
|
|
864
|
-
|
|
1162
|
+
deserializeData(data, useEncoding) {
|
|
1163
|
+
return __async(this, null, function* () {
|
|
1164
|
+
var _a, _b, _c;
|
|
1165
|
+
this.ensureDataStoreOptions();
|
|
1166
|
+
let decRes = ((_a = this.dataStoreOptions) == null ? void 0 : _a.decodeData) && useEncoding ? (_c = (_b = this.dataStoreOptions.decodeData) == null ? void 0 : _b[1]) == null ? void 0 : _c.call(_b, data) : void 0;
|
|
1167
|
+
if (decRes instanceof Promise)
|
|
1168
|
+
decRes = yield decRes;
|
|
1169
|
+
return JSON.parse(decRes != null ? decRes : data);
|
|
1170
|
+
});
|
|
865
1171
|
}
|
|
866
1172
|
//#region misc api
|
|
867
1173
|
/** Throws an error if the DataStoreOptions are not set or invalid */
|
|
@@ -879,13 +1185,12 @@ var DataStoreEngine = class {
|
|
|
879
1185
|
try {
|
|
880
1186
|
if ("structuredClone" in globalThis)
|
|
881
1187
|
return structuredClone(obj);
|
|
882
|
-
} catch {
|
|
1188
|
+
} catch (e) {
|
|
883
1189
|
}
|
|
884
1190
|
return JSON.parse(JSON.stringify(obj));
|
|
885
1191
|
}
|
|
886
1192
|
};
|
|
887
1193
|
var BrowserStorageEngine = class extends DataStoreEngine {
|
|
888
|
-
options;
|
|
889
1194
|
/**
|
|
890
1195
|
* Creates an instance of `BrowserStorageEngine`.
|
|
891
1196
|
*
|
|
@@ -894,36 +1199,40 @@ var BrowserStorageEngine = class extends DataStoreEngine {
|
|
|
894
1199
|
*/
|
|
895
1200
|
constructor(options) {
|
|
896
1201
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
897
|
-
this
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
};
|
|
1202
|
+
__publicField(this, "options");
|
|
1203
|
+
this.options = __spreadValues({
|
|
1204
|
+
type: "localStorage"
|
|
1205
|
+
}, options);
|
|
901
1206
|
}
|
|
902
1207
|
//#region storage api
|
|
903
1208
|
/** Fetches a value from persistent storage */
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
1209
|
+
getValue(name, defaultValue) {
|
|
1210
|
+
return __async(this, null, function* () {
|
|
1211
|
+
const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
|
|
1212
|
+
return typeof val === "undefined" ? defaultValue : val;
|
|
1213
|
+
});
|
|
907
1214
|
}
|
|
908
1215
|
/** Sets a value in persistent storage */
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
1216
|
+
setValue(name, value) {
|
|
1217
|
+
return __async(this, null, function* () {
|
|
1218
|
+
if (this.options.type === "localStorage")
|
|
1219
|
+
globalThis.localStorage.setItem(name, String(value));
|
|
1220
|
+
else
|
|
1221
|
+
globalThis.sessionStorage.setItem(name, String(value));
|
|
1222
|
+
});
|
|
914
1223
|
}
|
|
915
1224
|
/** Deletes a value from persistent storage */
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
1225
|
+
deleteValue(name) {
|
|
1226
|
+
return __async(this, null, function* () {
|
|
1227
|
+
if (this.options.type === "localStorage")
|
|
1228
|
+
globalThis.localStorage.removeItem(name);
|
|
1229
|
+
else
|
|
1230
|
+
globalThis.sessionStorage.removeItem(name);
|
|
1231
|
+
});
|
|
921
1232
|
}
|
|
922
1233
|
};
|
|
923
1234
|
var fs;
|
|
924
1235
|
var FileStorageEngine = class extends DataStoreEngine {
|
|
925
|
-
options;
|
|
926
|
-
fileAccessQueue = Promise.resolve();
|
|
927
1236
|
/**
|
|
928
1237
|
* Creates an instance of `FileStorageEngine`.
|
|
929
1238
|
*
|
|
@@ -932,146 +1241,160 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
932
1241
|
*/
|
|
933
1242
|
constructor(options) {
|
|
934
1243
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
935
|
-
this
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
1244
|
+
__publicField(this, "options");
|
|
1245
|
+
__publicField(this, "fileAccessQueue", Promise.resolve());
|
|
1246
|
+
this.options = __spreadValues({
|
|
1247
|
+
filePath: (id) => `.ds-${id}`
|
|
1248
|
+
}, options);
|
|
939
1249
|
}
|
|
940
1250
|
//#region json file
|
|
941
1251
|
/** Reads the file contents */
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
1252
|
+
readFile() {
|
|
1253
|
+
return __async(this, null, function* () {
|
|
1254
|
+
var _a, _b, _c, _d, _e;
|
|
1255
|
+
this.ensureDataStoreOptions();
|
|
1256
|
+
try {
|
|
1257
|
+
if (!fs)
|
|
1258
|
+
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
1259
|
+
if (!fs)
|
|
1260
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1261
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
1262
|
+
const data = yield fs.readFile(path, "utf-8");
|
|
1263
|
+
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;
|
|
1264
|
+
} catch (e) {
|
|
1265
|
+
return void 0;
|
|
1266
|
+
}
|
|
1267
|
+
});
|
|
956
1268
|
}
|
|
957
1269
|
/** Overwrites the file contents */
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
1270
|
+
writeFile(data) {
|
|
1271
|
+
return __async(this, null, function* () {
|
|
1272
|
+
var _a, _b, _c, _d, _e;
|
|
1273
|
+
this.ensureDataStoreOptions();
|
|
1274
|
+
try {
|
|
1275
|
+
if (!fs)
|
|
1276
|
+
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
1277
|
+
if (!fs)
|
|
1278
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1279
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
1280
|
+
yield fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
|
|
1281
|
+
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");
|
|
1282
|
+
} catch (err) {
|
|
1283
|
+
console.error("Error writing file:", err);
|
|
1284
|
+
}
|
|
1285
|
+
});
|
|
972
1286
|
}
|
|
973
1287
|
//#region storage api
|
|
974
1288
|
/** Fetches a value from persistent storage */
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
const value = data == null ? void 0 : data[name];
|
|
980
|
-
if (typeof value === "undefined")
|
|
981
|
-
return defaultValue;
|
|
982
|
-
if (typeof defaultValue === "string") {
|
|
983
|
-
if (typeof value === "object" && value !== null)
|
|
984
|
-
return JSON.stringify(value);
|
|
985
|
-
if (typeof value === "string")
|
|
986
|
-
return value;
|
|
987
|
-
return String(value);
|
|
988
|
-
}
|
|
989
|
-
if (typeof value === "string") {
|
|
990
|
-
try {
|
|
991
|
-
const parsed = JSON.parse(value);
|
|
992
|
-
return parsed;
|
|
993
|
-
} catch {
|
|
1289
|
+
getValue(name, defaultValue) {
|
|
1290
|
+
return __async(this, null, function* () {
|
|
1291
|
+
const data = yield this.readFile();
|
|
1292
|
+
if (!data)
|
|
994
1293
|
return defaultValue;
|
|
1294
|
+
const value = data == null ? void 0 : data[name];
|
|
1295
|
+
if (typeof value === "undefined")
|
|
1296
|
+
return defaultValue;
|
|
1297
|
+
if (typeof defaultValue === "string") {
|
|
1298
|
+
if (typeof value === "object" && value !== null)
|
|
1299
|
+
return JSON.stringify(value);
|
|
1300
|
+
if (typeof value === "string")
|
|
1301
|
+
return value;
|
|
1302
|
+
return String(value);
|
|
995
1303
|
}
|
|
996
|
-
}
|
|
997
|
-
return value;
|
|
998
|
-
}
|
|
999
|
-
/** Sets a value in persistent storage */
|
|
1000
|
-
async setValue(name, value) {
|
|
1001
|
-
this.fileAccessQueue = this.fileAccessQueue.then(async () => {
|
|
1002
|
-
let data = await this.readFile();
|
|
1003
|
-
if (!data)
|
|
1004
|
-
data = {};
|
|
1005
|
-
let storeVal = value;
|
|
1006
1304
|
if (typeof value === "string") {
|
|
1007
1305
|
try {
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
}
|
|
1013
|
-
} catch {
|
|
1306
|
+
const parsed = JSON.parse(value);
|
|
1307
|
+
return parsed;
|
|
1308
|
+
} catch (e) {
|
|
1309
|
+
return defaultValue;
|
|
1014
1310
|
}
|
|
1015
1311
|
}
|
|
1016
|
-
|
|
1017
|
-
await this.writeFile(data);
|
|
1018
|
-
}).catch((err) => {
|
|
1019
|
-
console.error("Error in setValue:", err);
|
|
1020
|
-
throw err;
|
|
1312
|
+
return value;
|
|
1021
1313
|
});
|
|
1022
|
-
|
|
1314
|
+
}
|
|
1315
|
+
/** Sets a value in persistent storage */
|
|
1316
|
+
setValue(name, value) {
|
|
1317
|
+
return __async(this, null, function* () {
|
|
1318
|
+
this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
|
|
1319
|
+
let data = yield this.readFile();
|
|
1320
|
+
if (!data)
|
|
1321
|
+
data = {};
|
|
1322
|
+
let storeVal = value;
|
|
1323
|
+
if (typeof value === "string") {
|
|
1324
|
+
try {
|
|
1325
|
+
if (value.startsWith("{") || value.startsWith("[")) {
|
|
1326
|
+
const parsed = JSON.parse(value);
|
|
1327
|
+
if (typeof parsed === "object" && parsed !== null)
|
|
1328
|
+
storeVal = parsed;
|
|
1329
|
+
}
|
|
1330
|
+
} catch (e) {
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
data[name] = storeVal;
|
|
1334
|
+
yield this.writeFile(data);
|
|
1335
|
+
})).catch((err) => {
|
|
1336
|
+
console.error("Error in setValue:", err);
|
|
1337
|
+
throw err;
|
|
1338
|
+
});
|
|
1339
|
+
yield this.fileAccessQueue.catch(() => {
|
|
1340
|
+
});
|
|
1023
1341
|
});
|
|
1024
1342
|
}
|
|
1025
1343
|
/** Deletes a value from persistent storage */
|
|
1026
|
-
|
|
1027
|
-
this
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1344
|
+
deleteValue(name) {
|
|
1345
|
+
return __async(this, null, function* () {
|
|
1346
|
+
this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
|
|
1347
|
+
const data = yield this.readFile();
|
|
1348
|
+
if (!data)
|
|
1349
|
+
return;
|
|
1350
|
+
delete data[name];
|
|
1351
|
+
yield this.writeFile(data);
|
|
1352
|
+
})).catch((err) => {
|
|
1353
|
+
console.error("Error in deleteValue:", err);
|
|
1354
|
+
throw err;
|
|
1355
|
+
});
|
|
1356
|
+
yield this.fileAccessQueue.catch(() => {
|
|
1357
|
+
});
|
|
1038
1358
|
});
|
|
1039
1359
|
}
|
|
1040
1360
|
/** Deletes the file that contains the data of this DataStore. */
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1361
|
+
deleteStorage() {
|
|
1362
|
+
return __async(this, null, function* () {
|
|
1363
|
+
var _a;
|
|
1364
|
+
this.ensureDataStoreOptions();
|
|
1365
|
+
try {
|
|
1366
|
+
if (!fs)
|
|
1367
|
+
fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
|
|
1368
|
+
if (!fs)
|
|
1369
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1370
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
1371
|
+
return yield fs.unlink(path);
|
|
1372
|
+
} catch (err) {
|
|
1373
|
+
console.error("Error deleting file:", err);
|
|
1374
|
+
}
|
|
1375
|
+
});
|
|
1054
1376
|
}
|
|
1055
1377
|
};
|
|
1056
1378
|
|
|
1057
1379
|
// lib/DataStoreSerializer.ts
|
|
1058
1380
|
var DataStoreSerializer = class _DataStoreSerializer {
|
|
1059
|
-
stores;
|
|
1060
|
-
options;
|
|
1061
1381
|
constructor(stores, options = {}) {
|
|
1382
|
+
__publicField(this, "stores");
|
|
1383
|
+
__publicField(this, "options");
|
|
1062
1384
|
if (!crypto || !crypto.subtle)
|
|
1063
1385
|
throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
|
|
1064
1386
|
this.stores = stores;
|
|
1065
|
-
this.options = {
|
|
1387
|
+
this.options = __spreadValues({
|
|
1066
1388
|
addChecksum: true,
|
|
1067
1389
|
ensureIntegrity: true,
|
|
1068
|
-
remapIds: {}
|
|
1069
|
-
|
|
1070
|
-
};
|
|
1390
|
+
remapIds: {}
|
|
1391
|
+
}, options);
|
|
1071
1392
|
}
|
|
1072
1393
|
/** Calculates the checksum of a string */
|
|
1073
|
-
|
|
1074
|
-
return
|
|
1394
|
+
calcChecksum(input) {
|
|
1395
|
+
return __async(this, null, function* () {
|
|
1396
|
+
return computeHash(input, "SHA-256");
|
|
1397
|
+
});
|
|
1075
1398
|
}
|
|
1076
1399
|
/**
|
|
1077
1400
|
* Serializes only a subset of the data stores into a string.
|
|
@@ -1079,72 +1402,80 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1079
1402
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1080
1403
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1081
1404
|
*/
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1405
|
+
serializePartial(stores, useEncoding = true, stringified = true) {
|
|
1406
|
+
return __async(this, null, function* () {
|
|
1407
|
+
var _a;
|
|
1408
|
+
const serData = [];
|
|
1409
|
+
const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
|
|
1410
|
+
for (const storeInst of filteredStores) {
|
|
1411
|
+
const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
|
|
1412
|
+
const rawData = storeInst.memoryCache ? storeInst.getData() : yield storeInst.loadData();
|
|
1413
|
+
const data = encoded ? yield storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
|
|
1414
|
+
serData.push({
|
|
1415
|
+
id: storeInst.id,
|
|
1416
|
+
data,
|
|
1417
|
+
formatVersion: storeInst.formatVersion,
|
|
1418
|
+
encoded,
|
|
1419
|
+
checksum: this.options.addChecksum ? yield this.calcChecksum(data) : void 0
|
|
1420
|
+
});
|
|
1421
|
+
}
|
|
1422
|
+
return stringified ? JSON.stringify(serData) : serData;
|
|
1423
|
+
});
|
|
1099
1424
|
}
|
|
1100
1425
|
/**
|
|
1101
1426
|
* Serializes the data stores into a string.
|
|
1102
1427
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1103
1428
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1104
1429
|
*/
|
|
1105
|
-
|
|
1106
|
-
return
|
|
1430
|
+
serialize(useEncoding = true, stringified = true) {
|
|
1431
|
+
return __async(this, null, function* () {
|
|
1432
|
+
return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
|
|
1433
|
+
});
|
|
1107
1434
|
}
|
|
1108
1435
|
/**
|
|
1109
1436
|
* Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
|
|
1110
1437
|
* Also triggers the migration process if the data format has changed.
|
|
1111
1438
|
*/
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
const
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1439
|
+
deserializePartial(stores, data) {
|
|
1440
|
+
return __async(this, null, function* () {
|
|
1441
|
+
const deserStores = typeof data === "string" ? JSON.parse(data) : data;
|
|
1442
|
+
if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
|
|
1443
|
+
throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
|
|
1444
|
+
const resolveStoreId = (id) => {
|
|
1445
|
+
var _a, _b;
|
|
1446
|
+
return (_b = (_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) != null ? _b : id;
|
|
1447
|
+
};
|
|
1448
|
+
const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
|
|
1449
|
+
for (const storeData of deserStores) {
|
|
1450
|
+
const effectiveId = resolveStoreId(storeData.id);
|
|
1451
|
+
if (!matchesFilter(effectiveId))
|
|
1452
|
+
continue;
|
|
1453
|
+
const storeInst = this.stores.find((s) => s.id === effectiveId);
|
|
1454
|
+
if (!storeInst)
|
|
1455
|
+
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.`);
|
|
1456
|
+
if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
|
|
1457
|
+
const checksum = yield this.calcChecksum(storeData.data);
|
|
1458
|
+
if (checksum !== storeData.checksum)
|
|
1459
|
+
throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
|
|
1132
1460
|
Expected: ${storeData.checksum}
|
|
1133
1461
|
Has: ${checksum}`);
|
|
1462
|
+
}
|
|
1463
|
+
const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData[1](storeData.data) : storeData.data;
|
|
1464
|
+
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1465
|
+
yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1466
|
+
else
|
|
1467
|
+
yield storeInst.setData(JSON.parse(decodedData));
|
|
1134
1468
|
}
|
|
1135
|
-
|
|
1136
|
-
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1137
|
-
await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1138
|
-
else
|
|
1139
|
-
await storeInst.setData(JSON.parse(decodedData));
|
|
1140
|
-
}
|
|
1469
|
+
});
|
|
1141
1470
|
}
|
|
1142
1471
|
/**
|
|
1143
1472
|
* Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
|
|
1144
1473
|
* Also triggers the migration process if the data format has changed.
|
|
1145
1474
|
*/
|
|
1146
|
-
|
|
1147
|
-
return
|
|
1475
|
+
deserialize(data) {
|
|
1476
|
+
return __async(this, null, function* () {
|
|
1477
|
+
return this.deserializePartial(this.stores.map((s) => s.id), data);
|
|
1478
|
+
});
|
|
1148
1479
|
}
|
|
1149
1480
|
/**
|
|
1150
1481
|
* Loads the persistent data of the DataStore instances into the in-memory cache.
|
|
@@ -1152,32 +1483,40 @@ Has: ${checksum}`);
|
|
|
1152
1483
|
* @param stores An array of store IDs or a function that takes the store IDs and returns a boolean - if omitted, all stores will be loaded
|
|
1153
1484
|
* @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
|
|
1154
1485
|
*/
|
|
1155
|
-
|
|
1156
|
-
return
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1486
|
+
loadStoresData(stores) {
|
|
1487
|
+
return __async(this, null, function* () {
|
|
1488
|
+
return Promise.allSettled(
|
|
1489
|
+
this.getStoresFiltered(stores).map((store) => __async(this, null, function* () {
|
|
1490
|
+
return {
|
|
1491
|
+
id: store.id,
|
|
1492
|
+
data: yield store.loadData()
|
|
1493
|
+
};
|
|
1494
|
+
}))
|
|
1495
|
+
);
|
|
1496
|
+
});
|
|
1162
1497
|
}
|
|
1163
1498
|
/**
|
|
1164
1499
|
* Resets the persistent and in-memory data of the DataStore instances to their default values.
|
|
1165
1500
|
* @param stores An array of store IDs or a function that takes the store IDs and returns a boolean - if omitted, all stores will be affected
|
|
1166
1501
|
*/
|
|
1167
|
-
|
|
1168
|
-
return
|
|
1169
|
-
|
|
1170
|
-
|
|
1502
|
+
resetStoresData(stores) {
|
|
1503
|
+
return __async(this, null, function* () {
|
|
1504
|
+
return Promise.allSettled(
|
|
1505
|
+
this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
|
|
1506
|
+
);
|
|
1507
|
+
});
|
|
1171
1508
|
}
|
|
1172
1509
|
/**
|
|
1173
1510
|
* Deletes the persistent data of the DataStore instances.
|
|
1174
1511
|
* Leaves the in-memory data untouched.
|
|
1175
1512
|
* @param stores An array of store IDs or a function that takes the store IDs and returns a boolean - if omitted, all stores will be affected
|
|
1176
1513
|
*/
|
|
1177
|
-
|
|
1178
|
-
return
|
|
1179
|
-
|
|
1180
|
-
|
|
1514
|
+
deleteStoresData(stores) {
|
|
1515
|
+
return __async(this, null, function* () {
|
|
1516
|
+
return Promise.allSettled(
|
|
1517
|
+
this.getStoresFiltered(stores).map((store) => store.deleteData())
|
|
1518
|
+
);
|
|
1519
|
+
});
|
|
1181
1520
|
}
|
|
1182
1521
|
/** Checks if a given value is an array of SerializedDataStore objects */
|
|
1183
1522
|
static isSerializedDataStoreObjArray(obj) {
|
|
@@ -1193,205 +1532,6 @@ Has: ${checksum}`);
|
|
|
1193
1532
|
}
|
|
1194
1533
|
};
|
|
1195
1534
|
|
|
1196
|
-
// node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
|
|
1197
|
-
var createNanoEvents = () => ({
|
|
1198
|
-
emit(event, ...args) {
|
|
1199
|
-
for (let callbacks = this.events[event] || [], i = 0, length = callbacks.length; i < length; i++) {
|
|
1200
|
-
callbacks[i](...args);
|
|
1201
|
-
}
|
|
1202
|
-
},
|
|
1203
|
-
events: {},
|
|
1204
|
-
on(event, cb) {
|
|
1205
|
-
;
|
|
1206
|
-
(this.events[event] ||= []).push(cb);
|
|
1207
|
-
return () => {
|
|
1208
|
-
var _a;
|
|
1209
|
-
this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((i) => cb !== i);
|
|
1210
|
-
};
|
|
1211
|
-
}
|
|
1212
|
-
});
|
|
1213
|
-
|
|
1214
|
-
// lib/NanoEmitter.ts
|
|
1215
|
-
var NanoEmitter = class {
|
|
1216
|
-
events = createNanoEvents();
|
|
1217
|
-
eventUnsubscribes = [];
|
|
1218
|
-
emitterOptions;
|
|
1219
|
-
/** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
|
|
1220
|
-
constructor(options = {}) {
|
|
1221
|
-
this.emitterOptions = {
|
|
1222
|
-
publicEmit: false,
|
|
1223
|
-
...options
|
|
1224
|
-
};
|
|
1225
|
-
}
|
|
1226
|
-
//#region on
|
|
1227
|
-
/**
|
|
1228
|
-
* Subscribes to an event and calls the callback when it's emitted.
|
|
1229
|
-
* @param event The event to subscribe to. Use `as "_"` in case your event names aren't thoroughly typed (like when using a template literal, e.g. \`event-${val}\` as "_")
|
|
1230
|
-
* @returns Returns a function that can be called to unsubscribe the event listener
|
|
1231
|
-
* @example ```ts
|
|
1232
|
-
* const emitter = new NanoEmitter<{
|
|
1233
|
-
* foo: (bar: string) => void;
|
|
1234
|
-
* }>({
|
|
1235
|
-
* publicEmit: true,
|
|
1236
|
-
* });
|
|
1237
|
-
*
|
|
1238
|
-
* let i = 0;
|
|
1239
|
-
* const unsub = emitter.on("foo", (bar) => {
|
|
1240
|
-
* // unsubscribe after 10 events:
|
|
1241
|
-
* if(++i === 10) unsub();
|
|
1242
|
-
* console.log(bar);
|
|
1243
|
-
* });
|
|
1244
|
-
*
|
|
1245
|
-
* emitter.emit("foo", "bar");
|
|
1246
|
-
* ```
|
|
1247
|
-
*/
|
|
1248
|
-
on(event, cb) {
|
|
1249
|
-
let unsub;
|
|
1250
|
-
const unsubProxy = () => {
|
|
1251
|
-
if (!unsub)
|
|
1252
|
-
return;
|
|
1253
|
-
unsub();
|
|
1254
|
-
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => u !== unsub);
|
|
1255
|
-
};
|
|
1256
|
-
unsub = this.events.on(event, cb);
|
|
1257
|
-
this.eventUnsubscribes.push(unsub);
|
|
1258
|
-
return unsubProxy;
|
|
1259
|
-
}
|
|
1260
|
-
//#region once
|
|
1261
|
-
/**
|
|
1262
|
-
* Subscribes to an event and calls the callback or resolves the Promise only once when it's emitted.
|
|
1263
|
-
* @param event The event to subscribe to. Use `as "_"` in case your event names aren't thoroughly typed (like when using a template literal, e.g. \`event-${val}\` as "_")
|
|
1264
|
-
* @param cb The callback to call when the event is emitted - if provided or not, the returned Promise will resolve with the event arguments
|
|
1265
|
-
* @returns Returns a Promise that resolves with the event arguments when the event is emitted
|
|
1266
|
-
* @example ```ts
|
|
1267
|
-
* const emitter = new NanoEmitter<{
|
|
1268
|
-
* foo: (bar: string) => void;
|
|
1269
|
-
* }>();
|
|
1270
|
-
*
|
|
1271
|
-
* // Promise syntax:
|
|
1272
|
-
* const [bar] = await emitter.once("foo");
|
|
1273
|
-
* console.log(bar);
|
|
1274
|
-
*
|
|
1275
|
-
* // Callback syntax:
|
|
1276
|
-
* emitter.once("foo", (bar) => console.log(bar));
|
|
1277
|
-
* ```
|
|
1278
|
-
*/
|
|
1279
|
-
once(event, cb) {
|
|
1280
|
-
return new Promise((resolve) => {
|
|
1281
|
-
let unsub;
|
|
1282
|
-
const onceProxy = ((...args) => {
|
|
1283
|
-
cb == null ? void 0 : cb(...args);
|
|
1284
|
-
unsub == null ? void 0 : unsub();
|
|
1285
|
-
resolve(args);
|
|
1286
|
-
});
|
|
1287
|
-
unsub = this.events.on(event, onceProxy);
|
|
1288
|
-
this.eventUnsubscribes.push(unsub);
|
|
1289
|
-
});
|
|
1290
|
-
}
|
|
1291
|
-
//#region onMulti
|
|
1292
|
-
/**
|
|
1293
|
-
* Allows subscribing to multiple events and calling the callback only when one of, all of, or a subset of the events are emitted, either continuously or only once.
|
|
1294
|
-
* @param options An object or array of objects with the following properties:
|
|
1295
|
-
* `callback` (required) is the function that will be called when the conditions are met.
|
|
1296
|
-
*
|
|
1297
|
-
* 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.
|
|
1298
|
-
* If `signal` is provided, the subscription will be canceled when the given signal is aborted.
|
|
1299
|
-
*
|
|
1300
|
-
* If `oneOf` is used, the callback will be called when any of the matching events are emitted.
|
|
1301
|
-
* 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.
|
|
1302
|
-
* 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.
|
|
1303
|
-
* At least one of `oneOf` or `allOf` must be provided.
|
|
1304
|
-
*
|
|
1305
|
-
* @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.
|
|
1306
|
-
*/
|
|
1307
|
-
onMulti(options) {
|
|
1308
|
-
const allUnsubs = [];
|
|
1309
|
-
const unsubAll = () => {
|
|
1310
|
-
for (const unsub of allUnsubs)
|
|
1311
|
-
unsub();
|
|
1312
|
-
allUnsubs.splice(0, allUnsubs.length);
|
|
1313
|
-
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
|
|
1314
|
-
};
|
|
1315
|
-
for (const opts of Array.isArray(options) ? options : [options]) {
|
|
1316
|
-
const optsWithDefaults = {
|
|
1317
|
-
allOf: [],
|
|
1318
|
-
oneOf: [],
|
|
1319
|
-
once: false,
|
|
1320
|
-
...opts
|
|
1321
|
-
};
|
|
1322
|
-
const {
|
|
1323
|
-
oneOf,
|
|
1324
|
-
allOf,
|
|
1325
|
-
once,
|
|
1326
|
-
signal,
|
|
1327
|
-
callback
|
|
1328
|
-
} = optsWithDefaults;
|
|
1329
|
-
if (signal == null ? void 0 : signal.aborted)
|
|
1330
|
-
return unsubAll;
|
|
1331
|
-
if (oneOf.length === 0 && allOf.length === 0)
|
|
1332
|
-
throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
|
|
1333
|
-
const curEvtUnsubs = [];
|
|
1334
|
-
const checkUnsubAllEvt = (force = false) => {
|
|
1335
|
-
if (!(signal == null ? void 0 : signal.aborted) && !force)
|
|
1336
|
-
return;
|
|
1337
|
-
for (const unsub of curEvtUnsubs)
|
|
1338
|
-
unsub();
|
|
1339
|
-
curEvtUnsubs.splice(0, curEvtUnsubs.length);
|
|
1340
|
-
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
|
|
1341
|
-
};
|
|
1342
|
-
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
1343
|
-
const allOfConditionMet = () => allOf.length === 0 || allOfEmitted.size === allOf.length;
|
|
1344
|
-
for (const event of oneOf) {
|
|
1345
|
-
const unsub = this.events.on(event, ((...args) => {
|
|
1346
|
-
checkUnsubAllEvt();
|
|
1347
|
-
if (allOfConditionMet()) {
|
|
1348
|
-
callback(event, ...args);
|
|
1349
|
-
if (once)
|
|
1350
|
-
checkUnsubAllEvt(true);
|
|
1351
|
-
}
|
|
1352
|
-
}));
|
|
1353
|
-
curEvtUnsubs.push(unsub);
|
|
1354
|
-
}
|
|
1355
|
-
for (const event of allOf) {
|
|
1356
|
-
const unsub = this.events.on(event, ((...args) => {
|
|
1357
|
-
checkUnsubAllEvt();
|
|
1358
|
-
allOfEmitted.add(event);
|
|
1359
|
-
if (allOfConditionMet() && (oneOf.length === 0 || oneOf.includes(event))) {
|
|
1360
|
-
callback(event, ...args);
|
|
1361
|
-
if (once)
|
|
1362
|
-
checkUnsubAllEvt(true);
|
|
1363
|
-
}
|
|
1364
|
-
}));
|
|
1365
|
-
curEvtUnsubs.push(unsub);
|
|
1366
|
-
}
|
|
1367
|
-
allUnsubs.push(() => checkUnsubAllEvt(true));
|
|
1368
|
-
}
|
|
1369
|
-
return unsubAll;
|
|
1370
|
-
}
|
|
1371
|
-
//#region emit
|
|
1372
|
-
/**
|
|
1373
|
-
* Emits an event on this instance.
|
|
1374
|
-
* - ⚠️ Needs `publicEmit` to be set to true in the NanoEmitter constructor or super() call!
|
|
1375
|
-
* @param event The event to emit
|
|
1376
|
-
* @param args The arguments to pass to the event listeners
|
|
1377
|
-
* @returns Returns true if `publicEmit` is true and the event was emitted successfully
|
|
1378
|
-
*/
|
|
1379
|
-
emit(event, ...args) {
|
|
1380
|
-
if (this.emitterOptions.publicEmit) {
|
|
1381
|
-
this.events.emit(event, ...args);
|
|
1382
|
-
return true;
|
|
1383
|
-
}
|
|
1384
|
-
return false;
|
|
1385
|
-
}
|
|
1386
|
-
//#region unsubscribeAll
|
|
1387
|
-
/** Unsubscribes all event listeners from this instance */
|
|
1388
|
-
unsubscribeAll() {
|
|
1389
|
-
for (const unsub of this.eventUnsubscribes)
|
|
1390
|
-
unsub();
|
|
1391
|
-
this.eventUnsubscribes = [];
|
|
1392
|
-
}
|
|
1393
|
-
};
|
|
1394
|
-
|
|
1395
1535
|
// lib/Debouncer.ts
|
|
1396
1536
|
var Debouncer = class extends NanoEmitter {
|
|
1397
1537
|
/**
|
|
@@ -1403,13 +1543,13 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1403
1543
|
super();
|
|
1404
1544
|
this.timeout = timeout;
|
|
1405
1545
|
this.type = type;
|
|
1546
|
+
/** All registered listener functions and the time they were attached */
|
|
1547
|
+
__publicField(this, "listeners", []);
|
|
1548
|
+
/** The currently active timeout */
|
|
1549
|
+
__publicField(this, "activeTimeout");
|
|
1550
|
+
/** The latest queued call */
|
|
1551
|
+
__publicField(this, "queuedCall");
|
|
1406
1552
|
}
|
|
1407
|
-
/** All registered listener functions and the time they were attached */
|
|
1408
|
-
listeners = [];
|
|
1409
|
-
/** The currently active timeout */
|
|
1410
|
-
activeTimeout;
|
|
1411
|
-
/** The latest queued call */
|
|
1412
|
-
queuedCall;
|
|
1413
1553
|
//#region listeners
|
|
1414
1554
|
/** Adds a listener function that will be called on timeout */
|
|
1415
1555
|
addListener(fn) {
|
|
@@ -1496,6 +1636,8 @@ function debounce(fn, timeout = 200, type = "immediate") {
|
|
|
1496
1636
|
return func;
|
|
1497
1637
|
}
|
|
1498
1638
|
|
|
1639
|
+
if(__exports != exports)module.exports = exports;return module.exports}));
|
|
1640
|
+
|
|
1499
1641
|
|
|
1500
1642
|
|
|
1501
1643
|
if (typeof module.exports == "object" && typeof exports == "object") {
|