@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.
- package/CHANGELOG.md +38 -0
- package/README.md +4 -3
- package/dist/CoreUtils.cjs +188 -114
- package/dist/CoreUtils.min.cjs +5 -3
- package/dist/CoreUtils.min.mjs +5 -3
- package/dist/CoreUtils.min.umd.js +5 -3
- package/dist/CoreUtils.mjs +188 -114
- package/dist/CoreUtils.umd.js +196 -120
- package/dist/lib/DataStore.d.ts +23 -9
- package/dist/lib/DataStoreEngine.d.ts +10 -10
- package/dist/lib/DataStoreSerializer.d.ts +3 -1
- package/dist/lib/Debouncer.d.ts +1 -1
- package/dist/lib/Errors.d.ts +15 -3
- package/dist/lib/NanoEmitter.d.ts +7 -6
- package/dist/lib/TieredCache.d.ts +4 -4
- package/dist/lib/Translate.d.ts +1 -1
- package/dist/lib/crypto.d.ts +1 -1
- package/dist/lib/index.d.ts +13 -13
- package/dist/lib/math.d.ts +2 -2
- package/dist/lib/misc.d.ts +7 -1
- package/dist/lib/{TestDataStore.d.ts → test/DirectAccessDataStore.d.ts} +4 -3
- package/dist/lib/test/softExpect.d.ts +11 -0
- package/dist/lib/text.d.ts +1 -1
- package/dist/lib/types.d.ts +7 -0
- package/package.json +18 -18
package/dist/CoreUtils.mjs
CHANGED
|
@@ -87,7 +87,7 @@ function roundFixed(num, fractionDigits) {
|
|
|
87
87
|
const scale = 10 ** fractionDigits;
|
|
88
88
|
return Math.round(num * scale) / scale;
|
|
89
89
|
}
|
|
90
|
-
function valsWithin(a, b, dec =
|
|
90
|
+
function valsWithin(a, b, dec = 1, withinRange = 0.5) {
|
|
91
91
|
return Math.abs(roundFixed(a, dec) - roundFixed(b, dec)) <= withinRange;
|
|
92
92
|
}
|
|
93
93
|
|
|
@@ -237,6 +237,52 @@ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase =
|
|
|
237
237
|
return arr.map((v) => caseArr[randRange(0, caseArr.length - 1, enhancedEntropy)] === 1 ? v.toUpperCase() : v).join("");
|
|
238
238
|
}
|
|
239
239
|
|
|
240
|
+
// lib/Errors.ts
|
|
241
|
+
var DatedError = class extends Error {
|
|
242
|
+
date;
|
|
243
|
+
constructor(message, options) {
|
|
244
|
+
super(message, options);
|
|
245
|
+
this.name = this.constructor.name;
|
|
246
|
+
this.date = /* @__PURE__ */ new Date();
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
var ChecksumMismatchError = class extends DatedError {
|
|
250
|
+
constructor(message, options) {
|
|
251
|
+
super(message, options);
|
|
252
|
+
this.name = "ChecksumMismatchError";
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
var CustomError = class extends DatedError {
|
|
256
|
+
constructor(name, message, options) {
|
|
257
|
+
super(message, options);
|
|
258
|
+
this.name = name;
|
|
259
|
+
}
|
|
260
|
+
};
|
|
261
|
+
var MigrationError = class extends DatedError {
|
|
262
|
+
constructor(message, options) {
|
|
263
|
+
super(message, options);
|
|
264
|
+
this.name = "MigrationError";
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
var ValidationError = class extends DatedError {
|
|
268
|
+
constructor(message, options) {
|
|
269
|
+
super(message, options);
|
|
270
|
+
this.name = "ValidationError";
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
var ScriptContextError = class extends DatedError {
|
|
274
|
+
constructor(message, options) {
|
|
275
|
+
super(message, options);
|
|
276
|
+
this.name = "ScriptContextError";
|
|
277
|
+
}
|
|
278
|
+
};
|
|
279
|
+
var NetworkError = class extends DatedError {
|
|
280
|
+
constructor(message, options) {
|
|
281
|
+
super(message, options);
|
|
282
|
+
this.name = "NetworkError";
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
|
|
240
286
|
// lib/misc.ts
|
|
241
287
|
async function consumeGen(valGen) {
|
|
242
288
|
return await (typeof valGen === "function" ? valGen() : valGen);
|
|
@@ -265,7 +311,7 @@ async function fetchAdvanced(input, options = {}) {
|
|
|
265
311
|
return res;
|
|
266
312
|
} catch (err) {
|
|
267
313
|
typeof id !== "undefined" && clearTimeout(id);
|
|
268
|
-
throw new
|
|
314
|
+
throw new NetworkError("Error while calling fetch", { cause: err });
|
|
269
315
|
}
|
|
270
316
|
}
|
|
271
317
|
function getListLength(listLike, zeroOnInvalid = true) {
|
|
@@ -276,7 +322,7 @@ function pauseFor(time, signal, rejectOnAbort = false) {
|
|
|
276
322
|
const timeout = setTimeout(() => res(), time);
|
|
277
323
|
signal == null ? void 0 : signal.addEventListener("abort", () => {
|
|
278
324
|
clearTimeout(timeout);
|
|
279
|
-
rejectOnAbort ? rej(new
|
|
325
|
+
rejectOnAbort ? rej(new CustomError("AbortError", "The pause was aborted")) : res();
|
|
280
326
|
});
|
|
281
327
|
});
|
|
282
328
|
}
|
|
@@ -311,14 +357,24 @@ function scheduleExit(code = 0, timeout = 0) {
|
|
|
311
357
|
if (timeout < 0)
|
|
312
358
|
throw new TypeError("Timeout must be a non-negative number");
|
|
313
359
|
let exit;
|
|
314
|
-
if (typeof process !== "undefined" && "exit" in process)
|
|
360
|
+
if (typeof process !== "undefined" && "exit" in process && typeof process.exit === "function")
|
|
315
361
|
exit = () => process.exit(code);
|
|
316
|
-
else if (typeof Deno !== "undefined" && "exit" in Deno)
|
|
362
|
+
else if (typeof Deno !== "undefined" && "exit" in Deno && typeof Deno.exit === "function")
|
|
317
363
|
exit = () => Deno.exit(code);
|
|
318
364
|
else
|
|
319
|
-
throw new
|
|
365
|
+
throw new ScriptContextError("Cannot exit the process, no exit method available");
|
|
320
366
|
setTimeout(exit, timeout);
|
|
321
367
|
}
|
|
368
|
+
function getCallStack(asArray, lines = Infinity) {
|
|
369
|
+
if (typeof lines !== "number" || isNaN(lines) || lines < 0)
|
|
370
|
+
throw new TypeError("lines parameter must be a non-negative number");
|
|
371
|
+
try {
|
|
372
|
+
throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)");
|
|
373
|
+
} catch (err) {
|
|
374
|
+
const stack = (err.stack ?? "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
|
|
375
|
+
return asArray !== false ? stack : stack.join("\n");
|
|
376
|
+
}
|
|
377
|
+
}
|
|
322
378
|
|
|
323
379
|
// lib/text.ts
|
|
324
380
|
function autoPlural(term, num, pluralType = "auto") {
|
|
@@ -388,16 +444,18 @@ function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
|
|
|
388
444
|
return arr.join(separators) + lastItm;
|
|
389
445
|
}
|
|
390
446
|
function secsToTimeStr(seconds) {
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
const
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
447
|
+
const isNegative = seconds < 0;
|
|
448
|
+
const s = Math.abs(seconds);
|
|
449
|
+
if (isNaN(s) || !isFinite(s))
|
|
450
|
+
throw new TypeError("The seconds argument must be a valid number");
|
|
451
|
+
const hrs = Math.floor(s / 3600);
|
|
452
|
+
const mins = Math.floor(s % 3600 / 60);
|
|
453
|
+
const secs = Math.floor(s % 60);
|
|
454
|
+
return (isNegative ? "-" : "") + [
|
|
455
|
+
hrs ? hrs + ":" : "",
|
|
456
|
+
String(mins).padStart(mins > 0 || hrs > 0 ? 2 : 1, "0"),
|
|
399
457
|
":",
|
|
400
|
-
String(secs).padStart(secs > 0 ||
|
|
458
|
+
String(secs).padStart(secs > 0 || mins > 0 || hrs > 0 || seconds === 0 ? 2 : 1, "0")
|
|
401
459
|
].join("");
|
|
402
460
|
}
|
|
403
461
|
function truncStr(input, length, endStr = "...") {
|
|
@@ -406,34 +464,6 @@ function truncStr(input, length, endStr = "...") {
|
|
|
406
464
|
return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
|
|
407
465
|
}
|
|
408
466
|
|
|
409
|
-
// lib/Errors.ts
|
|
410
|
-
var DatedError = class extends Error {
|
|
411
|
-
date;
|
|
412
|
-
constructor(message, options) {
|
|
413
|
-
super(message, options);
|
|
414
|
-
this.name = this.constructor.name;
|
|
415
|
-
this.date = /* @__PURE__ */ new Date();
|
|
416
|
-
}
|
|
417
|
-
};
|
|
418
|
-
var ChecksumMismatchError = class extends DatedError {
|
|
419
|
-
constructor(message, options) {
|
|
420
|
-
super(message, options);
|
|
421
|
-
this.name = "ChecksumMismatchError";
|
|
422
|
-
}
|
|
423
|
-
};
|
|
424
|
-
var MigrationError = class extends DatedError {
|
|
425
|
-
constructor(message, options) {
|
|
426
|
-
super(message, options);
|
|
427
|
-
this.name = "MigrationError";
|
|
428
|
-
}
|
|
429
|
-
};
|
|
430
|
-
var ValidationError = class extends DatedError {
|
|
431
|
-
constructor(message, options) {
|
|
432
|
-
super(message, options);
|
|
433
|
-
this.name = "ValidationError";
|
|
434
|
-
}
|
|
435
|
-
};
|
|
436
|
-
|
|
437
467
|
// lib/DataStore.ts
|
|
438
468
|
var dsFmtVer = 1;
|
|
439
469
|
var DataStore = class {
|
|
@@ -443,6 +473,7 @@ var DataStore = class {
|
|
|
443
473
|
encodeData;
|
|
444
474
|
decodeData;
|
|
445
475
|
compressionFormat = "deflate-raw";
|
|
476
|
+
memoryCache = true;
|
|
446
477
|
engine;
|
|
447
478
|
options;
|
|
448
479
|
/**
|
|
@@ -455,6 +486,7 @@ var DataStore = class {
|
|
|
455
486
|
cachedData;
|
|
456
487
|
migrations;
|
|
457
488
|
migrateIds = [];
|
|
489
|
+
//#region constructor
|
|
458
490
|
/**
|
|
459
491
|
* Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
|
|
460
492
|
* Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
|
|
@@ -469,7 +501,8 @@ var DataStore = class {
|
|
|
469
501
|
this.id = opts.id;
|
|
470
502
|
this.formatVersion = opts.formatVersion;
|
|
471
503
|
this.defaultData = opts.defaultData;
|
|
472
|
-
this.
|
|
504
|
+
this.memoryCache = Boolean(opts.memoryCache ?? true);
|
|
505
|
+
this.cachedData = this.memoryCache ? opts.defaultData : {};
|
|
473
506
|
this.migrations = opts.migrations;
|
|
474
507
|
if (opts.migrateIds)
|
|
475
508
|
this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
|
|
@@ -494,7 +527,7 @@ var DataStore = class {
|
|
|
494
527
|
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.");
|
|
495
528
|
this.engine.setDataStoreOptions(opts);
|
|
496
529
|
}
|
|
497
|
-
//#region
|
|
530
|
+
//#region loadData
|
|
498
531
|
/**
|
|
499
532
|
* Loads the data saved in persistent storage into the in-memory cache and also returns a copy of it.
|
|
500
533
|
* Automatically populates persistent storage with default data if it doesn't contain any data yet.
|
|
@@ -505,39 +538,40 @@ var DataStore = class {
|
|
|
505
538
|
if (this.firstInit) {
|
|
506
539
|
this.firstInit = false;
|
|
507
540
|
const dsVer = Number(await this.engine.getValue("__ds_fmt_ver", 0));
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
|
|
526
|
-
await Promise.allSettled(promises);
|
|
541
|
+
const oldData = await this.engine.getValue(`_uucfg-${this.id}`, null);
|
|
542
|
+
if (oldData) {
|
|
543
|
+
const oldVer = Number(await this.engine.getValue(`_uucfgver-${this.id}`, NaN));
|
|
544
|
+
const oldEnc = await this.engine.getValue(`_uucfgenc-${this.id}`, null);
|
|
545
|
+
const promises = [];
|
|
546
|
+
const migrateFmt = (oldKey, newKey, value) => {
|
|
547
|
+
promises.push(this.engine.setValue(newKey, value));
|
|
548
|
+
promises.push(this.engine.deleteValue(oldKey));
|
|
549
|
+
};
|
|
550
|
+
migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
|
|
551
|
+
if (!isNaN(oldVer))
|
|
552
|
+
migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
|
|
553
|
+
if (typeof oldEnc === "boolean")
|
|
554
|
+
migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? this.compressionFormat ?? null : null);
|
|
555
|
+
else {
|
|
556
|
+
promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
|
|
557
|
+
promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
|
|
527
558
|
}
|
|
528
|
-
await
|
|
559
|
+
await Promise.allSettled(promises);
|
|
529
560
|
}
|
|
561
|
+
if (isNaN(dsVer) || dsVer < dsFmtVer)
|
|
562
|
+
await this.engine.setValue("__ds_fmt_ver", dsFmtVer);
|
|
530
563
|
}
|
|
531
564
|
if (this.migrateIds.length > 0) {
|
|
532
565
|
await this.migrateId(this.migrateIds);
|
|
533
566
|
this.migrateIds = [];
|
|
534
567
|
}
|
|
535
|
-
const
|
|
568
|
+
const storedDataRaw = await this.engine.getValue(`__ds-${this.id}-dat`, null);
|
|
536
569
|
let storedFmtVer = Number(await this.engine.getValue(`__ds-${this.id}-ver`, NaN));
|
|
537
|
-
if (typeof
|
|
570
|
+
if (typeof storedDataRaw !== "string") {
|
|
538
571
|
await this.saveDefaultData();
|
|
539
|
-
return
|
|
572
|
+
return this.engine.deepCopy(this.defaultData);
|
|
540
573
|
}
|
|
574
|
+
const storedData = storedDataRaw ?? JSON.stringify(this.defaultData);
|
|
541
575
|
const encodingFmt = String(await this.engine.getValue(`__ds-${this.id}-enf`, null));
|
|
542
576
|
const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
|
|
543
577
|
let saveData = false;
|
|
@@ -550,23 +584,32 @@ var DataStore = class {
|
|
|
550
584
|
parsed = await this.runMigrations(parsed, storedFmtVer);
|
|
551
585
|
if (saveData)
|
|
552
586
|
await this.setData(parsed);
|
|
553
|
-
|
|
587
|
+
if (this.memoryCache)
|
|
588
|
+
return this.cachedData = this.engine.deepCopy(parsed);
|
|
589
|
+
else
|
|
590
|
+
return this.engine.deepCopy(parsed);
|
|
554
591
|
} catch (err) {
|
|
555
592
|
console.warn("Error while parsing JSON data, resetting it to the default value.", err);
|
|
556
593
|
await this.saveDefaultData();
|
|
557
594
|
return this.defaultData;
|
|
558
595
|
}
|
|
559
596
|
}
|
|
597
|
+
//#region getData
|
|
560
598
|
/**
|
|
561
599
|
* Returns a copy of the data from the in-memory cache.
|
|
562
|
-
* Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
|
|
600
|
+
* Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
|
|
601
|
+
* ⚠️ If `memoryCache` was set to `false` in the constructor options, this method will throw an error.
|
|
563
602
|
*/
|
|
564
603
|
getData() {
|
|
604
|
+
if (!this.memoryCache)
|
|
605
|
+
throw new DatedError("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");
|
|
565
606
|
return this.engine.deepCopy(this.cachedData);
|
|
566
607
|
}
|
|
608
|
+
//#region setData
|
|
567
609
|
/** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
|
|
568
610
|
setData(data) {
|
|
569
|
-
this.
|
|
611
|
+
if (this.memoryCache)
|
|
612
|
+
this.cachedData = data;
|
|
570
613
|
return new Promise(async (resolve) => {
|
|
571
614
|
await Promise.allSettled([
|
|
572
615
|
this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(data, this.encodingEnabled())),
|
|
@@ -576,15 +619,18 @@ var DataStore = class {
|
|
|
576
619
|
resolve();
|
|
577
620
|
});
|
|
578
621
|
}
|
|
622
|
+
//#region saveDefaultData
|
|
579
623
|
/** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
|
|
580
624
|
async saveDefaultData() {
|
|
581
|
-
|
|
625
|
+
if (this.memoryCache)
|
|
626
|
+
this.cachedData = this.defaultData;
|
|
582
627
|
await Promise.allSettled([
|
|
583
628
|
this.engine.setValue(`__ds-${this.id}-dat`, await this.engine.serializeData(this.defaultData, this.encodingEnabled())),
|
|
584
629
|
this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
|
|
585
630
|
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
|
|
586
631
|
]);
|
|
587
632
|
}
|
|
633
|
+
//#region deleteData
|
|
588
634
|
/**
|
|
589
635
|
* Call this method to clear all persistently stored data associated with this DataStore instance, including the storage container (if supported by the DataStoreEngine).
|
|
590
636
|
* The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
|
|
@@ -599,11 +645,12 @@ var DataStore = class {
|
|
|
599
645
|
]);
|
|
600
646
|
await ((_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a));
|
|
601
647
|
}
|
|
648
|
+
//#region encodingEnabled
|
|
602
649
|
/** Returns whether encoding and decoding are enabled for this DataStore instance */
|
|
603
650
|
encodingEnabled() {
|
|
604
651
|
return Boolean(this.encodeData && this.decodeData) && this.compressionFormat !== null || Boolean(this.compressionFormat);
|
|
605
652
|
}
|
|
606
|
-
//#region
|
|
653
|
+
//#region runMigrations
|
|
607
654
|
/**
|
|
608
655
|
* Runs all necessary migration functions consecutively and saves the result to the in-memory cache and persistent storage and also returns it.
|
|
609
656
|
* This method is automatically called by {@linkcode loadData()} if the data format has changed since the last time the data was saved.
|
|
@@ -637,8 +684,12 @@ var DataStore = class {
|
|
|
637
684
|
this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
|
|
638
685
|
this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
|
|
639
686
|
]);
|
|
640
|
-
|
|
687
|
+
if (this.memoryCache)
|
|
688
|
+
return this.cachedData = this.engine.deepCopy(newData);
|
|
689
|
+
else
|
|
690
|
+
return this.engine.deepCopy(newData);
|
|
641
691
|
}
|
|
692
|
+
//#region migrateId
|
|
642
693
|
/**
|
|
643
694
|
* Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
|
|
644
695
|
* 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.
|
|
@@ -682,7 +733,7 @@ var DataStoreEngine = class {
|
|
|
682
733
|
this.dataStoreOptions = dataStoreOptions;
|
|
683
734
|
}
|
|
684
735
|
//#region serialization api
|
|
685
|
-
/** Serializes the given object to a string, optionally encoded with `options.encodeData` if {@linkcode useEncoding} is set to
|
|
736
|
+
/** 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 */
|
|
686
737
|
async serializeData(data, useEncoding) {
|
|
687
738
|
var _a, _b, _c, _d, _e;
|
|
688
739
|
this.ensureDataStoreOptions();
|
|
@@ -730,7 +781,7 @@ var BrowserStorageEngine = class extends DataStoreEngine {
|
|
|
730
781
|
* Creates an instance of `BrowserStorageEngine`.
|
|
731
782
|
*
|
|
732
783
|
* - ⚠️ Requires a DOM environment
|
|
733
|
-
* - ⚠️ Don't reuse
|
|
784
|
+
* - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
|
|
734
785
|
*/
|
|
735
786
|
constructor(options) {
|
|
736
787
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
@@ -768,7 +819,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
768
819
|
* Creates an instance of `FileStorageEngine`.
|
|
769
820
|
*
|
|
770
821
|
* - ⚠️ Requires Node.js or Deno with Node compatibility (v1.31+)
|
|
771
|
-
* - ⚠️ Don't reuse
|
|
822
|
+
* - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
|
|
772
823
|
*/
|
|
773
824
|
constructor(options) {
|
|
774
825
|
super(options == null ? void 0 : options.dataStoreOptions);
|
|
@@ -786,7 +837,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
786
837
|
if (!fs)
|
|
787
838
|
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
788
839
|
if (!fs)
|
|
789
|
-
throw new
|
|
840
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
790
841
|
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
791
842
|
const data = await fs.readFile(path, "utf-8");
|
|
792
843
|
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;
|
|
@@ -802,7 +853,7 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
802
853
|
if (!fs)
|
|
803
854
|
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
804
855
|
if (!fs)
|
|
805
|
-
throw new
|
|
856
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
806
857
|
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
807
858
|
await fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
|
|
808
859
|
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");
|
|
@@ -831,8 +882,12 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
831
882
|
data = {};
|
|
832
883
|
data[name] = value;
|
|
833
884
|
await this.writeFile(data);
|
|
885
|
+
}).catch((err) => {
|
|
886
|
+
console.error("Error in setValue:", err);
|
|
887
|
+
throw err;
|
|
888
|
+
});
|
|
889
|
+
await this.fileAccessQueue.catch(() => {
|
|
834
890
|
});
|
|
835
|
-
await this.fileAccessQueue;
|
|
836
891
|
}
|
|
837
892
|
/** Deletes a value from persistent storage */
|
|
838
893
|
async deleteValue(name) {
|
|
@@ -842,8 +897,12 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
842
897
|
return;
|
|
843
898
|
delete data[name];
|
|
844
899
|
await this.writeFile(data);
|
|
900
|
+
}).catch((err) => {
|
|
901
|
+
console.error("Error in deleteValue:", err);
|
|
902
|
+
throw err;
|
|
903
|
+
});
|
|
904
|
+
await this.fileAccessQueue.catch(() => {
|
|
845
905
|
});
|
|
846
|
-
await this.fileAccessQueue;
|
|
847
906
|
}
|
|
848
907
|
/** Deletes the file that contains the data of this DataStore. */
|
|
849
908
|
async deleteStorage() {
|
|
@@ -853,9 +912,9 @@ var FileStorageEngine = class extends DataStoreEngine {
|
|
|
853
912
|
if (!fs)
|
|
854
913
|
fs = (_a = await import("fs/promises")) == null ? void 0 : _a.default;
|
|
855
914
|
if (!fs)
|
|
856
|
-
throw new
|
|
915
|
+
throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
|
|
857
916
|
const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
|
|
858
|
-
await fs.unlink(path);
|
|
917
|
+
return await fs.unlink(path);
|
|
859
918
|
} catch (err) {
|
|
860
919
|
console.error("Error deleting file:", err);
|
|
861
920
|
}
|
|
@@ -868,11 +927,12 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
868
927
|
options;
|
|
869
928
|
constructor(stores, options = {}) {
|
|
870
929
|
if (!crypto || !crypto.subtle)
|
|
871
|
-
throw new
|
|
930
|
+
throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
|
|
872
931
|
this.stores = stores;
|
|
873
932
|
this.options = {
|
|
874
933
|
addChecksum: true,
|
|
875
934
|
ensureIntegrity: true,
|
|
935
|
+
remapIds: {},
|
|
876
936
|
...options
|
|
877
937
|
};
|
|
878
938
|
}
|
|
@@ -889,9 +949,11 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
889
949
|
async serializePartial(stores, useEncoding = true, stringified = true) {
|
|
890
950
|
var _a;
|
|
891
951
|
const serData = [];
|
|
892
|
-
|
|
952
|
+
const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
|
|
953
|
+
for (const storeInst of filteredStores) {
|
|
893
954
|
const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
|
|
894
|
-
const
|
|
955
|
+
const rawData = storeInst.memoryCache ? storeInst.getData() : await storeInst.loadData();
|
|
956
|
+
const data = encoded ? await storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
|
|
895
957
|
serData.push({
|
|
896
958
|
id: storeInst.id,
|
|
897
959
|
data,
|
|
@@ -918,10 +980,18 @@ var DataStoreSerializer = class _DataStoreSerializer {
|
|
|
918
980
|
const deserStores = typeof data === "string" ? JSON.parse(data) : data;
|
|
919
981
|
if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
|
|
920
982
|
throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
|
|
921
|
-
|
|
922
|
-
|
|
983
|
+
const resolveStoreId = (id) => {
|
|
984
|
+
var _a;
|
|
985
|
+
return ((_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) ?? id;
|
|
986
|
+
};
|
|
987
|
+
const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
|
|
988
|
+
for (const storeData of deserStores) {
|
|
989
|
+
const effectiveId = resolveStoreId(storeData.id);
|
|
990
|
+
if (!matchesFilter(effectiveId))
|
|
991
|
+
continue;
|
|
992
|
+
const storeInst = this.stores.find((s) => s.id === effectiveId);
|
|
923
993
|
if (!storeInst)
|
|
924
|
-
throw new
|
|
994
|
+
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.`);
|
|
925
995
|
if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
|
|
926
996
|
const checksum = await this.calcChecksum(storeData.data);
|
|
927
997
|
if (checksum !== storeData.checksum)
|
|
@@ -1076,11 +1146,11 @@ var NanoEmitter = class {
|
|
|
1076
1146
|
once(event, cb) {
|
|
1077
1147
|
return new Promise((resolve) => {
|
|
1078
1148
|
let unsub;
|
|
1079
|
-
const onceProxy = (...args) => {
|
|
1149
|
+
const onceProxy = ((...args) => {
|
|
1080
1150
|
cb == null ? void 0 : cb(...args);
|
|
1081
1151
|
unsub == null ? void 0 : unsub();
|
|
1082
1152
|
resolve(args);
|
|
1083
|
-
};
|
|
1153
|
+
});
|
|
1084
1154
|
unsub = this.events.on(event, onceProxy);
|
|
1085
1155
|
this.eventUnsubscribes.push(unsub);
|
|
1086
1156
|
});
|
|
@@ -1092,11 +1162,12 @@ var NanoEmitter = class {
|
|
|
1092
1162
|
* `callback` (required) is the function that will be called when the conditions are met.
|
|
1093
1163
|
*
|
|
1094
1164
|
* 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.
|
|
1095
|
-
* If `signal` is provided, the subscription will be
|
|
1165
|
+
* If `signal` is provided, the subscription will be canceled when the given signal is aborted.
|
|
1096
1166
|
*
|
|
1097
1167
|
* If `oneOf` is used, the callback will be called when any of the matching events are emitted.
|
|
1098
1168
|
* 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.
|
|
1099
|
-
*
|
|
1169
|
+
* 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.
|
|
1170
|
+
* At least one of `oneOf` or `allOf` must be provided.
|
|
1100
1171
|
*
|
|
1101
1172
|
* @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.
|
|
1102
1173
|
*/
|
|
@@ -1124,6 +1195,8 @@ var NanoEmitter = class {
|
|
|
1124
1195
|
} = optsWithDefaults;
|
|
1125
1196
|
if (signal == null ? void 0 : signal.aborted)
|
|
1126
1197
|
return unsubAll;
|
|
1198
|
+
if (oneOf.length === 0 && allOf.length === 0)
|
|
1199
|
+
throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
|
|
1127
1200
|
const curEvtUnsubs = [];
|
|
1128
1201
|
const checkUnsubAllEvt = (force = false) => {
|
|
1129
1202
|
if (!(signal == null ? void 0 : signal.aborted) && !force)
|
|
@@ -1133,34 +1206,31 @@ var NanoEmitter = class {
|
|
|
1133
1206
|
curEvtUnsubs.splice(0, curEvtUnsubs.length);
|
|
1134
1207
|
this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
|
|
1135
1208
|
};
|
|
1209
|
+
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
1210
|
+
const allOfConditionMet = () => allOf.length === 0 || allOfEmitted.size === allOf.length;
|
|
1136
1211
|
for (const event of oneOf) {
|
|
1137
|
-
const unsub = this.events.on(event, (...args) => {
|
|
1212
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
1138
1213
|
checkUnsubAllEvt();
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1214
|
+
if (allOfConditionMet()) {
|
|
1215
|
+
callback(event, ...args);
|
|
1216
|
+
if (once)
|
|
1217
|
+
checkUnsubAllEvt(true);
|
|
1218
|
+
}
|
|
1219
|
+
}));
|
|
1143
1220
|
curEvtUnsubs.push(unsub);
|
|
1144
1221
|
}
|
|
1145
|
-
const allOfEmitted = /* @__PURE__ */ new Set();
|
|
1146
|
-
const checkAllOf = (event, ...args) => {
|
|
1147
|
-
checkUnsubAllEvt();
|
|
1148
|
-
allOfEmitted.add(event);
|
|
1149
|
-
if (allOfEmitted.size === allOf.length) {
|
|
1150
|
-
callback(event, ...args);
|
|
1151
|
-
if (once)
|
|
1152
|
-
checkUnsubAllEvt(true);
|
|
1153
|
-
}
|
|
1154
|
-
};
|
|
1155
1222
|
for (const event of allOf) {
|
|
1156
|
-
const unsub = this.events.on(event, (...args) => {
|
|
1223
|
+
const unsub = this.events.on(event, ((...args) => {
|
|
1157
1224
|
checkUnsubAllEvt();
|
|
1158
|
-
|
|
1159
|
-
|
|
1225
|
+
allOfEmitted.add(event);
|
|
1226
|
+
if (allOfConditionMet() && (oneOf.length === 0 || oneOf.includes(event))) {
|
|
1227
|
+
callback(event, ...args);
|
|
1228
|
+
if (once)
|
|
1229
|
+
checkUnsubAllEvt(true);
|
|
1230
|
+
}
|
|
1231
|
+
}));
|
|
1160
1232
|
curEvtUnsubs.push(unsub);
|
|
1161
1233
|
}
|
|
1162
|
-
if (oneOf.length === 0 && allOf.length === 0)
|
|
1163
|
-
throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
|
|
1164
1234
|
allUnsubs.push(() => checkUnsubAllEvt(true));
|
|
1165
1235
|
}
|
|
1166
1236
|
return unsubAll;
|
|
@@ -1288,13 +1358,14 @@ var Debouncer = class extends NanoEmitter {
|
|
|
1288
1358
|
function debounce(fn, timeout = 200, type = "immediate") {
|
|
1289
1359
|
const debouncer = new Debouncer(timeout, type);
|
|
1290
1360
|
debouncer.addListener(fn);
|
|
1291
|
-
const func = (...args) => debouncer.call(...args);
|
|
1361
|
+
const func = ((...args) => debouncer.call(...args));
|
|
1292
1362
|
func.debouncer = debouncer;
|
|
1293
1363
|
return func;
|
|
1294
1364
|
}
|
|
1295
1365
|
export {
|
|
1296
1366
|
BrowserStorageEngine,
|
|
1297
1367
|
ChecksumMismatchError,
|
|
1368
|
+
CustomError,
|
|
1298
1369
|
DataStore,
|
|
1299
1370
|
DataStoreEngine,
|
|
1300
1371
|
DataStoreSerializer,
|
|
@@ -1303,6 +1374,8 @@ export {
|
|
|
1303
1374
|
FileStorageEngine,
|
|
1304
1375
|
MigrationError,
|
|
1305
1376
|
NanoEmitter,
|
|
1377
|
+
NetworkError,
|
|
1378
|
+
ScriptContextError,
|
|
1306
1379
|
ValidationError,
|
|
1307
1380
|
abtoa,
|
|
1308
1381
|
atoab,
|
|
@@ -1322,6 +1395,7 @@ export {
|
|
|
1322
1395
|
digitCount,
|
|
1323
1396
|
fetchAdvanced,
|
|
1324
1397
|
formatNumber,
|
|
1398
|
+
getCallStack,
|
|
1325
1399
|
getListLength,
|
|
1326
1400
|
hexToRgb,
|
|
1327
1401
|
insertValues,
|