1import { Log } from '../log';
2import { CommandError } from '../utils/errors';
3import { resolvePortAsync } from '../utils/port';
4
5export interface BundlerProps {
6  /** Port to start the dev server on. */
7  port: number;
8  /** Skip opening the bundler from the native script. */
9  shouldStartBundler: boolean;
10}
11
12export async function resolveBundlerPropsAsync(
13  projectRoot: string,
14  options: {
15    port?: number;
16    bundler?: boolean;
17  }
18): Promise<BundlerProps> {
19  options.bundler = options.bundler ?? true;
20
21  if (
22    // If the user disables the bundler then they should not pass in the port property.
23    !options.bundler &&
24    options.port
25  ) {
26    throw new CommandError('BAD_ARGS', '--port and --no-bundler are mutually exclusive arguments');
27  }
28
29  // Resolve the port if the bundler is used.
30  let port = options.bundler
31    ? await resolvePortAsync(projectRoot, { reuseExistingPort: true, defaultPort: options.port })
32    : null;
33
34  // Skip bundling if the port is null -- meaning skip the bundler if the port is already running the app.
35  options.bundler = !!port;
36  if (!port) {
37    // any random number
38    port = 8081;
39  }
40  Log.debug(`Resolved port: ${port}, start dev server: ${options.bundler}`);
41
42  return {
43    shouldStartBundler: !!options.bundler,
44    port,
45  };
46}
47