websocket-transport.js (1832B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 "use strict"; 6 7 const EventEmitter = require("resource://devtools/shared/event-emitter.js"); 8 9 class WebSocketDebuggerTransport extends EventEmitter { 10 constructor(socket) { 11 super(); 12 13 this.active = false; 14 this.hooks = null; 15 this.socket = socket; 16 } 17 ready() { 18 if (this.active) { 19 return; 20 } 21 22 this.socket.addEventListener("message", this); 23 this.socket.addEventListener("close", this); 24 25 this.active = true; 26 } 27 28 send(object) { 29 this.emit("send", object); 30 if (this.socket) { 31 this.socket.send(JSON.stringify(object)); 32 } 33 } 34 35 startBulkSend() { 36 throw new Error("Bulk send is not supported by WebSocket transport"); 37 } 38 39 close() { 40 if (!this.socket) { 41 return; 42 } 43 this.emit("close"); 44 this.active = false; 45 46 this.socket.removeEventListener("message", this); 47 this.socket.removeEventListener("close", this); 48 this.socket.close(); 49 this.socket = null; 50 51 if (this.hooks) { 52 if (this.hooks.onTransportClosed) { 53 this.hooks.onTransportClosed(); 54 } 55 this.hooks = null; 56 } 57 } 58 59 handleEvent(event) { 60 switch (event.type) { 61 case "message": 62 this.onMessage(event); 63 break; 64 case "close": 65 this.close(); 66 break; 67 } 68 } 69 70 onMessage({ data }) { 71 if (typeof data !== "string") { 72 throw new Error( 73 "Binary messages are not supported by WebSocket transport" 74 ); 75 } 76 77 const object = JSON.parse(data); 78 this.emit("packet", object); 79 if (this.hooks) { 80 this.hooks.onPacket(object); 81 } 82 } 83 } 84 85 module.exports = WebSocketDebuggerTransport;