handleDebuggerConnection()

in packages/metro-inspector-proxy/src/Device.js [153:212]


  handleDebuggerConnection(socket: typeof WS, pageId: string) {
    // Disconnect current debugger if we already have debugger connected.
    if (this._debuggerConnection) {
      this._debuggerConnection.socket.close();
      this._debuggerConnection = null;
    }

    const debuggerInfo = {
      socket,
      prependedFilePrefix: false,
      pageId,
    };
    this._debuggerConnection = debuggerInfo;

    debug(`Got new debugger connection for page ${pageId} of ${this._name}`);

    this._sendMessageToDevice({
      event: 'connect',
      payload: {
        pageId: this._mapToDevicePageId(pageId),
      },
    });

    socket.on('message', (message: string) => {
      debug('(Debugger) -> (Proxy)    (Device): ' + message);
      const debuggerRequest = JSON.parse(message);
      const interceptedResponse = this._interceptMessageFromDebugger(
        debuggerRequest,
        debuggerInfo,
      );

      if (interceptedResponse) {
        socket.send(JSON.stringify(interceptedResponse));
      } else {
        this._sendMessageToDevice({
          event: 'wrappedEvent',
          payload: {
            pageId: this._mapToDevicePageId(pageId),
            wrappedEvent: JSON.stringify(debuggerRequest),
          },
        });
      }
    });
    socket.on('close', () => {
      debug(`Debugger for page ${pageId} and ${this._name} disconnected.`);
      this._sendMessageToDevice({
        event: 'disconnect',
        payload: {
          pageId: this._mapToDevicePageId(pageId),
        },
      });
      this._debuggerConnection = null;
    });

    const sendFunc = socket.send;
    socket.send = function (message: string) {
      debug('(Debugger) <- (Proxy)    (Device): ' + message);
      return sendFunc.call(socket, message);
    };
  }