import { browser , Runtime } from "webextension-polyfill-ts" ; /** Manage port connections between the panel and page */ export class PortController < T > { ports : { [ key ] : Array < Runtime . Port > ; } ; constructor ( ) { this . ports = { } ; } connect ( tabId , port ) { if ( ! this . ports [ tabId ] ) { this . ports [ tabId ] = [ ] ; } this . ports [ tabId ] . push ( port ) ; } disconnect ( port , message ? ) { for ( const t of Object . keys ( this . ports ) ) { const tab = Number ( t ) ; this . ports [ tab ] = this . ports [ tab ] . filter ( ( p ) => p !== port ) ; if ( this . ports [ tab ] . length === 0 ) { if ( message ) { this . toContent ( tab , message ) ; } delete this . ports [ tab ] ; } } } getPorts ( tabId ) { return this . ports [ tabId ] ; } toContent ( tabId , message ) { if ( message && tabId ) { browser . tabs . sendMessage ( tabId , message ) ; } } toPanel ( tabId , message ) { if ( tabId in this . ports ) { const tab = this . ports [ tabId ] ; for ( let i = 0 ; i < tab . length ; i ++ ) { tab [ i ] . postMessage ( message ) ; } } } } export default PortController ;