@sv443-network/coreutils 3.3.0 → 3.4.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 +11 -0
- package/README.md +3 -0
- package/dist/CoreUtils.cjs +46 -9
- 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 +46 -9
- package/dist/CoreUtils.umd.js +499 -578
- package/dist/lib/DataStore.d.ts +2 -2
- package/dist/lib/DataStoreSerializer.d.ts +6 -2
- package/dist/lib/Debouncer.d.ts +3 -3
- package/dist/lib/misc.d.ts +36 -0
- package/package.json +23 -23
package/dist/CoreUtils.umd.js
CHANGED
|
@@ -16,41 +16,13 @@
|
|
|
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};
|
|
20
19
|
"use strict";
|
|
21
20
|
var __create = Object.create;
|
|
22
21
|
var __defProp = Object.defineProperty;
|
|
23
22
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
24
23
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
25
|
-
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
26
24
|
var __getProtoOf = Object.getPrototypeOf;
|
|
27
25
|
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
|
-
};
|
|
54
26
|
var __export = (target, all) => {
|
|
55
27
|
for (var name in all)
|
|
56
28
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -72,27 +44,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
72
44
|
mod
|
|
73
45
|
));
|
|
74
46
|
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
|
-
};
|
|
96
47
|
|
|
97
48
|
// lib/index.ts
|
|
98
49
|
var lib_exports = {};
|
|
@@ -122,6 +73,7 @@ __export(lib_exports, {
|
|
|
122
73
|
consumeGen: () => consumeGen,
|
|
123
74
|
consumeStringGen: () => consumeStringGen,
|
|
124
75
|
createProgressBar: () => createProgressBar,
|
|
76
|
+
createRecurringTask: () => createRecurringTask,
|
|
125
77
|
darkenColor: () => darkenColor,
|
|
126
78
|
debounce: () => debounce,
|
|
127
79
|
decompress: () => decompress,
|
|
@@ -243,7 +195,7 @@ function randRange(...args) {
|
|
|
243
195
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
244
196
|
}
|
|
245
197
|
function roundFixed(num, fractionDigits) {
|
|
246
|
-
const scale =
|
|
198
|
+
const scale = 10 ** fractionDigits;
|
|
247
199
|
return Math.round(num * scale) / scale;
|
|
248
200
|
}
|
|
249
201
|
function valsWithin(a, b, dec = 1, withinRange = 0.5) {
|
|
@@ -307,7 +259,7 @@ function darkenColor(color, percent, upperCase = false) {
|
|
|
307
259
|
if (isHexCol)
|
|
308
260
|
return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
|
|
309
261
|
else if (color.startsWith("rgba"))
|
|
310
|
-
return `rgba(${r}, ${g}, ${b}, ${a
|
|
262
|
+
return `rgba(${r}, ${g}, ${b}, ${a ?? NaN})`;
|
|
311
263
|
else
|
|
312
264
|
return `rgb(${r}, ${g}, ${b})`;
|
|
313
265
|
}
|
|
@@ -341,43 +293,35 @@ function abtoa(buf) {
|
|
|
341
293
|
function atoab(str) {
|
|
342
294
|
return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
|
|
343
295
|
}
|
|
344
|
-
function compress(input, compressionFormat, outputType = "string") {
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
const uintArr = new Uint8Array(yield new Response(comp.readable).arrayBuffer());
|
|
353
|
-
return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
|
|
354
|
-
});
|
|
296
|
+
async function compress(input, compressionFormat, outputType = "string") {
|
|
297
|
+
const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((input == null ? void 0 : input.toString()) ?? String(input));
|
|
298
|
+
const comp = new CompressionStream(compressionFormat);
|
|
299
|
+
const writer = comp.writable.getWriter();
|
|
300
|
+
writer.write(byteArray);
|
|
301
|
+
writer.close();
|
|
302
|
+
const uintArr = new Uint8Array(await new Response(comp.readable).arrayBuffer());
|
|
303
|
+
return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
|
|
355
304
|
}
|
|
356
|
-
function decompress(input, compressionFormat, outputType = "string") {
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
const uintArr = new Uint8Array(yield new Response(decomp.readable).arrayBuffer());
|
|
365
|
-
return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
|
|
366
|
-
});
|
|
305
|
+
async function decompress(input, compressionFormat, outputType = "string") {
|
|
306
|
+
const byteArray = input instanceof Uint8Array ? input : atoab((input == null ? void 0 : input.toString()) ?? String(input));
|
|
307
|
+
const decomp = new DecompressionStream(compressionFormat);
|
|
308
|
+
const writer = decomp.writable.getWriter();
|
|
309
|
+
writer.write(byteArray);
|
|
310
|
+
writer.close();
|
|
311
|
+
const uintArr = new Uint8Array(await new Response(decomp.readable).arrayBuffer());
|
|
312
|
+
return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
|
|
367
313
|
}
|
|
368
|
-
function computeHash(input, algorithm = "SHA-256") {
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
return hashHex;
|
|
380
|
-
});
|
|
314
|
+
async function computeHash(input, algorithm = "SHA-256") {
|
|
315
|
+
let data;
|
|
316
|
+
if (typeof input === "string") {
|
|
317
|
+
const encoder = new TextEncoder();
|
|
318
|
+
data = encoder.encode(input);
|
|
319
|
+
} else
|
|
320
|
+
data = input;
|
|
321
|
+
const hashBuffer = await crypto.subtle.digest(algorithm, data);
|
|
322
|
+
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
323
|
+
const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
324
|
+
return hashHex;
|
|
381
325
|
}
|
|
382
326
|
function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
|
|
383
327
|
if (length < 1)
|
|
@@ -406,9 +350,9 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
|
|
|
406
350
|
|
|
407
351
|
// lib/Errors.ts
|
|
408
352
|
var DatedError = class extends Error {
|
|
353
|
+
date;
|
|
409
354
|
constructor(message, options) {
|
|
410
355
|
super(message, options);
|
|
411
|
-
__publicField(this, "date");
|
|
412
356
|
this.name = this.constructor.name;
|
|
413
357
|
this.date = /* @__PURE__ */ new Date();
|
|
414
358
|
}
|
|
@@ -451,37 +395,34 @@ var NetworkError = class extends DatedError {
|
|
|
451
395
|
};
|
|
452
396
|
|
|
453
397
|
// lib/misc.ts
|
|
454
|
-
function consumeGen(valGen) {
|
|
455
|
-
return
|
|
456
|
-
return yield typeof valGen === "function" ? valGen() : valGen;
|
|
457
|
-
});
|
|
398
|
+
async function consumeGen(valGen) {
|
|
399
|
+
return await (typeof valGen === "function" ? valGen() : valGen);
|
|
458
400
|
}
|
|
459
|
-
function consumeStringGen(strGen) {
|
|
460
|
-
return
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
);
|
|
464
|
-
});
|
|
401
|
+
async function consumeStringGen(strGen) {
|
|
402
|
+
return typeof strGen === "string" ? strGen : String(
|
|
403
|
+
typeof strGen === "function" ? await strGen() : strGen
|
|
404
|
+
);
|
|
465
405
|
}
|
|
466
|
-
function fetchAdvanced(
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
406
|
+
async function fetchAdvanced(input, options = {}) {
|
|
407
|
+
const { timeout = 1e4, signal, ...restOpts } = options;
|
|
408
|
+
const ctl = new AbortController();
|
|
409
|
+
signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
|
|
410
|
+
let sigOpts = {}, id = void 0;
|
|
411
|
+
if (timeout >= 0) {
|
|
412
|
+
id = setTimeout(() => ctl.abort(), timeout);
|
|
413
|
+
sigOpts = { signal: ctl.signal };
|
|
414
|
+
}
|
|
415
|
+
try {
|
|
416
|
+
const res = await fetch(input, {
|
|
417
|
+
...restOpts,
|
|
418
|
+
...sigOpts
|
|
419
|
+
});
|
|
420
|
+
typeof id !== "undefined" && clearTimeout(id);
|
|
421
|
+
return res;
|
|
422
|
+
} catch (err) {
|
|
423
|
+
typeof id !== "undefined" && clearTimeout(id);
|
|
424
|
+
throw new NetworkError("Error while calling fetch", { cause: err });
|
|
425
|
+
}
|
|
485
426
|
}
|
|
486
427
|
function getListLength(listLike, zeroOnInvalid = true) {
|
|
487
428
|
return "length" in listLike ? listLike.length : "size" in listLike ? listLike.size : "count" in listLike ? listLike.count : zeroOnInvalid ? 0 : NaN;
|
|
@@ -496,7 +437,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
|
|
|
496
437
|
});
|
|
497
438
|
}
|
|
498
439
|
function pureObj(obj) {
|
|
499
|
-
return Object.assign(/* @__PURE__ */ Object.create(null), obj
|
|
440
|
+
return Object.assign(/* @__PURE__ */ Object.create(null), obj ?? {});
|
|
500
441
|
}
|
|
501
442
|
function setImmediateInterval(callback, interval, signal) {
|
|
502
443
|
let intervalId;
|
|
@@ -513,12 +454,12 @@ function setImmediateInterval(callback, interval, signal) {
|
|
|
513
454
|
function setImmediateTimeoutLoop(callback, interval, signal) {
|
|
514
455
|
let timeout;
|
|
515
456
|
const cleanup = () => clearTimeout(timeout);
|
|
516
|
-
const loop = () =>
|
|
457
|
+
const loop = async () => {
|
|
517
458
|
if (signal == null ? void 0 : signal.aborted)
|
|
518
459
|
return cleanup();
|
|
519
|
-
|
|
460
|
+
await callback();
|
|
520
461
|
timeout = setTimeout(loop, interval);
|
|
521
|
-
}
|
|
462
|
+
};
|
|
522
463
|
signal == null ? void 0 : signal.addEventListener("abort", cleanup);
|
|
523
464
|
loop();
|
|
524
465
|
}
|
|
@@ -535,16 +476,48 @@ function scheduleExit(code = 0, timeout = 0) {
|
|
|
535
476
|
setTimeout(exit, timeout);
|
|
536
477
|
}
|
|
537
478
|
function getCallStack(asArray, lines = Infinity) {
|
|
538
|
-
var _a;
|
|
539
479
|
if (typeof lines !== "number" || isNaN(lines) || lines < 0)
|
|
540
480
|
throw new TypeError("lines parameter must be a non-negative number");
|
|
541
481
|
try {
|
|
542
|
-
throw new
|
|
482
|
+
throw new CustomError("GetCallStack", "Capturing a stack trace with CoreUtils.getCallStack(). If you see this anywhere, you can safely ignore it.");
|
|
543
483
|
} catch (err) {
|
|
544
|
-
const stack = (
|
|
484
|
+
const stack = (err.stack ?? "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
|
|
545
485
|
return asArray !== false ? stack : stack.join("\n");
|
|
546
486
|
}
|
|
547
487
|
}
|
|
488
|
+
function createRecurringTask(options) {
|
|
489
|
+
var _a;
|
|
490
|
+
let iterations = 0;
|
|
491
|
+
let aborted = false;
|
|
492
|
+
(_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
|
|
493
|
+
aborted = true;
|
|
494
|
+
}, { once: true });
|
|
495
|
+
const runRecurringTask = async (initial = false) => {
|
|
496
|
+
var _a2;
|
|
497
|
+
if (aborted)
|
|
498
|
+
return;
|
|
499
|
+
try {
|
|
500
|
+
if ((options.immediate ?? true) || !initial) {
|
|
501
|
+
iterations++;
|
|
502
|
+
if (await ((_a2 = options.condition) == null ? void 0 : _a2.call(options, iterations - 1)) ?? true) {
|
|
503
|
+
const val = await options.task(iterations - 1);
|
|
504
|
+
if (options.onSuccess)
|
|
505
|
+
await options.onSuccess(val, iterations - 1);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
} catch (err) {
|
|
509
|
+
if (options.onError)
|
|
510
|
+
await options.onError(err, iterations - 1);
|
|
511
|
+
if (options.abortOnError)
|
|
512
|
+
aborted = true;
|
|
513
|
+
if (!options.onError && !options.abortOnError)
|
|
514
|
+
throw err;
|
|
515
|
+
}
|
|
516
|
+
if (!aborted && (typeof options.maxIterations !== "number" || iterations < options.maxIterations))
|
|
517
|
+
setTimeout(runRecurringTask, options.timeout);
|
|
518
|
+
};
|
|
519
|
+
return runRecurringTask(true);
|
|
520
|
+
}
|
|
548
521
|
|
|
549
522
|
// lib/text.ts
|
|
550
523
|
function autoPlural(term, num, pluralType = "auto") {
|
|
@@ -596,9 +569,9 @@ function createProgressBar(percentage, barLength, chars = defaultPbChars) {
|
|
|
596
569
|
}
|
|
597
570
|
function insertValues(input, ...values) {
|
|
598
571
|
return input.replace(/%\d/gm, (match) => {
|
|
599
|
-
var _a
|
|
572
|
+
var _a;
|
|
600
573
|
const argIndex = Number(match.substring(1)) - 1;
|
|
601
|
-
return (
|
|
574
|
+
return (_a = values[argIndex] ?? match) == null ? void 0 : _a.toString();
|
|
602
575
|
});
|
|
603
576
|
}
|
|
604
577
|
function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
|
|
@@ -629,8 +602,7 @@ function secsToTimeStr(seconds) {
|
|
|
629
602
|
].join("");
|
|
630
603
|
}
|
|
631
604
|
function truncStr(input, length, endStr = "...") {
|
|
632
|
-
|
|
633
|
-
const str = (_a = input == null ? void 0 : input.toString()) != null ? _a : String(input);
|
|
605
|
+
const str = (input == null ? void 0 : input.toString()) ?? String(input);
|
|
634
606
|
const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
|
|
635
607
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
636
608
|
}
|
|
@@ -644,26 +616,26 @@ var createNanoEvents = () => ({
|
|
|
644
616
|
},
|
|
645
617
|
events: {},
|
|
646
618
|
on(event, cb) {
|
|
647
|
-
var _a;
|
|
648
619
|
;
|
|
649
|
-
(
|
|
620
|
+
(this.events[event] ||= []).push(cb);
|
|
650
621
|
return () => {
|
|
651
|
-
var
|
|
652
|
-
this.events[event] = (
|
|
622
|
+
var _a;
|
|
623
|
+
this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((i) => cb !== i);
|
|
653
624
|
};
|
|
654
625
|
}
|
|
655
626
|
});
|
|
656
627
|
|
|
657
628
|
// lib/NanoEmitter.ts
|
|
658
629
|
var NanoEmitter = class {
|
|
630
|
+
events = createNanoEvents();
|
|
631
|
+
eventUnsubscribes = [];
|
|
632
|
+
emitterOptions;
|
|
659
633
|
/** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
|
|
660
634
|
constructor(options = {}) {
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
publicEmit: false
|
|
666
|
-
}, options);
|
|
635
|
+
this.emitterOptions = {
|
|
636
|
+
publicEmit: false,
|
|
637
|
+
...options
|
|
638
|
+
};
|
|
667
639
|
}
|
|
668
640
|
//#region on
|
|
669
641
|
/**
|
|
@@ -755,11 +727,12 @@ var NanoEmitter = class {
|
|
|
755
727
|
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
|
|
756
728
|
};
|
|
757
729
|
for (const opts of Array.isArray(options) ? options : [options]) {
|
|
758
|
-
const optsWithDefaults =
|
|
730
|
+
const optsWithDefaults = {
|
|
759
731
|
allOf: [],
|
|
760
732
|
oneOf: [],
|
|
761
|
-
once: false
|
|
762
|
-
|
|
733
|
+
once: false,
|
|
734
|
+
...opts
|
|
735
|
+
};
|
|
763
736
|
const {
|
|
764
737
|
oneOf,
|
|
765
738
|
allOf,
|
|
@@ -836,6 +809,26 @@ var NanoEmitter = class {
|
|
|
836
809
|
// lib/DataStore.ts
|
|
837
810
|
var dsFmtVer = 1;
|
|
838
811
|
var DataStore = class extends NanoEmitter {
|
|
812
|
+
id;
|
|
813
|
+
formatVersion;
|
|
814
|
+
defaultData;
|
|
815
|
+
encodeData;
|
|
816
|
+
decodeData;
|
|
817
|
+
compressionFormat = "deflate-raw";
|
|
818
|
+
memoryCache;
|
|
819
|
+
engine;
|
|
820
|
+
keyPrefix;
|
|
821
|
+
options;
|
|
822
|
+
/**
|
|
823
|
+
* Whether all first-init checks should be done.
|
|
824
|
+
* This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
|
|
825
|
+
* 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.
|
|
826
|
+
*/
|
|
827
|
+
firstInit = true;
|
|
828
|
+
/** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
|
|
829
|
+
cachedData;
|
|
830
|
+
migrations;
|
|
831
|
+
migrateIds = [];
|
|
839
832
|
//#region constructor
|
|
840
833
|
/**
|
|
841
834
|
* Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
|
|
@@ -847,43 +840,22 @@ var DataStore = class extends NanoEmitter {
|
|
|
847
840
|
* @param opts The options for this DataStore instance
|
|
848
841
|
*/
|
|
849
842
|
constructor(opts) {
|
|
850
|
-
var _a, _b, _c;
|
|
851
843
|
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", []);
|
|
872
844
|
this.id = opts.id;
|
|
873
845
|
this.formatVersion = opts.formatVersion;
|
|
874
846
|
this.defaultData = opts.defaultData;
|
|
875
|
-
this.memoryCache =
|
|
847
|
+
this.memoryCache = opts.memoryCache ?? true;
|
|
876
848
|
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
877
849
|
this.migrations = opts.migrations;
|
|
878
850
|
if (opts.migrateIds)
|
|
879
851
|
this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
|
|
880
852
|
this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
|
|
881
|
-
this.keyPrefix =
|
|
853
|
+
this.keyPrefix = opts.keyPrefix ?? "__ds-";
|
|
882
854
|
this.options = opts;
|
|
883
855
|
if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
|
|
884
856
|
this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
|
|
885
857
|
this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
|
|
886
|
-
this.compressionFormat =
|
|
858
|
+
this.compressionFormat = opts.encodeData[0] ?? null;
|
|
887
859
|
} else if (opts.compressionFormat === null) {
|
|
888
860
|
this.encodeData = void 0;
|
|
889
861
|
this.decodeData = void 0;
|
|
@@ -891,12 +863,8 @@ var DataStore = class extends NanoEmitter {
|
|
|
891
863
|
} else {
|
|
892
864
|
const fmt = typeof opts.compressionFormat === "string" ? opts.compressionFormat : "deflate-raw";
|
|
893
865
|
this.compressionFormat = fmt;
|
|
894
|
-
this.encodeData = [fmt, (data) =>
|
|
895
|
-
|
|
896
|
-
})];
|
|
897
|
-
this.decodeData = [fmt, (data) => __async(this, null, function* () {
|
|
898
|
-
return yield decompress(data, fmt, "string");
|
|
899
|
-
})];
|
|
866
|
+
this.encodeData = [fmt, async (data) => await compress(data, fmt, "string")];
|
|
867
|
+
this.decodeData = [fmt, async (data) => await decompress(data, fmt, "string")];
|
|
900
868
|
}
|
|
901
869
|
this.engine.setDataStoreOptions({
|
|
902
870
|
id: this.id,
|
|
@@ -910,65 +878,62 @@ var DataStore = class extends NanoEmitter {
|
|
|
910
878
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
911
879
|
* Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
|
|
912
880
|
*/
|
|
913
|
-
loadData() {
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
const
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
migrateFmt(`
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
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);
|
|
881
|
+
async loadData() {
|
|
882
|
+
try {
|
|
883
|
+
if (this.firstInit) {
|
|
884
|
+
this.firstInit = false;
|
|
885
|
+
const dsVer = Number(await this.engine.getValue("__ds_fmt_ver", 0));
|
|
886
|
+
const oldData = await this.engine.getValue(`_uucfg-${this.id}`, null);
|
|
887
|
+
if (oldData) {
|
|
888
|
+
const oldVer = Number(await this.engine.getValue(`_uucfgver-${this.id}`, NaN));
|
|
889
|
+
const oldEnc = await this.engine.getValue(`_uucfgenc-${this.id}`, null);
|
|
890
|
+
const promises = [];
|
|
891
|
+
const migrateFmt = (oldKey, newKey, value) => {
|
|
892
|
+
promises.push(this.engine.setValue(newKey, value));
|
|
893
|
+
promises.push(this.engine.deleteValue(oldKey));
|
|
894
|
+
};
|
|
895
|
+
migrateFmt(`_uucfg-${this.id}`, `${this.keyPrefix}${this.id}-dat`, oldData);
|
|
896
|
+
if (!isNaN(oldVer))
|
|
897
|
+
migrateFmt(`_uucfgver-${this.id}`, `${this.keyPrefix}${this.id}-ver`, oldVer);
|
|
898
|
+
if (typeof oldEnc === "boolean" || oldEnc === "true" || oldEnc === "false" || typeof oldEnc === "number" || oldEnc === "0" || oldEnc === "1")
|
|
899
|
+
migrateFmt(`_uucfgenc-${this.id}`, `${this.keyPrefix}${this.id}-enf`, [0, "0", true, "true"].includes(oldEnc) ? this.compressionFormat ?? null : null);
|
|
900
|
+
else {
|
|
901
|
+
promises.push(this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat));
|
|
902
|
+
promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
|
|
939
903
|
}
|
|
940
|
-
|
|
941
|
-
yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
904
|
+
await Promise.allSettled(promises);
|
|
942
905
|
}
|
|
943
|
-
if (
|
|
944
|
-
|
|
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;
|
|
906
|
+
if (isNaN(dsVer) || dsVer < dsFmtVer)
|
|
907
|
+
await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
970
908
|
}
|
|
971
|
-
|
|
909
|
+
if (this.migrateIds.length > 0) {
|
|
910
|
+
await this.migrateId(this.migrateIds);
|
|
911
|
+
this.migrateIds = [];
|
|
912
|
+
}
|
|
913
|
+
const storedDataRaw = await this.engine.getValue(`${this.keyPrefix}${this.id}-dat`, null);
|
|
914
|
+
const storedFmtVer = Number(await this.engine.getValue(`${this.keyPrefix}${this.id}-ver`, NaN));
|
|
915
|
+
if (typeof storedDataRaw !== "string" && typeof storedDataRaw !== "object" || storedDataRaw === null || isNaN(storedFmtVer)) {
|
|
916
|
+
await this.saveDefaultData(false);
|
|
917
|
+
const data = this.engine.deepCopy(this.defaultData);
|
|
918
|
+
this.events.emit("loadData", data);
|
|
919
|
+
return data;
|
|
920
|
+
}
|
|
921
|
+
const storedData = storedDataRaw ?? JSON.stringify(this.defaultData);
|
|
922
|
+
const encodingFmt = String(await this.engine.getValue(`${this.keyPrefix}${this.id}-enf`, null));
|
|
923
|
+
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false" && encodingFmt !== "0" && encodingFmt !== "" && encodingFmt !== null;
|
|
924
|
+
let parsed = typeof storedData === "string" ? await this.engine.deserializeData(storedData, isEncoded) : storedData;
|
|
925
|
+
if (storedFmtVer < this.formatVersion && this.migrations)
|
|
926
|
+
parsed = await this.runMigrations(parsed, storedFmtVer);
|
|
927
|
+
const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(parsed) : this.engine.deepCopy(parsed);
|
|
928
|
+
this.events.emit("loadData", result);
|
|
929
|
+
return result;
|
|
930
|
+
} catch (err) {
|
|
931
|
+
const error = err instanceof Error ? err : new Error(String(err));
|
|
932
|
+
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
933
|
+
this.events.emit("error", error);
|
|
934
|
+
await this.saveDefaultData();
|
|
935
|
+
return this.defaultData;
|
|
936
|
+
}
|
|
972
937
|
}
|
|
973
938
|
//#region getData
|
|
974
939
|
/**
|
|
@@ -989,9 +954,9 @@ var DataStore = class extends NanoEmitter {
|
|
|
989
954
|
this.cachedData = data;
|
|
990
955
|
this.events.emit("updateDataSync", dataCopy);
|
|
991
956
|
}
|
|
992
|
-
return new Promise((resolve) =>
|
|
993
|
-
const results =
|
|
994
|
-
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`,
|
|
957
|
+
return new Promise(async (resolve) => {
|
|
958
|
+
const results = await Promise.allSettled([
|
|
959
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(data, this.encodingEnabled())),
|
|
995
960
|
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
|
|
996
961
|
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
997
962
|
]);
|
|
@@ -1003,30 +968,28 @@ var DataStore = class extends NanoEmitter {
|
|
|
1003
968
|
this.events.emit("error", error);
|
|
1004
969
|
}
|
|
1005
970
|
resolve();
|
|
1006
|
-
})
|
|
971
|
+
});
|
|
1007
972
|
}
|
|
1008
973
|
//#region saveDefaultData
|
|
1009
974
|
/**
|
|
1010
975
|
* Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage.
|
|
1011
976
|
* @param emitEvent Whether to emit the `setDefaultData` event - set to `false` to prevent event emission (used internally during initial population in {@linkcode loadData()})
|
|
1012
977
|
*/
|
|
1013
|
-
saveDefaultData(emitEvent = true) {
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
}
|
|
1029
|
-
});
|
|
978
|
+
async saveDefaultData(emitEvent = true) {
|
|
979
|
+
if (this.memoryCache)
|
|
980
|
+
this.cachedData = this.defaultData;
|
|
981
|
+
const results = await Promise.allSettled([
|
|
982
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(this.defaultData, this.encodingEnabled())),
|
|
983
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
|
|
984
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
985
|
+
]);
|
|
986
|
+
if (results.every((r) => r.status === "fulfilled"))
|
|
987
|
+
emitEvent && this.events.emit("setDefaultData", this.defaultData);
|
|
988
|
+
else {
|
|
989
|
+
const error = new Error("Error while saving default data to persistent storage: " + results.map((r) => r.status === "rejected" ? r.reason : null).filter(Boolean).join("; "));
|
|
990
|
+
console.error(error);
|
|
991
|
+
this.events.emit("error", error);
|
|
992
|
+
}
|
|
1030
993
|
}
|
|
1031
994
|
//#region deleteData
|
|
1032
995
|
/**
|
|
@@ -1034,17 +997,15 @@ var DataStore = class extends NanoEmitter {
|
|
|
1034
997
|
* The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
|
|
1035
998
|
* Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
|
|
1036
999
|
*/
|
|
1037
|
-
deleteData() {
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
this.events.emit("deleteData");
|
|
1047
|
-
});
|
|
1000
|
+
async deleteData() {
|
|
1001
|
+
var _a, _b;
|
|
1002
|
+
await Promise.allSettled([
|
|
1003
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-dat`),
|
|
1004
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-ver`),
|
|
1005
|
+
this.engine.deleteValue(`${this.keyPrefix}${this.id}-enf`)
|
|
1006
|
+
]);
|
|
1007
|
+
await ((_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a));
|
|
1008
|
+
this.events.emit("deleteData");
|
|
1048
1009
|
}
|
|
1049
1010
|
//#region encodingEnabled
|
|
1050
1011
|
/** Returns whether encoding and decoding are enabled for this DataStore instance */
|
|
@@ -1059,83 +1020,79 @@ var DataStore = class extends NanoEmitter {
|
|
|
1059
1020
|
*
|
|
1060
1021
|
* 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.
|
|
1061
1022
|
*/
|
|
1062
|
-
runMigrations(oldData, oldFmtVer, resetOnError = true) {
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
}
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
return this.engine.deepCopy(this.defaultData);
|
|
1087
|
-
}
|
|
1023
|
+
async runMigrations(oldData, oldFmtVer, resetOnError = true) {
|
|
1024
|
+
if (!this.migrations)
|
|
1025
|
+
return oldData;
|
|
1026
|
+
let newData = oldData;
|
|
1027
|
+
const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
|
|
1028
|
+
let lastFmtVer = oldFmtVer;
|
|
1029
|
+
for (let i = 0; i < sortedMigrations.length; i++) {
|
|
1030
|
+
const [fmtVer, migrationFunc] = sortedMigrations[i];
|
|
1031
|
+
const ver = Number(fmtVer);
|
|
1032
|
+
if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
|
|
1033
|
+
try {
|
|
1034
|
+
const migRes = migrationFunc(newData);
|
|
1035
|
+
newData = migRes instanceof Promise ? await migRes : migRes;
|
|
1036
|
+
lastFmtVer = oldFmtVer = ver;
|
|
1037
|
+
const isFinal = ver >= this.formatVersion || i === sortedMigrations.length - 1;
|
|
1038
|
+
this.events.emit("migrateData", ver, newData, isFinal);
|
|
1039
|
+
} catch (err) {
|
|
1040
|
+
const migError = new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
|
|
1041
|
+
this.events.emit("migrationError", ver, migError);
|
|
1042
|
+
this.events.emit("error", migError);
|
|
1043
|
+
if (!resetOnError)
|
|
1044
|
+
throw migError;
|
|
1045
|
+
await this.saveDefaultData();
|
|
1046
|
+
return this.engine.deepCopy(this.defaultData);
|
|
1088
1047
|
}
|
|
1089
1048
|
}
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1049
|
+
}
|
|
1050
|
+
await Promise.allSettled([
|
|
1051
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(newData, this.encodingEnabled())),
|
|
1052
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, lastFmtVer),
|
|
1053
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
1054
|
+
]);
|
|
1055
|
+
const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(newData) : this.engine.deepCopy(newData);
|
|
1056
|
+
this.events.emit("updateData", result);
|
|
1057
|
+
return result;
|
|
1099
1058
|
}
|
|
1100
1059
|
//#region migrateId
|
|
1101
1060
|
/**
|
|
1102
1061
|
* Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
|
|
1103
1062
|
* 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.
|
|
1104
1063
|
*/
|
|
1105
|
-
migrateId(oldIds) {
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
const [
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
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`)
|
|
1064
|
+
async migrateId(oldIds) {
|
|
1065
|
+
const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
|
|
1066
|
+
await Promise.all(ids.map(async (id) => {
|
|
1067
|
+
const [data, fmtVer, isEncoded] = await (async () => {
|
|
1068
|
+
const [d, f, e] = await Promise.all([
|
|
1069
|
+
this.engine.getValue(`${this.keyPrefix}${id}-dat`, JSON.stringify(this.defaultData)),
|
|
1070
|
+
this.engine.getValue(`${this.keyPrefix}${id}-ver`, NaN),
|
|
1071
|
+
this.engine.getValue(`${this.keyPrefix}${id}-enf`, null)
|
|
1127
1072
|
]);
|
|
1128
|
-
|
|
1129
|
-
}))
|
|
1130
|
-
|
|
1073
|
+
return [d, Number(f), Boolean(e) && String(e) !== "null"];
|
|
1074
|
+
})();
|
|
1075
|
+
if (data === void 0 || isNaN(fmtVer))
|
|
1076
|
+
return;
|
|
1077
|
+
const parsed = await this.engine.deserializeData(data, isEncoded);
|
|
1078
|
+
await Promise.allSettled([
|
|
1079
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(parsed, this.encodingEnabled())),
|
|
1080
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, fmtVer),
|
|
1081
|
+
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat),
|
|
1082
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-dat`),
|
|
1083
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-ver`),
|
|
1084
|
+
this.engine.deleteValue(`${this.keyPrefix}${id}-enf`)
|
|
1085
|
+
]);
|
|
1086
|
+
this.events.emit("migrateId", id, this.id);
|
|
1087
|
+
}));
|
|
1131
1088
|
}
|
|
1132
1089
|
};
|
|
1133
1090
|
|
|
1134
1091
|
// lib/DataStoreEngine.ts
|
|
1135
1092
|
var DataStoreEngine = class {
|
|
1093
|
+
dataStoreOptions;
|
|
1136
1094
|
// setDataStoreOptions() is called from inside the DataStore constructor to set this value
|
|
1137
1095
|
constructor(options) {
|
|
1138
|
-
__publicField(this, "dataStoreOptions");
|
|
1139
1096
|
if (options)
|
|
1140
1097
|
this.dataStoreOptions = options;
|
|
1141
1098
|
}
|
|
@@ -1145,29 +1102,25 @@ var DataStoreEngine = class {
|
|
|
1145
1102
|
}
|
|
1146
1103
|
//#region serialization api
|
|
1147
1104
|
/** 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 */
|
|
1148
|
-
serializeData(data, useEncoding) {
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
return encRes;
|
|
1159
|
-
});
|
|
1105
|
+
async serializeData(data, useEncoding) {
|
|
1106
|
+
var _a, _b, _c, _d, _e;
|
|
1107
|
+
this.ensureDataStoreOptions();
|
|
1108
|
+
const stringData = JSON.stringify(data);
|
|
1109
|
+
if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
|
|
1110
|
+
return stringData;
|
|
1111
|
+
const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
|
|
1112
|
+
if (encRes instanceof Promise)
|
|
1113
|
+
return await encRes;
|
|
1114
|
+
return encRes;
|
|
1160
1115
|
}
|
|
1161
1116
|
/** Deserializes the given string to a JSON object, optionally decoded with `options.decodeData` if {@linkcode useEncoding} is set to true */
|
|
1162
|
-
deserializeData(data, useEncoding) {
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
return JSON.parse(decRes != null ? decRes : data);
|
|
1170
|
-
});
|
|
1117
|
+
async deserializeData(data, useEncoding) {
|
|
1118
|
+
var _a, _b, _c;
|
|
1119
|
+
this.ensureDataStoreOptions();
|
|
1120
|
+
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;
|
|
1121
|
+
if (decRes instanceof Promise)
|
|
1122
|
+
decRes = await decRes;
|
|
1123
|
+
return JSON.parse(decRes ?? data);
|
|
1171
1124
|
}
|
|
1172
1125
|
//#region misc api
|
|
1173
1126
|
/** Throws an error if the DataStoreOptions are not set or invalid */
|
|
@@ -1185,12 +1138,13 @@ var DataStoreEngine = class {
|
|
|
1185
1138
|
try {
|
|
1186
1139
|
if ("structuredClone" in globalThis)
|
|
1187
1140
|
return structuredClone(obj);
|
|
1188
|
-
} catch
|
|
1141
|
+
} catch {
|
|
1189
1142
|
}
|
|
1190
1143
|
return JSON.parse(JSON.stringify(obj));
|
|
1191
1144
|
}
|
|
1192
1145
|
};
|
|
1193
1146
|
var BrowserStorageEngine = class extends DataStoreEngine {
|
|
1147
|
+
options;
|
|
1194
1148
|
/**
|
|
1195
1149
|
* Creates an instance of `BrowserStorageEngine`.
|
|
1196
1150
|
*
|
|
@@ -1199,40 +1153,36 @@ var BrowserStorageEngine = class extends DataStoreEngine {
|
|
|
1199
1153
|
*/
|
|
1200
1154
|
constructor(options) {
|
|
1201
1155
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
}
|
|
1156
|
+
this.options = {
|
|
1157
|
+
type: "localStorage",
|
|
1158
|
+
...options
|
|
1159
|
+
};
|
|
1206
1160
|
}
|
|
1207
1161
|
//#region storage api
|
|
1208
1162
|
/** Fetches a value from persistent storage */
|
|
1209
|
-
getValue(name, defaultValue) {
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
return typeof val === "undefined" ? defaultValue : val;
|
|
1213
|
-
});
|
|
1163
|
+
async getValue(name, defaultValue) {
|
|
1164
|
+
const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
|
|
1165
|
+
return typeof val === "undefined" ? defaultValue : val;
|
|
1214
1166
|
}
|
|
1215
1167
|
/** Sets a value in persistent storage */
|
|
1216
|
-
setValue(name, value) {
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
globalThis.sessionStorage.setItem(name, String(value));
|
|
1222
|
-
});
|
|
1168
|
+
async setValue(name, value) {
|
|
1169
|
+
if (this.options.type === "localStorage")
|
|
1170
|
+
globalThis.localStorage.setItem(name, String(value));
|
|
1171
|
+
else
|
|
1172
|
+
globalThis.sessionStorage.setItem(name, String(value));
|
|
1223
1173
|
}
|
|
1224
1174
|
/** Deletes a value from persistent storage */
|
|
1225
|
-
deleteValue(name) {
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
globalThis.sessionStorage.removeItem(name);
|
|
1231
|
-
});
|
|
1175
|
+
async deleteValue(name) {
|
|
1176
|
+
if (this.options.type === "localStorage")
|
|
1177
|
+
globalThis.localStorage.removeItem(name);
|
|
1178
|
+
else
|
|
1179
|
+
globalThis.sessionStorage.removeItem(name);
|
|
1232
1180
|
}
|
|
1233
1181
|
};
|
|
1234
1182
|
var fs;
|
|
1235
1183
|
var FileStorageEngine = class extends DataStoreEngine {
|
|
1184
|
+
options;
|
|
1185
|
+
fileAccessQueue = Promise.resolve();
|
|
1236
1186
|
/**
|
|
1237
1187
|
* Creates an instance of `FileStorageEngine`.
|
|
1238
1188
|
*
|
|
@@ -1241,160 +1191,149 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
1241
1191
|
*/
|
|
1242
1192
|
constructor(options) {
|
|
1243
1193
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
}, options);
|
|
1194
|
+
this.options = {
|
|
1195
|
+
filePath: (id) => `.ds-${id}`,
|
|
1196
|
+
...options
|
|
1197
|
+
};
|
|
1249
1198
|
}
|
|
1250
1199
|
//#region json file
|
|
1251
1200
|
/** Reads the file contents */
|
|
1252
|
-
readFile() {
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
}
|
|
1267
|
-
});
|
|
1201
|
+
async readFile() {
|
|
1202
|
+
var _a, _b, _c, _d;
|
|
1203
|
+
this.ensureDataStoreOptions();
|
|
1204
|
+
try {
|
|
1205
|
+
if (!fs)
|
|
1206
|
+
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
1207
|
+
if (!fs)
|
|
1208
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1209
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
1210
|
+
const data = await fs.readFile(path, "utf-8");
|
|
1211
|
+
return data ? JSON.parse(await ((_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, data)) ?? data) : void 0;
|
|
1212
|
+
} catch {
|
|
1213
|
+
return void 0;
|
|
1214
|
+
}
|
|
1268
1215
|
}
|
|
1269
1216
|
/** Overwrites the file contents */
|
|
1270
|
-
writeFile(data) {
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
}
|
|
1285
|
-
});
|
|
1217
|
+
async writeFile(data) {
|
|
1218
|
+
var _a, _b, _c, _d;
|
|
1219
|
+
this.ensureDataStoreOptions();
|
|
1220
|
+
try {
|
|
1221
|
+
if (!fs)
|
|
1222
|
+
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
1223
|
+
if (!fs)
|
|
1224
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1225
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
1226
|
+
await fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
|
|
1227
|
+
await fs.writeFile(path, await ((_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.encodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, JSON.stringify(data))) ?? JSON.stringify(data, void 0, 2), "utf-8");
|
|
1228
|
+
} catch (err) {
|
|
1229
|
+
console.error("Error writing file:", err);
|
|
1230
|
+
}
|
|
1286
1231
|
}
|
|
1287
1232
|
//#region storage api
|
|
1288
1233
|
/** Fetches a value from persistent storage */
|
|
1289
|
-
getValue(name, defaultValue) {
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1234
|
+
async getValue(name, defaultValue) {
|
|
1235
|
+
const data = await this.readFile();
|
|
1236
|
+
if (!data)
|
|
1237
|
+
return defaultValue;
|
|
1238
|
+
const value = data == null ? void 0 : data[name];
|
|
1239
|
+
if (typeof value === "undefined")
|
|
1240
|
+
return defaultValue;
|
|
1241
|
+
if (typeof defaultValue === "string") {
|
|
1242
|
+
if (typeof value === "object" && value !== null)
|
|
1243
|
+
return JSON.stringify(value);
|
|
1244
|
+
if (typeof value === "string")
|
|
1245
|
+
return value;
|
|
1246
|
+
return String(value);
|
|
1247
|
+
}
|
|
1248
|
+
if (typeof value === "string") {
|
|
1249
|
+
try {
|
|
1250
|
+
const parsed = JSON.parse(value);
|
|
1251
|
+
return parsed;
|
|
1252
|
+
} catch {
|
|
1296
1253
|
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);
|
|
1303
1254
|
}
|
|
1255
|
+
}
|
|
1256
|
+
return value;
|
|
1257
|
+
}
|
|
1258
|
+
/** Sets a value in persistent storage */
|
|
1259
|
+
async setValue(name, value) {
|
|
1260
|
+
this.fileAccessQueue = this.fileAccessQueue.then(async () => {
|
|
1261
|
+
let data = await this.readFile();
|
|
1262
|
+
if (!data)
|
|
1263
|
+
data = {};
|
|
1264
|
+
let storeVal = value;
|
|
1304
1265
|
if (typeof value === "string") {
|
|
1305
1266
|
try {
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1267
|
+
if (value.startsWith("{") || value.startsWith("[")) {
|
|
1268
|
+
const parsed = JSON.parse(value);
|
|
1269
|
+
if (typeof parsed === "object" && parsed !== null)
|
|
1270
|
+
storeVal = parsed;
|
|
1271
|
+
}
|
|
1272
|
+
} catch {
|
|
1310
1273
|
}
|
|
1311
1274
|
}
|
|
1312
|
-
|
|
1275
|
+
data[name] = storeVal;
|
|
1276
|
+
await this.writeFile(data);
|
|
1277
|
+
}).catch((err) => {
|
|
1278
|
+
console.error("Error in setValue:", err);
|
|
1279
|
+
throw err;
|
|
1313
1280
|
});
|
|
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
|
-
});
|
|
1281
|
+
await this.fileAccessQueue.catch(() => {
|
|
1341
1282
|
});
|
|
1342
1283
|
}
|
|
1343
1284
|
/** Deletes a value from persistent storage */
|
|
1344
|
-
deleteValue(name) {
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
yield this.fileAccessQueue.catch(() => {
|
|
1357
|
-
});
|
|
1285
|
+
async deleteValue(name) {
|
|
1286
|
+
this.fileAccessQueue = this.fileAccessQueue.then(async () => {
|
|
1287
|
+
const data = await this.readFile();
|
|
1288
|
+
if (!data)
|
|
1289
|
+
return;
|
|
1290
|
+
delete data[name];
|
|
1291
|
+
await this.writeFile(data);
|
|
1292
|
+
}).catch((err) => {
|
|
1293
|
+
console.error("Error in deleteValue:", err);
|
|
1294
|
+
throw err;
|
|
1295
|
+
});
|
|
1296
|
+
await this.fileAccessQueue.catch(() => {
|
|
1358
1297
|
});
|
|
1359
1298
|
}
|
|
1360
1299
|
/** Deletes the file that contains the data of this DataStore. */
|
|
1361
|
-
deleteStorage() {
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
}
|
|
1375
|
-
});
|
|
1300
|
+
async deleteStorage() {
|
|
1301
|
+
var _a;
|
|
1302
|
+
this.ensureDataStoreOptions();
|
|
1303
|
+
try {
|
|
1304
|
+
if (!fs)
|
|
1305
|
+
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
1306
|
+
if (!fs)
|
|
1307
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
1308
|
+
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
|
|
1309
|
+
return await fs.unlink(path);
|
|
1310
|
+
} catch (err) {
|
|
1311
|
+
console.error("Error deleting file:", err);
|
|
1312
|
+
}
|
|
1376
1313
|
}
|
|
1377
1314
|
};
|
|
1378
1315
|
|
|
1379
1316
|
// lib/DataStoreSerializer.ts
|
|
1380
1317
|
var DataStoreSerializer = class _DataStoreSerializer {
|
|
1318
|
+
stores;
|
|
1319
|
+
options;
|
|
1381
1320
|
constructor(stores, options = {}) {
|
|
1382
|
-
__publicField(this, "stores");
|
|
1383
|
-
__publicField(this, "options");
|
|
1384
1321
|
if (!crypto || !crypto.subtle)
|
|
1385
1322
|
throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
|
|
1386
1323
|
this.stores = stores;
|
|
1387
|
-
this.options =
|
|
1324
|
+
this.options = {
|
|
1388
1325
|
addChecksum: true,
|
|
1389
1326
|
ensureIntegrity: true,
|
|
1390
|
-
remapIds: {}
|
|
1391
|
-
|
|
1327
|
+
remapIds: {},
|
|
1328
|
+
...options
|
|
1329
|
+
};
|
|
1392
1330
|
}
|
|
1393
|
-
/**
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1331
|
+
/**
|
|
1332
|
+
* Calculates the checksum of a string. Uses {@linkcode computeHash()} with SHA-256 and digests as a hex string by default.
|
|
1333
|
+
* Override this in a subclass if a custom checksum method is needed.
|
|
1334
|
+
*/
|
|
1335
|
+
async calcChecksum(input) {
|
|
1336
|
+
return computeHash(input, "SHA-256");
|
|
1398
1337
|
}
|
|
1399
1338
|
/**
|
|
1400
1339
|
* Serializes only a subset of the data stores into a string.
|
|
@@ -1402,80 +1341,72 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1402
1341
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1403
1342
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1404
1343
|
*/
|
|
1405
|
-
serializePartial(stores, useEncoding = true, stringified = true) {
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
return stringified ? JSON.stringify(serData) : serData;
|
|
1423
|
-
});
|
|
1344
|
+
async serializePartial(stores, useEncoding = true, stringified = true) {
|
|
1345
|
+
var _a;
|
|
1346
|
+
const serData = [];
|
|
1347
|
+
const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
|
|
1348
|
+
for (const storeInst of filteredStores) {
|
|
1349
|
+
const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
|
|
1350
|
+
const rawData = storeInst.memoryCache ? storeInst.getData() : await storeInst.loadData();
|
|
1351
|
+
const data = encoded ? await storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
|
|
1352
|
+
serData.push({
|
|
1353
|
+
id: storeInst.id,
|
|
1354
|
+
data,
|
|
1355
|
+
formatVersion: storeInst.formatVersion,
|
|
1356
|
+
encoded,
|
|
1357
|
+
checksum: this.options.addChecksum ? await this.calcChecksum(data) : void 0
|
|
1358
|
+
});
|
|
1359
|
+
}
|
|
1360
|
+
return stringified ? JSON.stringify(serData) : serData;
|
|
1424
1361
|
}
|
|
1425
1362
|
/**
|
|
1426
1363
|
* Serializes the data stores into a string.
|
|
1427
1364
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1428
1365
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1429
1366
|
*/
|
|
1430
|
-
serialize(useEncoding = true, stringified = true) {
|
|
1431
|
-
return
|
|
1432
|
-
return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
|
|
1433
|
-
});
|
|
1367
|
+
async serialize(useEncoding = true, stringified = true) {
|
|
1368
|
+
return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
|
|
1434
1369
|
}
|
|
1435
1370
|
/**
|
|
1436
1371
|
* Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
|
|
1437
1372
|
* Also triggers the migration process if the data format has changed.
|
|
1438
1373
|
*/
|
|
1439
|
-
deserializePartial(stores, data) {
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
|
|
1374
|
+
async deserializePartial(stores, data) {
|
|
1375
|
+
const deserStores = typeof data === "string" ? JSON.parse(data) : data;
|
|
1376
|
+
if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
|
|
1377
|
+
throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
|
|
1378
|
+
const resolveStoreId = (id) => {
|
|
1379
|
+
var _a;
|
|
1380
|
+
return ((_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) ?? id;
|
|
1381
|
+
};
|
|
1382
|
+
const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
|
|
1383
|
+
for (const storeData of deserStores) {
|
|
1384
|
+
const effectiveId = resolveStoreId(storeData.id);
|
|
1385
|
+
if (!matchesFilter(effectiveId))
|
|
1386
|
+
continue;
|
|
1387
|
+
const storeInst = this.stores.find((s) => s.id === effectiveId);
|
|
1388
|
+
if (!storeInst)
|
|
1389
|
+
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.`);
|
|
1390
|
+
if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
|
|
1391
|
+
const checksum = await this.calcChecksum(storeData.data);
|
|
1392
|
+
if (checksum !== storeData.checksum)
|
|
1393
|
+
throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
|
|
1460
1394
|
Expected: ${storeData.checksum}
|
|
1461
1395
|
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));
|
|
1468
1396
|
}
|
|
1469
|
-
|
|
1397
|
+
const decodedData = storeData.encoded && storeInst.encodingEnabled() ? await storeInst.decodeData[1](storeData.data) : storeData.data;
|
|
1398
|
+
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1399
|
+
await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1400
|
+
else
|
|
1401
|
+
await storeInst.setData(JSON.parse(decodedData));
|
|
1402
|
+
}
|
|
1470
1403
|
}
|
|
1471
1404
|
/**
|
|
1472
1405
|
* Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
|
|
1473
1406
|
* Also triggers the migration process if the data format has changed.
|
|
1474
1407
|
*/
|
|
1475
|
-
deserialize(data) {
|
|
1476
|
-
return
|
|
1477
|
-
return this.deserializePartial(this.stores.map((s) => s.id), data);
|
|
1478
|
-
});
|
|
1408
|
+
async deserialize(data) {
|
|
1409
|
+
return this.deserializePartial(this.stores.map((s) => s.id), data);
|
|
1479
1410
|
}
|
|
1480
1411
|
/**
|
|
1481
1412
|
* Loads the persistent data of the DataStore instances into the in-memory cache.
|
|
@@ -1483,40 +1414,32 @@ Has: ${checksum}`);
|
|
|
1483
1414
|
* @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
|
|
1484
1415
|
* @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
|
|
1485
1416
|
*/
|
|
1486
|
-
loadStoresData(stores) {
|
|
1487
|
-
return
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
};
|
|
1494
|
-
}))
|
|
1495
|
-
);
|
|
1496
|
-
});
|
|
1417
|
+
async loadStoresData(stores) {
|
|
1418
|
+
return Promise.allSettled(
|
|
1419
|
+
this.getStoresFiltered(stores).map(async (store) => ({
|
|
1420
|
+
id: store.id,
|
|
1421
|
+
data: await store.loadData()
|
|
1422
|
+
}))
|
|
1423
|
+
);
|
|
1497
1424
|
}
|
|
1498
1425
|
/**
|
|
1499
1426
|
* Resets the persistent and in-memory data of the DataStore instances to their default values.
|
|
1500
1427
|
* @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
|
|
1501
1428
|
*/
|
|
1502
|
-
resetStoresData(stores) {
|
|
1503
|
-
return
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
);
|
|
1507
|
-
});
|
|
1429
|
+
async resetStoresData(stores) {
|
|
1430
|
+
return Promise.allSettled(
|
|
1431
|
+
this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
|
|
1432
|
+
);
|
|
1508
1433
|
}
|
|
1509
1434
|
/**
|
|
1510
1435
|
* Deletes the persistent data of the DataStore instances.
|
|
1511
1436
|
* Leaves the in-memory data untouched.
|
|
1512
1437
|
* @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
|
|
1513
1438
|
*/
|
|
1514
|
-
deleteStoresData(stores) {
|
|
1515
|
-
return
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
);
|
|
1519
|
-
});
|
|
1439
|
+
async deleteStoresData(stores) {
|
|
1440
|
+
return Promise.allSettled(
|
|
1441
|
+
this.getStoresFiltered(stores).map((store) => store.deleteData())
|
|
1442
|
+
);
|
|
1520
1443
|
}
|
|
1521
1444
|
/** Checks if a given value is an array of SerializedDataStore objects */
|
|
1522
1445
|
static isSerializedDataStoreObjArray(obj) {
|
|
@@ -1539,17 +1462,17 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1539
1462
|
* @param timeout Timeout in milliseconds between letting through calls - defaults to 200
|
|
1540
1463
|
* @param type The edge type to use for the debouncer - see {@linkcode DebouncerType} for details or [the documentation for an explanation and diagram](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#debouncer) - defaults to "immediate"
|
|
1541
1464
|
*/
|
|
1542
|
-
constructor(timeout = 200, type = "immediate") {
|
|
1543
|
-
super();
|
|
1465
|
+
constructor(timeout = 200, type = "immediate", nanoEmitterOptions) {
|
|
1466
|
+
super(nanoEmitterOptions);
|
|
1544
1467
|
this.timeout = timeout;
|
|
1545
1468
|
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");
|
|
1552
1469
|
}
|
|
1470
|
+
/** All registered listener functions and the time they were attached */
|
|
1471
|
+
listeners = [];
|
|
1472
|
+
/** The currently active timeout */
|
|
1473
|
+
activeTimeout;
|
|
1474
|
+
/** The latest queued call */
|
|
1475
|
+
queuedCall;
|
|
1553
1476
|
//#region listeners
|
|
1554
1477
|
/** Adds a listener function that will be called on timeout */
|
|
1555
1478
|
addListener(fn) {
|
|
@@ -1571,7 +1494,7 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1571
1494
|
//#region timeout
|
|
1572
1495
|
/** Sets the timeout for the debouncer */
|
|
1573
1496
|
setTimeout(timeout) {
|
|
1574
|
-
this.emit("change", this.timeout = timeout, this.type);
|
|
1497
|
+
this.events.emit("change", this.timeout = timeout, this.type);
|
|
1575
1498
|
}
|
|
1576
1499
|
/** Returns the current timeout */
|
|
1577
1500
|
getTimeout() {
|
|
@@ -1584,7 +1507,7 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1584
1507
|
//#region type
|
|
1585
1508
|
/** Sets the edge type for the debouncer */
|
|
1586
1509
|
setType(type) {
|
|
1587
|
-
this.emit("change", this.timeout, this.type = type);
|
|
1510
|
+
this.events.emit("change", this.timeout, this.type = type);
|
|
1588
1511
|
}
|
|
1589
1512
|
/** Returns the current edge type */
|
|
1590
1513
|
getType() {
|
|
@@ -1595,7 +1518,7 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1595
1518
|
call(...args) {
|
|
1596
1519
|
const cl = (...a) => {
|
|
1597
1520
|
this.queuedCall = void 0;
|
|
1598
|
-
this.emit("call", ...a);
|
|
1521
|
+
this.events.emit("call", ...a);
|
|
1599
1522
|
this.listeners.forEach((l) => l.call(this, ...a));
|
|
1600
1523
|
};
|
|
1601
1524
|
const setRepeatTimeout = () => {
|
|
@@ -1628,16 +1551,14 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1628
1551
|
}
|
|
1629
1552
|
}
|
|
1630
1553
|
};
|
|
1631
|
-
function debounce(fn, timeout = 200, type = "immediate") {
|
|
1632
|
-
const debouncer = new Debouncer(timeout, type);
|
|
1554
|
+
function debounce(fn, timeout = 200, type = "immediate", nanoEmitterOptions) {
|
|
1555
|
+
const debouncer = new Debouncer(timeout, type, nanoEmitterOptions);
|
|
1633
1556
|
debouncer.addListener(fn);
|
|
1634
1557
|
const func = ((...args) => debouncer.call(...args));
|
|
1635
1558
|
func.debouncer = debouncer;
|
|
1636
1559
|
return func;
|
|
1637
1560
|
}
|
|
1638
1561
|
|
|
1639
|
-
if(__exports != exports)module.exports = exports;return module.exports}));
|
|
1640
|
-
|
|
1641
1562
|
|
|
1642
1563
|
|
|
1643
1564
|
if (typeof module.exports == "object" && typeof exports == "object") {
|