@sv443-network/userutils 1.1.0 → 1.1.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.
package/dist/index.js CHANGED
@@ -1,30 +1,428 @@
1
1
  'use strict';
2
2
 
3
- var v=Object.defineProperty,x=Object.defineProperties;var w=Object.getOwnPropertyDescriptors;var h=Object.getOwnPropertySymbols;var O=Object.prototype.hasOwnProperty,M=Object.prototype.propertyIsEnumerable;var p=(t,e,n)=>e in t?v(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,f=(t,e)=>{for(var n in e||(e={}))O.call(e,n)&&p(t,n,e[n]);if(h)for(var n of h(e))M.call(e,n)&&p(t,n,e[n]);return t},b=(t,e)=>x(t,w(e));var m=(t,e,n)=>(p(t,typeof e!="symbol"?e+"":e,n),n);var c=(t,e,n)=>new Promise((r,i)=>{var o=s=>{try{u(n.next(s));}catch(l){i(l);}},a=s=>{try{u(n.throw(s));}catch(l){i(l);}},u=s=>s.done?r(s.value):Promise.resolve(s.value).then(o,a);u((n=n.apply(t,e)).next());});function D(t,e,n){return Math.max(Math.min(t,n),e)}function L(t,e,n,r,i){return Number(e)===0&&Number(r)===0?t*(i/n):(t-e)*((i-r)/(n-e))+r}function g(...t){let e,n;if(typeof t[0]=="number"&&typeof t[1]=="number")[e,n]=t;else if(typeof t[0]=="number"&&typeof t[1]!="number")e=0,n=t[0];else throw new TypeError(`Wrong parameter(s) provided - expected: "number" and "number|undefined", got: "${typeof t[0]}" and "${typeof t[1]}"`);if(e=Number(e),n=Number(n),isNaN(e)||isNaN(n))throw new TypeError(`Parameters "min" and "max" can't be NaN`);if(e>n)throw new TypeError(`Parameter "min" can't be bigger than "max"`);return Math.floor(Math.random()*(n-e+1))+e}function V(t){return T(t)[0]}function T(t){if(t.length===0)return [void 0,void 0];let e=g(t.length-1);return [t[e],e]}function $(t){let[e,n]=T(t);if(n!==void 0)return t.splice(n,1),e}function k(t){let e=[...t];if(t.length===0)return t;for(let n=e.length-1;n>0;n--){let r=Math.floor(g(0,1e4)/1e4*(n+1));[e[n],e[r]]=[e[r],e[n]];}return e}var y=class{constructor(e){m(this,"id");m(this,"formatVersion");m(this,"defaultConfig");m(this,"cachedConfig");m(this,"migrations");this.id=e.id,this.formatVersion=e.formatVersion,this.defaultConfig=e.defaultConfig,this.cachedConfig=e.defaultConfig,this.migrations=e.migrations;}loadData(){return c(this,null,function*(){try{let e=yield GM.getValue(`_uucfg-${this.id}`,this.defaultConfig),n=Number(yield GM.getValue(`_uucfgver-${this.id}`));if(typeof e!="string")return yield this.saveDefaultData(),this.defaultConfig;isNaN(n)&&(yield GM.setValue(`_uucfgver-${this.id}`,n=this.formatVersion));let r=JSON.parse(e);return n<this.formatVersion&&this.migrations&&(r=yield this.runMigrations(r,n)),this.cachedConfig=typeof r=="object"?r:void 0}catch(e){return yield this.saveDefaultData(),this.defaultConfig}})}getData(){return this.deepCopy(this.cachedConfig)}setData(e){return this.cachedConfig=e,new Promise(n=>c(this,null,function*(){yield Promise.allSettled([GM.setValue(`_uucfg-${this.id}`,JSON.stringify(e)),GM.setValue(`_uucfgver-${this.id}`,this.formatVersion)]),n();}))}saveDefaultData(){return c(this,null,function*(){return this.cachedConfig=this.defaultConfig,new Promise(e=>c(this,null,function*(){yield Promise.allSettled([GM.setValue(`_uucfg-${this.id}`,JSON.stringify(this.defaultConfig)),GM.setValue(`_uucfgver-${this.id}`,this.formatVersion)]),e();}))})}deleteConfig(){return c(this,null,function*(){yield Promise.allSettled([GM.deleteValue(`_uucfg-${this.id}`),GM.deleteValue(`_uucfgver-${this.id}`)]);})}runMigrations(e,n){return c(this,null,function*(){if(!this.migrations)return e;let r=e,i=Object.entries(this.migrations).sort(([a],[u])=>Number(a)-Number(u)),o=n;for(let[a,u]of i){let s=Number(a);if(n<this.formatVersion&&n<s)try{let l=u(r);r=l instanceof Promise?yield l:l,o=n=s;}catch(l){console.error(`Error while running migration function for format version ${a}:`,l);}}return yield Promise.allSettled([GM.setValue(`_uucfg-${this.id}`,JSON.stringify(r)),GM.setValue(`_uucfgver-${this.id}`,o)]),r})}deepCopy(e){return JSON.parse(JSON.stringify(e))}};function S(){try{return unsafeWindow}catch(t){return window}}function _(t,e){var n;return (n=t.parentNode)==null||n.insertBefore(e,t.nextSibling),e}function j(t,e){let n=t.parentNode;if(!n)throw new Error("Element doesn't have a parent node");return n.replaceChild(e,t),e.appendChild(t),e}function W(t){let e=document.createElement("style");e.innerHTML=t,document.head.appendChild(e);}function F(t,e=!1){let n=t.map(r=>new Promise((i,o)=>{let a=new Image;a.src=r,a.addEventListener("load",()=>i(a)),a.addEventListener("error",u=>e&&o(u));}));return Promise.allSettled(n)}function H(t){let e=document.createElement("a");Object.assign(e,{className:"userutils-open-in-new-tab",target:"_blank",rel:"noopener noreferrer",href:t}),e.style.display="none",document.body.appendChild(e),e.click(),setTimeout(e.remove,50);}function C(t,e,n){typeof Error.stackTraceLimit=="number"&&Error.stackTraceLimit<1e3&&(Error.stackTraceLimit=1e3),function(r){t.__proto__.addEventListener=function(...i){var a,u;let o=typeof i[1]=="function"?i[1]:(u=(a=i[1])==null?void 0:a.handleEvent)!=null?u:()=>{};i[1]=function(...s){if(!(i[0]===e&&n(Array.isArray(s)?s[0]:s)))return o.apply(this,s)},r.apply(this,i);};}(t.__proto__.addEventListener);}function J(t,e){return C(S(),t,e)}function q(t,e=1){let n=new(window.AudioContext||window.webkitAudioContext),r={mediaElement:t,amplify:i=>{r.gain.gain.value=i;},getAmpLevel:()=>r.gain.gain.value,context:n,source:n.createMediaElementSource(t),gain:n.createGain()};return r.source.connect(r.gain),r.gain.connect(n.destination),r.amplify(e),r}function K(t){let{overflowX:e,overflowY:n}=getComputedStyle(t);return {vertical:(n==="scroll"||n==="auto")&&t.scrollHeight>t.clientHeight,horizontal:(e==="scroll"||e==="auto")&&t.scrollWidth>t.clientWidth}}function B(t,e){return (Array.isArray(e)||e instanceof NodeList)&&(e=e.length),`${t}${e===1?"":"s"}`}function U(t){return new Promise(e=>{setTimeout(()=>e(),t);})}function X(t,e=300){let n;return function(...r){clearTimeout(n),n=setTimeout(()=>t.apply(this,r),e);}}function Y(n){return c(this,arguments,function*(t,e={}){let{timeout:r=1e4}=e,i=new AbortController,o=setTimeout(()=>i.abort(),r),a=yield fetch(t,b(f({},e),{signal:i.signal}));return clearTimeout(o),a})}var d=new Map;function ee(t,e){let n=[];d.has(t)&&(n=d.get(t)),n.push(e),d.set(t,n),E(t,n);}function te(t){return d.delete(t)}function E(t,e){let n=[];if(e.forEach((r,i)=>{try{let o=r.all?document.querySelectorAll(t):document.querySelector(t);(o!==null&&o instanceof NodeList&&o.length>0||o!==null)&&(r.listener(o),r.continuous||n.push(i));}catch(o){console.error(`Couldn't call listener for selector '${t}'`,o);}}),n.length>0){let r=e.filter((i,o)=>!n.includes(o));r.length===0?d.delete(t):d.set(t,r);}}function ne(t={}){new MutationObserver(()=>{for(let[n,r]of d.entries())E(n,r);}).observe(document.body,f({subtree:!0,childList:!0},t));}function re(){return d}
4
-
5
- exports.ConfigManager = y;
6
- exports.addGlobalStyle = W;
7
- exports.addParent = j;
8
- exports.amplifyMedia = q;
9
- exports.autoPlural = B;
10
- exports.clamp = D;
11
- exports.debounce = X;
12
- exports.fetchAdvanced = Y;
13
- exports.getSelectorMap = re;
14
- exports.getUnsafeWindow = S;
15
- exports.initOnSelector = ne;
16
- exports.insertAfter = _;
17
- exports.interceptEvent = C;
18
- exports.interceptWindowEvent = J;
19
- exports.isScrollable = K;
20
- exports.mapRange = L;
21
- exports.onSelector = ee;
22
- exports.openInNewTab = H;
23
- exports.pauseFor = U;
24
- exports.preloadImages = F;
25
- exports.randRange = g;
26
- exports.randomItem = V;
27
- exports.randomItemIndex = T;
28
- exports.randomizeArray = k;
29
- exports.removeOnSelector = te;
30
- exports.takeRandomItem = $;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
9
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
10
+ var __spreadValues = (a, b) => {
11
+ for (var prop in b || (b = {}))
12
+ if (__hasOwnProp.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ if (__getOwnPropSymbols)
15
+ for (var prop of __getOwnPropSymbols(b)) {
16
+ if (__propIsEnum.call(b, prop))
17
+ __defNormalProp(a, prop, b[prop]);
18
+ }
19
+ return a;
20
+ };
21
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
22
+ var __publicField = (obj, key, value) => {
23
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
24
+ return value;
25
+ };
26
+ var __async = (__this, __arguments, generator) => {
27
+ return new Promise((resolve, reject) => {
28
+ var fulfilled = (value) => {
29
+ try {
30
+ step(generator.next(value));
31
+ } catch (e) {
32
+ reject(e);
33
+ }
34
+ };
35
+ var rejected = (value) => {
36
+ try {
37
+ step(generator.throw(value));
38
+ } catch (e) {
39
+ reject(e);
40
+ }
41
+ };
42
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
43
+ step((generator = generator.apply(__this, __arguments)).next());
44
+ });
45
+ };
46
+
47
+ // lib/math.ts
48
+ function clamp(value, min, max) {
49
+ return Math.max(Math.min(value, max), min);
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;
55
+ }
56
+ function randRange(...args) {
57
+ let min, max;
58
+ if (typeof args[0] === "number" && typeof args[1] === "number") {
59
+ [min, max] = args;
60
+ } else if (typeof args[0] === "number" && typeof args[1] !== "number") {
61
+ min = 0;
62
+ max = args[0];
63
+ } else
64
+ throw new TypeError(`Wrong parameter(s) provided - expected: "number" and "number|undefined", got: "${typeof args[0]}" and "${typeof args[1]}"`);
65
+ min = Number(min);
66
+ max = Number(max);
67
+ if (isNaN(min) || isNaN(max))
68
+ throw new TypeError(`Parameters "min" and "max" can't be NaN`);
69
+ if (min > max)
70
+ throw new TypeError(`Parameter "min" can't be bigger than "max"`);
71
+ return Math.floor(Math.random() * (max - min + 1)) + min;
72
+ }
73
+
74
+ // lib/array.ts
75
+ function randomItem(array) {
76
+ return randomItemIndex(array)[0];
77
+ }
78
+ function randomItemIndex(array) {
79
+ if (array.length === 0)
80
+ return [void 0, void 0];
81
+ const idx = randRange(array.length - 1);
82
+ return [array[idx], idx];
83
+ }
84
+ function takeRandomItem(arr) {
85
+ const [itm, idx] = randomItemIndex(arr);
86
+ if (idx === void 0)
87
+ return void 0;
88
+ arr.splice(idx, 1);
89
+ return itm;
90
+ }
91
+ function randomizeArray(array) {
92
+ const retArray = [...array];
93
+ if (array.length === 0)
94
+ return array;
95
+ for (let i = retArray.length - 1; i > 0; i--) {
96
+ const j = Math.floor(randRange(0, 1e4) / 1e4 * (i + 1));
97
+ [retArray[i], retArray[j]] = [retArray[j], retArray[i]];
98
+ }
99
+ return retArray;
100
+ }
101
+
102
+ // lib/config.ts
103
+ var ConfigManager = class {
104
+ /**
105
+ * Creates an instance of ConfigManager to manage a user configuration that is cached in memory and persistently saved across sessions.
106
+ * 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
+ *
108
+ * ⚠️ 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`
110
+ *
111
+ * @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
+ * @param options The options for this ConfigManager instance
113
+ */
114
+ constructor(options) {
115
+ __publicField(this, "id");
116
+ __publicField(this, "formatVersion");
117
+ __publicField(this, "defaultConfig");
118
+ __publicField(this, "cachedConfig");
119
+ __publicField(this, "migrations");
120
+ this.id = options.id;
121
+ this.formatVersion = options.formatVersion;
122
+ this.defaultConfig = options.defaultConfig;
123
+ this.cachedConfig = options.defaultConfig;
124
+ this.migrations = options.migrations;
125
+ }
126
+ /**
127
+ * Loads the data saved in persistent storage into the in-memory cache and also returns it.
128
+ * Automatically populates persistent storage with default data if it doesn't contain any data yet.
129
+ * Also runs all necessary migration functions if the data format has changed since the last time the data was saved.
130
+ */
131
+ loadData() {
132
+ return __async(this, null, function* () {
133
+ try {
134
+ const gmData = yield GM.getValue(`_uucfg-${this.id}`, this.defaultConfig);
135
+ let gmFmtVer = Number(yield GM.getValue(`_uucfgver-${this.id}`));
136
+ if (typeof gmData !== "string") {
137
+ yield this.saveDefaultData();
138
+ return this.defaultConfig;
139
+ }
140
+ if (isNaN(gmFmtVer))
141
+ yield GM.setValue(`_uucfgver-${this.id}`, gmFmtVer = this.formatVersion);
142
+ let parsed = JSON.parse(gmData);
143
+ if (gmFmtVer < this.formatVersion && this.migrations)
144
+ parsed = yield this.runMigrations(parsed, gmFmtVer);
145
+ return this.cachedConfig = typeof parsed === "object" ? parsed : void 0;
146
+ } catch (err) {
147
+ yield this.saveDefaultData();
148
+ return this.defaultConfig;
149
+ }
150
+ });
151
+ }
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). */
153
+ getData() {
154
+ return this.deepCopy(this.cachedConfig);
155
+ }
156
+ /** Saves the data synchronously to the in-memory cache and asynchronously to the persistent storage */
157
+ setData(data) {
158
+ this.cachedConfig = data;
159
+ return new Promise((resolve) => __async(this, null, function* () {
160
+ yield Promise.all([
161
+ GM.setValue(`_uucfg-${this.id}`, JSON.stringify(data)),
162
+ GM.setValue(`_uucfgver-${this.id}`, this.formatVersion)
163
+ ]);
164
+ resolve();
165
+ }));
166
+ }
167
+ /** Saves the default configuration data passed in the constructor synchronously to the in-memory cache and asynchronously to persistent storage */
168
+ saveDefaultData() {
169
+ return __async(this, null, function* () {
170
+ this.cachedConfig = this.defaultConfig;
171
+ return new Promise((resolve) => __async(this, null, function* () {
172
+ yield Promise.all([
173
+ GM.setValue(`_uucfg-${this.id}`, JSON.stringify(this.defaultConfig)),
174
+ GM.setValue(`_uucfgver-${this.id}`, this.formatVersion)
175
+ ]);
176
+ resolve();
177
+ }));
178
+ });
179
+ }
180
+ /**
181
+ * 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.
184
+ *
185
+ * ⚠️ This requires the additional directive `@grant GM.deleteValue`
186
+ */
187
+ deleteConfig() {
188
+ return __async(this, null, function* () {
189
+ yield Promise.all([
190
+ GM.deleteValue(`_uucfg-${this.id}`),
191
+ GM.deleteValue(`_uucfgver-${this.id}`)
192
+ ]);
193
+ });
194
+ }
195
+ /** Runs all necessary migration functions consecutively - may be overwritten in a subclass */
196
+ runMigrations(oldData, oldFmtVer) {
197
+ return __async(this, null, function* () {
198
+ if (!this.migrations)
199
+ return oldData;
200
+ let newData = oldData;
201
+ const sortedMigrations = Object.entries(this.migrations).sort(([a], [b]) => Number(a) - Number(b));
202
+ let lastFmtVer = oldFmtVer;
203
+ for (const [fmtVer, migrationFunc] of sortedMigrations) {
204
+ const ver = Number(fmtVer);
205
+ if (oldFmtVer < this.formatVersion && oldFmtVer < ver) {
206
+ try {
207
+ const migRes = migrationFunc(newData);
208
+ newData = migRes instanceof Promise ? yield migRes : migRes;
209
+ lastFmtVer = oldFmtVer = ver;
210
+ } catch (err) {
211
+ console.error(`Error while running migration function for format version ${fmtVer}:`, err);
212
+ }
213
+ }
214
+ }
215
+ yield Promise.all([
216
+ GM.setValue(`_uucfg-${this.id}`, JSON.stringify(newData)),
217
+ GM.setValue(`_uucfgver-${this.id}`, lastFmtVer)
218
+ ]);
219
+ return newData;
220
+ });
221
+ }
222
+ /** Copies a JSON-compatible object and loses its internal references */
223
+ deepCopy(obj) {
224
+ return JSON.parse(JSON.stringify(obj));
225
+ }
226
+ };
227
+
228
+ // lib/dom.ts
229
+ function getUnsafeWindow() {
230
+ try {
231
+ return unsafeWindow;
232
+ } catch (e) {
233
+ return window;
234
+ }
235
+ }
236
+ function insertAfter(beforeElement, afterElement) {
237
+ var _a;
238
+ (_a = beforeElement.parentNode) == null ? void 0 : _a.insertBefore(afterElement, beforeElement.nextSibling);
239
+ return afterElement;
240
+ }
241
+ function addParent(element, newParent) {
242
+ const oldParent = element.parentNode;
243
+ if (!oldParent)
244
+ throw new Error("Element doesn't have a parent node");
245
+ oldParent.replaceChild(newParent, element);
246
+ newParent.appendChild(element);
247
+ return newParent;
248
+ }
249
+ function addGlobalStyle(style) {
250
+ const styleElem = document.createElement("style");
251
+ styleElem.innerHTML = style;
252
+ document.head.appendChild(styleElem);
253
+ }
254
+ function preloadImages(srcUrls, rejects = false) {
255
+ const promises = srcUrls.map((src) => new Promise((res, rej) => {
256
+ const image = new Image();
257
+ image.src = src;
258
+ image.addEventListener("load", () => res(image));
259
+ image.addEventListener("error", (evt) => rejects && rej(evt));
260
+ }));
261
+ return Promise.allSettled(promises);
262
+ }
263
+ function openInNewTab(href) {
264
+ const openElem = document.createElement("a");
265
+ Object.assign(openElem, {
266
+ className: "userutils-open-in-new-tab",
267
+ target: "_blank",
268
+ rel: "noopener noreferrer",
269
+ href
270
+ });
271
+ openElem.style.display = "none";
272
+ document.body.appendChild(openElem);
273
+ openElem.click();
274
+ setTimeout(openElem.remove, 50);
275
+ }
276
+ function interceptEvent(eventObject, eventName, predicate) {
277
+ if (typeof Error.stackTraceLimit === "number" && Error.stackTraceLimit < 1e3) {
278
+ Error.stackTraceLimit = 1e3;
279
+ }
280
+ (function(original) {
281
+ eventObject.__proto__.addEventListener = function(...args) {
282
+ var _a, _b;
283
+ const origListener = typeof args[1] === "function" ? args[1] : (_b = (_a = args[1]) == null ? void 0 : _a.handleEvent) != null ? _b : () => void 0;
284
+ args[1] = function(...a) {
285
+ if (args[0] === eventName && predicate(Array.isArray(a) ? a[0] : a))
286
+ return;
287
+ else
288
+ return origListener.apply(this, a);
289
+ };
290
+ original.apply(this, args);
291
+ };
292
+ })(eventObject.__proto__.addEventListener);
293
+ }
294
+ function interceptWindowEvent(eventName, predicate) {
295
+ return interceptEvent(getUnsafeWindow(), eventName, predicate);
296
+ }
297
+ function amplifyMedia(mediaElement, multiplier = 1) {
298
+ const context = new (window.AudioContext || window.webkitAudioContext)();
299
+ const result = {
300
+ mediaElement,
301
+ amplify: (multiplier2) => {
302
+ result.gain.gain.value = multiplier2;
303
+ },
304
+ getAmpLevel: () => result.gain.gain.value,
305
+ context,
306
+ source: context.createMediaElementSource(mediaElement),
307
+ gain: context.createGain()
308
+ };
309
+ result.source.connect(result.gain);
310
+ result.gain.connect(context.destination);
311
+ result.amplify(multiplier);
312
+ return result;
313
+ }
314
+ function isScrollable(element) {
315
+ const { overflowX, overflowY } = getComputedStyle(element);
316
+ return {
317
+ vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
318
+ horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth
319
+ };
320
+ }
321
+
322
+ // lib/misc.ts
323
+ function autoPlural(word, num) {
324
+ if (Array.isArray(num) || num instanceof NodeList)
325
+ num = num.length;
326
+ return `${word}${num === 1 ? "" : "s"}`;
327
+ }
328
+ function pauseFor(time) {
329
+ return new Promise((res) => {
330
+ setTimeout(() => res(), time);
331
+ });
332
+ }
333
+ function debounce(func, timeout = 300) {
334
+ let timer;
335
+ return function(...args) {
336
+ clearTimeout(timer);
337
+ timer = setTimeout(() => func.apply(this, args), timeout);
338
+ };
339
+ }
340
+ function fetchAdvanced(_0) {
341
+ return __async(this, arguments, function* (url, options = {}) {
342
+ const { timeout = 1e4 } = options;
343
+ const controller = new AbortController();
344
+ const id = setTimeout(() => controller.abort(), timeout);
345
+ const res = yield fetch(url, __spreadProps(__spreadValues({}, options), {
346
+ signal: controller.signal
347
+ }));
348
+ clearTimeout(id);
349
+ return res;
350
+ });
351
+ }
352
+
353
+ // lib/onSelector.ts
354
+ var selectorMap = /* @__PURE__ */ new Map();
355
+ function onSelector(selector, options) {
356
+ let selectorMapItems = [];
357
+ if (selectorMap.has(selector))
358
+ selectorMapItems = selectorMap.get(selector);
359
+ selectorMapItems.push(options);
360
+ selectorMap.set(selector, selectorMapItems);
361
+ checkSelectorExists(selector, selectorMapItems);
362
+ }
363
+ function removeOnSelector(selector) {
364
+ return selectorMap.delete(selector);
365
+ }
366
+ function checkSelectorExists(selector, options) {
367
+ const deleteIndices = [];
368
+ options.forEach((option, i) => {
369
+ try {
370
+ const elements = option.all ? document.querySelectorAll(selector) : document.querySelector(selector);
371
+ if (elements !== null && elements instanceof NodeList && elements.length > 0 || elements !== null) {
372
+ option.listener(elements);
373
+ if (!option.continuous)
374
+ deleteIndices.push(i);
375
+ }
376
+ } catch (err) {
377
+ console.error(`Couldn't call listener for selector '${selector}'`, err);
378
+ }
379
+ });
380
+ if (deleteIndices.length > 0) {
381
+ const newOptsArray = options.filter((_, i) => !deleteIndices.includes(i));
382
+ if (newOptsArray.length === 0)
383
+ selectorMap.delete(selector);
384
+ else {
385
+ selectorMap.set(selector, newOptsArray);
386
+ }
387
+ }
388
+ }
389
+ function initOnSelector(options = {}) {
390
+ const observer = new MutationObserver(() => {
391
+ for (const [selector, options2] of selectorMap.entries())
392
+ checkSelectorExists(selector, options2);
393
+ });
394
+ observer.observe(document.body, __spreadValues({
395
+ subtree: true,
396
+ childList: true
397
+ }, options));
398
+ }
399
+ function getSelectorMap() {
400
+ return selectorMap;
401
+ }
402
+
403
+ exports.ConfigManager = ConfigManager;
404
+ exports.addGlobalStyle = addGlobalStyle;
405
+ exports.addParent = addParent;
406
+ exports.amplifyMedia = amplifyMedia;
407
+ exports.autoPlural = autoPlural;
408
+ exports.clamp = clamp;
409
+ exports.debounce = debounce;
410
+ exports.fetchAdvanced = fetchAdvanced;
411
+ exports.getSelectorMap = getSelectorMap;
412
+ exports.getUnsafeWindow = getUnsafeWindow;
413
+ exports.initOnSelector = initOnSelector;
414
+ exports.insertAfter = insertAfter;
415
+ exports.interceptEvent = interceptEvent;
416
+ exports.interceptWindowEvent = interceptWindowEvent;
417
+ exports.isScrollable = isScrollable;
418
+ exports.mapRange = mapRange;
419
+ exports.onSelector = onSelector;
420
+ exports.openInNewTab = openInNewTab;
421
+ exports.pauseFor = pauseFor;
422
+ exports.preloadImages = preloadImages;
423
+ exports.randRange = randRange;
424
+ exports.randomItem = randomItem;
425
+ exports.randomItemIndex = randomItemIndex;
426
+ exports.randomizeArray = randomizeArray;
427
+ exports.removeOnSelector = removeOnSelector;
428
+ exports.takeRandomItem = takeRandomItem;