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