@sv443-network/coreutils 3.3.0 → 3.5.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.
@@ -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,10 +73,13 @@ __export(lib_exports, {
122
73
  consumeGen: () => consumeGen,
123
74
  consumeStringGen: () => consumeStringGen,
124
75
  createProgressBar: () => createProgressBar,
76
+ createRecurringTask: () => createRecurringTask,
77
+ createTable: () => createTable,
125
78
  darkenColor: () => darkenColor,
126
79
  debounce: () => debounce,
127
80
  decompress: () => decompress,
128
81
  defaultPbChars: () => defaultPbChars,
82
+ defaultTableLineCharset: () => defaultTableLineCharset,
129
83
  digitCount: () => digitCount,
130
84
  fetchAdvanced: () => fetchAdvanced,
131
85
  formatNumber: () => formatNumber,
@@ -243,7 +197,7 @@ function randRange(...args) {
243
197
  return Math.floor(Math.random() * (max - min + 1)) + min;
244
198
  }
245
199
  function roundFixed(num, fractionDigits) {
246
- const scale = __pow(10, fractionDigits);
200
+ const scale = 10 ** fractionDigits;
247
201
  return Math.round(num * scale) / scale;
248
202
  }
249
203
  function valsWithin(a, b, dec = 1, withinRange = 0.5) {
@@ -307,7 +261,7 @@ function darkenColor(color, percent, upperCase = false) {
307
261
  if (isHexCol)
308
262
  return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
309
263
  else if (color.startsWith("rgba"))
310
- return `rgba(${r}, ${g}, ${b}, ${a != null ? a : NaN})`;
264
+ return `rgba(${r}, ${g}, ${b}, ${a ?? NaN})`;
311
265
  else
312
266
  return `rgb(${r}, ${g}, ${b})`;
313
267
  }
@@ -341,43 +295,35 @@ function abtoa(buf) {
341
295
  function atoab(str) {
342
296
  return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
343
297
  }
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
- });
298
+ async function compress(input, compressionFormat, outputType = "string") {
299
+ const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((input == null ? void 0 : input.toString()) ?? String(input));
300
+ const comp = new CompressionStream(compressionFormat);
301
+ const writer = comp.writable.getWriter();
302
+ writer.write(byteArray);
303
+ writer.close();
304
+ const uintArr = new Uint8Array(await new Response(comp.readable).arrayBuffer());
305
+ return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
355
306
  }
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
- });
307
+ async function decompress(input, compressionFormat, outputType = "string") {
308
+ const byteArray = input instanceof Uint8Array ? input : atoab((input == null ? void 0 : input.toString()) ?? String(input));
309
+ const decomp = new DecompressionStream(compressionFormat);
310
+ const writer = decomp.writable.getWriter();
311
+ writer.write(byteArray);
312
+ writer.close();
313
+ const uintArr = new Uint8Array(await new Response(decomp.readable).arrayBuffer());
314
+ return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
367
315
  }
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
- });
316
+ async function computeHash(input, algorithm = "SHA-256") {
317
+ let data;
318
+ if (typeof input === "string") {
319
+ const encoder = new TextEncoder();
320
+ data = encoder.encode(input);
321
+ } else
322
+ data = input;
323
+ const hashBuffer = await crypto.subtle.digest(algorithm, data);
324
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
325
+ const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
326
+ return hashHex;
381
327
  }
382
328
  function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
383
329
  if (length < 1)
@@ -406,9 +352,9 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
406
352
 
407
353
  // lib/Errors.ts
408
354
  var DatedError = class extends Error {
355
+ date;
409
356
  constructor(message, options) {
410
357
  super(message, options);
411
- __publicField(this, "date");
412
358
  this.name = this.constructor.name;
413
359
  this.date = /* @__PURE__ */ new Date();
414
360
  }
@@ -451,37 +397,34 @@ var NetworkError = class extends DatedError {
451
397
  };
452
398
 
453
399
  // lib/misc.ts
454
- function consumeGen(valGen) {
455
- return __async(this, null, function* () {
456
- return yield typeof valGen === "function" ? valGen() : valGen;
457
- });
400
+ async function consumeGen(valGen) {
401
+ return await (typeof valGen === "function" ? valGen() : valGen);
458
402
  }
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
- });
403
+ async function consumeStringGen(strGen) {
404
+ return typeof strGen === "string" ? strGen : String(
405
+ typeof strGen === "function" ? await strGen() : strGen
406
+ );
465
407
  }
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
- });
408
+ async function fetchAdvanced(input, options = {}) {
409
+ const { timeout = 1e4, signal, ...restOpts } = options;
410
+ const ctl = new AbortController();
411
+ signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
412
+ let sigOpts = {}, id = void 0;
413
+ if (timeout >= 0) {
414
+ id = setTimeout(() => ctl.abort(), timeout);
415
+ sigOpts = { signal: ctl.signal };
416
+ }
417
+ try {
418
+ const res = await fetch(input, {
419
+ ...restOpts,
420
+ ...sigOpts
421
+ });
422
+ typeof id !== "undefined" && clearTimeout(id);
423
+ return res;
424
+ } catch (err) {
425
+ typeof id !== "undefined" && clearTimeout(id);
426
+ throw new NetworkError("Error while calling fetch", { cause: err });
427
+ }
485
428
  }
486
429
  function getListLength(listLike, zeroOnInvalid = true) {
487
430
  return "length" in listLike ? listLike.length : "size" in listLike ? listLike.size : "count" in listLike ? listLike.count : zeroOnInvalid ? 0 : NaN;
@@ -496,7 +439,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
496
439
  });
497
440
  }
498
441
  function pureObj(obj) {
499
- return Object.assign(/* @__PURE__ */ Object.create(null), obj != null ? obj : {});
442
+ return Object.assign(/* @__PURE__ */ Object.create(null), obj ?? {});
500
443
  }
