@ndriadev/futurable 2.3.2 → 2.3.5

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.cjs ADDED
@@ -0,0 +1 @@
1
+ "use strict";var P=Object.defineProperty,F=(g,t,n)=>t in g?P(g,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):g[t]=n,v=(g,t,n)=>(F(g,typeof t!="symbol"?t+"":t,n),n),p=(g=>(g.PENDING="pending",g.FULFILLED="fulfilled",g.REJECTED="rejected",g))(p||{});class Futurable extends Promise{constructor(t,n){const l=n?null:new AbortController,e=n||l.signal,i=[],c=()=>{for(const r of i)clearTimeout(r)};let s;const a={signal:e,cancel:()=>this.controller?.abort(),onCancel:r=>{s=r},delay:(r,h)=>new Futurable(f=>{i.push(setTimeout(()=>{f(r())},h))},e),sleep:r=>a.delay(()=>{},r),fetch:(r,h)=>new Futurable((f,m)=>{fetch(r,{...h||{},signal:e}).then(w=>f(w)).catch(w=>{w.name!=="AbortError"&&m(w)})},e),futurizable:r=>new Futurable((h,f)=>{r.then(h).catch(f)},e)};let o="pending";const d=new Promise((r,h)=>{if(e.aborted){c();return}else{const f=typeof e.onabort=="function"?e.onabort:()=>{};e.onabort=()=>{f(),c(),o==="pending"&&s&&s()},t(m=>{o="fulfilled",r(m)},m=>{o="rejected",h(m)},a)}});super((r,h)=>{d.then(f=>r(f)).catch(h)}),v(this,"controller"),v(this,"internalSignal"),v(this,"idsTimeout"),this.controller=l,this.internalSignal=e,this.idsTimeout=i}static get[Symbol.species](){return this}get[Symbol.toStringTag](){return"Futurable"}get signal(){return this.internalSignal}clearTimeout(){for(const t of this.idsTimeout)clearTimeout(t)}then(t,n){let l,e;const i=new Futurable((c,s)=>{l=c,e=s},this.internalSignal);return i.controller=this.controller,super.then(c=>{if(this.internalSignal?.aborted){this.clearTimeout();return}try{l(t?t(c):c)}catch(s){e(s)}},c=>{if(this.internalSignal?.aborted){this.clearTimeout();return}try{n?l(n(c)):e(c)}catch(s){e(s)}}),i}catch(t){return this.then(null,t)}finally(t){return this.then(n=>(t(),n),n=>{if(t(),n instanceof Error)throw n;return n})}cancel(){!this.internalSignal?.aborted&&this.controller?.abort()}delay(t,n){let l,e;const i=new Futurable((c,s)=>{l=c,e=s},this.internalSignal);return i.controller=this.controller,this.then(c=>{this.idsTimeout.push(setTimeout(()=>l(t(c)),n))},c=>{e(c)}),i}sleep(t){return this.delay(n=>n,t)}fetch(t,n){let l,e;const i=new Futurable((c,s)=>{l=c,e=s},this.internalSignal);return i.controller=this.controller,this.then(c=>{const s=typeof t=="function"?t(c):t,a={...typeof n=="function"?n(c):n,signal:this.internalSignal};fetch(s,a).then(o=>l(o)).catch(o=>{o.name!=="AbortError"&&e(o)})}),i}onCancel(t){let n,l;const e=new Futurable((i,c,s)=>{s.onCancel(t),n=i,l=c},this.internalSignal);return e.controller=this.controller,this.then(i=>n(i),i=>l(i)),e}futurizable(t){let n,l;const e=new Futurable((i,c)=>{n=i,l=c},this.internalSignal);return e.controller=this.controller,this.then(i=>{(typeof t=="function"?t(i):t).then(n).catch(l)}),e}static resolve(t,n){return t?new Futurable(l=>l(t),n):new Futurable(l=>l(),n)}static reject(t,n){return new Futurable((l,e)=>e(t),n)}static onCancel({cb:t,signal:n}){return new Futurable((l,e,i)=>{i.onCancel(()=>l(t()))},n)}static delay({cb:t,timer:n,signal:l}){return new Futurable((e,i,c)=>{c.delay(t,n).then(e,i)},l)}static sleep({timer:t,signal:n}){return Futurable.delay({cb:()=>{},timer:t,signal:n})}static fetch(t,n){const l=n?.signal||void 0;return n?.signal&&delete n.signal,new Futurable((e,i,c)=>{c.fetch(t,n).then(e).catch(i)},l)}static futurizable({promise:t,signal:n}){return new Futurable((l,e)=>{t.then(l).catch(e)},n)}static handleValues(t,n){const l=[];for(const e in t)t[e]instanceof Futurable?l.push(t[e]):t[e]instanceof Promise?l.push(new Futurable((i,c)=>{t[e].then(s=>i(s)).catch(c)},n)):l.push(new Futurable(i=>i(t[e]),n));return l}static all(t,n){let l,e;const i=new Futurable((s,a,o)=>{l=s,e=a,o.onCancel(()=>{for(const d of c)d.cancel()})},n);n||(n=i.internalSignal);const c=Futurable.handleValues(t,n);return super.all(c).then(s=>l(s)).catch(s=>e(s)),i}static allSettled(t,n){let l;const e=new Futurable((c,s,a)=>{l=c,a.onCancel(()=>{for(const o of i)o.cancel()})},n);n||(n=e.internalSignal);const i=Futurable.handleValues(t,n);return super.allSettled(i).then(c=>l(c)),e}static race(t,n){let l,e;const i=new Futurable((s,a,o)=>{l=s,e=a,o.onCancel(()=>{for(const d of c)d.cancel()})},n);n||(n=i.internalSignal);const c=Futurable.handleValues(t,n);return super.race(c).then(s=>l(s)).catch(s=>e(s)),i}static any(t,n){let l,e;const i=new Futurable((s,a,o)=>{l=s,e=a,o.onCancel(()=>{for(const d of c)d.cancel()})},n);n||(n=i.internalSignal);const c=Futurable.handleValues(t,n);return super.any(c).then(s=>l(s)).catch(s=>e(s)),i}static polling(t,{interval:n,signal:l,immediate:e}){let i,c,s;e&&(i=new Futurable((o,d,r)=>{r.onCancel(()=>{c&&c instanceof Futurable&&c.cancel()});const h=t();(h instanceof Futurable||h instanceof Promise)&&(c=h.then(()=>o()).catch(f=>s&&s(f)))},l));const a=setInterval(()=>{i&&i.cancel(),i=new Futurable((o,d,r)=>{r.onCancel(()=>{c&&c instanceof Futurable&&c.cancel()});const h=t();(h instanceof Futurable||h instanceof Promise)&&(c=h.then(()=>o()).catch(f=>s&&s(f)))},l)},n);return{cancel:()=>{a&&clearInterval(a),i&&i.cancel()},catch:o=>{s=o}}}static withResolvers(t){let n,l,e;const i=new Futurable((s,a,o)=>{n=s,l=a,e=o},t),c=i.cancel;return{resolve:n,reject:l,utils:e,cancel:c,promise:i}}}exports.Futurable=Futurable;
@@ -0,0 +1,255 @@
1
+ interface FuturableLike<T> {
2
+ /**
3
+ * Attaches callbacks for the resolution and/or rejection of the Futurable.
4
+ * @param onfulfilled The callback to execute when the Futurable is resolved.
5
+ * @param onrejected The callback to execute when the Futurable is rejected.
6
+ * @returns A Futurable for the completion of which ever callback is executed.
7
+ */
8
+ then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1> | FuturableLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2> | FuturableLike<TResult2>) | undefined | null): FuturableLike<TResult1 | TResult2>;
9
+ }
10
+ interface FuturableResolve<T> {
11
+ (value: T | FuturableLike<T> | PromiseLike<T>): void;
12
+ }
13
+ interface FuturableReject {
14
+ (reason?: any): void;
15
+ }
16
+ interface FuturableUtils<T> {
17
+ /**
18
+ * Internal futurable signal
19
+ */
20
+ signal: AbortSignal;
21
+ /**
22
+ * Cancel the futurable if it is to be executed or if it is still executing.
23
+ */
24
+ cancel: () => void;
25
+ /**
26
+ * Executes the callback passed as a parameter when the futurable is cancelled.
27
+ * @param cb: callback
28
+ */
29
+ onCancel: (cb: () => void) => void;
30
+ /**
31
+ * Waits for timer, then executes callback with the futurable value and returns the result obtained from the invocation.
32
+ * @param cb: callback executed after timer
33
+ * @param timer: timer to wait (in milliseconds)
34
+ */
35
+ delay: <TResult = T, TResult2 = never>(cb: () => TResult, timer: number) => FuturableLike<TResult | TResult2>;
36
+ /**
37
+ * Waits for timer parameter (in milliseconds) before returning the value.
38
+ * @param timer: timer to wait (in milliseconds)
39
+ */
40
+ sleep: (timer: number) => FuturableLike<void>;
41
+ /**
42
+ * Extension of the fetch API with cancellation support. Url parameter can be a string or a function with receive value from futurable chaining as paremeter.
43
+ * @param url: url to fetch
44
+ * @param opts: fetch options
45
+ */
46
+ fetch: (url: string, opts?: RequestInit) => Futurable<Response>;
47
+ /**
48
+ * Takes a promise and transforms it into a futurizable. Promise can be also a function that receives value from futurable chaining as parameter.
49
+ * @param promise: Promise to futurize
50
+ */
51
+ futurizable: <TResult = any>(promise: Promise<TResult>) => Futurable<TResult>;
52
+ }
53
+ type FuturableExecutor<T> = (resolve: FuturableResolve<T>, reject: FuturableReject,
54
+ /**
55
+ * Object containing implemented functionalities.
56
+ */
57
+ utils: FuturableUtils<T>) => void;
58
+ type FuturableIterable<T = any> = Iterable<FuturableLike<T> | PromiseLike<T> | T>;
59
+ interface FuturableWithResolvers<T> {
60
+ promise: Futurable<T> | Promise<T>;
61
+ resolve: (value: T | PromiseLike<T> | FuturableLike<T>) => void;
62
+ reject: (reason?: any) => void;
63
+ cancel: () => void;
64
+ utils: FuturableUtils<T>;
65
+ }
66
+ declare class Futurable<T> extends Promise<T> {
67
+ private controller;
68
+ private internalSignal;
69
+ private idsTimeout;
70
+ constructor(executor: FuturableExecutor<T>, signal?: AbortSignal);
71
+ static get [Symbol.species](): typeof Futurable;
72
+ get [Symbol.toStringTag](): string;
73
+ /**
74
+ * Return internal futurable signal
75
+ * @returns {AbortSignal}
76
+ */
77
+ get signal(): AbortSignal;
78
+ private clearTimeout;
79
+ /**
80
+ * Attaches callbacks for the resolution and/or rejection of the Futurable.
81
+ * @param {((value: T) => TResult1 | PromiseLike<TResult1> | FuturableLike<TResult1>) | undefined | null} onfulfilled
82
+ * @param {((reason: any) => TResult2 | PromiseLike<TResult2> | FuturableLike<TResult2>) | undefined | null} onrejected
83
+ * @returns {Futurable<TResult1 | TResult2>}
84
+ */
85
+ then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1> | FuturableLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2> | FuturableLike<TResult2>) | undefined | null): Futurable<TResult1 | TResult2>;
86
+ /**
87
+ * Attaches a callback for only the rejection of the Futurable.
88
+ * @param {((reason: any) => TResult2 | PromiseLike<TResult2> | FuturableLike<TResult2>) | undefined | null} onRejected
89
+ * @returns {Futurable<T | TResult2>}
90
+ */
91
+ catch<TResult2 = never>(onRejected: ((reason: any) => TResult2 | PromiseLike<TResult2> | FuturableLike<TResult2>) | undefined | null): Futurable<T | TResult2>;
92
+ /**
93
+ * Attaches a callback that is invoked when the Futurable is settled (fulfilled or rejected).
94
+ * The resolved value cannot be modified from the callback.
95
+ * @param {() => void | undefined | null} onfinally
96
+ * @returns {Futurable<T>}
97
+ */
98
+ finally(onfinally: () => void | undefined | null): Futurable<T>;
99
+ /**
100
+ * Cancel the futurable if it is to be executed or if it is still executing.
101
+ */
102
+ cancel(): void;
103
+ /**
104
+ * Waits for timer, then executes callback with the futurable value and returns the result obtained from the invocation.
105
+ * @param {(val: T) => TResult1 | PromiseLike<TResult1> | FuturableLike<TResult1>} cb - callback executed after timer with futurable chain value as parameter
106
+ * @param {number} timer - timer to wait (in milliseconds)
107
+ */
108
+ delay<TResult1 = T, TResult2 = never>(cb: (val: T) => TResult1 | PromiseLike<TResult1> | FuturableLike<TResult1>, timer: number): Futurable<TResult1 | TResult2>;
109
+ /**
110
+ * Waits for timer parameter (in milliseconds) before returning the value.
111
+ * @param {number} timer - timer to wait (in milliseconds)
112
+ * @returns {Futurable<T>}
113
+ */
114
+ sleep(timer: number): Futurable<T>;
115
+ /**
116
+ * Extension of the fetch API with cancellation support. Url parameter can be a string or a function with receive value from futurable chaining as paremeter.
117
+ * @param {string| ((val?:T)=>string)} url - url to fetch or function with futurable chaining value that returns url to fetch
118
+ * @param {object | RequestInit | ((val?: T) => RequestInit)} opts - fetch options or function with futurable chaining value that return fetch options
119
+ * @returns {Futurable<Response>}
120
+ */
121
+ fetch(url: string | ((val?: T) => string), opts?: object | RequestInit | ((val?: T) => RequestInit)): Futurable<Response>;
122
+ /**
123
+ * Executes the callback passed as a parameter when the futurable is cancelled.
124
+ * @param {()=>void} cb
125
+ * @returns {Futurable<TResult1 | TResult2>}
126
+ */
127
+ onCancel<TResult1 = void, TResult2 = never>(cb: () => void): Futurable<TResult1 | TResult2>;
128
+ /**
129
+ * Takes a promise and transforms it into a futurizable. Promise can be also a function that receives value from futurable chaining as parameter.
130
+ * @param {Promise<TResult1> | ((val?: T) => Promise<TResult1>)} promise - Promise to futurize or function that return promise with futurable chaining value as parameter
131
+ * @returns {Futurable<TResult1 | TResult2>}
132
+ */
133
+ futurizable<TResult1 = T, TResult2 = never>(promise: Promise<TResult1> | ((val?: T) => Promise<TResult1>)): Futurable<TResult1 | TResult2>;
134
+ /**
135
+ * Creates a new resolved futurable. Creates a new resolved futurable for the provided value.
136
+ * @returns {Futurable<void>}
137
+ */
138
+ static resolve(): Futurable<void>;
139
+ /**
140
+ * @param {T | PromiseLike<T> | FuturableLike<T>} value
141
+ * @param {AbortSignal} [signal]
142
+ * @returns {Futurable<T>}
143
+ */
144
+ static resolve<T = any>(value: T | PromiseLike<T> | FuturableLike<T>, signal?: AbortSignal): Futurable<T>;
145
+ /**
146
+ * Creates a new rejected futurable for the provided reason.
147
+ * @param {any} [reason]
148
+ * @param {AbortSignal} [signal]
149
+ * @returns {Futurable<T>}
150
+ */
151
+ static reject<T = never>(reason?: any, signal?: AbortSignal): Futurable<T>;
152
+ /**
153
+ * OnCancel static method. It accepts a callback or a object with cb property and an optional signal.
154
+ * @param {{cb: () => T, signal: AbortSignal|undefined}} options
155
+ * @returns {Futurable<T>}
156
+ */
157
+ static onCancel<T = void>({ cb, signal }: {
158
+ cb: () => T;
159
+ signal?: AbortSignal;
160
+ }): Futurable<T>;
161
+ /**
162
+ * Delay static method. It accepts a object with timer and cb properties and an optional signal property.
163
+ * @param {{cb: () => T, timer: number, signal: AbortSignal|undefined}} options
164
+ * @returns {Futurable<T|TResult2>}
165
+ */
166
+ static delay<T = any, TResult2 = never>({ cb, timer, signal }: {
167
+ cb: () => T;
168
+ timer: number;
169
+ signal?: AbortSignal;
170
+ }): Futurable<T | TResult2>;
171
+ /**
172
+ * Sleep static method. It accepts a timer or a object with timer property and an optional signal.
173
+ * @param {{timer: number, signal: AbortSignal|undefined}} options
174
+ * @returns {Futurable<void>}
175
+ */
176
+ static sleep({ timer, signal }: {
177
+ timer: number;
178
+ signal?: AbortSignal;
179
+ }): Futurable<void>;
180
+ /**
181
+ * Fetch static method.
182
+ * @param {string} url
183
+ * @param {RequestInit} [opts]
184
+ * @returns {Futurable<Response>}
185
+ */
186
+ static fetch(url: string, opts?: RequestInit): Futurable<Response>;
187
+ /**
188
+ * Futurizable static method.
189
+ * @param {{promise: Promise<TResult1>, signal: AbortSignal|undefined}} options
190
+ * @returns {Futurable<TResult1 | TResult2>}
191
+ */
192
+ static futurizable<TResult1 = any, TResult2 = never>({ promise, signal }: {
193
+ promise: Promise<TResult1>;
194
+ signal?: AbortSignal;
195
+ }): Futurable<TResult1 | TResult2>;
196
+ private static handleValues;
197
+ /**
198
+ * Creates a Futurable with cancellation support that is resolved with an array of results when all of the provided Futurables resolve, or rejected when any Futurable is rejected.
199
+ * @param {T} values
200
+ * @param {AbortSignal} [signal]
201
+ * @returns {Futurable<{ -readonly [P in keyof T]: Awaited<T[P]>; }>}
202
+ */
203
+ static all<T extends readonly unknown[] | []>(values: T, signal?: AbortSignal): Futurable<{
204
+ -readonly [P in keyof T]: Awaited<T[P]>;
205
+ }>;
206
+ /**
207
+ * Creates a Futurable with cancellation support that is resolved with an array of results when all of the provided Futurables resolve or reject.
208
+ * @param {T} values
209
+ * @param {AbortSignal} [signal]
210
+ * @returns {Futurable<{ -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>> }>}
211
+ */
212
+ static allSettled<T extends readonly unknown[] | []>(values: T, signal?: AbortSignal): Futurable<{
213
+ -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>>;
214
+ }>;
215
+ /**
216
+ * Creates a Futurable with cancellation support that is resolved or rejected when any of the provided Futurables are resolved or rejected.
217
+ * @param {T} values
218
+ * @param {AbortSignal} [signal]
219
+ * @returns {Futurable<Awaited<T[number]>>}
220
+ */
221
+ static race<T extends readonly unknown[] | []>(values: T, signal?: AbortSignal): Futurable<Awaited<T[number]>>;
222
+ /**
223
+ * The any function returns a futurable with cancellation support that is fulfilled by the first given futurable to be fulfilled,
224
+ * or rejected with an AggregateError containing an array of rejection reasons if all of the
225
+ * given futurables are rejected. It resolves all elements of the passed iterable to futurables as
226
+ * it runs this algorithm.
227
+ * @param {T} values
228
+ * @param {AbortSignal} [signal]
229
+ * @returns {Futurable<Awaited<T[number]>>}
230
+ */
231
+ static any<T extends readonly unknown[] | []>(values: T, signal?: AbortSignal): Futurable<Awaited<T[number]>>;
232
+ /**
233
+ * Creates a polling service with cancellation support and possibility to handle error. An optional param __immediate__ can be set _true_ if __fun__ must to be invoke immediatly.
234
+ * @param {()=> Futurable<T>} fun
235
+ * @param {{interval: number, signal?: AbortSignal, immediate?: boolean}} options
236
+ * @returns {{cancel: () => void, catch: (onrejected:(reason: unknown)=>void)=>void }}
237
+ */
238
+ static polling<T>(fun: () => Futurable<T> | Promise<T> | T, { interval, signal, immediate }: {
239
+ interval: number;
240
+ signal?: AbortSignal;
241
+ immediate?: boolean;
242
+ }): {
243
+ cancel: () => void;
244
+ catch: (onrejected: (reason: unknown) => void) => void;
245
+ };
246
+ /**
247
+ * Extension of _Promise.withResolvers_ static method. Creates a new Futurable and returns it in an object, along with its resolve, reject and cancel functions and utils object.
248
+ * @param {AbortSignal} [signal]
249
+ * @returns {{ resolve: null | FuturableResolve<T>, reject: null | FuturableReject, utils: null | FuturableUtils<T>, futurable: Futurable<T>, cancel: null | (() => void) }}
250
+ */
251
+ static withResolvers<T>(signal?: AbortSignal): FuturableWithResolvers<T>;
252
+ }
253
+
254
+ export { Futurable };
255
+ export type { FuturableExecutor, FuturableIterable, FuturableLike, FuturableReject, FuturableResolve, FuturableUtils };
@@ -0,0 +1,255 @@
1
+ interface FuturableLike<T> {
2
+ /**
3
+ * Attaches callbacks for the resolution and/or rejection of the Futurable.
4
+ * @param onfulfilled The callback to execute when the Futurable is resolved.
5
+ * @param onrejected The callback to execute when the Futurable is rejected.
6
+ * @returns A Futurable for the completion of which ever callback is executed.
7
+ */
8
+ then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1> | FuturableLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2> | FuturableLike<TResult2>) | undefined | null): FuturableLike<TResult1 | TResult2>;
9
+ }
10
+ interface FuturableResolve<T> {
11
+ (value: T | FuturableLike<T> | PromiseLike<T>): void;
12
+ }
13
+ interface FuturableReject {
14
+ (reason?: any): void;
15
+ }
16
+ interface FuturableUtils<T> {
17
+ /**
18
+ * Internal futurable signal
19
+ */
20
+ signal: AbortSignal;
21
+ /**
22
+ * Cancel the futurable if it is to be executed or if it is still executing.
23
+ */
24
+ cancel: () => void;
25
+ /**
26
+ * Executes the callback passed as a parameter when the futurable is cancelled.
27
+ * @param cb: callback
28
+ */
29
+ onCancel: (cb: () => void) => void;
30
+ /**
31
+ * Waits for timer, then executes callback with the futurable value and returns the result obtained from the invocation.
32
+ * @param cb: callback executed after timer
33
+ * @param timer: timer to wait (in milliseconds)
34
+ */
35
+ delay: <TResult = T, TResult2 = never>(cb: () => TResult, timer: number) => FuturableLike<TResult | TResult2>;
36
+ /**
37
+ * Waits for timer parameter (in milliseconds) before returning the value.
38
+ * @param timer: timer to wait (in milliseconds)
39
+ */
40
+ sleep: (timer: number) => FuturableLike<void>;
41
+ /**
42
+ * Extension of the fetch API with cancellation support. Url parameter can be a string or a function with receive value from futurable chaining as paremeter.
43
+ * @param url: url to fetch
44
+ * @param opts: fetch options
45
+ */
46
+ fetch: (url: string, opts?: RequestInit) => Futurable<Response>;
47
+ /**
48
+ * Takes a promise and transforms it into a futurizable. Promise can be also a function that receives value from futurable chaining as parameter.
49
+ * @param promise: Promise to futurize
50
+ */
51
+ futurizable: <TResult = any>(promise: Promise<TResult>) => Futurable<TResult>;
52
+ }
53
+ type FuturableExecutor<T> = (resolve: FuturableResolve<T>, reject: FuturableReject,
54
+ /**
55
+ * Object containing implemented functionalities.
56
+ */
57
+ utils: FuturableUtils<T>) => void;
58
+ type FuturableIterable<T = any> = Iterable<FuturableLike<T> | PromiseLike<T> | T>;
59
+ interface FuturableWithResolvers<T> {
60
+ promise: Futurable<T> | Promise<T>;
61
+ resolve: (value: T | PromiseLike<T> | FuturableLike<T>) => void;
62
+ reject: (reason?: any) => void;
63
+ cancel: () => void;
64
+ utils: FuturableUtils<T>;
65
+ }
66
+ declare class Futurable<T> extends Promise<T> {
67
+ private controller;
68
+ private internalSignal;
69
+ private idsTimeout;
70
+ constructor(executor: FuturableExecutor<T>, signal?: AbortSignal);
71
+ static get [Symbol.species](): typeof Futurable;
72
+ get [Symbol.toStringTag](): string;
73
+ /**
74
+ * Return internal futurable signal
75
+ * @returns {AbortSignal}
76
+ */
77
+ get signal(): AbortSignal;
78
+ private clearTimeout;
79
+ /**
80
+ * Attaches callbacks for the resolution and/or rejection of the Futurable.
81
+ * @param {((value: T) => TResult1 | PromiseLike<TResult1> | FuturableLike<TResult1>) | undefined | null} onfulfilled
82
+ * @param {((reason: any) => TResult2 | PromiseLike<TResult2> | FuturableLike<TResult2>) | undefined | null} onrejected
83
+ * @returns {Futurable<TResult1 | TResult2>}
84
+ */
85
+ then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1> | FuturableLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2> | FuturableLike<TResult2>) | undefined | null): Futurable<TResult1 | TResult2>;
86
+ /**
87
+ * Attaches a callback for only the rejection of the Futurable.
88
+ * @param {((reason: any) => TResult2 | PromiseLike<TResult2> | FuturableLike<TResult2>) | undefined | null} onRejected
89
+ * @returns {Futurable<T | TResult2>}
90
+ */
91
+ catch<TResult2 = never>(onRejected: ((reason: any) => TResult2 | PromiseLike<TResult2> | FuturableLike<TResult2>) | undefined | null): Futurable<T | TResult2>;
92
+ /**
93
+ * Attaches a callback that is invoked when the Futurable is settled (fulfilled or rejected).
94
+ * The resolved value cannot be modified from the callback.
95
+ * @param {() => void | undefined | null} onfinally
96
+ * @returns {Futurable<T>}
97
+ */
98
+ finally(onfinally: () => void | undefined | null): Futurable<T>;
99
+ /**
100
+ * Cancel the futurable if it is to be executed or if it is still executing.
101
+ */
102
+ cancel(): void;
103
+ /**
104
+ * Waits for timer, then executes callback with the futurable value and returns the result obtained from the invocation.
105
+ * @param {(val: T) => TResult1 | PromiseLike<TResult1> | FuturableLike<TResult1>} cb - callback executed after timer with futurable chain value as parameter
106
+ * @param {number} timer - timer to wait (in milliseconds)
107
+ */
108
+ delay<TResult1 = T, TResult2 = never>(cb: (val: T) => TResult1 | PromiseLike<TResult1> | FuturableLike<TResult1>, timer: number): Futurable<TResult1 | TResult2>;
109
+ /**
110
+ * Waits for timer parameter (in milliseconds) before returning the value.
111
+ * @param {number} timer - timer to wait (in milliseconds)
112
+ * @returns {Futurable<T>}
113
+ */
114
+ sleep(timer: number): Futurable<T>;
115
+ /**
116
+ * Extension of the fetch API with cancellation support. Url parameter can be a string or a function with receive value from futurable chaining as paremeter.
117
+ * @param {string| ((val?:T)=>string)} url - url to fetch or function with futurable chaining value that returns url to fetch
118
+ * @param {object | RequestInit | ((val?: T) => RequestInit)} opts - fetch options or function with futurable chaining value that return fetch options
119
+ * @returns {Futurable<Response>}
120
+ */
121
+ fetch(url: string | ((val?: T) => string), opts?: object | RequestInit | ((val?: T) => RequestInit)): Futurable<Response>;
122
+ /**
123
+ * Executes the callback passed as a parameter when the futurable is cancelled.
124
+ * @param {()=>void} cb
125
+ * @returns {Futurable<TResult1 | TResult2>}
126
+ */
127
+ onCancel<TResult1 = void, TResult2 = never>(cb: () => void): Futurable<TResult1 | TResult2>;
128
+ /**
129
+ * Takes a promise and transforms it into a futurizable. Promise can be also a function that receives value from futurable chaining as parameter.
130
+ * @param {Promise<TResult1> | ((val?: T) => Promise<TResult1>)} promise - Promise to futurize or function that return promise with futurable chaining value as parameter
131
+ * @returns {Futurable<TResult1 | TResult2>}
132
+ */
133
+ futurizable<TResult1 = T, TResult2 = never>(promise: Promise<TResult1> | ((val?: T) => Promise<TResult1>)): Futurable<TResult1 | TResult2>;
134
+ /**
135
+ * Creates a new resolved futurable. Creates a new resolved futurable for the provided value.
136
+ * @returns {Futurable<void>}
137
+ */
138
+ static resolve(): Futurable<void>;
139
+ /**
140
+ * @param {T | PromiseLike<T> | FuturableLike<T>} value
141
+ * @param {AbortSignal} [signal]
142
+ * @returns {Futurable<T>}
143
+ */
144
+ static resolve<T = any>(value: T | PromiseLike<T> | FuturableLike<T>, signal?: AbortSignal): Futurable<T>;
145
+ /**
146
+ * Creates a new rejected futurable for the provided reason.
147
+ * @param {any} [reason]
148
+ * @param {AbortSignal} [signal]
149
+ * @returns {Futurable<T>}
150
+ */
151
+ static reject<T = never>(reason?: any, signal?: AbortSignal): Futurable<T>;
152
+ /**
153
+ * OnCancel static method. It accepts a callback or a object with cb property and an optional signal.
154
+ * @param {{cb: () => T, signal: AbortSignal|undefined}} options
155
+ * @returns {Futurable<T>}
156
+ */
157
+ static onCancel<T = void>({ cb, signal }: {
158
+ cb: () => T;
159
+ signal?: AbortSignal;
160
+ }): Futurable<T>;
161
+ /**
162
+ * Delay static method. It accepts a object with timer and cb properties and an optional signal property.
163
+ * @param {{cb: () => T, timer: number, signal: AbortSignal|undefined}} options
164
+ * @returns {Futurable<T|TResult2>}
165
+ */
166
+ static delay<T = any, TResult2 = never>({ cb, timer, signal }: {
167
+ cb: () => T;
168
+ timer: number;
169
+ signal?: AbortSignal;
170
+ }): Futurable<T | TResult2>;
171
+ /**
172
+ * Sleep static method. It accepts a timer or a object with timer property and an optional signal.
173
+ * @param {{timer: number, signal: AbortSignal|undefined}} options
174
+ * @returns {Futurable<void>}
175
+ */
176
+ static sleep({ timer, signal }: {
177
+ timer: number;
178
+ signal?: AbortSignal;
179
+ }): Futurable<void>;
180
+ /**
181
+ * Fetch static method.
182
+ * @param {string} url
183
+ * @param {RequestInit} [opts]
184
+ * @returns {Futurable<Response>}
185
+ */
186
+ static fetch(url: string, opts?: RequestInit): Futurable<Response>;
187
+ /**
188
+ * Futurizable static method.
189
+ * @param {{promise: Promise<TResult1>, signal: AbortSignal|undefined}} options
190
+ * @returns {Futurable<TResult1 | TResult2>}
191
+ */
192
+ static futurizable<TResult1 = any, TResult2 = never>({ promise, signal }: {
193
+ promise: Promise<TResult1>;
194
+ signal?: AbortSignal;
195
+ }): Futurable<TResult1 | TResult2>;
196
+ private static handleValues;
197
+ /**
198
+ * Creates a Futurable with cancellation support that is resolved with an array of results when all of the provided Futurables resolve, or rejected when any Futurable is rejected.
199
+ * @param {T} values
200
+ * @param {AbortSignal} [signal]
201
+ * @returns {Futurable<{ -readonly [P in keyof T]: Awaited<T[P]>; }>}
202
+ */
203
+ static all<T extends readonly unknown[] | []>(values: T, signal?: AbortSignal): Futurable<{
204
+ -readonly [P in keyof T]: Awaited<T[P]>;
205
+ }>;
206
+ /**
207
+ * Creates a Futurable with cancellation support that is resolved with an array of results when all of the provided Futurables resolve or reject.
208
+ * @param {T} values
209
+ * @param {AbortSignal} [signal]
210
+ * @returns {Futurable<{ -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>> }>}
211
+ */
212
+ static allSettled<T extends readonly unknown[] | []>(values: T, signal?: AbortSignal): Futurable<{
213
+ -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>>;
214
+ }>;
215
+ /**
216
+ * Creates a Futurable with cancellation support that is resolved or rejected when any of the provided Futurables are resolved or rejected.
217
+ * @param {T} values
218
+ * @param {AbortSignal} [signal]
219
+ * @returns {Futurable<Awaited<T[number]>>}
220
+ */
221
+ static race<T extends readonly unknown[] | []>(values: T, signal?: AbortSignal): Futurable<Awaited<T[number]>>;
222
+ /**
223
+ * The any function returns a futurable with cancellation support that is fulfilled by the first given futurable to be fulfilled,
224
+ * or rejected with an AggregateError containing an array of rejection reasons if all of the
225
+ * given futurables are rejected. It resolves all elements of the passed iterable to futurables as
226
+ * it runs this algorithm.
227
+ * @param {T} values
228
+ * @param {AbortSignal} [signal]
229
+ * @returns {Futurable<Awaited<T[number]>>}
230
+ */
231
+ static any<T extends readonly unknown[] | []>(values: T, signal?: AbortSignal): Futurable<Awaited<T[number]>>;
232
+ /**
233
+ * Creates a polling service with cancellation support and possibility to handle error. An optional param __immediate__ can be set _true_ if __fun__ must to be invoke immediatly.
234
+ * @param {()=> Futurable<T>} fun
235
+ * @param {{interval: number, signal?: AbortSignal, immediate?: boolean}} options
236
+ * @returns {{cancel: () => void, catch: (onrejected:(reason: unknown)=>void)=>void }}
237
+ */
238
+ static polling<T>(fun: () => Futurable<T> | Promise<T> | T, { interval, signal, immediate }: {
239
+ interval: number;
240
+ signal?: AbortSignal;
241
+ immediate?: boolean;
242
+ }): {
243
+ cancel: () => void;
244
+ catch: (onrejected: (reason: unknown) => void) => void;
245
+ };
246
+ /**
247
+ * Extension of _Promise.withResolvers_ static method. Creates a new Futurable and returns it in an object, along with its resolve, reject and cancel functions and utils object.
248
+ * @param {AbortSignal} [signal]
249
+ * @returns {{ resolve: null | FuturableResolve<T>, reject: null | FuturableReject, utils: null | FuturableUtils<T>, futurable: Futurable<T>, cancel: null | (() => void) }}
250
+ */
251
+ static withResolvers<T>(signal?: AbortSignal): FuturableWithResolvers<T>;
252
+ }
253
+
254
+ export { Futurable };
255
+ export type { FuturableExecutor, FuturableIterable, FuturableLike, FuturableReject, FuturableResolve, FuturableUtils };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export interface FuturableLike<T> {
1
+ interface FuturableLike<T> {
2
2
  /**
3
3
  * Attaches callbacks for the resolution and/or rejection of the Futurable.
4
4
  * @param onfulfilled The callback to execute when the Futurable is resolved.
@@ -7,13 +7,13 @@ export interface FuturableLike<T> {
7
7
  */
8
8
  then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1> | FuturableLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2> | FuturableLike<TResult2>) | undefined | null): FuturableLike<TResult1 | TResult2>;
