import { ACTIONS , ActionParamsMap } from './constants/actions' ; import { EVENTS , EventParamsMap } from './constants/events' ; const LIB_ID = 'griffith' ; type MessagePayload = { name : ACTIONS & EVENTS ; data ? : unknown ; } ; type Message = { from : string ; id : string | number ; payload : MessagePayload ; } ; type Unsubscribe = { unsubscribe : ( ) => void ; } ; example param id param targetOrigin param shouldValidateId function createMessageHelper ( id ? , targetOrigin = '*' , shouldValidateId = false ) { const disposers = new Set < Unsubscribe > ( ) ; /**
     * Subscribe event from player
     */ function subscribeMessage < E extends keyof EventParamsMap > ( name , handler ) ; deprecated function subscribeMessage ( handler ) ; function subscribeMessage ( arg1 , arg2 ? ) { const isLegacy = typeof arg1 === 'function' ; const handler = isLegacy ? arg1 : arg2 ; const eventName = isLegacy ? undefined : arg1 ; function realHandler ( event ) { const origin = event . origin ; const originIsValidated = targetOrigin === '*' || targetOrigin === origin ; const { from , id : incomingId , payload } = event . data || { } ; const idIsValidated = ! shouldValidateId || id === incomingId ; if ( originIsValidated && from === LIB_ID && idIsValidated && payload ) { const { name , data } = payload ; if ( ! name || typeof handler !== 'function' ) { return ; } if ( isLegacy ) { handler ( name , data as any , event . source ) ; } else if ( eventName === name ) { handler ( data as any , event . source ) ; } } } window . addEventListener ( 'message' , realHandler ) ; const disposer = { unsubscribe : ( ) => { window . removeEventListener ( 'message' , realHandler ) ; disposers . delete ( disposer ) ; } , } ; disposers . add ( disposer ) ; return disposer ; } /**
     * Dispose all registered event listeners.
     */ const dispose = ( ) => { disposers . forEach ( ( x ) => x . unsubscribe ( ) ) ; } ; /**
     * Dispatch action to player
     */ const dispatchMessage = < T extends keyof ActionParamsMap > ( target , name , ... data ) => { target ?. postMessage ?. ( { from : LIB_ID , id , payload : { name , data : data [ 0 ] } } , targetOrigin || '*' ) ; } ; return { subscribeMessage , dispatchMessage , dispose , } ; } export default createMessageHelper ;