@sv443-network/userutils 10.0.0 → 10.0.2

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.
@@ -99,835 +99,1501 @@ var __async = (__this, __arguments, generator) => {
99
99
  // lib/index.ts
100
100
  var lib_exports = {};
101
101
  __export(lib_exports, {
102
+ BrowserStorageEngine: () => BrowserStorageEngine,
103
+ ChecksumMismatchError: () => ChecksumMismatchError,
104
+ CustomError: () => CustomError,
105
+ DataStore: () => DataStore,
106
+ DataStoreEngine: () => DataStoreEngine,
107
+ DataStoreSerializer: () => DataStoreSerializer,
108
+ DatedError: () => DatedError,
109
+ Debouncer: () => Debouncer,
102
110
  Dialog: () => Dialog,
111
+ FileStorageEngine: () => FileStorageEngine,
103
112
  GMStorageEngine: () => GMStorageEngine,
113
+ MigrationError: () => MigrationError,
104
114
  Mixins: () => Mixins,
115
+ NanoEmitter: () => NanoEmitter,
116
+ NetworkError: () => NetworkError,
105
117
  PlatformError: () => PlatformError,
118
+ ScriptContextError: () => ScriptContextError,
106
119
  SelectorObserver: () => SelectorObserver,
120
+ ValidationError: () => ValidationError,
121
+ abtoa: () => abtoa,
107
122
  addGlobalStyle: () => addGlobalStyle,
108
123
  addParent: () => addParent,
124
+ atoab: () => atoab,
125
+ autoPlural: () => autoPlural,
126
+ bitSetHas: () => bitSetHas,
127
+ capitalize: () => capitalize,
128
+ clamp: () => clamp,
129
+ compress: () => compress,
130
+ computeHash: () => computeHash,
131
+ consumeGen: () => consumeGen,
132
+ consumeStringGen: () => consumeStringGen,
133
+ createProgressBar: () => createProgressBar,
109
134
  currentDialogId: () => currentDialogId,
135
+ darkenColor: () => darkenColor,
136
+ debounce: () => debounce,
137
+ decompress: () => decompress,
110
138
  defaultDialogCss: () => defaultDialogCss,
139
+ defaultPbChars: () => defaultPbChars,
111
140
  defaultStrings: () => defaultStrings,
141
+ digitCount: () => digitCount,
142
+ fetchAdvanced: () => fetchAdvanced,
143
+ formatNumber: () => formatNumber,
144
+ getCallStack: () => getCallStack,
145
+ getListLength: () => getListLength,
112
146
  getSiblingsFrame: () => getSiblingsFrame,
113
147
  getUnsafeWindow: () => getUnsafeWindow,
148
+ hexToRgb: () => hexToRgb,
149
+ insertValues: () => insertValues,
114
150
  interceptEvent: () => interceptEvent,
115
151
  interceptWindowEvent: () => interceptWindowEvent,
116
152
  isDomLoaded: () => isDomLoaded,
117
153
  isScrollable: () => isScrollable,
154
+ joinArrayReadable: () => joinArrayReadable,
155
+ lightenColor: () => lightenColor,
156
+ mapRange: () => mapRange,
118
157
  observeElementProp: () => observeElementProp,
119
158
  onDomLoad: () => onDomLoad,
120
159
  openDialogs: () => openDialogs,
121
160
  openInNewTab: () => openInNewTab,
161
+ overflowVal: () => overflowVal,
162
+ pauseFor: () => pauseFor,
122
163
  preloadImages: () => preloadImages,
123
164
  probeElementStyle: () => probeElementStyle,
165
+ pureObj: () => pureObj,
166
+ randRange: () => randRange,
167
+ randomId: () => randomId,
168
+ randomItem: () => randomItem,
169
+ randomItemIndex: () => randomItemIndex,
170
+ randomizeArray: () => randomizeArray,
171
+ rgbToHex: () => rgbToHex,
172
+ roundFixed: () => roundFixed,
173
+ scheduleExit: () => scheduleExit,
174
+ secsToTimeStr: () => secsToTimeStr,
175
+ setImmediateInterval: () => setImmediateInterval,
176
+ setImmediateTimeoutLoop: () => setImmediateTimeoutLoop,
124
177
  setInnerHtmlUnsafe: () => setInnerHtmlUnsafe,
125
- tr: () => tr
178
+ takeRandomItem: () => takeRandomItem,
179
+ takeRandomItemIndex: () => takeRandomItemIndex,
180
+ tr: () => tr,
181
+ truncStr: () => truncStr,
182
+ valsWithin: () => valsWithin
126
183
  });
127
184
  module.exports = __toCommonJS(lib_exports);
128
185
 
129
- // node_modules/.pnpm/@sv443-network+coreutils@3.0.1/node_modules/@sv443-network/coreutils/dist/CoreUtils.min.umd.js
130
- (function(g, f) {
131
- if ("object" == typeof exports && "object" == typeof module) {
132
- module.exports = f();
133
- } else if ("function" == typeof define && define.amd) {
134
- define("CoreUtils", [], f);
135
- } else if ("object" == typeof exports) {
136
- exports["CoreUtils"] = f();
137
- } else {
138
- g["CoreUtils"] = f();
139
- }
140
- })(void 0, () => {
141
- var exports2 = {};
142
- var module2 = { exports: exports2 };
143
- "use strict";
144
- var X = Object.create;
145
- var F = Object.defineProperty;
146
- var Y = Object.getOwnPropertyDescriptor;
147
- var ee = Object.getOwnPropertyNames;
148
- var te = Object.getPrototypeOf, re = Object.prototype.hasOwnProperty;
149
- var ie = (r, e) => {
150
- for (var t in e) F(r, t, { get: e[t], enumerable: true });
151
- }, B = (r, e, t, i) => {
152
- if (e && typeof e == "object" || typeof e == "function") for (let n of ee(e)) !re.call(r, n) && n !== t && F(r, n, { get: () => e[n], enumerable: !(i = Y(e, n)) || i.enumerable });
153
- return r;
186
+ // node_modules/.pnpm/@sv443-network+coreutils@3.0.2/node_modules/@sv443-network/coreutils/dist/CoreUtils.mjs
187
+ function bitSetHas(bitSet, checkVal) {
188
+ return (bitSet & checkVal) === checkVal;
189
+ }
190
+ function clamp(value, min, max) {
191
+ if (typeof max !== "number") {
192
+ max = min;
193
+ min = 0;
194
+ }
195
+ return Math.max(Math.min(value, max), min);
196
+ }
197
+ function digitCount(num, withDecimals = true) {
198
+ num = Number(!["string", "number"].includes(typeof num) ? String(num) : num);
199
+ if (typeof num === "number" && isNaN(num))
200
+ return NaN;
201
+ const [intPart, decPart] = num.toString().split(".");
202
+ const intDigits = intPart === "0" ? 1 : Math.floor(Math.log10(Math.abs(Number(intPart))) + 1);
203
+ const decDigits = withDecimals && decPart ? decPart.length : 0;
204
+ return intDigits + decDigits;
205
+ }
206
+ function formatNumber(number, locale, format) {
207
+ return number.toLocaleString(
208
+ locale,
209
+ format === "short" ? {
210
+ notation: "compact",
211
+ compactDisplay: "short",
212
+ maximumFractionDigits: 1
213
+ } : {
214
+ style: "decimal",
215
+ maximumFractionDigits: 0
216
+ }
217
+ );
218
+ }
219
+ function mapRange(value, range1min, range1max, range2min, range2max) {
220
+ if (typeof range2min === "undefined" || typeof range2max === "undefined") {
221
+ range2max = range1max;
222
+ range1max = range1min;
223
+ range2min = range1min = 0;
224
+ }
225
+ if (Number(range1min) === 0 && Number(range2min) === 0)
226
+ return value * (range2max / range1max);
227
+ return (value - range1min) * ((range2max - range2min) / (range1max - range1min)) + range2min;
228
+ }
229
+ function overflowVal(value, minOrMax, max) {
230
+ const min = typeof max === "number" ? minOrMax : 0;
231
+ max = typeof max === "number" ? max : minOrMax;
232
+ if (min > max)
233
+ throw new RangeError(`Parameter "min" can't be bigger than "max"`);
234
+ if (isNaN(value) || isNaN(min) || isNaN(max) || !isFinite(value) || !isFinite(min) || !isFinite(max))
235
+ return NaN;
236
+ if (value >= min && value <= max)
237
+ return value;
238
+ const range = max - min + 1;
239
+ const wrappedValue = ((value - min) % range + range) % range + min;
240
+ return wrappedValue;
241
+ }
242
+ function randRange(...args) {
243
+ let min, max, enhancedEntropy = false;
244
+ if (typeof args[0] === "number" && typeof args[1] === "number")
245
+ [min, max] = args;
246
+ else if (typeof args[0] === "number" && typeof args[1] !== "number") {
247
+ min = 0;
248
+ [max] = args;
249
+ } else
250
+ throw new TypeError(`Wrong parameter(s) provided - expected (number, boolean|undefined) or (number, number, boolean|undefined) but got (${args.map((a) => typeof a).join(", ")}) instead`);
251
+ if (typeof args[2] === "boolean")
252
+ enhancedEntropy = args[2];
253
+ else if (typeof args[1] === "boolean")
254
+ enhancedEntropy = args[1];
255
+ min = Number(min);
256
+ max = Number(max);
257
+ if (isNaN(min) || isNaN(max))
258
+ return NaN;
259
+ if (min > max)
260
+ throw new TypeError(`Parameter "min" can't be bigger than "max"`);
261
+ if (enhancedEntropy) {
262
+ const uintArr = new Uint8Array(1);
263
+ crypto.getRandomValues(uintArr);
264
+ return Number(Array.from(
265
+ uintArr,
266
+ (v) => Math.round(mapRange(v, 0, 255, min, max)).toString(10)
267
+ ).join(""));
268
+ } else
269
+ return Math.floor(Math.random() * (max - min + 1)) + min;
270
+ }
271
+ function roundFixed(num, fractionDigits) {
272
+ const scale = __pow(10, fractionDigits);
273
+ return Math.round(num * scale) / scale;
274
+ }
275
+ function valsWithin(a, b, dec = 1, withinRange = 0.5) {
276
+ return Math.abs(roundFixed(a, dec) - roundFixed(b, dec)) <= withinRange;
277
+ }
278
+ function randomItem(array) {
279
+ return randomItemIndex(array)[0];
280
+ }
281
+ function randomItemIndex(array) {
282
+ if (array.length === 0)
283
+ return [void 0, void 0];
284
+ const idx = randRange(array.length - 1);
285
+ return [array[idx], idx];
286
+ }
287
+ function randomizeArray(array) {
288
+ const retArray = [...array];
289
+ if (array.length === 0)
290
+ return retArray;
291
+ for (let i = retArray.length - 1; i > 0; i--) {
292
+ const j = Math.floor(Math.random() * (i + 1));
293
+ [retArray[i], retArray[j]] = [retArray[j], retArray[i]];
294
+ }
295
+ return retArray;
296
+ }
297
+ function takeRandomItem(arr) {
298
+ var _a;
299
+ return (_a = takeRandomItemIndex(arr)) == null ? void 0 : _a[0];
300
+ }
301
+ function takeRandomItemIndex(arr) {
302
+ const [itm, idx] = randomItemIndex(arr);
303
+ if (idx === void 0)
304
+ return [void 0, void 0];
305
+ arr.splice(idx, 1);
306
+ return [itm, idx];
307
+ }
308
+ function darkenColor(color, percent, upperCase = false) {
309
+ var _a;
310
+ color = color.trim();
311
+ const darkenRgb = (r2, g2, b2, percent2) => {
312
+ r2 = Math.max(0, Math.min(255, r2 - r2 * percent2 / 100));
313
+ g2 = Math.max(0, Math.min(255, g2 - g2 * percent2 / 100));
314
+ b2 = Math.max(0, Math.min(255, b2 - b2 * percent2 / 100));
315
+ return [r2, g2, b2];
154
316
  };
155
- var I = (r, e, t) => (t = r != null ? X(te(r)) : {}, B(e || !r || !r.__esModule ? F(t, "default", { value: r, enumerable: true }) : t, r)), ne = (r) => B(F({}, "__esModule", { value: true }), r);
156
- var _e = {};
157
- ie(_e, { BrowserStorageEngine: () => U, ChecksumMismatchError: () => S, CustomError: () => v, DataStore: () => z, DataStoreEngine: () => E, DataStoreSerializer: () => j, DatedError: () => d, Debouncer: () => A, FileStorageEngine: () => R, MigrationError: () => w, NanoEmitter: () => P, NetworkError: () => x, ScriptContextError: () => g, ValidationError: () => $, abtoa: () => H, atoab: () => W, autoPlural: () => Pe, bitSetHas: () => ae, capitalize: () => Oe, clamp: () => D, compress: () => N, computeHash: () => k, consumeGen: () => ge, consumeStringGen: () => be, createProgressBar: () => Fe, darkenColor: () => L, debounce: () => Ie, decompress: () => fe, defaultPbChars: () => Q, digitCount: () => oe, fetchAdvanced: () => ye, formatNumber: () => se, getCallStack: () => Ee, getListLength: () => De, hexToRgb: () => q, insertValues: () => Ve, joinArrayReadable: () => Ne, lightenColor: () => pe, mapRange: () => V, overflowVal: () => ue, pauseFor: () => Te, pureObj: () => Se, randRange: () => T, randomId: () => he, randomItem: () => le, randomItemIndex: () => C, randomizeArray: () => de, rgbToHex: () => J, roundFixed: () => _, scheduleExit: () => xe, secsToTimeStr: () => Ae, setImmediateInterval: () => ve, setImmediateTimeoutLoop: () => we, takeRandomItem: () => me, takeRandomItemIndex: () => K, truncStr: () => Me, valsWithin: () => ce });
158
- module2.exports = ne(_e);
159
- function ae(r, e) {
160
- return (r & e) === e;
161
- }
162
- function D(r, e, t) {
163
- return typeof t != "number" && (t = e, e = 0), Math.max(Math.min(r, t), e);
164
- }
165
- function oe(r, e = true) {
166
- if (r = Number(["string", "number"].includes(typeof r) ? r : String(r)), typeof r == "number" && isNaN(r)) return NaN;
167
- let [t, i] = r.toString().split("."), n = t === "0" ? 1 : Math.floor(Math.log10(Math.abs(Number(t))) + 1), o = e && i ? i.length : 0;
168
- return n + o;
169
- }
170
- function se(r, e, t) {
171
- return r.toLocaleString(e, t === "short" ? { notation: "compact", compactDisplay: "short", maximumFractionDigits: 1 } : { style: "decimal", maximumFractionDigits: 0 });
172
- }
173
- function V(r, e, t, i, n) {
174
- return (typeof i > "u" || typeof n > "u") && (n = t, t = e, i = e = 0), Number(e) === 0 && Number(i) === 0 ? r * (n / t) : (r - e) * ((n - i) / (t - e)) + i;
175
- }
176
- function ue(r, e, t) {
177
- let i = typeof t == "number" ? e : 0;
178
- if (t = typeof t == "number" ? t : e, i > t) throw new RangeError(`Parameter "min" can't be bigger than "max"`);
179
- if (isNaN(r) || isNaN(i) || isNaN(t) || !isFinite(r) || !isFinite(i) || !isFinite(t)) return NaN;
180
- if (r >= i && r <= t) return r;
181
- let n = t - i + 1;
182
- return ((r - i) % n + n) % n + i;
183
- }
184
- function T(...r) {
185
- let e, t, i = false;
186
- if (typeof r[0] == "number" && typeof r[1] == "number") [e, t] = r;
187
- else if (typeof r[0] == "number" && typeof r[1] != "number") e = 0, [t] = r;
188
- else throw new TypeError(`Wrong parameter(s) provided - expected (number, boolean|undefined) or (number, number, boolean|undefined) but got (${r.map((n) => typeof n).join(", ")}) instead`);
189
- if (typeof r[2] == "boolean" ? i = r[2] : typeof r[1] == "boolean" && (i = r[1]), e = Number(e), t = Number(t), isNaN(e) || isNaN(t)) return NaN;
190
- if (e > t) throw new TypeError(`Parameter "min" can't be bigger than "max"`);
191
- if (i) {
192
- let n = new Uint8Array(1);
193
- return crypto.getRandomValues(n), Number(Array.from(n, (o) => Math.round(V(o, 0, 255, e, t)).toString(10)).join(""));
194
- } else return Math.floor(Math.random() * (t - e + 1)) + e;
195
- }
196
- function _(r, e) {
197
- let t = __pow(10, e);
198
- return Math.round(r * t) / t;
199
- }
200
- function ce(r, e, t = 1, i = 0.5) {
201
- return Math.abs(_(r, t) - _(e, t)) <= i;
202
- }
203
- function le(r) {
204
- return C(r)[0];
205
- }
206
- function C(r) {
207
- if (r.length === 0) return [void 0, void 0];
208
- let e = T(r.length - 1);
209
- return [r[e], e];
210
- }
211
- function de(r) {
212
- let e = [...r];
213
- if (r.length === 0) return e;
214
- for (let t = e.length - 1; t > 0; t--) {
215
- let i = Math.floor(Math.random() * (t + 1));
216
- [e[t], e[i]] = [e[i], e[t]];
317
+ let r, g, b, a;
318
+ const isHexCol = color.match(/^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/);
319
+ if (isHexCol)
320
+ [r, g, b, a] = hexToRgb(color);
321
+ else if (color.startsWith("rgb")) {
322
+ const rgbValues = (_a = color.match(/\d+(\.\d+)?/g)) == null ? void 0 : _a.map(Number);
323
+ if (!rgbValues)
324
+ throw new TypeError("Invalid RGB/RGBA color format");
325
+ [r, g, b, a] = rgbValues;
326
+ } else
327
+ throw new TypeError("Unsupported color format");
328
+ [r, g, b] = darkenRgb(r, g, b, percent);
329
+ if (isHexCol)
330
+ return rgbToHex(r, g, b, a, color.startsWith("#"), upperCase);
331
+ else if (color.startsWith("rgba"))
332
+ return `rgba(${r}, ${g}, ${b}, ${a != null ? a : NaN})`;
333
+ else
334
+ return `rgb(${r}, ${g}, ${b})`;
335
+ }
336
+ function hexToRgb(hex) {
337
+ hex = (hex.startsWith("#") ? hex.slice(1) : hex).trim();
338
+ const a = hex.length === 8 || hex.length === 4 ? parseInt(hex.slice(-(hex.length / 4)), 16) / (hex.length === 8 ? 255 : 15) : void 0;
339
+ if (!isNaN(Number(a)))
340
+ hex = hex.slice(0, -(hex.length / 4));
341
+ if (hex.length === 3 || hex.length === 4)
342
+ hex = hex.split("").map((c) => c + c).join("");
343
+ const hexInt = parseInt(hex, 16);
344
+ const r = hexInt >> 16 & 255;
345
+ const g = hexInt >> 8 & 255;
346
+ const b = hexInt & 255;
347
+ return [clamp(r, 0, 255), clamp(g, 0, 255), clamp(b, 0, 255), typeof a === "number" ? clamp(a, 0, 1) : void 0];
348
+ }
349
+ function lightenColor(color, percent, upperCase = false) {
350
+ return darkenColor(color, percent * -1, upperCase);
351
+ }
352
+ function rgbToHex(red, green, blue, alpha, withHash = true, upperCase = false) {
353
+ const toHexVal = (n) => clamp(Math.round(n), 0, 255).toString(16).padStart(2, "0")[upperCase ? "toUpperCase" : "toLowerCase"]();
354
+ return `${withHash ? "#" : ""}${toHexVal(red)}${toHexVal(green)}${toHexVal(blue)}${alpha ? toHexVal(alpha * 255) : ""}`;
355
+ }
356
+ function abtoa(buf) {
357
+ return btoa(
358
+ new Uint8Array(buf).reduce((data, byte) => data + String.fromCharCode(byte), "")
359
+ );
360
+ }
361
+ function atoab(str) {
362
+ return Uint8Array.from(atob(str), (c) => c.charCodeAt(0));
363
+ }
364
+ function compress(input, compressionFormat, outputType = "string") {
365
+ return __async(this, null, function* () {
366
+ var _a;
367
+ const byteArray = input instanceof Uint8Array ? input : new TextEncoder().encode((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
368
+ const comp = new CompressionStream(compressionFormat);
369
+ const writer = comp.writable.getWriter();
370
+ writer.write(byteArray);
371
+ writer.close();
372
+ const uintArr = new Uint8Array(yield new Response(comp.readable).arrayBuffer());
373
+ return outputType === "arrayBuffer" ? uintArr : abtoa(uintArr);
374
+ });
375
+ }
376
+ function decompress(input, compressionFormat, outputType = "string") {
377
+ return __async(this, null, function* () {
378
+ var _a;
379
+ const byteArray = input instanceof Uint8Array ? input : atoab((_a = input == null ? void 0 : input.toString()) != null ? _a : String(input));
380
+ const decomp = new DecompressionStream(compressionFormat);
381
+ const writer = decomp.writable.getWriter();
382
+ writer.write(byteArray);
383
+ writer.close();
384
+ const uintArr = new Uint8Array(yield new Response(decomp.readable).arrayBuffer());
385
+ return outputType === "arrayBuffer" ? uintArr : new TextDecoder().decode(uintArr);
386
+ });
387
+ }
388
+ function computeHash(input, algorithm = "SHA-256") {
389
+ return __async(this, null, function* () {
390
+ let data;
391
+ if (typeof input === "string") {
392
+ const encoder = new TextEncoder();
393
+ data = encoder.encode(input);
394
+ } else
395
+ data = input;
396
+ const hashBuffer = yield crypto.subtle.digest(algorithm, data);
397
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
398
+ const hashHex = hashArray.map((byte) => byte.toString(16).padStart(2, "0")).join("");
399
+ return hashHex;
400
+ });
401
+ }
402
+ function randomId(length = 16, radix = 16, enhancedEntropy = false, randomCase = true) {
403
+ if (length < 1)
404
+ throw new RangeError("The length argument must be at least 1");
405
+ if (radix < 2 || radix > 36)
406
+ throw new RangeError("The radix argument must be between 2 and 36");
407
+ let arr = [];
408
+ const caseArr = randomCase ? [0, 1] : [0];
409
+ if (enhancedEntropy) {
410
+ const uintArr = new Uint8Array(length);
411
+ crypto.getRandomValues(uintArr);
412
+ arr = Array.from(
413
+ uintArr,
414
+ (v) => mapRange(v, 0, 255, 0, radix).toString(radix).substring(0, 1)
415
+ );
416
+ } else {
417
+ arr = Array.from(
418
+ { length },
419
+ () => Math.floor(Math.random() * radix).toString(radix)
420
+ );
421
+ }
422
+ if (!arr.some((v) => /[a-zA-Z]/.test(v)))
423
+ return arr.join("");
424
+ return arr.map((v) => caseArr[randRange(0, caseArr.length - 1, enhancedEntropy)] === 1 ? v.toUpperCase() : v).join("");
425
+ }
426
+ var DatedError = class extends Error {
427
+ constructor(message, options) {
428
+ super(message, options);
429
+ __publicField(this, "date");
430
+ this.name = this.constructor.name;
431
+ this.date = /* @__PURE__ */ new Date();
432
+ }
433
+ };
434
+ var ChecksumMismatchError = class extends DatedError {
435
+ constructor(message, options) {
436
+ super(message, options);
437
+ this.name = "ChecksumMismatchError";
438
+ }
439
+ };
440
+ var CustomError = class extends DatedError {
441
+ constructor(name, message, options) {
442
+ super(message, options);
443
+ this.name = name;
444
+ }
445
+ };
446
+ var MigrationError = class extends DatedError {
447
+ constructor(message, options) {
448
+ super(message, options);
449
+ this.name = "MigrationError";
450
+ }
451
+ };
452
+ var ValidationError = class extends DatedError {
453
+ constructor(message, options) {
454
+ super(message, options);
455
+ this.name = "ValidationError";
456
+ }
457
+ };
458
+ var ScriptContextError = class extends DatedError {
459
+ constructor(message, options) {
460
+ super(message, options);
461
+ this.name = "ScriptContextError";
462
+ }
463
+ };
464
+ var NetworkError = class extends DatedError {
465
+ constructor(message, options) {
466
+ super(message, options);
467
+ this.name = "NetworkError";
468
+ }
469
+ };
470
+ function consumeGen(valGen) {
471
+ return __async(this, null, function* () {
472
+ return yield typeof valGen === "function" ? valGen() : valGen;
473
+ });
474
+ }
475
+ function consumeStringGen(strGen) {
476
+ return __async(this, null, function* () {
477
+ return typeof strGen === "string" ? strGen : String(
478
+ typeof strGen === "function" ? yield strGen() : strGen
479
+ );
480
+ });
481
+ }
482
+ function fetchAdvanced(_0) {
483
+ return __async(this, arguments, function* (input, options = {}) {
484
+ const _a = options, { timeout = 1e4, signal } = _a, restOpts = __objRest(_a, ["timeout", "signal"]);
485
+ const ctl = new AbortController();
486
+ signal == null ? void 0 : signal.addEventListener("abort", () => ctl.abort());
487
+ let sigOpts = {}, id = void 0;
488
+ if (timeout >= 0) {
489
+ id = setTimeout(() => ctl.abort(), timeout);
490
+ sigOpts = { signal: ctl.signal };
217
491
  }
218
- return e;
219
- }
220
- function me(r) {
221
- var e;
222
- return (e = K(r)) == null ? void 0 : e[0];
223
- }
224
- function K(r) {
225
- let [e, t] = C(r);
226
- return t === void 0 ? [void 0, void 0] : (r.splice(t, 1), [e, t]);
227
- }
228
- function L(r, e, t = false) {
229
- var l;
230
- r = r.trim();
231
- let i = (c, p, m, b) => (c = Math.max(0, Math.min(255, c - c * b / 100)), p = Math.max(0, Math.min(255, p - p * b / 100)), m = Math.max(0, Math.min(255, m - m * b / 100)), [c, p, m]), n, o, a, s, u = r.match(/^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$/);
232
- if (u) [n, o, a, s] = q(r);
233
- else if (r.startsWith("rgb")) {
234
- let c = (l = r.match(/\d+(\.\d+)?/g)) == null ? void 0 : l.map(Number);
235
- if (!c) throw new TypeError("Invalid RGB/RGBA color format");
236
- [n, o, a, s] = c;
237
- } else throw new TypeError("Unsupported color format");
238
- return [n, o, a] = i(n, o, a, e), u ? J(n, o, a, s, r.startsWith("#"), t) : r.startsWith("rgba") ? `rgba(${n}, ${o}, ${a}, ${s != null ? s : NaN})` : `rgb(${n}, ${o}, ${a})`;
239
- }
240
- function q(r) {
241
- r = (r.startsWith("#") ? r.slice(1) : r).trim();
242
- let e = r.length === 8 || r.length === 4 ? parseInt(r.slice(-(r.length / 4)), 16) / (r.length === 8 ? 255 : 15) : void 0;
243
- isNaN(Number(e)) || (r = r.slice(0, -(r.length / 4))), (r.length === 3 || r.length === 4) && (r = r.split("").map((a) => a + a).join(""));
244
- let t = parseInt(r, 16), i = t >> 16 & 255, n = t >> 8 & 255, o = t & 255;
245
- return [D(i, 0, 255), D(n, 0, 255), D(o, 0, 255), typeof e == "number" ? D(e, 0, 1) : void 0];
246
- }
247
- function pe(r, e, t = false) {
248
- return L(r, e * -1, t);
249
- }
250
- function J(r, e, t, i, n = true, o = false) {
251
- let a = (s) => D(Math.round(s), 0, 255).toString(16).padStart(2, "0")[o ? "toUpperCase" : "toLowerCase"]();
252
- return `${n ? "#" : ""}${a(r)}${a(e)}${a(t)}${i ? a(i * 255) : ""}`;
253
- }
254
- function H(r) {
255
- return btoa(new Uint8Array(r).reduce((e, t) => e + String.fromCharCode(t), ""));
256
- }
257
- function W(r) {
258
- return Uint8Array.from(atob(r), (e) => e.charCodeAt(0));
259
- }
260
- function N(r, e, t = "string") {
261
- return __async(this, null, function* () {
262
- var _a;
263
- let i = r instanceof Uint8Array ? r : new TextEncoder().encode((_a = r == null ? void 0 : r.toString()) != null ? _a : String(r)), n = new CompressionStream(e), o = n.writable.getWriter();
264
- o.write(i), o.close();
265
- let a = new Uint8Array(yield new Response(n.readable).arrayBuffer());
266
- return t === "arrayBuffer" ? a : H(a);
492
+ try {
493
+ const res = yield fetch(input, __spreadValues(__spreadValues({}, restOpts), sigOpts));
494
+ typeof id !== "undefined" && clearTimeout(id);
495
+ return res;
496
+ } catch (err) {
497
+ typeof id !== "undefined" && clearTimeout(id);
498
+ throw new NetworkError("Error while calling fetch", { cause: err });
499
+ }
500
+ });
501
+ }
502
+ function getListLength(listLike, zeroOnInvalid = true) {
503
+ return "length" in listLike ? listLike.length : "size" in listLike ? listLike.size : "count" in listLike ? listLike.count : zeroOnInvalid ? 0 : NaN;
504
+ }
505
+ function pauseFor(time, signal, rejectOnAbort = false) {
506
+ return new Promise((res, rej) => {
507
+ const timeout = setTimeout(() => res(), time);
508
+ signal == null ? void 0 : signal.addEventListener("abort", () => {
509
+ clearTimeout(timeout);
510
+ rejectOnAbort ? rej(new CustomError("AbortError", "The pause was aborted")) : res();
267
511
  });
512
+ });
513
+ }
514
+ function pureObj(obj) {
515
+ return Object.assign(/* @__PURE__ */ Object.create(null), obj != null ? obj : {});
516
+ }
517
+ function setImmediateInterval(callback, interval, signal) {
518
+ let intervalId;
519
+ const cleanup = () => clearInterval(intervalId);
520
+ const loop = () => {
521
+ if (signal == null ? void 0 : signal.aborted)
522
+ return cleanup();
523
+ callback();
524
+ };
525
+ signal == null ? void 0 : signal.addEventListener("abort", cleanup);
526
+ loop();
527
+ intervalId = setInterval(loop, interval);
528
+ }
529
+ function setImmediateTimeoutLoop(callback, interval, signal) {
530
+ let timeout;
531
+ const cleanup = () => clearTimeout(timeout);
532
+ const loop = () => __async(null, null, function* () {
533
+ if (signal == null ? void 0 : signal.aborted)
534
+ return cleanup();
535
+ yield callback();
536
+ timeout = setTimeout(loop, interval);
537
+ });
538
+ signal == null ? void 0 : signal.addEventListener("abort", cleanup);
539
+ loop();
540
+ }
541
+ function scheduleExit(code = 0, timeout = 0) {
542
+ if (timeout < 0)
543
+ throw new TypeError("Timeout must be a non-negative number");
544
+ let exit;
545
+ if (typeof process !== "undefined" && "exit" in process && typeof process.exit === "function")
546
+ exit = () => process.exit(code);
547
+ else if (typeof Deno !== "undefined" && "exit" in Deno && typeof Deno.exit === "function")
548
+ exit = () => Deno.exit(code);
549
+ else
550
+ throw new ScriptContextError("Cannot exit the process, no exit method available");
551
+ setTimeout(exit, timeout);
552
+ }
553
+ function getCallStack(asArray, lines = Infinity) {
554
+ var _a;
555
+ if (typeof lines !== "number" || isNaN(lines) || lines < 0)
556
+ throw new TypeError("lines parameter must be a non-negative number");
557
+ try {
558
+ throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)");
559
+ } catch (err) {
560
+ const stack = ((_a = err.stack) != null ? _a : "").split("\n").map((line) => line.trim()).slice(2, lines + 2);
561
+ return asArray !== false ? stack : stack.join("\n");
562
+ }
563
+ }
564
+ function autoPlural(term, num, pluralType = "auto") {
565
+ if (typeof num !== "number") {
566
+ if ("length" in num)
567
+ num = num.length;
568
+ else if ("size" in num)
569
+ num = num.size;
570
+ else if ("count" in num)
571
+ num = num.count;
572
+ }
573
+ if (!["-s", "-ies"].includes(pluralType))
574
+ pluralType = "auto";
575
+ if (isNaN(num))
576
+ num = 2;
577
+ const pType = pluralType === "auto" ? String(term).endsWith("y") ? "-ies" : "-s" : pluralType;
578
+ switch (pType) {
579
+ case "-s":
580
+ return `${term}${num === 1 ? "" : "s"}`;
581
+ case "-ies":
582
+ return `${String(term).slice(0, -1)}${num === 1 ? "y" : "ies"}`;
583
+ }
584
+ }
585
+ function capitalize(text) {
586
+ return text.charAt(0).toUpperCase() + text.slice(1);
587
+ }
588
+ var defaultPbChars = {
589
+ 100: "\u2588",
590
+ 75: "\u2593",
591
+ 50: "\u2592",
592
+ 25: "\u2591",
593
+ 0: "\u2500"
594
+ };
595
+ function createProgressBar(percentage, barLength, chars = defaultPbChars) {
596
+ if (percentage === 100)
597
+ return chars[100].repeat(barLength);
598
+ const filledLength = Math.floor(percentage / 100 * barLength);
599
+ const remainingPercentage = percentage / 10 * barLength - filledLength;
600
+ let lastBlock = "";
601
+ if (remainingPercentage >= 0.75)
602
+ lastBlock = chars[75];
603
+ else if (remainingPercentage >= 0.5)
604
+ lastBlock = chars[50];
605
+ else if (remainingPercentage >= 0.25)
606
+ lastBlock = chars[25];
607
+ const filledBar = chars[100].repeat(filledLength);
608
+ const emptyBar = chars[0].repeat(barLength - filledLength - (lastBlock ? 1 : 0));
609
+ return `${filledBar}${lastBlock}${emptyBar}`;
610
+ }
611
+ function insertValues(input, ...values) {
612
+ return input.replace(/%\d/gm, (match) => {
613
+ var _a2;
614
+ var _a;
615
+ const argIndex = Number(match.substring(1)) - 1;
616
+ return (_a = (_a2 = values[argIndex]) != null ? _a2 : match) == null ? void 0 : _a.toString();
617
+ });
618
+ }
619
+ function joinArrayReadable(array, separators = ", ", lastSeparator = " and ") {
620
+ const arr = [...array];
621
+ if (arr.length === 0)
622
+ return "";
623
+ else if (arr.length === 1)
624
+ return String(arr[0]);
625
+ else if (arr.length === 2)
626
+ return arr.join(lastSeparator);
627
+ const lastItm = lastSeparator + arr[arr.length - 1];
628
+ arr.pop();
629
+ return arr.join(separators) + lastItm;
630
+ }
631
+ function secsToTimeStr(seconds) {
632
+ const isNegative = seconds < 0;
633
+ const s = Math.abs(seconds);
634
+ if (isNaN(s) || !isFinite(s))
635
+ throw new TypeError("The seconds argument must be a valid number");
636
+ const hrs = Math.floor(s / 3600);
637
+ const mins = Math.floor(s % 3600 / 60);
638
+ const secs = Math.floor(s % 60);
639
+ return (isNegative ? "-" : "") + [
640
+ hrs ? hrs + ":" : "",
641
+ String(mins).padStart(mins > 0 || hrs > 0 ? 2 : 1, "0"),
642
+ ":",
643
+ String(secs).padStart(secs > 0 || mins > 0 || hrs > 0 || seconds === 0 ? 2 : 1, "0")
644
+ ].join("");
645
+ }
646
+ function truncStr(input, length, endStr = "...") {
647
+ var _a;
648
+ const str = (_a = input == null ? void 0 : input.toString()) != null ? _a : String(input);
649
+ const finalStr = str.length > length ? str.substring(0, length - endStr.length) + endStr : str;
650
+ return finalStr.length > length ? finalStr.substring(0, length) : finalStr;
651
+ }
652
+ var dsFmtVer = 1;
653
+ var DataStore = class {
654
+ //#region constructor
655
+ /**
656
+ * Creates an instance of DataStore to manage a sync & async database that is cached in memory and persistently saved across sessions.
657
+ * Supports migrating data from older versions to newer ones and populating the cache with default data if no persistent data is found.
658
+ *
659
+ * - ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultData`
660
+ *
661
+ * @template TData The type of the data that is saved in persistent storage for the currently set format version (will be automatically inferred from `defaultData` if not provided) - **This has to be a JSON-compatible object!** (no undefined, circular references, etc.)
662
+ * @param opts The options for this DataStore instance
663
+ */
664
+ constructor(opts) {
665
+ __publicField(this, "id");
666
+ __publicField(this, "formatVersion");
667
+ __publicField(this, "defaultData");
668
+ __publicField(this, "encodeData");
669
+ __publicField(this, "decodeData");
670
+ __publicField(this, "compressionFormat", "deflate-raw");
671
+ __publicField(this, "memoryCache", true);
672
+ __publicField(this, "engine");
673
+ __publicField(this, "options");
674
+ /**
675
+ * Whether all first-init checks should be done.
676
+ * This includes migrating the internal DataStore format, migrating data from the UserUtils format, and anything similar.
677
+ * 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.
678
+ */
679
+ __publicField(this, "firstInit", true);
680
+ /** In-memory cached copy of the data that is saved in persistent storage used for synchronous read access. */
681
+ __publicField(this, "cachedData");
682
+ __publicField(this, "migrations");
683
+ __publicField(this, "migrateIds", []);
684
+ var _a2, _b, _c;
685
+ var _a;
686
+ this.id = opts.id;
687
+ this.formatVersion = opts.formatVersion;
688
+ this.defaultData = opts.defaultData;
689
+ this.memoryCache = Boolean((_a2 = opts.memoryCache) != null ? _a2 : true);
690
+ this.cachedData = this.memoryCache ? opts.defaultData : {};
691
+ this.migrations = opts.migrations;
692
+ if (opts.migrateIds)
693
+ this.migrateIds = Array.isArray(opts.migrateIds) ? opts.migrateIds : [opts.migrateIds];
694
+ this.encodeData = opts.encodeData;
695
+ this.decodeData = opts.decodeData;
696
+ this.engine = typeof opts.engine === "function" ? opts.engine() : opts.engine;
697
+ this.options = opts;
698
+ if (typeof opts.compressionFormat === "undefined")
699
+ this.compressionFormat = opts.compressionFormat = (_b = (_a = opts.encodeData) == null ? void 0 : _a[0]) != null ? _b : "deflate-raw";
700
+ if (typeof opts.compressionFormat === "string") {
701
+ this.encodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
702
+ return yield compress(data, opts.compressionFormat, "string");
703
+ })];
704
+ this.decodeData = [opts.compressionFormat, (data) => __async(this, null, function* () {
705
+ return yield compress(data, opts.compressionFormat, "string");
706
+ })];
707
+ } else if ("encodeData" in opts && "decodeData" in opts && Array.isArray(opts.encodeData) && Array.isArray(opts.decodeData)) {
708
+ this.encodeData = [opts.encodeData[0], opts.encodeData[1]];
709
+ this.decodeData = [opts.decodeData[0], opts.decodeData[1]];
710
+ this.compressionFormat = (_c = opts.encodeData[0]) != null ? _c : null;
711
+ } else if (opts.compressionFormat === null) {
712
+ this.encodeData = void 0;
713
+ this.decodeData = void 0;
714
+ this.compressionFormat = null;
715
+ } else
716
+ 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.");
717
+ this.engine.setDataStoreOptions(opts);
268
718
  }
269
- function fe(r, e, t = "string") {
719
+ //#region loadData
720
+ /**
721
+ * Loads the data saved in persistent storage into the in-memory cache and also returns a copy of it.
722
+ * Automatically populates persistent storage with default data if it doesn't contain any data yet.
723
+ * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
724
+ */
725
+ loadData() {
270
726
  return __async(this, null, function* () {
271
727
  var _a;
272
- let i = r instanceof Uint8Array ? r : W((_a = r == null ? void 0 : r.toString()) != null ? _a : String(r)), n = new DecompressionStream(e), o = n.writable.getWriter();
273
- o.write(i), o.close();
274
- let a = new Uint8Array(yield new Response(n.readable).arrayBuffer());
275
- return t === "arrayBuffer" ? a : new TextDecoder().decode(a);
728
+ try {
729
+ if (this.firstInit) {
730
+ this.firstInit = false;
731
+ const dsVer = Number(yield this.engine.getValue("__ds_fmt_ver", 0));
732
+ const oldData = yield this.engine.getValue(`_uucfg-${this.id}`, null);
733
+ if (oldData) {
734
+ const oldVer = Number(yield this.engine.getValue(`_uucfgver-${this.id}`, NaN));
735
+ const oldEnc = yield this.engine.getValue(`_uucfgenc-${this.id}`, null);
736
+ const promises = [];
737
+ const migrateFmt = (oldKey, newKey, value) => {
738
+ promises.push(this.engine.setValue(newKey, value));
739
+ promises.push(this.engine.deleteValue(oldKey));
740
+ };
741
+ migrateFmt(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, oldData);
742
+ if (!isNaN(oldVer))
743
+ migrateFmt(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, oldVer);
744
+ if (typeof oldEnc === "boolean")
745
+ migrateFmt(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, oldEnc === true ? (_a = this.compressionFormat) != null ? _a : null : null);
746
+ else {
747
+ promises.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat));
748
+ promises.push(this.engine.deleteValue(`_uucfgenc-${this.id}`));
749
+ }
750
+ yield Promise.allSettled(promises);
751
+ }
752
+ if (isNaN(dsVer) || dsVer < dsFmtVer)
753
+ yield this.engine.setValue("__ds_fmt_ver", dsFmtVer);
754
+ }
755
+ if (this.migrateIds.length > 0) {
756
+ yield this.migrateId(this.migrateIds);
757
+ this.migrateIds = [];
758
+ }
759
+ const storedDataRaw = yield this.engine.getValue(`__ds-${this.id}-dat`, null);
760
+ let storedFmtVer = Number(yield this.engine.getValue(`__ds-${this.id}-ver`, NaN));
761
+ if (typeof storedDataRaw !== "string") {
762
+ yield this.saveDefaultData();
763
+ return this.engine.deepCopy(this.defaultData);
764
+ }
765
+ const storedData = storedDataRaw != null ? storedDataRaw : JSON.stringify(this.defaultData);
766
+ const encodingFmt = String(yield this.engine.getValue(`__ds-${this.id}-enf`, null));
767
+ const isEncoded = encodingFmt !== "null" && encodingFmt !== "false";
768
+ let saveData = false;
769
+ if (isNaN(storedFmtVer)) {
770
+ yield this.engine.setValue(`__ds-${this.id}-ver`, storedFmtVer = this.formatVersion);
771
+ saveData = true;
772
+ }
773
+ let parsed = yield this.engine.deserializeData(storedData, isEncoded);
774
+ if (storedFmtVer < this.formatVersion && this.migrations)
775
+ parsed = yield this.runMigrations(parsed, storedFmtVer);
776
+ if (saveData)
777
+ yield this.setData(parsed);
778
+ if (this.memoryCache)
779
+ return this.cachedData = this.engine.deepCopy(parsed);
780
+ else
781
+ return this.engine.deepCopy(parsed);
782
+ } catch (err) {
783
+ console.warn("Error while parsing JSON data, resetting it to the default value.", err);
784
+ yield this.saveDefaultData();
785
+ return this.defaultData;
786
+ }
276
787
  });
277
788
  }
278
- function k(r, e = "SHA-256") {
789
+ //#region getData
790
+ /**
791
+ * Returns a copy of the data from the in-memory cache.
792
+ * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
793
+ * ⚠️ If `memoryCache` was set to `false` in the constructor options, this method will throw an error.
794
+ */
795
+ getData() {
796
+ if (!this.memoryCache)
797
+ throw new DatedError("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");
798
+ return this.engine.deepCopy(this.cachedData);
799
+ }
800
+ //#region setData
801
+ /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
802
+ setData(data) {
803
+ if (this.memoryCache)
804
+ this.cachedData = data;
805
+ return new Promise((resolve) => __async(this, null, function* () {
806
+ yield Promise.allSettled([
807
+ this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(data, this.encodingEnabled())),
808
+ this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
809
+ this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
810
+ ]);
811
+ resolve();
812
+ }));
813
+ }
814
+ //#region saveDefaultData
815
+ /** Saves the default data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
816
+ saveDefaultData() {
279
817
  return __async(this, null, function* () {
280
- let t;
281
- typeof r == "string" ? t = new TextEncoder().encode(r) : t = r;
282
- let i = yield crypto.subtle.digest(e, t);
283
- return Array.from(new Uint8Array(i)).map((a) => a.toString(16).padStart(2, "0")).join("");
818
+ if (this.memoryCache)
819
+ this.cachedData = this.defaultData;
820
+ yield Promise.allSettled([
821
+ this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(this.defaultData, this.encodingEnabled())),
822
+ this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion),
823
+ this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
824
+ ]);
284
825
  });
285
826
  }
286
- function he(r = 16, e = 16, t = false, i = true) {
287
- if (r < 1) throw new RangeError("The length argument must be at least 1");
288
- if (e < 2 || e > 36) throw new RangeError("The radix argument must be between 2 and 36");
289
- let n = [], o = i ? [0, 1] : [0];
290
- if (t) {
291
- let a = new Uint8Array(r);
292
- crypto.getRandomValues(a), n = Array.from(a, (s) => V(s, 0, 255, 0, e).toString(e).substring(0, 1));
293
- } else n = Array.from({ length: r }, () => Math.floor(Math.random() * e).toString(e));
294
- return n.some((a) => /[a-zA-Z]/.test(a)) ? n.map((a) => o[T(0, o.length - 1, t)] === 1 ? a.toUpperCase() : a).join("") : n.join("");
295
- }
296
- var d = class extends Error {
297
- constructor(e, t) {
298
- super(e, t);
299
- __publicField(this, "date");
300
- this.name = this.constructor.name, this.date = /* @__PURE__ */ new Date();
301
- }
302
- }, S = class extends d {
303
- constructor(e, t) {
304
- super(e, t), this.name = "ChecksumMismatchError";
305
- }
306
- }, v = class extends d {
307
- constructor(e, t, i) {
308
- super(t, i), this.name = e;
309
- }
310
- }, w = class extends d {
311
- constructor(e, t) {
312
- super(e, t), this.name = "MigrationError";
313
- }
314
- }, $ = class extends d {
315
- constructor(e, t) {
316
- super(e, t), this.name = "ValidationError";
317
- }
318
- }, g = class extends d {
319
- constructor(e, t) {
320
- super(e, t), this.name = "ScriptContextError";
321
- }
322
- }, x = class extends d {
323
- constructor(e, t) {
324
- super(e, t), this.name = "NetworkError";
325
- }
326
- };
327
- function ge(r) {
827
+ //#region deleteData
828
+ /**
829
+ * Call this method to clear all persistently stored data associated with this DataStore instance, including the storage container (if supported by the DataStoreEngine).
830
+ * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
831
+ * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
832
+ */
833
+ deleteData() {
328
834
  return __async(this, null, function* () {
329
- return yield typeof r == "function" ? r() : r;
835
+ var _a, _b;
836
+ yield Promise.allSettled([
837
+ this.engine.deleteValue(`__ds-${this.id}-dat`),
838
+ this.engine.deleteValue(`__ds-${this.id}-ver`),
839
+ this.engine.deleteValue(`__ds-${this.id}-enf`)
840
+ ]);
841
+ yield (_b = (_a = this.engine).deleteStorage) == null ? void 0 : _b.call(_a);
330
842
  });
331
843
  }
332
- function be(r) {
333
- return __async(this, null, function* () {
334
- return typeof r == "string" ? r : String(typeof r == "function" ? yield r() : r);
335
- });
844
+ //#region encodingEnabled
845
+ /** Returns whether encoding and decoding are enabled for this DataStore instance */
846
+ encodingEnabled() {
847
+ return Boolean(this.encodeData && this.decodeData) && this.compressionFormat !== null || Boolean(this.compressionFormat);
336
848
  }
337
- function ye(_0) {
338
- return __async(this, arguments, function* (r, e = {}) {
339
- let _a = e, { timeout: t = 1e4, signal: i } = _a, n = __objRest(_a, ["timeout", "signal"]), o = new AbortController();
340
- i == null || i.addEventListener("abort", () => o.abort());
341
- let a = {}, s;
342
- t >= 0 && (s = setTimeout(() => o.abort(), t), a = { signal: o.signal });
343
- try {
344
- let u = yield fetch(r, __spreadValues(__spreadValues({}, n), a));
345
- return typeof s < "u" && clearTimeout(s), u;
346
- } catch (u) {
347
- throw typeof s < "u" && clearTimeout(s), new x("Error while calling fetch", { cause: u });
849
+ //#region runMigrations
850
+ /**
851
+ * Runs all necessary migration functions consecutively and saves the result to the in-memory cache and persistent storage and also returns it.
852
+ * This method is automatically called by {@linkcode loadData()} if the data format has changed since the last time the data was saved.
853
+ * Though calling this method manually is not necessary, it can be useful if you want to run migrations for special occasions like a user importing potentially outdated data that has been previously exported.
854
+ *
855
+ * 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.
856
+ */
857
+ runMigrations(oldData, oldFmtVer, resetOnError = true) {
858
+ return __async(this, null, function* () {
859
+ if (!this.migrations)
860
+ return oldData;
861
+ let newData = oldData;
862
+ const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
863
+ let lastFmtVer = oldFmtVer;
864
+ for (const [fmtVer, migrationFunc] of sortedMigrations) {
865
+ const ver = Number(fmtVer);
866
+ if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
867
+ try {
868
+ const migRes = migrationFunc(newData);
869
+ newData = migRes instanceof Promise ? yield migRes : migRes;
870
+ lastFmtVer = oldFmtVer = ver;
871
+ } catch (err) {
872
+ if (!resetOnError)
873
+ throw new MigrationError(`Error while running migration function for format version '${fmtVer}'`, { cause: err });
874
+ yield this.saveDefaultData();
875
+ return this.getData();
876
+ }
877
+ }
348
878
  }
879
+ yield Promise.allSettled([
880
+ this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(newData)),
881
+ this.engine.setValue(`__ds-${this.id}-ver`, lastFmtVer),
882
+ this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)
883
+ ]);
884
+ if (this.memoryCache)
885
+ return this.cachedData = this.engine.deepCopy(newData);
886
+ else
887
+ return this.engine.deepCopy(newData);
349
888
  });
350
889
  }
351
- function De(r, e = true) {
352
- return "length" in r ? r.length : "size" in r ? r.size : "count" in r ? r.count : e ? 0 : NaN;
353
- }
354
- function Te(r, e, t = false) {
355
- return new Promise((i, n) => {
356
- let o = setTimeout(() => i(), r);
357
- e == null || e.addEventListener("abort", () => {
358
- clearTimeout(o), t ? n(new v("AbortError", "The pause was aborted")) : i();
359
- });
890
+ //#region migrateId
891
+ /**
892
+ * Tries to migrate the currently saved persistent data from one or more old IDs to the ID set in the constructor.
893
+ * 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.
894
+ */
895
+ migrateId(oldIds) {
896
+ return __async(this, null, function* () {
897
+ const ids = Array.isArray(oldIds) ? oldIds : [oldIds];
898
+ yield Promise.all(ids.map((id) => __async(this, null, function* () {
899
+ const [data, fmtVer, isEncoded] = yield (() => __async(this, null, function* () {
900
+ const [d, f, e] = yield Promise.all([
901
+ this.engine.getValue(`__ds-${id}-dat`, JSON.stringify(this.defaultData)),
902
+ this.engine.getValue(`__ds-${id}-ver`, NaN),
903
+ this.engine.getValue(`__ds-${id}-enf`, null)
904
+ ]);
905
+ return [d, Number(f), Boolean(e) && String(e) !== "null"];
906
+ }))();
907
+ if (data === void 0 || isNaN(fmtVer))
908
+ return;
909
+ const parsed = yield this.engine.deserializeData(data, isEncoded);
910
+ yield Promise.allSettled([
911
+ this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(parsed)),
912
+ this.engine.setValue(`__ds-${this.id}-ver`, fmtVer),
913
+ this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat),
914
+ this.engine.deleteValue(`__ds-${id}-dat`),
915
+ this.engine.deleteValue(`__ds-${id}-ver`),
916
+ this.engine.deleteValue(`__ds-${id}-enf`)
917
+ ]);
918
+ })));
360
919
  });
361
920
  }
362
- function Se(r) {
363
- return Object.assign(/* @__PURE__ */ Object.create(null), r != null ? r : {});
921
+ };
922
+ var DataStoreEngine = class {
923
+ // setDataStoreOptions() is called from inside the DataStore constructor to set this value
924
+ constructor(options) {
925
+ __publicField(this, "dataStoreOptions");
926
+ if (options)
927
+ this.dataStoreOptions = options;
364
928
  }
365
- function ve(r, e, t) {
366
- let i, n = () => clearInterval(i), o = () => {
367
- if (t != null && t.aborted) return n();
368
- r();
369
- };
370
- t == null || t.addEventListener("abort", n), o(), i = setInterval(o, e);
929
+ /** Called by DataStore on creation, to pass its options. Only call this if you are using this instance standalone! */
930
+ setDataStoreOptions(dataStoreOptions) {
931
+ this.dataStoreOptions = dataStoreOptions;
371
932
  }
372
- function we(r, e, t) {
373
- let i, n = () => clearTimeout(i), o = () => __async(null, null, function* () {
374
- if (t != null && t.aborted) return n();
375
- yield r(), i = setTimeout(o, e);
933
+ //#region serialization api
934
+ /** 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 */
935
+ serializeData(data, useEncoding) {
936
+ return __async(this, null, function* () {
937
+ var _a, _b, _c, _d, _e;
938
+ this.ensureDataStoreOptions();
939
+ const stringData = JSON.stringify(data);
940
+ if (!useEncoding || !((_a = this.dataStoreOptions) == null ? void 0 : _a.encodeData) || !((_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData))
941
+ return stringData;
942
+ const encRes = (_e = (_d = (_c = this.dataStoreOptions) == null ? void 0 : _c.encodeData) == null ? void 0 : _d[1]) == null ? void 0 : _e.call(_d, stringData);
943
+ if (encRes instanceof Promise)
944
+ return yield encRes;
945
+ return encRes;
376
946
  });
377
- t == null || t.addEventListener("abort", n), o();
378
947
  }
379
- function xe(r = 0, e = 0) {
380
- if (e < 0) throw new TypeError("Timeout must be a non-negative number");
381
- let t;
382
- if (typeof process < "u" && "exit" in process && typeof process.exit == "function") t = () => process.exit(r);
383
- else if (typeof Deno < "u" && "exit" in Deno && typeof Deno.exit == "function") t = () => Deno.exit(r);
384
- else throw new g("Cannot exit the process, no exit method available");
385
- setTimeout(t, e);
948
+ /** Deserializes the given string to a JSON object, optionally decoded with `options.decodeData` if {@linkcode useEncoding} is set to true */
949
+ deserializeData(data, useEncoding) {
950
+ return __async(this, null, function* () {
951
+ var _a, _b, _c;
952
+ this.ensureDataStoreOptions();
953
+ 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;
954
+ if (decRes instanceof Promise)
955
+ decRes = yield decRes;
956
+ return JSON.parse(decRes != null ? decRes : data);
957
+ });
386
958
  }
387
- function Ee(r, e = 1 / 0) {
388
- var _a;
389
- if (typeof e != "number" || isNaN(e) || e < 0) throw new TypeError("lines parameter must be a non-negative number");
959
+ //#region misc api
960
+ /** Throws an error if the DataStoreOptions are not set or invalid */
961
+ ensureDataStoreOptions() {
962
+ if (!this.dataStoreOptions)
963
+ throw new DatedError("DataStoreEngine must be initialized with DataStore options before use. If you are using this instance standalone, set them in the constructor or call `setDataStoreOptions()` with the DataStore options.");
964
+ if (!this.dataStoreOptions.id)
965
+ throw new DatedError("DataStoreEngine must be initialized with a valid DataStore ID");
966
+ }
967
+ /**
968
+ * Copies a JSON-compatible object and loses all its internal references in the process.
969
+ * Uses [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) if available, otherwise falls back to `JSON.parse(JSON.stringify(obj))`.
970
+ */
971
+ deepCopy(obj) {
390
972
  try {
391
- throw new Error("This is to capture a stack trace with CoreUtils.getCallStack(). (If you see this somewhere, you can safely ignore it.)");
392
- } catch (t) {
393
- let i = ((_a = t.stack) != null ? _a : "").split(`
394
- `).map((n) => n.trim()).slice(2, e + 2);
395
- return r !== false ? i : i.join(`
396
- `);
973
+ if ("structuredClone" in globalThis)
974
+ return structuredClone(obj);
975
+ } catch (e) {
397
976
  }
977
+ return JSON.parse(JSON.stringify(obj));
398
978
  }
399
- function Pe(r, e, t = "auto") {
400
- switch (typeof e != "number" && ("length" in e ? e = e.length : "size" in e ? e = e.size : "count" in e && (e = e.count)), ["-s", "-ies"].includes(t) || (t = "auto"), isNaN(e) && (e = 2), t === "auto" ? String(r).endsWith("y") ? "-ies" : "-s" : t) {
401
- case "-s":
402
- return `${r}${e === 1 ? "" : "s"}`;
403
- case "-ies":
404
- return `${String(r).slice(0, -1)}${e === 1 ? "y" : "ies"}`;
405
- }
979
+ };
980
+ var BrowserStorageEngine = class extends DataStoreEngine {
981
+ /**
982
+ * Creates an instance of `BrowserStorageEngine`.
983
+ *
984
+ * - ⚠️ Requires a DOM environment
985
+ * - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
986
+ */
987
+ constructor(options) {
988
+ super(options == null ? void 0 : options.dataStoreOptions);
989
+ __publicField(this, "options");
990
+ this.options = __spreadValues({
991
+ type: "localStorage"
992
+ }, options);
406
993
  }
407
- function Oe(r) {
408
- return r.charAt(0).toUpperCase() + r.slice(1);
994
+ //#region storage api
995
+ /** Fetches a value from persistent storage */
996
+ getValue(name, defaultValue) {
997
+ return __async(this, null, function* () {
998
+ const val = this.options.type === "localStorage" ? globalThis.localStorage.getItem(name) : globalThis.sessionStorage.getItem(name);
999
+ return typeof val === "undefined" ? defaultValue : val;
1000
+ });
409
1001
  }
410
- var Q = { 100: "\u2588", 75: "\u2593", 50: "\u2592", 25: "\u2591", 0: "\u2500" };
411
- function Fe(r, e, t = Q) {
412
- if (r === 100) return t[100].repeat(e);
413
- let i = Math.floor(r / 100 * e), n = r / 10 * e - i, o = "";
414
- n >= 0.75 ? o = t[75] : n >= 0.5 ? o = t[50] : n >= 0.25 && (o = t[25]);
415
- let a = t[100].repeat(i), s = t[0].repeat(e - i - (o ? 1 : 0));
416
- return `${a}${o}${s}`;
1002
+ /** Sets a value in persistent storage */
1003
+ setValue(name, value) {
1004
+ return __async(this, null, function* () {
1005
+ if (this.options.type === "localStorage")
1006
+ globalThis.localStorage.setItem(name, String(value));
1007
+ else
1008
+ globalThis.sessionStorage.setItem(name, String(value));
1009
+ });
417
1010
  }
418
- function Ve(r, ...e) {
419
- return r.replace(/%\d/gm, (t) => {
420
- var _a;
421
- var n;
422
- let i = Number(t.substring(1)) - 1;
423
- return (n = (_a = e[i]) != null ? _a : t) == null ? void 0 : n.toString();
1011
+ /** Deletes a value from persistent storage */
1012
+ deleteValue(name) {
1013
+ return __async(this, null, function* () {
1014
+ if (this.options.type === "localStorage")
1015
+ globalThis.localStorage.removeItem(name);
1016
+ else
1017
+ globalThis.sessionStorage.removeItem(name);
424
1018
  });
425
1019
  }
426
- function Ne(r, e = ", ", t = " and ") {
427
- let i = [...r];
428
- if (i.length === 0) return "";
429
- if (i.length === 1) return String(i[0]);
430
- if (i.length === 2) return i.join(t);
431
- let n = t + i[i.length - 1];
432
- return i.pop(), i.join(e) + n;
433
- }
434
- function Ae(r) {
435
- let e = r < 0, t = Math.abs(r);
436
- if (isNaN(t) || !isFinite(t)) throw new TypeError("The seconds argument must be a valid number");
437
- let i = Math.floor(t / 3600), n = Math.floor(t % 3600 / 60), o = Math.floor(t % 60);
438
- return (e ? "-" : "") + [i ? i + ":" : "", String(n).padStart(n > 0 || i > 0 ? 2 : 1, "0"), ":", String(o).padStart(o > 0 || n > 0 || i > 0 || r === 0 ? 2 : 1, "0")].join("");
439
- }
440
- function Me(r, e, t = "...") {
441
- var _a;
442
- let i = (_a = r == null ? void 0 : r.toString()) != null ? _a : String(r), n = i.length > e ? i.substring(0, e - t.length) + t : i;
443
- return n.length > e ? n.substring(0, e) : n;
444
- }
445
- var G = 1, z = class {
446
- constructor(e) {
447
- __publicField(this, "id");
448
- __publicField(this, "formatVersion");
449
- __publicField(this, "defaultData");
450
- __publicField(this, "encodeData");
451
- __publicField(this, "decodeData");
452
- __publicField(this, "compressionFormat", "deflate-raw");
453
- __publicField(this, "memoryCache", true);
454
- __publicField(this, "engine");
455
- __publicField(this, "options");
456
- __publicField(this, "firstInit", true);
457
- __publicField(this, "cachedData");
458
- __publicField(this, "migrations");
459
- __publicField(this, "migrateIds", []);
460
- var _a, _b, _c;
461
- var t;
462
- if (this.id = e.id, this.formatVersion = e.formatVersion, this.defaultData = e.defaultData, this.memoryCache = !!((_a = e.memoryCache) != null ? _a : true), this.cachedData = this.memoryCache ? e.defaultData : {}, this.migrations = e.migrations, e.migrateIds && (this.migrateIds = Array.isArray(e.migrateIds) ? e.migrateIds : [e.migrateIds]), this.encodeData = e.encodeData, this.decodeData = e.decodeData, this.engine = typeof e.engine == "function" ? e.engine() : e.engine, this.options = e, typeof e.compressionFormat > "u" && (this.compressionFormat = e.compressionFormat = (_b = (t = e.encodeData) == null ? void 0 : t[0]) != null ? _b : "deflate-raw"), typeof e.compressionFormat == "string") this.encodeData = [e.compressionFormat, (i) => __async(this, null, function* () {
463
- return yield N(i, e.compressionFormat, "string");
464
- })], this.decodeData = [e.compressionFormat, (i) => __async(this, null, function* () {
465
- return yield N(i, e.compressionFormat, "string");
466
- })];
467
- else if ("encodeData" in e && "decodeData" in e && Array.isArray(e.encodeData) && Array.isArray(e.decodeData)) this.encodeData = [e.encodeData[0], e.encodeData[1]], this.decodeData = [e.decodeData[0], e.decodeData[1]], this.compressionFormat = (_c = e.encodeData[0]) != null ? _c : null;
468
- else if (e.compressionFormat === null) this.encodeData = void 0, this.decodeData = void 0, this.compressionFormat = null;
469
- else 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.");
470
- this.engine.setDataStoreOptions(e);
471
- }
472
- loadData() {
473
- return __async(this, null, function* () {
474
- var _a;
475
- try {
476
- if (this.firstInit) {
477
- this.firstInit = false;
478
- let u = Number(yield this.engine.getValue("__ds_fmt_ver", 0)), l = yield this.engine.getValue(`_uucfg-${this.id}`, null);
479
- if (l) {
480
- let c = Number(yield this.engine.getValue(`_uucfgver-${this.id}`, NaN)), p = yield this.engine.getValue(`_uucfgenc-${this.id}`, null), m = [], b = (O, h, y) => {
481
- m.push(this.engine.setValue(h, y)), m.push(this.engine.deleteValue(O));
482
- };
483
- b(`_uucfg-${this.id}`, `__ds-${this.id}-dat`, l), isNaN(c) || b(`_uucfgver-${this.id}`, `__ds-${this.id}-ver`, c), typeof p == "boolean" ? b(`_uucfgenc-${this.id}`, `__ds-${this.id}-enf`, p === true ? (_a = this.compressionFormat) != null ? _a : null : null) : (m.push(this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)), m.push(this.engine.deleteValue(`_uucfgenc-${this.id}`))), yield Promise.allSettled(m);
484
- }
485
- (isNaN(u) || u < G) && (yield this.engine.setValue("__ds_fmt_ver", G));
486
- }
487
- this.migrateIds.length > 0 && (yield this.migrateId(this.migrateIds), this.migrateIds = []);
488
- let e = yield this.engine.getValue(`__ds-${this.id}-dat`, null), t = Number(yield this.engine.getValue(`__ds-${this.id}-ver`, NaN));
489
- if (typeof e != "string") return yield this.saveDefaultData(), this.engine.deepCopy(this.defaultData);
490
- let i = e != null ? e : JSON.stringify(this.defaultData), n = String(yield this.engine.getValue(`__ds-${this.id}-enf`, null)), o = n !== "null" && n !== "false", a = false;
491
- isNaN(t) && (yield this.engine.setValue(`__ds-${this.id}-ver`, t = this.formatVersion), a = true);
492
- let s = yield this.engine.deserializeData(i, o);
493
- return t < this.formatVersion && this.migrations && (s = yield this.runMigrations(s, t)), a && (yield this.setData(s)), this.memoryCache ? this.cachedData = this.engine.deepCopy(s) : this.engine.deepCopy(s);
494
- } catch (e) {
495
- return console.warn("Error while parsing JSON data, resetting it to the default value.", e), yield this.saveDefaultData(), this.defaultData;
496
- }
497
- });
498
- }
499
- getData() {
500
- if (!this.memoryCache) throw new d("In-memory cache is disabled for this DataStore instance, so getData() can't be used. Please use loadData() instead.");
501
- return this.engine.deepCopy(this.cachedData);
502
- }
503
- setData(e) {
504
- return this.memoryCache && (this.cachedData = e), new Promise((t) => __async(this, null, function* () {
505
- yield Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(e, this.encodingEnabled())), this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion), this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)]), t();
506
- }));
507
- }
508
- saveDefaultData() {
509
- return __async(this, null, function* () {
510
- this.memoryCache && (this.cachedData = this.defaultData), yield Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(this.defaultData, this.encodingEnabled())), this.engine.setValue(`__ds-${this.id}-ver`, this.formatVersion), this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)]);
511
- });
512
- }
513
- deleteData() {
514
- return __async(this, null, function* () {
515
- var e, t;
516
- yield Promise.allSettled([this.engine.deleteValue(`__ds-${this.id}-dat`), this.engine.deleteValue(`__ds-${this.id}-ver`), this.engine.deleteValue(`__ds-${this.id}-enf`)]), yield (t = (e = this.engine).deleteStorage) == null ? void 0 : t.call(e);
517
- });
518
- }
519
- encodingEnabled() {
520
- return !!(this.encodeData && this.decodeData) && this.compressionFormat !== null || !!this.compressionFormat;
521
- }
522
- runMigrations(e, t, i = true) {
523
- return __async(this, null, function* () {
524
- if (!this.migrations) return e;
525
- let n = e, o = Object.entries(this.migrations).sort(([s], [u]) => Number(s) - Number(u)), a = t;
526
- for (let [s, u] of o) {
527
- let l = Number(s);
528
- if (t < this.formatVersion && t < l) try {
529
- let c = u(n);
530
- n = c instanceof Promise ? yield c : c, a = t = l;
531
- } catch (c) {
532
- if (!i) throw new w(`Error while running migration function for format version '${s}'`, { cause: c });
533
- return yield this.saveDefaultData(), this.getData();
534
- }
535
- }
536
- return yield Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(n)), this.engine.setValue(`__ds-${this.id}-ver`, a), this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat)]), this.memoryCache ? this.cachedData = this.engine.deepCopy(n) : this.engine.deepCopy(n);
537
- });
538
- }
539
- migrateId(e) {
540
- return __async(this, null, function* () {
541
- let t = Array.isArray(e) ? e : [e];
542
- yield Promise.all(t.map((i) => __async(this, null, function* () {
543
- let [n, o, a] = yield (() => __async(this, null, function* () {
544
- let [u, l, c] = yield Promise.all([this.engine.getValue(`__ds-${i}-dat`, JSON.stringify(this.defaultData)), this.engine.getValue(`__ds-${i}-ver`, NaN), this.engine.getValue(`__ds-${i}-enf`, null)]);
545
- return [u, Number(l), !!c && String(c) !== "null"];
546
- }))();
547
- if (n === void 0 || isNaN(o)) return;
548
- let s = yield this.engine.deserializeData(n, a);
549
- yield Promise.allSettled([this.engine.setValue(`__ds-${this.id}-dat`, yield this.engine.serializeData(s)), this.engine.setValue(`__ds-${this.id}-ver`, o), this.engine.setValue(`__ds-${this.id}-enf`, this.compressionFormat), this.engine.deleteValue(`__ds-${i}-dat`), this.engine.deleteValue(`__ds-${i}-ver`), this.engine.deleteValue(`__ds-${i}-enf`)]);
550
- })));
551
- });
552
- }
553
- };
554
- var E = class {
555
- constructor(e) {
556
- __publicField(this, "dataStoreOptions");
557
- e && (this.dataStoreOptions = e);
558
- }
559
- setDataStoreOptions(e) {
560
- this.dataStoreOptions = e;
561
- }
562
- serializeData(e, t) {
563
- return __async(this, null, function* () {
564
- var o, a, s, u, l;
565
- this.ensureDataStoreOptions();
566
- let i = JSON.stringify(e);
567
- if (!t || !((o = this.dataStoreOptions) != null && o.encodeData) || !((a = this.dataStoreOptions) != null && a.decodeData)) return i;
568
- let n = (l = (u = (s = this.dataStoreOptions) == null ? void 0 : s.encodeData) == null ? void 0 : u[1]) == null ? void 0 : l.call(u, i);
569
- return n instanceof Promise ? yield n : n;
570
- });
571
- }
572
- deserializeData(e, t) {
573
- return __async(this, null, function* () {
574
- var n, o, a;
575
- this.ensureDataStoreOptions();
576
- let i = (n = this.dataStoreOptions) != null && n.decodeData && t ? (a = (o = this.dataStoreOptions.decodeData) == null ? void 0 : o[1]) == null ? void 0 : a.call(o, e) : void 0;
577
- return i instanceof Promise && (i = yield i), JSON.parse(i != null ? i : e);
578
- });
579
- }
580
- ensureDataStoreOptions() {
581
- if (!this.dataStoreOptions) throw new d("DataStoreEngine must be initialized with DataStore options before use. If you are using this instance standalone, set them in the constructor or call `setDataStoreOptions()` with the DataStore options.");
582
- if (!this.dataStoreOptions.id) throw new d("DataStoreEngine must be initialized with a valid DataStore ID");
583
- }
584
- deepCopy(e) {
1020
+ };
1021
+ var fs;
1022
+ var FileStorageEngine = class extends DataStoreEngine {
1023
+ /**
1024
+ * Creates an instance of `FileStorageEngine`.
1025
+ *
1026
+ * - ⚠️ Requires Node.js or Deno with Node compatibility (v1.31+)
1027
+ * - ⚠️ Don't reuse engine instances, always create a new one for each {@linkcode DataStore} instance
1028
+ */
1029
+ constructor(options) {
1030
+ super(options == null ? void 0 : options.dataStoreOptions);
1031
+ __publicField(this, "options");
1032
+ __publicField(this, "fileAccessQueue", Promise.resolve());
1033
+ this.options = __spreadValues({
1034
+ filePath: (id) => `.ds-${id}`
1035
+ }, options);
1036
+ }
1037
+ //#region json file
1038
+ /** Reads the file contents */
1039
+ readFile() {
1040
+ return __async(this, null, function* () {
1041
+ var _a2;
1042
+ var _a, _b, _c, _d;
1043
+ this.ensureDataStoreOptions();
585
1044
  try {
586
- if ("structuredClone" in globalThis) return structuredClone(e);
587
- } catch (e2) {
1045
+ if (!fs)
1046
+ fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
1047
+ if (!fs)
1048
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1049
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
1050
+ const data = yield fs.readFile(path, "utf-8");
1051
+ return data ? JSON.parse((_a2 = yield (_d = (_c = (_b = this.dataStoreOptions) == null ? void 0 : _b.decodeData) == null ? void 0 : _c[1]) == null ? void 0 : _d.call(_c, data)) != null ? _a2 : data) : void 0;
1052
+ } catch (e) {
1053
+ return void 0;
588
1054
  }
589
- return JSON.parse(JSON.stringify(e));
590
- }
591
- }, U = class extends E {
592
- constructor(e) {
593
- super(e == null ? void 0 : e.dataStoreOptions);
594
- __publicField(this, "options");
595
- this.options = __spreadValues({ type: "localStorage" }, e);
596
- }
597
- getValue(e, t) {
598
- return __async(this, null, function* () {
599
- let i = this.options.type === "localStorage" ? globalThis.localStorage.getItem(e) : globalThis.sessionStorage.getItem(e);
600
- return typeof i > "u" ? t : i;
601
- });
602
- }
603
- setValue(e, t) {
604
- return __async(this, null, function* () {
605
- this.options.type === "localStorage" ? globalThis.localStorage.setItem(e, String(t)) : globalThis.sessionStorage.setItem(e, String(t));
1055
+ });
1056
+ }
1057
+ /** Overwrites the file contents */
1058
+ writeFile(data) {
1059
+ return __async(this, null, function* () {
1060
+ var _a2;
1061
+ var _a, _b, _c, _d;
1062
+ this.ensureDataStoreOptions();
1063
+ try {
1064
+ if (!fs)
1065
+ fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
1066
+ if (!fs)
1067
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1068
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
1069
+ yield fs.mkdir(path.slice(0, path.lastIndexOf(path.includes("/") ? "/" : "\\")), { recursive: true });
1070
+ yield fs.writeFile(path, (_a2 = 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 ? _a2 : JSON.stringify(data, void 0, 2), "utf-8");
1071
+ } catch (err) {
1072
+ console.error("Error writing file:", err);
1073
+ }
1074
+ });
1075
+ }
1076
+ //#region storage api
1077
+ /** Fetches a value from persistent storage */
1078
+ getValue(name, defaultValue) {
1079
+ return __async(this, null, function* () {
1080
+ const data = yield this.readFile();
1081
+ if (!data)
1082
+ return defaultValue;
1083
+ const value = data == null ? void 0 : data[name];
1084
+ if (typeof value === "undefined")
1085
+ return defaultValue;
1086
+ if (typeof value === "string")
1087
+ return value;
1088
+ return value;
1089
+ });
1090
+ }
1091
+ /** Sets a value in persistent storage */
1092
+ setValue(name, value) {
1093
+ return __async(this, null, function* () {
1094
+ this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
1095
+ let data = yield this.readFile();
1096
+ if (!data)
1097
+ data = {};
1098
+ data[name] = value;
1099
+ yield this.writeFile(data);
1100
+ })).catch((err) => {
1101
+ console.error("Error in setValue:", err);
1102
+ throw err;
606
1103
  });
607
- }
608
- deleteValue(e) {
609
- return __async(this, null, function* () {
610
- this.options.type === "localStorage" ? globalThis.localStorage.removeItem(e) : globalThis.sessionStorage.removeItem(e);
1104
+ yield this.fileAccessQueue.catch(() => {
611
1105
  });
612
- }
613
- }, f, R = class extends E {
614
- constructor(e) {
615
- super(e == null ? void 0 : e.dataStoreOptions);
616
- __publicField(this, "options");
617
- __publicField(this, "fileAccessQueue", Promise.resolve());
618
- this.options = __spreadValues({ filePath: (t) => `.ds-${t}` }, e);
619
- }
620
- readFile() {
621
- return __async(this, null, function* () {
622
- var _a;
623
- var e, t, i, n;
624
- this.ensureDataStoreOptions();
625
- try {
626
- if (f || (f = (e = yield import("fs/promises")) == null ? void 0 : e.default), !f) throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new d("'node:fs/promises' module not available") });
627
- let o = typeof this.options.filePath == "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id), a = yield f.readFile(o, "utf-8");
628
- return a ? JSON.parse((_a = yield (n = (i = (t = this.dataStoreOptions) == null ? void 0 : t.decodeData) == null ? void 0 : i[1]) == null ? void 0 : n.call(i, a)) != null ? _a : a) : void 0;
629
- } catch (e2) {
1106
+ });
1107
+ }
1108
+ /** Deletes a value from persistent storage */
1109
+ deleteValue(name) {
1110
+ return __async(this, null, function* () {
1111
+ this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
1112
+ const data = yield this.readFile();
1113
+ if (!data)
630
1114
  return;
631
- }
632
- });
633
- }
634
- writeFile(e) {
635
- return __async(this, null, function* () {
636
- var _a;
637
- var t, i, n, o;
638
- this.ensureDataStoreOptions();
639
- try {
640
- if (f || (f = (t = yield import("fs/promises")) == null ? void 0 : t.default), !f) throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new d("'node:fs/promises' module not available") });
641
- let a = typeof this.options.filePath == "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
642
- yield f.mkdir(a.slice(0, a.lastIndexOf(a.includes("/") ? "/" : "\\")), { recursive: true }), yield f.writeFile(a, (_a = yield (o = (n = (i = this.dataStoreOptions) == null ? void 0 : i.encodeData) == null ? void 0 : n[1]) == null ? void 0 : o.call(n, JSON.stringify(e))) != null ? _a : JSON.stringify(e, void 0, 2), "utf-8");
643
- } catch (a) {
644
- console.error("Error writing file:", a);
645
- }
1115
+ delete data[name];
1116
+ yield this.writeFile(data);
1117
+ })).catch((err) => {
1118
+ console.error("Error in deleteValue:", err);
1119
+ throw err;
646
1120
  });
647
- }
648
- getValue(e, t) {
649
- return __async(this, null, function* () {
650
- let i = yield this.readFile();
651
- if (!i) return t;
652
- let n = i == null ? void 0 : i[e];
653
- return typeof n > "u" ? t : n;
1121
+ yield this.fileAccessQueue.catch(() => {
654
1122
  });
655
- }
656
- setValue(e, t) {
657
- return __async(this, null, function* () {
658
- this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
659
- let i = yield this.readFile();
660
- i || (i = {}), i[e] = t, yield this.writeFile(i);
661
- })).catch((i) => {
662
- throw console.error("Error in setValue:", i), i;
663
- }), yield this.fileAccessQueue.catch(() => {
664
- });
665
- });
666
- }
667
- deleteValue(e) {
668
- return __async(this, null, function* () {
669
- this.fileAccessQueue = this.fileAccessQueue.then(() => __async(this, null, function* () {
670
- let t = yield this.readFile();
671
- t && (delete t[e], yield this.writeFile(t));
672
- })).catch((t) => {
673
- throw console.error("Error in deleteValue:", t), t;
674
- }), yield this.fileAccessQueue.catch(() => {
1123
+ });
1124
+ }
1125
+ /** Deletes the file that contains the data of this DataStore. */
1126
+ deleteStorage() {
1127
+ return __async(this, null, function* () {
1128
+ var _a;
1129
+ this.ensureDataStoreOptions();
1130
+ try {
1131
+ if (!fs)
1132
+ fs = (_a = yield import("fs/promises")) == null ? void 0 : _a.default;
1133
+ if (!fs)
1134
+ throw new ScriptContextError("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new DatedError("'node:fs/promises' module not available") });
1135
+ const path = typeof this.options.filePath === "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
1136
+ return yield fs.unlink(path);
1137
+ } catch (err) {
1138
+ console.error("Error deleting file:", err);
1139
+ }
1140
+ });
1141
+ }
1142
+ };
1143
+ var DataStoreSerializer = class _DataStoreSerializer {
1144
+ constructor(stores, options = {}) {
1145
+ __publicField(this, "stores");
1146
+ __publicField(this, "options");
1147
+ if (!crypto || !crypto.subtle)
1148
+ throw new ScriptContextError("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
1149
+ this.stores = stores;
1150
+ this.options = __spreadValues({
1151
+ addChecksum: true,
1152
+ ensureIntegrity: true,
1153
+ remapIds: {}
1154
+ }, options);
1155
+ }
1156
+ /** Calculates the checksum of a string */
1157
+ calcChecksum(input) {
1158
+ return __async(this, null, function* () {
1159
+ return computeHash(input, "SHA-256");
1160
+ });
1161
+ }
1162
+ /**
1163
+ * Serializes only a subset of the data stores into a string.
1164
+ * @param stores An array of store IDs or functions that take a store ID and return a boolean
1165
+ * @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
1166
+ * @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
1167
+ */
1168
+ serializePartial(stores, useEncoding = true, stringified = true) {
1169
+ return __async(this, null, function* () {
1170
+ var _a;
1171
+ const serData = [];
1172
+ const filteredStores = this.stores.filter((s) => typeof stores === "function" ? stores(s.id) : stores.includes(s.id));
1173
+ for (const storeInst of filteredStores) {
1174
+ const encoded = Boolean(useEncoding && storeInst.encodingEnabled() && ((_a = storeInst.encodeData) == null ? void 0 : _a[1]));
1175
+ const rawData = storeInst.memoryCache ? storeInst.getData() : yield storeInst.loadData();
1176
+ const data = encoded ? yield storeInst.encodeData[1](JSON.stringify(rawData)) : JSON.stringify(rawData);
1177
+ serData.push({
1178
+ id: storeInst.id,
1179
+ data,
1180
+ formatVersion: storeInst.formatVersion,
1181
+ encoded,
1182
+ checksum: this.options.addChecksum ? yield this.calcChecksum(data) : void 0
675
1183
  });
676
- });
677
- }
678
- deleteStorage() {
679
- return __async(this, null, function* () {
680
- var e;
681
- this.ensureDataStoreOptions();
682
- try {
683
- if (f || (f = (e = yield import("fs/promises")) == null ? void 0 : e.default), !f) throw new g("FileStorageEngine requires Node.js or Deno with Node compatibility (v1.31+)", { cause: new d("'node:fs/promises' module not available") });
684
- let t = typeof this.options.filePath == "string" ? this.options.filePath : this.options.filePath(this.dataStoreOptions.id);
685
- return yield f.unlink(t);
686
- } catch (t) {
687
- console.error("Error deleting file:", t);
688
- }
689
- });
690
- }
691
- };
692
- var j = class r {
693
- constructor(e, t = {}) {
694
- __publicField(this, "stores");
695
- __publicField(this, "options");
696
- if (!crypto || !crypto.subtle) throw new g("DataStoreSerializer has to run in a secure context (HTTPS) or in another environment that implements the subtleCrypto API!");
697
- this.stores = e, this.options = __spreadValues({ addChecksum: true, ensureIntegrity: true, remapIds: {} }, t);
698
- }
699
- calcChecksum(e) {
700
- return __async(this, null, function* () {
701
- return k(e, "SHA-256");
702
- });
703
- }
704
- serializePartial(e, t = true, i = true) {
705
- return __async(this, null, function* () {
706
- var a;
707
- let n = [], o = this.stores.filter((s) => typeof e == "function" ? e(s.id) : e.includes(s.id));
708
- for (let s of o) {
709
- let u = !!(t && s.encodingEnabled() && ((a = s.encodeData) != null && a[1])), l = s.memoryCache ? s.getData() : yield s.loadData(), c = u ? yield s.encodeData[1](JSON.stringify(l)) : JSON.stringify(l);
710
- n.push({ id: s.id, data: c, formatVersion: s.formatVersion, encoded: u, checksum: this.options.addChecksum ? yield this.calcChecksum(c) : void 0 });
711
- }
712
- return i ? JSON.stringify(n) : n;
713
- });
714
- }
715
- serialize(e = true, t = true) {
716
- return __async(this, null, function* () {
717
- return this.serializePartial(this.stores.map((i) => i.id), e, t);
718
- });
719
- }
720
- deserializePartial(e, t) {
721
- return __async(this, null, function* () {
722
- let i = typeof t == "string" ? JSON.parse(t) : t;
723
- if (!Array.isArray(i) || !i.every(r.isSerializedDataStoreObj)) throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
724
- let n = (a) => {
725
- var _a;
726
- var s;
727
- return (_a = (s = Object.entries(this.options.remapIds).find(([, u]) => u.includes(a))) == null ? void 0 : s[0]) != null ? _a : a;
728
- }, o = (a) => typeof e == "function" ? e(a) : e.includes(a);
729
- for (let a of i) {
730
- let s = n(a.id);
731
- if (!o(s)) continue;
732
- let u = this.stores.find((c) => c.id === s);
733
- if (!u) throw new d(`Can't deserialize data because no DataStore instance with the ID "${s}" was found! Make sure to provide it in the DataStoreSerializer constructor.`);
734
- if (this.options.ensureIntegrity && typeof a.checksum == "string") {
735
- let c = yield this.calcChecksum(a.data);
736
- if (c !== a.checksum) throw new S(`Checksum mismatch for DataStore with ID "${a.id}"!
737
- Expected: ${a.checksum}
738
- Has: ${c}`);
739
- }
740
- let l = a.encoded && u.encodingEnabled() ? yield u.decodeData[1](a.data) : a.data;
741
- a.formatVersion && !isNaN(Number(a.formatVersion)) && Number(a.formatVersion) < u.formatVersion ? yield u.runMigrations(JSON.parse(l), Number(a.formatVersion), false) : yield u.setData(JSON.parse(l));
1184
+ }
1185
+ return stringified ? JSON.stringify(serData) : serData;
1186
+ });
1187
+ }
1188
+ /**
1189
+ * Serializes the data stores into a string.
1190
+ * @param useEncoding Whether to encode the data using each DataStore's `encodeData()` method
1191
+ * @param stringified Whether to return the result as a string or as an array of `SerializedDataStore` objects
1192
+ */
1193
+ serialize(useEncoding = true, stringified = true) {
1194
+ return __async(this, null, function* () {
1195
+ return this.serializePartial(this.stores.map((s) => s.id), useEncoding, stringified);
1196
+ });
1197
+ }
1198
+ /**
1199
+ * Deserializes the data exported via {@linkcode serialize()} and imports only a subset into the DataStore instances.
1200
+ * Also triggers the migration process if the data format has changed.
1201
+ */
1202
+ deserializePartial(stores, data) {
1203
+ return __async(this, null, function* () {
1204
+ const deserStores = typeof data === "string" ? JSON.parse(data) : data;
1205
+ if (!Array.isArray(deserStores) || !deserStores.every(_DataStoreSerializer.isSerializedDataStoreObj))
1206
+ throw new TypeError("Invalid serialized data format! Expected an array of SerializedDataStore objects.");
1207
+ const resolveStoreId = (id) => {
1208
+ var _a2;
1209
+ var _a;
1210
+ return (_a2 = (_a = Object.entries(this.options.remapIds).find(([, v]) => v.includes(id))) == null ? void 0 : _a[0]) != null ? _a2 : id;
1211
+ };
1212
+ const matchesFilter = (id) => typeof stores === "function" ? stores(id) : stores.includes(id);
1213
+ for (const storeData of deserStores) {
1214
+ const effectiveId = resolveStoreId(storeData.id);
1215
+ if (!matchesFilter(effectiveId))
1216
+ continue;
1217
+ const storeInst = this.stores.find((s) => s.id === effectiveId);
1218
+ if (!storeInst)
1219
+ 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.`);
1220
+ if (this.options.ensureIntegrity && typeof storeData.checksum === "string") {
1221
+ const checksum = yield this.calcChecksum(storeData.data);
1222
+ if (checksum !== storeData.checksum)
1223
+ throw new ChecksumMismatchError(`Checksum mismatch for DataStore with ID "${storeData.id}"!
1224
+ Expected: ${storeData.checksum}
1225
+ Has: ${checksum}`);
742
1226
  }
743
- });
744
- }
745
- deserialize(e) {
746
- return __async(this, null, function* () {
747
- return this.deserializePartial(this.stores.map((t) => t.id), e);
748
- });
749
- }
750
- loadStoresData(e) {
751
- return __async(this, null, function* () {
752
- return Promise.allSettled(this.getStoresFiltered(e).map((t) => __async(this, null, function* () {
753
- return { id: t.id, data: yield t.loadData() };
754
- })));
755
- });
756
- }
757
- resetStoresData(e) {
758
- return __async(this, null, function* () {
759
- return Promise.allSettled(this.getStoresFiltered(e).map((t) => t.saveDefaultData()));
760
- });
761
- }
762
- deleteStoresData(e) {
763
- return __async(this, null, function* () {
764
- return Promise.allSettled(this.getStoresFiltered(e).map((t) => t.deleteData()));
765
- });
766
- }
767
- static isSerializedDataStoreObjArray(e) {
768
- return Array.isArray(e) && e.every((t) => typeof t == "object" && t !== null && "id" in t && "data" in t && "formatVersion" in t && "encoded" in t);
769
- }
770
- static isSerializedDataStoreObj(e) {
771
- return typeof e == "object" && e !== null && "id" in e && "data" in e && "formatVersion" in e && "encoded" in e;
772
- }
773
- getStoresFiltered(e) {
774
- return this.stores.filter((t) => typeof e > "u" ? true : Array.isArray(e) ? e.includes(t.id) : e(t.id));
775
- }
776
- };
777
- var Z = () => ({ emit(r, ...e) {
778
- for (let t = this.events[r] || [], i = 0, n = t.length; i < n; i++) t[i](...e);
779
- }, events: {}, on(r, e) {
1227
+ const decodedData = storeData.encoded && storeInst.encodingEnabled() ? yield storeInst.decodeData[1](storeData.data) : storeData.data;
1228
+ if (storeData.formatVersion && !isNaN(Number(storeData.formatVersion)) && Number(storeData.formatVersion) < storeInst.formatVersion)
1229
+ yield storeInst.runMigrations(JSON.parse(decodedData), Number(storeData.formatVersion), false);
1230
+ else
1231
+ yield storeInst.setData(JSON.parse(decodedData));
1232
+ }
1233
+ });
1234
+ }
1235
+ /**
1236
+ * Deserializes the data exported via {@linkcode serialize()} and imports the data into all matching DataStore instances.
1237
+ * Also triggers the migration process if the data format has changed.
1238
+ */
1239
+ deserialize(data) {
1240
+ return __async(this, null, function* () {
1241
+ return this.deserializePartial(this.stores.map((s) => s.id), data);
1242
+ });
1243
+ }
1244
+ /**
1245
+ * Loads the persistent data of the DataStore instances into the in-memory cache.
1246
+ * Also triggers the migration process if the data format has changed.
1247
+ * @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
1248
+ * @returns Returns a PromiseSettledResult array with the results of each DataStore instance in the format `{ id: string, data: object }`
1249
+ */
1250
+ loadStoresData(stores) {
1251
+ return __async(this, null, function* () {
1252
+ return Promise.allSettled(
1253
+ this.getStoresFiltered(stores).map((store) => __async(this, null, function* () {
1254
+ return {
1255
+ id: store.id,
1256
+ data: yield store.loadData()
1257
+ };
1258
+ }))
1259
+ );
1260
+ });
1261
+ }
1262
+ /**
1263
+ * Resets the persistent and in-memory data of the DataStore instances to their default values.
1264
+ * @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
1265
+ */
1266
+ resetStoresData(stores) {
1267
+ return __async(this, null, function* () {
1268
+ return Promise.allSettled(
1269
+ this.getStoresFiltered(stores).map((store) => store.saveDefaultData())
1270
+ );
1271
+ });
1272
+ }
1273
+ /**
1274
+ * Deletes the persistent data of the DataStore instances.
1275
+ * Leaves the in-memory data untouched.
1276
+ * @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
1277
+ */
1278
+ deleteStoresData(stores) {
1279
+ return __async(this, null, function* () {
1280
+ return Promise.allSettled(
1281
+ this.getStoresFiltered(stores).map((store) => store.deleteData())
1282
+ );
1283
+ });
1284
+ }
1285
+ /** Checks if a given value is an array of SerializedDataStore objects */
1286
+ static isSerializedDataStoreObjArray(obj) {
1287
+ return Array.isArray(obj) && obj.every((o) => typeof o === "object" && o !== null && "id" in o && "data" in o && "formatVersion" in o && "encoded" in o);
1288
+ }
1289
+ /** Checks if a given value is a SerializedDataStore object */
1290
+ static isSerializedDataStoreObj(obj) {
1291
+ return typeof obj === "object" && obj !== null && "id" in obj && "data" in obj && "formatVersion" in obj && "encoded" in obj;
1292
+ }
1293
+ /** Returns the DataStore instances whose IDs match the provided array or function */
1294
+ getStoresFiltered(stores) {
1295
+ return this.stores.filter((s) => typeof stores === "undefined" ? true : Array.isArray(stores) ? stores.includes(s.id) : stores(s.id));
1296
+ }
1297
+ };
1298
+ var createNanoEvents = () => ({
1299
+ emit(event, ...args) {
1300
+ for (let callbacks = this.events[event] || [], i = 0, length = callbacks.length; i < length; i++) {
1301
+ callbacks[i](...args);
1302
+ }
1303
+ },
1304
+ events: {},
1305
+ on(event, cb) {
780
1306
  var _a;
781
- return ((_a = this.events)[r] || (_a[r] = [])).push(e), () => {
782
- var t;
783
- this.events[r] = (t = this.events[r]) == null ? void 0 : t.filter((i) => e !== i);
1307
+ ;
1308
+ ((_a = this.events)[event] || (_a[event] = [])).push(cb);
1309
+ return () => {
1310
+ var _a2;
1311
+ this.events[event] = (_a2 = this.events[event]) == null ? void 0 : _a2.filter((i) => cb !== i);
784
1312
  };
785
- } });
786
- var P = class {
787
- constructor(e = {}) {
788
- __publicField(this, "events", Z());
789
- __publicField(this, "eventUnsubscribes", []);
790
- __publicField(this, "emitterOptions");
791
- this.emitterOptions = __spreadValues({ publicEmit: false }, e);
792
- }
793
- on(e, t) {
794
- let i, n = () => {
795
- i && (i(), this.eventUnsubscribes = this.eventUnsubscribes.filter((o) => o !== i));
796
- };
797
- return i = this.events.on(e, t), this.eventUnsubscribes.push(i), n;
798
- }
799
- once(e, t) {
800
- return new Promise((i) => {
801
- let n, o = ((...a) => {
802
- t == null || t(...a), n == null || n(), i(a);
803
- });
804
- n = this.events.on(e, o), this.eventUnsubscribes.push(n);
1313
+ }
1314
+ });
1315
+ var NanoEmitter = class {
1316
+ /** Creates a new instance of NanoEmitter - a lightweight event emitter with helper methods and a strongly typed event map */
1317
+ constructor(options = {}) {
1318
+ __publicField(this, "events", createNanoEvents());
1319
+ __publicField(this, "eventUnsubscribes", []);
1320
+ __publicField(this, "emitterOptions");
1321
+ this.emitterOptions = __spreadValues({
1322
+ publicEmit: false
1323
+ }, options);
1324
+ }
1325
+ //#region on
1326
+ /**
1327
+ * Subscribes to an event and calls the callback when it's emitted.
1328
+ * @param event The event to subscribe to. Use `as "_"` in case your event names aren't thoroughly typed (like when using a template literal, e.g. \`event-${val}\` as "_")
1329
+ * @returns Returns a function that can be called to unsubscribe the event listener
1330
+ * @example ```ts
1331
+ * const emitter = new NanoEmitter<{
1332
+ * foo: (bar: string) => void;
1333
+ * }>({
1334
+ * publicEmit: true,
1335
+ * });
1336
+ *
1337
+ * let i = 0;
1338
+ * const unsub = emitter.on("foo", (bar) => {
1339
+ * // unsubscribe after 10 events:
1340
+ * if(++i === 10) unsub();
1341
+ * console.log(bar);
1342
+ * });
1343
+ *
1344
+ * emitter.emit("foo", "bar");
1345
+ * ```
1346
+ */
1347
+ on(event, cb) {
1348
+ let unsub;
1349
+ const unsubProxy = () => {
1350
+ if (!unsub)
1351
+ return;
1352
+ unsub();
1353
+ this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => u !== unsub);
1354
+ };
1355
+ unsub = this.events.on(event, cb);
1356
+ this.eventUnsubscribes.push(unsub);
1357
+ return unsubProxy;
1358
+ }
1359
+ //#region once
1360
+ /**
1361
+ * Subscribes to an event and calls the callback or resolves the Promise only once when it's emitted.
1362
+ * @param event The event to subscribe to. Use `as "_"` in case your event names aren't thoroughly typed (like when using a template literal, e.g. \`event-${val}\` as "_")
1363
+ * @param cb The callback to call when the event is emitted - if provided or not, the returned Promise will resolve with the event arguments
1364
+ * @returns Returns a Promise that resolves with the event arguments when the event is emitted
1365
+ * @example ```ts
1366
+ * const emitter = new NanoEmitter<{
1367
+ * foo: (bar: string) => void;
1368
+ * }>();
1369
+ *
1370
+ * // Promise syntax:
1371
+ * const [bar] = await emitter.once("foo");
1372
+ * console.log(bar);
1373
+ *
1374
+ * // Callback syntax:
1375
+ * emitter.once("foo", (bar) => console.log(bar));
1376
+ * ```
1377
+ */
1378
+ once(event, cb) {
1379
+ return new Promise((resolve) => {
1380
+ let unsub;
1381
+ const onceProxy = ((...args) => {
1382
+ cb == null ? void 0 : cb(...args);
1383
+ unsub == null ? void 0 : unsub();
1384
+ resolve(args);
805
1385
  });
806
- }
807
- onMulti(e) {
808
- let t = [], i = () => {
809
- for (let n of t) n();
810
- t.splice(0, t.length), this.eventUnsubscribes = this.eventUnsubscribes.filter((n) => !t.includes(n));
1386
+ unsub = this.events.on(event, onceProxy);
1387
+ this.eventUnsubscribes.push(unsub);
1388
+ });
1389
+ }
1390
+ //#region onMulti
1391
+ /**
1392
+ * Allows subscribing to multiple events and calling the callback only when one of, all of, or a subset of the events are emitted, either continuously or only once.
1393
+ * @param options An object or array of objects with the following properties:
1394
+ * `callback` (required) is the function that will be called when the conditions are met.
1395
+ *
1396
+ * 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.
1397
+ * If `signal` is provided, the subscription will be canceled when the given signal is aborted.
1398
+ *
1399
+ * If `oneOf` is used, the callback will be called when any of the matching events are emitted.
1400
+ * 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.
1401
+ * 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.
1402
+ * At least one of `oneOf` or `allOf` must be provided.
1403
+ *
1404
+ * @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.
1405
+ */
1406
+ onMulti(options) {
1407
+ const allUnsubs = [];
1408
+ const unsubAll = () => {
1409
+ for (const unsub of allUnsubs)
1410
+ unsub();
1411
+ allUnsubs.splice(0, allUnsubs.length);
1412
+ this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !allUnsubs.includes(u));
1413
+ };
1414
+ for (const opts of Array.isArray(options) ? options : [options]) {
1415
+ const optsWithDefaults = __spreadValues({
1416
+ allOf: [],
1417
+ oneOf: [],
1418
+ once: false
1419
+ }, opts);
1420
+ const {
1421
+ oneOf,
1422
+ allOf,
1423
+ once,
1424
+ signal,
1425
+ callback
1426
+ } = optsWithDefaults;
1427
+ if (signal == null ? void 0 : signal.aborted)
1428
+ return unsubAll;
1429
+ if (oneOf.length === 0 && allOf.length === 0)
1430
+ throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
1431
+ const curEvtUnsubs = [];
1432
+ const checkUnsubAllEvt = (force = false) => {
1433
+ if (!(signal == null ? void 0 : signal.aborted) && !force)
1434
+ return;
1435
+ for (const unsub of curEvtUnsubs)
1436
+ unsub();
1437
+ curEvtUnsubs.splice(0, curEvtUnsubs.length);
1438
+ this.eventUnsubscribes = this.eventUnsubscribes.filter((u) => !curEvtUnsubs.includes(u));
811
1439
  };
812
- for (let n of Array.isArray(e) ? e : [e]) {
813
- let o = __spreadValues({ allOf: [], oneOf: [], once: false }, n), { oneOf: a, allOf: s, once: u, signal: l, callback: c } = o;
814
- if (l != null && l.aborted) return i;
815
- if (a.length === 0 && s.length === 0) throw new TypeError("NanoEmitter.onMulti(): Either `oneOf` or `allOf` or both must be provided in the options");
816
- let p = [], m = (h = false) => {
817
- if (!(!(l != null && l.aborted) && !h)) {
818
- for (let y of p) y();
819
- p.splice(0, p.length), this.eventUnsubscribes = this.eventUnsubscribes.filter((y) => !p.includes(y));
1440
+ const allOfEmitted = /* @__PURE__ */ new Set();
1441
+ const allOfConditionMet = () => allOf.length === 0 || allOfEmitted.size === allOf.length;
1442
+ for (const event of oneOf) {
1443
+ const unsub = this.events.on(event, ((...args) => {
1444
+ checkUnsubAllEvt();
1445
+ if (allOfConditionMet()) {
1446
+ callback(event, ...args);
1447
+ if (once)
1448
+ checkUnsubAllEvt(true);
820
1449
  }
821
- }, b = /* @__PURE__ */ new Set(), O = () => s.length === 0 || b.size === s.length;
822
- for (let h of a) {
823
- let y = this.events.on(h, ((...M) => {
824
- m(), O() && (c(h, ...M), u && m(true));
825
- }));
826
- p.push(y);
827
- }
828
- for (let h of s) {
829
- let y = this.events.on(h, ((...M) => {
830
- m(), b.add(h), O() && (a.length === 0 || a.includes(h)) && (c(h, ...M), u && m(true));
831
- }));
832
- p.push(y);
833
- }
834
- t.push(() => m(true));
1450
+ }));
1451
+ curEvtUnsubs.push(unsub);
835
1452
  }
836
- return i;
837
- }
838
- emit(e, ...t) {
839
- return this.emitterOptions.publicEmit ? (this.events.emit(e, ...t), true) : false;
840
- }
841
- unsubscribeAll() {
842
- for (let e of this.eventUnsubscribes) e();
843
- this.eventUnsubscribes = [];
844
- }
845
- };
846
- var A = class extends P {
847
- constructor(t = 200, i = "immediate") {
848
- super();
849
- __publicField(this, "listeners", []);
850
- __publicField(this, "activeTimeout");
851
- __publicField(this, "queuedCall");
852
- this.timeout = t;
853
- this.type = i;
854
- }
855
- addListener(t) {
856
- this.listeners.push(t);
857
- }
858
- removeListener(t) {
859
- let i = this.listeners.findIndex((n) => n === t);
860
- i !== -1 && this.listeners.splice(i, 1);
861
- }
862
- removeAllListeners() {
863
- this.listeners = [];
864
- }
865
- getListeners() {
866
- return this.listeners;
867
- }
868
- setTimeout(t) {
869
- this.emit("change", this.timeout = t, this.type);
870
- }
871
- getTimeout() {
872
- return this.timeout;
873
- }
874
- isTimeoutActive() {
875
- return typeof this.activeTimeout < "u";
876
- }
877
- setType(t) {
878
- this.emit("change", this.timeout, this.type = t);
1453
+ for (const event of allOf) {
1454
+ const unsub = this.events.on(event, ((...args) => {
1455
+ checkUnsubAllEvt();
1456
+ allOfEmitted.add(event);
1457
+ if (allOfConditionMet() && (oneOf.length === 0 || oneOf.includes(event))) {
1458
+ callback(event, ...args);
1459
+ if (once)
1460
+ checkUnsubAllEvt(true);
1461
+ }
1462
+ }));
1463
+ curEvtUnsubs.push(unsub);
1464
+ }
1465
+ allUnsubs.push(() => checkUnsubAllEvt(true));
879
1466
  }
880
- getType() {
881
- return this.type;
1467
+ return unsubAll;
1468
+ }
1469
+ //#region emit
1470
+ /**
1471
+ * Emits an event on this instance.
1472
+ * - ⚠️ Needs `publicEmit` to be set to true in the NanoEmitter constructor or super() call!
1473
+ * @param event The event to emit
1474
+ * @param args The arguments to pass to the event listeners
1475
+ * @returns Returns true if `publicEmit` is true and the event was emitted successfully
1476
+ */
1477
+ emit(event, ...args) {
1478
+ if (this.emitterOptions.publicEmit) {
1479
+ this.events.emit(event, ...args);
1480
+ return true;
882
1481
  }
883
- call(...t) {
884
- let i = (...o) => {
885
- this.queuedCall = void 0, this.emit("call", ...o), this.listeners.forEach((a) => a.call(this, ...o));
886
- }, n = () => {
1482
+ return false;
1483
+ }
1484
+ //#region unsubscribeAll
1485
+ /** Unsubscribes all event listeners from this instance */
1486
+ unsubscribeAll() {
1487
+ for (const unsub of this.eventUnsubscribes)
1488
+ unsub();
1489
+ this.eventUnsubscribes = [];
1490
+ }
1491
+ };
1492
+ var Debouncer = class extends NanoEmitter {
1493
+ /**
1494
+ * Creates a new debouncer with the specified timeout and edge type.
1495
+ * @param timeout Timeout in milliseconds between letting through calls - defaults to 200
1496
+ * @param type The edge type to use for the debouncer - see {@linkcode DebouncerType} for details or [the documentation for an explanation and diagram](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#debouncer) - defaults to "immediate"
1497
+ */
1498
+ constructor(timeout = 200, type = "immediate") {
1499
+ super();
1500
+ /** All registered listener functions and the time they were attached */
1501
+ __publicField(this, "listeners", []);
1502
+ /** The currently active timeout */
1503
+ __publicField(this, "activeTimeout");
1504
+ /** The latest queued call */
1505
+ __publicField(this, "queuedCall");
1506
+ this.timeout = timeout;
1507
+ this.type = type;
1508
+ }
1509
+ //#region listeners
1510
+ /** Adds a listener function that will be called on timeout */
1511
+ addListener(fn) {
1512
+ this.listeners.push(fn);
1513
+ }
1514
+ /** Removes the listener with the specified function reference */
1515
+ removeListener(fn) {
1516
+ const idx = this.listeners.findIndex((l) => l === fn);
1517
+ idx !== -1 && this.listeners.splice(idx, 1);
1518
+ }
1519
+ /** Removes all listeners */
1520
+ removeAllListeners() {
1521
+ this.listeners = [];
1522
+ }
1523
+ /** Returns all registered listeners */
1524
+ getListeners() {
1525
+ return this.listeners;
1526
+ }
1527
+ //#region timeout
1528
+ /** Sets the timeout for the debouncer */
1529
+ setTimeout(timeout) {
1530
+ this.emit("change", this.timeout = timeout, this.type);
1531
+ }
1532
+ /** Returns the current timeout */
1533
+ getTimeout() {
1534
+ return this.timeout;
1535
+ }
1536
+ /** Whether the timeout is currently active, meaning any latest call to the {@linkcode call()} method will be queued */
1537
+ isTimeoutActive() {
1538
+ return typeof this.activeTimeout !== "undefined";
1539
+ }
1540
+ //#region type
1541
+ /** Sets the edge type for the debouncer */
1542
+ setType(type) {
1543
+ this.emit("change", this.timeout, this.type = type);
1544
+ }
1545
+ /** Returns the current edge type */
1546
+ getType() {
1547
+ return this.type;
1548
+ }
1549
+ //#region call
1550
+ /** Use this to call the debouncer with the specified arguments that will be passed to all listener functions registered with {@linkcode addListener()} */
1551
+ call(...args) {
1552
+ const cl = (...a) => {
1553
+ this.queuedCall = void 0;
1554
+ this.emit("call", ...a);
1555
+ this.listeners.forEach((l) => l.call(this, ...a));
1556
+ };
1557
+ const setRepeatTimeout = () => {
1558
+ this.activeTimeout = setTimeout(() => {
1559
+ if (this.queuedCall) {
1560
+ this.queuedCall();
1561
+ setRepeatTimeout();
1562
+ } else
1563
+ this.activeTimeout = void 0;
1564
+ }, this.timeout);
1565
+ };
1566
+ switch (this.type) {
1567
+ case "immediate":
1568
+ if (typeof this.activeTimeout === "undefined") {
1569
+ cl(...args);
1570
+ setRepeatTimeout();
1571
+ } else
1572
+ this.queuedCall = () => cl(...args);
1573
+ break;
1574
+ case "idle":
1575
+ if (this.activeTimeout)
1576
+ clearTimeout(this.activeTimeout);
887
1577
  this.activeTimeout = setTimeout(() => {
888
- this.queuedCall ? (this.queuedCall(), n()) : this.activeTimeout = void 0;
1578
+ cl(...args);
1579
+ this.activeTimeout = void 0;
889
1580
  }, this.timeout);
890
- };
891
- switch (this.type) {
892
- case "immediate":
893
- typeof this.activeTimeout > "u" ? (i(...t), n()) : this.queuedCall = () => i(...t);
894
- break;
895
- case "idle":
896
- this.activeTimeout && clearTimeout(this.activeTimeout), this.activeTimeout = setTimeout(() => {
897
- i(...t), this.activeTimeout = void 0;
898
- }, this.timeout);
899
- break;
900
- default:
901
- throw new TypeError(`Invalid debouncer type: ${this.type}`);
902
- }
1581
+ break;
1582
+ default:
1583
+ throw new TypeError(`Invalid debouncer type: ${this.type}`);
903
1584
  }
904
- };
905
- function Ie(r, e = 200, t = "immediate") {
906
- let i = new A(e, t);
907
- i.addListener(r);
908
- let n = ((...o) => i.call(...o));
909
- return n.debouncer = i, n;
910
1585
  }
911
- if (typeof module2.exports == "object" && typeof exports2 == "object") {
912
- var __cp = (to, from, except, desc) => {
913
- if (from && typeof from === "object" || typeof from === "function") {
914
- for (let key of Object.getOwnPropertyNames(from)) {
915
- if (!Object.prototype.hasOwnProperty.call(to, key) && key !== except)
916
- Object.defineProperty(to, key, {
917
- get: () => from[key],
918
- enumerable: !(desc = Object.getOwnPropertyDescriptor(from, key)) || desc.enumerable
919
- });
920
- }
921
- }
922
- return to;
923
- };
924
- module2.exports = __cp(module2.exports, exports2);
925
- }
926
- return module2.exports;
927
- });
1586
+ };
1587
+ function debounce(fn, timeout = 200, type = "immediate") {
1588
+ const debouncer = new Debouncer(timeout, type);
1589
+ debouncer.addListener(fn);
1590
+ const func = ((...args) => debouncer.call(...args));
1591
+ func.debouncer = debouncer;
1592
+ return func;
1593
+ }
928
1594
 
929
1595
  // lib/Errors.ts
930
- var PlatformError = class extends (void 0) {
1596
+ var PlatformError = class extends DatedError {
931
1597
  constructor(message, options) {
932
1598
  super(message, options);
933
1599
  this.name = "PlatformError";
@@ -998,8 +1664,8 @@ function interceptEvent(eventObject, eventName, predicate = () => true) {
998
1664
  if (typeof window.GM === "object" && ((_a = GM == null ? void 0 : GM.info) == null ? void 0 : _a.scriptHandler) && GM.info.scriptHandler === "FireMonkey" && (eventObject === window || eventObject === getUnsafeWindow()))
999
1665
  throw new PlatformError("Intercepting window events is not supported on FireMonkey due to the isolated context the userscript is forced to run in.");
1000
1666
  if ("stackTraceLimit" in Error) {
1001
- Error.stackTraceLimit = Math.max(Error.stackTraceLimit, 100);
1002
- if (isNaN(Error.stackTraceLimit))
1667
+ Error.stackTraceLimit = Math.max(Number(Error.stackTraceLimit), 100);
1668
+ if (isNaN(Number(Error.stackTraceLimit)))
1003
1669
  Error.stackTraceLimit = 100;
1004
1670
  }
1005
1671
  (function(original) {
@@ -1268,7 +1934,7 @@ var openDialogs = [];
1268
1934
  var defaultStrings = {
1269
1935
  closeDialogTooltip: "Click to close the dialog"
1270
1936
  };
1271
- var Dialog = class _Dialog extends (void 0) {
1937
+ var Dialog = class _Dialog extends NanoEmitter {
1272
1938
  constructor(options) {
1273
1939
  super();
1274
1940
  /** Options passed to the dialog in the constructor */
@@ -1532,7 +2198,7 @@ var Dialog = class _Dialog extends (void 0) {
1532
2198
  };
1533
2199
 
1534
2200
  // lib/GMStorageEngine.ts
1535
- var GMStorageEngine = class extends (void 0) {
2201
+ var GMStorageEngine = class extends DataStoreEngine {
1536
2202
  /**
1537
2203
  * Creates an instance of `GMStorageEngine`.
1538
2204
  *
@@ -1617,7 +2283,7 @@ var Mixins = class {
1617
2283
  /** The current auto-increment priority counter */
1618
2284
  __publicField(this, "autoIncPrioCounter", /* @__PURE__ */ new Map());
1619
2285
  var _a, _b, _c;
1620
- this.defaultMixinCfg = (void 0)({
2286
+ this.defaultMixinCfg = pureObj({
1621
2287
  priority: (_a = config.defaultPriority) != null ? _a : 0,
1622
2288
  stopPropagation: (_b = config.defaultStopPropagation) != null ? _b : false,
1623
2289
  signal: config.defaultSignal
@@ -1633,9 +2299,9 @@ var Mixins = class {
1633
2299
  * @param config Configuration object to customize the mixin behavior, or just the priority if a number is passed.
1634
2300
  * @returns Returns a cleanup function, to be called when this mixin is no longer needed.
1635
2301
  */
1636
- add(mixinKey, mixinFn, config = (void 0)({})) {
2302
+ add(mixinKey, mixinFn, config = pureObj({})) {
1637
2303
  const calcPrio = typeof config === "number" ? config : this.calcPriority(mixinKey, config);
1638
- const mixin = (void 0)(__spreadValues(__spreadValues(__spreadProps(__spreadValues({}, this.defaultMixinCfg), {
2304
+ const mixin = pureObj(__spreadValues(__spreadValues(__spreadProps(__spreadValues({}, this.defaultMixinCfg), {
1639
2305
  key: mixinKey,
1640
2306
  fn: mixinFn
1641
2307
  }), typeof config === "object" ? config : {}), typeof calcPrio === "number" && !isNaN(calcPrio) ? { priority: calcPrio } : {}));
@@ -1805,7 +2471,7 @@ var SelectorObserver = class {
1805
2471
  debounce: 0
1806
2472
  }, options);
1807
2473
  if (options.debounce && options.debounce > 0 || this.customOptions.defaultDebounce && this.customOptions.defaultDebounce > 0) {
1808
- options.listener = (void 0)(
2474
+ options.listener = debounce(
1809
2475
  options.listener,
1810
2476
  options.debounce || this.customOptions.defaultDebounce,
1811
2477
  options.debounceType || this.customOptions.defaultDebounceType