@sv443-network/coreutils 2.0.2 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,6 +32,7 @@ var lib_exports = {};
32
32
  __export(lib_exports, {
33
33
  BrowserStorageEngine: () => BrowserStorageEngine,
34
34
  ChecksumMismatchError: () => ChecksumMismatchError,
35
+ CustomError: () => CustomError,
35
36
  DataStore: () => DataStore,
36
37
  DataStoreEngine: () => DataStoreEngine,
37
38
  DataStoreSerializer: () => DataStoreSerializer,
@@ -40,6 +41,8 @@ __export(lib_exports, {
40
41
  FileStorageEngine: () => FileStorageEngine,
41
42
  MigrationError: () => MigrationError,
42
43
  NanoEmitter: () => NanoEmitter,
44
+ NetworkError: () => NetworkError,
45
+ ScriptContextError: () => ScriptContextError,
43
46
  ValidationError: () => ValidationError,
44
47
  abtoa: () => abtoa,
45
48
  atoab: () => atoab,
@@ -59,6 +62,7 @@ __export(lib_exports, {
59
62
  digitCount: () => digitCount,
60
63
  fetchAdvanced: () => fetchAdvanced,
61
64
  formatNumber: () => formatNumber,
65
+ getCallStack: () => getCallStack,
62
66
  getListLength: () => getListLength,
63
67
  hexToRgb: () => hexToRgb,
64
68
  insertValues: () => insertValues,
@@ -175,7 +179,7 @@ function roundFixed(num, fractionDigits) {
175
179
  const scale = 10 ** fractionDigits;
176
180
  return Math.round(num * scale) / scale;
177
181
  }
178
- function valsWithin(a, b, dec = 10, withinRange = 0.5) {
182
+ function valsWithin(a, b, dec = 1, withinRange = 0.5) {
179
183
  return Math.abs(roundFixed(a, dec) - roundFixed(b, dec)) <= withinRange;
180
184
  }
181
185
 
@@ -325,6 +329,52 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
325
329
  return arr.map((v) => caseArr[randRange(0, caseArr.length - 1, enhancedEntropy)] === 1 ? v.toUpperCase() : v).join("");
326
330
  }
327
331
 
332
+ // lib/Errors.ts
333
+ var DatedError = class extends Error {
334
+ date;
335
+ constructor(message, options) {
336
+ super(message, options);
337
+ this.name = this.constructor.name;
338
+ this.date = /* @__PURE__ */ new Date();
339
+ }
340
+ };
341
+ var ChecksumMismatchError = class extends DatedError {
342
+ constructor(message, options) {
343
+ super(message, options);
344
+ this.name = "ChecksumMismatchError";
345
+ }
346
+ };
347
+ var CustomError = class extends DatedError {
348
+ constructor(name, message, options) {
349
+ super(message, options);
350
+ this.name = name;
351
+ }
352
+ };
353
+ var MigrationError = class extends DatedError {
354
+ constructor(message, options) {
355
+ super(message, options);
356
+ this.name = "MigrationError";
357
+ }
358
+ };
359
+ var ValidationError = class extends DatedError {
360
+ constructor(message, options) {
361
+ super(message, options);
362
+ this.name = "ValidationError";
363
+ }
364
+ };
365
+ var ScriptContextError = class extends DatedError {
366
+ constructor(message, options) {
367
+ super(message, options);
368
+ this.name = "ScriptContextError";
369
+ }
370
+ };
371
+ var NetworkError = class extends DatedError {
372
+ constructor(message, options) {
373
+ super(message, options);
374
+ this.name = "NetworkError";
375
+ }
376
+ };
377
+
328
378
  // lib/misc.ts
329
379
  async function consumeGen(valGen) {
330
380
  return await (typeof valGen === "function" ? valGen() : valGen);
@@ -353,7 +403,7 @@ async function fetchAdvanced(input, options = {}) {
353
403
  return res;
354
404
  } catch (err) {
355
405
  typeof id !== "undefined" && clearTimeout(id);
356
- throw new Error("Error while calling fetch", { cause: err });
406
+ throw new NetworkError("Error while calling fetch", { cause: err });
357
407
  }
358
408
  }
359
409
  function getListLength(listLike, zeroOnInvalid = true) {
@@ -364,7 +414,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
364
414
  const timeout = setTimeout(() => res(), time);
365
415
  signal == null ? void 0 : signal.addEventListener("abort", () => {
366
416
  clearTimeout(timeout);
367
- rejectOnAbort ? rej(new Error("The pause was aborted")) : res();
417
+ rejectOnAbort ? rej(new CustomError("AbortError", "The pause was aborted")) : res();
368
418
  });
369
419
  });
370
420
  }
@@ -399,14 +449,24 @@ function scheduleExit(code = 0, timeout = 0) {
399
449
  if (timeout < 0)
400
450
  throw new TypeError("Timeout must be a non-negative number");
401
451
  let exit;
402
- if (typeof process !== "undefined" && "exit" in process)
452
+ if (typeof process !== "undefined" && "exit" in process && typeof process.exit === "function")
403
453
  exit = () => process.exit(code);
404
- else if (typeof Deno !== "undefined" && "exit" in Deno)
454
+ else if (typeof Deno !== "undefined" && "exit" in Deno && typeof Deno.exit === "function")
405
455
  exit = () => Deno.exit(code);
406
456
  else
407
- throw new Error("Cannot exit the process, no exit method available");
457
+ throw new ScriptContextError("Cannot exit the process, no exit method available");
408
458
  setTimeout(exit, timeout);
409
459
  }
460
+ function getCallStack(asArray, lines = Infinity) {
461
+ if (typeof lines !== "number" || isNaN(lines) || lines < 0)
462
+ throw new TypeError("lines parameter must be a non-negative number");
463
+ try {
464
+ throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)");
465
+ } catch (err) {
466
+ const stack = (err.stack ?? "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
467
+ return asArray !== false ? stack : stack.join("\n");
468
+ }
469
+ }
410
470
 
411
471
  // lib/text.ts
412
472
  function autoPlural(term, num, pluralType = "auto") {
@@ -476,16 +536,18 @@ function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
476
536
  return arr.join(separators) + lastItm;
477
537
  }
478
538
  function secsToTimeStr(seconds) {
479
- if (seconds < 0)
480
- throw new TypeError("Seconds must be a positive number");
481
- const hours = Math.floor(seconds / 3600);
482
- const minutes = Math.floor(seconds % 3600 / 60);
483
- const secs = Math.floor(seconds % 60);
484
- return [
485
- hours ? hours + ":" : "",
486
- String(minutes).padStart(minutes > 0 || hours > 0 ? 2 : 1, "0"),
539
+ const isNegative = seconds < 0;
540
+ const s = Math.abs(seconds);
541
+ if (isNaN(s) || !isFinite(s))
542
+ throw new TypeError("The seconds argument must be a valid number");
543
+ const hrs = Math.floor(s / 3600);
544
+ const mins = Math.floor(s % 3600 / 60);
545
+ const secs = Math.floor(s % 60);
546
+ return (isNegative ? "-" : "") + [
547
+ hrs ? hrs + ":" : "",
548
+ String(mins).padStart(mins > 0 || hrs > 0 ? 2 : 1, "0"),
487
549
  ":",
488
- String(secs).padStart(secs > 0 || minutes > 0 || hours > 0 ? 2 : 1, "0")
550
+ String(secs).padStart(secs > 0 || mins > 0 || hrs > 0 || seconds === 0 ? 2 : 1, "0")
489
551
  ].join("");
490
552
  }
491
553
  function truncStr(input, length, endStr = "...") {
@@ -494,34 +556,6 @@ function truncStr(input, length, endStr = "...") {
494
556
  return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
495
557
  }
496
558
 
497
- // lib/Errors.ts
498
- var DatedError = class extends Error {
499
- date;
500
- constructor(message, options) {
501
- super(message, options);
502
- this.name = this.constructor.name;
503
- this.date = /* @__PURE__ */ new Date();
504
- }
505
- };
506
- var ChecksumMismatchError = class extends DatedError {
507
- constructor(message, options) {
508
- super(message, options);
509
- this.name = "ChecksumMismatchError";
510
- }
511
- };
512
- var MigrationError = class extends DatedError {
513
- constructor(message, options) {
514
- super(message, options);
515
- this.name = "MigrationError";
516
- }
517
- };
518
- var ValidationError = class extends DatedError {
519
- constructor(message, options) {
520
- super(message, options);
521
- this.name = "ValidationError";
522
- }
523
- };
524
-
525
559
  // lib/DataStore.ts
526
560
  var dsFmtVer = 1;
527
561
  var DataStore = class {
@@ -531,6 +565,7 @@ var DataStore = class {
531
565
  encodeData;
532
566
  decodeData;
533
567
  compressionFormat = "deflate-raw";
568
+ memoryCache = true;
534
569
  engine;
535
570
  options;
536
571
  /**
@@ -543,6 +578,7 @@ var DataStore = class {
543
578
  cachedData;
544
579
  migrations;
545
580
  migrateIds = [];
581
+ //#region constructor
546
582
  /**
547
583
  * Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
548
584
  * Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
@@ -557,7 +593,8 @@ var DataStore = class {
557
593
  this.id = opts.id;
558
594
  this.formatVersion = opts.formatVersion;
559
595
  this.defaultData = opts.defaultData;
560
- this.cachedData = opts.defaultData;
596
+ this.memoryCache = Boolean(opts.memoryCache ?? true);
597
+ this.cachedData = this.memoryCache ? opts.defaultData : {};
561
598
  this.migrations = opts.migrations;
562
599
  if (opts.migrateIds)
563
600
  this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
@@ -582,7 +619,7 @@ var DataStore = class {
582
619
  throw new TypeError("Either `compressionFormat` or `encodeData` and `decodeData` have to be set and valid, but not all three at a time. Please refer to the documentation for more info.");
583
620
  this.engine.setDataStoreOptions(opts);
584
621
  }
585
- //#region public
622
+ //#region loadData
586
623
  /**
587
624
  * Loads the data saved in persistent storage into the in-memory cache and also returns a copy of it.
588
625
  * Automatically populates persistent storage with default data if it doesn't contain any data yet.
@@ -593,39 +630,40 @@ var DataStore = class {
593
630
  if (this.firstInit) {
594
631
  this.firstInit = false;
595
632
  const dsVer = Number(await this.engine.getValue("__ds_fmt_ver", 0));
596
- if (isNaN(dsVer) || dsVer < 1) {
597
- const oldData = await this.engine.getValue(`_uucfg-${this.id}`, null);
598
- if (oldData) {
599
- const oldVer = Number(await this.engine.getValue(`_uucfgver-${this.id}`, NaN));
600
- const oldEnc = await this.engine.getValue(`_uucfgenc-${this.id}`, null);
601
- const promises = [];
602
- const migrateFmt = (oldKey, newKey, value) => {
603
- promises.push(this.engine.setValue(newKey, value));
604
- promises.push(this.engine.deleteValue(oldKey));
605
- };
606
- if (oldData)
607
- migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
608
- if (!isNaN(oldVer))
609
- migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
610
- if (typeof oldEnc === "boolean")
611
- migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? Boolean(this.compressionFormat) || null : null);
612
- else
613
- promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
614
- await Promise.allSettled(promises);
633
+ const oldData = await this.engine.getValue(`_uucfg-${this.id}`, null);
634
+ if (oldData) {
635
+ const oldVer = Number(await this.engine.getValue(`_uucfgver-${this.id}`, NaN));
636
+ const oldEnc = await this.engine.getValue(`_uucfgenc-${this.id}`, null);
637
+ const promises = [];
638
+ const migrateFmt = (oldKey, newKey, value) => {
639
+ promises.push(this.engine.setValue(newKey, value));
640
+ promises.push(this.engine.deleteValue(oldKey));
641
+ };
642
+ migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
643
+ if (!isNaN(oldVer))
644
+ migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
645
+ if (typeof oldEnc === "boolean")
646
+ migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? this.compressionFormat ?? null : null);
647
+ else {
648
+ promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
649
+ promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
615
650
  }
616
- await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
651
+ await Promise.allSettled(promises);
617
652
  }
653
+ if (isNaN(dsVer) || dsVer < dsFmtVer)
654
+ await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
618
655
  }
619
656
  if (this.migrateIds.length > 0) {
620
657
  await this.migrateId(this.migrateIds);
621
658
  this.migrateIds = [];
622
659
  }
623
- const storedData = await this.engine.getValue(`__ds-${this.id}-dat`, JSON.stringify(this.defaultData));
660
+ const storedDataRaw = await this.engine.getValue(`__ds-${this.id}-dat`, null);
624
661
  let storedFmtVer = Number(await this.engine.getValue(`__ds-${this.id}-ver`, NaN));
625
- if (typeof storedData !== "string") {
662
+ if (typeof storedDataRaw !== "string") {
626
663
  await this.saveDefaultData();
627
- return { ...this.defaultData };
664
+ return this.engine.deepCopy(this.defaultData);
628
665
  }
666
+ const storedData = storedDataRaw ?? JSON.stringify(this.defaultData);
629
667
  const encodingFmt = String(await this.engine.getValue(`__ds-${this.id}-enf`, null));
630
668
  const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
631
669
  let saveData = false;
@@ -638,23 +676,32 @@ var DataStore = class {
638
676
  parsed = await this.runMigrations(parsed, storedFmtVer);
639
677
  if (saveData)
640
678
  await this.setData(parsed);
641
- return this.cachedData = this.engine.deepCopy(parsed);
679
+ if (this.memoryCache)
680
+ return this.cachedData = this.engine.deepCopy(parsed);
681
+ else
682
+ return this.engine.deepCopy(parsed);
642
683
  } catch (err) {
643
684
  console.warn("Error while parsing JSON data, resetting it to the default value.", err);
644
685
  await this.saveDefaultData();
645
686
  return this.defaultData;
646
687
  }
647
688
  }
689
+ //#region getData
648
690
  /**
649
691
  * Returns a copy of the data from the in-memory cache.
650
- * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
692
+ * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
693
+ * ⚠️ If `memoryCache` was set to `false` in the constructor options, this method will throw an error.
651
694
  */
652
695
  getData() {
696
+ if (!this.memoryCache)
697
+ throw new DatedError("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");
653
698
  return this.engine.deepCopy(this.cachedData);
654
699
  }
700
+ //#region setData
655
701
  /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
656
702
  setData(data) {
657
- this.cachedData = data;
703
+ if (this.memoryCache)
704
+ this.cachedData = data;
658
705
  return new Promise(async (resolve) => {
659
706
  await Promise.allSettled([
660
707
  this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(data, this.encodingEnabled())),
@@ -664,15 +711,18 @@ var DataStore = class {
664
711
  resolve();
665
712
  });
666
713
  }
714
+ //#region saveDefaultData
667
715
  /** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
668
716
  async saveDefaultData() {
669
- this.cachedData = this.defaultData;
717
+ if (this.memoryCache)
718
+ this.cachedData = this.defaultData;
670
719
  await Promise.allSettled([
671
720
  this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(this.defaultData, this.encodingEnabled())),
672
721
  this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
673
722
  this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
674
723
  ]);
675
724
  }
725
+ //#region deleteData
676
726
  /**
677
727
  * Call this method to clear all persistently stored data associated with this DataStore instance, including the storage container (if supported by the DataStoreEngine).
678
728
  * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
@@ -687,11 +737,12 @@ var DataStore = class {
687
737
  ]);
688
738
  await ((_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a));
689
739
  }
740
+ //#region encodingEnabled
690
741
  /** Returns whether encoding and decoding are enabled for this DataStore instance */
691
742
  encodingEnabled() {
692
743
  return Boolean(this.encodeData && this.decodeData) && this.compressionFormat !== null || Boolean(this.compressionFormat);
693
744
  }
694
- //#region migrations
745
+ //#region runMigrations
695
746
  /**
696
747
  * Runs all necessary migration functions consecutively and saves the result to the in-memory cache and persistent storage and also returns it.
697
748
  * This method is automatically called by {@linkcode loadData()} if the data format has changed since the last time the data was saved.
@@ -725,8 +776,12 @@ var DataStore = class {
725
776
  this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
726
777
  this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
727
778
  ]);
728
- return this.cachedData = { ...newData };
779
+ if (this.memoryCache)
780
+ return this.cachedData = this.engine.deepCopy(newData);
781
+ else
782
+ return this.engine.deepCopy(newData);
729
783
  }
784
+ //#region migrateId
730
785
  /**
731
786
  * Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
732
787
  * 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.
@@ -770,7 +825,7 @@ var DataStoreEngine = class {
770
825
  this.dataStoreOptions = dataStoreOptions;
771
826
  }
772
827
  //#region serialization api
773
- /** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is set to true */
828
+ /** 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 */
774
829
  async serializeData(data, useEncoding) {
775
830
  var _a, _b, _c, _d, _e;
776
831
  this.ensureDataStoreOptions();
@@ -818,7 +873,7 @@ var BrowserStorageEngine = class extends DataStoreEngine {
818
873
  * Creates an instance of `BrowserStorageEngine`.
819
874
  *
820
875
  * - ⚠️ Requires a DOM environment
821
- * - ⚠️ Don't reuse engines across multiple {@linkcode DataStore} instances
876
+ * - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
822
877
  */
823
878
  constructor(options) {
824
879
  super(options == null ? void 0 : options.dataStoreOptions);
@@ -856,7 +911,7 @@ var FileStorageEngine = class extends DataStoreEngine {
856
911
  * Creates an instance of `FileStorageEngine`.
857
912
  *
858
913
  * - ⚠️ Requires Node.js or Deno with Node compatibility (v1.31+)
859
- * - ⚠️ Don't reuse engines across multiple {@linkcode DataStore} instances
914
+ * - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
860
915
  */
861
916
  constructor(options) {
862
917
  super(options == null ? void 0 : options.dataStoreOptions);
@@ -874,7 +929,7 @@ var FileStorageEngine = class extends DataStoreEngine {
874
929
  if (!fs)
875
930
  fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
876
931
  if (!fs)
877
- throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
932
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
878
933
  const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
879
934
  const data = await fs.readFile(path, "utf-8");
880
935
  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;
@@ -890,7 +945,7 @@ var FileStorageEngine = class extends DataStoreEngine {
890
945
  if (!fs)
891
946
  fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
892
947
  if (!fs)
893
- throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
948
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
894
949
  const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
895
950
  await fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
896
951
  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");
@@ -919,8 +974,12 @@ var FileStorageEngine = class extends DataStoreEngine {
919
974
  data = {};
920
975
  data[name] = value;
921
976
  await this.writeFile(data);
977
+ }).catch((err) => {
978
+ console.error("Error in setValue:", err);
979
+ throw err;
980
+ });
981
+ await this.fileAccessQueue.catch(() => {
922
982
  });
923
- await this.fileAccessQueue;
924
983
  }
925
984
  /** Deletes a value from persistent storage */
926
985
  async deleteValue(name) {
@@ -930,8 +989,12 @@ var FileStorageEngine = class extends DataStoreEngine {
930
989
  return;
931
990
  delete data[name];
932
991
  await this.writeFile(data);
992
+ }).catch((err) => {
993
+ console.error("Error in deleteValue:", err);
994
+ throw err;
995
+ });
996
+ await this.fileAccessQueue.catch(() => {
933
997
  });
934
- await this.fileAccessQueue;
935
998
  }
936
999
  /** Deletes the file that contains the data of this DataStore. */
937
1000
  async deleteStorage() {
@@ -941,9 +1004,9 @@ var FileStorageEngine = class extends DataStoreEngine {
941
1004
  if (!fs)
942
1005
  fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
943
1006
  if (!fs)
944
- throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
1007
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
945
1008
  const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
946
- await fs.unlink(path);
1009
+ return await fs.unlink(path);
947
1010
  } catch (err) {
948
1011
  console.error("Error deleting file:", err);
949
1012
  }
@@ -956,11 +1019,12 @@ var DataStoreSerializer = class _DataStoreSerializer {
956
1019
  options;
957
1020
  constructor(stores, options = {}) {
958
1021
  if (!crypto || !crypto.subtle)
959
- throw new Error("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
1022
+ throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
960
1023
  this.stores = stores;
961
1024
  this.options = {
962
1025
  addChecksum: true,
963
1026
  ensureIntegrity: true,
1027
+ remapIds: {},
964
1028
  ...options
965
1029
  };
966
1030
  }
@@ -977,9 +1041,11 @@ var DataStoreSerializer = class _DataStoreSerializer {
977
1041
  async serializePartial(stores, useEncoding = true, stringified = true) {
978
1042
  var _a;
979
1043
  const serData = [];
980
- for (const storeInst of this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id))) {
1044
+ const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
1045
+ for (const storeInst of filteredStores) {
981
1046
  const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
982
- const data = encoded ? await storeInst.encodeData[1](JSON.stringify(storeInst.getData())) : JSON.stringify(storeInst.getData());
1047
+ const rawData = storeInst.memoryCache ? storeInst.getData() : await storeInst.loadData();
1048
+ const data = encoded ? await storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
983
1049
  serData.push({
984
1050
  id: storeInst.id,
985
1051
  data,
@@ -1006,10 +1072,18 @@ var DataStoreSerializer = class _DataStoreSerializer {
1006
1072
  const deserStores = typeof data === "string" ? JSON.parse(data) : data;
1007
1073
  if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
1008
1074
  throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
1009
- for (const storeData of deserStores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id))) {
1010
- const storeInst = this.stores.find((s) => s.id === storeData.id);
1075
+ const resolveStoreId = (id) => {
1076
+ var _a;
1077
+ return ((_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) ?? id;
1078
+ };
1079
+ const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
1080
+ for (const storeData of deserStores) {
1081
+ const effectiveId = resolveStoreId(storeData.id);
1082
+ if (!matchesFilter(effectiveId))
1083
+ continue;
1084
+ const storeInst = this.stores.find((s) => s.id === effectiveId);
1011
1085
  if (!storeInst)
1012
- throw new Error(`DataStore instance with ID "${storeData.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);
1086
+ 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.`);
1013
1087
  if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
1014
1088
  const checksum = await this.calcChecksum(storeData.data);
1015
1089
  if (checksum !== storeData.checksum)
@@ -1164,11 +1238,11 @@ var NanoEmitter = class {
1164
1238
  once(event, cb) {
1165
1239
  return new Promise((resolve) => {
1166
1240
  let unsub;
1167
- const onceProxy = (...args) => {
1241
+ const onceProxy = ((...args) => {
1168
1242
  cb == null ? void 0 : cb(...args);
1169
1243
  unsub == null ? void 0 : unsub();
1170
1244
  resolve(args);
1171
- };
1245
+ });
1172
1246
  unsub = this.events.on(event, onceProxy);
1173
1247
  this.eventUnsubscribes.push(unsub);
1174
1248
  });
@@ -1180,11 +1254,12 @@ var NanoEmitter = class {
1180
1254
  * `callback` (required) is the function that will be called when the conditions are met.
1181
1255
  *
1182
1256
  * 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.
1183
- * If `signal` is provided, the subscription will be aborted when the given signal is aborted.
1257
+ * If `signal` is provided, the subscription will be canceled when the given signal is aborted.
1184
1258
  *
1185
1259
  * If `oneOf` is used, the callback will be called when any of the matching events are emitted.
1186
1260
  * 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.
1187
- * You may use a combination of the above two options, but at least one of them must be provided.
1261
+ * 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.
1262
+ * At least one of `oneOf` or `allOf` must be provided.
1188
1263
  *
1189
1264
  * @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.
1190
1265
  */
@@ -1212,6 +1287,8 @@ var NanoEmitter = class {
1212
1287
  } = optsWithDefaults;
1213
1288
  if (signal == null ? void 0 : signal.aborted)
1214
1289
  return unsubAll;
1290
+ if (oneOf.length === 0 && allOf.length === 0)
1291
+ throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
1215
1292
  const curEvtUnsubs = [];
1216
1293
  const checkUnsubAllEvt = (force = false) => {
1217
1294
  if (!(signal == null ? void 0 : signal.aborted) && !force)
@@ -1221,34 +1298,31 @@ var NanoEmitter = class {
1221
1298
  curEvtUnsubs.splice(0, curEvtUnsubs.length);
1222
1299
  this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
1223
1300
  };
1301
+ const allOfEmitted = /* @__PURE__ */ new Set();
1302
+ const allOfConditionMet = () => allOf.length === 0 || allOfEmitted.size === allOf.length;
1224
1303
  for (const event of oneOf) {
1225
- const unsub = this.events.on(event, (...args) => {
1304
+ const unsub = this.events.on(event, ((...args) => {
1226
1305
  checkUnsubAllEvt();
1227
- callback(event, ...args);
1228
- if (once)
1229
- checkUnsubAllEvt(true);
1230
- });
1306
+ if (allOfConditionMet()) {
1307
+ callback(event, ...args);
1308
+ if (once)
1309
+ checkUnsubAllEvt(true);
1310
+ }
1311
+ }));
1231
1312
  curEvtUnsubs.push(unsub);
1232
1313
  }
1233
- const allOfEmitted = /* @__PURE__ */ new Set();
1234
- const checkAllOf = (event, ...args) => {
1235
- checkUnsubAllEvt();
1236
- allOfEmitted.add(event);
1237
- if (allOfEmitted.size === allOf.length) {
1238
- callback(event, ...args);
1239
- if (once)
1240
- checkUnsubAllEvt(true);
1241
- }
1242
- };
1243
1314
  for (const event of allOf) {
1244
- const unsub = this.events.on(event, (...args) => {
1315
+ const unsub = this.events.on(event, ((...args) => {
1245
1316
  checkUnsubAllEvt();
1246
- checkAllOf(event, ...args);
1247
- });
1317
+ allOfEmitted.add(event);
1318
+ if (allOfConditionMet() && (oneOf.length === 0 || oneOf.includes(event))) {
1319
+ callback(event, ...args);
1320
+ if (once)
1321
+ checkUnsubAllEvt(true);
1322
+ }
1323
+ }));
1248
1324
  curEvtUnsubs.push(unsub);
1249
1325
  }
1250
- if (oneOf.length === 0 && allOf.length === 0)
1251
- throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
1252
1326
  allUnsubs.push(() => checkUnsubAllEvt(true));
1253
1327
  }
1254
1328
  return unsubAll;
@@ -1376,7 +1450,7 @@ var Debouncer = class extends NanoEmitter {
1376
1450
  function debounce(fn, timeout = 200, type = "immediate") {
1377
1451
  const debouncer = new Debouncer(timeout, type);
1378
1452
  debouncer.addListener(fn);
1379
- const func = (...args) => debouncer.call(...args);
1453
+ const func = ((...args) => debouncer.call(...args));
1380
1454
  func.debouncer = debouncer;
1381
1455
  return func;
1382
1456
  }