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