|
| 1 | +/** |
| 2 | + * Copyright (c) Facebook, Inc. and its affiliates. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + */ |
| 7 | +import http from 'http'; |
| 8 | +import {launchDebugger, logger} from '@react-native-community/cli-tools'; |
| 9 | +import {exec} from 'child_process'; |
| 10 | + |
| 11 | +function launchDefaultDebugger( |
| 12 | + host: string | undefined, |
| 13 | + port: number, |
| 14 | + args = '', |
| 15 | +) { |
| 16 | + const hostname = host || 'localhost'; |
| 17 | + const debuggerURL = `http://${hostname}:${port}/debugger-ui${args}`; |
| 18 | + logger.info('Launching Dev Tools...'); |
| 19 | + launchDebugger(debuggerURL); |
| 20 | +} |
| 21 | + |
| 22 | +function escapePath(pathname: string) { |
| 23 | + // " Can escape paths with spaces in OS X, Windows, and *nix |
| 24 | + return `"${pathname}"`; |
| 25 | +} |
| 26 | + |
| 27 | +type LaunchDevToolsOptions = { |
| 28 | + host?: string; |
| 29 | + port: number; |
| 30 | + watchFolders: ReadonlyArray<string>; |
| 31 | +}; |
| 32 | + |
| 33 | +function launchDevTools( |
| 34 | + {host, port, watchFolders}: LaunchDevToolsOptions, |
| 35 | + isDebuggerConnected: () => boolean, |
| 36 | +) { |
| 37 | + // Explicit config always wins |
| 38 | + const customDebugger = process.env.REACT_DEBUGGER; |
| 39 | + if (customDebugger) { |
| 40 | + startCustomDebugger({watchFolders, customDebugger}); |
| 41 | + } else if (!isDebuggerConnected()) { |
| 42 | + // Debugger is not yet open; we need to open a session |
| 43 | + launchDefaultDebugger(host, port); |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +function startCustomDebugger({ |
| 48 | + watchFolders, |
| 49 | + customDebugger, |
| 50 | +}: { |
| 51 | + watchFolders: ReadonlyArray<string>; |
| 52 | + customDebugger: string; |
| 53 | +}) { |
| 54 | + const folders = watchFolders.map(escapePath).join(' '); |
| 55 | + const command = `${customDebugger} ${folders}`; |
| 56 | + logger.info('Starting custom debugger by executing:', command); |
| 57 | + exec(command, function (error) { |
| 58 | + if (error !== null) { |
| 59 | + logger.error('Error while starting custom debugger:', error.stack || ''); |
| 60 | + } |
| 61 | + }); |
| 62 | +} |
| 63 | + |
| 64 | +export default function getDevToolsMiddleware( |
| 65 | + options: LaunchDevToolsOptions, |
| 66 | + isDebuggerConnected: () => boolean, |
| 67 | +) { |
| 68 | + return function devToolsMiddleware( |
| 69 | + _req: http.IncomingMessage, |
| 70 | + res: http.ServerResponse, |
| 71 | + ) { |
| 72 | + launchDevTools(options, isDebuggerConnected); |
| 73 | + res.end('OK'); |
| 74 | + }; |
| 75 | +} |
0 commit comments