501
444
  function setImmediateInterval(callback, interval, signal) {
502
445
  let intervalId;
@@ -513,12 +456,12 @@ function setImmediateInterval(callback, interval, signal) {
513
456
  function setImmediateTimeoutLoop(callback, interval, signal) {
514
457
  let timeout;
515
458
  const cleanup = () => clearTimeout(timeout);
516
- const loop = () => __async(null, null, function* () {
459
+ const loop = async () => {
517
460
  if (signal == null ? void 0 : signal.aborted)
518
461
  return cleanup();
519
- yield callback();
462
+ await callback();
520
463
  timeout = setTimeout(loop, interval);
521
- });
464
+ };
522
465
  signal == null ? void 0 : signal.addEventListener("abort", cleanup);
523
466
  loop();
524
467
  }
@@ -535,16 +478,48 @@ function scheduleExit(code = 0, timeout = 0) {
535
478
  setTimeout(exit, timeout);
536
479
  }
537
480
  function getCallStack(asArray, lines = Infinity) {
538
- var _a;
539
481
  if (typeof lines !== "number" || isNaN(lines) || lines < 0)
540
482
  throw new TypeError("lines parameter must be a non-negative number");
541
483
  try {
542
- throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)");
484
+ throw new CustomError("GetCallStack", "Capturing a stack trace with CoreUtils.getCallStack(). If you see this anywhere, you can safely ignore it.");
543
485
  } catch (err) {
544
- const stack = ((_a = err.stack) != null ? _a : "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
486
+ const stack = (err.stack ?? "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
545
487
  return asArray !== false ? stack : stack.join("\n");
546
488
  }
547
489
  }
490
+ function createRecurringTask(options) {
491
+ var _a;
492
+ let iterations = 0;
493
+ let aborted = false;
494
+ (_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => {
495
+ aborted = true;
496
+ }, { once: true });
497
+ const runRecurringTask = async (initial = false) => {
498
+ var _a2;
499
+ if (aborted)
500
+ return;
501
+ try {
502
+ if ((options.immediate ?? true) || !initial) {
503
+ iterations++;
504
+ if (await ((_a2 = options.condition) == null ? void 0 : _a2.call(options, iterations - 1)) ?? true) {
505
+ const val = await options.task(iterations - 1);
506
+ if (options.onSuccess)
507
+ await options.onSuccess(val, iterations - 1);
508
+ }
509
+ }
510
+ } catch (err) {
511
+ if (options.onError)
512
+ await options.onError(err, iterations - 1);
513
+ if (options.abortOnError)
514
+ aborted = true;
515
+ if (!options.onError && !options.abortOnError)
516
+ throw err;
517
+ }
518
+ if (!aborted && (typeof options.maxIterations !== "number" || iterations < options.maxIterations))
519
+ setTimeout(runRecurringTask, options.timeout);
520
+ };
521
+ return runRecurringTask(true);
522
+ }
548
523
 
549
524
  // lib/text.ts
550
525
  function autoPlural(term, num, pluralType = "auto") {
@@ -596,9 +571,9 @@ function createProgressBar(percentage, barLength, chars = defaultPbChars) {
596
571
  }
597
572
  function insertValues(input, ...values) {
598
573
  return input.replace(/%\d/gm, (match) => {
599
- var _a, _b;
574
+ var _a;
600
575
  const argIndex = Number(match.substring(1)) - 1;
601
- return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
576
+ return (_a = values[argIndex] ?? match) == null ? void 0 : _a.toString();
602
577
  });
603
578
  }
604
579
  function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
@@ -629,11 +604,177 @@ function secsToTimeStr(seconds) {
629
604
  ].join("");
630
605
  }
631
606
  function truncStr(input, length, endStr = "...") {
632
- var _a;
633
- const str = (_a = input == null ? void 0 : input.toString()) != null ? _a : String(input);
607
+ const str = (input == null ? void 0 : input.toString()) ?? String(input);
634
608
  const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
635
609
  return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
636
610
  }
611
+ var defaultTableLineCharset = {
612
+ single: {
613
+ horizontal: "\u2500",
614
+ vertical: "\u2502",
615
+ topLeft: "\u250C",
616
+ topRight: "\u2510",
617
+ bottomLeft: "\u2514",
618
+ bottomRight: "\u2518",
619
+ leftT: "\u251C",
620
+ rightT: "\u2524",
621
+ topT: "\u252C",
622
+ bottomT: "\u2534",
623
+ cross: "\u253C"
624
+ },
625
+ double: {
626
+ horizontal: "\u2550",
627
+ vertical: "\u2551",
628
+ topLeft: "\u2554",
629
+ topRight: "\u2557",
630
+ bottomLeft: "\u255A",
631
+ bottomRight: "\u255D",
632
+ leftT: "\u2560",
633
+ rightT: "\u2563",
634
+ topT: "\u2566",
635
+ bottomT: "\u2569",
636
+ cross: "\u256C"
637
+ },
638
+ none: {
639
+ horizontal: " ",
640
+ vertical: " ",
641
+ topLeft: " ",
642
+ topRight: " ",
643
+ bottomLeft: " ",
644
+ bottomRight: " ",
645
+ leftT: " ",
646
+ rightT: " ",
647
+ topT: " ",
648
+ bottomT: " ",
649
+ cross: " "
650
+ }
651
+ };
652
+ function createTable(rows, options) {
653
+ var _a;
654
+ const opts = {
655
+ columnAlign: "left",
656
+ truncateAbove: Infinity,
657
+ truncEndStr: "\u2026",
658
+ minPadding: 1,
659
+ lineStyle: "single",
660
+ applyCellStyle: () => void 0,
661
+ applyLineStyle: () => void 0,
662
+ lineCharset: defaultTableLineCharset,
663
+ ...options ?? {}
664
+ };
665
+ const defRange = (val, min, max) => clamp(typeof val !== "number" || isNaN(Number(val)) ? min : val, min, max);
666
+ opts.truncateAbove = defRange(opts.truncateAbove, 0, Infinity);
667
+ opts.minPadding = defRange(opts.minPadding, 0, Infinity);
668
+ const lnCh = opts.lineCharset[opts.lineStyle];
669
+ const stripAnsi = (str) => str.replace(/\u001b\[[0-9;]*m/g, "");
670
+ const stringRows = rows.map((row) => row.map((cell) => String(cell)));
671
+ const colCount = ((_a = rows[0]) == null ? void 0 : _a.length) ?? 0;
672
+ if (colCount === 0 || stringRows.length === 0)
673
+ return "";
674
+ if (isFinite(opts.truncateAbove)) {
675
+ const truncAnsi = (str, maxVisible, endStr) => {
676
+ const limit = maxVisible - endStr.length;
677
+ if (limit <= 0)
678
+ return endStr.slice(0, maxVisible);
679
+ let visible = 0;
680
+ let result = "";
681
+ let i = 0;
682
+ let hasAnsi = false;
683
+ while (i < str.length) {
684
+ if (str[i] === "\x1B" && str[i + 1] === "[") {
685
+ const seqEnd = str.indexOf("m", i + 2);
686
+ if (seqEnd !== -1) {
687
+ result += str.slice(i, seqEnd + 1);
688
+ hasAnsi = true;
689
+ i = seqEnd + 1;
690
+ continue;
691
+ }
692
+ }
693
+ if (visible === limit) {
694
+ result += endStr;
695
+ if (hasAnsi)
696
+ result += "\x1B[0m";
697
+ return result;
698
+ }
699
+ result += str[i];
700
+ visible++;
701
+ i++;
702
+ }
703
+ return result;
704
+ };
705
+ for (const row of stringRows)
706
+ for (let j = 0; j < row.length; j++)
707
+ if (stripAnsi(row[j] ?? "").length > opts.truncateAbove)
708
+ row[j] = truncAnsi(row[j] ?? "", opts.truncateAbove, opts.truncEndStr);
709
+ }
710
+ const colWidths = Array.from(
711
+ { length: colCount },
712
+ (_, j) => Math.max(0, ...stringRows.map((row) => stripAnsi(row[j] ?? "").length))
713
+ );
714
+ const applyLn = (i, j, ch) => {
715
+ const [before = "", after = ""] = opts.applyLineStyle(i, j) ?? [];
716
+ return `${before}${ch}${after}`;
717
+ };
718
+ const buildBorderRow = (lineIdx, leftCh, midCh, rightCh) => {
719
+ let result = "";
720
+ let j = 0;
721
+ result += applyLn(lineIdx, j++, leftCh);
722
+ for (let col = 0; col < colCount; col++) {
723
+ const cellWidth = (colWidths[col] ?? 0) + opts.minPadding * 2;
724
+ for (let ci = 0; ci < cellWidth; ci++)
725
+ result += applyLn(lineIdx, j++, lnCh.horizontal);
726
+ if (col < colCount - 1)
727
+ result += applyLn(lineIdx, j++, midCh);
728
+ }
729
+ result += applyLn(lineIdx, j++, rightCh);
730
+ return result;
731
+ };
732
+ const lines = [];
733
+ for (let rowIdx = 0; rowIdx < stringRows.length; rowIdx++) {
734
+ const row = stringRows[rowIdx] ?? [];
735
+ const lineIdxBase = rowIdx * 3;
736
+ if (opts.lineStyle !== "none") {
737
+ lines.push(
738
+ rowIdx === 0 ? buildBorderRow(lineIdxBase, lnCh.topLeft, lnCh.topT, lnCh.topRight) : buildBorderRow(lineIdxBase, lnCh.leftT, lnCh.cross, lnCh.rightT)
739
+ );
740
+ }
741
+ let contentLine = "";
742
+ let j = 0;
743
+ contentLine += applyLn(lineIdxBase + 1, j++, lnCh.vertical);
744
+ for (let colIdx = 0; colIdx < colCount; colIdx++) {
745
+ const cell = row[colIdx] ?? "";
746
+ const visLen = stripAnsi(cell).length;
747
+ const extra = (colWidths[colIdx] ?? 0) - visLen;
748
+ const align = (Array.isArray(opts.columnAlign) ? opts.columnAlign[colIdx] : opts.columnAlign) ?? "left";
749
+ let leftPad;
750
+ let rightPad;
751
+ switch (align) {
752
+ case "right":
753
+ leftPad = opts.minPadding + extra;
754
+ rightPad = opts.minPadding;
755
+ break;
756
+ case "centerLeft":
757
+ leftPad = opts.minPadding + Math.floor(extra / 2);
758
+ rightPad = opts.minPadding + Math.ceil(extra / 2);
759
+ break;
760
+ case "centerRight":
761
+ leftPad = opts.minPadding + Math.ceil(extra / 2);
762
+ rightPad = opts.minPadding + Math.floor(extra / 2);
763
+ break;
764
+ default:
765
+ leftPad = opts.minPadding;
766
+ rightPad = opts.minPadding + extra;
767
+ }
768
+ const [cellBefore = "", cellAfter = ""] = opts.applyCellStyle(rowIdx, colIdx) ?? [];
769
+ contentLine += " ".repeat(leftPad) + cellBefore + cell + cellAfter + " ".repeat(rightPad);
770
+ contentLine += applyLn(lineIdxBase + 1, j++, lnCh.vertical);
771
+ }
772
+ lines.push(contentLine);
773
+ if (opts.lineStyle !== "none" && rowIdx === stringRows.length - 1)
774
+ lines.push(buildBorderRow(lineIdxBase + 2, lnCh.bottomLeft, lnCh.bottomT, lnCh.bottomRight));
775
+ }
776
+ return lines.join("\n");
777
+ }
637
778
 
638
779
  // node_modules/.pnpm/nanoevents@9.1.0/node_modules/nanoevents/index.js
639
780
  var createNanoEvents = () => ({
@@ -644,26 +785,26 @@ var createNanoEvents = () => ({
644
785
  },
645
786
  events: {},
646
787
  on(event, cb) {
647
- var _a;
648
788
  ;
649
- ((_a = this.events)[event] || (_a[event] = [])).push(cb);
789
+ (this.events[event] ||= []).push(cb);
650
790
  return () => {
651
- var _a2;
652
- this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
791
+ var _a;
792
+ this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((i) => cb !== i);
653
793
  };
654
794
  }
655
795
  });
656
796
 
657
797
  // lib/NanoEmitter.ts
658
798
  var NanoEmitter = class {
799
+ events = createNanoEvents();
800
+ eventUnsubscribes = [];
801
+ emitterOptions;
659
802
  /** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
660
803
  constructor(options = {}) {
661
- __publicField(this, "events", createNanoEvents());
662
- __publicField(this, "eventUnsubscribes", []);
663
- __publicField(this, "emitterOptions");
664
- this.emitterOptions = __spreadValues({
665
- publicEmit: false
666
- }, options);
804
+ this.emitterOptions = {
805
+ publicEmit: false,
806
+ ...options
807
+ };
667
808
  }
668
809
  //#region on
669
810
  /**
@@ -755,11 +896,12 @@ var NanoEmitter = class {
755
896
  this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
756
897
  };
757
898
  for (const opts of Array.isArray(options) ? options : [options]) {
758
- const optsWithDefaults = __spreadValues({
899
+ const optsWithDefaults = {
759
900
  allOf: [],
760
901
  oneOf: [],
761
- once: false
762
- }, opts);
902
+ once: false,
903
+ ...opts
904
+ };
763
905
  const {
764
906
  oneOf,
765
907
  allOf,
@@ -836,6 +978,26 @@ var NanoEmitter = class {
836
978
  // lib/DataStore.ts
837
979
  var dsFmtVer = 1;
838
980
  var DataStore = class extends NanoEmitter {
981
+ id;
982
+ formatVersion;
983
+ defaultData;
984
+ encodeData;
985
+ decodeData;
986
+ compressionFormat = "deflate-raw";
987
+ memoryCache;
988
+ engine;
989
+ keyPrefix;
990
+ options;
991
+ /**
992
+ * Whether all first-init checks should be done.
993
+ * This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
994
+ * 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.
995
+ */
996
+ firstInit = true;
997
+ /** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
998
+ cachedData;
999
+ migrations;
1000
+ migrateIds = [];
839
1001
  //#region constructor
840
1002
  /**
841
1003
  * Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
@@ -847,43 +1009,22 @@ var DataStore = class extends NanoEmitter {
847
1009
  * @param opts The options for this DataStore instance
848
1010
  */
849
1011
  constructor(opts) {
850
- var _a, _b, _c;
851
1012
  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
1013
  this.id = opts.id;
873
1014
  this.formatVersion = opts.formatVersion;
874
1015
  this.defaultData = opts.defaultData;
875
- this.memoryCache = (_a = opts.memoryCache) != null ? _a : true;
1016
+ this.memoryCache = opts.memoryCache ?? true;
876
1017
  this.cachedData = this.memoryCache ? opts.defaultData : {};
877
1018
  this.migrations = opts.migrations;
878
1019
  if (opts.migrateIds)
879
1020
  this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
880
1021
  this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
881
- this.keyPrefix = (_b = opts.keyPrefix) != null ? _b : "__ds-";
1022
+ this.keyPrefix = opts.keyPrefix ?? "__ds-";
882
1023
  this.options = opts;
883
1024
  if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
884
1025
  this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
885
1026
  this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
886
- this.compressionFormat = (_c = opts.encodeData[0]) != null ? _c : null;
1027
+ this.compressionFormat = opts.encodeData[0] ?? null;
887
1028
  } else if (opts.compressionFormat === null) {
888
1029
  this.encodeData = void 0;
889
1030
  this.decodeData = void 0;
@@ -891,12 +1032,8 @@ var DataStore = class extends NanoEmitter {
891
1032
  } else {
892
1033
  const fmt = typeof opts.compressionFormat === "string" ? opts.compressionFormat : "deflate-raw";
893
1034
  this.compressionFormat = fmt;
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
- })];
1035
+ this.encodeData = [fmt, async (data) => await compress(data, fmt, "string")];
1036
+ this.decodeData = [fmt, async (data) => await decompress(data, fmt, "string")];
900
1037
  }
901
1038
  this.engine.setDataStoreOptions({
902
1039
  id: this.id,
@@ -910,65 +1047,62 @@ var DataStore = class extends NanoEmitter {
910
1047
  * Automatically populates persistent storage with default data if it doesn't contain any data yet.
911
1048
  * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
912
1049
  */
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);
1050
+ async loadData() {
1051
+ try {
1052
+ if (this.firstInit) {
1053
+ this.firstInit = false;
1054
+ const dsVer = Number(await this.engine.getValue("__ds_fmt_ver", 0));
1055
+ const oldData = await this.engine.getValue(`_uucfg-${this.id}`, null);
1056
+ if (oldData) {
1057
+ const oldVer = Number(await this.engine.getValue(`_uucfgver-${this.id}`, NaN));
1058
+ const oldEnc = await this.engine.getValue(`_uucfgenc-${this.id}`, null);
1059
+ const promises = [];
1060
+ const migrateFmt = (oldKey, newKey, value) => {
1061
+ promises.push(this.engine.setValue(newKey, value));
1062
+ promises.push(this.engine.deleteValue(oldKey));
1063
+ };
1064
+ migrateFmt(`_uucfg-${this.id}`, `${this.keyPrefix}${this.id}-dat`, oldData);
1065
+ if (!isNaN(oldVer))
1066
+ migrateFmt(`_uucfgver-${this.id}`, `${this.keyPrefix}${this.id}-ver`, oldVer);
1067
+ if (typeof oldEnc === "boolean" || oldEnc === "true" || oldEnc === "false" || typeof oldEnc === "number" || oldEnc === "0" || oldEnc === "1")
1068
+ migrateFmt(`_uucfgenc-${this.id}`, `${this.keyPrefix}${this.id}-enf`, [0, "0", true, "true"].includes(oldEnc) ? this.compressionFormat ?? null : null);
1069
+ else {
1070
+ promises.push(this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat));
1071
+ promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
939
1072
  }
940
- if (isNaN(dsVer) || dsVer < dsFmtVer)
941
- yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
942
- }
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;
1073
+ await Promise.allSettled(promises);
954
1074
  }
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;
1075
+ if (isNaN(dsVer) || dsVer < dsFmtVer)
1076
+ await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
970
1077
  }
971
- });
1078
+ if (this.migrateIds.length > 0) {
1079
+ await this.migrateId(this.migrateIds);
1080
+ this.migrateIds = [];
1081
+ }
1082
+ const storedDataRaw = await this.engine.getValue(`${this.keyPrefix}${this.id}-dat`, null);
1083
+ const storedFmtVer = Number(await this.engine.getValue(`${this.keyPrefix}${this.id}-ver`, NaN));
1084
+ if (typeof storedDataRaw !== "string" && typeof storedDataRaw !== "object" || storedDataRaw === null || isNaN(storedFmtVer)) {
1085
+ await this.saveDefaultData(false);
1086
+ const data = this.engine.deepCopy(this.defaultData);
1087
+ this.events.emit("loadData", data);
1088
+ return data;
1089
+ }
1090
+ const storedData = storedDataRaw ?? JSON.stringify(this.defaultData);
1091
+ const encodingFmt = String(await this.engine.getValue(`${this.keyPrefix}${this.id}-enf`, null));
1092
+ const isEncoded = encodingFmt !== "null" && encodingFmt !== "false" && encodingFmt !== "0" && encodingFmt !== "" && encodingFmt !== null;
1093
+ let parsed = typeof storedData === "string" ? await this.engine.deserializeData(storedData, isEncoded) : storedData;
1094
+ if (storedFmtVer < this.formatVersion && this.migrations)
1095
+ parsed = await this.runMigrations(parsed, storedFmtVer);
1096
+ const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(parsed) : this.engine.deepCopy(parsed);
1097
+ this.events.emit("loadData", result);
1098
+ return result;
1099
+ } catch (err) {
1100
+ const error = err instanceof Error ? err : new Error(String(err));
1101
+ console.warn("Error while parsing JSON data, resetting it to the default value.", err);
1102
+ this.events.emit("error", error);
1103
+ await this.saveDefaultData();
1104
+ return this.defaultData;
1105
+ }
972
1106
  }
973
1107
  //#region getData
974
1108
  /**
@@ -989,9 +1123,9 @@ var DataStore = class extends NanoEmitter {
989
1123
  this.cachedData = data;
990
1124
  this.events.emit("updateDataSync", dataCopy);
991
1125
  }
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())),
1126
+ return new Promise(async (resolve) => {
1127
+ const results = await Promise.allSettled([
1128
+ this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(data, this.encodingEnabled())),
995
1129
  this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
996
1130
  this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
997
1131
  ]);
@@ -1003,30 +1137,28 @@ var DataStore = class extends NanoEmitter {
1003
1137
  this.events.emit("error", error);
1004
1138
  }
1005
1139
  resolve();
1006
- }));
1140
+ });
1007
1141
  }
1008
1142
  //#region saveDefaultData
1009
1143
  /**
1010
1144
  * Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage.
1011
1145
  * @param emitEvent Whether to emit the `setDefaultData` event - set to `false` to prevent event emission (used internally during initial population in {@linkcode loadData()})
1012
1146
  */
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
- });
1147
+ async saveDefaultData(emitEvent = true) {
1148
+ if (this.memoryCache)
1149
+ this.cachedData = this.defaultData;
1150
+ const results = await Promise.allSettled([
1151
+ this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(this.defaultData, this.encodingEnabled())),
1152
+ this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, this.formatVersion),
1153
+ this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
1154
+ ]);
1155
+ if (results.every((r) => r.status === "fulfilled"))
1156
+ emitEvent && this.events.emit("setDefaultData", this.defaultData);
1157
+ else {
1158
+ const error = new Error("Error while saving default data to persistent storage: " + results.map((r) => r.status === "rejected" ? r.reason : null).filter(Boolean).join("; "));
1159
+ console.error(error);
1160
+ this.events.emit("error", error);
1161
+ }
1030
1162
  }
