import { Lifecycle , Request , ResponseToolkit as HapiResponseToolkit } from '@hapi/hapi' ; import { Logger } from '../../logging' ; import { HapiResponseAdapter , KibanaRequest , KibanaResponse , lifecycleResponseFactory , LifecycleResponseFactory , KibanaRequestState , } from '../router' ; enum ResultType { next = 'next' , rewriteUrl = 'rewriteUrl' } interface Next { type : ResultType . next ; } interface RewriteUrl { type : ResultType . rewriteUrl ; url : string ; } type OnPreRoutingResult = Next | RewriteUrl ; const preRoutingResult = { next ( ) { return { type : ResultType . next } ; } , rewriteUrl ( url ) { return { type : ResultType . rewriteUrl , url } ; } , isNext ( result ) { return result && result . type === ResultType . next ; } , isRewriteUrl ( result ) { return result && result . type === ResultType . rewriteUrl ; } , } ; public export interface OnPreRoutingToolkit { /** To pass request to the next handler */ next : ( ) => OnPreRoutingResult ; /** Rewrite requested resources url before is was authenticated and routed to a handler */ rewriteUrl : ( url : string ) => OnPreRoutingResult ; } const toolkit = { next : preRoutingResult . next , rewriteUrl : preRoutingResult . rewriteUrl , } ; /**
 * See  OnPreRoutingToolkit .
 *  public export type OnPreRoutingHandler = ( request : KibanaRequest , response : LifecycleResponseFactory , toolkit : OnPreRoutingToolkit ) => OnPreRoutingResult | KibanaResponse | Promise < OnPreRoutingResult | KibanaResponse > ; public param fn export function adoptToHapiOnRequest ( fn , log ) { return async function interceptPreRoutingRequest ( request , responseToolkit ) : Promise < Lifecycle . ReturnValue > { const hapiResponseAdapter = new HapiResponseAdapter ( responseToolkit ) ; try { const result = await fn ( KibanaRequest . from ( request ) , lifecycleResponseFactory , toolkit ) ; if ( result instanceof KibanaResponse ) { return hapiResponseAdapter . handle ( result ) ; } if ( preRoutingResult . isNext ( result ) ) { return responseToolkit . continue ; } if ( preRoutingResult . isRewriteUrl ( result ) ) { const appState = request . app as KibanaRequestState ; appState . rewrittenUrl = appState . rewrittenUrl ?? request . url ; const { url } = result ; request . setUrl ( url ) ; request . raw . req . url = url ; return responseToolkit . continue ; } throw new Error ( `Unexpected result from OnPreRouting. Expected OnPreRoutingResult or KibanaResponse, but given: ${ result }.` ) ; } catch ( error ) { log . error ( error ) ; return hapiResponseAdapter . toInternalError ( ) ; } } ; }