microsoft/vscode-react-native

Public

mirrored from https://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
e23f3af4e8969c6ae0b3d468530b6c68ee157de2

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/extension/rn-extension.ts

186lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4import * as fs from "fs";
5
6// @ifdef DEBUG
7try {
8 fs.statSync(`${__filename}.map`); // We check if source maps are available
9 /* tslint:disable:no-var-requires */
10 require("source-map-support").install(); // If they are, we enable stack traces translation to typescript
11 /* tslint:enable:no-var-requires */
12} catch (exceptions) {
13 // If something goes wrong, we just ignore the errors
14}
15// @endif
16
17import * as Q from "q";
18import * as path from "path";
19import * as vscode from "vscode";
20
21import {FileSystem} from "../common/node/fileSystem";
22import {CommandPaletteHandler} from "./commandPaletteHandler";
23import {Packager} from "../common/packager";
24import {EntryPointHandler, ProcessType} from "../common/entryPointHandler";
25import {ErrorHelper} from "../common/error/errorHelper";
26import {InternalError} from "../common/error/internalError";
27import {InternalErrorCode} from "../common/error/internalErrorCode";
28import {Log} from "../common/log/log";
29import {LogHelper} from "../common/log/logHelper";
30import {SettingsHelper} from "./settingsHelper";
31import {PackagerStatusIndicator} from "./packagerStatusIndicator";
32import {ReactNativeProjectHelper} from "../common/reactNativeProjectHelper";
33import {ReactDirManager} from "./reactDirManager";
34import {IntellisenseHelper} from "./intellisenseHelper";
35import {Telemetry} from "../common/telemetry";
36import {TelemetryHelper} from "../common/telemetryHelper";
37import {ExtensionServer} from "./extensionServer";
38import {DelayedOutputChannelLogger} from "./outputChannelLogger";
39import {ExponentHelper} from "../common/exponent/exponentHelper";
40
41/* all components use the same packager instance */
42const projectRootPath = SettingsHelper.getReactNativeProjectRoot();
43const workspaceRootPath = vscode.workspace.rootPath;
44const globalPackager = new Packager(workspaceRootPath, projectRootPath);
45const packagerStatusIndicator = new PackagerStatusIndicator();
46const globalExponentHelper = new ExponentHelper(workspaceRootPath, projectRootPath);
47const commandPaletteHandler = new CommandPaletteHandler(projectRootPath, globalPackager, packagerStatusIndicator, globalExponentHelper);
48
49const outputChannelLogger = new DelayedOutputChannelLogger("React-Native");
50const entryPointHandler = new EntryPointHandler(ProcessType.Extension, outputChannelLogger);
51const reactNativeProjectHelper = new ReactNativeProjectHelper(projectRootPath);
52const fsUtil = new FileSystem();
53
54interface ISetupableDisposable extends vscode.Disposable {
55 setup(): Q.Promise<any>;
56}
57
58export function activate(context: vscode.ExtensionContext): void {
59 configureLogLevel();
60 entryPointHandler.runApp("react-native", () => <string>require("../../package.json").version,
61 ErrorHelper.getInternalError(InternalErrorCode.ExtensionActivationFailed), projectRootPath, () => {
62 return reactNativeProjectHelper.isReactNativeProject()
63 .then(isRNProject => {
64 if (isRNProject) {
65 let activateExtensionEvent = TelemetryHelper.createTelemetryEvent("activate");
66 Telemetry.send(activateExtensionEvent);
67
68 warnWhenReactNativeVersionIsNotSupported();
69 entryPointHandler.runFunction("debugger.setupLauncherStub",
70 ErrorHelper.getInternalError(InternalErrorCode.DebuggerStubLauncherFailed), () =>
71 setupReactNativeDebugger()
72 .then(() =>
73 setupAndDispose(new ReactDirManager(), context))
74 .then(() =>
75 setupAndDispose(new ExtensionServer(projectRootPath, globalPackager, packagerStatusIndicator, globalExponentHelper), context))
76 .then(() => {}));
77 entryPointHandler.runFunction("intelliSense.setup",
78 ErrorHelper.getInternalError(InternalErrorCode.IntellisenseSetupFailed), () =>
79 IntellisenseHelper.setupReactNativeIntellisense());
80 }
81 entryPointHandler.runFunction("debugger.setupNodeDebuggerLocation",
82 ErrorHelper.getInternalError(InternalErrorCode.NodeDebuggerConfigurationFailed), () => {
83 configureNodeDebuggerLocation();
84 });
85 registerReactNativeCommands(context);
86 });
87 });
88}
89
90export function deactivate(): Q.Promise<void> {
91 return Q.Promise<void>(function (resolve) {
92 // Kill any packager processes that we spawned
93 entryPointHandler.runFunction("extension.deactivate",
94 ErrorHelper.getInternalError(InternalErrorCode.FailedToStopPackagerOnExit),
95 () => {
96 commandPaletteHandler.stopPackager().done(() => {
97 // Tell vscode that we are done with deactivation
98 resolve(void 0);
99 });
100 }, /*errorsAreFatal*/ true);
101 });
102}
103
104function configureLogLevel(): void {
105 LogHelper.logLevel = SettingsHelper.getLogLevel();
106}
107
108function configureNodeDebuggerLocation(): Q.Promise<void> {
109 const nodeDebugExtension = vscode.extensions.getExtension("ms-vscode.node-debug") // We try to get the new version
110 || vscode.extensions.getExtension("andreweinand.node-debug"); // If it's not available, we try to get the old version
111 if (!nodeDebugExtension) {
112 return Q.reject<void>(ErrorHelper.getInternalError(InternalErrorCode.CouldNotFindLocationOfNodeDebugger));
113 }
114 const nodeDebugPath = nodeDebugExtension.extensionPath;
115 return fsUtil.writeFile(path.resolve(__dirname, "../", "debugger", "nodeDebugLocation.json"), JSON.stringify({ nodeDebugPath }));
116}
117
118function setupAndDispose<T extends ISetupableDisposable>(setuptableDisposable: T, context: vscode.ExtensionContext): Q.Promise<T> {
119 return setuptableDisposable.setup()
120 .then(() => {
121 context.subscriptions.push(setuptableDisposable);
122 return setuptableDisposable;
123 });
124}
125
126function warnWhenReactNativeVersionIsNotSupported(): void {
127 return reactNativeProjectHelper.validateReactNativeVersion().done(() => { }, reason => {
128 TelemetryHelper.sendSimpleEvent("unsupportedRNVersion", { rnVersion: reason });
129 const shortMessage = `React Native Tools need React Native version 0.19.0 or later to be installed in <PROJECT_ROOT>/node_modules/`;
130 const longMessage = `${shortMessage}: ${reason}`;
131 vscode.window.showWarningMessage(shortMessage);
132 Log.logMessage(longMessage);
133 });
134}
135
136function registerReactNativeCommands(context: vscode.ExtensionContext): void {
137 // Register React Native commands
138 registerVSCodeCommand(context, "runAndroid", ErrorHelper.getInternalError(InternalErrorCode.FailedToRunOnAndroid), () => commandPaletteHandler.runAndroid());
139 registerVSCodeCommand(context, "runIos", ErrorHelper.getInternalError(InternalErrorCode.FailedToRunOnIos), () => commandPaletteHandler.runIos());
140 registerVSCodeCommand(context, "startPackager", ErrorHelper.getInternalError(InternalErrorCode.FailedToStartPackager), () => commandPaletteHandler.startPackager());
141 registerVSCodeCommand(context, "startExponentPackager", ErrorHelper.getInternalError(InternalErrorCode.FailedToStartExponentPackager), () => commandPaletteHandler.startExponentPackager());
142 registerVSCodeCommand(context, "stopPackager", ErrorHelper.getInternalError(InternalErrorCode.FailedToStopPackager), () => commandPaletteHandler.stopPackager());
143 registerVSCodeCommand(context, "restartPackager", ErrorHelper.getInternalError(InternalErrorCode.FailedToRestartPackager), () => commandPaletteHandler.restartPackager());
144 registerVSCodeCommand(context, "publishToExpHost", ErrorHelper.getInternalError(InternalErrorCode.FailedToPublishToExpHost), () => commandPaletteHandler.publishToExpHost());
145}
146
147function registerVSCodeCommand(
148 context: vscode.ExtensionContext, commandName: string,
149 error: InternalError, commandHandler: () => Q.Promise<void>): void {
150 context.subscriptions.push(vscode.commands.registerCommand(
151 `reactNative.${commandName}`,
152 () =>
153 entryPointHandler.runFunction(
154 `commandPalette.${commandName}`, error,
155 commandHandler)));
156}
157
158/**
159 * Sets up the debugger for the React Native project by dropping
160 * the debugger stub into the workspace
161 */
162function setupReactNativeDebugger(): Q.Promise<void> {
163 const launcherPath = require.resolve("../debugger/launcher");
164 const pkg = require("../../package.json");
165 const extensionVersionNumber = pkg.version;
166 const extensionName = pkg.name;
167
168 let debuggerEntryCode =
169 `// This file is automatically generated by ${extensionName}@${extensionVersionNumber}
170// Please do not modify it manually. All changes will be lost.
171try {
172 var path = require("path");
173 var Launcher = require(${JSON.stringify(launcherPath)}).Launcher;
174 new Launcher("${workspaceRootPath.replace(/\\/g, "\\\\")}", "${projectRootPath.replace(/\\/g, "\\\\")}").launch();
175} catch (e) {
176 throw new Error("Unable to launch application. Try deleting .vscode/launchReactNative.js and restarting vscode.");
177}`;
178 const vsCodeFolder = path.join(workspaceRootPath, ".vscode");
179 const debugStub = path.join(vsCodeFolder, "launchReactNative.js");
180
181 return fsUtil.ensureDirectory(vsCodeFolder)
182 .then(() => fsUtil.ensureFileWithContents(debugStub, debuggerEntryCode))
183 .catch((err: Error) => {
184 vscode.window.showErrorMessage(err.message);
185 });
186}