@whitesev/utils 2.6.6 → 2.6.7

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.
@@ -3721,7 +3721,7 @@ var Utils = (function () {
3721
3721
  * 解锁
3722
3722
  */
3723
3723
  this.unlock = function () {
3724
- setTimeout(() => {
3724
+ utils.workerSetTimeout(() => {
3725
3725
  that.#flag = false;
3726
3726
  }, that.#delayTime);
3727
3727
  };
@@ -4604,6 +4604,251 @@ var Utils = (function () {
4604
4604
  }
4605
4605
  }
4606
4606
 
4607
+ const createCache = (lastNumberWeakMap) => {
4608
+ return (collection, nextNumber) => {
4609
+ lastNumberWeakMap.set(collection, nextNumber);
4610
+ return nextNumber;
4611
+ };
4612
+ };
4613
+
4614
+ /*
4615
+ * The value of the constant Number.MAX_SAFE_INTEGER equals (2 ** 53 - 1) but it
4616
+ * is fairly new.
4617
+ */
4618
+ const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER === undefined ? 9007199254740991 : Number.MAX_SAFE_INTEGER;
4619
+ const TWO_TO_THE_POWER_OF_TWENTY_NINE = 536870912;
4620
+ const TWO_TO_THE_POWER_OF_THIRTY = TWO_TO_THE_POWER_OF_TWENTY_NINE * 2;
4621
+ const createGenerateUniqueNumber = (cache, lastNumberWeakMap) => {
4622
+ return (collection) => {
4623
+ const lastNumber = lastNumberWeakMap.get(collection);
4624
+ /*
4625
+ * Let's try the cheapest algorithm first. It might fail to produce a new
4626
+ * number, but it is so cheap that it is okay to take the risk. Just
4627
+ * increase the last number by one or reset it to 0 if we reached the upper
4628
+ * bound of SMIs (which stands for small integers). When the last number is
4629
+ * unknown it is assumed that the collection contains zero based consecutive
4630
+ * numbers.
4631
+ */
4632
+ let nextNumber = lastNumber === undefined ? collection.size : lastNumber < TWO_TO_THE_POWER_OF_THIRTY ? lastNumber + 1 : 0;
4633
+ if (!collection.has(nextNumber)) {
4634
+ return cache(collection, nextNumber);
4635
+ }
4636
+ /*
4637
+ * If there are less than half of 2 ** 30 numbers stored in the collection,
4638
+ * the chance to generate a new random number in the range from 0 to 2 ** 30
4639
+ * is at least 50%. It's benifitial to use only SMIs because they perform
4640
+ * much better in any environment based on V8.
4641
+ */
4642
+ if (collection.size < TWO_TO_THE_POWER_OF_TWENTY_NINE) {
4643
+ while (collection.has(nextNumber)) {
4644
+ nextNumber = Math.floor(Math.random() * TWO_TO_THE_POWER_OF_THIRTY);
4645
+ }
4646
+ return cache(collection, nextNumber);
4647
+ }
4648
+ // Quickly check if there is a theoretical chance to generate a new number.
4649
+ if (collection.size > MAX_SAFE_INTEGER) {
4650
+ throw new Error('Congratulations, you created a collection of unique numbers which uses all available integers!');
4651
+ }
4652
+ // Otherwise use the full scale of safely usable integers.
4653
+ while (collection.has(nextNumber)) {
4654
+ nextNumber = Math.floor(Math.random() * MAX_SAFE_INTEGER);
4655
+ }
4656
+ return cache(collection, nextNumber);
4657
+ };
4658
+ };
4659
+
4660
+ const LAST_NUMBER_WEAK_MAP = new WeakMap();
4661
+ const cache = createCache(LAST_NUMBER_WEAK_MAP);
4662
+ const generateUniqueNumber = createGenerateUniqueNumber(cache, LAST_NUMBER_WEAK_MAP);
4663
+
4664
+ const isMessagePort = (sender) => {
4665
+ return typeof sender.start === 'function';
4666
+ };
4667
+
4668
+ const PORT_MAP = new WeakMap();
4669
+
4670
+ const extendBrokerImplementation = (partialBrokerImplementation) => ({
4671
+ ...partialBrokerImplementation,
4672
+ connect: ({ call }) => {
4673
+ return async () => {
4674
+ const { port1, port2 } = new MessageChannel();
4675
+ const portId = await call('connect', { port: port1 }, [port1]);
4676
+ PORT_MAP.set(port2, portId);
4677
+ return port2;
4678
+ };
4679
+ },
4680
+ disconnect: ({ call }) => {
4681
+ return async (port) => {
4682
+ const portId = PORT_MAP.get(port);
4683
+ if (portId === undefined) {
4684
+ throw new Error('The given port is not connected.');
4685
+ }
4686
+ await call('disconnect', { portId });
4687
+ };
4688
+ },
4689
+ isSupported: ({ call }) => {
4690
+ return () => call('isSupported');
4691
+ }
4692
+ });
4693
+
4694
+ const ONGOING_REQUESTS = new WeakMap();
4695
+ const createOrGetOngoingRequests = (sender) => {
4696
+ if (ONGOING_REQUESTS.has(sender)) {
4697
+ // @todo TypeScript needs to be convinced that has() works as expected.
4698
+ return ONGOING_REQUESTS.get(sender);
4699
+ }
4700
+ const ongoingRequests = new Map();
4701
+ ONGOING_REQUESTS.set(sender, ongoingRequests);
4702
+ return ongoingRequests;
4703
+ };
4704
+ const createBroker = (brokerImplementation) => {
4705
+ const fullBrokerImplementation = extendBrokerImplementation(brokerImplementation);
4706
+ return (sender) => {
4707
+ const ongoingRequests = createOrGetOngoingRequests(sender);
4708
+ sender.addEventListener('message', (({ data: message }) => {
4709
+ const { id } = message;
4710
+ if (id !== null && ongoingRequests.has(id)) {
4711
+ const { reject, resolve } = ongoingRequests.get(id);
4712
+ ongoingRequests.delete(id);
4713
+ if (message.error === undefined) {
4714
+ resolve(message.result);
4715
+ }
4716
+ else {
4717
+ reject(new Error(message.error.message));
4718
+ }
4719
+ }
4720
+ }));
4721
+ if (isMessagePort(sender)) {
4722
+ sender.start();
4723
+ }
4724
+ const call = (method, params = null, transferables = []) => {
4725
+ return new Promise((resolve, reject) => {
4726
+ const id = generateUniqueNumber(ongoingRequests);
4727
+ ongoingRequests.set(id, { reject, resolve });
4728
+ if (params === null) {
4729
+ sender.postMessage({ id, method }, transferables);
4730
+ }
4731
+ else {
4732
+ sender.postMessage({ id, method, params }, transferables);
4733
+ }
4734
+ });
4735
+ };
4736
+ const notify = (method, params, transferables = []) => {
4737
+ sender.postMessage({ id: null, method, params }, transferables);
4738
+ };
4739
+ let functions = {};
4740
+ for (const [key, handler] of Object.entries(fullBrokerImplementation)) {
4741
+ functions = { ...functions, [key]: handler({ call, notify }) };
4742
+ }
4743
+ return { ...functions };
4744
+ };
4745
+ };
4746
+
4747
+ // Prefilling the Maps with a function indexed by zero is necessary to be compliant with the specification.
4748
+ const scheduledIntervalsState = new Map([[0, null]]); // tslint:disable-line no-empty
4749
+ const scheduledTimeoutsState = new Map([[0, null]]); // tslint:disable-line no-empty
4750
+ const wrap = createBroker({
4751
+ clearInterval: ({ call }) => {
4752
+ return (timerId) => {
4753
+ if (typeof scheduledIntervalsState.get(timerId) === 'symbol') {
4754
+ scheduledIntervalsState.set(timerId, null);
4755
+ call('clear', { timerId, timerType: 'interval' }).then(() => {
4756
+ scheduledIntervalsState.delete(timerId);
4757
+ });
4758
+ }
4759
+ };
4760
+ },
4761
+ clearTimeout: ({ call }) => {
4762
+ return (timerId) => {
4763
+ if (typeof scheduledTimeoutsState.get(timerId) === 'symbol') {
4764
+ scheduledTimeoutsState.set(timerId, null);
4765
+ call('clear', { timerId, timerType: 'timeout' }).then(() => {
4766
+ scheduledTimeoutsState.delete(timerId);
4767
+ });
4768
+ }
4769
+ };
4770
+ },
4771
+ setInterval: ({ call }) => {
4772
+ return (func, delay = 0, ...args) => {
4773
+ const symbol = Symbol();
4774
+ const timerId = generateUniqueNumber(scheduledIntervalsState);
4775
+ scheduledIntervalsState.set(timerId, symbol);
4776
+ const schedule = () => call('set', {
4777
+ delay,
4778
+ now: performance.timeOrigin + performance.now(),
4779
+ timerId,
4780
+ timerType: 'interval'
4781
+ }).then(() => {
4782
+ const state = scheduledIntervalsState.get(timerId);
4783
+ if (state === undefined) {
4784
+ throw new Error('The timer is in an undefined state.');
4785
+ }
4786
+ if (state === symbol) {
4787
+ func(...args);
4788
+ // Doublecheck if the interval should still be rescheduled because it could have been cleared inside of func().
4789
+ if (scheduledIntervalsState.get(timerId) === symbol) {
4790
+ schedule();
4791
+ }
4792
+ }
4793
+ });
4794
+ schedule();
4795
+ return timerId;
4796
+ };
4797
+ },
4798
+ setTimeout: ({ call }) => {
4799
+ return (func, delay = 0, ...args) => {
4800
+ const symbol = Symbol();
4801
+ const timerId = generateUniqueNumber(scheduledTimeoutsState);
4802
+ scheduledTimeoutsState.set(timerId, symbol);
4803
+ call('set', {
4804
+ delay,
4805
+ now: performance.timeOrigin + performance.now(),
4806
+ timerId,
4807
+ timerType: 'timeout'
4808
+ }).then(() => {
4809
+ const state = scheduledTimeoutsState.get(timerId);
4810
+ if (state === undefined) {
4811
+ throw new Error('The timer is in an undefined state.');
4812
+ }
4813
+ if (state === symbol) {
4814
+ // A timeout can be savely deleted because it is only called once.
4815
+ scheduledTimeoutsState.delete(timerId);
4816
+ func(...args);
4817
+ }
4818
+ });
4819
+ return timerId;
4820
+ };
4821
+ }
4822
+ });
4823
+ const load = (url) => {
4824
+ const worker = new Worker(url);
4825
+ return wrap(worker);
4826
+ };
4827
+
4828
+ const createLoadOrReturnBroker = (loadBroker, worker) => {
4829
+ let broker = null;
4830
+ return () => {
4831
+ if (broker !== null) {
4832
+ return broker;
4833
+ }
4834
+ const blob = new Blob([worker], { type: 'application/javascript; charset=utf-8' });
4835
+ const url = URL.createObjectURL(blob);
4836
+ broker = loadBroker(url);
4837
+ // Bug #1: Edge up until v18 didn't like the URL to be revoked directly.
4838
+ setTimeout(() => URL.revokeObjectURL(url));
4839
+ return broker;
4840
+ };
4841
+ };
4842
+
4843
+ // This is the minified and stringified code of the worker-timers-worker package.
4844
+ const worker = `(()=>{var e={455:function(e,t){!function(e){"use strict";var t=function(e){return function(t){var r=e(t);return t.add(r),r}},r=function(e){return function(t,r){return e.set(t,r),r}},n=void 0===Number.MAX_SAFE_INTEGER?9007199254740991:Number.MAX_SAFE_INTEGER,o=536870912,s=2*o,a=function(e,t){return function(r){var a=t.get(r),i=void 0===a?r.size:a<s?a+1:0;if(!r.has(i))return e(r,i);if(r.size<o){for(;r.has(i);)i=Math.floor(Math.random()*s);return e(r,i)}if(r.size>n)throw new Error("Congratulations, you created a collection of unique numbers which uses all available integers!");for(;r.has(i);)i=Math.floor(Math.random()*n);return e(r,i)}},i=new WeakMap,u=r(i),c=a(u,i),d=t(c);e.addUniqueNumber=d,e.generateUniqueNumber=c}(t)}},t={};function r(n){var o=t[n];if(void 0!==o)return o.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,r),s.exports}(()=>{"use strict";const e=-32603,t=-32602,n=-32601,o=(e,t)=>Object.assign(new Error(e),{status:t}),s=t=>o('The handler of the method called "'.concat(t,'" returned an unexpected result.'),e),a=(t,r)=>async({data:{id:a,method:i,params:u}})=>{const c=r[i];try{if(void 0===c)throw(e=>o('The requested method called "'.concat(e,'" is not supported.'),n))(i);const r=void 0===u?c():c(u);if(void 0===r)throw(t=>o('The handler of the method called "'.concat(t,'" returned no required result.'),e))(i);const d=r instanceof Promise?await r:r;if(null===a){if(void 0!==d.result)throw s(i)}else{if(void 0===d.result)throw s(i);const{result:e,transferables:r=[]}=d;t.postMessage({id:a,result:e},r)}}catch(e){const{message:r,status:n=-32603}=e;t.postMessage({error:{code:n,message:r},id:a})}};var i=r(455);const u=new Map,c=(e,r,n)=>({...r,connect:({port:t})=>{t.start();const n=e(t,r),o=(0,i.generateUniqueNumber)(u);return u.set(o,(()=>{n(),t.close(),u.delete(o)})),{result:o}},disconnect:({portId:e})=>{const r=u.get(e);if(void 0===r)throw(e=>o('The specified parameter called "portId" with the given value "'.concat(e,'" does not identify a port connected to this worker.'),t))(e);return r(),{result:null}},isSupported:async()=>{if(await new Promise((e=>{const t=new ArrayBuffer(0),{port1:r,port2:n}=new MessageChannel;r.onmessage=({data:t})=>e(null!==t),n.postMessage(t,[t])}))){const e=n();return{result:e instanceof Promise?await e:e}}return{result:!1}}}),d=(e,t,r=()=>!0)=>{const n=c(d,t,r),o=a(e,n);return e.addEventListener("message",o),()=>e.removeEventListener("message",o)},l=e=>t=>{const r=e.get(t);if(void 0===r)return Promise.resolve(!1);const[n,o]=r;return clearTimeout(n),e.delete(t),o(!1),Promise.resolve(!0)},f=(e,t,r)=>(n,o,s)=>{const{expected:a,remainingDelay:i}=e(n,o);return new Promise((e=>{t.set(s,[setTimeout(r,i,a,t,e,s),e])}))},m=(e,t)=>{const r=performance.now(),n=e+t-r-performance.timeOrigin;return{expected:r+n,remainingDelay:n}},p=(e,t,r,n)=>{const o=e-performance.now();o>0?t.set(n,[setTimeout(p,o,e,t,r,n),r]):(t.delete(n),r(!0))},h=new Map,v=l(h),w=new Map,g=l(w),M=f(m,h,p),y=f(m,w,p);d(self,{clear:async({timerId:e,timerType:t})=>({result:await("interval"===t?v(e):g(e))}),set:async({delay:e,now:t,timerId:r,timerType:n})=>({result:await("interval"===n?M:y)(e,t,r)})})})()})();`; // tslint:disable-line:max-line-length
4845
+
4846
+ const loadOrReturnBroker = createLoadOrReturnBroker(load, worker);
4847
+ const clearInterval = (timerId) => loadOrReturnBroker().clearInterval(timerId);
4848
+ const clearTimeout = (timerId) => loadOrReturnBroker().clearTimeout(timerId);
4849
+ const setInterval = (...args) => loadOrReturnBroker().setInterval(...args);
4850
+ const setTimeout$1 = (...args) => loadOrReturnBroker().setTimeout(...args);
4851
+
4607
4852
  // ==UserScript==
4608
4853
  // @name ModuleRaid.js
4609
4854
  // @namespace http://tampermonkey.net/
@@ -5008,7 +5253,7 @@ var Utils = (function () {
5008
5253
  this.windowApi = new WindowApi(option);
5009
5254
  }
5010
5255
  /** 版本号 */
5011
- version = "2025.4.11";
5256
+ version = "2025.5.26";
5012
5257
  addStyle(cssText) {
5013
5258
  if (typeof cssText !== "string") {
5014
5259
  throw new Error("Utils.addStyle 参数cssText 必须为String类型");
@@ -5253,11 +5498,11 @@ var Utils = (function () {
5253
5498
  }
5254
5499
  debounce(fn, delay = 0) {
5255
5500
  let timer = null;
5256
- const context = this;
5501
+ let UtilsContext = this;
5257
5502
  return function (...args) {
5258
- clearTimeout(timer);
5259
- timer = setTimeout(function () {
5260
- fn.apply(context, args);
5503
+ UtilsContext.workerClearTimeout(timer);
5504
+ timer = UtilsContext.workerSetTimeout(function () {
5505
+ fn.apply(UtilsContext, args);
5261
5506
  }, delay);
5262
5507
  };
5263
5508
  }
@@ -5294,6 +5539,7 @@ var Utils = (function () {
5294
5539
  **/
5295
5540
  Dictionary = UtilsDictionary;
5296
5541
  dispatchEvent(element, eventName, details) {
5542
+ // let UtilsContext = this;
5297
5543
  let eventNameList = [];
5298
5544
  if (typeof eventName === "string") {
5299
5545
  eventNameList = [eventName];
@@ -5310,6 +5556,7 @@ var Utils = (function () {
5310
5556
  });
5311
5557
  }
5312
5558
  downloadBase64(base64Data, fileName, isIFrame = false) {
5559
+ let UtilsContext = this;
5313
5560
  if (typeof base64Data !== "string") {
5314
5561
  throw new Error("Utils.downloadBase64 参数 base64Data 必须为 string 类型");
5315
5562
  }
@@ -5322,7 +5569,7 @@ var Utils = (function () {
5322
5569
  iframeElement.style.display = "none";
5323
5570
  iframeElement.src = base64Data;
5324
5571
  this.windowApi.document.body.appendChild(iframeElement);
5325
- setTimeout(() => {
5572
+ UtilsContext.workerSetTimeout(() => {
5326
5573
  iframeElement.contentWindow.document.execCommand("SaveAs", true, fileName);
5327
5574
  this.windowApi.document.body.removeChild(iframeElement);
5328
5575
  }, 100);
@@ -7280,17 +7527,18 @@ var Utils = (function () {
7280
7527
  throw new TypeError("Utils.setTimeout 参数 delayTime 必须为 number 类型");
7281
7528
  }
7282
7529
  return new Promise((resolve) => {
7283
- setTimeout(() => {
7530
+ UtilsContext.workerSetTimeout(() => {
7284
7531
  resolve(UtilsContext.tryCatch().run(callback));
7285
7532
  }, delayTime);
7286
7533
  });
7287
7534
  }
7288
7535
  sleep(delayTime = 0) {
7536
+ let UtilsContext = this;
7289
7537
  if (typeof delayTime !== "number") {
7290
7538
  throw new Error("Utils.sleep 参数 delayTime 必须为 number 类型");
7291
7539
  }
7292
7540
  return new Promise((resolve) => {
7293
- setTimeout(() => {
7541
+ UtilsContext.workerSetTimeout(() => {
7294
7542
  resolve(undefined);
7295
7543
  }, delayTime);
7296
7544
  });
@@ -7654,7 +7902,7 @@ var Utils = (function () {
7654
7902
  },
7655
7903
  });
7656
7904
  if (__timeout__ > 0) {
7657
- setTimeout(() => {
7905
+ UtilsContext.workerSetTimeout(() => {
7658
7906
  // 取消观察器
7659
7907
  if (typeof observer?.disconnect === "function") {
7660
7908
  observer.disconnect();
@@ -7976,12 +8224,13 @@ var Utils = (function () {
7976
8224
  });
7977
8225
  }
7978
8226
  waitPropertyByInterval(checkObj, checkPropertyName, intervalTimer = 250, maxTime = -1) {
8227
+ let UtilsContext = this;
7979
8228
  if (checkObj == null) {
7980
8229
  throw new TypeError("checkObj 不能为空对象 ");
7981
8230
  }
7982
8231
  let isResolve = false;
7983
8232
  return new Promise((resolve, reject) => {
7984
- let interval = setInterval(() => {
8233
+ let interval = UtilsContext.workerSetInterval(() => {
7985
8234
  let obj = checkObj;
7986
8235
  if (typeof checkObj === "function") {
7987
8236
  obj = checkObj();
@@ -7995,14 +8244,14 @@ var Utils = (function () {
7995
8244
  if ((typeof checkPropertyName === "function" && checkPropertyName(obj)) ||
7996
8245
  Reflect.has(obj, checkPropertyName)) {
7997
8246
  isResolve = true;
7998
- clearInterval(interval);
8247
+ UtilsContext.workerClearInterval(interval);
7999
8248
  resolve(obj[checkPropertyName]);
8000
8249
  }
8001
8250
  }, intervalTimer);
8002
8251
  if (maxTime !== -1) {
8003
- setTimeout(() => {
8252
+ UtilsContext.workerSetTimeout(() => {
8004
8253
  if (!isResolve) {
8005
- clearInterval(interval);
8254
+ UtilsContext.workerClearInterval(interval);
8006
8255
  reject();
8007
8256
  }
8008
8257
  }, maxTime);
@@ -8213,6 +8462,64 @@ var Utils = (function () {
8213
8462
  */
8214
8463
  Vue = Vue;
8215
8464
  ModuleRaid = ModuleRaid;
8465
+ /**
8466
+ * 自动使用 Worker 执行 setTimeout
8467
+ * @param callback 回调函数
8468
+ * @param [timeout=0] 延迟时间,默认为0
8469
+ */
8470
+ workerSetTimeout(callback, timeout = 0) {
8471
+ try {
8472
+ return setTimeout$1(callback, timeout);
8473
+ }
8474
+ catch (error) {
8475
+ return globalThis.setTimeout(callback, timeout);
8476
+ }
8477
+ }
8478
+ /**
8479
+ * 配合 .setTimeout 使用
8480
+ * @param timeId setTimeout 返回的`id`
8481
+ */
8482
+ workerClearTimeout(timeId) {
8483
+ try {
8484
+ if (timeId != null) {
8485
+ clearTimeout(timeId);
8486
+ }
8487
+ }
8488
+ catch (error) {
8489
+ }
8490
+ finally {
8491
+ globalThis.clearTimeout(timeId);
8492
+ }
8493
+ }
8494
+ /**
8495
+ * 自动使用 Worker 执行 setInterval
8496
+ * @param callback 回调函数
8497
+ * @param timeout 间隔时间,默认为0
8498
+ */
8499
+ workerSetInterval(callback, timeout = 0) {
8500
+ try {
8501
+ return setInterval(callback, timeout);
8502
+ }
8503
+ catch (error) {
8504
+ return globalThis.setInterval(callback, timeout);
8505
+ }
8506
+ }
8507
+ /**
8508
+ * 配合 .setInterval 使用
8509
+ * @param timeId setInterval 返回的`id`
8510
+ */
8511
+ workerClearInterval(timeId) {
8512
+ try {
8513
+ if (timeId != null) {
8514
+ clearInterval(timeId);
8515
+ }
8516
+ }
8517
+ catch (error) {
8518
+ }
8519
+ finally {
8520
+ globalThis.clearInterval(timeId);
8521
+ }
8522
+ }
8216
8523
  }
8217
8524
  let utils = new Utils();
8218
8525