@sv443-network/userutils 2.0.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -48,28 +48,36 @@ var __async = (__this, __arguments, generator) => {
48
48
  function clamp(value, min, max) {
49
49
  return Math.max(Math.min(value, max), min);
50
50
  }
51
- function mapRange(value, range_1_min, range_1_max, range_2_min, range_2_max) {
52
- if (Number(range_1_min) === 0 && Number(range_2_min) === 0)
53
- return value * (range_2_max / range_1_max);
54
- return (value - range_1_min) * ((range_2_max - range_2_min) / (range_1_max - range_1_min)) + range_2_min;
51
+ function mapRange(value, range1min, range1max, range2min, range2max) {
52
+ if (Number(range1min) === 0 && Number(range2min) === 0)
53
+ return value * (range2max / range1max);
54
+ return (value - range1min) * ((range2max - range2min) / (range1max - range1min)) + range2min;
55
55
  }
56
56
  function randRange(...args) {
57
57
  let min, max;
58
- if (typeof args[0] === "number" && typeof args[1] === "number") {
58
+ if (typeof args[0] === "number" && typeof args[1] === "number")
59
59
  [min, max] = args;
60
- } else if (typeof args[0] === "number" && typeof args[1] !== "number") {
60
+ else if (typeof args[0] === "number" && typeof args[1] !== "number") {
61
61
  min = 0;
62
- max = args[0];
62
+ [max] = args;
63
63
  } else
64
64
  throw new TypeError(`Wrong parameter(s) provided - expected: "number" and "number|undefined", got: "${typeof args[0]}" and "${typeof args[1]}"`);
65
65
  min = Number(min);
66
66
  max = Number(max);
67
67
  if (isNaN(min) || isNaN(max))
68
- throw new TypeError(`Parameters "min" and "max" can't be NaN`);
68
+ return NaN;
69
69
  if (min > max)
70
70
  throw new TypeError(`Parameter "min" can't be bigger than "max"`);
71
71
  return Math.floor(Math.random() * (max - min + 1)) + min;
72
72
  }
73
+ function randomId(length = 16, radix = 16) {
74
+ const arr = new Uint8Array(length);
75
+ crypto.getRandomValues(arr);
76
+ return Array.from(
77
+ arr,
78
+ (v) => mapRange(v, 0, 255, 0, radix).toString(radix).substring(0, 1)
79
+ ).join("");
80
+ }
73
81
 
74
82
  // lib/array.ts
75
83
  function randomItem(array) {
@@ -99,14 +107,14 @@ function randomizeArray(array) {
99
107
  return retArray;
100
108
  }
101
109
 
102
- // lib/config.ts
110
+ // lib/ConfigManager.ts
103
111
  var ConfigManager = class {
104
112
  /**
105
113
  * Creates an instance of ConfigManager to manage a user configuration that is cached in memory and persistently saved across sessions.
106
114
  * Supports migrating data from older versions of the configuration to newer ones and populating the cache with default data if no persistent data is found.
107
115
  *
108
116
  * ⚠️ Requires the directives `@grant GM.getValue` and `@grant GM.setValue`
109
- * ⚠️ Make sure to call `loadData()` at least once after creating an instance, or the returned data will be the same as `options.defaultConfig`
117
+ * ⚠️ Make sure to call {@linkcode loadData()} at least once after creating an instance, or the returned data will be the same as `options.defaultConfig`
110
118
  *
111
119
  * @template TData The type of the data that is saved in persistent storage (will be automatically inferred from `config.defaultConfig`) - this should also be the type of the data format associated with the current `options.formatVersion`
112
120
  * @param options The options for this ConfigManager instance
@@ -149,7 +157,10 @@ var ConfigManager = class {
149
157
  }
150
158
  });
151
159
  }
152
- /** Returns a copy of the data from the in-memory cache. Use `loadData()` to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage). */
160
+ /**
161
+ * Returns a copy of the data from the in-memory cache.
162
+ * Use {@linkcode loadData()} to get fresh data from persistent storage (usually not necessary since the cache should always exactly reflect persistent storage).
163
+ */
153
164
  getData() {
154
165
  return this.deepCopy(this.cachedConfig);
155
166
  }
@@ -179,8 +190,8 @@ var ConfigManager = class {
179
190
  }
180
191
  /**
181
192
  * Call this method to clear all persistently stored data associated with this ConfigManager instance.
182
- * The in-memory cache will be left untouched, so you may still access the data with `getData()`.
183
- * Calling `loadData()` or `setData()` after this method was called will recreate persistent storage with the cached or default data.
193
+ * The in-memory cache will be left untouched, so you may still access the data with {@linkcode getData()}
194
+ * Calling {@linkcode loadData()} or {@linkcode setData()} after this method was called will recreate persistent storage with the cached or default data.
184
195
  *
185
196
  * ⚠️ This requires the additional directive `@grant GM.deleteValue`
186
197
  */
@@ -273,7 +284,7 @@ function openInNewTab(href) {
273
284
  openElem.click();
274
285
  setTimeout(openElem.remove, 50);
275
286
  }
276
- function interceptEvent(eventObject, eventName, predicate) {
287
+ function interceptEvent(eventObject, eventName, predicate = () => true) {
277
288
  if (typeof Error.stackTraceLimit === "number" && Error.stackTraceLimit < 1e3) {
278
289
  Error.stackTraceLimit = 1e3;
279
290
  }
@@ -291,56 +302,9 @@ function interceptEvent(eventObject, eventName, predicate) {
291
302
  };
292
303
  })(eventObject.__proto__.addEventListener);
293
304
  }
294
- function interceptWindowEvent(eventName, predicate) {
305
+ function interceptWindowEvent(eventName, predicate = () => true) {
295
306
  return interceptEvent(getUnsafeWindow(), eventName, predicate);
296
307
  }
297
- function amplifyMedia(mediaElement, initialMultiplier = 1) {
298
- const context = new (window.AudioContext || window.webkitAudioContext)();
299
- const props = {
300
- /** Sets the gain multiplier */
301
- setGain(multiplier) {
302
- props.gainNode.gain.setValueAtTime(multiplier, props.context.currentTime);
303
- },
304
- /** Returns the current gain multiplier */
305
- getGain() {
306
- return props.gainNode.gain.value;
307
- },
308
- /** Enable the amplification for the first time or if it was disabled before */
309
- enable() {
310
- props.source.connect(props.limiterNode);
311
- props.limiterNode.connect(props.gainNode);
312
- props.gainNode.connect(props.context.destination);
313
- },
314
- /** Disable the amplification */
315
- disable() {
316
- props.source.disconnect(props.limiterNode);
317
- props.limiterNode.disconnect(props.gainNode);
318
- props.gainNode.disconnect(props.context.destination);
319
- props.source.connect(props.context.destination);
320
- },
321
- /**
322
- * Set the options of the [limiter / DynamicsCompressorNode](https://developer.mozilla.org/en-US/docs/Web/API/DynamicsCompressorNode/DynamicsCompressorNode#options)
323
- * The default is `{ threshold: -12, knee: 30, ratio: 12, attack: 0.003, release: 0.25 }`
324
- */
325
- setLimiterOptions(options) {
326
- for (const [key, val] of Object.entries(options))
327
- props.limiterNode[key].setValueAtTime(val, props.context.currentTime);
328
- },
329
- context,
330
- source: context.createMediaElementSource(mediaElement),
331
- gainNode: context.createGain(),
332
- limiterNode: context.createDynamicsCompressor()
333
- };
334
- props.setLimiterOptions({
335
- threshold: -12,
336
- knee: 30,
337
- ratio: 12,
338
- attack: 3e-3,
339
- release: 0.25
340
- });
341
- props.setGain(initialMultiplier);
342
- return props;
343
- }
344
308
  function isScrollable(element) {
345
309
  const { overflowX, overflowY } = getComputedStyle(element);
346
310
  return {
@@ -379,63 +343,184 @@ function fetchAdvanced(_0) {
379
343
  return res;
380
344
  });
381
345
  }
382
- function insertValues(str, ...values) {
383
- return str.replace(/%\d/gm, (match) => {
346
+ function insertValues(input, ...values) {
347
+ return input.replace(/%\d/gm, (match) => {
384
348
  var _a, _b;
385
349
  const argIndex = Number(match.substring(1)) - 1;
386
350
  return (_b = (_a = values[argIndex]) != null ? _a : match) == null ? void 0 : _b.toString();
387
351
  });
388
352
  }
389
-
390
- // lib/onSelector.ts
391
- var selectorMap = /* @__PURE__ */ new Map();
392
- function onSelector(selector, options) {
393
- let selectorMapItems = [];
394
- if (selectorMap.has(selector))
395
- selectorMapItems = selectorMap.get(selector);
396
- selectorMapItems.push(options);
397
- selectorMap.set(selector, selectorMapItems);
398
- checkSelectorExists(selector, selectorMapItems);
353
+ function compress(input, compressionFormat, outputType = "base64") {
354
+ return __async(this, null, function* () {
355
+ const byteArray = typeof input === "string" ? new TextEncoder().encode(input) : input;
356
+ const comp = new CompressionStream(compressionFormat);
357
+ const writer = comp.writable.getWriter();
358
+ writer.write(byteArray);
359
+ writer.close();
360
+ const buf = yield new Response(comp.readable).arrayBuffer();
361
+ return outputType === "arrayBuffer" ? buf : ab2str(buf);
362
+ });
363
+ }
364
+ function decompress(input, compressionFormat, outputType = "string") {
365
+ return __async(this, null, function* () {
366
+ const byteArray = typeof input === "string" ? str2ab(input) : input;
367
+ const decomp = new DecompressionStream(compressionFormat);
368
+ const writer = decomp.writable.getWriter();
369
+ writer.write(byteArray);
370
+ writer.close();
371
+ const buf = yield new Response(decomp.readable).arrayBuffer();
372
+ return outputType === "arrayBuffer" ? buf : new TextDecoder().decode(buf);
373
+ });
374
+ }
375
+ function ab2str(buf) {
376
+ return getUnsafeWindow().btoa(
377
+ new Uint8Array(buf).reduce((data, byte) => data + String.fromCharCode(byte), "")
378
+ );
399
379
  }
400
- function removeOnSelector(selector) {
401
- return selectorMap.delete(selector);
380
+ function str2ab(str) {
381
+ return Uint8Array.from(getUnsafeWindow().atob(str), (c) => c.charCodeAt(0));
402
382
  }
403
- function checkSelectorExists(selector, options) {
404
- const deleteIndices = [];
405
- options.forEach((option, i) => {
406
- try {
407
- const elements = option.all ? document.querySelectorAll(selector) : document.querySelector(selector);
408
- if (elements !== null && elements instanceof NodeList && elements.length > 0 || elements !== null) {
409
- option.listener(elements);
410
- if (!option.continuous)
411
- deleteIndices.push(i);
383
+
384
+ // lib/SelectorObserver.ts
385
+ var SelectorObserver = class {
386
+ constructor(baseElement, options = {}) {
387
+ __publicField(this, "enabled", false);
388
+ __publicField(this, "baseElement");
389
+ __publicField(this, "observer");
390
+ __publicField(this, "observerOptions");
391
+ __publicField(this, "listenerMap");
392
+ this.baseElement = baseElement;
393
+ this.listenerMap = /* @__PURE__ */ new Map();
394
+ this.observer = new MutationObserver(() => this.checkAllSelectors());
395
+ this.observerOptions = __spreadValues({
396
+ childList: true,
397
+ subtree: true
398
+ }, options);
399
+ }
400
+ checkAllSelectors() {
401
+ for (const [selector, listeners] of this.listenerMap.entries())
402
+ this.checkSelector(selector, listeners);
403
+ }
404
+ checkSelector(selector, listeners) {
405
+ var _a;
406
+ if (!this.enabled)
407
+ return;
408
+ const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
409
+ if (!baseElement)
410
+ return;
411
+ const all = listeners.some((listener) => listener.all);
412
+ const one = listeners.some((listener) => !listener.all);
413
+ const allElements = all ? baseElement.querySelectorAll(selector) : null;
414
+ const oneElement = one ? baseElement.querySelector(selector) : null;
415
+ for (const options of listeners) {
416
+ if (options.all) {
417
+ if (allElements && allElements.length > 0) {
418
+ options.listener(allElements);
419
+ if (!options.continuous)
420
+ this.removeListener(selector, options);
421
+ }
422
+ } else {
423
+ if (oneElement) {
424
+ options.listener(oneElement);
425
+ if (!options.continuous)
426
+ this.removeListener(selector, options);
427
+ }
412
428
  }
413
- } catch (err) {
414
- console.error(`Couldn't call listener for selector '${selector}'`, err);
429
+ if (((_a = this.listenerMap.get(selector)) == null ? void 0 : _a.length) === 0)
430
+ this.listenerMap.delete(selector);
415
431
  }
416
- });
417
- if (deleteIndices.length > 0) {
418
- const newOptsArray = options.filter((_, i) => !deleteIndices.includes(i));
419
- if (newOptsArray.length === 0)
420
- selectorMap.delete(selector);
421
- else {
422
- selectorMap.set(selector, newOptsArray);
432
+ }
433
+ debounce(func, time) {
434
+ let timeout;
435
+ return function(...args) {
436
+ clearTimeout(timeout);
437
+ timeout = setTimeout(() => func.apply(this, args), time);
438
+ };
439
+ }
440
+ /**
441
+ * Starts observing the children of the base element for changes to the given {@linkcode selector} according to the set {@linkcode options}
442
+ * @param selector The selector to observe
443
+ * @param options Options for the selector observation
444
+ * @param options.listener Gets called whenever the selector was found in the DOM
445
+ * @param [options.all] Whether to use `querySelectorAll()` instead - default is false
446
+ * @param [options.continuous] Whether to call the listener continuously instead of just once - default is false
447
+ * @param [options.debounce] Whether to debounce the listener to reduce calls to `querySelector` or `querySelectorAll` - set undefined or <=0 to disable (default)
448
+ */
449
+ addListener(selector, options) {
450
+ options = __spreadValues({ all: false, continuous: false, debounce: 0 }, options);
451
+ if (options.debounce && options.debounce > 0 || this.observerOptions.defaultDebounce && this.observerOptions.defaultDebounce > 0) {
452
+ options.listener = this.debounce(
453
+ options.listener,
454
+ options.debounce || this.observerOptions.defaultDebounce
455
+ );
423
456
  }
457
+ if (this.listenerMap.has(selector))
458
+ this.listenerMap.get(selector).push(options);
459
+ else
460
+ this.listenerMap.set(selector, [options]);
461
+ this.checkSelector(selector, [options]);
424
462
  }
425
- }
426
- function initOnSelector(options = {}) {
427
- const observer = new MutationObserver(() => {
428
- for (const [selector, options2] of selectorMap.entries())
429
- checkSelectorExists(selector, options2);
430
- });
431
- observer.observe(document.body, __spreadValues({
432
- subtree: true,
433
- childList: true
434
- }, options));
435
- }
436
- function getSelectorMap() {
437
- return selectorMap;
438
- }
463
+ /** Disables the observation of the child elements */
464
+ disable() {
465
+ if (!this.enabled)
466
+ return;
467
+ this.enabled = false;
468
+ this.observer.disconnect();
469
+ }
470
+ /**
471
+ * Enables or reenables the observation of the child elements.
472
+ * @param immediatelyCheckSelectors Whether to immediately check if all previously registered selectors exist (default is true)
473
+ * @returns Returns true when the observation was enabled, false otherwise (e.g. when the base element wasn't found)
474
+ */
475
+ enable(immediatelyCheckSelectors = true) {
476
+ const baseElement = typeof this.baseElement === "string" ? document.querySelector(this.baseElement) : this.baseElement;
477
+ if (this.enabled || !baseElement)
478
+ return false;
479
+ this.enabled = true;
480
+ this.observer.observe(baseElement, this.observerOptions);
481
+ if (immediatelyCheckSelectors)
482
+ this.checkAllSelectors();
483
+ return true;
484
+ }
485
+ /** Returns whether the observation of the child elements is currently enabled */
486
+ isEnabled() {
487
+ return this.enabled;
488
+ }
489
+ /** Removes all listeners that have been registered with {@linkcode addListener()} */
490
+ clearListeners() {
491
+ this.listenerMap.clear();
492
+ }
493
+ /**
494
+ * Removes all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()}
495
+ * @returns Returns true when all listeners for the associated selector were found and removed, false otherwise
496
+ */
497
+ removeAllListeners(selector) {
498
+ return this.listenerMap.delete(selector);
499
+ }
500
+ /**
501
+ * Removes a single listener for the given {@linkcode selector} and {@linkcode options} that has been registered with {@linkcode addListener()}
502
+ * @returns Returns true when the listener was found and removed, false otherwise
503
+ */
504
+ removeListener(selector, options) {
505
+ const listeners = this.listenerMap.get(selector);
506
+ if (!listeners)
507
+ return false;
508
+ const index = listeners.indexOf(options);
509
+ if (index > -1) {
510
+ listeners.splice(index, 1);
511
+ return true;
512
+ }
513
+ return false;
514
+ }
515
+ /** Returns all listeners that have been registered with {@linkcode addListener()} */
516
+ getAllListeners() {
517
+ return this.listenerMap;
518
+ }
519
+ /** Returns all listeners for the given {@linkcode selector} that have been registered with {@linkcode addListener()} */
520
+ getListeners(selector) {
521
+ return this.listenerMap.get(selector);
522
+ }
523
+ };
439
524
 
440
525
  // lib/translation.ts
441
526
  var trans = {};
@@ -463,30 +548,29 @@ tr.getLanguage = () => {
463
548
  };
464
549
 
465
550
  exports.ConfigManager = ConfigManager;
551
+ exports.SelectorObserver = SelectorObserver;
466
552
  exports.addGlobalStyle = addGlobalStyle;
467
553
  exports.addParent = addParent;
468
- exports.amplifyMedia = amplifyMedia;
469
554
  exports.autoPlural = autoPlural;
470
555
  exports.clamp = clamp;
556
+ exports.compress = compress;
471
557
  exports.debounce = debounce;
558
+ exports.decompress = decompress;
472
559
  exports.fetchAdvanced = fetchAdvanced;
473
- exports.getSelectorMap = getSelectorMap;
474
560
  exports.getUnsafeWindow = getUnsafeWindow;
475
- exports.initOnSelector = initOnSelector;
476
561
  exports.insertAfter = insertAfter;
477
562
  exports.insertValues = insertValues;
478
563
  exports.interceptEvent = interceptEvent;
479
564
  exports.interceptWindowEvent = interceptWindowEvent;
480
565
  exports.isScrollable = isScrollable;
481
566
  exports.mapRange = mapRange;
482
- exports.onSelector = onSelector;
483
567
  exports.openInNewTab = openInNewTab;
484
568
  exports.pauseFor = pauseFor;
485
569
  exports.preloadImages = preloadImages;
486
570
  exports.randRange = randRange;
571
+ exports.randomId = randomId;
487
572
  exports.randomItem = randomItem;
488
573
  exports.randomItemIndex = randomItemIndex;
489
574
  exports.randomizeArray = randomizeArray;
490
- exports.removeOnSelector = removeOnSelector;
491
575
  exports.takeRandomItem = takeRandomItem;
492
576
  exports.tr = tr;