@sv443-network/coreutils 3.2.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 +23 -0
- package/dist/CoreUtils.cjs +249 -225
- 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 +249 -225
- package/dist/CoreUtils.umd.js +764 -792
- package/dist/lib/DataStore.d.ts +32 -4
- package/package.json +1 -1
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,34 +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
|
-
|
|
588
|
-
|
|
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
|
|
589
813
|
/**
|
|
590
|
-
*
|
|
591
|
-
*
|
|
592
|
-
*
|
|
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
|
|
593
819
|
*/
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
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 {
|
|
599
839
|
//#region constructor
|
|
600
840
|
/**
|
|
601
841
|
* Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
|
|
@@ -607,21 +847,43 @@ var DataStore = class {
|
|
|
607
847
|
* @param opts The options for this DataStore instance
|
|
608
848
|
*/
|
|
609
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", []);
|
|
610
872
|
this.id = opts.id;
|
|
611
873
|
this.formatVersion = opts.formatVersion;
|
|
612
874
|
this.defaultData = opts.defaultData;
|
|
613
|
-
this.memoryCache = opts.memoryCache
|
|
875
|
+
this.memoryCache = (_a = opts.memoryCache) != null ? _a : true;
|
|
614
876
|
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
615
877
|
this.migrations = opts.migrations;
|
|
616
878
|
if (opts.migrateIds)
|
|
617
879
|
this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
|
|
618
880
|
this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
|
|
619
|
-
this.keyPrefix = opts.keyPrefix
|
|
881
|
+
this.keyPrefix = (_b = opts.keyPrefix) != null ? _b : "__ds-";
|
|
620
882
|
this.options = opts;
|
|
621
883
|
if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
|
|
622
884
|
this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
|
|
623
885
|
this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
|
|
624
|
-
this.compressionFormat = opts.encodeData[0]
|
|
886
|
+
this.compressionFormat = (_c = opts.encodeData[0]) != null ? _c : null;
|
|
625
887
|
} else if (opts.compressionFormat === null) {
|
|
626
888
|
this.encodeData = void 0;
|
|
627
889
|
this.decodeData = void 0;
|
|
@@ -629,8 +891,12 @@ var DataStore = class {
|
|
|
629
891
|
} else {
|
|
630
892
|
const fmt = typeof opts.compressionFormat === "string" ? opts.compressionFormat : "deflate-raw";
|
|
631
893
|
this.compressionFormat = fmt;
|
|
632
|
-
this.encodeData = [fmt,
|
|
633
|
-
|
|
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
|
+
})];
|
|
634
900
|
}
|
|
635
901
|
this.engine.setDataStoreOptions({
|
|
636
902
|
id: this.id,
|
|
@@ -644,66 +910,65 @@ var DataStore = class {
|
|
|
644
910
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
645
911
|
* Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
|
|
646
912
|
*/
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
const
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
promises
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
migrateFmt(`
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
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);
|
|
669
939
|
}
|
|
670
|
-
|
|
940
|
+
if (isNaN(dsVer) || dsVer < dsFmtVer)
|
|
941
|
+
yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
671
942
|
}
|
|
672
|
-
if (
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
this.
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
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;
|
|
692
970
|
}
|
|
693
|
-
|
|
694
|
-
if (storedFmtVer < this.formatVersion && this.migrations)
|
|
695
|
-
parsed = await this.runMigrations(parsed, storedFmtVer);
|
|
696
|
-
if (saveData)
|
|
697
|
-
await this.setData(parsed);
|
|
698
|
-
if (this.memoryCache)
|
|
699
|
-
return this.cachedData = this.engine.deepCopy(parsed);
|
|
700
|
-
else
|
|
701
|
-
return this.engine.deepCopy(parsed);
|
|
702
|
-
} catch (err) {
|
|
703
|
-
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
704
|
-
await this.saveDefaultData();
|
|
705
|
-
return this.defaultData;
|
|
706
|
-
}
|
|
971
|
+
});
|
|
707
972
|
}
|
|
708
973
|
//#region getData
|
|
709
974
|
/**
|
|
@@ -719,27 +984,49 @@ var DataStore = class {
|
|
|
719
984
|
//#region setData
|
|
720
985
|
/** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
|
|
721
986
|
setData(data) {
|
|
722
|
-
|
|
987
|
+
const dataCopy = this.engine.deepCopy(data);
|
|
988
|
+
if (this.memoryCache) {
|
|
723
989
|
this.cachedData = data;
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
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())),
|
|
727
995
|
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
|
|
728
996
|
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
|
|
729
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
|
+
}
|
|
730
1005
|
resolve();
|
|
731
|
-
});
|
|
1006
|
+
}));
|
|
732
1007
|
}
|
|
733
1008
|
//#region saveDefaultData
|
|
734
|
-
/**
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
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
|
+
});
|
|
743
1030
|
}
|
|
744
1031
|
//#region deleteData
|
|
745
1032
|
/**
|
|
@@ -747,14 +1034,17 @@ var DataStore = class {
|
|
|
747
1034
|
* The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
|
|
748
1035
|
* Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
|
|
749
1036
|
*/
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
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
|
+
});
|
|
758
1048
|
}
|
|
759
1049
|
//#region encodingEnabled
|
|
760
1050
|
/** Returns whether encoding and decoding are enabled for this DataStore instance */
|
|
@@ -769,73 +1059,83 @@ var DataStore = class {
|
|
|
769
1059
|
*
|
|
770
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.
|
|
771
1061
|
*/
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
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
|
+
}
|
|
790
1088
|
}
|
|
791
1089
|
}
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
return
|
|
800
|
-
|
|
801
|
-
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
|
+
});
|
|
802
1099
|
}
|
|
803
1100
|
//#region migrateId
|
|
804
1101
|
/**
|
|
805
1102
|
* Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
|
|
806
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.
|
|
807
1104
|
*/
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
const [
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
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`)
|
|
816
1127
|
]);
|
|
817
|
-
|
|
818
|
-
})
|
|
819
|
-
|
|
820
|
-
return;
|
|
821
|
-
const parsed = await this.engine.deserializeData(data, isEncoded);
|
|
822
|
-
await Promise.allSettled([
|
|
823
|
-
this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(parsed, this.encodingEnabled())),
|
|
824
|
-
this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, fmtVer),
|
|
825
|
-
this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat),
|
|
826
|
-
this.engine.deleteValue(`${this.keyPrefix}${id}-dat`),
|
|
827
|
-
this.engine.deleteValue(`${this.keyPrefix}${id}-ver`),
|
|
828
|
-
this.engine.deleteValue(`${this.keyPrefix}${id}-enf`)
|
|
829
|
-
]);
|
|
830
|
-
}));
|
|
1128
|
+
this.events.emit("migrateId", id, this.id);
|
|
1129
|
+
})));
|
|
1130
|
+
});
|
|
831
1131
|
}
|
|
832
1132
|
};
|
|
833
1133
|
|
|
834
1134
|
// lib/DataStoreEngine.ts
|
|
835
1135
|
var DataStoreEngine = class {
|
|
836
|
-
dataStoreOptions;
|
|
837
1136
|
// setDataStoreOptions() is called from inside the DataStore constructor to set this value
|
|
838
1137
|
constructor(options) {
|
|
1138
|
+
__publicField(this, "dataStoreOptions");
|
|
839
1139
|
if (options)
|
|
840
1140
|
this.dataStoreOptions = options;
|
|
841
1141
|
}
|
|
@@ -845,25 +1145,29 @@ var DataStoreEngine = class {
|
|
|
845
1145
|
}
|
|
846
1146
|
//#region serialization api
|
|
847
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 */
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
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
|
+
});
|
|
858
1160
|
}
|
|
859
1161
|
/** Deserializes the given string to a JSON object, optionally decoded with `options.decodeData` if {@linkcode useEncoding} is set to true */
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
decRes
|
|
866
|
-
|
|
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
|
+
});
|
|
867
1171
|
}
|
|
868
1172
|
//#region misc api
|
|
869
1173
|
/** Throws an error if the DataStoreOptions are not set or invalid */
|
|
@@ -881,13 +1185,12 @@ var DataStoreEngine = class {
|
|
|
881
1185
|
try {
|
|
882
1186
|
if ("structuredClone" in globalThis)
|
|
883
1187
|
return structuredClone(obj);
|
|
884
|
-
} catch {
|
|
1188
|
+
} catch (e) {
|
|
885
1189
|
}
|
|
886
1190
|
return JSON.parse(JSON.stringify(obj));
|
|
887
1191
|
}
|
|
888
1192
|
};
|
|
889
1193
|
var BrowserStorageEngine = class extends DataStoreEngine {
|
|
890
|
-
options;
|
|
891
1194
|
/**
|
|
892
1195
|
* Creates an instance of `BrowserStorageEngine`.
|
|
893
1196
|
*
|
|
@@ -896,36 +1199,40 @@ var BrowserStorageEngine = class extends DataStoreEngine {
|
|
|
896
1199
|
*/
|
|
897
1200
|
constructor(options) {
|
|
898
1201
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
899
|
-
this
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
};
|
|
1202
|
+
__publicField(this, "options");
|
|
1203
|
+
this.options = __spreadValues({
|
|
1204
|
+
type: "localStorage"
|
|
1205
|
+
}, options);
|
|
903
1206
|
}
|
|
904
1207
|
//#region storage api
|
|
905
1208
|
/** Fetches a value from persistent storage */
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
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
|
+
});
|
|
909
1214
|
}
|
|
910
1215
|
/** Sets a value in persistent storage */
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
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
|
+
});
|
|
916
1223
|
}
|
|
917
1224
|
/** Deletes a value from persistent storage */
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
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
|
+
});
|
|
923
1232
|
}
|
|
924
1233
|
};
|
|
925
1234
|
var fs;
|
|
926
1235
|
var FileStorageEngine = class extends DataStoreEngine {
|
|
927
|
-
options;
|
|
928
|
-
fileAccessQueue = Promise.resolve();
|
|
929
1236
|
/**
|
|
930
1237
|
* Creates an instance of `FileStorageEngine`.
|
|
931
1238
|
*
|
|
@@ -934,146 +1241,160 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
934
1241
|
*/
|
|
935
1242
|
constructor(options) {
|
|
936
1243
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
937
|
-
this
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
1244
|
+
__publicField(this, "options");
|
|
1245
|
+
__publicField(this, "fileAccessQueue", Promise.resolve());
|
|
1246
|
+
this.options = __spreadValues({
|
|
1247
|
+
filePath: (id) => `.ds-${id}`
|
|
1248
|
+
}, options);
|
|
941
1249
|
}
|
|
942
1250
|
//#region json file
|
|
943
1251
|
/** Reads the file contents */
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
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
|
+
});
|
|
958
1268
|
}
|
|
959
1269
|
/** Overwrites the file contents */
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
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
|
+
});
|
|
974
1286
|
}
|
|
975
1287
|
//#region storage api
|
|
976
1288
|
/** Fetches a value from persistent storage */
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
const value = data == null ? void 0 : data[name];
|
|
982
|
-
if (typeof value === "undefined")
|
|
983
|
-
return defaultValue;
|
|
984
|
-
if (typeof defaultValue === "string") {
|
|
985
|
-
if (typeof value === "object" && value !== null)
|
|
986
|
-
return JSON.stringify(value);
|
|
987
|
-
if (typeof value === "string")
|
|
988
|
-
return value;
|
|
989
|
-
return String(value);
|
|
990
|
-
}
|
|
991
|
-
if (typeof value === "string") {
|
|
992
|
-
try {
|
|
993
|
-
const parsed = JSON.parse(value);
|
|
994
|
-
return parsed;
|
|
995
|
-
} catch {
|
|
1289
|
+
getValue(name, defaultValue) {
|
|
1290
|
+
return __async(this, null, function* () {
|
|
1291
|
+
const data = yield this.readFile();
|
|
1292
|
+
if (!data)
|
|
996
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);
|
|
997
1303
|
}
|
|
998
|
-
}
|
|
999
|
-
return value;
|
|
1000
|
-
}
|
|
1001
|
-
/** Sets a value in persistent storage */
|
|
1002
|
-
async setValue(name, value) {
|
|
1003
|
-
this.fileAccessQueue = this.fileAccessQueue.then(async () => {
|
|
1004
|
-
let data = await this.readFile();
|
|
1005
|
-
if (!data)
|
|
1006
|
-
data = {};
|
|
1007
|
-
let storeVal = value;
|
|
1008
1304
|
if (typeof value === "string") {
|
|
1009
1305
|
try {
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
}
|
|
1015
|
-
} catch {
|
|
1306
|
+
const parsed = JSON.parse(value);
|
|
1307
|
+
return parsed;
|
|
1308
|
+
} catch (e) {
|
|
1309
|
+
return defaultValue;
|
|
1016
1310
|
}
|
|
1017
1311
|
}
|
|
1018
|
-
|
|
1019
|
-
await this.writeFile(data);
|
|
1020
|
-
}).catch((err) => {
|
|
1021
|
-
console.error("Error in setValue:", err);
|
|
1022
|
-
throw err;
|
|
1312
|
+
return value;
|
|
1023
1313
|
});
|
|
1024
|
-
|
|
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
|
+
});
|
|
1025
1341
|
});
|
|
1026
1342
|
}
|
|
1027
1343
|
/** Deletes a value from persistent storage */
|
|
1028
|
-
|
|
1029
|
-
this
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
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
|
+
});
|
|
1040
1358
|
});
|
|
1041
1359
|
}
|
|
1042
1360
|
/** Deletes the file that contains the data of this DataStore. */
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
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
|
+
});
|
|
1056
1376
|
}
|
|
1057
1377
|
};
|
|
1058
1378
|
|
|
1059
1379
|
// lib/DataStoreSerializer.ts
|
|
1060
1380
|
var DataStoreSerializer = class _DataStoreSerializer {
|
|
1061
|
-
stores;
|
|
1062
|
-
options;
|
|
1063
1381
|
constructor(stores, options = {}) {
|
|
1382
|
+
__publicField(this, "stores");
|
|
1383
|
+
__publicField(this, "options");
|
|
1064
1384
|
if (!crypto || !crypto.subtle)
|
|
1065
1385
|
throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
|
|
1066
1386
|
this.stores = stores;
|
|
1067
|
-
this.options = {
|
|
1387
|
+
this.options = __spreadValues({
|
|
1068
1388
|
addChecksum: true,
|
|
1069
1389
|
ensureIntegrity: true,
|
|
1070
|
-
remapIds: {}
|
|
1071
|
-
|
|
1072
|
-
};
|
|
1390
|
+
remapIds: {}
|
|
1391
|
+
}, options);
|
|
1073
1392
|
}
|
|
1074
1393
|
/** Calculates the checksum of a string */
|
|
1075
|
-
|
|
1076
|
-
return
|
|
1394
|
+
calcChecksum(input) {
|
|
1395
|
+
return __async(this, null, function* () {
|
|
1396
|
+
return computeHash(input, "SHA-256");
|
|
1397
|
+
});
|
|
1077
1398
|
}
|
|
1078
1399
|
/**
|
|
1079
1400
|
* Serializes only a subset of the data stores into a string.
|
|
@@ -1081,72 +1402,80 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
1081
1402
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1082
1403
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1083
1404
|
*/
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
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
|
+
});
|
|
1101
1424
|
}
|
|
1102
1425
|
/**
|
|
1103
1426
|
* Serializes the data stores into a string.
|
|
1104
1427
|
* @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
|
|
1105
1428
|
* @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
|
|
1106
1429
|
*/
|
|
1107
|
-
|
|
1108
|
-
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
|
+
});
|
|
1109
1434
|
}
|
|
1110
1435
|
/**
|
|
1111
1436
|
* Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
|
|
1112
1437
|
* Also triggers the migration process if the data format has changed.
|
|
1113
1438
|
*/
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
const
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
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}"!
|
|
1134
1460
|
Expected: ${storeData.checksum}
|
|
1135
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));
|
|
1136
1468
|
}
|
|
1137
|
-
|
|
1138
|
-
if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
|
|
1139
|
-
await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
|
|
1140
|
-
else
|
|
1141
|
-
await storeInst.setData(JSON.parse(decodedData));
|
|
1142
|
-
}
|
|
1469
|
+
});
|
|
1143
1470
|
}
|
|
1144
1471
|
/**
|
|
1145
1472
|
* Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
|
|
1146
1473
|
* Also triggers the migration process if the data format has changed.
|
|
1147
1474
|
*/
|
|
1148
|
-
|
|
1149
|
-
return
|
|
1475
|
+
deserialize(data) {
|
|
1476
|
+
return __async(this, null, function* () {
|
|
1477
|
+
return this.deserializePartial(this.stores.map((s) => s.id), data);
|
|
1478
|
+
});
|
|
1150
1479
|
}
|
|
1151
1480
|
/**
|
|
1152
1481
|
* Loads the persistent data of the DataStore instances into the in-memory cache.
|
|
@@ -1154,32 +1483,40 @@ Has: ${checksum}`);
|
|
|
1154
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
|
|
1155
1484
|
* @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
|
|
1156
1485
|
*/
|
|
1157
|
-
|
|
1158
|
-
return
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
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
|
+
});
|
|
1164
1497
|
}
|
|
1165
1498
|
/**
|
|
1166
1499
|
* Resets the persistent and in-memory data of the DataStore instances to their default values.
|
|
1167
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
|
|
1168
1501
|
*/
|
|
1169
|
-
|
|
1170
|
-
return
|
|
1171
|
-
|
|
1172
|
-
|
|
1502
|
+
resetStoresData(stores) {
|
|
1503
|
+
return __async(this, null, function* () {
|
|
1504
|
+
return Promise.allSettled(
|
|
1505
|
+
this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
|
|
1506
|
+
);
|
|
1507
|
+
});
|
|
1173
1508
|
}
|
|
1174
1509
|
/**
|
|
1175
1510
|
* Deletes the persistent data of the DataStore instances.
|
|
1176
1511
|
* Leaves the in-memory data untouched.
|
|
1177
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
|
|
1178
1513
|
*/
|
|
1179
|
-
|
|
1180
|
-
return
|
|
1181
|
-
|
|
1182
|
-
|
|
1514
|
+
deleteStoresData(stores) {
|
|
1515
|
+
return __async(this, null, function* () {
|
|
1516
|
+
return Promise.allSettled(
|
|
1517
|
+
this.getStoresFiltered(stores).map((store) => store.deleteData())
|
|
1518
|
+
);
|
|
1519
|
+
});
|
|
1183
1520
|
}
|
|
1184
1521
|
/** Checks if a given value is an array of SerializedDataStore objects */
|
|
1185
1522
|
static isSerializedDataStoreObjArray(obj) {
|
|
@@ -1195,371 +1532,6 @@ Has: ${checksum}`);
|
|
|
1195
1532
|
}
|
|
1196
1533
|
};
|
|
1197
1534
|
|
|
1198
|
-
// node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
|
|
1199
|
-
var createNanoEvents = () => ({
|
|
1200
|
-
emit(event, ...args) {
|
|
1201
|
-
for (let callbacks = this.events[event] || [], i = 0, length = callbacks.length; i < length; i++) {
|
|
1202
|
-
callbacks[i](...args);
|
|
1203
|
-
}
|
|
1204
|
-
},
|
|
1205
|
-
events: {},
|
|
1206
|
-
on(event, cb) {
|
|
1207
|
-
;
|
|
1208
|
-
(this.events[event] ||= []).push(cb);
|
|
1209
|
-
return () => {
|
|
1210
|
-
var _a;
|
|
1211
|
-
this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((i) => cb !== i);
|
|
1212
|
-
};
|
|
1213
|
-
}
|
|
1214
|
-
});
|
|
1215
|
-
|
|
1216
|
-
// lib/NanoEmitter.ts
|
|
1217
|
-
var NanoEmitter = class {
|
|
1218
|
-
events = createNanoEvents();
|
|
1219
|
-
eventUnsubscribes = [];
|
|
1220
|
-
emitterOptions;
|
|
1221
|
-
/** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
|
|
1222
|
-
constructor(options = {}) {
|
|
1223
|
-
this.emitterOptions = {
|
|
1224
|
-
publicEmit: false,
|
|
1225
|
-
...options
|
|
1226
|
-
};
|
|
1227
|
-
}
|
|
1228
|
-
//#region on
|
|
1229
|
-
/**
|
|
1230
|
-
* Subscribes to an event and calls the callback when it's emitted.
|
|
1231
|
-
* @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 "_")
|
|
1232
|
-
* @returns Returns a function that can be called to unsubscribe the event listener
|
|
1233
|
-
* @example ```ts
|
|
1234
|
-
* const emitter = new NanoEmitter<{
|
|
1235
|
-
* foo: (bar: string) => void;
|
|
1236
|
-
* }>({
|
|
1237
|
-
* publicEmit: true,
|
|
1238
|
-
* });
|
|
1239
|
-
*
|
|
1240
|
-
* let i = 0;
|
|
1241
|
-
* const unsub = emitter.on("foo", (bar) => {
|
|
1242
|
-
* // unsubscribe after 10 events:
|
|
1243
|
-
* if(++i === 10) unsub();
|
|
1244
|
-
* console.log(bar);
|
|
1245
|
-
* });
|
|
1246
|
-
*
|
|
1247
|
-
* emitter.emit("foo", "bar");
|
|
1248
|
-
* ```
|
|
1249
|
-
*/
|
|
1250
|
-
on(event, cb) {
|
|
1251
|
-
let unsub;
|
|
1252
|
-
const unsubProxy = () => {
|
|
1253
|
-
if (!unsub)
|
|
1254
|
-
return;
|
|
1255
|
-
unsub();
|
|
1256
|
-
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => u !== unsub);
|
|
1257
|
-
};
|
|
1258
|
-
unsub = this.events.on(event, cb);
|
|
1259
|
-
this.eventUnsubscribes.push(unsub);
|
|
1260
|
-
return unsubProxy;
|
|
1261
|
-
}
|
|
1262
|
-
//#region once
|
|
1263
|
-
/**
|
|
1264
|
-
* Subscribes to an event and calls the callback or resolves the Promise only once when it's emitted.
|
|
1265
|
-
* @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 "_")
|
|
1266
|
-
* @param cb The callback to call when the event is emitted - if provided or not, the returned Promise will resolve with the event arguments
|
|
1267
|
-
* @returns Returns a Promise that resolves with the event arguments when the event is emitted
|
|
1268
|
-
* @example ```ts
|
|
1269
|
-
* const emitter = new NanoEmitter<{
|
|
1270
|
-
* foo: (bar: string) => void;
|
|
1271
|
-
* }>();
|
|
1272
|
-
*
|
|
1273
|
-
* // Promise syntax:
|
|
1274
|
-
* const [bar] = await emitter.once("foo");
|
|
1275
|
-
* console.log(bar);
|
|
1276
|
-
*
|
|
1277
|
-
* // Callback syntax:
|
|
1278
|
-
* emitter.once("foo", (bar) => console.log(bar));
|
|
1279
|
-
* ```
|
|
1280
|
-
*/
|
|
1281
|
-
once(event, cb) {
|
|
1282
|
-
return new Promise((resolve) => {
|
|
1283
|
-
let unsub;
|
|
1284
|
-
const onceProxy = ((...args) => {
|
|
1285
|
-
cb == null ? void 0 : cb(...args);
|
|
1286
|
-
unsub == null ? void 0 : unsub();
|
|
1287
|
-
resolve(args);
|
|
1288
|
-
});
|
|
1289
|
-
unsub = this.events.on(event, onceProxy);
|
|
1290
|
-
this.eventUnsubscribes.push(unsub);
|
|
1291
|
-
});
|
|
1292
|
-
}
|
|
1293
|
-
//#region onMulti
|
|
1294
|
-
/**
|
|
1295
|
-
* 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.
|
|
1296
|
-
* @param options An object or array of objects with the following properties:
|
|
1297
|
-
* `callback` (required) is the function that will be called when the conditions are met.
|
|
1298
|
-
*
|
|
1299
|
-
* 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.
|
|
1300
|
-
* If `signal` is provided, the subscription will be canceled when the given signal is aborted.
|
|
1301
|
-
*
|
|
1302
|
-
* If `oneOf` is used, the callback will be called when any of the matching events are emitted.
|
|
1303
|
-
* 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.
|
|
1304
|
-
* 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.
|
|
1305
|
-
* At least one of `oneOf` or `allOf` must be provided.
|
|
1306
|
-
*
|
|
1307
|
-
* @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.
|
|
1308
|
-
*/
|
|
1309
|
-
onMulti(options) {
|
|
1310
|
-
const allUnsubs = [];
|
|
1311
|
-
const unsubAll = () => {
|
|
1312
|
-
for (const unsub of allUnsubs)
|
|
1313
|
-
unsub();
|
|
1314
|
-
allUnsubs.splice(0, allUnsubs.length);
|
|
1315
|
-
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
|
|
1316
|
-
};
|
|
1317
|
-
for (const opts of Array.isArray(options) ? options : [options]) {
|
|
1318
|
-
const optsWithDefaults = {
|
|
1319
|
-
allOf: [],
|
|
1320
|
-
oneOf: [],
|
|
1321
|
-
once: false,
|
|
1322
|
-
...opts
|
|
1323
|
-
};
|
|
1324
|
-
const {
|
|
1325
|
-
oneOf,
|
|
1326
|
-
allOf,
|
|
1327
|
-
once,
|
|
1328
|
-
signal,
|
|
1329
|
-
callback
|
|
1330
|
-
} = optsWithDefaults;
|
|
1331
|
-
if (signal == null ? void 0 : signal.aborted)
|
|
1332
|
-
return unsubAll;
|
|
1333
|
-
if (oneOf.length === 0 && allOf.length === 0)
|
|
1334
|
-
throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
|
|
1335
|
-
const curEvtUnsubs = [];
|
|
1336
|
-
const checkUnsubAllEvt = (force = false) => {
|
|
1337
|
-
if (!(signal == null ? void 0 : signal.aborted) && !force)
|
|
1338
|
-
return;
|
|
1339
|
-
for (const unsub of curEvtUnsubs)
|
|
1340
|
-
unsub();
|
|
1341
|
-
curEvtUnsubs.splice(0, curEvtUnsubs.length);
|
|
1342
|
-
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
|
|
1343
|
-
};
|
|
1344
|
-
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
1345
|
-
const allOfConditionMet = () => allOf.length === 0 || allOfEmitted.size === allOf.length;
|
|
1346
|
-
for (const event of oneOf) {
|
|
1347
|
-
const unsub = this.events.on(event, ((...args) => {
|
|
1348
|
-
checkUnsubAllEvt();
|
|
1349
|
-
if (allOfConditionMet()) {
|
|
1350
|
-
callback(event, ...args);
|
|
1351
|
-
if (once)
|
|
1352
|
-
checkUnsubAllEvt(true);
|
|
1353
|
-
}
|
|
1354
|
-
}));
|
|
1355
|
-
curEvtUnsubs.push(unsub);
|
|
1356
|
-
}
|
|
1357
|
-
for (const event of allOf) {
|
|
1358
|
-
const unsub = this.events.on(event, ((...args) => {
|
|
1359
|
-
checkUnsubAllEvt();
|
|
1360
|
-
allOfEmitted.add(event);
|
|
1361
|
-
if (allOfConditionMet() && (oneOf.length === 0 || oneOf.includes(event))) {
|
|
1362
|
-
callback(event, ...args);
|
|
1363
|
-
if (once)
|
|
1364
|
-
checkUnsubAllEvt(true);
|
|
1365
|
-
}
|
|
1366
|
-
}));
|
|
1367
|
-
curEvtUnsubs.push(unsub);
|
|
1368
|
-
}
|
|
1369
|
-
allUnsubs.push(() => checkUnsubAllEvt(true));
|
|
1370
|
-
}
|
|
1371
|
-
return unsubAll;
|
|
1372
|
-
}
|
|
1373
|
-
//#region emit
|
|
1374
|
-
/**
|
|
1375
|
-
* Emits an event on this instance.
|
|
1376
|
-
* - ⚠️ Needs `publicEmit` to be set to true in the NanoEmitter constructor or super() call!
|
|
1377
|
-
* @param event The event to emit
|
|
1378
|
-
* @param args The arguments to pass to the event listeners
|
|
1379
|
-
* @returns Returns true if `publicEmit` is true and the event was emitted successfully
|
|
1380
|
-
*/
|
|
1381
|
-
emit(event, ...args) {
|
|
1382
|
-
if (this.emitterOptions.publicEmit) {
|
|
1383
|
-
this.events.emit(event, ...args);
|
|
1384
|
-
return true;
|
|
1385
|
-
}
|
|
1386
|
-
return false;
|
|
1387
|
-
}
|
|
1388
|
-
//#region unsubscribeAll
|
|
1389
|
-
/** Unsubscribes all event listeners from this instance */
|
|
1390
|
-
unsubscribeAll() {
|
|
1391
|
-
for (const unsub of this.eventUnsubscribes)
|
|
1392
|
-
unsub();
|
|
1393
|
-
this.eventUnsubscribes = [];
|
|
1394
|
-
}
|
|
1395
|
-
};
|
|
1396
|
-
|
|
1397
|
-
// lib/Debouncer.ts
|
|
1398
|
-
var Debouncer = class extends NanoEmitter {
|
|
1399
|
-
/**
|
|
1400
|
-
* Creates a new debouncer with the specified timeout and edge type.
|
|
1401
|
-
* @param timeout Timeout in milliseconds between letting through calls - defaults to 200
|
|
1402
|
-
* @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"
|
|
1403
|
-
*/
|
|
1404
|
-
constructor(timeout = 200, type = "immediate") {
|
|
1405
|
-
super();
|
|
1406
|
-
this.timeout = timeout;
|
|
1407
|
-
this.type = type;
|
|
1408
|
-
}
|
|
1409
|
-
/** All registered listener functions and the time they were attached */
|
|
1410
|
-
listeners = [];
|
|
1411
|
-
/** The currently active timeout */
|
|
1412
|
-
activeTimeout;
|
|
1413
|
-
/** The latest queued call */
|
|
1414
|
-
queuedCall;
|
|
1415
|
-
//#region listeners
|
|
1416
|
-
/** Adds a listener function that will be called on timeout */
|
|
1417
|
-
addListener(fn) {
|
|
1418
|
-
this.listeners.push(fn);
|
|
1419
|
-
}
|
|
1420
|
-
/** Removes the listener with the specified function reference */
|
|
1421
|
-
removeListener(fn) {
|
|
1422
|
-
const idx = this.listeners.findIndex((l) => l === fn);
|
|
1423
|
-
idx !== -1 && this.listeners.splice(idx, 1);
|
|
1424
|
-
}
|
|
1425
|
-
/** Removes all listeners */
|
|
1426
|
-
removeAllListeners() {
|
|
1427
|
-
this.listeners = [];
|
|
1428
|
-
}
|
|
1429
|
-
/** Returns all registered listeners */
|
|
1430
|
-
getListeners() {
|
|
1431
|
-
return this.listeners;
|
|
1432
|
-
}
|
|
1433
|
-
//#region timeout
|
|
1434
|
-
/** Sets the timeout for the debouncer */
|
|
1435
|
-
setTimeout(timeout) {
|
|
1436
|
-
this.emit("change", this.timeout = timeout, this.type);
|
|
1437
|
-
}
|
|
1438
|
-
/** Returns the current timeout */
|
|
1439
|
-
getTimeout() {
|
|
1440
|
-
return this.timeout;
|
|
1441
|
-
}
|
|
1442
|
-
/** Whether the timeout is currently active, meaning any latest call to the {@linkcode call()} method will be queued */
|
|
1443
|
-
isTimeoutActive() {
|
|
1444
|
-
return typeof this.activeTimeout !== "undefined";
|
|
1445
|
-
}
|
|
1446
|
-
//#region type
|
|
1447
|
-
/** Sets the edge type for the debouncer */
|
|
1448
|
-
setType(type) {
|
|
1449
|
-
this.emit("change", this.timeout, this.type = type);
|
|
1450
|
-
}
|
|
1451
|
-
/** Returns the current edge type */
|
|
1452
|
-
getType() {
|
|
1453
|
-
return this.type;
|
|
1454
|
-
}
|
|
1455
|
-
//#region call
|
|
1456
|
-
/** Use this to call the debouncer with the specified arguments that will be passed to all listener functions registered with {@linkcode addListener()} */
|
|
1457
|
-
call(...args) {
|
|
1458
|
-
const cl = (...a) => {
|
|
1459
|
-
this.queuedCall = void 0;
|
|
1460
|
-
this.emit("call", ...a);
|
|
1461
|
-
this.listeners.forEach((l) => l.call(this, ...a));
|
|
1462
|
-
};
|
|
1463
|
-
const setRepeatTimeout = () => {
|
|
1464
|
-
this.activeTimeout = setTimeout(() => {
|
|
1465
|
-
if (this.queuedCall) {
|
|
1466
|
-
this.queuedCall();
|
|
1467
|
-
setRepeatTimeout();
|
|
1468
|
-
} else
|
|
1469
|
-
this.activeTimeout = void 0;
|
|
1470
|
-
}, this.timeout);
|
|
1471
|
-
};
|
|
1472
|
-
switch (this.type) {
|
|
1473
|
-
case "immediate":
|
|
1474
|
-
if (typeof this.activeTimeout === "undefined") {
|
|
1475
|
-
cl(...args);
|
|
1476
|
-
setRepeatTimeout();
|
|
1477
|
-
} else
|
|
1478
|
-
this.queuedCall = () => cl(...args);
|
|
1479
|
-
break;
|
|
1480
|
-
case "idle":
|
|
1481
|
-
if (this.activeTimeout)
|
|
1482
|
-
clearTimeout(this.activeTimeout);
|
|
1483
|
-
this.activeTimeout = setTimeout(() => {
|
|
1484
|
-
cl(...args);
|
|
1485
|
-
this.activeTimeout = void 0;
|
|
1486
|
-
}, this.timeout);
|
|
1487
|
-
break;
|
|
1488
|
-
default:
|
|
1489
|
-
throw new TypeError(`Invalid debouncer type: ${this.type}`);
|
|
1490
|
-
}
|
|
1491
|
-
}
|
|
1492
|
-
};
|
|
1493
|
-
function debounce(fn, timeout = 200, type = "immediate") {
|
|
1494
|
-
const debouncer = new Debouncer(timeout, type);
|
|
1495
|
-
debouncer.addListener(fn);
|
|
1496
|
-
const func = ((...args) => debouncer.call(...args));
|
|
1497
|
-
func.debouncer = debouncer;
|
|
1498
|
-
return func;
|
|
1499
|
-
}
|
|
1500
|
-
`oneOf` or `allOf` or both must be provided in the options");
|
|
1501
|
-
const curEvtUnsubs = [];
|
|
1502
|
-
const checkUnsubAllEvt = (force = false) => {
|
|
1503
|
-
if (!(signal == null ? void 0 : signal.aborted) && !force)
|
|
1504
|
-
return;
|
|
1505
|
-
for (const unsub of curEvtUnsubs)
|
|
1506
|
-
unsub();
|
|
1507
|
-
curEvtUnsubs.splice(0, curEvtUnsubs.length);
|
|
1508
|
-
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
|
|
1509
|
-
};
|
|
1510
|
-
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
1511
|
-
const allOfConditionMet = () => allOf.length === 0 || allOfEmitted.size === allOf.length;
|
|
1512
|
-
for (const event of oneOf) {
|
|
1513
|
-
const unsub = this.events.on(event, ((...args) => {
|
|
1514
|
-
checkUnsubAllEvt();
|
|
1515
|
-
if (allOfConditionMet()) {
|
|
1516
|
-
callback(event, ...args);
|
|
1517
|
-
if (once)
|
|
1518
|
-
checkUnsubAllEvt(true);
|
|
1519
|
-
}
|
|
1520
|
-
}));
|
|
1521
|
-
curEvtUnsubs.push(unsub);
|
|
1522
|
-
}
|
|
1523
|
-
for (const event of allOf) {
|
|
1524
|
-
const unsub = this.events.on(event, ((...args) => {
|
|
1525
|
-
checkUnsubAllEvt();
|
|
1526
|
-
allOfEmitted.add(event);
|
|
1527
|
-
if (allOfConditionMet() && (oneOf.length === 0 || oneOf.includes(event))) {
|
|
1528
|
-
callback(event, ...args);
|
|
1529
|
-
if (once)
|
|
1530
|
-
checkUnsubAllEvt(true);
|
|
1531
|
-
}
|
|
1532
|
-
}));
|
|
1533
|
-
curEvtUnsubs.push(unsub);
|
|
1534
|
-
}
|
|
1535
|
-
allUnsubs.push(() => checkUnsubAllEvt(true));
|
|
1536
|
-
}
|
|
1537
|
-
return unsubAll;
|
|
1538
|
-
}
|
|
1539
|
-
//#region emit
|
|
1540
|
-
/**
|
|
1541
|
-
* Emits an event on this instance.
|
|
1542
|
-
* - ⚠️ Needs `publicEmit` to be set to true in the NanoEmitter constructor or super() call!
|
|
1543
|
-
* @param event The event to emit
|
|
1544
|
-
* @param args The arguments to pass to the event listeners
|
|
1545
|
-
* @returns Returns true if `publicEmit` is true and the event was emitted successfully
|
|
1546
|
-
*/
|
|
1547
|
-
emit(event, ...args) {
|
|
1548
|
-
if (this.emitterOptions.publicEmit) {
|
|
1549
|
-
this.events.emit(event, ...args);
|
|
1550
|
-
return true;
|
|
1551
|
-
}
|
|
1552
|
-
return false;
|
|
1553
|
-
}
|
|
1554
|
-
//#region unsubscribeAll
|
|
1555
|
-
/** Unsubscribes all event listeners from this instance */
|
|
1556
|
-
unsubscribeAll() {
|
|
1557
|
-
for (const unsub of this.eventUnsubscribes)
|
|
1558
|
-
unsub();
|
|
1559
|
-
this.eventUnsubscribes = [];
|
|
1560
|
-
}
|
|
1561
|
-
};
|
|
1562
|
-
|
|
1563
1535
|
// lib/Debouncer.ts
|
|
1564
1536
|
var Debouncer = class extends NanoEmitter {
|
|
1565
1537
|
/**
|
|
@@ -1665,7 +1637,7 @@ function debounce(fn, timeout = 200, type = "immediate") {
|
|
|
1665
1637
|
}
|
|
1666
1638
|
|
|
1667
1639
|
if(__exports != exports)module.exports = exports;return module.exports}));
|
|
1668
|
-
|
|
1640
|
+
|
|
1669
1641
|
|
|
1670
1642
|
|
|
1671
1643
|
if (typeof module.exports == "object" && typeof exports == "object") {
|