import debug from 'debug' ; import { ExtractedResponse } from './response' ; import type { Request , Response , DriverRequest , Interceptor } from '../types' ; import type { Express } from 'express' ; const logger = debug ( 'teremock:puppeteer:request' ) ; type Ret = DriverRequest & { onRespondPromise : Promise < RespondResolve > ; } ; type GetRealResponse = ( r : Request ) => Promise < ExtractedResponse > ; type RealResponseResolve = { realResponse : ExtractedResponse ; interceptor : Interceptor ; } ; type MockedResponseResolve = { response : Response ; interceptor : Interceptor ; } ; type RespondResolve = RealResponseResolve | MockedResponseResolve ; let id = 0 ; export async function extractExpressRequest ( req , res , realUrl , getRealResponse ) { const request = { url : realUrl , method : req . method , headers : req . headers , body : req . body , resourceType : 'xhr' , id : id ++ , timestamp : Date . now ( ) , } ; let resolve ; let reject ; const onRespondPromise = new Promise < RespondResolve > ( ( r , rej ) => { resolve = r ; reject = rej ; } ) ; const abort = async ( ) => { res . status ( 503 ) . end ( ) ; reject ( new Error ( `abort()` ) ) ; } ; const next = async ( interceptor ) : Promise < void > => { const realResponse = await getRealResponse ( request ) ; const realResp = { realResponse , interceptor } ; resolve ( realResp ) ; } ; const respond = async ( resp , interceptor ) => { const mockedResp = { response : resp , interceptor } ; resolve ( mockedResp ) ; } ; logger ( `got the request, sending it to teremock core` ) ; return { request , abort , respond , next , onRespondPromise } ; }