HMRClient.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. * @format
  8. * @flow
  9. */
  10. 'use strict';
  11. const DevSettings = require('./DevSettings');
  12. const invariant = require('invariant');
  13. const MetroHMRClient = require('metro/src/lib/bundle-modules/HMRClient');
  14. const Platform = require('./Platform');
  15. const prettyFormat = require('pretty-format');
  16. import NativeRedBox from '../NativeModules/specs/NativeRedBox';
  17. import * as LogBoxData from '../LogBox/Data/LogBoxData';
  18. import type {ExtendedError} from '../Core/Devtools/parseErrorStack';
  19. const pendingEntryPoints = [];
  20. let hmrClient = null;
  21. let hmrUnavailableReason: string | null = null;
  22. let currentCompileErrorMessage: string | null = null;
  23. let didConnect: boolean = false;
  24. let pendingLogs: Array<[LogLevel, Array<mixed>]> = [];
  25. type LogLevel =
  26. | 'trace'
  27. | 'info'
  28. | 'warn'
  29. | 'error'
  30. | 'log'
  31. | 'group'
  32. | 'groupCollapsed'
  33. | 'groupEnd'
  34. | 'debug';
  35. export type HMRClientNativeInterface = {|
  36. enable(): void,
  37. disable(): void,
  38. registerBundle(requestUrl: string): void,
  39. log(level: LogLevel, data: Array<mixed>): void,
  40. setup(
  41. platform: string,
  42. bundleEntry: string,
  43. host: string,
  44. port: number | string,
  45. isEnabled: boolean,
  46. ): void,
  47. |};
  48. /**
  49. * HMR Client that receives from the server HMR updates and propagates them
  50. * runtime to reflects those changes.
  51. */
  52. const HMRClient: HMRClientNativeInterface = {
  53. enable() {
  54. if (hmrUnavailableReason !== null) {
  55. // If HMR became unavailable while you weren't using it,
  56. // explain why when you try to turn it on.
  57. // This is an error (and not a warning) because it is shown
  58. // in response to a direct user action.
  59. throw new Error(hmrUnavailableReason);
  60. }
  61. invariant(hmrClient, 'Expected HMRClient.setup() call at startup.');
  62. const LoadingView = require('./LoadingView');
  63. // We use this for internal logging only.
  64. // It doesn't affect the logic.
  65. hmrClient.send(JSON.stringify({type: 'log-opt-in'}));
  66. // When toggling Fast Refresh on, we might already have some stashed updates.
  67. // Since they'll get applied now, we'll show a banner.
  68. const hasUpdates = hmrClient.hasPendingUpdates();
  69. if (hasUpdates) {
  70. LoadingView.showMessage('Refreshing...', 'refresh');
  71. }
  72. try {
  73. hmrClient.enable();
  74. } finally {
  75. if (hasUpdates) {
  76. LoadingView.hide();
  77. }
  78. }
  79. // There could be a compile error while Fast Refresh was off,
  80. // but we ignored it at the time. Show it now.
  81. showCompileError();
  82. },
  83. disable() {
  84. invariant(hmrClient, 'Expected HMRClient.setup() call at startup.');
  85. hmrClient.disable();
  86. },
  87. registerBundle(requestUrl: string) {
  88. invariant(hmrClient, 'Expected HMRClient.setup() call at startup.');
  89. pendingEntryPoints.push(requestUrl);
  90. registerBundleEntryPoints(hmrClient);
  91. },
  92. log(level: LogLevel, data: Array<mixed>) {
  93. if (!hmrClient) {
  94. // Catch a reasonable number of early logs
  95. // in case hmrClient gets initialized later.
  96. pendingLogs.push([level, data]);
  97. if (pendingLogs.length > 100) {
  98. pendingLogs.shift();
  99. }
  100. return;
  101. }
  102. try {
  103. hmrClient.send(
  104. JSON.stringify({
  105. type: 'log',
  106. level,
  107. data: data.map(item =>
  108. typeof item === 'string'
  109. ? item
  110. : prettyFormat(item, {
  111. escapeString: true,
  112. highlight: true,
  113. maxDepth: 3,
  114. min: true,
  115. plugins: [prettyFormat.plugins.ReactElement],
  116. }),
  117. ),
  118. }),
  119. );
  120. } catch (error) {
  121. // If sending logs causes any failures we want to silently ignore them
  122. // to ensure we do not cause infinite-logging loops.
  123. }
  124. },
  125. // Called once by the bridge on startup, even if Fast Refresh is off.
  126. // It creates the HMR client but doesn't actually set up the socket yet.
  127. setup(
  128. platform: string,
  129. bundleEntry: string,
  130. host: string,
  131. port: number | string,
  132. isEnabled: boolean,
  133. ) {
  134. invariant(platform, 'Missing required parameter `platform`');
  135. invariant(bundleEntry, 'Missing required parameter `bundleEntry`');
  136. invariant(host, 'Missing required parameter `host`');
  137. invariant(!hmrClient, 'Cannot initialize hmrClient twice');
  138. // Moving to top gives errors due to NativeModules not being initialized
  139. const LoadingView = require('./LoadingView');
  140. const wsHost = port !== null && port !== '' ? `${host}:${port}` : host;
  141. const client = new MetroHMRClient(`ws://${wsHost}/hot`);
  142. hmrClient = client;
  143. pendingEntryPoints.push(
  144. `ws://${wsHost}/hot?bundleEntry=${bundleEntry}&platform=${platform}`,
  145. );
  146. client.on('connection-error', e => {
  147. let error = `Cannot connect to the Metro server.
  148. Try the following to fix the issue:
  149. - Ensure that the Metro server is running and available on the same network`;
  150. if (Platform.OS === 'ios') {
  151. error += `
  152. - Ensure that the Metro server URL is correctly set in AppDelegate`;
  153. } else {
  154. error += `
  155. - Ensure that your device/emulator is connected to your machine and has USB debugging enabled - run 'adb devices' to see a list of connected devices
  156. - If you're on a physical device connected to the same machine, run 'adb reverse tcp:8081 tcp:8081' to forward requests from your device
  157. - If your device is on the same Wi-Fi network, set 'Debug server host & port for device' in 'Dev settings' to your machine's IP address and the port of the local dev server - e.g. 10.0.1.1:8081`;
  158. }
  159. error += `
  160. URL: ${host}:${port}
  161. Error: ${e.message}`;
  162. setHMRUnavailableReason(error);
  163. });
  164. client.on('update-start', ({isInitialUpdate}) => {
  165. currentCompileErrorMessage = null;
  166. didConnect = true;
  167. if (client.isEnabled() && !isInitialUpdate) {
  168. LoadingView.showMessage('Refreshing...', 'refresh');
  169. }
  170. });
  171. client.on('update', ({isInitialUpdate}) => {
  172. if (client.isEnabled() && !isInitialUpdate) {
  173. dismissRedbox();
  174. LogBoxData.clear();
  175. }
  176. });
  177. client.on('update-done', () => {
  178. LoadingView.hide();
  179. });
  180. client.on('error', data => {
  181. LoadingView.hide();
  182. if (data.type === 'GraphNotFoundError') {
  183. client.close();
  184. setHMRUnavailableReason(
  185. 'The Metro server has restarted since the last edit. Reload to reconnect.',
  186. );
  187. } else if (data.type === 'RevisionNotFoundError') {
  188. client.close();
  189. setHMRUnavailableReason(
  190. 'The Metro server and the client are out of sync. Reload to reconnect.',
  191. );
  192. } else {
  193. currentCompileErrorMessage = `${data.type} ${data.message}`;
  194. if (client.isEnabled()) {
  195. showCompileError();
  196. }
  197. }
  198. });
  199. client.on('close', data => {
  200. LoadingView.hide();
  201. setHMRUnavailableReason('Disconnected from the Metro server.');
  202. });
  203. if (isEnabled) {
  204. HMRClient.enable();
  205. } else {
  206. HMRClient.disable();
  207. }
  208. registerBundleEntryPoints(hmrClient);
  209. flushEarlyLogs(hmrClient);
  210. },
  211. };
  212. function setHMRUnavailableReason(reason) {
  213. invariant(hmrClient, 'Expected HMRClient.setup() call at startup.');
  214. if (hmrUnavailableReason !== null) {
  215. // Don't show more than one warning.
  216. return;
  217. }
  218. hmrUnavailableReason = reason;
  219. // We only want to show a warning if Fast Refresh is on *and* if we ever
  220. // previously managed to connect successfully. We don't want to show
  221. // the warning to native engineers who use cached bundles without Metro.
  222. if (hmrClient.isEnabled() && didConnect) {
  223. console.warn(reason);
  224. // (Not using the `warning` module to prevent a Buck cycle.)
  225. }
  226. }
  227. function registerBundleEntryPoints(client) {
  228. if (hmrUnavailableReason) {
  229. DevSettings.reload('Bundle Splitting – Metro disconnected');
  230. return;
  231. }
  232. if (pendingEntryPoints.length > 0) {
  233. client.send(
  234. JSON.stringify({
  235. type: 'register-entrypoints',
  236. entryPoints: pendingEntryPoints,
  237. }),
  238. );
  239. pendingEntryPoints.length = 0;
  240. }
  241. }
  242. function flushEarlyLogs(client) {
  243. try {
  244. pendingLogs.forEach(([level: LogLevel, data: Array<mixed>]) => {
  245. HMRClient.log(level, data);
  246. });
  247. } finally {
  248. pendingLogs.length = 0;
  249. }
  250. }
  251. function dismissRedbox() {
  252. if (
  253. Platform.OS === 'ios' &&
  254. NativeRedBox != null &&
  255. NativeRedBox.dismiss != null
  256. ) {
  257. NativeRedBox.dismiss();
  258. } else {
  259. const NativeExceptionsManager = require('../Core/NativeExceptionsManager')
  260. .default;
  261. NativeExceptionsManager &&
  262. NativeExceptionsManager.dismissRedbox &&
  263. NativeExceptionsManager.dismissRedbox();
  264. }
  265. }
  266. function showCompileError() {
  267. if (currentCompileErrorMessage === null) {
  268. return;
  269. }
  270. // Even if there is already a redbox, syntax errors are more important.
  271. // Otherwise you risk seeing a stale runtime error while a syntax error is more recent.
  272. dismissRedbox();
  273. const message = currentCompileErrorMessage;
  274. currentCompileErrorMessage = null;
  275. const error: ExtendedError = new Error(message);
  276. // Symbolicating compile errors is wasted effort
  277. // because the stack trace is meaningless:
  278. error.preventSymbolication = true;
  279. throw error;
  280. }
  281. module.exports = HMRClient;