microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/debugger/appWorker.ts
394lines · modeblame
9f036952Nisheet Jain10 years ago | 1 | // Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | // Licensed under the MIT license. See LICENSE file in the project root for details. | |
| 3 | | |
4677921cdigeff10 years ago | 4 | import * as Q from "q"; |
cc70057dVladimir Kotikov9 years ago | 5 | import * as path from "path"; |
ea8a5f88digeff10 years ago | 6 | import * as WebSocket from "ws"; |
e45838cbVladimir Kotikov9 years ago | 7 | import { EventEmitter } from "events"; |
0a68f8dbArtem Egorov8 years ago | 8 | import { ensurePackagerRunning } from "../common/packagerStatus"; |
a4a7e387Meena Kunnathur Balakrishnan10 years ago | 9 | import {ErrorHelper} from "../common/error/errorHelper"; |
0a68f8dbArtem Egorov8 years ago | 10 | import { logger } from "vscode-chrome-debug-core"; |
7cc67271digeff10 years ago | 11 | import {ExecutionsLimiter} from "../common/executionsLimiter"; |
cc70057dVladimir Kotikov9 years ago | 12 | import { FileSystem as NodeFileSystem} from "../common/node/fileSystem"; |
b05b5086Vladimir Kotikov9 years ago | 13 | import { ForkedAppWorker } from "./forkedAppWorker"; |
cc70057dVladimir Kotikov9 years ago | 14 | import { ScriptImporter } from "./scriptImporter"; |
bb869343Serge Svekolnikov8 years ago | 15 | import { ReactNativeProjectHelper } from "../common/reactNativeProjectHelper"; |
d124bf0eYuri Skorokhodov7 years ago | 16 | import * as nls from "vscode-nls"; |
| 17 | import { InternalErrorCode } from "../common/error/internalErrorCode"; | |
| 18 | const localize = nls.loadMessageBundle(); | |
4677921cdigeff10 years ago | 19 | |
e45838cbVladimir Kotikov9 years ago | 20 | export interface RNAppMessage { |
ea8a5f88digeff10 years ago | 21 | method: string; |
e45838cbVladimir Kotikov9 years ago | 22 | url?: string; |
ea8a5f88digeff10 years ago | 23 | // These objects have also other properties but that we don't currently use |
| 24 | } | |
5d4d4de0digeff10 years ago | 25 | |
e45838cbVladimir Kotikov9 years ago | 26 | export interface IDebuggeeWorker { |
| 27 | start(): Q.Promise<any>; | |
| 28 | stop(): void; | |
| 29 | postMessage(message: RNAppMessage): void; | |
| 30 | } | |
| 31 | | |
1758f9a6Yuri Skorokhodov7 years ago | 32 | function printDebuggingError(error: Error, reason: any) { |
| 33 | const nestedError = ErrorHelper.getNestedError(error, InternalErrorCode.DebuggingWontWorkReloadJSAndReconnect, reason); | |
0a68f8dbArtem Egorov8 years ago | 34 | |
| 35 | logger.error(nestedError.message); | |
039239d1Vladimir Kotikov9 years ago | 36 | } |
| 37 | | |
| 38 | /** This class will create a SandboxedAppWorker that will run the RN App logic, and then create a socket | |
| 39 | * and send the RN App messages to the SandboxedAppWorker. The only RN App message that this class handles | |
| 40 | * is the prepareJSRuntime, which we reply to the RN App that the sandbox was created successfully. | |
| 41 | * When the socket closes, we'll create a new SandboxedAppWorker and a new socket pair and discard the old ones. | |
| 42 | */ | |
| 43 | | |
| 44 | export class MultipleLifetimesAppWorker extends EventEmitter { | |
| 45 | public static WORKER_BOOTSTRAP = ` | |
cc70057dVladimir Kotikov9 years ago | 46 | // Initialize some variables before react-native code would access them |
d64a6928Vladimir Kotikov9 years ago | 47 | var onmessage=null, self=global; |
cc70057dVladimir Kotikov9 years ago | 48 | // Cache Node's original require as __debug__.require |
d64a6928Vladimir Kotikov9 years ago | 49 | global.__debug__={require: require}; |
0864d702Ruslan Bikkinin7 years ago | 50 | // Prevent leaking process.versions from debugger process to |
| 51 | // worker because pure React Native doesn't do that and some packages as js-md5 rely on this behavior | |
| 52 | Object.defineProperty(process, "versions", { | |
| 53 | value: undefined | |
| 54 | }); | |
7daed3fcArtem Egorov8 years ago | 55 | |
4cf8fdf4Yuri Skorokhodov6 years ago | 56 | // TODO: Replace by url.fileURLToPath method when Node 10 LTS become deprecated |
| 57 | function fileUrlToPath(url) { | |
| 58 | if (process.platform === 'win32') { | |
| 59 | return url.toString().replace('file:///', ''); | |
| 60 | } else { | |
| 61 | return url.toString().replace('file://', ''); | |
| 62 | } | |
| 63 | } | |
| 64 | | |
2ecfbd20Yuri Skorokhodov7 years ago | 65 | function getNativeModules() { |
| 66 | var NativeModules; | |
| 67 | try { | |
| 68 | // This approach is for old RN versions | |
| 69 | NativeModules = global.require('NativeModules'); | |
| 70 | } catch (err) { | |
| 71 | // ignore error and try another way for more recent RN versions | |
| 72 | try { | |
| 73 | var nativeModuleId; | |
| 74 | var modules = global.__r.getModules(); | |
| 75 | var ids = Object.keys(modules); | |
| 76 | for (var i = 0; i < ids.length; i++) { | |
| 77 | if (modules[ids[i]].verboseName) { | |
| 78 | var packagePath = new String(modules[ids[i]].verboseName); | |
4cf8fdf4Yuri Skorokhodov6 years ago | 79 | if (packagePath.indexOf('react-native/Libraries/BatchedBridge/NativeModules.js') > 0) { |
2ecfbd20Yuri Skorokhodov7 years ago | 80 | nativeModuleId = parseInt(ids[i], 10); |
| 81 | break; | |
| 82 | } | |
| 83 | } | |
| 84 | } | |
| 85 | if (nativeModuleId) { | |
| 86 | NativeModules = global.__r(nativeModuleId); | |
| 87 | } | |
| 88 | } | |
| 89 | catch (err) { | |
| 90 | // suppress errors | |
| 91 | } | |
| 92 | } | |
| 93 | return NativeModules; | |
| 94 | } | |
| 95 | | |
| 96 | // Originally, this was made for iOS only | |
7daed3fcArtem Egorov8 years ago | 97 | var vscodeHandlers = { |
| 98 | 'vscode_reloadApp': function () { | |
2ecfbd20Yuri Skorokhodov7 years ago | 99 | var NativeModules = getNativeModules(); |
| 100 | if (NativeModules) { | |
| 101 | NativeModules.DevMenu.reload(); | |
7daed3fcArtem Egorov8 years ago | 102 | } |
| 103 | }, | |
| 104 | 'vscode_showDevMenu': function () { | |
2ecfbd20Yuri Skorokhodov7 years ago | 105 | var NativeModules = getNativeModules(); |
| 106 | if (NativeModules) { | |
| 107 | NativeModules.DevMenu.show(); | |
7daed3fcArtem Egorov8 years ago | 108 | } |
| 109 | } | |
| 110 | }; | |
| 111 | | |
| 112 | process.on("message", function (message) { | |
| 113 | if (message.data && vscodeHandlers[message.data.method]) { | |
| 114 | vscodeHandlers[message.data.method](); | |
| 115 | } else if(onmessage) { | |
| 116 | onmessage(message); | |
| 117 | } | |
cc70057dVladimir Kotikov9 years ago | 118 | }); |
7daed3fcArtem Egorov8 years ago | 119 | |
cc70057dVladimir Kotikov9 years ago | 120 | var postMessage = function(message){ |
| 121 | process.send(message); | |
| 122 | }; | |
bb869343Serge Svekolnikov8 years ago | 123 | |
| 124 | if (!self.postMessage) { | |
| 125 | self.postMessage = postMessage; | |
| 126 | } | |
| 127 | | |
cc70057dVladimir Kotikov9 years ago | 128 | var importScripts = (function(){ |
| 129 | var fs=require('fs'), vm=require('vm'); | |
| 130 | return function(scriptUrl){ | |
4cf8fdf4Yuri Skorokhodov6 years ago | 131 | scriptUrl = fileUrlToPath(scriptUrl); |
| 132 | var scriptCode = fs.readFileSync(scriptUrl, 'utf8'); | |
e67ace8aYuri Skorokhodov6 years ago | 133 | // Add a 'debugger;' statement to stop code execution |
| 134 | // to wait for the sourcemaps to be processed by the debug adapter | |
| 135 | vm.runInThisContext('debugger;' + scriptCode, {filename: scriptUrl}); | |
cc70057dVladimir Kotikov9 years ago | 136 | }; |
4cf8fdf4Yuri Skorokhodov6 years ago | 137 | })(); |
| 138 | `; | |
cc70057dVladimir Kotikov9 years ago | 139 | |
cf6dd6b9Yuri Skorokhodov7 years ago | 140 | public static CONSOLE_TRACE_PATCH = `// Worker is ran as nodejs process, so console.trace() writes to stderr and it leads to error in native app |
| 141 | // To avoid this console.trace() is overridden to print stacktrace via console.log() | |
| 142 | // Please, see Node JS implementation: https://github.com/nodejs/node/blob/master/lib/internal/console/constructor.js | |
| 143 | console.trace = (function() { | |
| 144 | return function() { | |
| 145 | try { | |
| 146 | var err = { | |
| 147 | name: 'Trace', | |
| 148 | message: require('util').format.apply(null, arguments) | |
| 149 | }; | |
| 150 | // Node uses 10, but usually it's not enough for RN app trace | |
| 151 | Error.stackTraceLimit = 30; | |
| 152 | Error.captureStackTrace(err, console.trace); | |
| 153 | console.log(err.stack); | |
| 154 | } catch (e) { | |
| 155 | console.error(e); | |
| 156 | } | |
| 157 | }; | |
4cf8fdf4Yuri Skorokhodov6 years ago | 158 | })(); |
| 159 | `; | |
cf6dd6b9Yuri Skorokhodov7 years ago | 160 | |
13a99427Yuri Skorokhodov6 years ago | 161 | public static PROCESS_TO_STRING_PATCH = `// As worker is ran in node, it breaks broadcast-channels package approach of identifying if it’s ran in node: |
| 162 | // https://github.com/pubkey/broadcast-channel/blob/master/src/util.js#L64 | |
| 163 | // To avoid it if process.toString() is called if will return empty string instead of [object process]. | |
| 164 | var nativeObjectToString = Object.prototype.toString; | |
| 165 | Object.prototype.toString = function() { | |
| 166 | if (this === process) { | |
| 167 | return ''; | |
| 168 | } else { | |
| 169 | return nativeObjectToString.call(this); | |
| 170 | } | |
f4e3ce39Yuri Skorokhodov6 years ago | 171 | }; |
13a99427Yuri Skorokhodov6 years ago | 172 | `; |
| 173 | | |
039239d1Vladimir Kotikov9 years ago | 174 | public static WORKER_DONE = `// Notify debugger that we're done with loading |
cc70057dVladimir Kotikov9 years ago | 175 | // and started listening for IPC messages |
| 176 | postMessage({workerLoaded:true});`; | |
| 177 | | |
bb869343Serge Svekolnikov8 years ago | 178 | public static FETCH_STUB = `(function(self) { |
4cf8fdf4Yuri Skorokhodov6 years ago | 179 | 'use strict'; |
bb869343Serge Svekolnikov8 years ago | 180 | |
4cf8fdf4Yuri Skorokhodov6 years ago | 181 | if (self.fetch) { |
| 182 | return; | |
| 183 | } | |
| 184 | | |
| 185 | self.fetch = fetch; | |
bb869343Serge Svekolnikov8 years ago | 186 | |
4cf8fdf4Yuri Skorokhodov6 years ago | 187 | function fetch(url) { |
| 188 | return new Promise((resolve, reject) => { | |
| 189 | var data = require('fs').readFileSync(fileUrlToPath(url), 'utf8'); | |
| 190 | resolve( | |
| 191 | { | |
| 192 | text: function () { | |
| 193 | return data; | |
| 194 | } | |
bb869343Serge Svekolnikov8 years ago | 195 | }); |
4cf8fdf4Yuri Skorokhodov6 years ago | 196 | }); |
| 197 | } | |
| 198 | })(global); | |
| 199 | `; | |
bb869343Serge Svekolnikov8 years ago | 200 | |
6eeec3c0Serge Svekolnikov8 years ago | 201 | private packagerAddress: string; |
e3ae4227digeff10 years ago | 202 | private packagerPort: number; |
4677921cdigeff10 years ago | 203 | private sourcesStoragePath: string; |
7daed3fcArtem Egorov8 years ago | 204 | private projectRootPath: string; |
6eeec3c0Serge Svekolnikov8 years ago | 205 | private packagerRemoteRoot?: string; |
| 206 | private packagerLocalRoot?: string; | |
cf911877Yuri Skorokhodov7 years ago | 207 | private debuggerWorkerUrlPath?: string; |
ea8a5f88digeff10 years ago | 208 | private socketToApp: WebSocket; |
5c8365a6Artem Egorov8 years ago | 209 | private singleLifetimeWorker: IDebuggeeWorker | null; |
3b6023b2Jimmy Thomson10 years ago | 210 | private webSocketConstructor: (url: string) => WebSocket; |
| 211 | | |
7cc67271digeff10 years ago | 212 | private executionLimiter = new ExecutionsLimiter(); |
cc70057dVladimir Kotikov9 years ago | 213 | private nodeFileSystem = new NodeFileSystem(); |
| 214 | private scriptImporter: ScriptImporter; | |
7cc67271digeff10 years ago | 215 | |
6eeec3c0Serge Svekolnikov8 years ago | 216 | constructor( |
| 217 | attachRequestArguments: any, | |
| 218 | sourcesStoragePath: string, | |
| 219 | projectRootPath: string, | |
| 220 | { | |
| 221 | webSocketConstructor = (url: string) => new WebSocket(url), | |
| 222 | } = {}) { | |
e45838cbVladimir Kotikov9 years ago | 223 | super(); |
6eeec3c0Serge Svekolnikov8 years ago | 224 | this.packagerAddress = attachRequestArguments.address || "localhost"; |
| 225 | this.packagerPort = attachRequestArguments.port; | |
| 226 | this.packagerRemoteRoot = attachRequestArguments.remoteRoot; | |
| 227 | this.packagerLocalRoot = attachRequestArguments.localRoot; | |
cf911877Yuri Skorokhodov7 years ago | 228 | this.debuggerWorkerUrlPath = attachRequestArguments.debuggerWorkerUrlPath; |
4677921cdigeff10 years ago | 229 | this.sourcesStoragePath = sourcesStoragePath; |
7daed3fcArtem Egorov8 years ago | 230 | this.projectRootPath = projectRootPath; |
1758f9a6Yuri Skorokhodov7 years ago | 231 | if (!this.sourcesStoragePath) |
| 232 | throw ErrorHelper.getInternalError(InternalErrorCode.SourcesStoragePathIsNullOrEmpty); | |
3b6023b2Jimmy Thomson10 years ago | 233 | this.webSocketConstructor = webSocketConstructor; |
6eeec3c0Serge Svekolnikov8 years ago | 234 | this.scriptImporter = new ScriptImporter(this.packagerAddress, this.packagerPort, sourcesStoragePath, this.packagerRemoteRoot, this.packagerLocalRoot); |
4677921cdigeff10 years ago | 235 | } |
| 236 | | |
cc70057dVladimir Kotikov9 years ago | 237 | public start(retryAttempt: boolean = false): Q.Promise<any> { |
d124bf0eYuri Skorokhodov7 years ago | 238 | const errPackagerNotRunning = ErrorHelper.getInternalError(InternalErrorCode.CannotAttachToPackagerCheckPackagerRunningOnPort, this.packagerPort); |
0a68f8dbArtem Egorov8 years ago | 239 | |
6eeec3c0Serge Svekolnikov8 years ago | 240 | return ensurePackagerRunning(this.packagerAddress, this.packagerPort, errPackagerNotRunning) |
cc70057dVladimir Kotikov9 years ago | 241 | .then(() => { |
| 242 | // Don't fetch debugger worker on socket disconnect | |
| 243 | return retryAttempt ? Q.resolve<void>(void 0) : | |
| 244 | this.downloadAndPatchDebuggerWorker(); | |
| 245 | }) | |
| 246 | .then(() => this.createSocketToApp(retryAttempt)); | |
ff7dce65digeff10 years ago | 247 | } |
| 248 | | |
e45838cbVladimir Kotikov9 years ago | 249 | public stop() { |
| 250 | if (this.socketToApp) { | |
| 251 | this.socketToApp.removeAllListeners(); | |
| 252 | this.socketToApp.close(); | |
| 253 | } | |
| 254 | | |
| 255 | if (this.singleLifetimeWorker) { | |
| 256 | this.singleLifetimeWorker.stop(); | |
| 257 | } | |
| 258 | } | |
| 259 | | |
cc70057dVladimir Kotikov9 years ago | 260 | public downloadAndPatchDebuggerWorker(): Q.Promise<void> { |
| 261 | let scriptToRunPath = path.resolve(this.sourcesStoragePath, ScriptImporter.DEBUGGER_WORKER_FILENAME); | |
cf911877Yuri Skorokhodov7 years ago | 262 | return this.scriptImporter.downloadDebuggerWorker(this.sourcesStoragePath, this.projectRootPath, this.debuggerWorkerUrlPath) |
cc70057dVladimir Kotikov9 years ago | 263 | .then(() => this.nodeFileSystem.readFile(scriptToRunPath, "utf8")) |
| 264 | .then((workerContent: string) => { | |
bb869343Serge Svekolnikov8 years ago | 265 | const isHaulProject = ReactNativeProjectHelper.isHaulProject(this.projectRootPath); |
cc70057dVladimir Kotikov9 years ago | 266 | // Add our customizations to debugger worker to get it working smoothly |
| 267 | // in Node env and polyfill WebWorkers API over Node's IPC. | |
bb869343Serge Svekolnikov8 years ago | 268 | const modifiedDebuggeeContent = [ |
| 269 | MultipleLifetimesAppWorker.WORKER_BOOTSTRAP, | |
cf6dd6b9Yuri Skorokhodov7 years ago | 270 | MultipleLifetimesAppWorker.CONSOLE_TRACE_PATCH, |
13a99427Yuri Skorokhodov6 years ago | 271 | MultipleLifetimesAppWorker.PROCESS_TO_STRING_PATCH, |
bb869343Serge Svekolnikov8 years ago | 272 | isHaulProject ? MultipleLifetimesAppWorker.FETCH_STUB : null, |
| 273 | workerContent, | |
| 274 | MultipleLifetimesAppWorker.WORKER_DONE, | |
| 275 | ].join("\n"); | |
cc70057dVladimir Kotikov9 years ago | 276 | return this.nodeFileSystem.writeFile(scriptToRunPath, modifiedDebuggeeContent); |
| 277 | }); | |
| 278 | } | |
| 279 | | |
ff7dce65digeff10 years ago | 280 | private startNewWorkerLifetime(): Q.Promise<void> { |
6eeec3c0Serge Svekolnikov8 years ago | 281 | this.singleLifetimeWorker = new ForkedAppWorker(this.packagerAddress, this.packagerPort, this.sourcesStoragePath, this.projectRootPath, |
| 282 | (message) => { | |
| 283 | this.sendMessageToApp(message); | |
| 284 | }, | |
| 285 | this.packagerRemoteRoot, this.packagerLocalRoot); | |
0a68f8dbArtem Egorov8 years ago | 286 | logger.verbose("A new app worker lifetime was created."); |
e45838cbVladimir Kotikov9 years ago | 287 | return this.singleLifetimeWorker.start() |
cc70057dVladimir Kotikov9 years ago | 288 | .then(startedEvent => { |
| 289 | this.emit("connected", startedEvent); | |
| 290 | }); | |
4677921cdigeff10 years ago | 291 | } |
| 292 | | |
cc70057dVladimir Kotikov9 years ago | 293 | private createSocketToApp(retryAttempt: boolean = false): Q.Promise<void> { |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 294 | let deferred = Q.defer<void>(); |
6e731058Jimmy Thomson10 years ago | 295 | this.socketToApp = this.webSocketConstructor(this.debuggerProxyUrl()); |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 296 | this.socketToApp.on("open", () => { |
| 297 | this.onSocketOpened(); | |
| 298 | }); | |
299b0557Patricio Beltran10 years ago | 299 | this.socketToApp.on("close", |
| 300 | () => { | |
| 301 | this.executionLimiter.execute("onSocketClose.msg", /*limitInSeconds*/ 10, () => { | |
| 302 | /* | |
| 303 | * It is not the best idea to compare with the message, but this is the only thing React Native gives that is unique when | |
| 304 | * it closes the socket because it already has a connection to a debugger. | |
| 305 | * https://github.com/facebook/react-native/blob/588f01e9982775f0699c7bfd56623d4ed3949810/local-cli/server/util/webSocketProxy.js#L38 | |
| 306 | */ | |
6d5c8798Nikita Matrosov9 years ago | 307 | let msgKey = "_closeMessage"; |
| 308 | if (this.socketToApp[msgKey] === "Another debugger is already connected") { | |
d124bf0eYuri Skorokhodov7 years ago | 309 | deferred.reject(ErrorHelper.getInternalError(InternalErrorCode.AnotherDebuggerConnectedToPackager)); |
299b0557Patricio Beltran10 years ago | 310 | } |
d124bf0eYuri Skorokhodov7 years ago | 311 | logger.log(localize("DisconnectedFromThePackagerToReactNative", "Disconnected from the Proxy (Packager) to the React Native application. Retrying reconnection soon...")); |
299b0557Patricio Beltran10 years ago | 312 | }); |
| 313 | setTimeout(() => { | |
| 314 | this.start(true /* retryAttempt */); | |
| 315 | }, 100); | |
| 316 | }); | |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 317 | this.socketToApp.on("message", |
ea8a5f88digeff10 years ago | 318 | (message: any) => this.onMessage(message)); |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 319 | this.socketToApp.on("error", |
32cab018Meena Kunnathur Balakrishnan10 years ago | 320 | (error: Error) => { |
cc70057dVladimir Kotikov9 years ago | 321 | if (retryAttempt) { |
1758f9a6Yuri Skorokhodov7 years ago | 322 | printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.ReconnectionToPackagerFailedCheckForErrorsOrRestartReactNative), error); |
499fe4ebMeena Kunnathur Balakrishnan10 years ago | 323 | } |
| 324 | | |
32cab018Meena Kunnathur Balakrishnan10 years ago | 325 | deferred.reject(error); |
| 326 | }); | |
| 327 | | |
499fe4ebMeena Kunnathur Balakrishnan10 years ago | 328 | // In an attempt to catch failures in starting the packager on first attempt, |
| 329 | // wait for 300 ms before resolving the promise | |
b9356af0Meena Kunnathur Balakrishnan10 years ago | 330 | Q.delay(300).done(() => deferred.resolve(void 0)); |
32cab018Meena Kunnathur Balakrishnan10 years ago | 331 | return deferred.promise; |
4677921cdigeff10 years ago | 332 | } |
| 333 | | |
| 334 | private debuggerProxyUrl() { | |
6eeec3c0Serge Svekolnikov8 years ago | 335 | return `ws://${this.packagerAddress}:${this.packagerPort}/debugger-proxy?role=debugger&name=vscode`; |
4677921cdigeff10 years ago | 336 | } |
| 337 | | |
ea8a5f88digeff10 years ago | 338 | private onSocketOpened() { |
7cc67271digeff10 years ago | 339 | this.executionLimiter.execute("onSocketOpened.msg", /*limitInSeconds*/ 10, () => |
d124bf0eYuri Skorokhodov7 years ago | 340 | logger.log(localize("EstablishedConnectionWithPackagerToReactNativeApp", "Established a connection with the Proxy (Packager) to the React Native application"))); |
4677921cdigeff10 years ago | 341 | } |
| 342 | | |
9174feb7Vladimir Kotikov9 years ago | 343 | private killWorker() { |
| 344 | if (!this.singleLifetimeWorker) return; | |
| 345 | this.singleLifetimeWorker.stop(); | |
| 346 | this.singleLifetimeWorker = null; | |
| 347 | } | |
e7b314e8Vladimir Kotikov9 years ago | 348 | |
9174feb7Vladimir Kotikov9 years ago | 349 | private onMessage(message: string) { |
5d4d4de0digeff10 years ago | 350 | try { |
0a68f8dbArtem Egorov8 years ago | 351 | logger.verbose("From RN APP: " + message); |
ea8a5f88digeff10 years ago | 352 | let object = <RNAppMessage>JSON.parse(message); |
5d4d4de0digeff10 years ago | 353 | if (object.method === "prepareJSRuntime") { |
e7b314e8Vladimir Kotikov9 years ago | 354 | // In RN 0.40 Android runtime doesn't seem to be sending "$disconnected" event |
| 355 | // when user reloads an app, hence we need to try to kill it here either. | |
9174feb7Vladimir Kotikov9 years ago | 356 | this.killWorker(); |
5d4d4de0digeff10 years ago | 357 | // The MultipleLifetimesAppWorker will handle prepareJSRuntime aka create new lifetime |
| 358 | this.gotPrepareJSRuntime(object); | |
ff7dce65digeff10 years ago | 359 | } else if (object.method === "$disconnected") { |
| 360 | // We need to shutdown the current app worker, and create a new lifetime | |
9174feb7Vladimir Kotikov9 years ago | 361 | this.killWorker(); |
5d4d4de0digeff10 years ago | 362 | } else if (object.method) { |
| 363 | // All the other messages are handled by the single lifetime worker | |
5c8365a6Artem Egorov8 years ago | 364 | if (this.singleLifetimeWorker) { |
| 365 | this.singleLifetimeWorker.postMessage(object); | |
| 366 | } | |
5d4d4de0digeff10 years ago | 367 | } else { |
ea8a5f88digeff10 years ago | 368 | // Message doesn't have a method. Ignore it. This is an info message instead of warn because it's normal and expected |
d124bf0eYuri Skorokhodov7 years ago | 369 | logger.verbose(`The react-native app sent a message without specifying a method: ${message}`); |
5d4d4de0digeff10 years ago | 370 | } |
| 371 | } catch (exception) { | |
1758f9a6Yuri Skorokhodov7 years ago | 372 | printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToProcessMessageFromReactNativeApp, message), exception); |
4677921cdigeff10 years ago | 373 | } |
| 374 | } | |
| 375 | | |
| 376 | private gotPrepareJSRuntime(message: any): void { | |
| 377 | // Create the sandbox, and replay that we finished processing the message | |
ff7dce65digeff10 years ago | 378 | this.startNewWorkerLifetime().done(() => { |
| 379 | this.sendMessageToApp({ replyID: parseInt(message.id, 10) }); | |
1758f9a6Yuri Skorokhodov7 years ago | 380 | }, error => printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToPrepareJSRuntimeEnvironment, message), error)); |
4677921cdigeff10 years ago | 381 | } |
| 382 | | |
ff7dce65digeff10 years ago | 383 | private sendMessageToApp(message: any): void { |
5c8365a6Artem Egorov8 years ago | 384 | let stringified: string = ""; |
354c28a1digeff10 years ago | 385 | try { |
| 386 | stringified = JSON.stringify(message); | |
d124bf0eYuri Skorokhodov7 years ago | 387 | logger.verbose(`To RN APP: ${stringified}`); |
354c28a1digeff10 years ago | 388 | this.socketToApp.send(stringified); |
| 389 | } catch (exception) { | |
| 390 | let messageToShow = stringified || ("" + message); // Try to show the stringified version, but show the toString if unavailable | |
1758f9a6Yuri Skorokhodov7 years ago | 391 | printDebuggingError(ErrorHelper.getInternalError(InternalErrorCode.FailedToSendMessageToTheReactNativeApp, messageToShow), exception); |
354c28a1digeff10 years ago | 392 | } |
4677921cdigeff10 years ago | 393 | } |
| 394 | } |