1031
1163
  //#region deleteData
1032
1164
  /**
@@ -1034,17 +1166,15 @@ var DataStore = class extends NanoEmitter {
1034
1166
  * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
1035
1167
  * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
1036
1168
  */
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
- });
1169
+ async deleteData() {
1170
+ var _a, _b;
1171
+ await Promise.allSettled([
1172
+ this.engine.deleteValue(`${this.keyPrefix}${this.id}-dat`),
1173
+ this.engine.deleteValue(`${this.keyPrefix}${this.id}-ver`),
1174
+ this.engine.deleteValue(`${this.keyPrefix}${this.id}-enf`)
1175
+ ]);
1176
+ await ((_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a));
1177
+ this.events.emit("deleteData");
1048
1178
  }
1049
1179
  //#region encodingEnabled
1050
1180
  /** Returns whether encoding and decoding are enabled for this DataStore instance */
@@ -1059,83 +1189,79 @@ var DataStore = class extends NanoEmitter {
1059
1189
  *
1060
1190
  * 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
1191
  */
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
- }
1192
+ async runMigrations(oldData, oldFmtVer, resetOnError = true) {
1193
+ if (!this.migrations)
1194
+ return oldData;
1195
+ let newData = oldData;
1196
+ const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
1197
+ let lastFmtVer = oldFmtVer;
1198
+ for (let i = 0; i < sortedMigrations.length; i++) {
1199
+ const [fmtVer, migrationFunc] = sortedMigrations[i];
1200
+ const ver = Number(fmtVer);
1201
+ if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
1202
+ try {
1203
+ const migRes = migrationFunc(newData);
1204
+ newData = migRes instanceof Promise ? await migRes : migRes;
1205
+ lastFmtVer = oldFmtVer = ver;
1206
+ const isFinal = ver >= this.formatVersion || i === sortedMigrations.length - 1;
1207
+ this.events.emit("migrateData", ver, newData, isFinal);
1208
+ } catch (err) {
1209
+ const migError = new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
1210
+ this.events.emit("migrationError", ver, migError);
1211
+ this.events.emit("error", migError);
1212
+ if (!resetOnError)
1213
+ throw migError;
1214
+ await this.saveDefaultData();
1215
+ return this.engine.deepCopy(this.defaultData);
1088
1216
  }
1089
1217
  }
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
- });
1218
+ }
1219
+ await Promise.allSettled([
1220
+ this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(newData, this.encodingEnabled())),
1221
+ this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, lastFmtVer),
1222
+ this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat)
1223
+ ]);
1224
+ const result = this.memoryCache ? this.cachedData = this.engine.deepCopy(newData) : this.engine.deepCopy(newData);
1225
+ this.events.emit("updateData", result);
1226
+ return result;
1099
1227
  }
