microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
b648d5cc9c9052afe2bcb20bb398734e167df2b7

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/extension/rn-extension.ts

179lines · 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 {PackagerStatusIndicator} from "./packagerStatusIndicator";
30import {ReactNativeProjectHelper} from "../common/reactNativeProjectHelper";
31import {ReactDirManager} from "./reactDirManager";
32import {IntellisenseHelper} from "./intellisenseHelper";
33import {Telemetry} from "../common/telemetry";
34import {TelemetryHelper} from "../common/telemetryHelper";
35import {ExtensionServer} from "./extensionServer";
36import {DelayedOutputChannelLogger} from "./outputChannelLogger";
37import {ExponentHelper} from "../common/exponent/exponentHelper";
38
39/* all components use the same packager instance */
40const projectRootPath = vscode.workspace.rootPath;
41const globalPackager = new Packager(projectRootPath);
42const packagerStatusIndicator = new PackagerStatusIndicator();
43const globalExponentHelper = new ExponentHelper(projectRootPath);
44const commandPaletteHandler = new CommandPaletteHandler(projectRootPath, globalPackager, packagerStatusIndicator, globalExponentHelper);
45
46const outputChannelLogger = new DelayedOutputChannelLogger("React-Native");
47const entryPointHandler = new EntryPointHandler(ProcessType.Extension, outputChannelLogger);
48const reactNativeProjectHelper = new ReactNativeProjectHelper(projectRootPath);
49const fsUtil = new FileSystem();
50
51interface ISetupableDisposable extends vscode.Disposable {
52 setup(): Q.Promise<any>;
53}
54
55export function activate(context: vscode.ExtensionContext): void {
56
57 entryPointHandler.runApp("react-native", () => <string>require("../../package.json").version,
58 ErrorHelper.getInternalError(InternalErrorCode.ExtensionActivationFailed), projectRootPath, () => {
59 return reactNativeProjectHelper.isReactNativeProject()
60 .then(isRNProject => {
61 if (isRNProject) {
62 let activateExtensionEvent = TelemetryHelper.createTelemetryEvent("activate");
63 Telemetry.send(activateExtensionEvent);
64
65 warnWhenReactNativeVersionIsNotSupported();
66 entryPointHandler.runFunction("debugger.setupLauncherStub",
67 ErrorHelper.getInternalError(InternalErrorCode.DebuggerStubLauncherFailed), () =>
68 setupReactNativeDebugger()
69 .then(() =>
70 setupAndDispose(new ReactDirManager(), context))
71 .then(() =>
72 setupAndDispose(new ExtensionServer(projectRootPath, globalPackager, packagerStatusIndicator, globalExponentHelper), context))
73 .then(() => {}));
74 entryPointHandler.runFunction("intelliSense.setup",
75 ErrorHelper.getInternalError(InternalErrorCode.IntellisenseSetupFailed), () =>
76 IntellisenseHelper.setupReactNativeIntellisense());
77 }
78 entryPointHandler.runFunction("debugger.setupNodeDebuggerLocation",
79 ErrorHelper.getInternalError(InternalErrorCode.NodeDebuggerConfigurationFailed), () =>
80 configureNodeDebuggerLocation());
81 registerReactNativeCommands(context);
82 });
83 });
84}
85
86export function deactivate(): Q.Promise<void> {
87 return Q.Promise<void>(function (resolve) {
88 // Kill any packager processes that we spawned
89 entryPointHandler.runFunction("extension.deactivate",
90 ErrorHelper.getInternalError(InternalErrorCode.FailedToStopPackagerOnExit),
91 () => {
92 commandPaletteHandler.stopPackager().done(() => {
93 // Tell vscode that we are done with deactivation
94 resolve(void 0);
95 });
96 }, /*errorsAreFatal*/ true);
97 });
98}
99
100function configureNodeDebuggerLocation(): Q.Promise<void> {
101 const nodeDebugExtension = vscode.extensions.getExtension("ms-vscode.node-debug") // We try to get the new version
102 || vscode.extensions.getExtension("andreweinand.node-debug"); // If it's not available, we try to get the old version
103 if (!nodeDebugExtension) {
104 return Q.reject<void>(ErrorHelper.getInternalError(InternalErrorCode.CouldNotFindLocationOfNodeDebugger));
105 }
106 const nodeDebugPath = nodeDebugExtension.extensionPath;
107 return fsUtil.writeFile(path.resolve(__dirname, "../", "debugger", "nodeDebugLocation.json"), JSON.stringify({ nodeDebugPath }));
108}
109
110function setupAndDispose<T extends ISetupableDisposable>(setuptableDisposable: T, context: vscode.ExtensionContext): Q.Promise<T> {
111 return setuptableDisposable.setup()
112 .then(() => {
113 context.subscriptions.push(setuptableDisposable);
114 return setuptableDisposable;
115 });
116}
117
118function warnWhenReactNativeVersionIsNotSupported(): void {
119 return reactNativeProjectHelper.validateReactNativeVersion().done(() => { }, reason => {
120 TelemetryHelper.sendSimpleEvent("unsupportedRNVersion", { rnVersion: reason });
121 const shortMessage = `React Native Tools need React Native version 0.19.0 or later to be installed in <PROJECT_ROOT>/node_modules/`;
122 const longMessage = `${shortMessage}: ${reason}`;
123 vscode.window.showWarningMessage(shortMessage);
124 Log.logMessage(longMessage);
125 });
126}
127
128function registerReactNativeCommands(context: vscode.ExtensionContext): void {
129 // Register React Native commands
130 registerVSCodeCommand(context, "runAndroid", ErrorHelper.getInternalError(InternalErrorCode.FailedToRunOnAndroid), () => commandPaletteHandler.runAndroid());
131 registerVSCodeCommand(context, "runIos", ErrorHelper.getInternalError(InternalErrorCode.FailedToRunOnIos), () => commandPaletteHandler.runIos());
132 registerVSCodeCommand(context, "startPackager", ErrorHelper.getInternalError(InternalErrorCode.FailedToStartPackager), () => commandPaletteHandler.startPackager());
133 registerVSCodeCommand(context, "startExponentPackager", ErrorHelper.getInternalError(InternalErrorCode.FailedToStartExponentPackager), () => commandPaletteHandler.startExponentPackager());
134 registerVSCodeCommand(context, "stopPackager", ErrorHelper.getInternalError(InternalErrorCode.FailedToStopPackager), () => commandPaletteHandler.stopPackager());
135 registerVSCodeCommand(context, "restartPackager", ErrorHelper.getInternalError(InternalErrorCode.FailedToRestartPackager), () => commandPaletteHandler.restartPackager());
136 registerVSCodeCommand(context, "publishToExpHost", ErrorHelper.getInternalError(InternalErrorCode.FailedToPublishToExpHost), () => commandPaletteHandler.publishToExpHost());
137}
138
139function registerVSCodeCommand(
140 context: vscode.ExtensionContext, commandName: string,
141 error: InternalError, commandHandler: () => Q.Promise<void>): void {
142 context.subscriptions.push(vscode.commands.registerCommand(
143 `reactNative.${commandName}`,
144 () =>
145 entryPointHandler.runFunction(
146 `commandPalette.${commandName}`, error,
147 commandHandler)));
148}
149
150/**
151 * Sets up the debugger for the React Native project by dropping
152 * the debugger stub into the workspace
153 */
154function setupReactNativeDebugger(): Q.Promise<void> {
155 const launcherPath = require.resolve("../debugger/launcher");
156 const pkg = require("../../package.json");
157 const extensionVersionNumber = pkg.version;
158 const extensionName = pkg.name;
159
160 let debuggerEntryCode =
161 `// This file is automatically generated by ${extensionName}@${extensionVersionNumber}
162// Please do not modify it manually. All changes will be lost.
163try {
164 var path = require("path");
165 var Launcher = require(${JSON.stringify(launcherPath)}).Launcher;
166 new Launcher(path.resolve(__dirname, "..")).launch();
167} catch (e) {
168 throw new Error("Unable to launch application. Try deleting .vscode/launchReactNative.js and restarting vscode.");
169}`;
170
171 const vscodeFolder = path.join(projectRootPath, ".vscode");
172 const debugStub = path.join(vscodeFolder, "launchReactNative.js");
173
174 return fsUtil.ensureDirectory(vscodeFolder)
175 .then(() => fsUtil.ensureFileWithContents(debugStub, debuggerEntryCode))
176 .catch((err: Error) => {
177 vscode.window.showErrorMessage(err.message);
178 });
179}