9
9
  }
10
- export interface FuturableResolve<T> {
10
+ interface FuturableResolve<T> {
11
11
  (value: T | FuturableLike<T> | PromiseLike<T>): void;
12
12
  }
13
- export interface FuturableReject {
13
+ interface FuturableReject {
14
14
  (reason?: any): void;
15
15
  }
16
- export interface FuturableUtils<T> {
16
+ interface FuturableUtils<T> {
17
17
  /**
18
18
  * Internal futurable signal
19
19
  */
@@ -50,12 +50,12 @@ export interface FuturableUtils<T> {
50
50
  */
51
51
  futurizable: <TResult = any>(promise: Promise<TResult>) => Futurable<TResult>;
52
52
  }
53
- export type FuturableExecutor<T> = (resolve: FuturableResolve<T>, reject: FuturableReject,
53
+ type FuturableExecutor<T> = (resolve: FuturableResolve<T>, reject: FuturableReject,
54
54
  /**
55
55
  * Object containing implemented functionalities.
56
56
  */
57
57
  utils: FuturableUtils<T>) => void;
58
- export type FuturableIterable<T = any> = Iterable<FuturableLike<T> | PromiseLike<T> | T>;
58
+ type FuturableIterable<T = any> = Iterable<FuturableLike<T> | PromiseLike<T> | T>;
59
59
  interface FuturableWithResolvers<T> {
60
60
  promise: Futurable<T> | Promise<T>;
61
61
  resolve: (value: T | PromiseLike<T> | FuturableLike<T>) => void;
@@ -63,7 +63,7 @@ interface FuturableWithResolvers<T> {
63
63
  cancel: () => void;
64
64
  utils: FuturableUtils<T>;
65
65
  }
66
- export declare class Futurable<T> extends Promise<T> {
66
+ declare class Futurable<T> extends Promise<T> {
67
67
  private controller;
68
68
  private internalSignal;
69
69
  private idsTimeout;
@@ -250,5 +250,6 @@ export declare class Futurable<T> extends Promise<T> {
250
250
  */
251
251
  static withResolvers<T>(signal?: AbortSignal): FuturableWithResolvers<T>;
252
252
  }
253
- export {};
254
- //# sourceMappingURL=index.d.ts.map
253
+
254
+ export { Futurable };
255
+ export type { FuturableExecutor, FuturableIterable, FuturableLike, FuturableReject, FuturableResolve, FuturableUtils };
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ var S=Object.defineProperty,T=(d,t,n)=>t in d?S(d,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):d[t]=n,y=(d,t,n)=>(T(d,typeof t!="symbol"?t+"":t,n),n),u=(d=>(d.PENDING="pending",d.FULFILLED="fulfilled",d.REJECTED="rejected",d))(u||{});class s extends Promise{constructor(t,n){const l=n?null:new AbortController,e=n||l.signal,i=[],c=()=>{for(const a of i)clearTimeout(a)};let o;const h={signal:e,cancel:()=>this.controller?.abort(),onCancel:a=>{o=a},delay:(a,f)=>new s(g=>{i.push(setTimeout(()=>{g(a())},f))},e),sleep:a=>h.delay(()=>{},a),fetch:(a,f)=>new s((g,p)=>{fetch(a,{...f||{},signal:e}).then(w=>g(w)).catch(w=>{w.name!=="AbortError"&&p(w)})},e),futurizable:a=>new s((f,g)=>{a.then(f).catch(g)},e)};let r="pending";const m=new Promise((a,f)=>{if(e.aborted){c();return}else{const g=typeof e.onabort=="function"?e.onabort:()=>{};e.onabort=()=>{g(),c(),r==="pending"&&o&&o()},t(p=>{r="fulfilled",a(p)},p=>{r="rejected",f(p)},h)}});super((a,f)=>{m.then(g=>a(g)).catch(f)}),y(this,"controller"),y(this,"internalSignal"),y(this,"idsTimeout"),this.controller=l,this.internalSignal=e,this.idsTimeout=i}static get[Symbol.species](){return this}get[Symbol.toStringTag](){return"Futurable"}get signal(){return this.internalSignal}clearTimeout(){for(const t of this.idsTimeout)clearTimeout(t)}then(t,n){let l,e;const i=new s((c,o)=>{l=c,e=o},this.internalSignal);return i.controller=this.controller,super.then(c=>{if(this.internalSignal?.aborted){this.clearTimeout();return}try{l(t?t(c):c)}catch(o){e(o)}},c=>{if(this.internalSignal?.aborted){this.clearTimeout();return}try{n?l(n(c)):e(c)}catch(o){e(o)}}),i}catch(t){return this.then(null,t)}finally(t){return this.then(n=>(t(),n),n=>{if(t(),n instanceof Error)throw n;return n})}cancel(){!this.internalSignal?.aborted&&this.controller?.abort()}delay(t,n){let l,e;const i=new s((c,o)=>{l=c,e=o},this.internalSignal);return i.controller=this.controller,this.then(c=>{this.idsTimeout.push(setTimeout(()=>l(t(c)),n))},c=>{e(c)}),i}sleep(t){return this.delay(n=>n,t)}fetch(t,n){let l,e;const i=new s((c,o)=>{l=c,e=o},this.internalSignal);return i.controller=this.controller,this.then(c=>{const o=typeof t=="function"?t(c):t,h={...typeof n=="function"?n(c):n,signal:this.internalSignal};fetch(o,h).then(r=>l(r)).catch(r=>{r.name!=="AbortError"&&e(r)})}),i}onCancel(t){let n,l;const e=new s((i,c,o)=>{o.onCancel(t),n=i,l=c},this.internalSignal);return e.controller=this.controller,this.then(i=>n(i),i=>l(i)),e}futurizable(t){let n,l;const e=new s((i,c)=>{n=i,l=c},this.internalSignal);return e.controller=this.controller,this.then(i=>{(typeof t=="function"?t(i):t).then(n).catch(l)}),e}static resolve(t,n){return t?new s(l=>l(t),n):new s(l=>l(),n)}static reject(t,n){return new s((l,e)=>e(t),n)}static onCancel({cb:t,signal:n}){return new s((l,e,i)=>{i.onCancel(()=>l(t()))},n)}static delay({cb:t,timer:n,signal:l}){return new s((e,i,c)=>{c.delay(t,n).then(e,i)},l)}static sleep({timer:t,signal:n}){return s.delay({cb:()=>{},timer:t,signal:n})}static fetch(t,n){const l=n?.signal||void 0;return n?.signal&&delete n.signal,new s((e,i,c)=>{c.fetch(t,n).then(e).catch(i)},l)}static futurizable({promise:t,signal:n}){return new s((l,e)=>{t.then(l).catch(e)},n)}static handleValues(t,n){const l=[];for(const e in t)t[e]instanceof s?l.push(t[e]):t[e]instanceof Promise?l.push(new s((i,c)=>{t[e].then(o=>i(o)).catch(c)},n)):l.push(new s(i=>i(t[e]),n));return l}static all(t,n){let l,e;const i=new s((o,h,r)=>{l=o,e=h,r.onCancel(()=>{for(const m of c)m.cancel()})},n);n||(n=i.internalSignal);const c=s.handleValues(t,n);return super.all(c).then(o=>l(o)).catch(o=>e(o)),i}static allSettled(t,n){let l;const e=new s((c,o,h)=>{l=c,h.onCancel(()=>{for(const r of i)r.cancel()})},n);n||(n=e.internalSignal);const i=s.handleValues(t,n);return super.allSettled(i).then(c=>l(c)),e}static race(t,n){let l,e;const i=new s((o,h,r)=>{l=o,e=h,r.onCancel(()=>{for(const m of c)m.cancel()})},n);n||(n=i.internalSignal);const c=s.handleValues(t,n);return super.race(c).then(o=>l(o)).catch(o=>e(o)),i}static any(t,n){let l,e;const i=new s((o,h,r)=>{l=o,e=h,r.onCancel(()=>{for(const m of c)m.cancel()})},n);n||(n=i.internalSignal);const c=s.handleValues(t,n);return super.any(c).then(o=>l(o)).catch(o=>e(o)),i}static polling(t,{interval:n,signal:l,immediate:e}){let i,c,o;e&&(i=new s((r,m,a)=>{a.onCancel(()=>{c&&c instanceof s&&c.cancel()});const f=t();(f instanceof s||f instanceof Promise)&&(c=f.then(()=>r()).catch(g=>o&&o(g)))},l));const h=setInterval(()=>{i&&i.cancel(),i=new s((r,m,a)=>{a.onCancel(()=>{c&&c instanceof s&&c.cancel()});const f=t();(f instanceof s||f instanceof Promise)&&(c=f.then(()=>r()).catch(g=>o&&o(g)))},l)},n);return{cancel:()=>{h&&clearInterval(h),i&&i.cancel()},catch:r=>{o=r}}}static withResolvers(t){let n,l,e;const i=new s((o,h,r)=>{n=o,l=h,e=r},t),c=i.cancel;return{resolve:n,reject:l,utils:e,cancel:c,promise:i}}}export{s as Futurable};