1100
1228
  //#region migrateId
1101
1229
  /**
1102
1230
  * Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
1103
1231
  * 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
1232
  */
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`)
1233
+ async migrateId(oldIds) {
1234
+ const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
1235
+ await Promise.all(ids.map(async (id) => {
1236
+ const [data, fmtVer, isEncoded] = await (async () => {
1237
+ const [d, f, e] = await Promise.all([
1238
+ this.engine.getValue(`${this.keyPrefix}${id}-dat`, JSON.stringify(this.defaultData)),
1239
+ this.engine.getValue(`${this.keyPrefix}${id}-ver`, NaN),
1240
+ this.engine.getValue(`${this.keyPrefix}${id}-enf`, null)
1127
1241
  ]);
1128
- this.events.emit("migrateId", id, this.id);
1129
- })));
1130
- });
1242
+ return [d, Number(f), Boolean(e) && String(e) !== "null"];
1243
+ })();
1244
+ if (data === void 0 || isNaN(fmtVer))
1245
+ return;
1246
+ const parsed = await this.engine.deserializeData(data, isEncoded);
1247
+ await Promise.allSettled([
1248
+ this.engine.setValue(`${this.keyPrefix}${this.id}-dat`, await this.engine.serializeData(parsed, this.encodingEnabled())),
1249
+ this.engine.setValue(`${this.keyPrefix}${this.id}-ver`, fmtVer),
1250
+ this.engine.setValue(`${this.keyPrefix}${this.id}-enf`, this.compressionFormat),
1251
+ this.engine.deleteValue(`${this.keyPrefix}${id}-dat`),
1252
+ this.engine.deleteValue(`${this.keyPrefix}${id}-ver`),
1253
+ this.engine.deleteValue(`${this.keyPrefix}${id}-enf`)
1254
+ ]);
1255
+ this.events.emit("migrateId", id, this.id);
1256
+ }));
1131
1257
  }
1132
1258
  };
1133
1259
 
1134
1260
  // lib/DataStoreEngine.ts
1135
1261
  var DataStoreEngine = class {
1262
+ dataStoreOptions;
1136
1263
  // setDataStoreOptions() is called from inside the DataStore constructor to set this value
1137
1264
  constructor(options) {
1138
- __publicField(this, "dataStoreOptions");
1139
1265
  if (options)
1140
1266
  this.dataStoreOptions = options;
1141
1267
  }
@@ -1145,29 +1271,25 @@ var DataStoreEngine = class {
1145
1271
  }
1146
1272
  //#region serialization api
1147
1273
  /** 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
- 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
- });
1274
+ async serializeData(data, useEncoding) {
1275
+ var _a, _b, _c, _d, _e;
1276
+ this.ensureDataStoreOptions();
1277
+ const stringData = JSON.stringify(data);
1278
+ if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
1279
+ return stringData;
1280
+ const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
1281
+ if (encRes instanceof Promise)
1282
+ return await encRes;
1283
+ return encRes;
1160
1284
  }
1161
1285
  /** 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
- 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
- });
1286
+ async deserializeData(data, useEncoding) {
1287
+ var _a, _b, _c;
1288
+ this.ensureDataStoreOptions();
1289
+ 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;
1290
+ if (decRes instanceof Promise)
1291
+ decRes = await decRes;
1292
+ return JSON.parse(decRes ?? data);
1171
1293
  }
1172
1294
  //#region misc api
1173
1295
  /** Throws an error if the DataStoreOptions are not set or invalid */
@@ -1185,12 +1307,13 @@ var DataStoreEngine = class {
1185
1307
  try {
1186
1308
  if ("structuredClone" in globalThis)
1187
1309
  return structuredClone(obj);
1188
- } catch (e) {
1310
+ } catch {
1189
1311
  }
1190
1312
  return JSON.parse(JSON.stringify(obj));
1191
1313
  }
1192
1314
  };
1193
1315
  var BrowserStorageEngine = class extends DataStoreEngine {
1316
+ options;
1194
1317
  /**
1195
1318
  * Creates an instance of `BrowserStorageEngine`.
1196
1319
  *
@@ -1199,40 +1322,36 @@ var BrowserStorageEngine = class extends DataStoreEngine {
1199
1322
  */
1200
1323
  constructor(options) {
1201
1324
  super(options == null ? void 0 : options.dataStoreOptions);
1202
- __publicField(this, "options");
1203
- this.options = __spreadValues({
1204
- type: "localStorage"
1205
- }, options);
1325
+ this.options = {
1326
+ type: "localStorage",
1327
+ ...options
1328
+ };
1206
1329
  }
1207
1330
  //#region storage api
1208
1331
  /** Fetches a value from persistent storage */
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
- });
1332
+ async getValue(name, defaultValue) {
1333
+ const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
1334
+ return typeof val === "undefined" ? defaultValue : val;
1214
1335
  }
1215
1336
  /** Sets a value in persistent storage */
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
- });
1337
+ async setValue(name, value) {
1338
+ if (this.options.type === "localStorage")
1339
+ globalThis.localStorage.setItem(name, String(value));
1340
+ else
1341
+ globalThis.sessionStorage.setItem(name, String(value));
1223
1342
  }
1224
1343
  /** Deletes a value from persistent storage */
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
- });
1344
+ async deleteValue(name) {
1345
+ if (this.options.type === "localStorage")
1346
+ globalThis.localStorage.removeItem(name);
1347
+ else
1348
+ globalThis.sessionStorage.removeItem(name);
1232
1349
  }
1233
1350
  };
1234
1351
  var fs;
1235
1352
  var FileStorageEngine = class extends DataStoreEngine {
1353
+ options;
1354
+ fileAccessQueue = Promise.resolve();
1236
1355
  /**
1237
1356
  * Creates an instance of `FileStorageEngine`.
1238
1357
  *
@@ -1241,160 +1360,150 @@ var FileStorageEngine = class extends DataStoreEngine {
1241
1360
  */
1242
1361
  constructor(options) {
1243
1362
  super(options == null ? void 0 : options.dataStoreOptions);
1244
- __publicField(this, "options");
1245
- __publicField(this, "fileAccessQueue", Promise.resolve());
1246
- this.options = __spreadValues({
1247
- filePath: (id) => `.ds-${id}`
1248
- }, options);
1363
+ this.options = {
1364
+ filePath: (id) => `.ds-${id}`,
1365
+ ...options
1366
+ };
1249
1367
  }
1250
1368
  //#region json file
1251
1369
  /** Reads the file contents */
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
- });
1370
+ async readFile() {
1371
+ var _a, _b, _c, _d;
1372
+ this.ensureDataStoreOptions();
1373
+ try {
1374
+ if (!fs)
1375
+ fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
1376
+ if (!fs)
1377
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1378
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
1379
+ const data = await fs.readFile(path, "utf-8");
1380
+ 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;
1381
+ } catch {
1382
+ return void 0;
1383
+ }
1268
1384
  }
1269
1385
  /** Overwrites the file contents */
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
- });
1386
+ async writeFile(data) {
1387
+ var _a, _b, _c, _d;
1388
+ this.ensureDataStoreOptions();
1389
+ try {
1390
+ if (!fs)
1391
+ fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
1392
+ if (!fs)
1393
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1394
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
1395
+ await fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
1396
+ 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");
1397
+ } catch (err) {
1398
+ console.error("Error writing file:", err);
1399
+ }
1286
1400
  }
1287
1401
  //#region storage api
1288
1402
  /** Fetches a value from persistent storage */
1289
- getValue(name, defaultValue) {
1290
- return __async(this, null, function* () {
1291
- const data = yield this.readFile();
1292
- if (!data)
1293
- return defaultValue;
1294
- const value = data == null ? void 0 : data[name];
1295
- if (typeof value === "undefined")
1403
+ async getValue(name, defaultValue) {
1404
+ const data = await this.readFile();
1405
+ if (!data)
1406
+ return defaultValue;
1407
+ const value = data == null ? void 0 : data[name];
1408
+ if (typeof value === "undefined")
1409
+ return defaultValue;
1410
+ if (typeof defaultValue === "string") {
1411
+ if (typeof value === "object" && value !== null)
1412
+ return JSON.stringify(value);
1413
+ if (typeof value === "string")
1414
+ return value;
1415
+ return String(value);
1416
+ }
1417
+ if (typeof value === "string") {
1418
+ try {
1419
+ const parsed = JSON.parse(value);
1420
+ return parsed;
1421
+ } catch {
1296
1422
  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
1423
  }
1424
+ }
1425
+ return value;
1426
+ }
1427
+ /** Sets a value in persistent storage */
1428
+ async setValue(name, value) {
1429
+ this.fileAccessQueue = this.fileAccessQueue.then(async () => {
1430
+ let data = await this.readFile();
1431
+ if (!data)
1432
+ data = {};
1433
+ let storeVal = value;
1304
1434
  if (typeof value === "string") {
1305
1435
  try {
1306
- const parsed = JSON.parse(value);
1307
- return parsed;
1308
- } catch (e) {
1309
- return defaultValue;
1436
+ if (value.startsWith("{") || value.startsWith("[")) {
1437
+ const parsed = JSON.parse(value);
1438
+ if (typeof parsed === "object" && parsed !== null)
1439
+ storeVal = parsed;
1440
+ }
1441
+ } catch {
1310
1442
  }
1311
1443
  }
1312
- return value;
1444
+ data[name] = storeVal;
1445
+ await this.writeFile(data);
1446
+ }).catch((err) => {
1447
+ console.error("Error in setValue:", err);
1448
+ throw err;
1313
1449
  });
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
- });
1450
+ await this.fileAccessQueue.catch(() => {
1341
1451
  });
1342
1452
  }
1343
1453
  /** Deletes a value from persistent storage */
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
- });
1454
+ async deleteValue(name) {
1455
+ this.fileAccessQueue = this.fileAccessQueue.then(async () => {
1456
+ const data = await this.readFile();
1457
+ if (!data)
1458
+ return;
1459
+ delete data[name];
1460
+ await this.writeFile(data);
1461
+ }).catch((err) => {
1462
+ console.error("Error in deleteValue:", err);
1463
+ throw err;
1464
+ });
1465
+ await this.fileAccessQueue.catch(() => {
1358
1466
  });
1359
1467
  }
1360
1468
  /** Deletes the file that contains the data of this DataStore. */
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
- });
1469
+ async deleteStorage() {
1470
+ var _a;
1471
+ this.ensureDataStoreOptions();
1472
+ try {
1473
+ if (!fs)
1474
+ fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
1475
+ if (!fs)
1476
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1477
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id, this.dataStoreOptions);
1478
+ return await fs.unlink(path);
1479
+ } catch (err) {
1480
+ console.error("Error deleting file:", err);
1481
+ }
1376
1482
  }
1377
1483
  };
1378
1484
 
1379
1485
  // lib/DataStoreSerializer.ts
1380
1486
  var DataStoreSerializer = class _DataStoreSerializer {
1487
+ stores;
1488
+ // eslint-disable-line @typescript-eslint/no-explicit-any
1489
+ options;
1381
1490
  constructor(stores, options = {}) {
1382
- __publicField(this, "stores");
1383
- __publicField(this, "options");
1384
1491
  if (!crypto || !crypto.subtle)
1385
1492
  throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
1386
1493
  this.stores = stores;
1387
- this.options = __spreadValues({
1494
+ this.options = {
1388
1495
  addChecksum: true,
1389
1496
  ensureIntegrity: true,
1390
- remapIds: {}
1391
- }, options);
1497
+ remapIds: {},
1498
+ ...options
1499
+ };
1392
1500
  }
1393
- /** Calculates the checksum of a string */
1394
- calcChecksum(input) {
1395
- return __async(this, null, function* () {
1396
- return computeHash(input, "SHA-256");
1397
- });
1501
+ /**
1502
+ * Calculates the checksum of a string. Uses {@linkcode computeHash()} with SHA-256 and digests as a hex string by default.
1503
+ * Override this in a subclass if a custom checksum method is needed.
1504
+ */
1505
+ async calcChecksum(input) {
1506
+ return computeHash(input, "SHA-256");
1398
1507
  }
1399
1508
  /**
1400
1509
  * Serializes only a subset of the data stores into a string.
@@ -1402,80 +1511,72 @@ var DataStoreSerializer = class _DataStoreSerializer {
1402
1511
  * @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
1403
1512
  * @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
1404
1513
  */
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
- });
1514
+ async serializePartial(stores, useEncoding = true, stringified = true) {
1515
+ var _a;
1516
+ const serData = [];
1517
+ const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
1518
+ for (const storeInst of filteredStores) {
1519
+ const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
1520
+ const rawData = storeInst.memoryCache ? storeInst.getData() : await storeInst.loadData();
1521
+ const data = encoded ? await storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
1522
+ serData.push({
1523
+ id: storeInst.id,
1524
+ data,
1525
+ formatVersion: storeInst.formatVersion,
1526
+ encoded,
1527
+ checksum: this.options.addChecksum ? await this.calcChecksum(data) : void 0
1528
+ });
1529
+ }
1530
+ return stringified ? JSON.stringify(serData) : serData;
1424
1531
  }
1425
1532
  /**
1426
1533
  * Serializes the data stores into a string.
1427
1534
  * @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
1428
1535
  * @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
1429
1536
  */
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
- });
1537
+ async serialize(useEncoding = true, stringified = true) {
1538
+ return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
1434
1539
  }
1435
1540
  /**
1436
1541
  * Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
1437
1542
  * Also triggers the migration process if the data format has changed.
1438
1543
  */
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}"!
1544
+ async deserializePartial(stores, data) {
1545
+ const deserStores = typeof data === "string" ? JSON.parse(data) : data;
1546
+ if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
1547
+ throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
1548
+ const resolveStoreId = (id) => {
1549
+ var _a;
1550
+ return ((_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) ?? id;
1551
+ };
1552
+ const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
1553
+ for (const storeData of deserStores) {
1554
+ const effectiveId = resolveStoreId(storeData.id);
1555
+ if (!matchesFilter(effectiveId))
1556
+ continue;
1557
+ const storeInst = this.stores.find((s) => s.id === effectiveId);
1558
+ if (!storeInst)
1559
+ 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.`);
1560
+ if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
1561
+ const checksum = await this.calcChecksum(storeData.data);
1562
+ if (checksum !== storeData.checksum)
1563
+ throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
1460
1564
  Expected: ${storeData.checksum}
