import { EventEmitter2 } from 'eventemitter2' ; import type { EventAndListener } from 'eventemitter2' ; import type { MockEventMap , RegisterEvent , RunEvent , NetWorkRegister , MockRoute , } from './types' ; export interface MockEventEmitter { emit < T extends keyof MockEventMap > ( event , value ) : boolean ; on < T extends keyof MockEventMap > ( event , listener ) : void ; once < T extends keyof MockEventMap > ( event , listener ) : void ; onAny < T extends keyof MockEventMap > ( listener ) : void ; off < T extends keyof MockEventMap > ( event , listener ) : this ; offAny ( listener ) : this ; } export const eventEmitter = new EventEmitter2 ( ) ; export const log = ( ) => { const logListener = ( event , ... payload ) => console . log ( `%cReceive%c %c${ event . toString ( ) }` , 'background: rgba(0, 255, 255, 0.6); color: black; padding: 0px 6px; border-radius: 4px;' , '' , 'text-decoration: underline' , payload ) ; eventEmitter . onAny ( logListener ) ; return ( ) => eventEmitter . offAny ( logListener ) ; } ; export const registerMock = ( rule ) => { eventEmitter . emit ( rule . type , rule ) ; } ; const networkRules = [ ] ; export const matchNetworkRule = ( targetUrl , opts ) : NetWorkRegister | undefined => networkRules . find ( ( { url , method : ruleMethod } ) => { if ( ruleMethod && opts . method !== ruleMethod ) { return ; } if ( typeof url === 'function' ) { return url ( targetUrl ) ; } if ( typeof url === 'string' ) { return targetUrl . includes ( url ) ; } return url . test ( targetUrl ) ; } ) ; export const mockRoute = ( route ) => { const innerRoute = { scenarios : [ ] , ... route , type : 'Register/networkRoute' , timeStamp : new Date ( ) . getTime ( ) , } ; if ( route . method ) { innerRoute . method = route . method . toUpperCase ( ) ; } networkRules . unshift ( innerRoute ) ; registerMock ( innerRoute ) ; } ; export const mockRoutes = ( routes ) => routes . forEach ( ( route ) => mockRoute ( route ) ) ; export const clearMocks = ( ) => { networkRules . length = 0 ; } ; export const onRun = ( event ) => { eventEmitter . emit ( event . type , event ) ; } ;