This repository has been archived by the owner on Dec 6, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathpackager.js
338 lines (299 loc) · 9.56 KB
/
packager.js
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// @flow
import {
PackagerLogsStream,
Project,
ProjectSettings,
ProjectUtils,
} from 'xdl';
import _ from 'lodash';
import spawn from 'cross-spawn';
import ProgressBar from 'progress';
import bunyan from '@expo/bunyan';
import chalk from 'chalk';
import { spawnBsbWatcherAsync } from './bsb';
import log from './log';
function installExitHooks(projectDir, isInteractive) {
if (!isInteractive && process.platform === 'win32') {
require('readline')
.createInterface({
input: process.stdin,
output: process.stdout,
})
.on('SIGINT', () => {
process.emit('SIGINT');
});
}
process.on('SIGINT', () => {
log.withTimestamp('Stopping packager...');
cleanUpPackager(projectDir).then(() => {
// TODO: this shows up after process exits, fix it
log.withTimestamp(chalk.green('Packager stopped.'));
process.exit();
});
});
}
async function cleanUpPackager(projectDir) {
const result = await Promise.race([
Project.stopAsync(projectDir),
new Promise((resolve, reject) => setTimeout(resolve, 1000, 'stopFailed')),
]);
if (result === 'stopFailed') {
// find RN packager pid, attempt to kill manually
try {
const { packagerPid } = await ProjectSettings.readPackagerInfoAsync(
projectDir
);
process.kill(packagerPid);
} catch (e) {
process.exit(1);
}
}
}
function shouldIgnoreMsg(msg) {
return msg.indexOf('Duplicate module name: bser') >= 0 ||
msg.indexOf('Duplicate module name: fb-watchman') >= 0 ||
msg.indexOf('Warning: React.createClass is no longer supported') >= 0 ||
msg.indexOf('Warning: PropTypes has been moved to a separate package') >= 0;
}
async function run(
onReady: () => ?any,
options: Object = {},
isInteractive?: boolean = false
) {
// first, run bsb
log.withTimestamp('Starting BuckleScript watcher for building Reason code');
let { bsbChildProcess } = await spawnBsbWatcherAsync();
log.withTimestamp(chalk.green('BuckleScript watcher started'));
let packagerReady = false;
let needsClear = false;
let logBuffer = '';
let progressBar;
const projectDir = process.cwd();
if (process.platform !== 'win32') {
const watchmanExists = spawn.sync('which', ['watchman']).status === 0;
if (process.platform === 'darwin' && !watchmanExists) {
const watcherDetails = spawn
.sync('sysctl', ['kern.maxfiles'])
.stdout.toString();
if (parseInt(watcherDetails.split(':')[1].trim()) < 5242880) {
log.withTimestamp(
`${chalk.red(`Unable to start server`)}
See https://git.io/v5vcn for more information, either install watchman or run the following snippet:
${chalk.cyan(` sudo sysctl -w kern.maxfiles=5242880
sudo sysctl -w kern.maxfilesperproc=524288`)}
`
);
process.exit(1);
}
} else if (!watchmanExists) {
try {
const watcherDetails = spawn
.sync('sysctl', ['fs.inotify.max_user_watches'])
.stdout.toString();
if (parseInt(watcherDetails.split('=')[1].trim()) < 12288) {
log.withTimestamp(
`${chalk.red(`Unable to start server`)}
See https://git.io/v5vcn for more information, either install watchman or run the following snippet:
${chalk.cyan(` sudo sysctl -w fs.inotify.max_user_instances=1024
sudo sysctl -w fs.inotify.max_user_watches=12288`)}`
);
process.exit(1);
}
} catch (e) {
// note(brentvatne): I'm not sure why stdout is null for some OS's
// https://github.com/react-community/create-react-native-app/issues/391
log.withTimestamp(
'Warning: Unable to run `sysctl fs.inotify.max_user_watches`. If you encounter issues, please refer to https://git.io/v5vcn'
);
}
}
}
const handleLogChunk = chunk => {
// pig, meet lipstick
// 1. https://github.com/facebook/react-native/issues/14620
// 2. https://github.com/facebook/react-native/issues/14610
// 3. https://github.com/react-community/create-react-native-app/issues/229#issuecomment-308654303
// @ide is investigating 3), the first two are upstream issues that will
// likely be resolved by others
if (shouldIgnoreMsg(chunk.msg)) {
return;
}
// we don't need to print the entire manifest when loading the app
if (chunk.msg.indexOf(' with appParams: ') >= 0) {
if (needsClear) {
// this is set when we previously encountered an error
// TODO clearConsole();
}
let devEnabled = chunk.msg.includes('__DEV__ === true');
log.withTimestamp(
`Running app on ${chunk.deviceName} in ${devEnabled ? 'development' : 'production'} mode\n`
);
return;
}
if (chunk.msg === 'Dependency graph loaded.') {
packagerReady = true;
onReady();
return;
}
if (packagerReady) {
const message = `${chunk.msg.trim()}\n`;
logWithLevel(chunk);
if (chunk.level === bunyan.ERROR) {
// if you run into a syntax error then we should clear log output on reload
needsClear = message.indexOf('SyntaxError') >= 0;
}
} else {
if (chunk.level >= bunyan.ERROR) {
log(chalk.yellow('***ERROR STARTING PACKAGER***'));
log(logBuffer);
log(chalk.red(chunk.msg));
logBuffer = '';
} else {
logBuffer += chunk.msg + '\n';
}
}
};
// Subscribe to packager/server logs
let packagerLogsStream = new PackagerLogsStream({
projectRoot: projectDir,
onStartBuildBundle: () => {
progressBar = new ProgressBar(
'Building JavaScript bundle [:bar] :percent',
{
total: 100,
clear: true,
complete: '=',
incomplete: ' ',
}
);
log.setBundleProgressBar(progressBar);
},
onProgressBuildBundle: percent => {
if (!progressBar || progressBar.complete) return;
let ticks = percent - progressBar.curr;
ticks > 0 && progressBar.tick(ticks);
},
onFinishBuildBundle: (err, startTime, endTime) => {
if (progressBar && !progressBar.complete) {
progressBar.tick(100 - progressBar.curr);
}
if (progressBar) {
log.setBundleProgressBar(null);
progressBar = null;
if (err) {
log.withTimestamp(chalk.red(`Failed building JavaScript bundle`));
} else {
let duration = endTime - startTime;
log.withTimestamp(
chalk.green(`Finished building JavaScript bundle in ${duration}ms`)
);
}
}
},
updateLogs: updater => {
let newLogChunks = updater([]);
if (progressBar) {
// Restarting watchman causes `onFinishBuildBundle` to not fire. Until
// this is handled upstream in xdl, reset progress bar with error here.
newLogChunks.forEach(chunk => {
if (chunk.msg === 'Restarted watchman.') {
progressBar.tick(100 - progressBar.curr);
log.setBundleProgressBar(null);
progressBar = null;
log.withTimestamp(chalk.red('Failed building JavaScript bundle'));
}
});
}
newLogChunks.map(handleLogChunk);
},
});
// Subscribe to device updates separately from packager/server updates
ProjectUtils.attachLoggerStream(projectDir, {
stream: {
write: chunk => {
if (chunk.tag === 'device') {
handleLogChunk(chunk);
}
},
},
type: 'raw',
});
installExitHooks(projectDir, isInteractive);
log.withTimestamp('Starting packager...');
Project.startAsync(projectDir, options).then(
() => {},
reason => {
log.withTimestamp(chalk.red(`Error starting packager: ${reason.stack}`));
process.exit(1);
}
);
}
const logStackTrace = (chunk, logFn, nestedLogFn, colorFn) => {
let traceInfo;
try {
traceInfo = JSON.parse(chunk.msg);
} catch (e) {
return logFn(colorFn(chunk.msg));
}
let { message, stack } = traceInfo;
logFn(colorFn(chalk.bold(message)));
const isLibraryFrame = line => {
return line.startsWith('node_modules');
};
let stackFrames = _.compact(stack.split('\n'));
let lastAppCodeFrameIndex = _.findLastIndex(stackFrames, line => {
return !isLibraryFrame(line);
});
let lastFrameIndexToLog = Math.min(
stackFrames.length - 1,
lastAppCodeFrameIndex + 2 // show max two more frames after last app code frame
);
let unloggedFrames = stackFrames.length - lastFrameIndexToLog;
// If we're only going to exclude one frame, just log them all
if (unloggedFrames === 1) {
lastFrameIndexToLog = stackFrames.length - 1;
unloggedFrames = 0;
}
for (let i = 0; i <= lastFrameIndexToLog; i++) {
let line = stackFrames[i];
if (!line) {
continue;
} else if (line.match(/react-native\/.*YellowBox.js/)) {
continue;
}
if (line.startsWith('node_modules')) {
nestedLogFn(colorFn('- ' + line));
} else {
nestedLogFn(colorFn('* ' + line));
}
}
if (unloggedFrames > 0) {
nestedLogFn(
colorFn(
`- ... ${unloggedFrames} more stack frames from framework internals`
)
);
}
};
const logWithLevel = chunk => {
if (!chunk.msg) {
return;
}
let colorFn = (str) => str;
if (chunk.level === bunyan.WARN) {
colorFn = chalk.yellow;
} else if (chunk.level === bunyan.ERROR) {
colorFn = chalk.red;
}
if (chunk.includesStack) {
logStackTrace(chunk, log.withTimestamp, log, colorFn);
} else {
logLines(chunk.msg, log.withTimestamp, colorFn);
}
};
const logLines = (msg, logFn, colorFn) => {
for (let line of msg.split('\n')) {
logFn(colorFn(line));
}
};
export default { run };