Это ide на основе vs code(code oss), в ней будет встроенный умный апи роутинг, свой маркет с плагинами(агент харнесс, поддержка java/kotlin/мобильной разработки, командная разработка проектов, orca, оркестратор агентов
/**
* Returns a promise that can be cancelled using the provided cancellation token.
*
* @remarks When cancellation is requested, the promise will be rejected with a {@link CancellationError}.
* If the promise resolves to a disposable object, it will be automatically disposed when cancellation
* is requested.
*
* @paramcallback A function that accepts a cancellation token and returns a promise
* @returns A promise that can be cancelled
*/
export
function
createCancelablePromise<T>
(
callback
:
(
:
)
=>
Promise
<
T
>
)
:
<
T
>
{
const
=
new
CancellationTokenSource
(
)
;
const
=
callback
(
.
)
;
let
=
false
;
const
=
new
Promise<T>
(
(
,
)
=>
{
const
=
.
.
onCancellationRequested
(
(
)
=>
{
=
true
;
.
dispose
(
)
;
reject
(
new
CancellationError
(
)
)
;
}
)
;
Promise
.
resolve
(
)
.
then
(
=>
{
.
dispose
(
)
;
.
dispose
(
)
;
if
(
!
)
{
resolve
(
)
;
}
else
if
(
isDisposable
(
)
)
{
// promise has been cancelled, result is disposable and will
// be cleaned up
.
dispose
(
)
;
}
}
,
=>
{
.
dispose
(
)
;
.
dispose
(
)
;
reject
(
)
;
}
)
;
}
)
;
return
<
<
T
>>
new
class
{
cancel
(
)
{
.
cancel
(
)
;
.
dispose
(
)
;
}
then<TResult1 =T, TResult2 =never>
(
?
:
(
(
:
T
)
=>
|
Promise
<
>
)
|
undefined
|
null
,
?
:
(
(
:
unknown
)
=>
|
Promise
<
>
)
|
undefined
|
null
)
:
Promise
<
|
>
{
return
.
then
(
,
)
;
}
catch
<
=
never
>
(
?
:
(
(
:
unknown
)
=>
|
Promise
<
>
)
|
undefined
|
null
)
:
Promise
<
T
|
>
{
return
this
.
then
(
undefined
,
)
;
}
finally
(
?
:
(
(
)
=>
void
)
|
undefined
|
null
)
:
Promise
<
T
>
{
return
.
finally
(
)
;
}
}
;
}
/**
* Returns a promise that resolves with `undefined` as soon as the passed token is cancelled.
* @see{@link raceCancellationError}
*/
export
function
raceCancellation<T>
(
:
Promise
<
T
>
,
:
)
:
Promise
<
T
|
undefined
>
;
/**
* Returns a promise that resolves with `defaultValue` as soon as the passed token is cancelled.
* @see{@link raceCancellationError}
*/
export
function
raceCancellation<T>
(
:
Promise
<
T
>
,
:
,
:
T
)
:
Promise
<
T
>
;
export
function
raceCancellation<T>
(
:
Promise
<
T
>
,
:
,
?
:
T
)
:
Promise
<
T
|
undefined
>
{
return
new
Promise
(
(
,
)
=>
{
const
=
.
onCancellationRequested
(
(
)
=>
{
.
dispose
(
)
;
resolve
(
)
;
}
)
;
.
then
(
,
)
.
finally
(
(
)
=>
.
dispose
(
)
)
;
}
)
;
}
/**
* Returns a promise that rejects with an {@CancellationError} as soon as the passed token is cancelled.
* @see{@link raceCancellation}
*/
export
function
raceCancellationError<T>
(
:
Promise
<
T
>
,
:
)
:
Promise
<
T
>
{
return
new
Promise
(
(
,
)
=>
{
const
=
.
onCancellationRequested
(
(
)
=>
{
.
dispose
(
)
;
reject
(
new
CancellationError
(
)
)
;
}
)
;
.
then
(
,
)
.
finally
(
(
)
=>
.
dispose
(
)
)
;
}
)
;
}
export
function
rejectIfNotCanceled
(
:
unknown
)
:
undefined
{
if
(
isCancellationError
(
)
)
{
return
undefined
;
}
return
Promise
.
reject
(
)
as
never
;
}
/**
* Wraps a cancellable promise such that it is no cancellable. Can be used to
* avoid issues with shared promises that would normally be returned as
* cancellable to consumers.
*/
export
function
notCancellablePromise<T>
(
:
<
T
>
)
:
Promise
<
T
>
{
return
new
Promise<T>
(
(
,
)
=>
{
.
then
(
,
)
;
}
)
;
}
/**
* Returns as soon as one of the promises resolves or rejects and cancels remaining promises
*/
export
function
raceCancellablePromises<T>
(
:
(
<
T
>
|
Promise
<
T
>
)
[
]
)
:
<
T
>
{
let
=
-
1
;
const
=
.
map
(
(
,
)
=>
.
then
(
=>
{
=
;
return
;
}
)
)
;
const
=
Promise
.
race
(
)
as
<
T
>
;
.
cancel
=
(
)
=>
{
.
forEach
(
(
,
)
=>
{
if
(
!==
&&
(
as
<
T
>
)
.
)
{
(
as
<
T
>
)
.
cancel
(
)
;
}
}
)
;
}
;
const
cancel
=
(
)
=>
.
cancel
(
)
;
.
then
(
,
)
;
return
;
}
export
function
raceTimeout<T>
(
:
Promise
<
T
>
,
:
number
,
?
:
(
)
=>
void
)
:
Promise
<
T
|
undefined
>
{
let
:
(
(
:
T
|
undefined
)
=>
void
)
|
undefined
=
undefined
;
const
=
setTimeout
(
(
)
=>
{
?.
(
undefined
)
;
?.
(
)
;
}
,
)
;
return
Promise
.
race
(
[
.
finally
(
(
)
=>
clearTimeout
(
)
)
,
new
Promise<T|undefined>
(
=>
=
)
]
)
;
}
export
function
asPromise<T>
(
callback
:
(
)
=>
T
|
<
T
>
)
:
Promise
<
T
>
{
return
new
Promise<T>
(
(
,
)
=>
{
const
=
callback
(
)
;
if
(
isThenable<T>
(
)
)
{
.
then
(
,
)
;
}
else
{
resolve
(
)
;
}
}
)
;
}
/**
* Creates and returns a new promise, plus its `resolve` and `reject` callbacks.
*
* Replace with standardized [`Promise.withResolvers`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers) once it is supported
*/
export
function
promiseWithResolvers<T>
(
)
:
{
:
Promise
<
T
>
;
resolve
:
(
:
T
|
<
T
>
)
=>
void
;
reject
:
(
?
:
any
)
=>
void
}
{
let
resolve
:
(
:
T
|
<
T
>
)
=>
void
;
let
reject
:
(
?
:
any
)
=>
void
;
const
=
new
Promise<T>
(
(
,
)
=>
{
=
;
=
;
}
)
;
return
{
,
:
!
,
:
!
}
;
}
export
interface
ITask<T>
{
(
)
:
T
;
}
export
interface
ICancellableTask<T>
{
(
:
)
:
T
;
}
/**
* A helper to prevent accumulation of sequential async tasks.
*
* Imagine a mail man with the sole task of delivering letters. As soon as
* a letter submitted for delivery, he drives to the destination, delivers it
* and returns to his base. Imagine that during the trip, N more letters were submitted.
* When the mail man returns, he picks those N letters and delivers them all in a
* single trip. Even though N+1 submissions occurred, only 2 deliveries were made.
*
* The throttler implements this via the queue() method, by providing it a task
* factory. Following the example:
*
* const throttler = new Throttler();
* const letters = [];
*
* function deliver() {
* const lettersToDeliver = letters;
* letters = [];
* return makeTheTrip(lettersToDeliver);
* }
*
* function onLetterReceived(l) {
* letters.push(l);
* throttler.queue(deliver);
* }
*/
export
class
Throttler
implements
IDisposable
{
private
:
Promise
<
any
>
|
null
;
private
:
Promise
<
any
>
|
null
;
private
:
<
Promise
<
any
>>
|
null
;
private
:
;
constructor
(
)
{
this
.
=
null
;
this
.
=
null
;
this
.
=
null
;
this
.
=
new
CancellationTokenSource
(
)
;
}
queue<T>
(
:
<
Promise
<
T
>>
)
:
Promise
<
T
>
{
if
(
this
.
.
.
)
{
return
Promise
.
reject
(
new
Error
(
'Throttler is disposed'
)
)
;
}
if
(
this
.
)
{
this
.
=
;
if
(
!
this
.
)
{
const
onComplete
=
(
)
=>
{
this
.
=
null
;
if
(
this
.
.
.
)
{
return
;
}
const
=
this
.
queue
(
this
.
!
)
;
this
.
=
null
;
return
;
}
;
this
.
=
new
Promise
(
=>
{
this
.
!
.
then
(
,
)
.
then
(
)
;
}
)
;
}
return
new
Promise
(
(
,
)
=>
{
this
.
!
.
then
(
,
)
;
}
)
;
}
this
.
=
promiseFactory
(
this
.
.
)
;
return
new
Promise
(
(
,
)
=>
{
this
.
!
.
then
(
(
:
T
)
=>
{
this
.
=
null
;
resolve
(
)
;
}
,
(
:
unknown
)
=>
{
this
.
=
null
;
reject
(
)
;
}
)
;
}
)
;
}
dispose
(
)
:
void
{
this
.
.
cancel
(
)
;
}
}
export
class
Sequencer
{
private
:
Promise
<
unknown
>
=
Promise
.
resolve
(
null
)
;
queue<T>
(
:
<
Promise
<
T
>>
)
:
Promise
<
T
>
{
return
this
.
=
this
.
.
then
(
(
)
=>
promiseTask
(
)
,
(
)
=>
promiseTask
(
)
)
;
}
}
/**
* A {@link Throttler} per key. Calls for the same key coalesce (only the most
* recently queued task runs after the active one settles); calls for different
* keys are independent. Idle keys are cleaned up automatically.
*/
export
class
ThrottlerByKey<TKey>
implements
IDisposable
{
private
readonly
=
new
Map<TKey,{ throttler: Throttler; count:number}>
(
)
;
queue<T>
(
:
,
:
<
Promise
<
T
>>
)
:
Promise
<
T
>
{
let
=
this
.
.
get
(
)
;
if
(
!
)
{
=
{
:
new
Throttler
(
)
,
:
0
}
;
this
.
.
set
(
,
)
;
}
.
++
;
return
.
.
queue
(
)
.
finally
(
(
)
=>
{
if
(
--
!
.
===
0
)
{
!
.
.
dispose
(
)
;
this
.
.
delete
(
)
;
}
}
)
;
}
dispose
(
)
:
void
{
for
(
const
{
}
of
this
.
.
values
(
)
)
{
.
dispose
(
)
;
}
this
.
.
clear
(
)
;
}
}
export
class
SequencerByKey<TKey>
{
private
=
new
Map<TKey,Promise<unknown>>
(
)
;
queue<T>
(
:
,
:
<
Promise
<
T
>>
)
:
Promise
<
T
>
{
const
=
this
.
.
get
(
)
??
Promise
.
resolve
(
)
;
const
=
.
catch
(
(
)
=>
{
}
)
.
then
(
)
.
finally
(
(
)
=>
{
if
(
this
.
.
get
(
)
===
)
{
this
.
.
delete
(
)
;
}
}
)
;
this
.
.
set
(
,
)
;
return
;
}
peek
(
:
)
:
Promise
<
unknown
>
|
undefined
{
return
this
.
.
get
(
)
||
undefined
;
}
keys
(
)
:
<
>
{
return
this
.
.
keys
(
)
;
}
}
interface
IScheduledLater
extends
IDisposable
{
isTriggered
(
)
:
boolean
;
}
const
=
(
:
number
,
fn
:
(
)
=>
void
)
:
=>
{
let
=
true
;
const
=
setTimeout
(
(
)
=>
{
=
false
;
fn
(
)
;
}
,
)
;
return
{
isTriggered
:
(
)
=>
,
dispose
:
(
)
=>
{
clearTimeout
(
)
;
=
false
;
}
,
}
;
}
;
const
=
(
fn
:
(
)
=>
void
)
:
=>
{
let
=
true
;
queueMicrotask
(
(
)
=>
{
if
(
)
{
=
false
;
fn
(
)
;
}
}
)
;
return
{
isTriggered
:
(
)
=>
,
dispose
:
(
)
=>
{
=
false
;
}
,
}
;
}
;
/**
* A helper to delay (debounce) execution of a task that is being requested often.
*
* Following the throttler, now imagine the mail man wants to optimize the number of
* trips proactively. The trip itself can be long, so he decides not to make the trip
* as soon as a letter is submitted. Instead he waits a while, in case more
* letters are submitted. After said waiting period, if no letters were submitted, he
* decides to make the trip. Imagine that N more letters were submitted after the first
* one, all within a short period of time between each other. Even though N+1
* submissions occurred, only 1 delivery was made.
*
* The delayer offers this behavior via the trigger() method, into which both the task
* to be executed and the waiting period (delay) must be passed in as arguments. Following
* the example:
*
* const delayer = new Delayer(WAITING_PERIOD);
* const letters = [];
*
* function letterReceived(l) {
* letters.push(l);
* delayer.trigger(() => { return makeTheTrip(); });
* }
*/
export
class
Delayer<T>
implements
IDisposable
{
private
:
|
null
;
private
:
Promise
<
any
>
|
null
;
private
:
(
(
?
:
any
|
Promise
<
any
>
)
=>
void
)
|
null
;
private
:
(
(
:
unknown
)
=>
void
)
|
null
;
private
:
<
T
|
Promise
<
T
>>
|
null
;
constructor
(
public
:
number
|
typeof
)
{
this
.
=
null
;
this
.
=
null
;
this
.
=
null
;
this
.
=
null
;
this
.
=
null
;
}
trigger
(
:
<
T
|
Promise
<
T
>>
,
=
this
.
)
:
Promise
<
T
>
{
this
.
=
;
this
.
cancelTimeout
(
)
;
if
(
!
this
.
)
{
this
.
=
new
Promise
(
(
,
)
=>
{
this
.
=
;
this
.
=
;
}
)
.
then
(
(
)
=>
{
this
.
=
null
;
this
.
=
null
;
if
(
this
.
)
{
const
=
this
.
;
this
.
=
null
;
return
task
(
)
;
}
return
undefined
;
}
)
;
}
const
fn
=
(
)
=>
{
this
.
=
null
;
this
.
?.
(
null
)
;
}
;
this
.
=
===
?
microtaskDeferred
(
)
:
timeoutDeferred
(
,
)
;
return
this
.
;
}
isTriggered
(
)
:
boolean
{
return
!
!
this
.
?.
isTriggered
(
)
;
}
cancel
(
)
:
void
{
this
.
cancelTimeout
(
)
;
if
(
this
.
)
{
this
.
?.
(
new
CancellationError
(
)
)
;
this
.
=
null
;
}
}
private
cancelTimeout
(
)
:
void
{
this
.
?.
dispose
(
)
;
this
.
=
null
;
}
dispose
(
)
:
void
{
this
.
cancel
(
)
;
}
}
/**
* A helper to delay execution of a task that is being requested often, while
* preventing accumulation of consecutive executions, while the task runs.
*
* The mail man is clever and waits for a certain amount of time, before going
* out to deliver letters. While the mail man is going out, more letters arrive
* and can only be delivered once he is back. Once he is back the mail man will
* do one more trip to deliver the letters that have accumulated while he was out.
*/
export
class
ThrottledDelayer<T>
{
private
:
<
Promise
<
T
>>
;
private
:
;
constructor
(
:
number
)
{
this
.
=
new
Delayer
(
)
;
this
.
=
new
Throttler
(
)
;
}
trigger
(
:
<
Promise
<
T
>>
,
?
:
number
)
:
Promise
<
T
>
{
return
this
.
.
trigger
(
(
)
=>
this
.
.
queue
(
)
,
)
as
unknown
as
Promise
<
T
>
;
}
isTriggered
(
)
:
boolean
{
return
this
.
.
isTriggered
(
)
;
}
cancel
(
)
:
void
{
this
.
.
cancel
(
)
;
}
dispose
(
)
:
void
{
this
.
.
dispose
(
)
;
this
.
.
dispose
(
)
;
}
}
/**
* A barrier that is initially closed and then becomes opened permanently.
*/
export
class
Barrier
{
private
:
boolean
;
private
:
Promise
<
boolean
>
;
private
!
:
(
:
boolean
)
=>
void
;
constructor
(
)
{
this
.
=
false
;
this
.
=
new
Promise<boolean>
(
(
,
)
=>
{
this
.
=
;
}
)
;
}
isOpen
(
)
:
boolean
{
return
this
.
;
}
open
(
)
:
void
{
this
.
=
true
;
this
.
_completePromise
(
true
)
;
}
wait
(
)
:
Promise
<
boolean
>
{
return
this
.
;
}
}
/**
* A barrier that is initially closed and then becomes opened permanently after a certain period of
* time or when open is called explicitly
*/
export
class
AutoOpenBarrier
extends
Barrier
{
private
readonly
:
;
constructor
(
:
number
)
{
super
(
)
;
this
.
=
setTimeout
(
(
)
=>
this
.
open
(
)
,
)
;
}
open
(
)
:
void
{
clearTimeout
(
this
.
)
;
super
.
open
(
)
;
}
}
export
function
timeout
(
:
number
)
:
<
void
>
;
export
function
timeout
(
:
number
,
:
)
:
Promise
<
void
>
;
export
function
timeout
(
:
number
,
?
:
)
:
<
void
>
|
Promise
<
void
>
{
if
(
!
)
{
return
createCancelablePromise
(
=>
timeout
(
,
)
)
;
}
return
new
Promise
(
(
,
)
=>
{
const
=
setTimeout
(
(
)
=>
{
.
dispose
(
)
;
resolve
(
)
;
}
,
)
;
const
=
.
onCancellationRequested
(
(
)
=>
{
clearTimeout
(
)
;
.
dispose
(
)
;
reject
(
new
CancellationError
(
)
)
;
}
)
;
}
)
;
}
/**
* Creates a timeout that can be disposed using its returned value.
* @paramhandler The timeout handler.
* @paramtimeout An optional timeout in milliseconds.
* @paramstore An optional {@link DisposableStore} that will have the timeout disposable managed automatically.
*
* @example
* const store = new DisposableStore;
* // Call the timeout after 1000ms at which point it will be automatically
* // evicted from the store.
* const timeoutDisposable = disposableTimeout(() => {}, 1000, store);
*
* if (foo) {
* // Cancel the timeout and evict it from store.
* timeoutDisposable.dispose();
* }
*/
export
function
disposableTimeout
(
handler
:
(
)
=>
void
,
=
0
,
?
:
)
:
{
const
=
setTimeout
(
(
)
=>
{
handler
(
)
;
if
(
)
{
.
dispose
(
)
;
}
}
,
)
;
const
=
toDisposable
(
(
)
=>
{
clearTimeout
(
)
;
?.
delete
(
)
;
}
)
;
?.
add
(
)
;
return
;
}
/**
* The largest delay (in milliseconds) a single `setTimeout` can represent.
* Larger values overflow its internal 32-bit signed integer and fire (almost)
* immediately instead of waiting.
*/
export
const
MAX_TIMEOUT_DELAY
=
2
**
31
-
1
;
// ~24.8 days
/**
* Like {@link disposableTimeout}, but supports delays larger than
* {@link MAX_TIMEOUT_DELAY} (~24.8 days), which a single `setTimeout` cannot
* represent. The wait is split into chunks and re-armed until the target time is
* reached, so the handler fires at approximately `Date.now() + timeout`.
*
* Note: like `setTimeout`, firing is best-effort and may drift across system
* sleep or wall-clock changes; do not rely on it for precise scheduling.
*
* @paramhandler The timeout handler.
* @paramtimeout The timeout in milliseconds. May exceed {@link MAX_TIMEOUT_DELAY}.
* @paramstore An optional {@link DisposableStore} that will have the timeout disposable managed automatically.
*/
export
function
disposableLongTimeout
(
handler
:
(
)
=>
void
,
:
number
,
?
:
)
:
{
const
=
.
now
(
)
+
;
let
:
;
const
arm
=
(
)
=>
{
const
=
-
.
now
(
)
;
if
(
<=
0
)
{
handler
(
)
;
if
(
)
{
.
dispose
(
)
;
}
return
;
}
=
setTimeout
(
,
.
min
(
,
MAX_TIMEOUT_DELAY
)
)
;
}
;
const
=
toDisposable
(
(
)
=>
{
clearTimeout
(
)
;
?.
delete
(
)
;
}
)
;
=
setTimeout
(
,
.
min
(
.
max
(
0
,
)
,
MAX_TIMEOUT_DELAY
)
)
;
?.
add
(
)
;
return
;
}
/**
* Runs the provided list of promise factories in sequential order. The returned
* promise will complete to an array of results from each promise.
*/
export
function
sequence<T>
(
:
<
Promise
<
T
>>
[
]
)
:
Promise
<
T
[
]
>
{
const
:
T
[
]
=
[
]
;
let
=
0
;
const
=
.
;
function
next
(
)
:
Promise
<
T
>
|
null
{
return
<
?
[
++
]
(
)
:
null
;
}
function
thenHandler
(
:
unknown
)
:
Promise
<
any
>
{
if
(
!==
undefined
&&
!==
null
)
{
.
push
(
as
T
)
;
}
const
=
next
(
)
;
if
(
)
{
return
.
then
(
)
;
}
return
Promise
.
resolve
(
)
;
}
return
Promise
.
resolve
(
null
)
.
then
(
)
;
}
export
function
first<T>
(
:
<
Promise
<
T
>>
[
]
,
shouldStop
:
(
:
T
)
=>
boolean
=
=>
!
!
,
:
T
|
null
=
null
)
:
Promise
<
T
|
null
>
{
let
=
0
;
const
=
.
;
const
loop
:
(
)
=>
Promise
<
T
|
null
>
=
(
)
=>
{
if
(
>=
)
{
return
Promise
.
resolve
(
)
;
}
const
=
[
++
]
;
const
=
Promise
.
resolve
(
factory
(
)
)
;
return
.
then
(
=>
{
if
(
shouldStop
(
)
)
{
return
Promise
.
resolve
(
)
;
}
return
loop
(
)
;
}
)
;
}
;
return
loop
(
)
;
}
/**
* Returns the result of the first promise that matches the "shouldStop",
* running all promises in parallel. Supports cancelable promises.
*/
export
function
firstParallel<T>
(
:
Promise
<
T
>
[
]
,
?
:
(
:
T
)
=>
boolean
,
?
:
T
|
null
)
:
Promise
<
T
|
null
>
;
export
function
firstParallel<T,RextendsT>
(
:
Promise
<
T
>
[
]
,
shouldStop
:
(
:
T
)
=>
is
R
,
?
:
R
|
null
)
:
Promise
<
R
|
null
>
;
export
function
firstParallel<T>
(
:
Promise
<
T
>
[
]
,
shouldStop
:
(
:
T
)
=>
boolean
=
=>
!
!
,
:
T
|
null
=
null
)
{
if
(
.
===
0
)
{
return
Promise
.
resolve
(
)
;
}
let
=
.
;
const
finish
=
(
)
=>
{
=
-
1
;
for
(
const
of
)
{
(
as
<
<
T
>>
)
.
?.
(
)
;
}
}
;
return
new
Promise<T|null>
(
(
,
)
=>
{
for
(
const
of
)
{
.
then
(
=>
{
if
(
--
>=
0
&&
shouldStop
(
)
)
{
finish
(
)
;
resolve
(
)
;
}
else
if
(
===
0
)
{
resolve
(
)
;
}
}
)
.
catch
(
=>
{
if
(
--
>=
0
)
{
finish
(
)
;
reject
(
)
;
}
}
)
;
}
}
)
;
}
interface
ILimitedTaskFactory<T>
{
:
<
Promise
<
T
>>
;
c
:
(
:
T
|
Promise
<
T
>
)
=>
void
;
e
:
(
?
:
unknown
)
=>
void
;
}
export
interface
ILimiter<T>
{
readonly
:
number
;
queue
(
:
<
Promise
<
T
>>
)
:
Promise
<
T
>
;
clear
(
)
:
void
;
}
/**
* A helper to queue N promises and run them all with a max degree of parallelism. The helper
* ensures that at any time no more than M promises are running at the same time.
*/
export
class
Limiter<T>
implements
ILimiter<T>
{
private
=
0
;
private
=
false
;
private
:
number
;
private
readonly
:
number
;
private
readonly
:
<
T
>
[
]
;
private
readonly
:
<
void
>
;
constructor
(
:
number
)
{
this
.
=
;
this
.
=
[
]
;
this
.
=
0
;
this
.
=
new
Emitter<void>
(
)
;
}
/**
*
* @returns A promise that resolved when all work is done (onDrained) or when
* there is nothing to do
*/
whenIdle
(
)
:
Promise
<
void
>
{
return
this
.
>
0
?
.
toPromise
(
this
.
)
:
Promise
.
resolve
(
)
;
}
get
onDrained
(
)
:
<
void
>
{
return
this
.
.
;
}
get
size
(
)
:
number
{
return
this
.
;
}
queue
(
:
<
Promise
<
T
>>
)
:
Promise
<
T
>
{
if
(
this
.
)
{
throw
new
Error
(
'Object has been disposed'
)
;
}
this
.
++
;
return
new
Promise<T>
(
(
,
)
=>
{
this
.
.
push
(
{
,
,
}
)
;
this
.
consume
(
)
;
}
)
;
}
private
consume
(
)
:
void
{
while
(
this
.
.
&&
this
.
<
this
.
)
{
const
=
this
.
.
shift
(
)
!
;
this
.
++
;
const
=
.
factory
(
)
;
.
then
(
.
,
.
)
;
.
then
(
(
)
=>
this
.
consumed
(
)
,
(
)
=>
this
.
consumed
(
)
)
;
}
}
private
consumed
(
)
:
void
{
if
(
this
.
)
{
return
;
}
this
.
--
;
if
(
--
this
.
===
0
)
{
this
.
.
fire
(
)
;
}
if
(
this
.
.
>
0
)
{
this
.
consume
(
)
;
}
}
clear
(
)
:
void
{
if
(
this
.
)
{
throw
new
Error
(
'Object has been disposed'
)
;
}
this
.
.
=
0
;
this
.
=
this
.
;
}
dispose
(
)
:
void
{
this
.
=
true
;
this
.
.
=
0
;
// stop further processing
this
.
=
0
;
this
.
.
dispose
(
)
;
}
}
/**
* A queue is handles one promise at a time and guarantees that at any time only one promise is executing.
*/
export
class
Queue<T>
extends
Limiter<T>
{
constructor
(
)
{
super
(
1
)
;
}
}
/**
* Same as `Queue`, ensures that only 1 task is executed at the same time. The difference to `Queue` is that
* there is only 1 task about to be scheduled next. As such, calling `queue` while a task is executing will
* replace the currently queued task until it executes.
*
* As such, the returned promise may not be from the factory that is passed in but from the next factory that
* is running after having called `queue`.
*/
export
class
LimitedQueue
{
private
readonly
=
new
TaskSequentializer
(
)
;
private
=
0
;
queue
(
:
<
Promise
<
void
>>
)
:
Promise
<
void
>
{
if
(
!
this
.
.
isRunning
(
)
)
{
return
this
.
.
run
(
this
.
++
,
factory
(
)
)
;
}
return
this
.
.
queue
(
(
)
=>
{
return
this
.
.
run
(
this
.
++
,
factory
(
)
)
;
}
)
;
}
}
/**
* A helper to organize queues per resource. The ResourceQueue makes sure to manage queues per resource
* by disposing them once the queue is empty.
*/
export
class
ResourceQueue
implements
IDisposable
{
private
readonly
=
new
Map<string, Queue<void>>
(
)
;
private
readonly
=
new
Set<DeferredPromise<void>>
(
)
;
private
:
<
number
>
|
undefined
=
undefined
;
private
=
0
;
async
whenDrained
(
)
:
Promise
<
void
>
{
if
(
this
.
isDrained
(
)
)
{
return
;
}
const
=
new
DeferredPromise<void>
(
)
;
this
.
.
add
(
)
;
return
.
;
}
private
isDrained
(
)
:
boolean
{
for
(
const
[
,
]
of
this
.
)
{
if
(
.
>
0
)
{
return
false
;
}
}
return
true
;
}
queueSize
(
:
URI
,
:
=
)
:
number
{
const
=
.
getComparisonKey
(
)
;
return
this
.
.
get
(
)
?.
??
0
;
}
queueFor
(
:
URI
,
:
<
Promise
<
void
>>
,
:
=
)
:
Promise
<
void
>
{
const
=
.
getComparisonKey
(
)
;
let
=
this
.
.
get
(
)
;
if
(
!
)
{
=
new
Queue<void>
(
)
;
const
=
this
.
++
;
const
=
.
once
(
.
)
(
(
)
=>
{
?.
dispose
(
)
;
this
.
.
delete
(
)
;
this
.
onDidQueueDrain
(
)
;
this
.
?.
deleteAndDispose
(
)
;
if
(
this
.
?.
===
0
)
{
this
.
.
dispose
(
)
;
this
.
=
undefined
;
}
}
)
;
if
(
!
this
.
)
{
this
.
=
new
DisposableMap
(
)
;
}
this
.
.
set
(
,
)
;
this
.
.
set
(
,
)
;
}
return
.
queue
(
)
;
}
private
onDidQueueDrain
(
)
:
void
{
if
(
!
this
.
isDrained
(
)
)
{
return
;
// not done yet
}
this
.
releaseDrainers
(
)
;
}
private
releaseDrainers
(
)
:
void
{
for
(
const
of
this
.
)
{
.
complete
(
)
;
}
this
.
.
clear
(
)
;
}
dispose
(
)
:
void
{
for
(
const
[
,
]
of
this
.
)
{
.
dispose
(
)
;
}
this
.
.
clear
(
)
;
// Even though we might still have pending
// tasks queued, after the queues have been
// disposed, we can no longer track them, so
// we release drainers to prevent hanging
// promises when the resource queue is being
// disposed.
this
.
releaseDrainers
(
)
;
this
.
?.
dispose
(
)
;
}
}
export
type
Task<T=void>
=
(
)
=>
(
Promise
<
T
>
|
T
)
;
/**
* Wrap a type in an optional promise. This can be useful to avoid the runtime
* overhead of creating a promise.
*/
export
type
MaybePromise<T>
=
Promise
<
T
>
|
T
;
/**
* Processes tasks in the order they were scheduled.
*/
export
class
TaskQueue
{
private
:
<
any
>
|
undefined
=
undefined
;
private
:
{
:
<
any
>
;
:
<
any
>
;
:
boolean
}
[
]
=
[
]
;
/**
* Waits for the current and pending tasks to finish, then runs and awaits the given task.
* If the task is skipped because of clearPending, the promise is rejected with a CancellationError.
*/
public
schedule<T>
(
:
<
T
>
)
:
Promise
<
T
>
{
const
=
new
DeferredPromise<T>
(
)
;
this
.
.
push
(
{
,
,
:
false
}
)
;
this
.
_runIfNotRunning
(
)
;
return
.
;
}
/**
* Waits for the current and pending tasks to finish, then runs and awaits the given task.
* If the task is skipped because of clearPending, the promise is resolved with undefined.
*/
public
scheduleSkipIfCleared<T>
(
:
<
T
>
)
:
Promise
<
T
|
undefined
>
{
const
=
new
DeferredPromise<T>
(
)
;
this
.
.
push
(
{
,
,
:
true
}
)
;
this
.
_runIfNotRunning
(
)
;
return
.
;
}
private
_runIfNotRunning
(
)
:
void
{
if
(
this
.
===
undefined
)
{
this
.
_processQueue
(
)
;
}
}
private
async
_processQueue
(
)
:
Promise
<
void
>
{
if
(
this
.
.
===
0
)
{
return
;
}
const
=
this
.
.
shift
(
)
;
if
(
!
)
{
return
;
}
if
(
this
.
)
{
throw
new
BugIndicatingError
(
)
;
}
this
.
=
.
;
try
{
const
=
await
.
task
(
)
;
.
.
complete
(
)
;
}
catch
(
)
{
.
.
error
(
)
;
}
finally
{
this
.
=
undefined
;
this
.
_processQueue
(
)
;
}
}
/**
* Clears all pending tasks. Does not cancel the currently running task.
*/
public
clearPending
(
)
:
void
{
const
=
this
.
;
this
.
=
[
]
;
for
(
const
of
)
{
if
(
.
)
{
.
.
complete
(
undefined
)
;
}
else
{
.
.
error
(
new
CancellationError
(
)
)
;
}
}
}
}
export
class
TimeoutTimer
implements
IDisposable
{
private
:
|
undefined
;
private
=
false
;
constructor
(
)
;
constructor
(
runner
:
(
)
=>
void
,
:
number
)
;
constructor
(
?
:
(
)
=>
void
,
?
:
number
)
{
this
.
=
undefined
;
if
(
typeof
===
'function'
&&
typeof
===
'number'
)
{
this
.
setIfNotSet
(
,
)
;
}
}
dispose
(
)
:
void
{
this
.
cancel
(
)
;
this
.
=
true
;
}
cancel
(
)
:
void
{
if
(
this
.
!==
undefined
)
{
clearTimeout
(
this
.
)
;
this
.
=
undefined
;
}
}
cancelAndSet
(
runner
:
(
)
=>
void
,
:
number
)
:
void
{
if
(
this
.
)
{
throw
new
BugIndicatingError
(
`Calling 'cancelAndSet' on a disposed TimeoutTimer`
)
;
}
this
.
cancel
(
)
;
this
.
=
setTimeout
(
(
)
=>
{
this
.
=
undefined
;
runner
(
)
;
}
,
)
;
}
setIfNotSet
(
runner
:
(
)
=>
void
,
:
number
)
:
void
{
if
(
this
.
)
{
throw
new
BugIndicatingError
(
`Calling 'setIfNotSet' on a disposed TimeoutTimer`
)
;
}
if
(
this
.
!==
undefined
)
{
// timer is already set
return
;
}
this
.
=
setTimeout
(
(
)
=>
{
this
.
=
undefined
;
runner
(
)
;
}
,
)
;
}
}
export
class
IntervalTimer
implements
IDisposable
{
private
:
|
undefined
=
undefined
;
private
=
false
;
cancel
(
)
:
void
{
this
.
?.
dispose
(
)
;
this
.
=
undefined
;
}
cancelAndSet
(
runner
:
(
)
=>
void
,
:
number
,
=
)
:
void
{
if
(
this
.
)
{
throw
new
BugIndicatingError
(
`Calling 'cancelAndSet' on a disposed IntervalTimer`
)
;
}
this
.
cancel
(
)
;
const
=
.
setInterval
(
(
)
=>
{
runner
(
)
;
}
,
)
;
this
.
=
toDisposable
(
(
)
=>
{
.
clearInterval
(
)
;
this
.
=
undefined
;
}
)
;
}
dispose
(
)
:
void
{
this
.
cancel
(
)
;
this
.
=
true
;
}
}
export
class
RunOnceScheduler<Runner extends(...args:any[])=>
any
=
(
)
=>
any
>
implements
IDisposable
{
protected
:
|
null
;
private
:
|
undefined
;
private
:
number
;
private
timeoutHandler
:
(
)
=>
void
;
constructor
(
:
,
:
number
)
{
this
.
=
undefined
;
this
.
=
;
this
.
=
;
this
.
=
this
.
onTimeout
.
bind
(
this
)
;
}
/**
* Dispose RunOnceScheduler
*/
dispose
(
)
:
void
{
this
.
cancel
(
)
;
this
.
=
null
;
}
/**
* Cancel current scheduled runner (if any).
*/
cancel
(
)
:
void
{
if
(
this
.
isScheduled
(
)
)
{
clearTimeout
(
this
.
)
;
this
.
=
undefined
;
}
}
/**
* Cancel previous runner (if any) & schedule a new runner.
*/
schedule
(
=
this
.
)
:
void
{
this
.
cancel
(
)
;
this
.
=
setTimeout
(
this
.
,
)
;
}
get
delay
(
)
:
number
{
return
this
.
;
}
set
delay
(
:
number
)
{
this
.
=
;
}
/**
* Returns true if scheduled.
*/
isScheduled
(
)
:
boolean
{
return
this
.
!==
undefined
;
}
flush
(
)
:
void
{
if
(
this
.
isScheduled
(
)
)
{
this
.
cancel
(
)
;
this
.
doRun
(
)
;
}
}
private
onTimeout
(
)
{
this
.
=
undefined
;
if
(
this
.
)
{
this
.
doRun
(
)
;
}
}
protected
doRun
(
)
:
void
{
this
.
?.
(
)
;
}
}
/**
* Same as `RunOnceScheduler`, but doesn't count the time spent in sleep mode.
* > **NOTE**: Only offers 1s resolution.
*
* When calling `setTimeout` with 3hrs, and putting the computer immediately to sleep
* for 8hrs, `setTimeout` will fire **as soon as the computer wakes from sleep**. But
* this scheduler will execute 3hrs **after waking the computer from sleep**.
*/
export
class
ProcessTimeRunOnceScheduler
{
private
:
(
(
)
=>
void
)
|
null
;
private
:
number
;
private
:
number
;
private
:
|
undefined
;
private
intervalHandler
:
(
)
=>
void
;
constructor
(
runner
:
(
)
=>
void
,
:
number
)
{
if
(
%
1000
!==
0
)
{
console
.
warn
(
`ProcessTimeRunOnceScheduler resolution is 1s, ${delay}ms is not a multiple of 1000ms.`
)
;
}
this
.
=
;
this
.
=
;
this
.
=
0
;
this
.
=
undefined
;
this
.
=
this
.
onInterval
.
bind
(
this
)
;
}
dispose
(
)
:
void
{
this
.
cancel
(
)
;
this
.
=
null
;
}
cancel
(
)
:
void
{
if
(
this
.
isScheduled
(
)
)
{
clearInterval
(
this
.
)
;
this
.
=
undefined
;
}
}
/**
* Cancel previous runner (if any) & schedule a new runner.
*/
schedule
(
=
this
.
)
:
void
{
if
(
%
1000
!==
0
)
{
console
.
warn
(
`ProcessTimeRunOnceScheduler resolution is 1s, ${delay}ms is not a multiple of 1000ms.`
)
;
}
this
.
cancel
(
)
;
this
.
=
.
ceil
(
/
1000
)
;
this
.
=
setInterval
(
this
.
,
1000
)
;
}
/**
* Returns true if scheduled.
*/
isScheduled
(
)
:
boolean
{
return
this
.
!==
undefined
;
}
private
onInterval
(
)
{
this
.
--
;
if
(
this
.
>
0
)
{
// still need to wait
return
;
}
// time elapsed
clearInterval
(
this
.
)
;
this
.
=
undefined
;
this
.
?.
(
)
;
}
}
export
class
RunOnceWorker<T>
extends
RunOnceScheduler<(units:T[])=>
void
>
{
private
:
T
[
]
=
[
]
;
constructor
(
runner
:
(
:
T
[
]
)
=>
void
,
:
number
)
{
super
(
,
)
;
}
work
(
:
T
)
:
void
{
this
.
.
push
(
)
;
if
(
!
this
.
isScheduled
(
)
)
{
this
.
schedule
(
)
;
}
}
protected
doRun
(
)
:
void
{
const
=
this
.
;
this
.
=
[
]
;
this
.
?.
(
)
;
}
dispose
(
)
:
void
{
this
.
=
[
]
;
super
.
dispose
(
)
;
}
}
export
interface
IThrottledWorkerOptions
{
/**
* maximum of units the worker will pass onto handler at once
*/
:
number
;
/**
* maximum of units the worker will keep in memory for processing
*/
:
number
|
undefined
;
/**
* delay before processing the next round of chunks when chunk size exceeds limits
*/
:
number
;
/**
* When enabled will guarantee that two distinct calls to `work()` are not executed
* without throttle delay between them.
* Otherwise if the worker isn't currently throttling it will execute work immediately.
*/
?
:
boolean
;
}
/**
* The `ThrottledWorker` will accept units of work `T`
* to handle. The contract is:
* * there is a maximum of units the worker can handle at once (via `maxWorkChunkSize`)
* * there is a maximum of units the worker will keep in memory for processing (via `maxBufferedWork`)
* * after having handled `maxWorkChunkSize` units, the worker needs to rest (via `throttleDelay`)
*/
export
class
ThrottledWorker<T>
extends
Disposable
{
private
readonly
:
T
[
]
=
[
]
;
private
readonly
=
this
.
_register
(
new
MutableDisposable<RunOnceScheduler>
(
)
)
;
private
=
false
;
private
=
0
;
constructor
(
private
:
,
private
readonly
handler
:
(
:
T
[
]
)
=>
void
)
{
super
(
)
;
}
/**
* The number of work units that are pending to be processed.
*/
get
pending
(
)
:
number
{
return
this
.
.
;
}
/**
* Add units to be worked on. Use `pending` to figure out
* how many units are not yet processed after this method
* was called.
*
* @returns whether the work was accepted or not. If the
* worker is disposed, it will not accept any more work.
* If the number of pending units would become larger
* than `maxPendingWork`, more work will also not be accepted.
*/
work
(
:
readonly
T
[
]
)
:
boolean
{
if
(
this
.
)
{
return
false
;
// work not accepted: disposed
}
// Check for reaching maximum of pending work
if
(
typeof
this
.
.
===
'number'
)
{
// Throttled: simple check if pending + units exceeds max pending
if
(
this
.
.
)
{
if
(
this
.
+
.
>
this
.
.
)
{
return
false
;
// work not accepted: too much pending work
}
}
// Unthrottled: same as throttled, but account for max chunk getting
// worked on directly without being pending
else
{
if
(
this
.
+
.
-
this
.
.
>
this
.
.
)
{
return
false
;
// work not accepted: too much pending work
}
}
}
// Add to pending units first
for
(
const
of
)
{
this
.
.
push
(
)
;
}
const
=
.
now
(
)
-
this
.
;
if
(
!
this
.
.
&&
(
!
this
.
.
||
>=
this
.
.
)
)
{
// Work directly if we are not throttling and we are not
// enforced to throttle between `work()` calls.
this
.
doWork
(
)
;
}
else
if
(
!
this
.
.
&&
this
.
.
)
{
// Otherwise, schedule the throttler to work.
this
.
scheduleThrottler
(
.
max
(
this
.
.
-
,
0
)
)
;
}
else
{
// Otherwise, our work will be picked up by the running throttler
}
return
true
;
// work accepted
}
private
doWork
(
)
:
void
{
this
.
=
.
now
(
)
;
// Extract chunk to handle and handle it
this
.
handler
(
this
.
.
splice
(
0
,
this
.
.
)
)
;
// If we have remaining work, schedule it after a delay
if
(
this
.
.
>
0
)
{
this
.
scheduleThrottler
(
)
;
}
}
private
scheduleThrottler
(
=
this
.
.
)
:
void
{
this
.
.
=
new
RunOnceScheduler
(
(
)
=>
{
this
.
.
clear
(
)
;
this
.
doWork
(
)
;
}
,
)
;
this
.
.
.
schedule
(
)
;
}
dispose
(
)
:
void
{
super
.
dispose
(
)
;
this
.
.
=
0
;
this
.
=
true
;
}
}
//#region -- run on idle tricks ------------
export
interface
IdleDeadline
{
readonly
:
boolean
;
timeRemaining
(
)
:
number
;
}
type
IdleApi
=
<
typeof
,
'requestIdleCallback'
|
'cancelIdleCallback'
>
;
/**
* Execute the callback the next time the browser is idle, returning an
* {@link IDisposable} that will cancel the callback when disposed. This wraps
* [requestIdleCallback] so it will fallback to [setTimeout] if the environment
* doesn't support it.
*
* @paramcallback The callback to run when idle, this includes an
* [IdleDeadline] that provides the time alloted for the idle callback by the
* browser. Not respecting this deadline will result in a degraded user
* experience.
* @paramtimeout A timeout at which point to queue no longer wait for an idle
* callback but queue it on the regular event loop (like setTimeout). Typically
* this should not be used.
*
* [IdleDeadline]: https://developer.mozilla.org/en-US/docs/Web/API/IdleDeadline
* [requestIdleCallback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
* [setTimeout]: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout
*
* **Note** that there is `dom.ts#runWhenWindowIdle` which is better suited when running inside a browser
* context
*/
export
let
runWhenGlobalIdle
:
(
callback
:
(
:
)
=>
void
,
?
:
number
)
=>
;
export
let
_runWhenIdle
:
(
:
,
callback
:
(
:
)
=>
void
,
?
:
number
)
=>
;
(
function
(
)
{
const
:
any
=
;
if
(
typeof
.
!==
'function'
||
typeof
.
!==
'function'
)
{
_runWhenIdle
=
(
,
,
?
)
=>
{
setTimeout0
(
(
)
=>
{
if
(
)
{
return
;
}
const
=
.
now
(
)
+
15
;
// one frame at 64fps
const
:
=
{
:
true
,
timeRemaining
(
)
{
return
.
max
(
0
,
-
.
now
(
)
)
;
}
}
;
runner
(
.
freeze
(
)
)
;
}
)
;
let
=
false
;
return
{
dispose
(
)
{
if
(
)
{
return
;
}
=
true
;
}
}
;
}
;
}
else
{
_runWhenIdle
=
(
:
typeof
,
,
?
)
=>
{
const
:
number
=
.
requestIdleCallback
(
,
typeof
===
'number'
?
{
}
:
undefined
)
;
let
=
false
;
return
{
dispose
(
)
{
if
(
)
{
return
;
}
=
true
;
.
cancelIdleCallback
(
)
;
}
}
;
}
;
}
runWhenGlobalIdle
=
(
,
)
=>
_runWhenIdle
(
,
,
)
;
}
)
(
)
;
export
function
installFakeRunWhenIdle
(
:
typeof
)
:
{
const
=
;
const
=
;
=
;
runWhenGlobalIdle
=
(
,
)
=>
fakeImpl
(
,
,
)
;
return
toDisposable
(
(
)
=>
{
=
;
=
;
}
)
;
}
export
abstract
class
AbstractIdleValue<T>
{
private
readonly
_executor
:
(
)
=>
void
;
private
readonly
:
;
private
:
boolean
=
false
;
private
?
:
T
;
private
:
unknown
;
constructor
(
:
,
executor
:
(
)
=>
T
)
{
this
.
_executor
=
(
)
=>
{
try
{
this
.
=
executor
(
)
;
}
catch
(
)
{
this
.
=
;
}
finally
{
this
.
=
true
;
}
}
;
this
.
=
_runWhenIdle
(
,
(
)
=>
this
.
_executor
(
)
)
;
}
dispose
(
)
:
void
{
this
.
.
dispose
(
)
;
}
get
value
(
)
:
T
{
if
(
!
this
.
)
{
this
.
.
dispose
(
)
;
this
.
_executor
(
)
;
}
if
(
this
.
)
{
throw
this
.
;
}
return
this
.
!
;
}
get
isInitialized
(
)
:
boolean
{
return
this
.
;
}
}
/**
* An `IdleValue` that always uses the current window (which might be throttled or inactive)
*
* **Note** that there is `dom.ts#WindowIdleValue` which is better suited when running inside a browser
* context
*/
export
class
GlobalIdleValue<T>
extends
AbstractIdleValue<T>
{
constructor
(
executor
:
(
)
=>
T
)
{
super
(
,
)
;
}
}
//#endregion
export
async
function
retry<T>
(
:
<
Promise
<
T
>>
,
:
number
,
:
number
)
:
Promise
<
T
>
{
let
:
|
undefined
;
for
(
let
=
0
;
<
;
++
)
{
try
{
return
await
task
(
)
;
}
catch
(
)
{
=
;
await
timeout
(
)
;
}
}
throw
;
}
//#region Task Sequentializer
interface
IRunningTask
{
readonly
:
number
;
readonly
cancel
:
(
)
=>
void
;
readonly
:
Promise
<
void
>
;
}
interface
IQueuedTask
{
readonly
:
Promise
<
void
>
;
readonly
promiseResolve
:
(
)
=>
void
;
readonly
promiseReject
:
(
:
)
=>
void
;
:
<
Promise
<
void
>>
;
}
export
interface
ITaskSequentializerWithRunningTask
{
readonly
:
Promise
<
void
>
;
}
export
interface
ITaskSequentializerWithQueuedTask
{
readonly
:
;
}
/**
* @deprecated use `LimitedQueue` instead for an easier to use API
*/
export
class
TaskSequentializer
{
private
?
:
;
private
?
:
;
isRunning
(
?
:
number
)
:
this
is
{
if
(
typeof
===
'number'
)
{
return
this
.
?.
===
;
}
return
!
!
this
.
;
}
get
running
(
)
:
Promise
<
void
>
|
undefined
{
return
this
.
?.
;
}
cancelRunning
(
)
:
void
{
this
.
?.
cancel
(
)
;
}
run
(
:
number
,
:
Promise
<
void
>
,
?
:
(
)
=>
void
,
)
:
Promise
<
void
>
{
this
.
=
{
,
cancel
:
(
)
=>
?.
(
)
,
}
;
.
then
(
(
)
=>
this
.
doneRunning
(
)
,
(
)
=>
this
.
doneRunning
(
)
)
;
return
;
}
private
doneRunning
(
:
number
)
:
void
{
if
(
this
.
&&
===
this
.
.
)
{
// only set running to done if the promise finished that is associated with that taskId
this
.
=
undefined
;
// schedule the queued task now that we are free if we have any
this
.
runQueued
(
)
;
}
}
private
runQueued
(
)
:
void
{
if
(
this
.
)
{
const
=
this
.
;
this
.
=
undefined
;
// Run queued task and complete on the associated promise
.
run
(
)
.
then
(
.
,
.
)
;
}
}
/**
* Note: the promise to schedule as next run MUST itself call `run`.
* Otherwise, this sequentializer will report `false` for `isRunning`
* even when this task is running. Missing this detail means that
* suddenly multiple tasks will run in parallel.
*/
queue
(
:
<
Promise
<
void
>>
)
:
Promise
<
void
>
{
// this is our first queued task, so we create associated promise with it
// so that we can return a promise that completes when the task has
// completed.
if
(
!
this
.
)
{
const
{
,
:
,
:
}
=
promiseWithResolvers<void>
(
)
;
this
.
=
{
,
,
,
}
;
}
// we have a previous queued task, just overwrite it
else
{
this
.
.
=
;
}
return
this
.
.
;
}
hasQueued
(
)
:
this
is
{
return
!
!
this
.
;
}
async
join
(
)
:
Promise
<
void
>
{
return
this
.
?.
??
this
.
?.
;
}
}
//#endregion
//#region
/**
* The `IntervalCounter` allows to count the number
* of calls to `increment()` over a duration of
* `interval`. This utility can be used to conditionally
* throttle a frequent task when a certain threshold
* is reached.
*/
export
class
IntervalCounter
{
private
=
0
;
private
=
0
;
constructor
(
private
readonly
:
number
,
private
readonly
nowFn
=
(
)
=>
.
now
(
)
)
{
}
increment
(
)
:
number
{
const
=
this
.
nowFn
(
)
;
// We are outside of the range of `interval` and as such
// start counting from 0 and remember the time
if
(
-
this
.
>
this
.
)
{
this
.
=
;
this
.
=
0
;
}
this
.
++
;
return
this
.
;
}
}
//#endregion
//#region
export
type
ValueCallback<T=unknown>
=
(
:
T
|
Promise
<
T
>
)
=>
void
;
const
enum
{
,
}
/**
* Creates a promise whose resolution or rejection can be controlled imperatively.
*/
export
class
DeferredPromise<T>
{
public
static
fromPromise<T>
(
:
Promise
<
T
>
)
:
<
T
>
{
const
=
new
DeferredPromise<T>
(
)
;
.
settleWith
(
)
;
return
;
}
private
!
:
<
T
>
;
private
!
:
(
:
unknown
)
=>
void
;
private
?
:
{
:
.
;
:
unknown
}
|
{
:
.
;
:
T
}
;
public
get
isRejected
(
)
{
return
this
.
?.
===
.
;
}
public
get
isResolved
(
)
{
return
this
.
?.
===
.
;
}
public
get
isSettled
(
)
{
return
!
!
this
.
;
}
public
get
value
(
)
{
return
this
.
?.
===
.
?
this
.
?.
:
undefined
;
}
public
readonly
:
Promise
<
T
>
;
constructor
(
)
{
this
.
=
new
Promise<T>
(
(
,
)
=>
{
this
.
=
;
this
.
=
;
}
)
;
}
public
complete
(
:
T
)
{
if
(
this
.
)
{
return
Promise
.
resolve
(
)
;
}
return
new
Promise<void>
(
=>
{
this
.
completeCallback
(
)
;
this
.
=
{
:
.
,
}
;
resolve
(
)
;
}
)
;
}
public
error
(
:
unknown
)
{
if
(
this
.
)
{
return
Promise
.
resolve
(
)
;
}
return
new
Promise<void>
(
=>
{
this
.
errorCallback
(
)
;
this
.
=
{
:
.
,
:
}
;
resolve
(
)
;
}
)
;
}
public
settleWith
(
:
Promise
<
T
>
)
:
Promise
<
void
>
{
return
.
then
(
=>
this
.
complete
(
)
,
=>
this
.
error
(
)
)
;
}
public
cancel
(
)
{
return
this
.
error
(
new
CancellationError
(
)
)
;
}
}
//#endregion
//#region Promises
export
namespace
{
/**
* A drop-in replacement for `Promise.all` with the only difference
* that the method awaits every promise to either fulfill or reject.
*
* Similar to `Promise.all`, only the first error will be returned
* if any.
*/
export
async
function
settled<T>
(
:
Promise
<
T
>
[
]
)
:
Promise
<
T
[
]
>
{
let
:
|
undefined
=
undefined
;
const
=
await
Promise
.
all
(
.
map
(
=>
.
then
(
=>
,
=>
{
if
(
!
)
{
=
;
}
return
undefined
;
// do not rethrow so that other promises can settle
}
)
)
)
;
if
(
typeof
!==
'undefined'
)
{
throw
;
}
return
as
unknown
as
T
[
]
;
// cast is needed and protected by the `throw` above
}
/**
* A helper to create a new `Promise<T>` with a body that is a promise
* itself. By default, an error that raises from the async body will
* end up as a unhandled rejection, so this utility properly awaits the
* body and rejects the promise as a normal promise does without async
* body.
*
* This method should only be used in rare cases where otherwise `async`
* cannot be used (e.g. when callbacks are involved that require this).
*/
/**
* Returns the resolved value.
* Throws if the promise is not resolved yet.
*/
public
requireValue
(
)
:
T
{
if
(
!
this
.
)
{
throw
new
BugIndicatingError
(
'Promise is not resolved yet'
)
;
}
if
(
this
.
)
{
throw
this
.
;
}
return
this
.
!
;
}
}
export
class
LazyStatefulPromise<T>
{
private
readonly
=
new
Lazy
(
(
)
=>
new
StatefulPromise
(
this
.
_compute
(
)
)
)
;
constructor
(
private
readonly
_compute
:
(
)
=>
Promise
<
T
>
,
)
{
}
/**
* Returns the resolved value.
* Throws if the promise is not resolved yet.
*/
public
requireValue
(
)
:
T
{
return
this
.
.
.
requireValue
(
)
;
}
/**
* Returns the promise (and triggers a computation of the promise if not yet done so).
*/
public
getPromise
(
)
:
Promise
<
T
>
{
return
this
.
.
.
;
}
/**
* Reads the current value without triggering a computation of the promise.
*/
public
get
currentValue
(
)
:
T
|
undefined
{
return
this
.
.
?.
;
}
}
//#endregion
//#region
const
enum
{
,
,
,
}
/**
* An object that allows to emit async values asynchronously or bring the iterable to an error state using `reject()`.
* This emitter is valid only for the duration of the executor (until the promise returned by the executor settles).
*/
export
interface
AsyncIterableEmitter<T>
{
/**
* The value will be appended at the end.
*
* **NOTE** If `reject()` has already been called, this method has no effect.
*/
emitOne
(
:
T
)
:
void
;
/**
* The values will be appended at the end.
*
* **NOTE** If `reject()` has already been called, this method has no effect.
*/
emitMany
(
:
T
[
]
)
:
void
;
/**
* Writing an error will permanently invalidate this iterable.
* The current users will receive an error thrown, as will all future users.
*
* **NOTE** If `reject()` have already been called, this method has no effect.
*/
reject
(
:
)
:
void
;
}
/**
* An executor for the `AsyncIterableObject` that has access to an emitter.
*/
export
interface
AsyncIterableExecutor<T>
{
/**
* @paramemitter An object that allows to emit async values valid only for the duration of the executor.
*/
(
:
<
T
>
)
:
unknown
|
Promise
<
unknown
>
;
}
/**
* A rich implementation for an `AsyncIterable<T>`.
*/
export
class
AsyncIterableObject<T>
implements
AsyncIterable<T>
{
public
static
fromArray<T>
(
:
T
[
]
)
:
<
T
>
{
return
new
AsyncIterableObject<T>
(
(
)
=>
{
.
emitMany
(
)
;
}
)
;
}
public
static
fromPromise<T>
(
:
Promise
<
T
[
]
>
)
:
<
T
>
{
return
new
AsyncIterableObject<T>
(
async
(
)
=>
{
.
emitMany
(
await
)
;
}
)
;
}
public
static
fromPromisesResolveOrder<T>
(
:
Promise
<
T
>
[
]
)
:
<
T
>
{
return
new
AsyncIterableObject<T>
(
async
(
)
=>
{
await
Promise
.
all
(
.
map
(
async
(
)
=>
.
emitOne
(
await
)
)
)
;
}
)
;
}
public
static
merge<T>
(
:
<
T
>
[
]
)
:
<
T
>
{
return
new
AsyncIterableObject
(
async
(
)
=>
{
await
Promise
.
all
(
.
map
(
async
(
)
=>
{
for
await
(
const
of
)
{
.
emitOne
(
)
;
}
}
)
)
;
}
)
;
}
public
static
EMPTY
=
.
fromArray<any>
(
[
]
)
;
private
:
;
private
:
T
[
]
;
private
:
|
null
;
private
readonly
?
:
(
)
=>
void
|
Promise
<
void
>
;
private
readonly
:
<
void
>
;
constructor
(
:
<
T
>
,
?
:
(
)
=>
void
|
Promise
<
void
>
)
{
this
.
=
.
;
this
.
=
[
]
;
this
.
=
null
;
this
.
=
;
this
.
=
new
Emitter<void>
(
)
;
queueMicrotask
(
async
(
)
=>
{
const
:
<
T
>
=
{
emitOne
:
(
)
=>
this
.
emitOne
(
)
,
emitMany
:
(
)
=>
this
.
emitMany
(
)
,
reject
:
(
)
=>
this
.
reject
(
)
}
;
try
{
await
Promise
.
resolve
(
executor
(
)
)
;
this
.
resolve
(
)
;
}
catch
(
)
{
this
.
reject
(
)
;
}
finally
{
// The executor has settled; emitting afterwards must be a no-op per the
// documented "no effect after resolve()/reject()" contract (see emitOne).
.
emitOne
=
(
)
=>
{
}
;
.
emitMany
=
(
)
=>
{
}
;
.
reject
=
(
)
=>
{
}
;
}
}
)
;
}
[
.
]
(
)
:
<
T
,
undefined
,
undefined
>
{
let
=
0
;
return
{
next
:
async
(
)
=>
{
do
{
if
(
this
.
===
.
)
{
throw
this
.
;
}
if
(
<
this
.
.
)
{
return
{
:
false
,
:
this
.
[
++
]
}
;
}
if
(
this
.
===
.
)
{
return
{
:
true
,
:
undefined
}
;
}
await
.
toPromise
(
this
.
.
)
;
}
while
(
true
)
;
}
,
return
:
async
(
)
=>
{
this
.
?.
(
)
;
return
{
:
true
,
:
undefined
}
;
}
}
;
}
public
static
map<T,R>
(
:
<
T
>
,
mapFn
:
(
:
T
)
=>
R
)
:
<
R
>
{
return
new
AsyncIterableObject<R>
(
async
(
)
=>
{
for
await
(
const
of
)
{
.
emitOne
(
mapFn
(
)
)
;
}
}
)
;
}
public
map<R>
(
mapFn
:
(
:
T
)
=>
R
)
:
<
R
>
{
return
.
map
(
this
,
)
;
}
public
static
filter<T>
(
:
<
T
>
,
filterFn
:
(
:
T
)
=>
boolean
)
:
<
T
>
{
return
new
AsyncIterableObject<T>
(
async
(
)
=>
{
for
await
(
const
of
)
{
if
(
filterFn
(
)
)
{
.
emitOne
(
)
;
}
}
}
)
;
}
public
filter<T2extendsT>
(
filterFn
:
(
:
T
)
=>
is
T2
)
:
<
T2
>
;
public
filter
(
filterFn
:
(
:
T
)
=>
boolean
)
:
<
T
>
;
public
filter
(
filterFn
:
(
:
T
)
=>
boolean
)
:
<
T
>
{
return
.
filter
(
this
,
)
;
}
public
static
coalesce<T>
(
:
<
T
|
undefined
|
null
>
)
:
<
T
>
{
return
<
<
T
>>
.
filter
(
,
=>
!
!
)
;
}
public
coalesce
(
)
:
<
<
T
>>
{
return
.
coalesce
(
this
)
as
<
<
T
>>
;
}
public
static
async
toPromise<T>
(
:
<
T
>
)
:
Promise
<
T
[
]
>
{
const
:
T
[
]
=
[
]
;
for
await
(
const
of
)
{
.
push
(
)
;
}
return
;
}
public
toPromise
(
)
:
Promise
<
T
[
]
>
{
return
.
toPromise
(
this
)
;
}
/**
* The value will be appended at the end.
*
* **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
*/
private
emitOne
(
:
T
)
:
void
{
if
(
this
.
!==
.
)
{
return
;
}
// it is important to add new values at the end,
// as we may have iterators already running on the array
this
.
.
push
(
)
;
this
.
.
fire
(
)
;
}
/**
* The values will be appended at the end.
*
* **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
*/
private
emitMany
(
:
T
[
]
)
:
void
{
if
(
this
.
!==
.
)
{
return
;
}
// it is important to add new values at the end,
// as we may have iterators already running on the array
this
.
=
this
.
.
concat
(
)
;
this
.
.
fire
(
)
;
}
/**
* Calling `resolve()` will mark the result array as complete.
*
* **NOTE** `resolve()` must be called, otherwise all consumers of this iterable will hang indefinitely, similar to a non-resolved promise.
* **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
*/
private
resolve
(
)
:
void
{
if
(
this
.
!==
.
)
{
return
;
}
this
.
=
.
;
this
.
.
fire
(
)
;
}
/**
* Writing an error will permanently invalidate this iterable.
* The current users will receive an error thrown, as will all future users.
*
* **NOTE** If `resolve()` or `reject()` have already been called, this method has no effect.
*/
private
reject
(
:
)
{
if
(
this
.
!==
.
)
{
return
;
}
this
.
=
.
;
this
.
=
;
this
.
.
fire
(
)
;
}
}
export
function
createCancelableAsyncIterableProducer<T>
(
callback
:
(
:
)
=>
<
T
>
)
:
<
T
>
{
const
=
new
CancellationTokenSource
(
)
;
const
=
callback
(
.
)
;
return
new
CancelableAsyncIterableProducer<T>
(
,
async
(
)
=>
{
const
=
.
.
onCancellationRequested
(
(
)
=>
{
.
dispose
(
)
;
.
dispose
(
)
;
.
reject
(
new
CancellationError
(
)
)
;
}
)
;
try
{
for
await
(
const
of
)
{
if
(
.
.
)
{
// canceled in the meantime
return
;
}
.
emitOne
(
)
;
}
.
dispose
(
)
;
.
dispose
(
)
;
}
catch
(
)
{
.
dispose
(
)
;
.
dispose
(
)
;
.
reject
(
)
;
}
}
)
;
}
export
class
AsyncIterableSource<T>
{
private
readonly
=
new
DeferredPromise<void>
(
)
;
private
readonly
:
<
T
>
;
private
_errorFn
:
(
:
)
=>
void
;
private
_emitOneFn
:
(
:
T
)
=>
void
;
private
_emitManyFn
:
(
:
T
[
]
)
=>
void
;
/**
*
* @paramonReturn A function that will be called when consuming the async iterable
* has finished by the consumer, e.g the for-await-loop has be existed (break, return) early.
* This is NOT called when resolving this source by its owner.
*/
constructor
(
?
:
(
)
=>
Promise
<
void
>
|
void
)
{
this
.
=
new
AsyncIterableObject
(
=>
{
if
(
)
{
.
reject
(
)
;
return
;
}
if
(
)
{
.
emitMany
(
)
;
}
this
.
_errorFn
=
(
:
)
=>
.
reject
(
)
;
this
.
_emitOneFn
=
(
:
T
)
=>
.
emitOne
(
)
;
this
.
_emitManyFn
=
(
:
T
[
]
)
=>
.
emitMany
(
)
;
return
this
.
.
;
}
,
)
;
let
:
|
undefined
;
let
:
T
[
]
|
undefined
;
this
.
_errorFn
=
(
:
)
=>
{
if
(
!
)
{
=
;
}
}
;
this
.
_emitOneFn
=
(
:
T
)
=>
{
if
(
!
)
{
=
[
]
;
}
.
push
(
)
;
}
;
this
.
_emitManyFn
=
(
:
T
[
]
)
=>
{
if
(
!
)
{
=
.
slice
(
)
;
}
else
{
.
forEach
(
=>
!
.
push
(
)
)
;
}
}
;
}
get
asyncIterable
(
)
:
<
T
>
{
return
this
.
;
}
resolve
(
)
:
void
{
this
.
.
complete
(
)
;
}
reject
(
:
)
:
void
{
this
.
_errorFn
(
)
;
this
.
.
complete
(
)
;
}
emitOne
(
:
T
)
:
void
{
this
.
_emitOneFn
(
)
;
}
emitMany
(
:
T
[
]
)
{
this
.
_emitManyFn
(
)
;
}
}
export
function
cancellableIterable<T>
(
:
<
T
>
|
<
T
>
,
:
)
:
<
T
>
{
const
=
.
in
?
[
.
]
(
)
:
;
return
{
async
next
(
)
:
Promise
<
<
T
>>
{
if
(
.
)
{
return
{
:
true
,
:
undefined
}
;
}
const
=
await
raceCancellation
(
.
next
(
)
,
)
;
return
||
{
:
true
,
:
undefined
}
;
}
,
throw
:
.
?.
bind
(
)
,
return
:
.
?.
bind
(
)
,
[
.
]
(
)
{
return
this
;
}
}
;
}
type
ProducerConsumerValue<T>
=
{
:
true
;
:
T
;
}
|
{
:
false
;
:
;
}
;
class
ProducerConsumer<T>
{
private
readonly
:
<
T
>
[
]
=
[
]
;
private
readonly
:
<
T
>
[
]
=
[
]
;
private
:
<
T
>
|
undefined
;
public
get
hasFinalValue
(
)
:
boolean
{
return
!
!
this
.
;
}
produce
(
:
<
T
>
)
:
void
{
this
.
_ensureNoFinalValue
(
)
;
if
(
this
.
.
>
0
)
{
const
=
this
.
.
shift
(
)
!
;
this
.
_resolveOrRejectDeferred
(
,
)
;
}
else
{
this
.
.
push
(
)
;
}
}
produceFinal
(
:
<
T
>
)
:
void
{
this
.
_ensureNoFinalValue
(
)
;
this
.
=
;
for
(
const
of
this
.
)
{
this
.
_resolveOrRejectDeferred
(
,
)
;
}
this
.
.
=
0
;
}
private
_ensureNoFinalValue
(
)
:
void
{
if
(
this
.
)
{
throw
new
BugIndicatingError
(
'ProducerConsumer: cannot produce after final value has been set'
)
;
}
}
private
_resolveOrRejectDeferred
(
:
<
T
>
,
:
<
T
>
)
:
void
{
if
(
.
)
{
.
complete
(
.
)
;
}
else
{
.
error
(
.
)
;
}
}
consume
(
)
:
Promise
<
T
>
{
if
(
this
.
.
>
0
||
this
.
)
{
const
=
this
.
.
>
0
?
this
.
.
shift
(
)
!
:
this
.
!
;
if
(
.
)
{
return
Promise
.
resolve
(
.
)
;
}
else
{
return
Promise
.
reject
(
.
)
;
}
}
else
{
const
=
new
DeferredPromise<T>
(
)
;
this
.
.
push
(
)
;
return
.
;
}
}
}
/**
* Important difference to AsyncIterableObject:
* If it is iterated two times, the second iterator will not see the values emitted by the first iterator.
*/