import * as util from '../lib/util' ; import Command from '../Command' ; import { CancellablePromise } from '@theintern/common' ; param poller param args param timeout param pollInterval returns export default function pollUntil < T > ( poller , timeout ? , pollInterval ? ) ; export default function pollUntil < T > ( poller , args ? , timeout ? , pollInterval ? ) ; export default function pollUntil < T > ( poller , args ? , timeout ? , pollInterval ? ) ; export default function pollUntil < T , U > ( poller , args ? , timeout ? , pollInterval ? ) ; export default function pollUntil < T , U , V > ( poller , args ? , timeout ? , pollInterval ? ) ; export default function pollUntil < T , U , V , W > ( poller , args ? , timeout ? , pollInterval ? ) ; export default function pollUntil < T , U , V , W , X > ( poller , args ? , timeout ? , pollInterval ? ) ; export default function pollUntil < T , U , V , W , X , Y > ( poller , args ? , timeout ? , pollInterval ? ) ; export default function pollUntil < T , U , V , W , X , Y > ( poller , argsOrTimeout ? , timeout ? , pollInterval ? ) { let args ; if ( typeof argsOrTimeout === 'number' ) { pollInterval = timeout ; timeout = argsOrTimeout ; } else { args = argsOrTimeout ; } args = args || [ ] ; pollInterval = pollInterval || 67 ; return function ( this ) { const session = this . session ; let originalTimeout ; return session . getExecuteAsyncTimeout ( ) . then ( function ( currentTimeout ) { let resultOrError ; function storeResult ( result ) { resultOrError = result ; } function finish ( ) { if ( resultOrError instanceof Error ) { throw resultOrError ; } if ( resultOrError == null ) { const error = new Error ( 'Polling timed out with no result' ) ; error . name = 'ScriptTimeout' ; throw error ; } return resultOrError ; } function cleanup ( ) { if ( ! isNaN ( originalTimeout ) ) { return session . setExecuteAsyncTimeout ( originalTimeout ) . then ( finish ) ; } return finish ( ) ; } if ( ! isNaN ( < number > timeout ) ) { originalTimeout = currentTimeout ; } else { timeout = currentTimeout ; } return session . setExecuteAsyncTimeout ( timeout ! ) . then ( function ( ) { return session . executeAsync ( function ( poller , args , timeout , pollInterval , done ) : void { poller = < Function > new Function ( < string > poller ) ; const endTime = Number ( new Date ( ) ) + timeout ; ( function poll ( this ) { const result = poller . apply ( this , args ) ; if ( result != null ) { done ( result ) ; } else if ( Number ( new Date ( ) ) < endTime ) { setTimeout ( poll , pollInterval ) ; } else { done ( null ) ; } } ) ( ) ; } , [ util . toExecuteString ( poller ) , args , timeout , pollInterval ] ) ; } ) . then ( storeResult , storeResult ) . then ( cleanup , cleanup ) ; } ) ; } ; }