@sv443-network/coreutils 2.0.3 → 3.0.1

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,33 +44,13 @@ 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 = {};
99
50
  __export(lib_exports, {
100
51
  BrowserStorageEngine: () => BrowserStorageEngine,
101
52
  ChecksumMismatchError: () => ChecksumMismatchError,
53
+ CustomError: () => CustomError,
102
54
  DataStore: () => DataStore,
103
55
  DataStoreEngine: () => DataStoreEngine,
104
56
  DataStoreSerializer: () => DataStoreSerializer,
@@ -107,6 +59,8 @@ __export(lib_exports, {
107
59
  FileStorageEngine: () => FileStorageEngine,
108
60
  MigrationError: () => MigrationError,
109
61
  NanoEmitter: () => NanoEmitter,
62
+ NetworkError: () => NetworkError,
63
+ ScriptContextError: () => ScriptContextError,
110
64
  ValidationError: () => ValidationError,
111
65
  abtoa: () => abtoa,
112
66
  atoab: () => atoab,
@@ -126,6 +80,7 @@ __export(lib_exports, {
126
80
  digitCount: () => digitCount,
127
81
  fetchAdvanced: () => fetchAdvanced,
128
82
  formatNumber: () => formatNumber,
83
+ getCallStack: () => getCallStack,
129
84
  getListLength: () => getListLength,
130
85
  hexToRgb: () => hexToRgb,
131
86
  insertValues: () => insertValues,
@@ -239,10 +194,10 @@ function randRange(...args) {
239
194
  return Math.floor(Math.random() * (max - min + 1)) + min;
240
195
  }
241
196
  function roundFixed(num, fractionDigits) {
242
- const scale = __pow(10, fractionDigits);
197
+ const scale = 10 ** fractionDigits;
243
198
  return Math.round(num * scale) / scale;
244
199
  }
245
- function valsWithin(a, b, dec = 10, withinRange = 0.5) {
200
+ function valsWithin(a, b, dec = 1, withinRange = 0.5) {
246
201
  return Math.abs(roundFixed(a, dec) - roundFixed(b, dec)) <= withinRange;
247
202
  }
248
203
 
@@ -303,7 +258,7 @@ function darkenColor(color, percent, upperCase = false) {
303
258
  if (isHexCol)
304
259
  return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
305
260
  else if (color.startsWith("rgba"))
306
- return `rgba(${r}, ${g}, ${b}, ${a != null ? a : NaN})`;
261
+ return `rgba(${r}, ${g}, ${b}, ${a ?? NaN})`;
307
262
  else
308
263
  return `rgb(${r}, ${g}, ${b})`;
309
264
  }
@@ -337,43 +292,35 @@ function abtoa(buf) {
337
292
  function atoab(str) {
338
293
  return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
339
294
  }
340
- function compress(input, compressionFormat, outputType = "string") {
341
- return __async(this, null, function* () {
342
- var _a;
343
- const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
344
- const comp = new CompressionStream(compressionFormat);
345
- const writer = comp.writable.getWriter();
346
- writer.write(byteArray);
347
- writer.close();
348
- const uintArr = new Uint8Array(yield new Response(comp.readable).arrayBuffer());
349
- return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
350
- });
295
+ async function compress(input, compressionFormat, outputType = "string") {
296
+ const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((input == null ? void 0 : input.toString()) ?? String(input));
297
+ const comp = new CompressionStream(compressionFormat);
298
+ const writer = comp.writable.getWriter();
299
+ writer.write(byteArray);
300
+ writer.close();
301
+ const uintArr = new Uint8Array(await new Response(comp.readable).arrayBuffer());
302
+ return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
351
303
  }
352
- function decompress(input, compressionFormat, outputType = "string") {
353
- return __async(this, null, function* () {
354
- var _a;
355
- const byteArray = input instanceof Uint8Array ? input : atoab((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
356
- const decomp = new DecompressionStream(compressionFormat);
357
- const writer = decomp.writable.getWriter();
358
- writer.write(byteArray);
359
- writer.close();
360
- const uintArr = new Uint8Array(yield new Response(decomp.readable).arrayBuffer());
361
- return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
362
- });
304
+ async function decompress(input, compressionFormat, outputType = "string") {
305
+ const byteArray = input instanceof Uint8Array ? input : atoab((input == null ? void 0 : input.toString()) ?? String(input));
306
+ const decomp = new DecompressionStream(compressionFormat);
307
+ const writer = decomp.writable.getWriter();
308
+ writer.write(byteArray);
309
+ writer.close();
310
+ const uintArr = new Uint8Array(await new Response(decomp.readable).arrayBuffer());
311
+ return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
363
312
  }
364
- function computeHash(input, algorithm = "SHA-256") {
365
- return __async(this, null, function* () {
366
- let data;
367
- if (typeof input === "string") {
368
- const encoder = new TextEncoder();
369
- data = encoder.encode(input);
370
- } else
371
- data = input;
372
- const hashBuffer = yield crypto.subtle.digest(algorithm, data);
373
- const hashArray = Array.from(new Uint8Array(hashBuffer));
374
- const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
375
- return hashHex;
376
- });
313
+ async function computeHash(input, algorithm = "SHA-256") {
314
+ let data;
315
+ if (typeof input === "string") {
316
+ const encoder = new TextEncoder();
317
+ data = encoder.encode(input);
318
+ } else
319
+ data = input;
320
+ const hashBuffer = await crypto.subtle.digest(algorithm, data);
321
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
322
+ const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
323
+ return hashHex;
377
324
  }
378
325
  function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
379
326
  if (length < 1)
@@ -400,39 +347,81 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
400
347
  return arr.map((v) => caseArr[randRange(0, caseArr.length - 1, enhancedEntropy)] === 1 ? v.toUpperCase() : v).join("");
401
348
  }
402
349
 
350
+ // lib/Errors.ts
351
+ var DatedError = class extends Error {
352
+ date;
353
+ constructor(message, options) {
354
+ super(message, options);
355
+ this.name = this.constructor.name;
356
+ this.date = /* @__PURE__ */ new Date();
357
+ }
358
+ };
359
+ var ChecksumMismatchError = class extends DatedError {
360
+ constructor(message, options) {
361
+ super(message, options);
362
+ this.name = "ChecksumMismatchError";
363
+ }
364
+ };
365
+ var CustomError = class extends DatedError {
366
+ constructor(name, message, options) {
367
+ super(message, options);
368
+ this.name = name;
369
+ }
370
+ };
371
+ var MigrationError = class extends DatedError {
372
+ constructor(message, options) {
373
+ super(message, options);
374
+ this.name = "MigrationError";
375
+ }
376
+ };
377
+ var ValidationError = class extends DatedError {
378
+ constructor(message, options) {
379
+ super(message, options);
380
+ this.name = "ValidationError";
381
+ }
382
+ };
383
+ var ScriptContextError = class extends DatedError {
384
+ constructor(message, options) {
385
+ super(message, options);
386
+ this.name = "ScriptContextError";
387
+ }
388
+ };
389
+ var NetworkError = class extends DatedError {
390
+ constructor(message, options) {
391
+ super(message, options);
392
+ this.name = "NetworkError";
393
+ }
394
+ };
395
+
403
396
  // lib/misc.ts
404
- function consumeGen(valGen) {
405
- return __async(this, null, function* () {
406
- return yield typeof valGen === "function" ? valGen() : valGen;
407
- });
397
+ async function consumeGen(valGen) {
398
+ return await (typeof valGen === "function" ? valGen() : valGen);
408
399
  }
409
- function consumeStringGen(strGen) {
410
- return __async(this, null, function* () {
411
- return typeof strGen === "string" ? strGen : String(
412
- typeof strGen === "function" ? yield strGen() : strGen
413
- );
414
- });
400
+ async function consumeStringGen(strGen) {
401
+ return typeof strGen === "string" ? strGen : String(
402
+ typeof strGen === "function" ? await strGen() : strGen
403
+ );
415
404
  }
416
- function fetchAdvanced(_0) {
417
- return __async(this, arguments, function* (input, options = {}) {
418
- const { timeout = 1e4 } = options;
419
- const ctl = new AbortController();
420
- const _a = options, { signal } = _a, restOpts = __objRest(_a, ["signal"]);
421
- signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
422
- let sigOpts = {}, id = void 0;
423
- if (timeout >= 0) {
424
- id = setTimeout(() => ctl.abort(), timeout);
425
- sigOpts = { signal: ctl.signal };
426
- }
427
- try {
428
- const res = yield fetch(input, __spreadValues(__spreadValues({}, restOpts), sigOpts));
429
- typeof id !== "undefined" && clearTimeout(id);
430
- return res;
431
- } catch (err) {
432
- typeof id !== "undefined" && clearTimeout(id);
433
- throw new Error("Error while calling fetch", { cause: err });
434
- }
435
- });
405
+ async function fetchAdvanced(input, options = {}) {
406
+ const { timeout = 1e4, signal, ...restOpts } = options;
407
+ const ctl = new AbortController();
408
+ signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
409
+ let sigOpts = {}, id = void 0;
410
+ if (timeout >= 0) {
411
+ id = setTimeout(() => ctl.abort(), timeout);
412
+ sigOpts = { signal: ctl.signal };
413
+ }
414
+ try {
415
+ const res = await fetch(input, {
416
+ ...restOpts,
417
+ ...sigOpts
418
+ });
419
+ typeof id !== "undefined" && clearTimeout(id);
420
+ return res;
421
+ } catch (err) {
422
+ typeof id !== "undefined" && clearTimeout(id);
423
+ throw new NetworkError("Error while calling fetch", { cause: err });
424
+ }
436
425
  }
437
426
  function getListLength(listLike, zeroOnInvalid = true) {
438
427
  return "length" in listLike ? listLike.length : "size" in listLike ? listLike.size : "count" in listLike ? listLike.count : zeroOnInvalid ? 0 : NaN;
@@ -442,12 +431,12 @@ function pauseFor(time, signal, rejectOnAbort = false) {
442
431
  const timeout = setTimeout(() => res(), time);
443
432
  signal == null ? void 0 : signal.addEventListener("abort", () => {
444
433
  clearTimeout(timeout);
445
- rejectOnAbort ? rej(new Error("The pause was aborted")) : res();
434
+ rejectOnAbort ? rej(new CustomError("AbortError", "The pause was aborted")) : res();
446
435
  });
447
436
  });
448
437
  }
449
438
  function pureObj(obj) {
450
- return Object.assign(/* @__PURE__ */ Object.create(null), obj != null ? obj : {});
439
+ return Object.assign(/* @__PURE__ */ Object.create(null), obj ?? {});
451
440
  }
452
441
  function setImmediateInterval(callback, interval, signal) {
453
442
  let intervalId;
@@ -464,12 +453,12 @@ function setImmediateInterval(callback, interval, signal) {
464
453
  function setImmediateTimeoutLoop(callback, interval, signal) {
465
454
  let timeout;
466
455
  const cleanup = () => clearTimeout(timeout);
467
- const loop = () => __async(null, null, function* () {
456
+ const loop = async () => {
468
457
  if (signal == null ? void 0 : signal.aborted)
469
458
  return cleanup();
470
- yield callback();
459
+ await callback();
471
460
  timeout = setTimeout(loop, interval);
472
- });
461
+ };
473
462
  signal == null ? void 0 : signal.addEventListener("abort", cleanup);
474
463
  loop();
475
464
  }
@@ -477,14 +466,24 @@ function scheduleExit(code = 0, timeout = 0) {
477
466
  if (timeout < 0)
478
467
  throw new TypeError("Timeout must be a non-negative number");
479
468
  let exit;
480
- if (typeof process !== "undefined" && "exit" in process)
469
+ if (typeof process !== "undefined" && "exit" in process && typeof process.exit === "function")
481
470
  exit = () => process.exit(code);
482
- else if (typeof Deno !== "undefined" && "exit" in Deno)
471
+ else if (typeof Deno !== "undefined" && "exit" in Deno && typeof Deno.exit === "function")
483
472
  exit = () => Deno.exit(code);
484
473
  else
485
- throw new Error("Cannot exit the process, no exit method available");
474
+ throw new ScriptContextError("Cannot exit the process, no exit method available");
486
475
  setTimeout(exit, timeout);
487
476
  }
477
+ function getCallStack(asArray, lines = Infinity) {
478
+ if (typeof lines !== "number" || isNaN(lines) || lines < 0)
479
+ throw new TypeError("lines parameter must be a non-negative number");
480
+ try {
481
+ throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)");
482
+ } catch (err) {
483
+ const stack = (err.stack ?? "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
484
+ return asArray !== false ? stack : stack.join("\n");
485
+ }
486
+ }
488
487
 
489
488
  // lib/text.ts
490
489
  function autoPlural(term, num, pluralType = "auto") {
@@ -536,9 +535,9 @@ function createProgressBar(percentage, barLength, chars = defaultPbChars) {
536
535
  }
537
536
  function insertValues(input, ...values) {
538
537
  return input.replace(/%\d/gm, (match) => {
539
- var _a, _b;
538
+ var _a;
540
539
  const argIndex = Number(match.substring(1)) - 1;
541
- return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
540
+ return (_a = values[argIndex] ?? match) == null ? void 0 : _a.toString();
542
541
  });
543
542
  }
544
543
  function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
@@ -554,56 +553,49 @@ function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
554
553
  return arr.join(separators) + lastItm;
555
554
  }
556
555
  function secsToTimeStr(seconds) {
557
- if (seconds < 0)
558
- throw new TypeError("Seconds must be a positive number");
559
- const hours = Math.floor(seconds / 3600);
560
- const minutes = Math.floor(seconds % 3600 / 60);
561
- const secs = Math.floor(seconds % 60);
562
- return [
563
- hours ? hours + ":" : "",
564
- String(minutes).padStart(minutes > 0 || hours > 0 ? 2 : 1, "0"),
556
+ const isNegative = seconds < 0;
557
+ const s = Math.abs(seconds);
558
+ if (isNaN(s) || !isFinite(s))
559
+ throw new TypeError("The seconds argument must be a valid number");
560
+ const hrs = Math.floor(s / 3600);
561
+ const mins = Math.floor(s % 3600 / 60);
562
+ const secs = Math.floor(s % 60);
563
+ return (isNegative ? "-" : "") + [
564
+ hrs ? hrs + ":" : "",
565
+ String(mins).padStart(mins > 0 || hrs > 0 ? 2 : 1, "0"),
565
566
  ":",
566
- String(secs).padStart(secs > 0 || minutes > 0 || hours > 0 ? 2 : 1, "0")
567
+ String(secs).padStart(secs > 0 || mins > 0 || hrs > 0 || seconds === 0 ? 2 : 1, "0")
567
568
  ].join("");
568
569
  }
569
570
  function truncStr(input, length, endStr = "...") {
570
- var _a;
571
- const str = (_a = input == null ? void 0 : input.toString()) != null ? _a : String(input);
571
+ const str = (input == null ? void 0 : input.toString()) ?? String(input);
572
572
  const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
573
573
  return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
574
574
  }
575
575
 
576
- // lib/Errors.ts
577
- var DatedError = class extends Error {
578
- constructor(message, options) {
579
- super(message, options);
580
- __publicField(this, "date");
581
- this.name = this.constructor.name;
582
- this.date = /* @__PURE__ */ new Date();
583
- }
584
- };
585
- var ChecksumMismatchError = class extends DatedError {
586
- constructor(message, options) {
587
- super(message, options);
588
- this.name = "ChecksumMismatchError";
589
- }
590
- };
591
- var MigrationError = class extends DatedError {
592
- constructor(message, options) {
593
- super(message, options);
594
- this.name = "MigrationError";
595
- }
596
- };
597
- var ValidationError = class extends DatedError {
598
- constructor(message, options) {
599
- super(message, options);
600
- this.name = "ValidationError";
601
- }
602
- };
603
-
604
576
  // lib/DataStore.ts
605
577
  var dsFmtVer = 1;
606
578
  var DataStore = class {
579
+ id;
580
+ formatVersion;
581
+ defaultData;
582
+ encodeData;
583
+ decodeData;
584
+ compressionFormat = "deflate-raw";
585
+ memoryCache = true;
586
+ engine;
587
+ options;
588
+ /**
589
+ * Whether all first-init checks should be done.
590
+ * This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
591
+ * 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.
592
+ */
593
+ firstInit = true;
594
+ /** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
595
+ cachedData;
596
+ migrations;
597
+ migrateIds = [];
598
+ //#region constructor
607
599
  /**
608
600
  * Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
609
601
  * Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
@@ -614,29 +606,12 @@ var DataStore = class {
614
606
  * @param opts The options for this DataStore instance
615
607
  */
616
608
  constructor(opts) {
617
- __publicField(this, "id");
618
- __publicField(this, "formatVersion");
619
- __publicField(this, "defaultData");
620
- __publicField(this, "encodeData");
621
- __publicField(this, "decodeData");
622
- __publicField(this, "compressionFormat", "deflate-raw");
623
- __publicField(this, "engine");
624
- __publicField(this, "options");
625
- /**
626
- * Whether all first-init checks should be done.
627
- * This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
628
- * 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.
629
- */
630
- __publicField(this, "firstInit", true);
631
- /** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
632
- __publicField(this, "cachedData");
633
- __publicField(this, "migrations");
634
- __publicField(this, "migrateIds", []);
635
- var _a, _b, _c;
609
+ var _a;
636
610
  this.id = opts.id;
637
611
  this.formatVersion = opts.formatVersion;
638
612
  this.defaultData = opts.defaultData;
639
- this.cachedData = opts.defaultData;
613
+ this.memoryCache = Boolean(opts.memoryCache ?? true);
614
+ this.cachedData = this.memoryCache ? opts.defaultData : {};
640
615
  this.migrations = opts.migrations;
641
616
  if (opts.migrateIds)
642
617
  this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
@@ -645,18 +620,14 @@ var DataStore = class {
645
620
  this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
646
621
  this.options = opts;
647
622
  if (typeof opts.compressionFormat === "undefined")
648
- this.compressionFormat = opts.compressionFormat = (_b = (_a = opts.encodeData) == null ? void 0 : _a[0]) != null ? _b : "deflate-raw";
623
+ this.compressionFormat = opts.compressionFormat = ((_a = opts.encodeData) == null ? void 0 : _a[0]) ?? "deflate-raw";
649
624
  if (typeof opts.compressionFormat === "string") {
650
- this.encodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
651
- return yield compress(data, opts.compressionFormat, "string");
652
- })];
653
- this.decodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
654
- return yield compress(data, opts.compressionFormat, "string");
655
- })];
625
+ this.encodeData = [opts.compressionFormat, async (data) => await compress(data, opts.compressionFormat, "string")];
626
+ this.decodeData = [opts.compressionFormat, async (data) => await compress(data, opts.compressionFormat, "string")];
656
627
  } else if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
657
628
  this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
658
629
  this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
659
- this.compressionFormat = (_c = opts.encodeData[0]) != null ? _c : null;
630
+ this.compressionFormat = opts.encodeData[0] ?? null;
660
631
  } else if (opts.compressionFormat === null) {
661
632
  this.encodeData = void 0;
662
633
  this.decodeData = void 0;
@@ -665,123 +636,130 @@ var DataStore = class {
665
636
  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.");
666
637
  this.engine.setDataStoreOptions(opts);
667
638
  }
668
- //#region public
639
+ //#region loadData
669
640
  /**
670
641
  * Loads the data saved in persistent storage into the in-memory cache and also returns a copy of it.
671
642
  * Automatically populates persistent storage with default data if it doesn't contain any data yet.
672
643
  * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
673
644
  */
674
- loadData() {
675
- return __async(this, null, function* () {
676
- try {
677
- if (this.firstInit) {
678
- this.firstInit = false;
679
- const dsVer = Number(yield this.engine.getValue("__ds_fmt_ver", 0));
680
- if (isNaN(dsVer) || dsVer < 1) {
681
- const oldData = yield this.engine.getValue(`_uucfg-${this.id}`, null);
682
- if (oldData) {
683
- const oldVer = Number(yield this.engine.getValue(`_uucfgver-${this.id}`, NaN));
684
- const oldEnc = yield this.engine.getValue(`_uucfgenc-${this.id}`, null);
685
- const promises = [];
686
- const migrateFmt = (oldKey, newKey, value) => {
687
- promises.push(this.engine.setValue(newKey, value));
688
- promises.push(this.engine.deleteValue(oldKey));
689
- };
690
- if (oldData)
691
- migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
692
- if (!isNaN(oldVer))
693
- migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
694
- if (typeof oldEnc === "boolean")
695
- migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? Boolean(this.compressionFormat) || null : null);
696
- else
697
- promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
698
- yield Promise.allSettled(promises);
699
- }
700
- yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
645
+ async loadData() {
646
+ try {
647
+ if (this.firstInit) {
648
+ this.firstInit = false;
649
+ const dsVer = Number(await this.engine.getValue("__ds_fmt_ver", 0));
650
+ const oldData = await this.engine.getValue(`_uucfg-${this.id}`, null);
651
+ if (oldData) {
652
+ const oldVer = Number(await this.engine.getValue(`_uucfgver-${this.id}`, NaN));
653
+ const oldEnc = await this.engine.getValue(`_uucfgenc-${this.id}`, null);
654
+ const promises = [];
655
+ const migrateFmt = (oldKey, newKey, value) => {
656
+ promises.push(this.engine.setValue(newKey, value));
657
+ promises.push(this.engine.deleteValue(oldKey));
658
+ };
659
+ migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
660
+ if (!isNaN(oldVer))
661
+ migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
662
+ if (typeof oldEnc === "boolean")
663
+ migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? this.compressionFormat ?? null : null);
664
+ else {
665
+ promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
666
+ promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
701
667
  }
668
+ await Promise.allSettled(promises);
702
669
  }
703
- if (this.migrateIds.length > 0) {
704
- yield this.migrateId(this.migrateIds);
705
- this.migrateIds = [];
706
- }
707
- const storedDataRaw = yield this.engine.getValue(`__ds-${this.id}-dat`, null);
708
- let storedFmtVer = Number(yield this.engine.getValue(`__ds-${this.id}-ver`, NaN));
709
- if (typeof storedDataRaw !== "string") {
710
- yield this.saveDefaultData();
711
- return __spreadValues({}, this.defaultData);
712
- }
713
- const storedData = storedDataRaw != null ? storedDataRaw : JSON.stringify(this.defaultData);
714
- const encodingFmt = String(yield this.engine.getValue(`__ds-${this.id}-enf`, null));
715
- const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
716
- let saveData = false;
717
- if (isNaN(storedFmtVer)) {
718
- yield this.engine.setValue(`__ds-${this.id}-ver`, storedFmtVer = this.formatVersion);
719
- saveData = true;
720
- }
721
- let parsed = yield this.engine.deserializeData(storedData, isEncoded);
722
- if (storedFmtVer < this.formatVersion && this.migrations)
723
- parsed = yield this.runMigrations(parsed, storedFmtVer);
724
- if (saveData)
725
- yield this.setData(parsed);
726
- return this.cachedData = this.engine.deepCopy(parsed);
727
- } catch (err) {
728
- console.warn("Error while parsing JSON data, resetting it to the default value.", err);
729
- yield this.saveDefaultData();
730
- return this.defaultData;
670
+ if (isNaN(dsVer) || dsVer < dsFmtVer)
671
+ await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
731
672
  }
732
- });
673
+ if (this.migrateIds.length > 0) {
674
+ await this.migrateId(this.migrateIds);
675
+ this.migrateIds = [];
676
+ }
677
+ const storedDataRaw = await this.engine.getValue(`__ds-${this.id}-dat`, null);
678
+ let storedFmtVer = Number(await this.engine.getValue(`__ds-${this.id}-ver`, NaN));
679
+ if (typeof storedDataRaw !== "string") {
680
+ await this.saveDefaultData();
681
+ return this.engine.deepCopy(this.defaultData);
682
+ }
683
+ const storedData = storedDataRaw ?? JSON.stringify(this.defaultData);
684
+ const encodingFmt = String(await this.engine.getValue(`__ds-${this.id}-enf`, null));
685
+ const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
686
+ let saveData = false;
687
+ if (isNaN(storedFmtVer)) {
688
+ await this.engine.setValue(`__ds-${this.id}-ver`, storedFmtVer = this.formatVersion);
689
+ saveData = true;
690
+ }
691
+ let parsed = await this.engine.deserializeData(storedData, isEncoded);
692
+ if (storedFmtVer < this.formatVersion && this.migrations)
693
+ parsed = await this.runMigrations(parsed, storedFmtVer);
694
+ if (saveData)
695
+ await this.setData(parsed);
696
+ if (this.memoryCache)
697
+ return this.cachedData = this.engine.deepCopy(parsed);
698
+ else
699
+ return this.engine.deepCopy(parsed);
700
+ } catch (err) {
701
+ console.warn("Error while parsing JSON data, resetting it to the default value.", err);
702
+ await this.saveDefaultData();
703
+ return this.defaultData;
704
+ }
733
705
  }
706
+ //#region getData
734
707
  /**
735
708
  * Returns a copy of the data from the in-memory cache.
736
- * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
709
+ * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
710
+ * ⚠️ If `memoryCache` was set to `false` in the constructor options, this method will throw an error.
737
711
  */
738
712
  getData() {
713
+ if (!this.memoryCache)
714
+ throw new DatedError("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");
739
715
  return this.engine.deepCopy(this.cachedData);
740
716
  }
717
+ //#region setData
741
718
  /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
742
719
  setData(data) {
743
- this.cachedData = data;
744
- return new Promise((resolve) => __async(this, null, function* () {
745
- yield Promise.allSettled([
746
- this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(data, this.encodingEnabled())),
720
+ if (this.memoryCache)
721
+ this.cachedData = data;
722
+ return new Promise(async (resolve) => {
723
+ await Promise.allSettled([
724
+ this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(data, this.encodingEnabled())),
747
725
  this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
748
726
  this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
749
727
  ]);
750
728
  resolve();
751
- }));
729
+ });
752
730
  }
731
+ //#region saveDefaultData
753
732
  /** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
754
- saveDefaultData() {
755
- return __async(this, null, function* () {
733
+ async saveDefaultData() {
734
+ if (this.memoryCache)
756
735
  this.cachedData = this.defaultData;
757
- yield Promise.allSettled([
758
- this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(this.defaultData, this.encodingEnabled())),
759
- this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
760
- this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
761
- ]);
762
- });
736
+ await Promise.allSettled([
737
+ this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(this.defaultData, this.encodingEnabled())),
738
+ this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
739
+ this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
740
+ ]);
763
741
  }
742
+ //#region deleteData
764
743
  /**
765
744
  * Call this method to clear all persistently stored data associated with this DataStore instance, including the storage container (if supported by the DataStoreEngine).
766
745
  * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
767
746
  * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
768
747
  */
769
- deleteData() {
770
- return __async(this, null, function* () {
771
- var _a, _b;
772
- yield Promise.allSettled([
773
- this.engine.deleteValue(`__ds-${this.id}-dat`),
774
- this.engine.deleteValue(`__ds-${this.id}-ver`),
775
- this.engine.deleteValue(`__ds-${this.id}-enf`)
776
- ]);
777
- yield (_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a);
778
- });
779
- }
748
+ async deleteData() {
749
+ var _a, _b;
750
+ await Promise.allSettled([
751
+ this.engine.deleteValue(`__ds-${this.id}-dat`),
752
+ this.engine.deleteValue(`__ds-${this.id}-ver`),
753
+ this.engine.deleteValue(`__ds-${this.id}-enf`)
754
+ ]);
755
+ await ((_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a));
756
+ }
757
+ //#region encodingEnabled
780
758
  /** Returns whether encoding and decoding are enabled for this DataStore instance */
781
759
  encodingEnabled() {
782
760
  return Boolean(this.encodeData && this.decodeData) && this.compressionFormat !== null || Boolean(this.compressionFormat);
783
761
  }
784
- //#region migrations
762
+ //#region runMigrations
785
763
  /**
786
764
  * Runs all necessary migration functions consecutively and saves the result to the in-memory cache and persistent storage and also returns it.
787
765
  * This method is automatically called by {@linkcode loadData()} if the data format has changed since the last time the data was saved.
@@ -789,73 +767,73 @@ var DataStore = class {
789
767
  *
790
768
  * 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.
791
769
  */
792
- runMigrations(oldData, oldFmtVer, resetOnError = true) {
793
- return __async(this, null, function* () {
794
- if (!this.migrations)
795
- return oldData;
796
- let newData = oldData;
797
- const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
798
- let lastFmtVer = oldFmtVer;
799
- for (const [fmtVer, migrationFunc] of sortedMigrations) {
800
- const ver = Number(fmtVer);
801
- if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
802
- try {
803
- const migRes = migrationFunc(newData);
804
- newData = migRes instanceof Promise ? yield migRes : migRes;
805
- lastFmtVer = oldFmtVer = ver;
806
- } catch (err) {
807
- if (!resetOnError)
808
- throw new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
809
- yield this.saveDefaultData();
810
- return this.getData();
811
- }
770
+ async runMigrations(oldData, oldFmtVer, resetOnError = true) {
771
+ if (!this.migrations)
772
+ return oldData;
773
+ let newData = oldData;
774
+ const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
775
+ let lastFmtVer = oldFmtVer;
776
+ for (const [fmtVer, migrationFunc] of sortedMigrations) {
777
+ const ver = Number(fmtVer);
778
+ if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
779
+ try {
780
+ const migRes = migrationFunc(newData);
781
+ newData = migRes instanceof Promise ? await migRes : migRes;
782
+ lastFmtVer = oldFmtVer = ver;
783
+ } catch (err) {
784
+ if (!resetOnError)
785
+ throw new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
786
+ await this.saveDefaultData();
787
+ return this.getData();
812
788
  }
813
789
  }
814
- yield Promise.allSettled([
815
- this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(newData)),
816
- this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
817
- this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
818
- ]);
819
- return this.cachedData = __spreadValues({}, newData);
820
- });
821
- }
790
+ }
791
+ await Promise.allSettled([
792
+ this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(newData)),
793
+ this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
794
+ this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
795
+ ]);
796
+ if (this.memoryCache)
797
+ return this.cachedData = this.engine.deepCopy(newData);
798
+ else
799
+ return this.engine.deepCopy(newData);
800
+ }
801
+ //#region migrateId
822
802
  /**
823
803
  * Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
824
804
  * 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.
825
805
  */
826
- migrateId(oldIds) {
827
- return __async(this, null, function* () {
828
- const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
829
- yield Promise.all(ids.map((id) => __async(this, null, function* () {
830
- const [data, fmtVer, isEncoded] = yield (() => __async(this, null, function* () {
831
- const [d, f, e] = yield Promise.all([
832
- this.engine.getValue(`__ds-${id}-dat`, JSON.stringify(this.defaultData)),
833
- this.engine.getValue(`__ds-${id}-ver`, NaN),
834
- this.engine.getValue(`__ds-${id}-enf`, null)
835
- ]);
836
- return [d, Number(f), Boolean(e) && String(e) !== "null"];
837
- }))();
838
- if (data === void 0 || isNaN(fmtVer))
839
- return;
840
- const parsed = yield this.engine.deserializeData(data, isEncoded);
841
- yield Promise.allSettled([
842
- this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(parsed)),
843
- this.engine.setValue(`__ds-${this.id}-ver`, fmtVer),
844
- this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat),
845
- this.engine.deleteValue(`__ds-${id}-dat`),
846
- this.engine.deleteValue(`__ds-${id}-ver`),
847
- this.engine.deleteValue(`__ds-${id}-enf`)
806
+ async migrateId(oldIds) {
807
+ const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
808
+ await Promise.all(ids.map(async (id) => {
809
+ const [data, fmtVer, isEncoded] = await (async () => {
810
+ const [d, f, e] = await Promise.all([
811
+ this.engine.getValue(`__ds-${id}-dat`, JSON.stringify(this.defaultData)),
812
+ this.engine.getValue(`__ds-${id}-ver`, NaN),
813
+ this.engine.getValue(`__ds-${id}-enf`, null)
848
814
  ]);
849
- })));
850
- });
815
+ return [d, Number(f), Boolean(e) && String(e) !== "null"];
816
+ })();
817
+ if (data === void 0 || isNaN(fmtVer))
818
+ return;
819
+ const parsed = await this.engine.deserializeData(data, isEncoded);
820
+ await Promise.allSettled([
821
+ this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(parsed)),
822
+ this.engine.setValue(`__ds-${this.id}-ver`, fmtVer),
823
+ this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat),
824
+ this.engine.deleteValue(`__ds-${id}-dat`),
825
+ this.engine.deleteValue(`__ds-${id}-ver`),
826
+ this.engine.deleteValue(`__ds-${id}-enf`)
827
+ ]);
828
+ }));
851
829
  }
852
830
  };
853
831
 
854
832
  // lib/DataStoreEngine.ts
855
833
  var DataStoreEngine = class {
834
+ dataStoreOptions;
856
835
  // setDataStoreOptions() is called from inside the DataStore constructor to set this value
857
836
  constructor(options) {
858
- __publicField(this, "dataStoreOptions");
859
837
  if (options)
860
838
  this.dataStoreOptions = options;
861
839
  }
@@ -864,30 +842,26 @@ var DataStoreEngine = class {
864
842
  this.dataStoreOptions = dataStoreOptions;
865
843
  }
866
844
  //#region serialization api
867
- /** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is set to true */
868
- serializeData(data, useEncoding) {
869
- return __async(this, null, function* () {
870
- var _a, _b, _c, _d, _e;
871
- this.ensureDataStoreOptions();
872
- const stringData = JSON.stringify(data);
873
- if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
874
- return stringData;
875
- const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
876
- if (encRes instanceof Promise)
877
- return yield encRes;
878
- return encRes;
879
- });
845
+ /** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is not set to false and the `encodeData` and `decodeData` options are set */
846
+ async serializeData(data, useEncoding) {
847
+ var _a, _b, _c, _d, _e;
848
+ this.ensureDataStoreOptions();
849
+ const stringData = JSON.stringify(data);
850
+ if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
851
+ return stringData;
852
+ const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
853
+ if (encRes instanceof Promise)
854
+ return await encRes;
855
+ return encRes;
880
856
  }
881
857
  /** Deserializes the given string to a JSON object, optionally decoded with `options.decodeData` if {@linkcode useEncoding} is set to true */
882
- deserializeData(data, useEncoding) {
883
- return __async(this, null, function* () {
884
- var _a, _b, _c;
885
- this.ensureDataStoreOptions();
886
- 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;
887
- if (decRes instanceof Promise)
888
- decRes = yield decRes;
889
- return JSON.parse(decRes != null ? decRes : data);
890
- });
858
+ async deserializeData(data, useEncoding) {
859
+ var _a, _b, _c;
860
+ this.ensureDataStoreOptions();
861
+ 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;
862
+ if (decRes instanceof Promise)
863
+ decRes = await decRes;
864
+ return JSON.parse(decRes ?? data);
891
865
  }
892
866
  //#region misc api
893
867
  /** Throws an error if the DataStoreOptions are not set or invalid */
@@ -905,191 +879,175 @@ var DataStoreEngine = class {
905
879
  try {
906
880
  if ("structuredClone" in globalThis)
907
881
  return structuredClone(obj);
908
- } catch (e) {
882
+ } catch {
909
883
  }
910
884
  return JSON.parse(JSON.stringify(obj));
911
885
  }
912
886
  };
913
887
  var BrowserStorageEngine = class extends DataStoreEngine {
888
+ options;
914
889
  /**
915
890
  * Creates an instance of `BrowserStorageEngine`.
916
891
  *
917
892
  * - ⚠️ Requires a DOM environment
918
- * - ⚠️ Don't reuse engines across multiple {@linkcode DataStore} instances
893
+ * - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
919
894
  */
920
895
  constructor(options) {
921
896
  super(options == null ? void 0 : options.dataStoreOptions);
922
- __publicField(this, "options");
923
- this.options = __spreadValues({
924
- type: "localStorage"
925
- }, options);
897
+ this.options = {
898
+ type: "localStorage",
899
+ ...options
900
+ };
926
901
  }
927
902
  //#region storage api
928
903
  /** Fetches a value from persistent storage */
929
- getValue(name, defaultValue) {
930
- return __async(this, null, function* () {
931
- const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
932
- return typeof val === "undefined" ? defaultValue : val;
933
- });
904
+ async getValue(name, defaultValue) {
905
+ const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
906
+ return typeof val === "undefined" ? defaultValue : val;
934
907
  }
935
908
  /** Sets a value in persistent storage */
936
- setValue(name, value) {
937
- return __async(this, null, function* () {
938
- if (this.options.type === "localStorage")
939
- globalThis.localStorage.setItem(name, String(value));
940
- else
941
- globalThis.sessionStorage.setItem(name, String(value));
942
- });
909
+ async setValue(name, value) {
910
+ if (this.options.type === "localStorage")
911
+ globalThis.localStorage.setItem(name, String(value));
912
+ else
913
+ globalThis.sessionStorage.setItem(name, String(value));
943
914
  }
944
915
  /** Deletes a value from persistent storage */
945
- deleteValue(name) {
946
- return __async(this, null, function* () {
947
- if (this.options.type === "localStorage")
948
- globalThis.localStorage.removeItem(name);
949
- else
950
- globalThis.sessionStorage.removeItem(name);
951
- });
916
+ async deleteValue(name) {
917
+ if (this.options.type === "localStorage")
918
+ globalThis.localStorage.removeItem(name);
919
+ else
920
+ globalThis.sessionStorage.removeItem(name);
952
921
  }
953
922
  };
954
923
  var fs;
955
924
  var FileStorageEngine = class extends DataStoreEngine {
925
+ options;
926
+ fileAccessQueue = Promise.resolve();
956
927
  /**
957
928
  * Creates an instance of `FileStorageEngine`.
958
929
  *
959
930
  * - ⚠️ Requires Node.js or Deno with Node compatibility (v1.31+)
960
- * - ⚠️ Don't reuse engines across multiple {@linkcode DataStore} instances
931
+ * - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
961
932
  */
962
933
  constructor(options) {
963
934
  super(options == null ? void 0 : options.dataStoreOptions);
964
- __publicField(this, "options");
965
- __publicField(this, "fileAccessQueue", Promise.resolve());
966
- this.options = __spreadValues({
967
- filePath: (id) => `.ds-${id}`
968
- }, options);
935
+ this.options = {
936
+ filePath: (id) => `.ds-${id}`,
937
+ ...options
938
+ };
969
939
  }
970
940
  //#region json file
971
941
  /** Reads the file contents */
972
- readFile() {
973
- return __async(this, null, function* () {
974
- var _a, _b, _c, _d, _e;
975
- this.ensureDataStoreOptions();
976
- try {
977
- if (!fs)
978
- fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
979
- if (!fs)
980
- throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
981
- const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
982
- const data = yield fs.readFile(path, "utf-8");
983
- 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;
984
- } catch (e) {
985
- return void 0;
986
- }
987
- });
942
+ async readFile() {
943
+ var _a, _b, _c, _d;
944
+ this.ensureDataStoreOptions();
945
+ try {
946
+ if (!fs)
947
+ fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
948
+ if (!fs)
949
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
950
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
951
+ const data = await fs.readFile(path, "utf-8");
952
+ 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;
953
+ } catch {
954
+ return void 0;
955
+ }
988
956
  }
989
957
  /** Overwrites the file contents */
990
- writeFile(data) {
991
- return __async(this, null, function* () {
992
- var _a, _b, _c, _d, _e;
993
- this.ensureDataStoreOptions();
994
- try {
995
- if (!fs)
996
- fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
997
- if (!fs)
998
- throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
999
- const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
1000
- yield fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
1001
- 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");
1002
- } catch (err) {
1003
- console.error("Error writing file:", err);
1004
- }
1005
- });
958
+ async writeFile(data) {
959
+ var _a, _b, _c, _d;
960
+ this.ensureDataStoreOptions();
961
+ try {
962
+ if (!fs)
963
+ fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
964
+ if (!fs)
965
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
966
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
967
+ await fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
968
+ 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");
969
+ } catch (err) {
970
+ console.error("Error writing file:", err);
971
+ }
1006
972
  }
1007
973
  //#region storage api
1008
974
  /** Fetches a value from persistent storage */
1009
- getValue(name, defaultValue) {
1010
- return __async(this, null, function* () {
1011
- const data = yield this.readFile();
1012
- if (!data)
1013
- return defaultValue;
1014
- const value = data == null ? void 0 : data[name];
1015
- if (typeof value === "undefined")
1016
- return defaultValue;
1017
- if (typeof value === "string")
1018
- return value;
975
+ async getValue(name, defaultValue) {
976
+ const data = await this.readFile();
977
+ if (!data)
978
+ return defaultValue;
979
+ const value = data == null ? void 0 : data[name];
980
+ if (typeof value === "undefined")
981
+ return defaultValue;
982
+ if (typeof value === "string")
1019
983
  return value;
1020
- });
984
+ return value;
1021
985
  }
1022
986
  /** Sets a value in persistent storage */
1023
- setValue(name, value) {
1024
- return __async(this, null, function* () {
1025
- this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
1026
- let data = yield this.readFile();
1027
- if (!data)
1028
- data = {};
1029
- data[name] = value;
1030
- yield this.writeFile(data);
1031
- })).catch((err) => {
1032
- console.error("Error in setValue:", err);
1033
- throw err;
1034
- });
1035
- yield this.fileAccessQueue.catch(() => {
1036
- });
987
+ async setValue(name, value) {
988
+ this.fileAccessQueue = this.fileAccessQueue.then(async () => {
989
+ let data = await this.readFile();
990
+ if (!data)
991
+ data = {};
992
+ data[name] = value;
993
+ await this.writeFile(data);
994
+ }).catch((err) => {
995
+ console.error("Error in setValue:", err);
996
+ throw err;
997
+ });
998
+ await this.fileAccessQueue.catch(() => {
1037
999
  });
1038
1000
  }
1039
1001
  /** Deletes a value from persistent storage */
1040
- deleteValue(name) {
1041
- return __async(this, null, function* () {
1042
- this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
1043
- const data = yield this.readFile();
1044
- if (!data)
1045
- return;
1046
- delete data[name];
1047
- yield this.writeFile(data);
1048
- })).catch((err) => {
1049
- console.error("Error in deleteValue:", err);
1050
- throw err;
1051
- });
1052
- yield this.fileAccessQueue.catch(() => {
1053
- });
1002
+ async deleteValue(name) {
1003
+ this.fileAccessQueue = this.fileAccessQueue.then(async () => {
1004
+ const data = await this.readFile();
1005
+ if (!data)
1006
+ return;
1007
+ delete data[name];
1008
+ await this.writeFile(data);
1009
+ }).catch((err) => {
1010
+ console.error("Error in deleteValue:", err);
1011
+ throw err;
1012
+ });
1013
+ await this.fileAccessQueue.catch(() => {
1054
1014
  });
1055
1015
  }
1056
1016
  /** Deletes the file that contains the data of this DataStore. */
1057
- deleteStorage() {
1058
- return __async(this, null, function* () {
1059
- var _a;
1060
- this.ensureDataStoreOptions();
1061
- try {
1062
- if (!fs)
1063
- fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
1064
- if (!fs)
1065
- throw new DatedError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new Error("'node:fs/promises' module not available") });
1066
- const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
1067
- yield fs.unlink(path);
1068
- } catch (err) {
1069
- console.error("Error deleting file:", err);
1070
- }
1071
- });
1017
+ async deleteStorage() {
1018
+ var _a;
1019
+ this.ensureDataStoreOptions();
1020
+ try {
1021
+ if (!fs)
1022
+ fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
1023
+ if (!fs)
1024
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1025
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
1026
+ return await fs.unlink(path);
1027
+ } catch (err) {
1028
+ console.error("Error deleting file:", err);
1029
+ }
1072
1030
  }
1073
1031
  };
1074
1032
 
1075
1033
  // lib/DataStoreSerializer.ts
1076
1034
  var DataStoreSerializer = class _DataStoreSerializer {
1035
+ stores;
1036
+ options;
1077
1037
  constructor(stores, options = {}) {
1078
- __publicField(this, "stores");
1079
- __publicField(this, "options");
1080
1038
  if (!crypto || !crypto.subtle)
1081
- throw new Error("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
1039
+ throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
1082
1040
  this.stores = stores;
1083
- this.options = __spreadValues({
1041
+ this.options = {
1084
1042
  addChecksum: true,
1085
- ensureIntegrity: true
1086
- }, options);
1043
+ ensureIntegrity: true,
1044
+ remapIds: {},
1045
+ ...options
1046
+ };
1087
1047
  }
1088
1048
  /** Calculates the checksum of a string */
1089
- calcChecksum(input) {
1090
- return __async(this, null, function* () {
1091
- return computeHash(input, "SHA-256");
1092
- });
1049
+ async calcChecksum(input) {
1050
+ return computeHash(input, "SHA-256");
1093
1051
  }
1094
1052
  /**
1095
1053
  * Serializes only a subset of the data stores into a string.
@@ -1097,70 +1055,72 @@ var DataStoreSerializer = class _DataStoreSerializer {
1097
1055
  * @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
1098
1056
  * @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
1099
1057
  */
1100
- serializePartial(stores, useEncoding = true, stringified = true) {
1101
- return __async(this, null, function* () {
1102
- var _a;
1103
- const serData = [];
1104
- for (const storeInst of this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id))) {
1105
- const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
1106
- const data = encoded ? yield storeInst.encodeData[1](JSON.stringify(storeInst.getData())) : JSON.stringify(storeInst.getData());
1107
- serData.push({
1108
- id: storeInst.id,
1109
- data,
1110
- formatVersion: storeInst.formatVersion,
1111
- encoded,
1112
- checksum: this.options.addChecksum ? yield this.calcChecksum(data) : void 0
1113
- });
1114
- }
1115
- return stringified ? JSON.stringify(serData) : serData;
1116
- });
1058
+ async serializePartial(stores, useEncoding = true, stringified = true) {
1059
+ var _a;
1060
+ const serData = [];
1061
+ const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
1062
+ for (const storeInst of filteredStores) {
1063
+ const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
1064
+ const rawData = storeInst.memoryCache ? storeInst.getData() : await storeInst.loadData();
1065
+ const data = encoded ? await storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
1066
+ serData.push({
1067
+ id: storeInst.id,
1068
+ data,
1069
+ formatVersion: storeInst.formatVersion,
1070
+ encoded,
1071
+ checksum: this.options.addChecksum ? await this.calcChecksum(data) : void 0
1072
+ });
1073
+ }
1074
+ return stringified ? JSON.stringify(serData) : serData;
1117
1075
  }
1118
1076
  /**
1119
1077
  * Serializes the data stores into a string.
1120
1078
  * @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
1121
1079
  * @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
1122
1080
  */
1123
- serialize(useEncoding = true, stringified = true) {
1124
- return __async(this, null, function* () {
1125
- return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
1126
- });
1081
+ async serialize(useEncoding = true, stringified = true) {
1082
+ return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
1127
1083
  }
1128
1084
  /**
1129
1085
  * Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
1130
1086
  * Also triggers the migration process if the data format has changed.
1131
1087
  */
1132
- deserializePartial(stores, data) {
1133
- return __async(this, null, function* () {
1134
- const deserStores = typeof data === "string" ? JSON.parse(data) : data;
1135
- if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
1136
- throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
1137
- for (const storeData of deserStores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id))) {
1138
- const storeInst = this.stores.find((s) => s.id === storeData.id);
1139
- if (!storeInst)
1140
- throw new Error(`DataStore instance with ID "${storeData.id}" not found! Make sure to provide it in the DataStoreSerializer constructor.`);
1141
- if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
1142
- const checksum = yield this.calcChecksum(storeData.data);
1143
- if (checksum !== storeData.checksum)
1144
- throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
1088
+ async deserializePartial(stores, data) {
1089
+ const deserStores = typeof data === "string" ? JSON.parse(data) : data;
1090
+ if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
1091
+ throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
1092
+ const resolveStoreId = (id) => {
1093
+ var _a;
1094
+ return ((_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) ?? id;
1095
+ };
1096
+ const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
1097
+ for (const storeData of deserStores) {
1098
+ const effectiveId = resolveStoreId(storeData.id);
1099
+ if (!matchesFilter(effectiveId))
1100
+ continue;
1101
+ const storeInst = this.stores.find((s) => s.id === effectiveId);
1102
+ if (!storeInst)
1103
+ 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.`);
1104
+ if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
1105
+ const checksum = await this.calcChecksum(storeData.data);
1106
+ if (checksum !== storeData.checksum)
1107
+ throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
1145
1108
  Expected: ${storeData.checksum}
1146
1109
  Has: ${checksum}`);
1147
- }
1148
- const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData[1](storeData.data) : storeData.data;
1149
- if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
1150
- yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
1151
- else
1152
- yield storeInst.setData(JSON.parse(decodedData));
1153
1110
  }
1154
- });
1111
+ const decodedData = storeData.encoded && storeInst.encodingEnabled() ? await storeInst.decodeData[1](storeData.data) : storeData.data;
1112
+ if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
1113
+ await storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
1114
+ else
1115
+ await storeInst.setData(JSON.parse(decodedData));
1116
+ }
1155
1117
  }
1156
1118
  /**
1157
1119
  * Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
1158
1120
  * Also triggers the migration process if the data format has changed.
1159
1121
  */
1160
- deserialize(data) {
1161
- return __async(this, null, function* () {
1162
- return this.deserializePartial(this.stores.map((s) => s.id), data);
1163
- });
1122
+ async deserialize(data) {
1123
+ return this.deserializePartial(this.stores.map((s) => s.id), data);
1164
1124
  }
1165
1125
  /**
1166
1126
  * Loads the persistent data of the DataStore instances into the in-memory cache.
@@ -1168,40 +1128,32 @@ Has: ${checksum}`);
1168
1128
  * @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
1169
1129
  * @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
1170
1130
  */
1171
- loadStoresData(stores) {
1172
- return __async(this, null, function* () {
1173
- return Promise.allSettled(
1174
- this.getStoresFiltered(stores).map((store) => __async(this, null, function* () {
1175
- return {
1176
- id: store.id,
1177
- data: yield store.loadData()
1178
- };
1179
- }))
1180
- );
1181
- });
1131
+ async loadStoresData(stores) {
1132
+ return Promise.allSettled(
1133
+ this.getStoresFiltered(stores).map(async (store) => ({
1134
+ id: store.id,
1135
+ data: await store.loadData()
1136
+ }))
1137
+ );
1182
1138
  }
1183
1139
  /**
1184
1140
  * Resets the persistent and in-memory data of the DataStore instances to their default values.
1185
1141
  * @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
1186
1142
  */
1187
- resetStoresData(stores) {
1188
- return __async(this, null, function* () {
1189
- return Promise.allSettled(
1190
- this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
1191
- );
1192
- });
1143
+ async resetStoresData(stores) {
1144
+ return Promise.allSettled(
1145
+ this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
1146
+ );
1193
1147
  }
1194
1148
  /**
1195
1149
  * Deletes the persistent data of the DataStore instances.
1196
1150
  * Leaves the in-memory data untouched.
1197
1151
  * @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
1198
1152
  */
1199
- deleteStoresData(stores) {
1200
- return __async(this, null, function* () {
1201
- return Promise.allSettled(
1202
- this.getStoresFiltered(stores).map((store) => store.deleteData())
1203
- );
1204
- });
1153
+ async deleteStoresData(stores) {
1154
+ return Promise.allSettled(
1155
+ this.getStoresFiltered(stores).map((store) => store.deleteData())
1156
+ );
1205
1157
  }
1206
1158
  /** Checks if a given value is an array of SerializedDataStore objects */
1207
1159
  static isSerializedDataStoreObjArray(obj) {
@@ -1226,26 +1178,26 @@ var createNanoEvents = () => ({
1226
1178
  },
1227
1179
  events: {},
1228
1180
  on(event, cb) {
1229
- var _a;
1230
1181
  ;
1231
- ((_a = this.events)[event] || (_a[event] = [])).push(cb);
1182
+ (this.events[event] ||= []).push(cb);
1232
1183
  return () => {
1233
- var _a2;
1234
- this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
1184
+ var _a;
1185
+ this.events[event] = (_a = this.events[event]) == null ? void 0 : _a.filter((i) => cb !== i);
1235
1186
  };
1236
1187
  }
1237
1188
  });
1238
1189
 
1239
1190
  // lib/NanoEmitter.ts
1240
1191
  var NanoEmitter = class {
1192
+ events = createNanoEvents();
1193
+ eventUnsubscribes = [];
1194
+ emitterOptions;
1241
1195
  /** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
1242
1196
  constructor(options = {}) {
1243
- __publicField(this, "events", createNanoEvents());
1244
- __publicField(this, "eventUnsubscribes", []);
1245
- __publicField(this, "emitterOptions");
1246
- this.emitterOptions = __spreadValues({
1247
- publicEmit: false
1248
- }, options);
1197
+ this.emitterOptions = {
1198
+ publicEmit: false,
1199
+ ...options
1200
+ };
1249
1201
  }
1250
1202
  //#region on
1251
1203
  /**
@@ -1319,11 +1271,12 @@ var NanoEmitter = class {
1319
1271
  * `callback` (required) is the function that will be called when the conditions are met.
1320
1272
  *
1321
1273
  * 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.
1322
- * If `signal` is provided, the subscription will be aborted when the given signal is aborted.
1274
+ * If `signal` is provided, the subscription will be canceled when the given signal is aborted.
1323
1275
  *
1324
1276
  * If `oneOf` is used, the callback will be called when any of the matching events are emitted.
1325
1277
  * 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.
1326
- * You may use a combination of the above two options, but at least one of them must be provided.
1278
+ * 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.
1279
+ * At least one of `oneOf` or `allOf` must be provided.
1327
1280
  *
1328
1281
  * @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.
1329
1282
  */
@@ -1336,11 +1289,12 @@ var NanoEmitter = class {
1336
1289
  this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
1337
1290
  };
1338
1291
  for (const opts of Array.isArray(options) ? options : [options]) {
1339
- const optsWithDefaults = __spreadValues({
1292
+ const optsWithDefaults = {
1340
1293
  allOf: [],
1341
1294
  oneOf: [],
1342
- once: false
1343
- }, opts);
1295
+ once: false,
1296
+ ...opts
1297
+ };
1344
1298
  const {
1345
1299
  oneOf,
1346
1300
  allOf,
@@ -1350,6 +1304,8 @@ var NanoEmitter = class {
1350
1304
  } = optsWithDefaults;
1351
1305
  if (signal == null ? void 0 : signal.aborted)
1352
1306
  return unsubAll;
1307
+ if (oneOf.length === 0 && allOf.length === 0)
1308
+ throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
1353
1309
  const curEvtUnsubs = [];
1354
1310
  const checkUnsubAllEvt = (force = false) => {
1355
1311
  if (!(signal == null ? void 0 : signal.aborted) && !force)
@@ -1359,34 +1315,31 @@ var NanoEmitter = class {
1359
1315
  curEvtUnsubs.splice(0, curEvtUnsubs.length);
1360
1316
  this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
1361
1317
  };
1318
+ const allOfEmitted = /* @__PURE__ */ new Set();
1319
+ const allOfConditionMet = () => allOf.length === 0 || allOfEmitted.size === allOf.length;
1362
1320
  for (const event of oneOf) {
1363
1321
  const unsub = this.events.on(event, ((...args) => {
1364
1322
  checkUnsubAllEvt();
1365
- callback(event, ...args);
1366
- if (once)
1367
- checkUnsubAllEvt(true);
1323
+ if (allOfConditionMet()) {
1324
+ callback(event, ...args);
1325
+ if (once)
1326
+ checkUnsubAllEvt(true);
1327
+ }
1368
1328
  }));
1369
1329
  curEvtUnsubs.push(unsub);
1370
1330
  }
1371
- const allOfEmitted = /* @__PURE__ */ new Set();
1372
- const checkAllOf = (event, ...args) => {
1373
- checkUnsubAllEvt();
1374
- allOfEmitted.add(event);
1375
- if (allOfEmitted.size === allOf.length) {
1376
- callback(event, ...args);
1377
- if (once)
1378
- checkUnsubAllEvt(true);
1379
- }
1380
- };
1381
1331
  for (const event of allOf) {
1382
1332
  const unsub = this.events.on(event, ((...args) => {
1383
1333
  checkUnsubAllEvt();
1384
- checkAllOf(event, ...args);
1334
+ allOfEmitted.add(event);
1335
+ if (allOfConditionMet() && (oneOf.length === 0 || oneOf.includes(event))) {
1336
+ callback(event, ...args);
1337
+ if (once)
1338
+ checkUnsubAllEvt(true);
1339
+ }
1385
1340
  }));
1386
1341
  curEvtUnsubs.push(unsub);
1387
1342
  }
1388
- if (oneOf.length === 0 && allOf.length === 0)
1389
- throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
1390
1343
  allUnsubs.push(() => checkUnsubAllEvt(true));
1391
1344
  }
1392
1345
  return unsubAll;
@@ -1426,13 +1379,13 @@ var Debouncer = class extends NanoEmitter {
1426
1379
  super();
1427
1380
  this.timeout = timeout;
1428
1381
  this.type = type;
1429
- /** All registered listener functions and the time they were attached */
1430
- __publicField(this, "listeners", []);
1431
- /** The currently active timeout */
1432
- __publicField(this, "activeTimeout");
1433
- /** The latest queued call */
1434
- __publicField(this, "queuedCall");
1435
1382
  }
1383
+ /** All registered listener functions and the time they were attached */
1384
+ listeners = [];
1385
+ /** The currently active timeout */
1386
+ activeTimeout;
1387
+ /** The latest queued call */
1388
+ queuedCall;
1436
1389
  //#region listeners
1437
1390
  /** Adds a listener function that will be called on timeout */
1438
1391
  addListener(fn) {
@@ -1519,8 +1472,6 @@ function debounce(fn, timeout = 200, type = "immediate") {
1519
1472
  return func;
1520
1473
  }
1521
1474
 
1522
- if(__exports != exports)module.exports = exports;return module.exports}));
1523
-
1524
1475
 
1525
1476
 
1526
1477
  if (typeof module.exports == "object" && typeof exports == "object") {