@whitesev/pops 3.2.2 → 3.3.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.
@@ -178,272 +178,55 @@ var pops = (function () {
178
178
  */
179
179
  const SymbolEvents = Symbol("events_" + (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1));
180
180
 
181
- const PopsCoreDefaultEnv = {
181
+ const OriginPrototype = {
182
+ Object: {
183
+ defineProperty: Object.defineProperty,
184
+ },
185
+ };
186
+ const PopsCoreDefaultApi = {
182
187
  document: document,
183
188
  window: window,
184
189
  globalThis: globalThis,
185
190
  self: self,
191
+ setTimeout: globalThis.setTimeout.bind(globalThis),
192
+ setInterval: globalThis.setInterval.bind(globalThis),
193
+ clearTimeout: globalThis.clearTimeout.bind(globalThis),
194
+ clearInterval: globalThis.clearInterval.bind(globalThis),
186
195
  };
187
- const PopsCoreEnv = Object.assign({}, PopsCoreDefaultEnv);
196
+ const PopsCoreApi = Object.assign({}, PopsCoreDefaultApi);
188
197
  const PopsCore = {
198
+ init(option) {
199
+ if (!option) {
200
+ option = Object.assign({}, PopsCoreDefaultApi);
201
+ }
202
+ Object.assign(PopsCoreApi, option);
203
+ },
189
204
  get document() {
190
- return PopsCoreEnv.document;
205
+ return PopsCoreApi.document;
191
206
  },
192
207
  get window() {
193
- return PopsCoreEnv.window;
208
+ return PopsCoreApi.window;
194
209
  },
195
210
  get globalThis() {
196
- return PopsCoreEnv.globalThis;
211
+ return PopsCoreApi.globalThis;
197
212
  },
198
213
  get self() {
199
- return PopsCoreEnv.self;
214
+ return PopsCoreApi.self;
200
215
  },
201
- };
202
- const OriginPrototype = {
203
- Object: {
204
- defineProperty: Object.defineProperty,
216
+ get setTimeout() {
217
+ return PopsCoreApi.setTimeout;
205
218
  },
206
- };
207
-
208
- const createCache = (lastNumberWeakMap) => {
209
- return (collection, nextNumber) => {
210
- lastNumberWeakMap.set(collection, nextNumber);
211
- return nextNumber;
212
- };
213
- };
214
-
215
- /*
216
- * The value of the constant Number.MAX_SAFE_INTEGER equals (2 ** 53 - 1) but it
217
- * is fairly new.
218
- */
219
- const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER === undefined ? 9007199254740991 : Number.MAX_SAFE_INTEGER;
220
- const TWO_TO_THE_POWER_OF_TWENTY_NINE = 536870912;
221
- const TWO_TO_THE_POWER_OF_THIRTY = TWO_TO_THE_POWER_OF_TWENTY_NINE * 2;
222
- const createGenerateUniqueNumber = (cache, lastNumberWeakMap) => {
223
- return (collection) => {
224
- const lastNumber = lastNumberWeakMap.get(collection);
225
- /*
226
- * Let's try the cheapest algorithm first. It might fail to produce a new
227
- * number, but it is so cheap that it is okay to take the risk. Just
228
- * increase the last number by one or reset it to 0 if we reached the upper
229
- * bound of SMIs (which stands for small integers). When the last number is
230
- * unknown it is assumed that the collection contains zero based consecutive
231
- * numbers.
232
- */
233
- let nextNumber = lastNumber === undefined ? collection.size : lastNumber < TWO_TO_THE_POWER_OF_THIRTY ? lastNumber + 1 : 0;
234
- if (!collection.has(nextNumber)) {
235
- return cache(collection, nextNumber);
236
- }
237
- /*
238
- * If there are less than half of 2 ** 30 numbers stored in the collection,
239
- * the chance to generate a new random number in the range from 0 to 2 ** 30
240
- * is at least 50%. It's benifitial to use only SMIs because they perform
241
- * much better in any environment based on V8.
242
- */
243
- if (collection.size < TWO_TO_THE_POWER_OF_TWENTY_NINE) {
244
- while (collection.has(nextNumber)) {
245
- nextNumber = Math.floor(Math.random() * TWO_TO_THE_POWER_OF_THIRTY);
246
- }
247
- return cache(collection, nextNumber);
248
- }
249
- // Quickly check if there is a theoretical chance to generate a new number.
250
- if (collection.size > MAX_SAFE_INTEGER) {
251
- throw new Error('Congratulations, you created a collection of unique numbers which uses all available integers!');
252
- }
253
- // Otherwise use the full scale of safely usable integers.
254
- while (collection.has(nextNumber)) {
255
- nextNumber = Math.floor(Math.random() * MAX_SAFE_INTEGER);
256
- }
257
- return cache(collection, nextNumber);
258
- };
259
- };
260
-
261
- const LAST_NUMBER_WEAK_MAP = new WeakMap();
262
- const cache = createCache(LAST_NUMBER_WEAK_MAP);
263
- const generateUniqueNumber = createGenerateUniqueNumber(cache, LAST_NUMBER_WEAK_MAP);
264
-
265
- const createBrokerFactory = (createOrGetOngoingRequests, extendBrokerImplementation, generateUniqueNumber, isMessagePort) => (brokerImplementation) => {
266
- const fullBrokerImplementation = extendBrokerImplementation(brokerImplementation);
267
- return (sender) => {
268
- const ongoingRequests = createOrGetOngoingRequests(sender);
269
- sender.addEventListener('message', (({ data: message }) => {
270
- const { id } = message;
271
- if (id !== null && ongoingRequests.has(id)) {
272
- const { reject, resolve } = ongoingRequests.get(id);
273
- ongoingRequests.delete(id);
274
- if (message.error === undefined) {
275
- resolve(message.result);
276
- }
277
- else {
278
- reject(new Error(message.error.message));
279
- }
280
- }
281
- }));
282
- if (isMessagePort(sender)) {
283
- sender.start();
284
- }
285
- const call = (method, params = null, transferables = []) => {
286
- return new Promise((resolve, reject) => {
287
- const id = generateUniqueNumber(ongoingRequests);
288
- ongoingRequests.set(id, { reject, resolve });
289
- if (params === null) {
290
- sender.postMessage({ id, method }, transferables);
291
- }
292
- else {
293
- sender.postMessage({ id, method, params }, transferables);
294
- }
295
- });
296
- };
297
- const notify = (method, params, transferables = []) => {
298
- sender.postMessage({ id: null, method, params }, transferables);
299
- };
300
- let functions = {};
301
- for (const [key, handler] of Object.entries(fullBrokerImplementation)) {
302
- functions = { ...functions, [key]: handler({ call, notify }) };
303
- }
304
- return { ...functions };
305
- };
306
- };
307
-
308
- const createCreateOrGetOngoingRequests = (ongoingRequestsMap) => (sender) => {
309
- if (ongoingRequestsMap.has(sender)) {
310
- // @todo TypeScript needs to be convinced that has() works as expected.
311
- return ongoingRequestsMap.get(sender);
312
- }
313
- const ongoingRequests = new Map();
314
- ongoingRequestsMap.set(sender, ongoingRequests);
315
- return ongoingRequests;
316
- };
317
-
318
- const createExtendBrokerImplementation = (portMap) => (partialBrokerImplementation) => ({
319
- ...partialBrokerImplementation,
320
- connect: ({ call }) => {
321
- return async () => {
322
- const { port1, port2 } = new MessageChannel();
323
- const portId = await call('connect', { port: port1 }, [port1]);
324
- portMap.set(port2, portId);
325
- return port2;
326
- };
219
+ get setInterval() {
220
+ return PopsCoreApi.setInterval;
327
221
  },
328
- disconnect: ({ call }) => {
329
- return async (port) => {
330
- const portId = portMap.get(port);
331
- if (portId === undefined) {
332
- throw new Error('The given port is not connected.');
333
- }
334
- await call('disconnect', { portId });
335
- };
222
+ get clearTimeout() {
223
+ return PopsCoreApi.clearTimeout;
224
+ },
225
+ get clearInterval() {
226
+ return PopsCoreApi.clearInterval;
336
227
  },
337
- isSupported: ({ call }) => {
338
- return () => call('isSupported');
339
- }
340
- });
341
-
342
- const isMessagePort = (sender) => {
343
- return typeof sender.start === 'function';
344
- };
345
-
346
- const createBroker = createBrokerFactory(createCreateOrGetOngoingRequests(new WeakMap()), createExtendBrokerImplementation(new WeakMap()), generateUniqueNumber, isMessagePort);
347
-
348
- const createClearIntervalFactory = (scheduledIntervalsState) => (clear) => (timerId) => {
349
- if (typeof scheduledIntervalsState.get(timerId) === 'symbol') {
350
- scheduledIntervalsState.set(timerId, null);
351
- clear(timerId).then(() => {
352
- scheduledIntervalsState.delete(timerId);
353
- });
354
- }
355
- };
356
-
357
- const createClearTimeoutFactory = (scheduledTimeoutsState) => (clear) => (timerId) => {
358
- if (typeof scheduledTimeoutsState.get(timerId) === 'symbol') {
359
- scheduledTimeoutsState.set(timerId, null);
360
- clear(timerId).then(() => {
361
- scheduledTimeoutsState.delete(timerId);
362
- });
363
- }
364
- };
365
-
366
- const createSetIntervalFactory = (generateUniqueNumber, scheduledIntervalsState) => (set) => (func, delay = 0, ...args) => {
367
- const symbol = Symbol();
368
- const timerId = generateUniqueNumber(scheduledIntervalsState);
369
- scheduledIntervalsState.set(timerId, symbol);
370
- const schedule = () => set(delay, timerId).then(() => {
371
- const state = scheduledIntervalsState.get(timerId);
372
- if (state === undefined) {
373
- throw new Error('The timer is in an undefined state.');
374
- }
375
- if (state === symbol) {
376
- func(...args);
377
- // Doublecheck if the interval should still be rescheduled because it could have been cleared inside of func().
378
- if (scheduledIntervalsState.get(timerId) === symbol) {
379
- schedule();
380
- }
381
- }
382
- });
383
- schedule();
384
- return timerId;
385
- };
386
-
387
- const createSetTimeoutFactory = (generateUniqueNumber, scheduledTimeoutsState) => (set) => (func, delay = 0, ...args) => {
388
- const symbol = Symbol();
389
- const timerId = generateUniqueNumber(scheduledTimeoutsState);
390
- scheduledTimeoutsState.set(timerId, symbol);
391
- set(delay, timerId).then(() => {
392
- const state = scheduledTimeoutsState.get(timerId);
393
- if (state === undefined) {
394
- throw new Error('The timer is in an undefined state.');
395
- }
396
- if (state === symbol) {
397
- // A timeout can be savely deleted because it is only called once.
398
- scheduledTimeoutsState.delete(timerId);
399
- func(...args);
400
- }
401
- });
402
- return timerId;
403
- };
404
-
405
- // Prefilling the Maps with a function indexed by zero is necessary to be compliant with the specification.
406
- const scheduledIntervalsState = new Map([[0, null]]); // tslint:disable-line no-empty
407
- const scheduledTimeoutsState = new Map([[0, null]]); // tslint:disable-line no-empty
408
- const createClearInterval = createClearIntervalFactory(scheduledIntervalsState);
409
- const createClearTimeout = createClearTimeoutFactory(scheduledTimeoutsState);
410
- const createSetInterval = createSetIntervalFactory(generateUniqueNumber, scheduledIntervalsState);
411
- const createSetTimeout = createSetTimeoutFactory(generateUniqueNumber, scheduledTimeoutsState);
412
- const wrap = createBroker({
413
- clearInterval: ({ call }) => createClearInterval((timerId) => call('clear', { timerId, timerType: 'interval' })),
414
- clearTimeout: ({ call }) => createClearTimeout((timerId) => call('clear', { timerId, timerType: 'timeout' })),
415
- setInterval: ({ call }) => createSetInterval((delay, timerId) => call('set', { delay, now: performance.timeOrigin + performance.now(), timerId, timerType: 'interval' })),
416
- setTimeout: ({ call }) => createSetTimeout((delay, timerId) => call('set', { delay, now: performance.timeOrigin + performance.now(), timerId, timerType: 'timeout' }))
417
- });
418
- const load = (url) => {
419
- const worker = new Worker(url);
420
- return wrap(worker);
421
- };
422
-
423
- const createLoadOrReturnBroker = (loadBroker, worker) => {
424
- let broker = null;
425
- return () => {
426
- if (broker !== null) {
427
- return broker;
428
- }
429
- const blob = new Blob([worker], { type: 'application/javascript; charset=utf-8' });
430
- const url = URL.createObjectURL(blob);
431
- broker = loadBroker(url);
432
- // Bug #1: Edge up until v18 didn't like the URL to be revoked directly.
433
- setTimeout(() => URL.revokeObjectURL(url));
434
- return broker;
435
- };
436
228
  };
437
229
 
438
- // This is the minified and stringified code of the worker-timers-worker package.
439
- const worker = `(()=>{var e={455(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),l=t(c);e.addUniqueNumber=l,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 l=r instanceof Promise?await r:r;if(null===a){if(void 0!==l.result)throw s(i)}else{if(void 0===l.result)throw s(i);const{result:e,transferables:r=[]}=l;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}}}),l=(e,t,r=()=>!0)=>{const n=c(l,t,r),o=a(e,n);return e.addEventListener("message",o),()=>e.removeEventListener("message",o)},d=(e,t)=>r=>{const n=t.get(r);if(void 0===n)return Promise.resolve(!1);const[o,s]=n;return e(o),t.delete(r),s(!1),Promise.resolve(!0)},m=(e,t,r,n)=>(o,s,a)=>{const i=o+s-t.timeOrigin,u=i-t.now();return new Promise(t=>{e.set(a,[r(n,u,i,e,t,a),t])})},f=new Map,h=d(globalThis.clearTimeout,f),p=new Map,v=d(globalThis.clearTimeout,p),w=((e,t)=>{const r=(n,o,s,a)=>{const i=n-e.now();i>0?o.set(a,[t(r,i,n,o,s,a),s]):(o.delete(a),s(!0))};return r})(performance,globalThis.setTimeout),g=m(f,performance,globalThis.setTimeout,w),T=m(p,performance,globalThis.setTimeout,w);l(self,{clear:async({timerId:e,timerType:t})=>({result:await("interval"===t?h(e):v(e))}),set:async({delay:e,now:t,timerId:r,timerType:n})=>({result:await("interval"===n?g:T)(e,t,r)})})})()})();`; // tslint:disable-line:max-line-length
440
-
441
- const loadOrReturnBroker = createLoadOrReturnBroker(load, worker);
442
- const clearInterval$1 = (timerId) => loadOrReturnBroker().clearInterval(timerId);
443
- const clearTimeout$1 = (timerId) => loadOrReturnBroker().clearTimeout(timerId);
444
- const setInterval$1 = (...args) => loadOrReturnBroker().setInterval(...args);
445
- const setTimeout$1 = (...args) => loadOrReturnBroker().setTimeout(...args);
446
-
447
230
  let t$1 = class t{constructor(){this.__map={};}beforeEach(t){this.__interceptor=t;}on(t,i){const s=Array.isArray(t)?t:[t];for(const t of s){this.__map[t]=this.__map[t]||[];const s=this.__map[t];s&&s.push(i);}return this}emit(t,i,s){ void 0!==this.__interceptor?this.__interceptor(t,(()=>{this.__emit(t,i),s&&s();})):(this.__emit(t,i),s&&s());}__emit(t,i){const s=this.__map[t];if(Array.isArray(s)&&(null==s?void 0:s.length))for(const _ of s)_(i,t);this.event=i;}off(t,i){const s=this.__map[t];if(void 0!==s)if(void 0===i)delete this.__map[t];else {const t=s.findIndex((t=>t===i));s.splice(t,1);}}destroy(){this.__map={};}};
448
231
 
449
232
  const n$1="clientX",e$2="clientY",t=16,c$3="start",o$1="move",s$1="cancel",u$3="end",a$2="left",i$3="right",r$4="up",d$1="down",m$2={4:"start",5:"move",1:"end",3:"cancel"};function v$1(n){return m$2[n]}function b(n,e,t){const c={1:{0:{move:4},4:{move:5,end:1,cancel:3},5:{move:5,end:1,cancel:3}},0:{4:{move:2,end:1,cancel:3},5:{start:2,move:2,end:1,cancel:3}}}[Number(n)][e];return void 0!==c&&c[t]||0}function g$1(n){[1,3,2].includes(n.state)&&(n.state=0);}function h$3(n){return [5,1,3].includes(n)}function j(n){if(n.disabled)return n.state=0,true}function O(n,e){return Object.assign(Object.assign(Object.assign({},n),e),{state:0,disabled:false})}function p$3(n){return Math.round(100*n)/100}
@@ -709,55 +492,25 @@ var pops = (function () {
709
492
  * 自动使用 Worker 执行 setTimeout
710
493
  */
711
494
  setTimeout(callback, timeout = 0) {
712
- try {
713
- return setTimeout$1(callback, timeout);
714
- }
715
- catch {
716
- return setTimeout(callback, timeout);
717
- }
495
+ return PopsCore.setTimeout(callback, timeout);
718
496
  }
719
497
  /**
720
498
  * 配合 .setTimeout 使用
721
499
  */
722
500
  clearTimeout(timeId) {
723
- try {
724
- if (timeId != null) {
725
- clearTimeout$1(timeId);
726
- }
727
- }
728
- catch {
729
- // TODO
730
- }
731
- finally {
732
- clearTimeout(timeId);
733
- }
501
+ return PopsCore.clearTimeout(timeId);
734
502
  }
735
503
  /**
736
504
  * 自动使用 Worker 执行 setInterval
737
505
  */
738
506
  setInterval(callback, timeout = 0) {
739
- try {
740
- return setInterval$1(callback, timeout);
741
- }
742
- catch {
743
- return setInterval(callback, timeout);
744
- }
507
+ return PopsCore.setInterval(callback, timeout);
745
508
  }
746
509
  /**
747
510
  * 配合 .setInterval 使用
748
511
  */
749
512
  clearInterval(timeId) {
750
- try {
751
- if (timeId != null) {
752
- clearInterval$1(timeId);
753
- }
754
- }
755
- catch {
756
- // 忽略
757
- }
758
- finally {
759
- clearInterval(timeId);
760
- }
513
+ return PopsCore.clearInterval(timeId);
761
514
  }
762
515
  /**
763
516
  * 覆盖对象中的数组新值
@@ -13462,7 +13215,7 @@ var pops = (function () {
13462
13215
  },
13463
13216
  };
13464
13217
 
13465
- const version = "3.2.2";
13218
+ const version = "3.3.0";
13466
13219
 
13467
13220
  class Pops {
13468
13221
  /** 配置 */