• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2021 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15const path = require('path');
16const http = require('http');
17const childProcess = require('child_process');
18
19module.exports = async function() {
20  // Start the local HTTP server.
21  const ROOT_DIR = path.dirname(path.dirname(__dirname));
22  const node = path.join(ROOT_DIR, 'ui', 'node');
23  const args = [
24    path.join(ROOT_DIR, 'ui', 'build.js'),
25    '--serve',
26    '--no-build',
27    '--out=.',
28  ];
29  const spwOpts = {stdio: ['ignore', 'inherit', 'inherit']};
30  const srvProc = childProcess.spawn(node, args, spwOpts);
31  global.__DEV_SERVER__ = srvProc;
32
33  // Wait for the HTTP server to be ready.
34  let attempts = 10;
35  for (; attempts > 0; attempts--) {
36    await new Promise((r) => setTimeout(r, 1000));
37    try {
38      await new Promise((resolve, reject) => {
39        const req = http.request('http://127.0.0.1:10000/frontend_bundle.js');
40        req.end();
41        req.on('error', (err) => reject(err));
42        req.on('finish', () => resolve());
43      });
44      break;
45    } catch (err) {
46      console.error('Waiting for HTTP server to come up', err.message);
47    }
48  }
49  if (attempts === 0) {
50    throw new Error('HTTP server didn\'t come up');
51  }
52  if (srvProc.exitCode !== null) {
53    throw new Error(
54        `The dev server unexpectedly exited, code=${srvProc.exitCode}`);
55  }
56};
57