@creejs/commons-retrier 2.1.20 → 2.1.22
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/cjs/index-dev.cjs +36 -0
- package/dist/cjs/index-dev.cjs.map +1 -1
- package/dist/cjs/index-min.cjs +1 -1
- package/dist/cjs/index-min.cjs.map +1 -1
- package/dist/esm/index-dev.js +36 -0
- package/dist/esm/index-dev.js.map +1 -1
- package/dist/esm/index-min.js +1 -1
- package/dist/esm/index-min.js.map +1 -1
- package/dist/umd/index.dev.js +36 -0
- package/dist/umd/index.dev.js.map +1 -1
- package/dist/umd/index.min.js +1 -1
- package/dist/umd/index.min.js.map +1 -1
- package/package.json +1 -1
- package/types/index.d.ts +7 -1
- package/types/retrier-factory.d.ts +21 -0
package/dist/esm/index-min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
let t=class t extends Error{static isAggregatedErrorLike(t){return t&&Array.isArray(t.errors)}static isAggregatedError(e){return e instanceof t}constructor(t,e){super(t),this.errors=e??[]}addError(t){this.errors.push(t)}removeError(t){const e=this.errors.indexOf(t);return-1!==e&&(this.errors.splice(e,1),!0)}};var e=function(t,...e){if(null==t)throw new TypeError('"target" Should Not Nil');for(const r of e)if(null!=r)for(const e in r)void 0===t[e]&&(t[e]=r[e]);return t};var r={isArray:function(t){return Array.isArray(t)},isBoolean:function(t){return"boolean"==typeof t},isBuffer:function(t){return null!=t&&Buffer.isBuffer(t)},isFunction:n,isInstance:function(t){return null!=t&&"object"==typeof t&&!c(t)},isIterable:function(t){return null!=t&&"function"==typeof t[Symbol.iterator]},isDate:function(t){return null!=t&&t instanceof Date},isError:function(t){return null!=t&&t instanceof Error},isMap:function(t){return null!=t&&"object"==typeof t&&t.constructor===Map},isWeakMap:function(t){return null!=t&&"object"==typeof t&&t.constructor===WeakMap},isNumber:o,isPositive:i,isNegative:function(t){return!!o(t)&&t<0},isNotNegative:a,isNil:s,isNullOrUndefined:function(t){return null==t},isNull:function(t){return null===t},isUndefined:function(t){return void 0===t},isPlainObject:c,isObject:function(t){return null!=t&&"object"==typeof t},isPromise:l,isRegExp:function(t){return null!=t&&"object"==typeof t&&t.constructor===RegExp},isSet:function(t){return null!=t&&"object"==typeof t&&t.constructor===Set},isWeakSet:function(t){return null!=t&&"object"==typeof t&&t.constructor===WeakSet},isStream:function(t){return null!=t&&"function"==typeof t.pipe},isString:u,isSymbol:function(t){return null!=t&&"symbol"==typeof t},isPrimitive:function(t){return null!==t&&("string"==typeof t||"number"==typeof t||"boolean"==typeof t)},isInt8Array:function(t){return t instanceof Int8Array},isUint8Array:function(t){return t instanceof Uint8Array},isUint8ClampedArray:function(t){return t instanceof Uint8ClampedArray},isInt16Array:function(t){return t instanceof Int16Array},isUint16Array:function(t){return t instanceof Uint16Array},isInt32Array:function(t){return t instanceof Int32Array},isUint32Array:function(t){return t instanceof Uint32Array},isFloat32Array:function(t){return t instanceof Float32Array},isFloat64Array:function(t){return t instanceof Float64Array},isBigInt64Array:function(t){return t instanceof BigInt64Array},isBigUint64Array:function(t){return t instanceof BigUint64Array},isTypedArray:function(t){return ArrayBuffer.isView(t)&&t.constructor!==DataView},isArrayBuffer:function(t){return t instanceof ArrayBuffer}};function n(t){return"function"==typeof t}function s(t){return null==t}function i(t){return!!o(t)&&t>0}function a(t){return!!o(t)&&t>=0}function o(t){return null!=t&&"number"==typeof t}function c(t){return null!==t&&"object"==typeof t&&(t.constructor===Object||void 0===t.constructor)}function l(t){return null!=t&&"function"==typeof t.then}function u(t){return null!=t&&"string"==typeof t}var h={assertNumber:m,assertPositive:function(t,e){if(!i(t))throw new Error(`${e?'"'+e+'" ':""}Not Positive: ${t}`)},assertNotNegative:_,assertFunction:w,assertNotNil:function(t,e){if(s(t))throw new Error((e?'"'+e+'" ':"")+"Should Not Nil")},assertString:function(t,e){if(!u(t))throw new Error(`${e?'"'+e+'" ':""}Not String: type=${typeof t} value=${p(t)}`)}};function f(t,e){if(!Array.isArray(t))throw new Error(`${e?'"'+e+'" ':""}Not Array: type=${typeof t} value=${p(t)}`)}function m(t,e){if(!o(t))throw new Error(`${e?'"'+e+'" ':""}Not Number: type=${typeof t} value=${p(t)}`)}function _(t,e){if(!a(t))throw new Error(`${e?'"'+e+'" ':""}Not "0 or Positive": ${t}`)}function w(t,e){if(!n(t))throw new Error(`${e?'"'+e+'" ':""}Not Function: type=${typeof t} value=${p(t)}`)}function d(t,e){if(!l(t))throw new Error(`${e?'"'+e+'" ':""}Not Promise: type=${typeof t} value=${p(t)}`)}function p(t){if(null===t)return"null";if(void 0===t)return"undefined";let e;try{e=JSON.stringify(t)}catch(r){e=t.toString()}return e}var g={any:function(e){if(f(e),0===e.length)throw new Error("Empty Tasks");const n=y(),s=[];for(let i=0;i<e.length;i++){const a=e[i];let o;if(r.isPromise(a))o=a;else{if(!r.isFunction(a)){s.push(new Error(`Invalid Task at index ${i}/${e.length-1}: ${a}`));continue}o=k(a)}o.then(t=>{n.resolve(t)}).catch(r=>{s.push(r),s.length>=e.length&&n.reject(new t("All Tasks Failed",s))})}return s.length===e.length&&n.reject(new t("All Tasks Failed",s)),n.promise},defer:y,delay:function(t,e){r.isNumber(t)?(e=t,t=Promise.resolve()):null==t&&null==e&&(e=1,t=Promise.resolve()),null!=t&&d(t),m(e=e??1e3);const n=y(),s=Date.now();return t.then((...t)=>{const r=Date.now()-s;r<e?setTimeout(()=>n.resolve(...t),e-r):n.resolve(...t)}).catch(t=>{const r=Date.now()-s;r<e?setTimeout(()=>n.reject(t),e-r):n.reject(t)}),n.promise},timeout:function(t,e,r){d(t),m(e=e??1);const n=y(e,r),s=Date.now();return t.then((...t)=>{Date.now()-s<=e?n.resolve(...t):n.reject(new Error(r??`Promise Timeout: ${e}ms`))}).catch(t=>{!n.resolved&&!n.rejected&&n.reject(t)}),n.promise},allSettled:v,returnValuePromised:k,series:async function(t){f(t);const e=[];for(const n of t)if(w(n),r.isFunction(n))e.push(await k(n));else{if(!r.isPromise(n))throw new Error(`Invalid Task: ${n}`);e.push(await n)}return e},seriesAllSettled:async function(t){f(t);const e=[];for(const r of t){w(r);try{e.push({ok:!0,result:await r()})}catch(t){e.push({ok:!1,result:t})}}return e},parallel:async function(t,e=5){if(f(t),m(e),e<=0)throw new Error(`Invalid maxParallel: ${e}, should > 0`);t.forEach(t=>w(t));const r=[];if(t.length<=e){const e=await Promise.all(t.map(t=>k(t)));return r.push(...e),r}const n=[];for(const s of t)if(w(s),n.push(s),n.length>=e){const t=await Promise.all(n.map(t=>k(t)));r.push(...t),n.length=0}if(n.length>0&&n.length<e){const t=await Promise.all(n.map(t=>k(t)));r.push(...t)}return r},parallelAny:async function(e,n=5,s){if(f(e,"tasks"),m(n),0===e.length)throw new Error("Empty Tasks");if(n<=0)throw new Error(`Invalid maxParallel: ${n}, should > 0`);const i=[];let a=0,o=0;const c=y();function l(){if(a>=e.length)return;if(o>n)return;const u=e[a++];let h;o++,h=r.isPromise(u)?u:r.isFunction(u)?k(u):Promise.reject(new TypeError(`Invalid task: ${typeof u}, Only Promise or Function allowed`)),h.then(t=>{o--,c.resolve(t)}).catch(r=>{i.push(r),i.length>=e.length&&c.pending?c.reject(new t(s??"All Tasks Failed",i)):(o--,l())})}const u=Math.min(e.length,n);for(let t=0;t<u;t++)l();return c.promise},parallelAllSettled:async function(t,e=5){if(f(t),m(e),e<=0)throw new Error(`Invalid maxParallel: ${e}, should > 0`);t.forEach(t=>w(t));const r=[];if(t.length<=e){const e=await v(t.map(t=>k(t)));return r.push(...e),r}const n=[];for(const s of t)if(n.push(s),n.length>=e){const t=await v(n.map(t=>k(t)));r.push(...t),n.length=0}if(n.length>0&&n.length<e){const t=await v(n.map(t=>k(t)));r.push(...t)}return r},wait:function(t){_(t);const e={};let r;return e.timerHandler=r=setTimeout(()=>{clearTimeout(r),e._resolve()},t),e.promise=new Promise((t,n)=>{e._resolve=e=>{null!=r&&clearTimeout(r),t(e)}}),e.wakeup=()=>{e._resolve()},e}};function y(t=-1,e){m(t);const r={};let n;return r.pending=!0,r.canceled=!1,r.rejected=!1,r.resolved=!1,t>=0&&(r.timerCleared=!1,r.timerHandler=n=setTimeout(()=>{clearTimeout(n),r.timerCleared=!0,r.reject(new Error(e??`Promise Timeout: ${t}ms`))},t)),r.promise=new Promise((t,e)=>{r.resolve=e=>{r.resolved||r.rejected||r.canceled||(null!=n&&(clearTimeout(n),r.timerCleared=!0),r.pending=!1,r.canceled=!1,r.rejected=!1,r.resolved=!0,t(e))},r.reject=t=>{r.resolved||r.rejected||r.canceled||(null!=n&&(clearTimeout(n),r.timerCleared=!0),r.pending=!1,r.canceled=!1,r.resolved=!1,r.rejected=!0,e(t))}}),r.cancel=r.promise.cancel=t=>{r.resolved||r.rejected||r.canceled||(null!=n&&(clearTimeout(n),r.timerCleared=!0),r.reject(t??new Error("Cancelled")),r.canceled=r.promise.canceled=!0)},r}async function v(t){f(t);const e=await Promise.allSettled(t),r=[];for(const t of e)"fulfilled"===t.status&&r.push({ok:!0,result:t.value}),"rejected"===t.status&&r.push({ok:!1,result:t.reason});return r}function k(t){try{const e=t();return r.isPromise(e)?e:Promise.resolve(e)}catch(t){return Promise.reject(t)}}new TextDecoder,new TextEncoder;const{assertPositive:x,assertNotNegative:b}=h,{isNumber:E}=r;class L{constructor(){this._min=50,this._max=3e4,this._nextInterval=this._min,this._jitter=0}get jitter(){return this._jitter}set jitter(t){b(t,"jitter"),this._jitter=t}copyPolicySettingTo(t){t.range(this._min,this._max),t._nextInterval=this._nextInterval}range(t,e){if(x(t,"min"),x(e,"max"),t>=e)throw new Error("min must < max");return this._min=t,this._nextInterval<this._min&&(this._nextInterval=this._min),this._max=e,this._nextInterval>this._max&&(this._nextInterval=this._max),this}min(t){if(x(t,"min"),t>=this._max)throw new Error("min must < max");return this._min=t,this._nextInterval<this._min&&(this._nextInterval=this._min),this}max(t){if(x(t,"max"),t<=this._min)throw new Error("max must > min");return this._max=t,this._nextInterval>this._max&&(this._nextInterval=this._max),this}reset(){return this._nextInterval=this._min,this}generate(t){const e=this._nextInterval;return this._increase(t),e}_increase(t){const e=this._next(t);if(!E(e))throw new Error("Generated Next Interval Not Number");const r=this._jitter<=0?e:e+Math.floor(Math.random()*this._jitter);return r<this._min?this._nextInterval=this._min:r>this._max?this._nextInterval=this._max:this._nextInterval=r}_next(t){throw new Error("Not Impled Yet")}}var T={isFunction:N,isNil:I};function N(t){return"function"==typeof t}function I(t){return null==t}function S(t){return null!=t&&"string"==typeof t}var F={assertNumber:function(t,e){if(!function(t){return null!=t&&"number"==typeof t}(t))throw new Error(`${e?'"'+e+'" ':""}Not Number: type=${typeof t} value=${R(t)}`)},assertFunction:function(t,e){if(!N(t))throw new Error(`${e?'"'+e+'" ':""}Not Function: type=${typeof t} value=${R(t)}`)},assertNotNil:function(t,e){if(I(t))throw new Error((e?'"'+e+'" ':"")+"Should Not Nil")},assertString:function(t,e){if(!S(t))throw new Error(`${e?'"'+e+'" ':""}Not String: type=${typeof t} value=${R(t)}`)},assertStringOrSymbol:function(t,e){if(!S(t)&&!function(t){return null!=t&&"symbol"==typeof t}(t))throw new Error(`${e?'"'+e+'" ':""}Not String or Symbol: type=${typeof t} value=${R(t)}`)}};function R(t){if(null===t)return"null";if(void 0===t)return"undefined";let e;try{e=JSON.stringify(t)}catch(r){e=t.toString()}return e}new TextDecoder,new TextEncoder;const A="DOwner$#$",{assertFunction:P,assertNotNil:j}=F;class O{constructor(t,e,r=!1){j(t,"event"),P(e,"callback"),this._event=t,this._callback=e,this._isOnce=!!r,this._owner=void 0}set owner(t){this._owner=t}get owner(){return this._owner===A?void 0:this._owner}get event(){return this._event}get isOnce(){return this._isOnce}isSameCallback(t){return this._callback===t}get callback(){return this._callback}invoke(...t){try{return this._callback(...t)}finally{if(this._isOnce)try{this._event._remove(this)}catch(t){console.warn(t)}}}listener(...t){return this.invoke(...t)}}const{isFunction:$,isNil:C}=T,{assertStringOrSymbol:B,assertFunction:M}=F;class D{static get DefaultOwner(){return A}constructor(t){B(t,"eventName"),this._name=t,this._callbacks=new Set,this._listeners=[],this._callback2Listeners=new Map,this._listener2Owner=new Map,this._owner2Listeners=new Map}get name(){return this._name}isEmpty(){return 0===this._callbacks.size}rawListeners(){return[...this._listeners]}listenerCount(t){return null==t?this._listeners.length:this._callback2Listeners.get(t)?.size??0}callbacks(){return[...this.rawListeners().map(t=>t.callback)]}emit(...t){if(0===this._listeners.length)return!1;for(const e of[...this._listeners])e.invoke(...t);return!0}emitOwner(t,...e){if(0===this._listeners.length)return!1;const r=this._owner2Listeners.get(t);if(null==r)return!1;for(const t of[...r])t.invoke(...e);return!0}hasListener(t){return!!$(t)&&this._callbacks.has(t)}hasOwner(t){return!C(t)&&this._owner2Listeners.has(t)}addListener(t,e){return this._addListener(t,e,!1,!1)}prependListener(t,e){return this._addListener(t,e,!1,!0)}addOnceListener(t,e){return this._addListener(t,e,!0,!1)}prependOnceListener(t,e){return this._addListener(t,e,!0,!0)}_addListener(t,e,r,n){if(C(t))return!1;M(t),this._callbacks.has(t)||this._callbacks.add(t),e=e??A;const s=new O(this,t,r);s.owner=e,n?this._listeners.unshift(s):this._listeners.push(s),this._listener2Owner.set(s,e);let i=this._callback2Listeners.get(t);null==i&&(i=new Set,this._callback2Listeners.set(t,i)),i.add(s);let a=this._owner2Listeners.get(e);return null==a&&(a=new Set,this._owner2Listeners.set(e,a)),a.add(s),!0}removeListener(t){if(C(t))return!1;if(!this._callbacks.has(t))return!1;this._callbacks.delete(t);const e=this._callback2Listeners.get(t);if(null==e)return!1;this._callback2Listeners.delete(t);for(const t of e){-1!==this._listeners.indexOf(t)&&this._listeners.splice(this._listeners.indexOf(t),1);const e=this._listener2Owner.get(t);if(null==e)continue;this._listener2Owner.delete(t);const r=this._owner2Listeners.get(e);null!=r&&(r.delete(t),0===r.size&&this._owner2Listeners.delete(e))}return!0}_remove(t){const e=this._listeners.indexOf(t);-1!==e&&this._listeners.splice(e,1);const{callback:r}=t,n=this._callback2Listeners.get(r);null!=n&&(n.delete(t),0===n.size&&(this._callback2Listeners.delete(r),this._callbacks.delete(r)));const s=this._listener2Owner.get(t);if(null==s)return;this._listener2Owner.delete(t);const i=this._owner2Listeners.get(s);null!=i&&(i.delete(t),0===i.size&&this._owner2Listeners.delete(s))}removeAllListeners(t){if(C(t))return this._callbacks.clear(),this._listeners.length=0,this._callback2Listeners.clear(),this._listener2Owner.clear(),this._owner2Listeners.clear(),this;const e=this._owner2Listeners.get(t);if(null==e)return this;this._owner2Listeners.delete(t);for(const t of e){-1!==this._listeners.indexOf(t)&&this._listeners.splice(this._listeners.indexOf(t),1),this._listener2Owner.delete(t);const{callback:e}=t,r=this._callback2Listeners.get(e);null!=r&&(r.delete(t),0===r.size&&(this._callback2Listeners.delete(e),this._callbacks.delete(e)))}return this}}const{isNil:U}=T,{assertString:W,assertFunction:z,assertNumber:H,assertStringOrSymbol:V,assertNotNil:J}=F,G=["on","once","addListener","prependListener","prependOnceListener","off","offAll","offOwner","removeAllListeners","removeListener","emit","emitOwner","setMaxListeners","getMaxListeners","hasOwner","listeners","listenerCount","eventNames","rawListeners"];let Y=10;class q{static mixin(t){const e=new q;t.__emitter=e;for(const r of G){const n=e[r];t[r]=n.bind(e)}return t}static get defaultMaxListeners(){return Y}static set defaultMaxListeners(t){H(t),Y=t??10}constructor(){this._name2Event=new Map,this._maxListeners=Y}addListener(t,e,r){return this.on(t,e,r)}prependListener(t,e,r){return W(t),z(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).prependListener(e,r),this}prependOnceListener(t,e,r){return W(t),z(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).prependOnceListener(e,r),this}emit(t,...e){const r=this._name2Event.get(t);return null!=r&&!r.isEmpty()&&(r.emit(...e),!0)}emitOwner(t,e,...r){if(null==e)throw new Error('Missing "owner"');const n=this._name2Event.get(t);return null!=n&&!n.isEmpty()&&(n.emitOwner(e,...r),!0)}eventNames(){return[...this._name2Event.keys()]}getMaxListeners(){return this._maxListeners}listenerCount(t,e){V(t,"eventName");const r=this._name2Event.get(t);return null==r||r.isEmpty()?0:r.listenerCount(e)}listeners(t){V(t,"eventName");const e=this._name2Event.get(t);return null==e||e.isEmpty()?[]:e.callbacks()}off(t,e){const r=this._name2Event.get(t);return null==r?this:(r.removeListener(e),r.isEmpty()?(this._name2Event.delete(t),this):this)}offAll(t,e){V(t,"eventName");const r=this._name2Event.get(t);return null==r?this:(r.removeAllListeners(e),r.isEmpty()?(this._name2Event.delete(t),this):this)}offOwner(t){J(t,"owner");const e=[...this._name2Event.values()];for(const r of e)r.removeAllListeners(t),r.isEmpty()&&this._name2Event.delete(r.name);return this}on(t,e,r){return W(t),z(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).addListener(e,r),this}_checkMaxListeners(t){let e=0;0!==this._maxListeners&&this._maxListeners!==1/0&&(e=this.listenerCount(t))>=this._maxListeners&&console.warn(`maxlistenersexceededwarning: Possible EventEmitter memory leak detected. ${e} ${t} listeners added to [${this}]. Use emitter.setMaxListeners() to increase limit`)}once(t,e,r){return W(t),z(e),this._getOrCreateEvent(t).addOnceListener(e,r),this}rawListeners(t){return this._name2Event.get(t)?.rawListeners()||[]}removeAllListeners(t,e){return this.offAll(t,e)}removeListener(t,e){return this.off(t,e)}setMaxListeners(t){if(H(t),t<0)throw new RangeError("maxListeners must >=0");return this._maxListeners=t,this}_getOrCreateEvent(t){if(this._name2Event.has(t))return this._name2Event.get(t);const e=new D(t);return this._name2Event.set(t,e),e}hasOwner(t){if(U(t))return!1;for(const e of this._name2Event.values())if(e.hasOwner(t))return!0;return!1}}var K={Start:"start",Retry:"retry",Success:"success",Failure:"failure",Timeout:"timeout",TaskTimeout:"task-timeout",Stop:"stop",Completed:"complete",MaxRetries:"max-retries"};const{assertPositive:Q}=h;class X extends L{constructor(t){super(),this.interval=t}set interval(t){Q(t,"interval"),this._interval=t,this._nextInterval=t,this._min=t,this._max=t}get interval(){return this._interval}_next(t){return this.interval}}const{assertPositive:Z}=h;class tt extends L{constructor(t){super(),Z(t,"increasement"),this._increasement=t}set increasement(t){Z(t,"increasement"),this._increasement=t}get increasement(){return this._increasement}_next(t){return this._nextInterval>=this._max?this._max:this._nextInterval+this.increasement}}const{assertPositive:et}=h;class rt extends L{constructor(t){if(super(),et(t,"factor"),t<1)throw new Error("factor must be >= 1");this._factor=t}set factor(t){if(et(t,"factor"),t<1)throw new Error("factor must be >= 1");this._factor=t}get factor(){return this._factor}_next(t){return this._nextInterval>=this._max?this._max:this._nextInterval*this.factor}}const{assertPositive:nt}=h;class st extends L{constructor(t){super(),nt(t,"stepLength"),this._stepLength=t,this.increasement=t}set stepLength(t){nt(t,"stepLength"),this._stepLength=t,this.increasement=t}get stepLength(){return this._stepLength}_next(t){const e=this._nextInterval+this.increasement;return e>=this._max?(this.increasement=-this.stepLength,this._max):e<=this._min?(this.increasement=this.stepLength,this._min):e}}const{assertNotNegative:it}=h;class at extends X{constructor(t,e=500){super(t),it(e,"jitter"),this._jitter=e??500}}const{assertNotNegative:ot}=h;class ct extends rt{constructor(t=500){super(2),ot(t,"jitter"),this._jitter=t??500}}const{assertNotNegative:lt}=h;class ut extends tt{constructor(t,e=500){super(t),lt(e,"jitter"),this._jitter=e??500}}const{assertNotNil:ht,assertFunction:ft}=h;class mt{constructor(t,e){ht(t,"retrier"),ft(e,"task"),this.retrier=t,this.task=e,this.result=void 0,this.error=void 0}get failed(){return null!=this.error}get succeeded(){return null==this.error}async execute(t,e,r){try{this.result=await this.task(t,e,r),this.error=void 0}catch(t){this.error=t instanceof Error?t:new Error(String(t))}}dispose(){this.retrier=void 0}}class _t extends mt{static isAlwaysTask(t){return t instanceof _t}constructor(t,e,r){super(t,e),this.resetPolicy=r}async execute(t,e,r){await super.execute(t,e,r),this.succeeded&&this.resetPolicy&&this.retrier.resetRetryPolicy()}}class wt extends mt{static isForeverTask(t){return t instanceof wt}constructor(t,e,r){super(t,e),this.resetPolicy=r}async execute(t,e,r){await super.execute(t,e,r),this.succeeded&&this.resetPolicy&&this.retrier.resetRetryPolicy()}}const{assertPositive:dt,assertString:pt,assertFunction:gt,assertNumber:yt}=h,{isNil:vt}=r,kt="!#@%$&^*";class xt{static naming(t){const e=new xt;return e.name(t),e}static infinite(){const t=new xt;return t.infinite(),t}static times(t){const e=new xt;return e.times(t),e}static maxRetries(t){const e=new xt;return e.maxRetries(t),e}static min(t){const e=new xt;return e.min(t),e}static max(t){const e=new xt;return e.max(t),e}static range(t,e){const r=new xt;return r.range(t,e),r}static fixedInterval(t){const e=new xt;return e.fixedInterval(t),e}static fixedBackoff(t,e=500){const r=new xt;return r.fixedBackoff(t,e),r}static fixedIncrease(t){const e=new xt;return e.fixedIncrease(t),e}static linearBackoff(t,e=500){const r=new xt;return r.linearBackoff(t,e),r}static factorIncrease(t){const e=new xt;return e.factorIncrease(t),e}static exponentialBackoff(t=500){const e=new xt;return e.exponentialBackoff(t),e}static shuttleInterval(t){const e=new xt;return e.shuttleInterval(t),e}static timeout(t){const e=new xt;return e.timeout(t),e}static taskTimeout(t){const e=new xt;return e.taskTimeout(t),e}static start(t){const e=new xt;return e.task(t),e.start()}constructor(t){q.mixin(this),this._policy=new X(t??1e3),this._maxRetries=3,this._currentRetries=1,this._timeout=12e4,this._taskTimeout=2e3,this._name="unamed",this._taskingFlag=void 0,this._breakFlag=void 0,this._breakReason=void 0}get running(){return!vt(this._taskingFlag)}name(t){return pt(t,"name"),this._assertChangeable(t),this._name=t,this}infinite(){return this._assertChangeable("infinite"),this._maxRetries=1/0,this}times(t){return this._assertChangeable("times"),this.maxRetries(t)}maxRetries(t){return dt(t,"maxRetries"),this._assertChangeable("maxRetries"),this._maxRetries=t,this}min(t){return this._assertChangeable("min"),this._policy.min(t),this}max(t){return this._assertChangeable("max"),this._policy.max(t),this}range(t,e){return this._assertChangeable("range"),this._policy.range(t,e),this}fixedInterval(t){this._assertChangeable("fixedInterval");const e=this._policy;if(e instanceof X)return e.interval=t,this;const r=new X(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}fixedBackoff(t,e=500){this._assertChangeable("fixedBackoff");const r=this._policy;if(r instanceof X)return r.interval=t,r.jitter=e,this;const n=new at(t,e);return r?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}fixedIncrease(t){this._assertChangeable("fixedIncrease");const e=this._policy;if(e instanceof tt)return e.increasement=t,this;const r=new tt(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}linearBackoff(t,e=500){this._assertChangeable("linearBackoff");const r=this._policy;if(r instanceof ut)return r.increasement=t,r.jitter=e,this;const n=new ut(t,e);return r?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}factorIncrease(t){this._assertChangeable("factorIncrease");const e=this._policy;if(e instanceof rt)return e.factor=t,this;const r=new rt(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}exponentialBackoff(t=500){this._assertChangeable("exponentialBackoff");const e=this._policy;if(e instanceof ct)return e.jitter=t,this;const r=new ct(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}shuttleInterval(t){this._assertChangeable("shuttleInterval");const e=this._policy;if(e instanceof st)return e.stepLength=t,this;const r=new st(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}taskTimeout(t){return dt(t,"taskTimeout"),this._assertChangeable("taskTimeout"),this._taskTimeout=t,this}timeout(t){return yt(t,"timeout"),this._assertChangeable("timeout"),this._timeout=t,this}noTimeout(){return this._assertChangeable("noTimeout"),this._timeout=0,this}task(t){return gt(t,"task"),this._assertChangeable("task"),this._task=new mt(this,t),this}retry(t){return this._assertChangeable("retry"),this.task(t),this}always(t,e=!0){return this._assertChangeable("always"),this._task=new _t(this,t,e),this}forever(t,e=!0){return this._assertChangeable("forever"),this.noTimeout(),this.infinite(),this._task=new wt(this,t,e),this}async start(){if(null==this._task)throw new Error("No Task to Retry");return null!=this._taskingFlag||(this._taskingFlag=g.defer(),wt.isForeverTask(this._task)?(this._executeForeverTask(this._task),this._taskingFlag.resolve()):this._executeEndableTask(this._task)),this._taskingFlag.promise}wakeup(){this.running?null!=this._sleepWaiter&&this._sleepWaiter.wakeup():this.start()}async stop(t){if(this.emit(K.Stop,t),null!=this._taskingFlag)return null!=this._breakFlag||(null!=this._sleepWaiter&&this._sleepWaiter.wakeup(),this._breakFlag=g.defer(),this._breakReason=t??new Error("Manually Stop"),this.once(K.Completed,()=>{this._breakFlag?.resolve()}),this._breakFlag.promise.finally(()=>{this._breakFlag=void 0,this._breakReason=void 0})),this._breakFlag.promise}resetRetryPolicy(){this._policy.reset()}onRetry(t){return this.on(K.Retry,t),this}onError(t){return this.on(K.Error,t),this}onFailure(t){return this.on(K.Failure,t),this}onSuccess(t){return this.on(K.Success,t),this}onStart(t){return this.on(K.Start,t),this}onStop(t){return this.on(K.Stop,t),this}onTimeout(t){return this.on(K.Timeout,t),this}onTaskTimeout(t){return this.on(K.TaskTimeout,t),this}onCompleted(t){return this.on(K.Completed,t),this}onMaxRetries(t){return this.on(K.MaxRetries,t),this}async _executeForeverTask(t){if(null==this._taskingFlag)throw new Error("Must be called in start()");const e=Date.now();this.emit(K.Start,e);let r=null;for(;;){if(null!=this._breakFlag){const t=Date.now()-e;this.emit(K.Completed,this._currentRetries,t);break}r=Date.now()-e,this.emit(K.Retry,this._currentRetries,r);const n=this._policy.generate(this._currentRetries);try{try{await g.timeout(t.execute(this._currentRetries,r,n),this._taskTimeout,kt)}catch(t){throw t.message===kt&&this.emit(K.TaskTimeout,this._currentRetries,r,this._taskTimeout),t}if(t.failed)throw t.error;const e=t.result;this.emit(K.Success,e,this._currentRetries,r)}catch(t){this.emit(K.Failure,t,this._currentRetries,r)}++this._currentRetries,this._sleepWaiter=g.wait(n),await this._sleepWaiter.promise}}async _executeEndableTask(t){if(null==this._taskingFlag)throw new Error("Must be called in start()");const e=Date.now();let r;this.emit(K.Start,e);let n=null;for(;;){if(null!=this._breakFlag){this._taskingFlag.reject(this._breakReason??new Error("Have Been Broken"));break}if(n=Date.now()-e,!bt(this._timeout)&&n>=this._timeout){if(this.emit(K.Timeout,this._currentRetries,n,this._timeout),_t.isAlwaysTask(this._task)){this._taskingFlag.resolve();break}this._taskingFlag.reject(r??new Error(`Timeout "${this._timeout}" Exceeded`));break}this.emit(K.Retry,this._currentRetries,n);const s=this._policy.generate(this._currentRetries);try{try{await g.timeout(t.execute(this._currentRetries,n,s),this._taskTimeout,kt)}catch(t){throw t.message===kt&&this.emit(K.TaskTimeout,this._currentRetries,n,this._taskTimeout),t}if(t.failed)throw r=t.error,t.error;const e=t.result;if(this.emit(K.Success,e,this._currentRetries,n),!_t.isAlwaysTask(t)){this._taskingFlag.resolve(e);break}}catch(t){this.emit(K.Failure,t,this._currentRetries,n)}const i=++this._currentRetries;if(this._currentRetries>this._maxRetries){if(this.emit(K.MaxRetries,i,this._maxRetries),_t.isAlwaysTask(t)){this._taskingFlag.resolve();break}this._taskingFlag.reject(r??new Error(`Max Retries Exceeded, Retring ${this._currentRetries} times > max ${this._maxRetries}`));break}this._sleepWaiter=g.wait(s),await this._sleepWaiter.promise}if(this._taskingFlag.promise.finally(()=>{this.resetRetryPolicy(),this._taskingFlag=void 0;const t=Date.now()-e;this.emit(K.Completed,this._currentRetries,t)}),!_t.isAlwaysTask(this._task))return this._taskingFlag.promise}_assertChangeable(t){if(null!=this._taskingFlag)throw new Error(`No Change "${t}" After Retrier Started`)}}function bt(t){return t<=0||t===1/0}function Et(t){const e=new xt;return e.name(t),e}function Lt(){const t=new xt;return t.infinite(),t}function Tt(t){const e=new xt;return e.times(t),e}function Nt(t){const e=new xt;return e.maxRetries(t),e}function It(t){const e=new xt;return e.min(t),e}function St(t){const e=new xt;return e.max(t),e}function Ft(t,e){const r=new xt;return r.range(t,e),r}function Rt(t){const e=new xt;return e.fixedInterval(t),e}function At(t,e=500){const r=new xt;return r.fixedBackoff(t,e),r}function Pt(t){const e=new xt;return e.fixedIncrease(t),e}function jt(t,e=500){const r=new xt;return r.linearBackoff(t,e),r}function Ot(t){const e=new xt;return e.factorIncrease(t),e}function $t(t=500){const e=new xt;return e.exponentialBackoff(t),e}function Ct(t){const e=new xt;return e.shuttleInterval(t),e}function Bt(t){const e=new xt;return e.timeout(t),e}function Mt(t){const e=new xt;return e.taskTimeout(t),e}function Dt(t){const e=new xt;return e.task(t),e.start()}var Ut={name:Et,infinite:Lt,times:Tt,maxRetries:Nt,min:It,max:St,range:Ft,fixedInterval:Rt,fixedBackoff:At,fixedIncrease:Pt,linearBackoff:jt,factorIncrease:Ot,exponentialBackoff:$t,shuttleInterval:Ct,timeout:Bt,taskTimeout:Mt,start:Dt};e(xt,Ut);var Wt={Policy:L,Retrier:xt,Event:K,RetrierFactory:Ut,...Ut};export{K as Event,L as Policy,xt as Retrier,Ut as RetrierFactory,Wt as default,$t as exponentialBackoff,Ot as factorIncrease,At as fixedBackoff,Pt as fixedIncrease,Rt as fixedInterval,Lt as infinite,jt as linearBackoff,St as max,Nt as maxRetries,It as min,Et as name,Ft as range,Ct as shuttleInterval,Dt as start,Mt as taskTimeout,Bt as timeout,Tt as times};
|
|
1
|
+
let t=class t extends Error{static isAggregatedErrorLike(t){return t&&Array.isArray(t.errors)}static isAggregatedError(e){return e instanceof t}constructor(t,e){super(t),this.errors=e??[]}addError(t){this.errors.push(t)}removeError(t){const e=this.errors.indexOf(t);return-1!==e&&(this.errors.splice(e,1),!0)}};var e=function(t,...e){if(null==t)throw new TypeError('"target" Should Not Nil');for(const r of e)if(null!=r)for(const e in r)void 0===t[e]&&(t[e]=r[e]);return t};var r={isArray:function(t){return Array.isArray(t)},isBoolean:function(t){return"boolean"==typeof t},isBuffer:function(t){return null!=t&&Buffer.isBuffer(t)},isFunction:n,isInstance:function(t){return null!=t&&"object"==typeof t&&!c(t)},isIterable:function(t){return null!=t&&"function"==typeof t[Symbol.iterator]},isDate:function(t){return null!=t&&t instanceof Date},isError:function(t){return null!=t&&t instanceof Error},isMap:function(t){return null!=t&&"object"==typeof t&&t.constructor===Map},isWeakMap:function(t){return null!=t&&"object"==typeof t&&t.constructor===WeakMap},isNumber:o,isPositive:i,isNegative:function(t){return!!o(t)&&t<0},isNotNegative:a,isNil:s,isNullOrUndefined:function(t){return null==t},isNull:function(t){return null===t},isUndefined:function(t){return void 0===t},isPlainObject:c,isObject:function(t){return null!=t&&"object"==typeof t},isPromise:l,isRegExp:function(t){return null!=t&&"object"==typeof t&&t.constructor===RegExp},isSet:function(t){return null!=t&&"object"==typeof t&&t.constructor===Set},isWeakSet:function(t){return null!=t&&"object"==typeof t&&t.constructor===WeakSet},isStream:function(t){return null!=t&&"function"==typeof t.pipe},isString:u,isSymbol:function(t){return null!=t&&"symbol"==typeof t},isPrimitive:function(t){return null!==t&&("string"==typeof t||"number"==typeof t||"boolean"==typeof t)},isInt8Array:function(t){return t instanceof Int8Array},isUint8Array:function(t){return t instanceof Uint8Array},isUint8ClampedArray:function(t){return t instanceof Uint8ClampedArray},isInt16Array:function(t){return t instanceof Int16Array},isUint16Array:function(t){return t instanceof Uint16Array},isInt32Array:function(t){return t instanceof Int32Array},isUint32Array:function(t){return t instanceof Uint32Array},isFloat32Array:function(t){return t instanceof Float32Array},isFloat64Array:function(t){return t instanceof Float64Array},isBigInt64Array:function(t){return t instanceof BigInt64Array},isBigUint64Array:function(t){return t instanceof BigUint64Array},isTypedArray:function(t){return ArrayBuffer.isView(t)&&t.constructor!==DataView},isArrayBuffer:function(t){return t instanceof ArrayBuffer}};function n(t){return"function"==typeof t}function s(t){return null==t}function i(t){return!!o(t)&&t>0}function a(t){return!!o(t)&&t>=0}function o(t){return null!=t&&"number"==typeof t}function c(t){return null!==t&&"object"==typeof t&&(t.constructor===Object||void 0===t.constructor)}function l(t){return null!=t&&"function"==typeof t.then}function u(t){return null!=t&&"string"==typeof t}var h={assertNumber:m,assertPositive:function(t,e){if(!i(t))throw new Error(`${e?'"'+e+'" ':""}Not Positive: ${t}`)},assertNotNegative:_,assertFunction:w,assertNotNil:function(t,e){if(s(t))throw new Error((e?'"'+e+'" ':"")+"Should Not Nil")},assertString:function(t,e){if(!u(t))throw new Error(`${e?'"'+e+'" ':""}Not String: type=${typeof t} value=${p(t)}`)}};function f(t,e){if(!Array.isArray(t))throw new Error(`${e?'"'+e+'" ':""}Not Array: type=${typeof t} value=${p(t)}`)}function m(t,e){if(!o(t))throw new Error(`${e?'"'+e+'" ':""}Not Number: type=${typeof t} value=${p(t)}`)}function _(t,e){if(!a(t))throw new Error(`${e?'"'+e+'" ':""}Not "0 or Positive": ${t}`)}function w(t,e){if(!n(t))throw new Error(`${e?'"'+e+'" ':""}Not Function: type=${typeof t} value=${p(t)}`)}function d(t,e){if(!l(t))throw new Error(`${e?'"'+e+'" ':""}Not Promise: type=${typeof t} value=${p(t)}`)}function p(t){if(null===t)return"null";if(void 0===t)return"undefined";let e;try{e=JSON.stringify(t)}catch(r){e=t.toString()}return e}var g={any:function(e){if(f(e),0===e.length)throw new Error("Empty Tasks");const n=y(),s=[];for(let i=0;i<e.length;i++){const a=e[i];let o;if(r.isPromise(a))o=a;else{if(!r.isFunction(a)){s.push(new Error(`Invalid Task at index ${i}/${e.length-1}: ${a}`));continue}o=k(a)}o.then(t=>{n.resolve(t)}).catch(r=>{s.push(r),s.length>=e.length&&n.reject(new t("All Tasks Failed",s))})}return s.length===e.length&&n.reject(new t("All Tasks Failed",s)),n.promise},defer:y,delay:function(t,e){r.isNumber(t)?(e=t,t=Promise.resolve()):null==t&&null==e&&(e=1,t=Promise.resolve()),null!=t&&d(t),m(e=e??1e3);const n=y(),s=Date.now();return t.then((...t)=>{const r=Date.now()-s;r<e?setTimeout(()=>n.resolve(...t),e-r):n.resolve(...t)}).catch(t=>{const r=Date.now()-s;r<e?setTimeout(()=>n.reject(t),e-r):n.reject(t)}),n.promise},timeout:function(t,e,r){d(t),m(e=e??1);const n=y(e,r),s=Date.now();return t.then((...t)=>{Date.now()-s<=e?n.resolve(...t):n.reject(new Error(r??`Promise Timeout: ${e}ms`))}).catch(t=>{!n.resolved&&!n.rejected&&n.reject(t)}),n.promise},allSettled:v,returnValuePromised:k,series:async function(t){f(t);const e=[];for(const n of t)if(w(n),r.isFunction(n))e.push(await k(n));else{if(!r.isPromise(n))throw new Error(`Invalid Task: ${n}`);e.push(await n)}return e},seriesAllSettled:async function(t){f(t);const e=[];for(const r of t){w(r);try{e.push({ok:!0,result:await r()})}catch(t){e.push({ok:!1,result:t})}}return e},parallel:async function(t,e=5){if(f(t),m(e),e<=0)throw new Error(`Invalid maxParallel: ${e}, should > 0`);t.forEach(t=>w(t));const r=[];if(t.length<=e){const e=await Promise.all(t.map(t=>k(t)));return r.push(...e),r}const n=[];for(const s of t)if(w(s),n.push(s),n.length>=e){const t=await Promise.all(n.map(t=>k(t)));r.push(...t),n.length=0}if(n.length>0&&n.length<e){const t=await Promise.all(n.map(t=>k(t)));r.push(...t)}return r},parallelAny:async function(e,n=5,s){if(f(e,"tasks"),m(n),0===e.length)throw new Error("Empty Tasks");if(n<=0)throw new Error(`Invalid maxParallel: ${n}, should > 0`);const i=[];let a=0,o=0;const c=y();function l(){if(a>=e.length)return;if(o>n)return;const u=e[a++];let h;o++,h=r.isPromise(u)?u:r.isFunction(u)?k(u):Promise.reject(new TypeError(`Invalid task: ${typeof u}, Only Promise or Function allowed`)),h.then(t=>{o--,c.resolve(t)}).catch(r=>{i.push(r),i.length>=e.length&&c.pending?c.reject(new t(s??"All Tasks Failed",i)):(o--,l())})}const u=Math.min(e.length,n);for(let t=0;t<u;t++)l();return c.promise},parallelAllSettled:async function(t,e=5){if(f(t),m(e),e<=0)throw new Error(`Invalid maxParallel: ${e}, should > 0`);t.forEach(t=>w(t));const r=[];if(t.length<=e){const e=await v(t.map(t=>k(t)));return r.push(...e),r}const n=[];for(const s of t)if(n.push(s),n.length>=e){const t=await v(n.map(t=>k(t)));r.push(...t),n.length=0}if(n.length>0&&n.length<e){const t=await v(n.map(t=>k(t)));r.push(...t)}return r},wait:function(t){_(t);const e={};let r;return e.timerHandler=r=setTimeout(()=>{clearTimeout(r),e._resolve()},t),e.promise=new Promise((t,n)=>{e._resolve=e=>{null!=r&&clearTimeout(r),t(e)}}),e.wakeup=()=>{e._resolve()},e}};function y(t=-1,e){m(t);const r={};let n;return r.pending=!0,r.canceled=!1,r.rejected=!1,r.resolved=!1,t>=0&&(r.timerCleared=!1,r.timerHandler=n=setTimeout(()=>{clearTimeout(n),r.timerCleared=!0,r.reject(new Error(e??`Promise Timeout: ${t}ms`))},t)),r.promise=new Promise((t,e)=>{r.resolve=e=>{r.resolved||r.rejected||r.canceled||(null!=n&&(clearTimeout(n),r.timerCleared=!0),r.pending=!1,r.canceled=!1,r.rejected=!1,r.resolved=!0,t(e))},r.reject=t=>{r.resolved||r.rejected||r.canceled||(null!=n&&(clearTimeout(n),r.timerCleared=!0),r.pending=!1,r.canceled=!1,r.resolved=!1,r.rejected=!0,e(t))}}),r.cancel=r.promise.cancel=t=>{r.resolved||r.rejected||r.canceled||(null!=n&&(clearTimeout(n),r.timerCleared=!0),r.reject(t??new Error("Cancelled")),r.canceled=r.promise.canceled=!0)},r}async function v(t){f(t);const e=await Promise.allSettled(t),r=[];for(const t of e)"fulfilled"===t.status&&r.push({ok:!0,result:t.value}),"rejected"===t.status&&r.push({ok:!1,result:t.reason});return r}function k(t){try{const e=t();return r.isPromise(e)?e:Promise.resolve(e)}catch(t){return Promise.reject(t)}}new TextDecoder,new TextEncoder;const{assertPositive:x,assertNotNegative:b}=h,{isNumber:E}=r;class L{constructor(){this._min=50,this._max=3e4,this._nextInterval=this._min,this._jitter=0}get jitter(){return this._jitter}set jitter(t){b(t,"jitter"),this._jitter=t}copyPolicySettingTo(t){t.range(this._min,this._max),t._nextInterval=this._nextInterval}range(t,e){if(x(t,"min"),x(e,"max"),t>=e)throw new Error("min must < max");return this._min=t,this._nextInterval<this._min&&(this._nextInterval=this._min),this._max=e,this._nextInterval>this._max&&(this._nextInterval=this._max),this}min(t){if(x(t,"min"),t>=this._max)throw new Error("min must < max");return this._min=t,this._nextInterval<this._min&&(this._nextInterval=this._min),this}max(t){if(x(t,"max"),t<=this._min)throw new Error("max must > min");return this._max=t,this._nextInterval>this._max&&(this._nextInterval=this._max),this}reset(){return this._nextInterval=this._min,this}generate(t){const e=this._nextInterval;return this._increase(t),e}_increase(t){const e=this._next(t);if(!E(e))throw new Error("Generated Next Interval Not Number");const r=this._jitter<=0?e:e+Math.floor(Math.random()*this._jitter);return r<this._min?this._nextInterval=this._min:r>this._max?this._nextInterval=this._max:this._nextInterval=r}_next(t){throw new Error("Not Impled Yet")}}var T={isFunction:N,isNil:I};function N(t){return"function"==typeof t}function I(t){return null==t}function S(t){return null!=t&&"string"==typeof t}var F={assertNumber:function(t,e){if(!function(t){return null!=t&&"number"==typeof t}(t))throw new Error(`${e?'"'+e+'" ':""}Not Number: type=${typeof t} value=${R(t)}`)},assertFunction:function(t,e){if(!N(t))throw new Error(`${e?'"'+e+'" ':""}Not Function: type=${typeof t} value=${R(t)}`)},assertNotNil:function(t,e){if(I(t))throw new Error((e?'"'+e+'" ':"")+"Should Not Nil")},assertString:function(t,e){if(!S(t))throw new Error(`${e?'"'+e+'" ':""}Not String: type=${typeof t} value=${R(t)}`)},assertStringOrSymbol:function(t,e){if(!S(t)&&!function(t){return null!=t&&"symbol"==typeof t}(t))throw new Error(`${e?'"'+e+'" ':""}Not String or Symbol: type=${typeof t} value=${R(t)}`)}};function R(t){if(null===t)return"null";if(void 0===t)return"undefined";let e;try{e=JSON.stringify(t)}catch(r){e=t.toString()}return e}new TextDecoder,new TextEncoder;const A="DOwner$#$",{assertFunction:P,assertNotNil:j}=F;class O{constructor(t,e,r=!1){j(t,"event"),P(e,"callback"),this._event=t,this._callback=e,this._isOnce=!!r,this._owner=void 0}set owner(t){this._owner=t}get owner(){return this._owner===A?void 0:this._owner}get event(){return this._event}get isOnce(){return this._isOnce}isSameCallback(t){return this._callback===t}get callback(){return this._callback}invoke(...t){try{return this._callback(...t)}finally{if(this._isOnce)try{this._event._remove(this)}catch(t){console.warn(t)}}}listener(...t){return this.invoke(...t)}}const{isFunction:$,isNil:C}=T,{assertStringOrSymbol:B,assertFunction:M}=F;class D{static get DefaultOwner(){return A}constructor(t){B(t,"eventName"),this._name=t,this._callbacks=new Set,this._listeners=[],this._callback2Listeners=new Map,this._listener2Owner=new Map,this._owner2Listeners=new Map}get name(){return this._name}isEmpty(){return 0===this._callbacks.size}rawListeners(){return[...this._listeners]}listenerCount(t){return null==t?this._listeners.length:this._callback2Listeners.get(t)?.size??0}callbacks(){return[...this.rawListeners().map(t=>t.callback)]}emit(...t){if(0===this._listeners.length)return!1;for(const e of[...this._listeners])e.invoke(...t);return!0}emitOwner(t,...e){if(0===this._listeners.length)return!1;const r=this._owner2Listeners.get(t);if(null==r)return!1;for(const t of[...r])t.invoke(...e);return!0}hasListener(t){return!!$(t)&&this._callbacks.has(t)}hasOwner(t){return!C(t)&&this._owner2Listeners.has(t)}addListener(t,e){return this._addListener(t,e,!1,!1)}prependListener(t,e){return this._addListener(t,e,!1,!0)}addOnceListener(t,e){return this._addListener(t,e,!0,!1)}prependOnceListener(t,e){return this._addListener(t,e,!0,!0)}_addListener(t,e,r,n){if(C(t))return!1;M(t),this._callbacks.has(t)||this._callbacks.add(t),e=e??A;const s=new O(this,t,r);s.owner=e,n?this._listeners.unshift(s):this._listeners.push(s),this._listener2Owner.set(s,e);let i=this._callback2Listeners.get(t);null==i&&(i=new Set,this._callback2Listeners.set(t,i)),i.add(s);let a=this._owner2Listeners.get(e);return null==a&&(a=new Set,this._owner2Listeners.set(e,a)),a.add(s),!0}removeListener(t){if(C(t))return!1;if(!this._callbacks.has(t))return!1;this._callbacks.delete(t);const e=this._callback2Listeners.get(t);if(null==e)return!1;this._callback2Listeners.delete(t);for(const t of e){-1!==this._listeners.indexOf(t)&&this._listeners.splice(this._listeners.indexOf(t),1);const e=this._listener2Owner.get(t);if(null==e)continue;this._listener2Owner.delete(t);const r=this._owner2Listeners.get(e);null!=r&&(r.delete(t),0===r.size&&this._owner2Listeners.delete(e))}return!0}_remove(t){const e=this._listeners.indexOf(t);-1!==e&&this._listeners.splice(e,1);const{callback:r}=t,n=this._callback2Listeners.get(r);null!=n&&(n.delete(t),0===n.size&&(this._callback2Listeners.delete(r),this._callbacks.delete(r)));const s=this._listener2Owner.get(t);if(null==s)return;this._listener2Owner.delete(t);const i=this._owner2Listeners.get(s);null!=i&&(i.delete(t),0===i.size&&this._owner2Listeners.delete(s))}removeAllListeners(t){if(C(t))return this._callbacks.clear(),this._listeners.length=0,this._callback2Listeners.clear(),this._listener2Owner.clear(),this._owner2Listeners.clear(),this;const e=this._owner2Listeners.get(t);if(null==e)return this;this._owner2Listeners.delete(t);for(const t of e){-1!==this._listeners.indexOf(t)&&this._listeners.splice(this._listeners.indexOf(t),1),this._listener2Owner.delete(t);const{callback:e}=t,r=this._callback2Listeners.get(e);null!=r&&(r.delete(t),0===r.size&&(this._callback2Listeners.delete(e),this._callbacks.delete(e)))}return this}}const{isNil:U}=T,{assertString:W,assertFunction:z,assertNumber:H,assertStringOrSymbol:V,assertNotNil:J}=F,G=["on","once","addListener","prependListener","prependOnceListener","off","offAll","offOwner","removeAllListeners","removeListener","emit","emitOwner","setMaxListeners","getMaxListeners","hasOwner","listeners","listenerCount","eventNames","rawListeners"];let Y=10;class q{static mixin(t){const e=new q;t.__emitter=e;for(const r of G){const n=e[r];t[r]=n.bind(e)}return t}static get defaultMaxListeners(){return Y}static set defaultMaxListeners(t){H(t),Y=t??10}constructor(){this._name2Event=new Map,this._maxListeners=Y}addListener(t,e,r){return this.on(t,e,r)}prependListener(t,e,r){return W(t),z(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).prependListener(e,r),this}prependOnceListener(t,e,r){return W(t),z(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).prependOnceListener(e,r),this}emit(t,...e){const r=this._name2Event.get(t);return null!=r&&!r.isEmpty()&&(r.emit(...e),!0)}emitOwner(t,e,...r){if(null==e)throw new Error('Missing "owner"');const n=this._name2Event.get(t);return null!=n&&!n.isEmpty()&&(n.emitOwner(e,...r),!0)}eventNames(){return[...this._name2Event.keys()]}getMaxListeners(){return this._maxListeners}listenerCount(t,e){V(t,"eventName");const r=this._name2Event.get(t);return null==r||r.isEmpty()?0:r.listenerCount(e)}listeners(t){V(t,"eventName");const e=this._name2Event.get(t);return null==e||e.isEmpty()?[]:e.callbacks()}off(t,e){const r=this._name2Event.get(t);return null==r?this:(r.removeListener(e),r.isEmpty()?(this._name2Event.delete(t),this):this)}offAll(t,e){V(t,"eventName");const r=this._name2Event.get(t);return null==r?this:(r.removeAllListeners(e),r.isEmpty()?(this._name2Event.delete(t),this):this)}offOwner(t){J(t,"owner");const e=[...this._name2Event.values()];for(const r of e)r.removeAllListeners(t),r.isEmpty()&&this._name2Event.delete(r.name);return this}on(t,e,r){return W(t),z(e),this._checkMaxListeners(t),this._getOrCreateEvent(t).addListener(e,r),this}_checkMaxListeners(t){let e=0;0!==this._maxListeners&&this._maxListeners!==1/0&&(e=this.listenerCount(t))>=this._maxListeners&&console.warn(`maxlistenersexceededwarning: Possible EventEmitter memory leak detected. ${e} ${t} listeners added to [${this}]. Use emitter.setMaxListeners() to increase limit`)}once(t,e,r){return W(t),z(e),this._getOrCreateEvent(t).addOnceListener(e,r),this}rawListeners(t){return this._name2Event.get(t)?.rawListeners()||[]}removeAllListeners(t,e){return this.offAll(t,e)}removeListener(t,e){return this.off(t,e)}setMaxListeners(t){if(H(t),t<0)throw new RangeError("maxListeners must >=0");return this._maxListeners=t,this}_getOrCreateEvent(t){if(this._name2Event.has(t))return this._name2Event.get(t);const e=new D(t);return this._name2Event.set(t,e),e}hasOwner(t){if(U(t))return!1;for(const e of this._name2Event.values())if(e.hasOwner(t))return!0;return!1}}var K={Start:"start",Retry:"retry",Success:"success",Failure:"failure",Timeout:"timeout",TaskTimeout:"task-timeout",Stop:"stop",Completed:"complete",MaxRetries:"max-retries"};const{assertPositive:Q}=h;class X extends L{constructor(t){super(),this.interval=t}set interval(t){Q(t,"interval"),this._interval=t,this._nextInterval=t,this._min=t,this._max=t}get interval(){return this._interval}_next(t){return this.interval}}const{assertPositive:Z}=h;class tt extends L{constructor(t){super(),Z(t,"increasement"),this._increasement=t}set increasement(t){Z(t,"increasement"),this._increasement=t}get increasement(){return this._increasement}_next(t){return this._nextInterval>=this._max?this._max:this._nextInterval+this.increasement}}const{assertPositive:et}=h;class rt extends L{constructor(t){if(super(),et(t,"factor"),t<1)throw new Error("factor must be >= 1");this._factor=t}set factor(t){if(et(t,"factor"),t<1)throw new Error("factor must be >= 1");this._factor=t}get factor(){return this._factor}_next(t){return this._nextInterval>=this._max?this._max:this._nextInterval*this.factor}}const{assertPositive:nt}=h;class st extends L{constructor(t){super(),nt(t,"stepLength"),this._stepLength=t,this.increasement=t}set stepLength(t){nt(t,"stepLength"),this._stepLength=t,this.increasement=t}get stepLength(){return this._stepLength}_next(t){const e=this._nextInterval+this.increasement;return e>=this._max?(this.increasement=-this.stepLength,this._max):e<=this._min?(this.increasement=this.stepLength,this._min):e}}const{assertNotNegative:it}=h;class at extends X{constructor(t,e=500){super(t),it(e,"jitter"),this._jitter=e??500}}const{assertNotNegative:ot}=h;class ct extends rt{constructor(t=500){super(2),ot(t,"jitter"),this._jitter=t??500}}const{assertNotNegative:lt}=h;class ut extends tt{constructor(t,e=500){super(t),lt(e,"jitter"),this._jitter=e??500}}const{assertNotNil:ht,assertFunction:ft}=h;class mt{constructor(t,e){ht(t,"retrier"),ft(e,"task"),this.retrier=t,this.task=e,this.result=void 0,this.error=void 0}get failed(){return null!=this.error}get succeeded(){return null==this.error}async execute(t,e,r){try{this.result=await this.task(t,e,r),this.error=void 0}catch(t){this.error=t instanceof Error?t:new Error(String(t))}}dispose(){this.retrier=void 0}}class _t extends mt{static isAlwaysTask(t){return t instanceof _t}constructor(t,e,r){super(t,e),this.resetPolicy=r}async execute(t,e,r){await super.execute(t,e,r),this.succeeded&&this.resetPolicy&&this.retrier.resetRetryPolicy()}}class wt extends mt{static isForeverTask(t){return t instanceof wt}constructor(t,e,r){super(t,e),this.resetPolicy=r}async execute(t,e,r){await super.execute(t,e,r),this.succeeded&&this.resetPolicy&&this.retrier.resetRetryPolicy()}}const{assertPositive:dt,assertString:pt,assertFunction:gt,assertNumber:yt}=h,{isNil:vt}=r,kt="!#@%$&^*";class xt{static naming(t){const e=new xt;return e.name(t),e}static infinite(){const t=new xt;return t.infinite(),t}static times(t){const e=new xt;return e.times(t),e}static maxRetries(t){const e=new xt;return e.maxRetries(t),e}static min(t){const e=new xt;return e.min(t),e}static max(t){const e=new xt;return e.max(t),e}static range(t,e){const r=new xt;return r.range(t,e),r}static fixedInterval(t){const e=new xt;return e.fixedInterval(t),e}static fixedBackoff(t,e=500){const r=new xt;return r.fixedBackoff(t,e),r}static fixedIncrease(t){const e=new xt;return e.fixedIncrease(t),e}static linearBackoff(t,e=500){const r=new xt;return r.linearBackoff(t,e),r}static factorIncrease(t){const e=new xt;return e.factorIncrease(t),e}static exponentialBackoff(t=500){const e=new xt;return e.exponentialBackoff(t),e}static shuttleInterval(t){const e=new xt;return e.shuttleInterval(t),e}static timeout(t){const e=new xt;return e.timeout(t),e}static taskTimeout(t){const e=new xt;return e.taskTimeout(t),e}static start(t){const e=new xt;return e.task(t),e.start()}constructor(t){q.mixin(this),this._policy=new X(t??1e3),this._maxRetries=3,this._currentRetries=1,this._timeout=12e4,this._taskTimeout=2e3,this._name="unamed",this._taskingFlag=void 0,this._breakFlag=void 0,this._breakReason=void 0}get running(){return!vt(this._taskingFlag)}name(t){return pt(t,"name"),this._assertChangeable(t),this._name=t,this}infinite(){return this._assertChangeable("infinite"),this._maxRetries=1/0,this}times(t){return this._assertChangeable("times"),this.maxRetries(t)}maxRetries(t){return dt(t,"maxRetries"),this._assertChangeable("maxRetries"),this._maxRetries=t,this}min(t){return this._assertChangeable("min"),this._policy.min(t),this}max(t){return this._assertChangeable("max"),this._policy.max(t),this}range(t,e){return this._assertChangeable("range"),this._policy.range(t,e),this}fixedInterval(t){this._assertChangeable("fixedInterval");const e=this._policy;if(e instanceof X)return e.interval=t,this;const r=new X(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}fixedBackoff(t,e=500){this._assertChangeable("fixedBackoff");const r=this._policy;if(r instanceof X)return r.interval=t,r.jitter=e,this;const n=new at(t,e);return r?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}fixedIncrease(t){this._assertChangeable("fixedIncrease");const e=this._policy;if(e instanceof tt)return e.increasement=t,this;const r=new tt(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}linearBackoff(t,e=500){this._assertChangeable("linearBackoff");const r=this._policy;if(r instanceof ut)return r.increasement=t,r.jitter=e,this;const n=new ut(t,e);return r?.copyPolicySettingTo(n),n.reset(),this._policy=n,this}factorIncrease(t){this._assertChangeable("factorIncrease");const e=this._policy;if(e instanceof rt)return e.factor=t,this;const r=new rt(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}exponentialBackoff(t=500){this._assertChangeable("exponentialBackoff");const e=this._policy;if(e instanceof ct)return e.jitter=t,this;const r=new ct(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}shuttleInterval(t){this._assertChangeable("shuttleInterval");const e=this._policy;if(e instanceof st)return e.stepLength=t,this;const r=new st(t);return e?.copyPolicySettingTo(r),r.reset(),this._policy=r,this}taskTimeout(t){return dt(t,"taskTimeout"),this._assertChangeable("taskTimeout"),this._taskTimeout=t,this}timeout(t){return yt(t,"timeout"),this._assertChangeable("timeout"),this._timeout=t,this}noTimeout(){return this._assertChangeable("noTimeout"),this._timeout=0,this}task(t){return gt(t,"task"),this._assertChangeable("task"),this._task=new mt(this,t),this}retry(t){return this._assertChangeable("retry"),this.task(t),this}always(t,e=!0){return this._assertChangeable("always"),this._task=new _t(this,t,e),this}forever(t,e=!0){return this._assertChangeable("forever"),this.noTimeout(),this.infinite(),this._task=new wt(this,t,e),this}async start(){if(null==this._task)throw new Error("No Task to Retry");return null!=this._taskingFlag||(this._taskingFlag=g.defer(),wt.isForeverTask(this._task)?(this._executeForeverTask(this._task),this._taskingFlag.resolve()):this._executeEndableTask(this._task)),this._taskingFlag.promise}wakeup(){this.running?null!=this._sleepWaiter&&this._sleepWaiter.wakeup():this.start()}async stop(t){if(this.emit(K.Stop,t),null!=this._taskingFlag)return null!=this._breakFlag||(null!=this._sleepWaiter&&this._sleepWaiter.wakeup(),this._breakFlag=g.defer(),this._breakReason=t??new Error("Manually Stop"),this.once(K.Completed,()=>{this._breakFlag?.resolve()}),this._breakFlag.promise.finally(()=>{this._breakFlag=void 0,this._breakReason=void 0})),this._breakFlag.promise}resetRetryPolicy(){this._policy.reset()}onRetry(t){return this.on(K.Retry,t),this}onError(t){return this.on(K.Error,t),this}onFailure(t){return this.on(K.Failure,t),this}onSuccess(t){return this.on(K.Success,t),this}onStart(t){return this.on(K.Start,t),this}onStop(t){return this.on(K.Stop,t),this}onTimeout(t){return this.on(K.Timeout,t),this}onTaskTimeout(t){return this.on(K.TaskTimeout,t),this}onCompleted(t){return this.on(K.Completed,t),this}onMaxRetries(t){return this.on(K.MaxRetries,t),this}async _executeForeverTask(t){if(null==this._taskingFlag)throw new Error("Must be called in start()");const e=Date.now();this.emit(K.Start,e);let r=null;for(;;){if(null!=this._breakFlag){const t=Date.now()-e;this.emit(K.Completed,this._currentRetries,t);break}r=Date.now()-e,this.emit(K.Retry,this._currentRetries,r);const n=this._policy.generate(this._currentRetries);try{try{await g.timeout(t.execute(this._currentRetries,r,n),this._taskTimeout,kt)}catch(t){throw t.message===kt&&this.emit(K.TaskTimeout,this._currentRetries,r,this._taskTimeout),t}if(t.failed)throw t.error;const e=t.result;this.emit(K.Success,e,this._currentRetries,r)}catch(t){this.emit(K.Failure,t,this._currentRetries,r)}++this._currentRetries,this._sleepWaiter=g.wait(n),await this._sleepWaiter.promise}}async _executeEndableTask(t){if(null==this._taskingFlag)throw new Error("Must be called in start()");const e=Date.now();let r;this.emit(K.Start,e);let n=null;for(;;){if(null!=this._breakFlag){this._taskingFlag.reject(this._breakReason??new Error("Have Been Broken"));break}if(n=Date.now()-e,!bt(this._timeout)&&n>=this._timeout){if(this.emit(K.Timeout,this._currentRetries,n,this._timeout),_t.isAlwaysTask(this._task)){this._taskingFlag.resolve();break}this._taskingFlag.reject(r??new Error(`Timeout "${this._timeout}" Exceeded`));break}this.emit(K.Retry,this._currentRetries,n);const s=this._policy.generate(this._currentRetries);try{try{await g.timeout(t.execute(this._currentRetries,n,s),this._taskTimeout,kt)}catch(t){throw t.message===kt&&this.emit(K.TaskTimeout,this._currentRetries,n,this._taskTimeout),t}if(t.failed)throw r=t.error,t.error;const e=t.result;if(this.emit(K.Success,e,this._currentRetries,n),!_t.isAlwaysTask(t)){this._taskingFlag.resolve(e);break}}catch(t){this.emit(K.Failure,t,this._currentRetries,n)}const i=++this._currentRetries;if(this._currentRetries>this._maxRetries){if(this.emit(K.MaxRetries,i,this._maxRetries),_t.isAlwaysTask(t)){this._taskingFlag.resolve();break}this._taskingFlag.reject(r??new Error(`Max Retries Exceeded, Retring ${this._currentRetries} times > max ${this._maxRetries}`));break}this._sleepWaiter=g.wait(s),await this._sleepWaiter.promise}if(this._taskingFlag.promise.finally(()=>{this.resetRetryPolicy(),this._taskingFlag=void 0;const t=Date.now()-e;this.emit(K.Completed,this._currentRetries,t)}),!_t.isAlwaysTask(this._task))return this._taskingFlag.promise}_assertChangeable(t){if(null!=this._taskingFlag)throw new Error(`No Change "${t}" After Retrier Started`)}}function bt(t){return t<=0||t===1/0}function Et(t){const e=new xt;return e.name(t),e}function Lt(){const t=new xt;return t.infinite(),t}function Tt(t){const e=new xt;return e.times(t),e}function Nt(t){const e=new xt;return e.maxRetries(t),e}function It(t){const e=new xt;return e.min(t),e}function St(t){const e=new xt;return e.max(t),e}function Ft(t,e){const r=new xt;return r.range(t,e),r}function Rt(t){const e=new xt;return e.fixedInterval(t),e}function At(t,e=500){const r=new xt;return r.fixedBackoff(t,e),r}function Pt(t){const e=new xt;return e.fixedIncrease(t),e}function jt(t,e=500){const r=new xt;return r.linearBackoff(t,e),r}function Ot(t){const e=new xt;return e.factorIncrease(t),e}function $t(t=500){const e=new xt;return e.exponentialBackoff(t),e}function Ct(t){const e=new xt;return e.shuttleInterval(t),e}function Bt(t){const e=new xt;return e.timeout(t),e}function Mt(t){const e=new xt;return e.taskTimeout(t),e}function Dt(t){const e=new xt;return e.task(t),e.start()}var Ut={retry:function(t){const e=new xt;return e.retry(t),e},always:function(t){const e=new xt;return e.always(t),e},forever:function(t){const e=new xt;return e.forever(t),e},name:Et,infinite:Lt,times:Tt,maxRetries:Nt,min:It,max:St,range:Ft,fixedInterval:Rt,fixedBackoff:At,fixedIncrease:Pt,linearBackoff:jt,factorIncrease:Ot,exponentialBackoff:$t,shuttleInterval:Ct,timeout:Bt,taskTimeout:Mt,start:Dt};e(xt,Ut);var Wt={Policy:L,Retrier:xt,Event:K,RetrierFactory:Ut,...Ut};export{K as Event,L as Policy,xt as Retrier,Ut as RetrierFactory,Wt as default,$t as exponentialBackoff,Ot as factorIncrease,At as fixedBackoff,Pt as fixedIncrease,Rt as fixedInterval,Lt as infinite,jt as linearBackoff,St as max,Nt as maxRetries,It as min,Et as name,Ft as range,Ct as shuttleInterval,Dt as start,Mt as taskTimeout,Bt as timeout,Tt as times};
|
|
2
2
|
//# sourceMappingURL=index-min.js.map
|