1461
1565
  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
1566
  }
1469
- });
1567
+ const decodedData = storeData.encoded && storeInst.encodingEnabled() ? await storeInst.decodeData[1](storeData.data) : storeData.data;
1568
+ if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
1569
+ await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
1570
+ else
1571
+ await storeInst.setData(JSON.parse(decodedData));
1572
+ }
1470
1573
  }
1471
1574
  /**
1472
1575
  * Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
1473
1576
  * Also triggers the migration process if the data format has changed.
1474
1577
  */
1475
- deserialize(data) {
1476
- return __async(this, null, function* () {
1477
- return this.deserializePartial(this.stores.map((s) => s.id), data);
1478
- });
1578
+ async deserialize(data) {
1579
+ return this.deserializePartial(this.stores.map((s) => s.id), data);
1479
1580
  }
1480
1581
  /**
1481
1582
  * Loads the persistent data of the DataStore instances into the in-memory cache.
@@ -1483,6 +1584,155 @@ Has: ${checksum}`);
1483
1584
  * @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
1585
  * @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
1485
1586
  */
1587
+ async loadStoresData(stores) {
1588
+ return Promise.allSettled(
1589
+ this.getStoresFiltered(stores).map(async (store) => ({
1590
+ id: store.id,
1591
+ data: await store.loadData()
1592
+ }))
1593
+ );
1594
+ }
1595
+ /**
1596
+ * Resets the persistent and in-memory data of the DataStore instances to their default values.
1597
+ * @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
1598
+ */
1599
+ async resetStoresData(stores) {
1600
+ return Promise.allSettled(
1601
+ this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
1602
+ );
1603
+ }
1604
+ /**
1605
+ * Deletes the persistent data of the DataStore instances.
1606
+ * Leaves the in-memory data untouched.
1607
+ * @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
1608
+ */
1609
+ async deleteStoresData(stores) {
1610
+ return Promise.allSettled(
1611
+ this.getStoresFiltered(stores).map((store) => store.deleteData())
1612
+ );
1613
+ }
1614
+ /** Checks if a given value is an array of SerializedDataStore objects */
1615
+ static isSerializedDataStoreObjArray(obj) {
1616
+ return Array.isArray(obj) && obj.every((o) => typeof o === "object" && o !== null && "id" in o && "data" in o && "formatVersion" in o && "encoded" in o);
1617
+ }
1618
+ /** Checks if a given value is a SerializedDataStore object */
1619
+ static isSerializedDataStoreObj(obj) {
1620
+ return typeof obj === "object" && obj !== null && "id" in obj && "data" in obj && "formatVersion" in obj && "encoded" in obj;
1621
+ }
1622
+ /** Returns the DataStore instances whose IDs match the provided array or function */
1623
+ getStoresFiltered(stores) {
1624
+ return this.stores.filter((s) => typeof stores === "undefined" ? true : Array.isArray(stores) ? stores.includes(s.id) : stores(s.id));
1625
+ }
1626
+ };
1627
+
1628
+ // lib/Debouncer.ts
1629
+ var Debouncer = class extends NanoEmitter {
1630
+ /**
1631
+ * Creates a new debouncer with the specified timeout and edge type.
1632
+ * @param timeout Timeout in milliseconds between letting through calls - defaults to 200
1633
+ * @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"
1634
+ */
1635
+ constructor(timeout = 200, type = "immediate", nanoEmitterOptions) {
1636
+ super(nanoEmitterOptions);
1637
+ this.timeout = timeout;
1638
+ this.type = type;
1639
+ }
1640
+ /** All registered listener functions and the time they were attached */
1641
+ listeners = [];
1642
+ /** The currently active timeout */
1643
+ activeTimeout;
1644
+ /** The latest queued call */
1645
+ queuedCall;
1646
+ //#region listeners
1647
+ /** Adds a listener function that will be called on timeout */
1648
+ addListener(fn) {
1649
+ this.listeners.push(fn);
1650
+ }
1651
+ /** Removes the listener with the specified function reference */
1652
+ removeListener(fn) {
1653
+ const idx = this.listeners.findIndex((l) => l === fn);
1654
+ idx !== -1 && this.listeners.splice(idx, 1);
1655
+ }
1656
+ /** Removes all listeners */
1657
+ removeAllListeners() {
1658
+ this.listeners = [];
1659
+ }
1660
+ /** Returns all registered listeners */
1661
+ getListeners() {
1662
+ return this.listeners;
1663
+ }
1664
+ //#region timeout
1665
+ /** Sets the timeout for the debouncer */
1666
+ setTimeout(timeout) {
1667
+ this.events.emit("change", this.timeout = timeout, this.type);
1668
+ }
1669
+ /** Returns the current timeout */
1670
+ getTimeout() {
1671
+ return this.timeout;
1672
+ }
1673
+ /** Whether the timeout is currently active, meaning any latest call to the {@linkcode call()} method will be queued */
1674
+ isTimeoutActive() {
1675
+ return typeof this.activeTimeout !== "undefined";
1676
+ }
1677
+ //#region type
1678
+ /** Sets the edge type for the debouncer */
1679
+ setType(type) {
1680
+ this.events.emit("change", this.timeout, this.type = type);
1681
+ }
1682
+ /** Returns the current edge type */
1683
+ getType() {
1684
+ return this.type;
1685
+ }
1686
+ //#region call
1687
+ /** Use this to call the debouncer with the specified arguments that will be passed to all listener functions registered with {@linkcode addListener()} */
1688
+ call(...args) {
1689
+ const cl = (...a) => {
1690
+ this.queuedCall = void 0;
1691
+ this.events.emit("call", ...a);
1692
+ this.listeners.forEach((l) => l.call(this, ...a));
1693
+ };
1694
+ const setRepeatTimeout = () => {
1695
+ this.activeTimeout = setTimeout(() => {
1696
+ if (this.queuedCall) {
1697
+ this.queuedCall();
1698
+ setRepeatTimeout();
1699
+ } else
1700
+ this.activeTimeout = void 0;
1701
+ }, this.timeout);
1702
+ };
1703
+ switch (this.type) {
1704
+ case "immediate":
1705
+ if (typeof this.activeTimeout === "undefined") {
1706
+ cl(...args);
1707
+ setRepeatTimeout();
1708
+ } else
1709
+ this.queuedCall = () => cl(...args);
1710
+ break;
1711
+ case "idle":
1712
+ if (this.activeTimeout)
1713
+ clearTimeout(this.activeTimeout);
1714
+ this.activeTimeout = setTimeout(() => {
1715
+ cl(...args);
1716
+ this.activeTimeout = void 0;
1717
+ }, this.timeout);
1718
+ break;
1719
+ default:
1720
+ throw new TypeError(`Invalid debouncer type: ${this.type}`);
1721
+ }
1722
+ }
1723
+ };
1724
+ function debounce(fn, timeout = 200, type = "immediate", nanoEmitterOptions) {
1725
+ const debouncer = new Debouncer(timeout, type, nanoEmitterOptions);
1726
+ debouncer.addListener(fn);
1727
+ const func = ((...args) => debouncer.call(...args));
1728
+ func.debouncer = debouncer;
1729
+ return func;
1730
+ }
1731
+ sistent data of the DataStore instances into the in-memory cache.
1732
+ * Also triggers the migration process if the data format has changed.
1733
+ * @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
1734
+ * @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
1735
+ */
1486
1736
  loadStoresData(stores) {
1487
1737
  return __async(this, null, function* () {
1488
1738
  return Promise.allSettled(
@@ -1539,8 +1789,8 @@ var Debouncer = class extends NanoEmitter {
1539
1789
  * @param timeout Timeout in milliseconds between letting through calls - defaults to 200
1540
1790
  * @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
1791
  */
1542
- constructor(timeout = 200, type = "immediate") {
1543
- super();
1792
+ constructor(timeout = 200, type = "immediate", nanoEmitterOptions) {
1793
+ super(nanoEmitterOptions);
1544
1794
  this.timeout = timeout;
1545
1795
  this.type = type;
1546
1796
  /** All registered listener functions and the time they were attached */
@@ -1571,7 +1821,7 @@ var Debouncer = class extends NanoEmitter {
1571
1821
  //#region timeout
1572
1822
  /** Sets the timeout for the debouncer */
1573
1823
  setTimeout(timeout) {
1574
- this.emit("change", this.timeout = timeout, this.type);
1824
+ this.events.emit("change", this.timeout = timeout, this.type);
1575
1825
  }
1576
1826
  /** Returns the current timeout */
1577
1827
  getTimeout() {
@@ -1584,7 +1834,7 @@ var Debouncer = class extends NanoEmitter {
1584
1834
  //#region type
1585
1835
  /** Sets the edge type for the debouncer */
1586
1836
  setType(type) {
1587
- this.emit("change", this.timeout, this.type = type);
1837
+ this.events.emit("change", this.timeout, this.type = type);
1588
1838
  }
1589
1839
  /** Returns the current edge type */
1590
1840
  getType() {
@@ -1595,7 +1845,7 @@ var Debouncer = class extends NanoEmitter {
1595
1845
  call(...args) {
1596
1846
  const cl = (...a) => {
1597
1847
  this.queuedCall = void 0;
1598
- this.emit("call", ...a);
1848
+ this.events.emit("call", ...a);
1599
1849
  this.listeners.forEach((l) => l.call(this, ...a));
1600
1850
  };
1601
1851
  const setRepeatTimeout = () => {
@@ -1628,8 +1878,8 @@ var Debouncer = class extends NanoEmitter {
1628
1878
  }
1629
1879
  }
1630
1880
  };
1631
- function debounce(fn, timeout = 200, type = "immediate") {
1632
- const debouncer = new Debouncer(timeout, type);
1881
+ function debounce(fn, timeout = 200, type = "immediate", nanoEmitterOptions) {
1882
+ const debouncer = new Debouncer(timeout, type, nanoEmitterOptions);
1633
1883
  debouncer.addListener(fn);
1634
1884
  const func = ((...args) => debouncer.call(...args));
1635
1885
  func.debouncer = debouncer;
@@ -1637,7 +1887,7 @@ function debounce(fn, timeout = 200, type = "immediate") {
1637
1887
  }
1638
1888
 
1639
1889
  if(__exports != exports)module.exports = exports;return module.exports}));
1640
-
1890
+ //# sourceMappingURL=CoreUtils.umd.js.map
1641
1891
 
1642
1892
 
1643
1893
  if (typeof module.exports == "object" && typeof exports == "object") {