forked from bytesonus/juno-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjuno-node.ts
More file actions
231 lines (205 loc) · 5.87 KB
/
juno-node.ts
File metadata and controls
231 lines (205 loc) · 5.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import { isIP } from 'net';
import { promises as fsPromises } from 'fs';
import { BaseProtocol } from './protocol/base-protocol';
import BaseConnection from './connection/base-connection';
import { JsonProtocol } from './protocol/json-protocol';
import { ResponseTypes, RequestTypes } from './utils/constants';
import {
FunctionCallRequest,
FunctionCallResponse,
TriggerHookRequest,
JunoMessage
} from './models/messages';
import UnixSocketConnection from './connection/unix-socket-connection';
import InetSocketConnection from './connection/inet-socket-connection';
export default class JunoModule {
private protocol: BaseProtocol;
private moduleId?: string;
private connection: BaseConnection;
private requests: { [type: string]: Function } = {};
private functions: { [type: string]: Function } = {};
private hookListeners: { [type: string]: Function[] } = {};
private messagBuffer?: Buffer;
private registered = false;
constructor(connection: BaseConnection, protocol: BaseProtocol) {
this.protocol = protocol;
this.connection = connection;
// this.connection.setOnDataListener(this.onDataHandler);
}
public static async default(socketPath: string) {
const [ host, port ] = socketPath.split(':');
if (isIP(host) && !isNaN(Number(port))) {
return this.fromInetSocket(host, Number(port));
}
if ( (await fsPromises.lstat(socketPath)).isSocket() ) {
return this.fromUnixSocket(socketPath);
}
throw new Error('Invalid socket object. Only unix domain sockets and Inet sockets are allowed');
}
public static async fromUnixSocket(path: string) {
// Return Error if invoked from windows
if (process.platform == 'win32') {
throw new Error('Unix sockets are not supported on windows');
}
if ( (await fsPromises.lstat(path)).isSocket() ) {
return new JunoModule(new UnixSocketConnection(path), new JsonProtocol());
}
throw new Error('Invalid unix socket path');
}
public static async fromInetSocket(host: string, port: number) {
if (isIP(host) && !isNaN(Number(port))) {
return new JunoModule(new InetSocketConnection(host, port), new JsonProtocol());
}
throw new Error('Invalid Inet socket address. Use the format `{host}:{port}`')
}
public async initialize(
moduleId: string,
version: string,
deps: { [type: string]: string } = {}
) {
this.moduleId = moduleId;
// Setup Connection only when initialize called?
await this.connection.setupConnection();
this.connection.setOnDataListener((data) => {
this.onDataHandler(data);
});
return this.sendRequest(
this.protocol.initialize(
moduleId,
version,
deps
)
);
}
public async declareFunction(fnName: string, fn: Function) {
this.functions[fnName] = fn;
return this.sendRequest(
this.protocol.declareFunction(fnName)
);
}
public async callFunction(fnName: string, args: any = {}) {
return this.sendRequest(
this.protocol.callFunction(fnName, args)
);
}
public async registerHook(hook: string, cb: Function) {
if (this.hookListeners[hook]) {
this.hookListeners[hook].push(cb);
} else {
this.hookListeners[hook] = [
cb
];
}
return this.sendRequest(
this.protocol.registerHook(hook)
);
}
public async triggerHook(hook: string) {
return this.sendRequest(
this.protocol.triggerHook(hook)
);
}
public async close() {
return this.connection.closeConnection();
}
private async sendRequest(request: JunoMessage) {
if (request.type === RequestTypes.ModuleRegistration && this.registered) {
throw new Error('Module already registered');
}
const encoded = this.protocol.encode(request);
if (this.registered || request.type === RequestTypes.ModuleRegistration) {
await this.connection.send(
encoded
);
} else {
if (this.messagBuffer) {
this.messagBuffer = Buffer.concat([this.messagBuffer, encoded]);
} else {
this.messagBuffer = encoded;
}
}
return new Promise((resolve, reject) => {
this.requests[request.requestId] = (response: any) => {
if (response) {
resolve(response);
} else {
reject(response);
}
};
});
}
private async onDataHandler(data: Buffer) {
const response = this.protocol.decode(data);
let value;
switch (response.type) {
case ResponseTypes.ModuleRegistered: {
value = true;
break;
}
case ResponseTypes.FunctionResponse: {
value = await (response as FunctionCallResponse).data;
break;
}
case ResponseTypes.FunctionDeclared: {
value = true;
break;
}
case ResponseTypes.HookRegistered: {
value = true;
break;
}
case ResponseTypes.HookTriggered: {
value = await this.executeHookTriggered(response as TriggerHookRequest);
break;
}
case RequestTypes.FunctionCall: {
this.executeFunctionCall(response as FunctionCallRequest);
break;
}
default: {
value = false;
break;
}
}
if (this.requests[response.requestId]) {
this.requests[response.requestId](value);
delete this.requests[response.requestId];
}
}
private async executeFunctionCall(request: FunctionCallRequest) {
if (this.functions[request.function]) {
let res = this.functions[request.function](request.arguments || {});
if (res instanceof Promise) {
res = await res;
}
this.sendRequest({
requestId: request.requestId,
type: ResponseTypes.FunctionResponse,
data: res || {}
});
return true;
} else {
// Function wasn't found in the module.
return false;
}
}
private async executeHookTriggered(request: TriggerHookRequest) {
if (request.hook) {
// Hook triggered by another module.
if (request.hook === `juno.activated`) {
this.registered = true;
if (this.messagBuffer) {
this.connection.send(this.messagBuffer);
}
} else if (this.hookListeners[request.hook]) {
for (const listener of this.hookListeners[request.hook]) {
listener();
}
}
return true;
} else {
// This moddule triggered the hook.
return true;
}
}
}