-
Notifications
You must be signed in to change notification settings - Fork 4
/
executor.ts
1267 lines (1146 loc) · 44.6 KB
/
executor.ts
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { exec, spawn } from 'child_process';
import cluster from 'cluster';
import * as cors from 'connect-cors';
import * as crypto from 'crypto';
import Debug from 'debug';
import * as detectPort from 'detect-port';
import * as fs from 'fs';
import * as http from 'http';
import * as ip from 'ip';
import * as isDocker from 'is-docker';
import * as _ from 'lodash';
import minilog from 'minilog';
import * as mkdirp from 'mkdirp';
import * as path from 'path';
import * as serveStatic from 'serve-static';
import { fromStringWithSourceMap, SourceListMap } from 'source-list-map';
import * as url from 'url';
import { ConcatSource, RawSource } from 'webpack-sources';
import { Builder, Builders } from './Builder';
import getDllName from './getDllName';
import liveReloadMiddleware from './plugins/react-native/liveReloadMiddleware';
import symbolicateMiddleware from './plugins/react-native/symbolicateMiddleware';
import { hookAsync, hookSync } from './webpackHooks';
import Zen from './Zen';
const LARIX_DLL_VERSION = 3;
const BACKEND_CHANGE_MSG = 'backend_change';
const debug = Debug('zen');
const expoPorts = {};
const clientStats = { all: false, assets: true, warnings: true, errors: true, errorDetails: false };
const zenLogger = minilog('zen');
process.on('uncaughtException', ex => {
zenLogger.error(ex);
});
process.on('unhandledRejection', reason => {
zenLogger.error(reason);
});
const __WINDOWS__ = /^win/.test(process.platform);
let server;
let startBackend = false;
let lastExitCode = 0;
let nodeDebugOpt;
process.on('exit', () => {
if (server) {
server.kill('SIGTERM');
}
});
const spawnServer = (cwd, args: any[], options: { nodeDebugger: boolean; serverPath: string }, logger) => {
server = spawn('node', [...args], {
stdio: [0, 1, 2],
cwd,
env: { ...process.env, LAST_EXIT_CODE: `${lastExitCode}` }
});
logger.info(`Spawning ${['node', ...args].join(' ')}, env: { LAST_EXIT_CODE: ${lastExitCode} }`);
server.on('exit', code => {
lastExitCode = code;
if (code === 250) {
// App requested full reload
startBackend = true;
}
logger.info(`Backend stopped, exit code:`, code);
server = undefined;
// eslint-disable-next-line @typescript-eslint/no-use-before-define
runServer(cwd, options.serverPath, options.nodeDebugger, logger);
});
};
const runServer = (cwd, serverPath, nodeDebugger, logger) => {
if (!fs.existsSync(serverPath)) {
throw new Error(`Backend doesn't exist at ${serverPath}, exiting`);
}
if (startBackend) {
startBackend = false;
logger.debug('Starting backend');
if (!nodeDebugOpt) {
if (!nodeDebugger) {
// disables node debugger when the option was set to false
spawnServer(cwd, [serverPath], { serverPath, nodeDebugger }, logger);
} else {
exec('node -v', (error, stdout, stderr) => {
if (error) {
zenLogger.error(error);
process.exit(1);
}
const nodeVersion = stdout.match(/^v([0-9]+)\.([0-9]+)\.([0-9]+)/);
const nodeMajor = parseInt(nodeVersion[1], 10);
const nodeMinor = parseInt(nodeVersion[2], 10);
nodeDebugOpt = nodeMajor >= 6 || (nodeMajor === 6 && nodeMinor >= 9) ? '--inspect' : '--debug';
detectPort(9229).then(debugPort => {
// Bind the port to public ip in order to allow users to access the port for debugging when using docker.
const debugHost = isDocker() ? '0.0.0.0:' : '';
spawnServer(
cwd,
[nodeDebugOpt + '=' + debugHost + debugPort, serverPath],
{ serverPath, nodeDebugger },
logger
);
});
});
}
} else {
spawnServer(cwd, [nodeDebugOpt, serverPath], { serverPath, nodeDebugger }, logger);
}
}
};
const webpackReporter = (zen: Zen, builder: Builder, outputPath: string, log, err?, stats?) => {
if (err) {
log.error(err.stack);
throw new Error('Build error');
}
if (stats) {
const str = stats.toString(builder.config.stats);
if (str.length > 0) {
log.info(str);
}
if (builder.writeStats) {
mkdirp.sync(outputPath);
fs.writeFileSync(path.join(outputPath, 'stats.json'), JSON.stringify(stats.toJson(clientStats)));
}
}
if (!zen.watch && cluster.isWorker) {
const exitCode = stats.compilation.errors && stats.compilation.errors.length ? 1 : 0;
log.info(`Build process finished, exit code: ${exitCode}`);
process.exit(exitCode);
}
};
const frontendVirtualModules = [];
class MobileAssetsPlugin {
public vendorAssets: any;
constructor(vendorAssets?) {
this.vendorAssets = vendorAssets || [];
}
public apply(compiler) {
hookAsync(compiler, 'after-compile', (compilation, callback) => {
compilation.chunks.forEach(chunk => {
chunk.files.forEach(file => {
if (file.endsWith('.bundle')) {
const assets = this.vendorAssets;
compilation.modules.forEach(module => {
if (module._asset) {
assets.push(module._asset);
}
});
compilation.assets[file.replace('.bundle', '') + '.assets'] = new RawSource(JSON.stringify(assets));
}
});
});
callback();
});
}
}
const reactNativeImpl = {
community: {
messageSocket: '@react-native-community/cli/build/commands/server/messageSocket',
webSocketProxy: '@react-native-community/cli/build/commands/server/webSocketProxy',
inspectorProxy: undefined,
copyToClipBoardMiddleware: '@react-native-community/cli/build/commands/server/middleware/copyToClipBoardMiddleware',
cpuProfilerMiddleware: undefined,
getDevToolsMiddleware: '@react-native-community/cli/build/commands/server/middleware/getDevToolsMiddleware',
heapCaptureMiddleware: undefined,
indexPageMiddleware: '@react-native-community/cli/build/commands/server/middleware/indexPage',
loadRawBodyMiddleware: '@react-native-community/cli/build/commands/server/middleware/loadRawBodyMiddleware',
openStackFrameInEditorMiddleware:
'@react-native-community/cli/build/commands/server/middleware/openStackFrameInEditorMiddleware',
statusPageMiddleware: '@react-native-community/cli/build/commands/server/middleware/statusPageMiddleware',
systraceProfileMiddleware: '@react-native-community/cli/build/commands/server/middleware/systraceProfileMiddleware',
unless: '@react-native-community/cli/build/commands/server/middleware/unless'
},
original: {
messageSocket: 'react-native/local-cli/server/util/messageSocket',
webSocketProxy: 'react-native/local-cli/server/util/webSocketProxy',
inspectorProxy: 'react-native/local-cli/server/util/inspectorProxy',
copyToClipBoardMiddleware: 'react-native/local-cli/server/middleware/copyToClipBoardMiddleware',
cpuProfilerMiddleware: 'react-native/local-cli/server/middleware/cpuProfilerMiddleware',
getDevToolsMiddleware: 'react-native/local-cli/server/middleware/getDevToolsMiddleware',
heapCaptureMiddleware: 'react-native/local-cli/server/middleware/heapCaptureMiddleware',
indexPageMiddleware: 'react-native/local-cli/server/middleware/indexPage',
loadRawBodyMiddleware: 'react-native/local-cli/server/middleware/loadRawBodyMiddleware',
openStackFrameInEditorMiddleware: 'react-native/local-cli/server/middleware/openStackFrameInEditorMiddleware',
statusPageMiddleware: 'react-native/local-cli/server/middleware/statusPageMiddleware',
systraceProfileMiddleware: 'react-native/local-cli/server/middleware/systraceProfileMiddleware',
unless: 'react-native/local-cli/server/middleware/unless'
}
};
const debugMiddleware = (req, res, next) => {
if (['/debug', '/debug/bundles'].indexOf(req.path) >= 0) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<!doctype html><div><a href="/debug/bundles">Cached Bundles</a></div>');
} else {
next();
}
};
const startReactNativeServer = async (builder: Builder, zen: Zen, logger, applyMiddleware: (app) => void) => {
let wsProxy;
let ms;
let inspectorProxy;
const connect = builder.require('connect');
const compression = builder.require('compression');
const httpProxyMiddleware = builder.require('http-proxy-middleware');
const mime = builder.require('mime', builder.require.resolve('webpack-dev-middleware'));
const app = connect();
const serverInstance = http.createServer(app);
mime.define({ 'application/javascript': ['bundle'] }, true);
mime.define({ 'application/json': ['assets'] }, true);
const isOriginal = builder.require.probe(reactNativeImpl.original.messageSocket);
const rnRequire = isOriginal ? builder.require : name => builder.require(name).default;
const rnImpl = isOriginal ? reactNativeImpl.original : reactNativeImpl.community;
const messageSocket = rnRequire(rnImpl.messageSocket);
const webSocketProxy = rnRequire(rnImpl.webSocketProxy);
try {
if (rnImpl.inspectorProxy) {
const InspectorProxy = rnRequire(rnImpl.inspectorProxy);
inspectorProxy = new InspectorProxy();
}
} catch (ignored) {
// continue, regardless of error
}
const copyToClipBoardMiddleware = rnRequire(rnImpl.copyToClipBoardMiddleware);
let cpuProfilerMiddleware;
try {
if (rnImpl.cpuProfilerMiddleware) {
cpuProfilerMiddleware = rnRequire(rnImpl.cpuProfilerMiddleware);
}
} catch (ignored) {
// continue, regardless of error
}
const getDevToolsMiddleware = rnRequire(rnImpl.getDevToolsMiddleware);
let heapCaptureMiddleware;
try {
if (rnImpl.heapCaptureMiddleware) {
heapCaptureMiddleware = rnRequire(rnImpl.heapCaptureMiddleware);
}
} catch (ignored) {
// continue, regardless of error
}
const indexPageMiddleware = rnRequire(rnImpl.indexPageMiddleware);
const loadRawBodyMiddleware = rnRequire(rnImpl.loadRawBodyMiddleware);
const openStackFrameInEditorMiddleware = rnRequire(rnImpl.openStackFrameInEditorMiddleware);
const statusPageMiddleware = rnRequire(rnImpl.statusPageMiddleware);
const systraceProfileMiddleware = rnRequire(rnImpl.systraceProfileMiddleware);
const unless = rnRequire(rnImpl.unless);
const args = {
port: builder.config.devServer.port,
projectRoots: [path.resolve('.')]
};
app
.use(cors())
.use(loadRawBodyMiddleware)
.use((req, res, next) => {
req.path = req.url.split('?')[0];
if (req.path === '/symbolicate') {
req.rawBody = req.rawBody.replace(/index\.mobile\.delta/g, 'index.mobile.bundle');
}
const origWriteHead = res.writeHead;
res.writeHead = (...parms) => {
const code = parms[0];
if (code === 404) {
logger.error(`404 at URL ${req.url}`);
}
origWriteHead.apply(res, parms);
};
if (req.path !== '/onchange') {
if (!zen.dev) {
logger.debug(`Prod mobile packager request: http://localhost:${builder.config.devServer.port}${req.url}`);
} else if (debug.enabled) {
logger.debug(`Dev mobile packager request: ${debug.enabled ? req.url : req.path}`);
}
}
next();
})
.use(compression());
app.use('/assets', serveStatic(path.join(builder.require.cwd, '.expo', builder.stack.platform)));
if (builder.child) {
app.use(serveStatic(builder.child.config.output.path));
}
app
.use((req, res, next) => {
if (req.path === '/debugger-ui/deltaUrlToBlobUrl.js') {
debug(`serving monkey patched deltaUrlToBlobUrl`);
res.writeHead(200, { 'Content-Type': 'application/javascript' });
res.end(`window.deltaUrlToBlobUrl = function(url) { return url.replace('.delta', '.bundle'); }`);
} else {
next();
}
})
.use(
'/debugger-ui',
serveStatic(
isOriginal
? path.join(
path.dirname(builder.require.resolve('react-native/package.json')),
'/local-cli/server/util/debugger-ui'
)
: path.join(
path.dirname(builder.require.resolve('@react-native-community/cli/package.json')),
'/build/commands/server/debugger-ui'
)
)
)
.use(getDevToolsMiddleware(args, () => wsProxy && wsProxy.isChromeConnected()))
.use(getDevToolsMiddleware(args, () => ms && ms.isChromeConnected()));
app
.use(openStackFrameInEditorMiddleware(args))
.use(copyToClipBoardMiddleware)
.use(statusPageMiddleware)
.use(systraceProfileMiddleware)
.use(indexPageMiddleware)
.use(debugMiddleware);
if (heapCaptureMiddleware) {
app.use(heapCaptureMiddleware);
}
if (cpuProfilerMiddleware) {
app.use(cpuProfilerMiddleware);
}
if (inspectorProxy) {
app.use(unless('/inspector', inspectorProxy.processRequest.bind(inspectorProxy)));
}
app.use((req, res, next) => {
if (builder.stack.platform !== 'web') {
// Workaround for Expo Client bug in parsing Content-Type header with charset
const origSetHeader = res.setHeader;
res.setHeader = (key, value) => {
let val = value;
if (key === 'Content-Type' && value.indexOf('application/javascript') >= 0) {
val = value.split(';')[0];
}
origSetHeader.call(res, key, val);
};
}
next();
});
applyMiddleware(app);
if (builder.config.devServer.proxy) {
Object.keys(builder.config.devServer.proxy).forEach(key => {
app.use(httpProxyMiddleware(key, builder.config.devServer.proxy[key]));
});
}
serverInstance.timeout = 0;
serverInstance.keepAliveTimeout = 0;
return new Promise(resolve =>
serverInstance.listen(builder.config.devServer.port, () => {
if (builder.platform !== 'web') {
wsProxy = webSocketProxy.attachToServer(serverInstance, '/debugger-proxy');
ms = messageSocket.attachToServer(serverInstance, '/message');
webSocketProxy.attachToServer(serverInstance, '/devtools');
if (inspectorProxy) {
inspectorProxy.attachToServer(serverInstance, '/inspector');
}
}
resolve(serverInstance);
})
);
};
const startWebpackDevServer = (hasBackend: boolean, zen: Zen, builder: Builder, reporter, logger) => {
const webpack = builder.require('webpack');
const config = builder.config;
const platform = builder.stack.platform;
const configOutputPath = config.output.path;
config.output.path = '/';
let vendorHashesJson;
let vendorSourceListMap;
let vendorSource;
let vendorMap;
if (builder.webpackDll && builder.child) {
const name = getDllName(builder);
const jsonPath = path.join(builder.dllBuildDir, `${name}_dll.json`);
const json = JSON.parse(fs.readFileSync(path.resolve('./' + jsonPath)).toString());
config.plugins.push(
new webpack.DllReferencePlugin({
context: process.cwd(),
manifest: json
})
);
vendorHashesJson = JSON.parse(
fs.readFileSync(path.join(builder.dllBuildDir, `${name}_dll_hashes.json`)).toString()
);
vendorSource = new RawSource(
fs.readFileSync(path.join(builder.dllBuildDir, vendorHashesJson.name)).toString() + '\n'
);
if (platform !== 'web') {
const vendorAssets = JSON.parse(
fs.readFileSync(path.join(builder.dllBuildDir, vendorHashesJson.name + '.assets')).toString()
);
config.plugins.push(new MobileAssetsPlugin(vendorAssets));
}
if (builder.sourceMap) {
vendorMap = new RawSource(
fs.readFileSync(path.join(builder.dllBuildDir, vendorHashesJson.name + '.map')).toString()
);
vendorSourceListMap = fromStringWithSourceMap(vendorSource.source(), JSON.parse(vendorMap.source()));
}
}
const compiler = webpack(config);
let awaitedAlready = false;
hookAsync(compiler, 'after-emit', (compilation, callback) => {
if (!awaitedAlready) {
if (hasBackend || builder.waitOn) {
let waitOnUrls;
const backendOption = builder.backendUrl || builder.backendUrl;
if (backendOption) {
const { protocol, hostname, port } = url.parse(backendOption.replace('{ip}', ip.address()));
waitOnUrls = [`tcp:${hostname}:${port || (protocol === 'https:' ? 443 : 80)}`];
} else {
waitOnUrls = builder.waitOn ? [].concat(builder.waitOn) : undefined;
}
if (waitOnUrls && waitOnUrls.length) {
logger.debug(`waiting for ${waitOnUrls}`);
const waitStart = Date.now();
const waitNotifier = setInterval(() => {
logger.debug(`still waiting for ${waitOnUrls} after ${Date.now() - waitStart}ms...`);
}, 10000);
const waitOn = builder.require('wait-on');
waitOn({ resources: waitOnUrls }, err => {
clearInterval(waitNotifier);
awaitedAlready = true;
if (err) {
logger.error(err);
} else {
logger.debug('Backend has been started, resuming webpack dev server...');
}
callback();
});
} else {
awaitedAlready = true;
callback();
}
} else {
callback();
}
} else {
callback();
}
});
if (builder.webpackDll && builder.child && platform !== 'web') {
hookAsync(compiler, 'after-compile', (compilation, callback) => {
compilation.chunks.forEach(chunk => {
chunk.files.forEach(file => {
if (file.endsWith('.bundle')) {
if (builder.sourceMap) {
const sourceListMap = new SourceListMap();
sourceListMap.add(vendorSourceListMap);
sourceListMap.add(
fromStringWithSourceMap(
compilation.assets[file].source(),
JSON.parse(compilation.assets[file + '.map'].source())
)
);
const sourceAndMap = sourceListMap.toStringWithSourceMap({ file });
compilation.assets[file] = new RawSource(sourceAndMap.source);
compilation.assets[file + '.map'] = new RawSource(JSON.stringify(sourceAndMap.map));
} else {
compilation.assets[file] = new ConcatSource(vendorSource, compilation.assets[file]);
}
}
});
});
callback();
});
}
if (builder.webpackDll && builder.child && platform === 'web' && !builder.ssr) {
hookAsync(compiler, 'after-compile', (compilation, callback) => {
compilation.assets[vendorHashesJson.name] = vendorSource;
if (builder.sourceMap) {
compilation.assets[vendorHashesJson.name + '.map'] = vendorMap;
}
callback();
});
hookSync(compiler, 'compilation', compilation => {
hookAsync(compilation, 'html-webpack-plugin-before-html-processing', (htmlPluginData, callback) => {
htmlPluginData.assets.js.unshift('/' + vendorHashesJson.name);
callback(null, htmlPluginData);
});
});
}
let frontendFirstStart = true;
hookSync(compiler, 'done', stats => {
// if (stats.compilation.errors && stats.compilation.errors.length) {
// stats.compilation.errors.forEach(error => logger.error(error.message));
// }
const dir = configOutputPath;
mkdirp.sync(dir);
if (stats.compilation.assets['assets.json']) {
const assetsMap = JSON.parse(stats.compilation.assets['assets.json'].source());
const prefix = compiler.outputPath;
_.each(stats.toJson(clientStats).assetsByChunkName, (assets, bundle) => {
const bundleJs = assets.constructor === Array ? assets[0] : assets;
assetsMap[`${bundle}.js`] = prefix + bundleJs;
if (assets.length > 1) {
assetsMap[`${bundle}.js.map`] = prefix + `${bundleJs}.map`;
}
});
if (builder.webpackDll) {
assetsMap['vendor.js'] = prefix + vendorHashesJson.name;
}
fs.writeFileSync(path.join(dir, 'assets.json'), JSON.stringify(assetsMap));
}
if (stats.compilation.assets['loadable-stats.json']) {
fs.writeFileSync(path.join(dir, 'loadable-stats.json'), stats.compilation.assets['loadable-stats.json'].source());
}
if (frontendFirstStart) {
frontendFirstStart = false;
try {
if (builder.stack.hasAny('react-native')) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
startExpoProject(zen, builder, logger);
}
} catch (e) {
logger.error(e.stack);
}
}
});
let serverPromise;
if (platform === 'web') {
const WebpackDevServer = builder.require('webpack-dev-server');
const serverInstance = new WebpackDevServer(compiler, {
...config.devServer,
reporter: (opts1, opts2) => {
const opts = opts2 || opts1;
const { state, stats } = opts;
if (state) {
logger.debug('bundle is now VALID.');
} else {
logger.debug('bundle is now INVALID.');
}
reporter(null, stats);
}
});
serverPromise = new Promise(resolve => {
serverInstance.listen(builder.config.devServer.port, () => {
resolve(serverInstance);
});
});
} else {
const webpackHotMiddleware = builder.require('webpack-hot-middleware');
const webpackDevMiddleware = builder.require('webpack-dev-middleware');
// Workaround for bug in Haul /symbolicate under Windows
compiler.options.output.path = path.sep;
const devMiddleware = webpackDevMiddleware(
compiler,
_.merge({}, builder.config.devServer, {
reporter(mwOpts, { state, stats }) {
if (state) {
logger.info('bundle is now VALID.');
} else {
logger.info('bundle is now INVALID.');
}
reporter(null, stats);
}
})
);
serverPromise = startReactNativeServer(builder, zen, logger, app => {
app.use(liveReloadMiddleware(compiler)).use(symbolicateMiddleware(compiler, logger));
app.use((req, res, next) => {
if (builder.stack.platform !== 'web') {
// Workaround for Expo Client bug in parsing Content-Type header with charset
const origSetHeader = res.setHeader;
res.setHeader = (key, value) => {
let val = value;
if (key === 'Content-Type' && value.indexOf('application/javascript') >= 0) {
val = value.split(';')[0];
}
origSetHeader.call(res, key, val);
};
const query = url.parse(req.url, true).query;
const urlPlatform = query && query.platform;
if (urlPlatform && urlPlatform !== builder.stack.platform) {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end(`Serving '${builder.stack.platform}' bundles, but got request from '${urlPlatform}'`);
return;
}
}
return devMiddleware(req, res, next);
});
app.use(webpackHotMiddleware(compiler, { log: false }));
});
}
serverPromise.then(() => {
logger.info(`Webpack dev server listening on http://localhost:${config.devServer.port}`);
});
};
const startClientWebpack = (hasBackend, zen, builder) => {
const webpack = builder.require('webpack');
const config = builder.config;
const configOutputPath = config.output.path;
const VirtualModules = builder.require('webpack-virtual-modules');
const clientVirtualModules = new VirtualModules({
[path.join(builder.projectRoot, 'node_modules', 'backend_reload.js')]: ''
});
config.plugins.push(clientVirtualModules);
frontendVirtualModules.push(clientVirtualModules);
const logger = minilog(`${config.name}-webpack`);
if (builder.silent) {
(logger as any).suggest.deny(/.*/, 'debug');
}
try {
const reporter = (...args) => webpackReporter(zen, builder, configOutputPath, logger, ...args);
if (zen.watch) {
startWebpackDevServer(hasBackend, zen, builder, reporter, logger);
} else {
if (builder.stack.platform !== 'web') {
config.plugins.push(new MobileAssetsPlugin());
}
const compiler = webpack(config);
compiler.run(reporter);
}
} catch (err) {
logger.error(err.message, err.stack);
}
};
let backendReloadCount = 0;
const increaseBackendReloadCount = builder => {
backendReloadCount++;
for (const virtualModules of frontendVirtualModules) {
virtualModules.writeModule(
path.join(builder.projectRoot, 'node_modules', 'backend_reload.js'),
`var count = ${backendReloadCount};\n`
);
}
};
const startServerWebpack = (zen, builder) => {
const config = builder.config;
const logger = minilog(`${config.name}-webpack`);
if (builder.silent) {
(logger as any).suggest.deny(/.*/, 'debug');
}
try {
const webpack = builder.require('webpack');
const reporter = (...args) => webpackReporter(zen, builder, config.output.path, logger, ...args);
const compiler = webpack(config);
if (zen.watch) {
hookSync(compiler, 'done', stats => {
if (stats.compilation.errors && stats.compilation.errors.length) {
stats.compilation.errors.forEach(error => logger.error(error.message));
}
});
hookSync(compiler, 'compilation', compilation => {
hookSync(compilation, 'after-optimize-assets', assets => {
// Patch webpack-generated original source files path, by stripping hash after filename
const mapKey = _.findKey(assets, (v, k) => k.endsWith('.map'));
if (mapKey) {
const srcMap = JSON.parse(assets[mapKey]._value);
for (const idx of Object.keys(srcMap.sources)) {
srcMap.sources[idx] = srcMap.sources[idx].split(';')[0];
}
assets[mapKey]._value = JSON.stringify(srcMap);
}
});
});
compiler.watch({}, reporter);
hookSync(compiler, 'done', stats => {
if (!stats.compilation.errors.length) {
const { output } = config;
startBackend = true;
if (server) {
if (!__WINDOWS__) {
server.kill('SIGUSR2');
}
if (builder.frontendRefreshOnBackendChange) {
for (const module of stats.compilation.modules) {
if (module.built && module.resource && module.resource.indexOf('server') >= 0) {
// Force front-end refresh on back-end change
logger.debug('Force front-end current page refresh, due to change in backend at:', module.resource);
process.send({ cmd: BACKEND_CHANGE_MSG });
break;
}
}
}
} else {
runServer(builder.require.cwd, path.join(output.path, 'index.js'), builder.nodeDebugger, logger);
}
}
});
} else {
compiler.run(reporter);
}
} catch (err) {
logger.error(err.message, err.stack);
}
};
const deviceLoggers = {};
const mirrorExpoLogs = (builder: Builder, projectRoot: string) => {
const bunyan = builder.require('@expo/bunyan');
if (!bunyan._patched) {
deviceLoggers[projectRoot] = minilog('expo-for-' + builder.name);
const origCreate = bunyan.createLogger;
bunyan.createLogger = opts => {
const logger = origCreate.call(bunyan, opts);
const origChild = logger.child;
logger.child = (...args) => {
const child = origChild.apply(logger, args);
const patched = { ...child };
for (const name of ['info', 'debug', 'warn', 'error']) {
patched[name] = (...logArgs) => {
const [obj, msg] = logArgs;
if (!obj.issueCleared) {
let message;
try {
const json = JSON.parse(msg);
message = json.stack ? json.message + '\n' + json.stack : json.message;
} catch (e) {
// continue, regardless of error
}
message = message || msg || obj;
deviceLoggers[projectRoot][name].apply(deviceLoggers[projectRoot], [message]);
child[name].call(child, logArgs);
}
};
}
return patched;
};
return logger;
};
bunyan._patched = true;
}
};
const startExpoServer = async (zen: Zen, builder: Builder, projectRoot: string, packagerPort) => {
const { Config, Project, ProjectSettings } = builder.require('xdl');
mirrorExpoLogs(builder, projectRoot);
Config.validation.reactNativeVersionWarnings = false;
Config.developerTool = 'crna';
Config.offline = true;
await Project.startExpoServerAsync(projectRoot);
await ProjectSettings.setPackagerInfoAsync(projectRoot, {
packagerPort
});
};
const launchExpoApp = async (builder: Builder, platform: string, logger) => {
const { UrlUtils, Android, Simulator } = builder.require('xdl');
const qr = builder.require('qrcode-terminal');
const projectRoot = path.join(builder.require.cwd, '.expo', platform);
const address = await UrlUtils.constructManifestUrlAsync(projectRoot);
const localAddress = await UrlUtils.constructManifestUrlAsync(projectRoot, {
hostType: 'localhost'
});
logger.info(`Expo address for ${platform}, Local: ${localAddress}, LAN: ${address}`);
logger.info(
"To open this app on your phone scan this QR code in Expo Client (if it doesn't get started automatically)"
);
qr.generate(address, code => {
logger.info('\n' + code);
});
if (!isDocker()) {
if (platform === 'android' || platform === 'all') {
const { success, error } = await Android.openProjectAsync(projectRoot);
if (!success) {
logger.error(error.message);
}
}
if (platform === 'ios' || platform === 'all') {
const { success, msg } = await Simulator.openUrlInSimulatorSafeAsync(localAddress);
if (!success) {
logger.error('Failed to start Simulator: ', msg);
}
}
}
};
const copyExpoImage = (cwd: string, expoDir: string, appJson: any, keyPath: string) => {
const imagePath: string = _.get(appJson, keyPath);
if (imagePath) {
const absImagePath = path.join(cwd, imagePath);
fs.writeFileSync(path.join(expoDir, path.basename(absImagePath)), fs.readFileSync(absImagePath));
_.set(appJson, keyPath, path.basename(absImagePath));
}
};
const setupExpoDir = (zen: Zen, builder: Builder, dir, platform) => {
const reactNativeDir = path.join(dir, 'node_modules', 'react-native');
mkdirp.sync(path.join(reactNativeDir, 'local-cli'));
fs.writeFileSync(
path.join(reactNativeDir, 'package.json'),
fs.readFileSync(builder.require.resolve('react-native/package.json'))
);
fs.writeFileSync(path.join(reactNativeDir, 'local-cli/cli.js'), '');
const reactDir = path.join(dir, 'node_modules', 'react');
mkdirp.sync(reactDir);
fs.writeFileSync(path.join(reactDir, 'package.json'), fs.readFileSync(builder.require.resolve('react/package.json')));
const pkg = JSON.parse(fs.readFileSync(builder.require.resolve('./package.json')).toString());
const origDeps = pkg.dependencies;
delete pkg.devDependencies;
pkg.dependencies = { react: origDeps.react, 'react-native': origDeps['react-native'] };
if (platform !== 'all') {
pkg.name = pkg.name + '-' + platform;
}
pkg.main = `index.mobile`;
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify(pkg, null, 2));
const appJson = JSON.parse(fs.readFileSync(builder.require.resolve('./app.json'), 'utf8'));
[
'expo.icon',
'expo.ios.icon',
'expo.android.icon',
'expo.splash.image',
'expo.ios.splash.image',
'expo.ios.splash.tabletImage',
'expo.android.splash.ldpi',
'expo.android.splash.mdpi',
'expo.android.splash.hdpi',
'expo.android.splash.xhdpi',
'expo.android.splash.xxhdpi',
'expo.android.splash.xxxhdpi'
].forEach(keyPath => copyExpoImage(builder.require.cwd, dir, appJson, keyPath));
fs.writeFileSync(path.join(dir, 'app.json'), JSON.stringify(appJson, null, 2));
let expRcJson: any = {};
try {
expRcJson = JSON.parse(fs.readFileSync(builder.require.resolve('./.exprc'), 'utf8'));
} catch (e) {
// continue, regardless of error
}
if (platform !== 'all') {
expRcJson.manifestPort = expoPorts[platform];
}
fs.writeFileSync(path.join(dir, '.exprc'), JSON.stringify(expRcJson, null, 2));
};
const startExpoProject = async (zen: Zen, builder: Builder, logger: any) => {
const platform = builder.stack.platform;
try {
const projectRoot = path.join(builder.require.cwd, '.expo', platform);
setupExpoDir(zen, builder, projectRoot, platform);
await startExpoServer(zen, builder, projectRoot, builder.config.devServer.port);
await launchExpoApp(builder, platform, logger);
} catch (e) {
logger.error(e.stack);
}
};
const isDllValid = (zen, builder, logger): boolean => {
const name = getDllName(builder);
try {
const hashesPath = path.join(builder.dllBuildDir, `${name}_dll_hashes.json`);
if (!fs.existsSync(hashesPath)) {
return false;
}
const relMeta = JSON.parse(fs.readFileSync(hashesPath).toString());
if (LARIX_DLL_VERSION !== relMeta.version) {
return false;
}
if (!fs.existsSync(path.join(builder.dllBuildDir, relMeta.name))) {
return false;
}
if (builder.sourceMap && !fs.existsSync(path.join(builder.dllBuildDir, relMeta.name + '.map'))) {
return false;
}
if (!_.isEqual(relMeta.modules, builder.child.config.entry.vendor)) {
return false;
}
const json = JSON.parse(fs.readFileSync(path.join(builder.dllBuildDir, `${name}_dll.json`)).toString());
for (const entryFilename of Object.keys(json.content)) {
const filename = entryFilename.split('!').pop();
if (filename.indexOf(' ') < 0 && filename.indexOf('@virtual') < 0) {
if (!fs.existsSync(filename)) {
logger.warn(`${name} DLL need to be regenerated, file: ${filename} is missing.`);
return false;
}
const hash = crypto
.createHash('md5')
.update(fs.readFileSync(filename))
.digest('hex');
if (relMeta.hashes[filename] !== hash) {
logger.warn(`Hash for ${name} DLL file ${filename} has changed, need to rebuild it`);
return false;
}
}
}
return true;
} catch (e) {
logger.warn(`Error checking vendor bundle ${name}, regenerating it...`, e);
return false;
}
};
const buildDll = (zen: Zen, builder: Builder) => {
const webpack = builder.require('webpack');
const config = builder.child.config;
return new Promise(done => {
const name = getDllName(builder);
const logger = minilog(`${config.name}-webpack`);
if (builder.silent) {
(logger as any).suggest.deny(/.*/, 'debug');
}
const reporter = (...args) => webpackReporter(zen, builder, config.output.path, logger, ...args);
if (!isDllValid(zen, builder, logger)) {
logger.debug(`Generating ${name} DLL bundle with modules:\n${JSON.stringify(config.entry.vendor)}`);
mkdirp.sync(builder.dllBuildDir);
const compiler = webpack(config);
hookSync(compiler, 'done', stats => {
try {
const json = JSON.parse(fs.readFileSync(path.join(builder.dllBuildDir, `${name}_dll.json`)).toString());
const vendorKey = _.findKey(
stats.compilation.assets,
(v, key) => key.startsWith('vendor') && key.endsWith('_dll.js')
);
const assets = [];
stats.compilation.modules.forEach(module => {
if (module._asset) {
assets.push(module._asset);
}
});
fs.writeFileSync(path.join(builder.dllBuildDir, `${vendorKey}.assets`), JSON.stringify(assets));
const meta = { name: vendorKey, hashes: {}, modules: config.entry.vendor, version: LARIX_DLL_VERSION };
for (const filename of Object.keys(json.content)) {
if (filename.indexOf(' ') < 0 && filename.indexOf('@virtual') < 0) {
meta.hashes[filename] = crypto
.createHash('md5')
.update(fs.readFileSync(filename.split('!').pop()))
.digest('hex');
}
}
fs.writeFileSync(path.join(builder.dllBuildDir, `${name}_dll_hashes.json`), JSON.stringify(meta));
fs.writeFileSync(path.join(builder.dllBuildDir, `${name}_dll.json`), JSON.stringify(json));
} catch (e) {