microsoft/vscode-react-native

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
df4bce4041caa61af1460ef87f2380820508a455

Branches

Tags

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

Clone

HTTPS

Download ZIP

src/common/extensionMessaging.ts

83lines · 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 Q from "q";
5import * as net from "net";
6import {HostPlatform} from "./hostPlatform";
7
8export let ErrorMarker = "vscodereactnative-error-marker";
9
10/**
11 * Defines the messages sent to the extension.
12 * Add new messages to this enum.
13 */
14export enum ExtensionMessage {
15 START_PACKAGER,
16 STOP_PACKAGER,
17 PREWARM_BUNDLE_CACHE,
18 START_MONITORING_LOGCAT,
19 STOP_MONITORING_LOGCAT,
20 GET_PACKAGER_PORT,
21}
22
23export interface MessageWithArguments {
24 message: ExtensionMessage;
25 args: any[];
26}
27
28export interface IExtensionMessageSender {
29 sendMessage(message: ExtensionMessage, args?: any[]): Q.Promise<any>;
30}
31
32export function validateMessageWithArguments(message: MessageWithArguments): void {
33 const print = () => JSON.stringify(message);
34
35 if (!ExtensionMessage[message.message]) {
36 throw new Error(`The message type of ${print()} is invalid: ${message.message}`);
37 }
38 if (!Array.isArray(message.args)) {
39 throw new Error(`The arguments of the message ${print()} should be an array, but they are: ${message.args}`);
40 }
41}
42
43/**
44 * Sends messages to the extension.
45 */
46export class ExtensionMessageSender implements IExtensionMessageSender {
47
48 public sendMessage(message: ExtensionMessage, args?: any[]): Q.Promise<any> {
49 let deferred = Q.defer<any>();
50 let messageWithArguments: MessageWithArguments = { message: message, args: args || [] };
51 validateMessageWithArguments(messageWithArguments);
52 let body = "";
53
54 let pipePath = HostPlatform.getExtensionPipePath();
55 let socket = net.connect(pipePath, function() {
56 let messageJson = JSON.stringify(messageWithArguments);
57 socket.write(messageJson);
58 });
59
60 socket.on("data", function(data: any) {
61 body += data;
62 });
63
64 socket.on("error", function(data: any) {
65 deferred.reject(new Error("An error ocurred while handling message: " + ExtensionMessage[message]));
66 });
67
68 socket.on("end", function() {
69 try {
70 if (body === ErrorMarker) {
71 deferred.reject(new Error("An error ocurred while handling message: " + ExtensionMessage[message]));
72 } else {
73 let responseBody: any = body ? JSON.parse(body) : null;
74 deferred.resolve(responseBody);
75 }
76 } catch (e) {
77 deferred.reject(e);
78 }
79 });
80
81 return deferred.promise;
82 }
83}