import type { Page } from 'puppeteer' ; import { stderr as stderrSupportsColor } from 'supports-color' ; import consoleWithStyle from 'console-with-style' ; import { wrapRouter } from './router' ; const checkSsrErrors = ( text ) => { if ( text . indexOf ( 'Server: "%s" Client: "%s"%s' ) !== - 1 ) { throw new Error ( `SSR breaking error: ${ text }` ) ; } } ; const format = consoleWithStyle ( ( stderrSupportsColor && stderrSupportsColor . level ) || 0 ) ; declare global { var nativeConsole ; } const { nativeConsole } = global ; export const wrapPuppeteerPage = ( page ) => { if ( page . url ( ) && page . url ( ) !== 'about:blank' ) { throw new Error ( `You should wrap blank page before navigation, but page already has url "${ page . url ( ) }"` ) ; } page . on ( 'requestfailed' , ( request ) => nativeConsole . error ( '[PAGE REQUEST FAILED]' , { error : request . failure ( ) , url : request . url ( ) , headers : request . headers ( ) , } ) ) ; page . on ( 'error' , ( error ) => { nativeConsole . error ( `[PAGE CRASHED]` , error . message ) ; } ) ; page . on ( 'pageerror' , ( error ) => { nativeConsole . error ( `[PAGE ERROR]` , error . message ) ; } ) ; page . on ( 'console' , async ( consoleObj ) => { const args = consoleObj . args ( ) ; const text = consoleObj . text ( ) ; const messages = [ ] ; checkSsrErrors ( text ) ; for ( let i = 0 ; i < args . length ; i ++ ) { const arg = args [ i ] ; const json = await arg . jsonValue ( ) . catch ( ( ) => null ) ; messages . push ( json ) ; } const logLevel = consoleObj . type ( ) === 'error' ? 'error' : 'log' ; const consoleArgs = messages . length ? messages : [ text ] ; nativeConsole [ logLevel ] ( `[PAGE ${ consoleObj . type ( ) . toUpperCase ( ) }]` , format ( ... consoleArgs ) ) ; } ) ; return { page , reset : ( url = 'about:blank' ) => { return page . goto ( url ) ; } , router : wrapRouter ( page ) , close : ( ) => { return page . close ( ) ; } , } ; } ;