forked from CodecrumbsIO/codecrumbs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsource-watcher.js
More file actions
88 lines (76 loc) · 2.75 KB
/
source-watcher.js
File metadata and controls
88 lines (76 loc) · 2.75 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
const WebSocketClient = require('websocket').client;
const { SOCKET_MSG_MAX_SIZE } = require('./config');
const logger = require('./utils/logger');
const { parseFiles } = require('./api/');
const { SOCKET_MESSAGE_TYPE } = require('../shared/constants');
const projectSourceWatcher = require('./project-source/');
const { detectLanguage } = require('./code-parse/language');
const run = (
{ mediatorEndPoint, namespace, projectName },
{ projectDir, entryPoint, webpackConfigPath, astParserFallback }
) => {
const { language, extensions: fileExtensions } = detectLanguage(entryPoint, astParserFallback);
const webSocketClient = new WebSocketClient({
maxReceivedFrameSize: SOCKET_MSG_MAX_SIZE,
maxReceivedMessageSize: SOCKET_MSG_MAX_SIZE
});
webSocketClient.on('connectFailed', error => {
logger.error(`Connect error for ${namespace}, error: ${error} `);
});
webSocketClient.on('connect', connection => {
logger.info(
`+ started: source watcher: ${namespace} for: ${projectName}; `,
`setup: dir - ${projectDir}, entry point - ${entryPoint}`
);
connection.on('message', ({ utf8Data }) => {
const message = JSON.parse(utf8Data);
switch (message.type) {
case SOCKET_MESSAGE_TYPE.CLIENT_CONNECTED:
projectSourceWatcher.subscribeOnChange(
namespace,
{ projectName, projectDir, entryPoint, webpackConfigPath, language, fileExtensions },
{
onInit: data => {
logger.info(`> emit '${SOCKET_MESSAGE_TYPE.SOURCE_INIT_SOURCE_FILES_SYNC}'`);
connection.sendUTF(
JSON.stringify({
type: SOCKET_MESSAGE_TYPE.SOURCE_INIT_SOURCE_FILES_SYNC,
namespace,
data
})
);
},
onChange: data =>
connection.sendUTF(
JSON.stringify({
type: SOCKET_MESSAGE_TYPE.SOURCE_UPDATE_SOURCE_FILE_SYNC,
namespace,
data
})
)
}
);
break;
case SOCKET_MESSAGE_TYPE.CLIENT_REQUEST_FETCH_FILE:
if (message.namespace === namespace) {
parseFiles(message.data, projectDir, language).then(files =>
connection.sendUTF(
JSON.stringify({
type: SOCKET_MESSAGE_TYPE.SOURCE_RESPONSE_FETCH_FILE,
namespace,
data: { files }
})
)
);
}
break;
default:
logger.warn(`Unhandled message: ${message}`);
}
});
});
webSocketClient.connect(`ws://${mediatorEndPoint}/`);
};
module.exports = {
run
};