1import { MessageSocket } from '@expo/dev-server';
2import assert from 'assert';
3import openBrowserAsync from 'better-opn';
4import resolveFrom from 'resolve-from';
5
6import { APISettings } from '../../api/settings';
7import * as Log from '../../log';
8import { FileNotifier } from '../../utils/FileNotifier';
9import { resolveWithTimeout } from '../../utils/delay';
10import { env } from '../../utils/env';
11import { CommandError } from '../../utils/errors';
12import {
13  BaseOpenInCustomProps,
14  BaseResolveDeviceProps,
15  PlatformManager,
16} from '../platforms/PlatformManager';
17import { AsyncNgrok } from './AsyncNgrok';
18import { DevelopmentSession } from './DevelopmentSession';
19import { CreateURLOptions, UrlCreator } from './UrlCreator';
20
21export type ServerLike = {
22  close(callback?: (err?: Error) => void): void;
23};
24
25export type DevServerInstance = {
26  /** Bundler dev server instance. */
27  server: ServerLike;
28  /** Dev server URL location properties. */
29  location: {
30    url: string;
31    port: number;
32    protocol: 'http' | 'https';
33    host?: string;
34  };
35  /** Additional middleware that's attached to the `server`. */
36  middleware: any;
37  /** Message socket for communicating with the runtime. */
38  messageSocket: MessageSocket;
39};
40
41export interface BundlerStartOptions {
42  /** Should the dev server use `https` protocol. */
43  https?: boolean;
44  /** Should start the dev servers in development mode (minify). */
45  mode?: 'development' | 'production';
46  /** Is dev client enabled. */
47  devClient?: boolean;
48  /** Should run dev servers with clean caches. */
49  resetDevServer?: boolean;
50  /** Which manifest type to serve. */
51  forceManifestType?: 'expo-updates' | 'classic';
52  /** Code signing private key path (defaults to same directory as certificate) */
53  privateKeyPath?: string;
54
55  /** Max amount of workers (threads) to use with Metro bundler, defaults to undefined for max workers. */
56  maxWorkers?: number;
57  /** Port to start the dev server on. */
58  port?: number;
59
60  /** Should start a headless dev server e.g. mock representation to approximate info from a server running in a different process. */
61  headless?: boolean;
62  /** Should instruct the bundler to create minified bundles. */
63  minify?: boolean;
64
65  // Webpack options
66  /** Should modify and create PWA icons. */
67  isImageEditingEnabled?: boolean;
68
69  location: CreateURLOptions;
70}
71
72const PLATFORM_MANAGERS = {
73  simulator: () =>
74    require('../platforms/ios/ApplePlatformManager')
75      .ApplePlatformManager as typeof import('../platforms/ios/ApplePlatformManager').ApplePlatformManager,
76  emulator: () =>
77    require('../platforms/android/AndroidPlatformManager')
78      .AndroidPlatformManager as typeof import('../platforms/android/AndroidPlatformManager').AndroidPlatformManager,
79};
80
81const MIDDLEWARES = {
82  classic: () =>
83    require('./middleware/ClassicManifestMiddleware')
84      .ClassicManifestMiddleware as typeof import('./middleware/ClassicManifestMiddleware').ClassicManifestMiddleware,
85  'expo-updates': () =>
86    require('./middleware/ExpoGoManifestHandlerMiddleware')
87      .ExpoGoManifestHandlerMiddleware as typeof import('./middleware/ExpoGoManifestHandlerMiddleware').ExpoGoManifestHandlerMiddleware,
88};
89
90export abstract class BundlerDevServer {
91  /** Name of the bundler. */
92  abstract get name(): string;
93
94  /** Ngrok instance for managing tunnel connections. */
95  protected ngrok: AsyncNgrok | null = null;
96  /** Interfaces with the Expo 'Development Session' API. */
97  protected devSession: DevelopmentSession | null = null;
98  /** Http server and related info. */
99  protected instance: DevServerInstance | null = null;
100  /** Native platform interfaces for opening projects.  */
101  private platformManagers: Record<string, PlatformManager<any>> = {};
102  /** Manages the creation of dev server URLs. */
103  protected urlCreator?: UrlCreator | null = null;
104
105  constructor(
106    /** Project root folder. */
107    public projectRoot: string,
108    // TODO: Replace with custom scheme maybe...
109    public isDevClient?: boolean
110  ) {}
111
112  protected setInstance(instance: DevServerInstance) {
113    this.instance = instance;
114  }
115
116  /** Get the manifest middleware function. */
117  protected async getManifestMiddlewareAsync(
118    options: Pick<
119      BundlerStartOptions,
120      'minify' | 'mode' | 'forceManifestType' | 'privateKeyPath'
121    > = {}
122  ) {
123    const manifestType = options.forceManifestType || 'classic';
124    assert(manifestType in MIDDLEWARES, `Manifest middleware for type '${manifestType}' not found`);
125    const Middleware = MIDDLEWARES[manifestType]();
126
127    const urlCreator = this.getUrlCreator();
128    const middleware = new Middleware(this.projectRoot, {
129      constructUrl: urlCreator.constructUrl.bind(urlCreator),
130      mode: options.mode,
131      minify: options.minify,
132      isNativeWebpack: this.name === 'webpack' && this.isTargetingNative(),
133      privateKeyPath: options.privateKeyPath,
134    });
135    return middleware.getHandler();
136  }
137
138  /** Start the dev server using settings defined in the start command. */
139  public async startAsync(options: BundlerStartOptions): Promise<DevServerInstance> {
140    await this.stopAsync();
141
142    let instance: DevServerInstance;
143    if (options.headless) {
144      instance = await this.startHeadlessAsync(options);
145    } else {
146      instance = await this.startImplementationAsync(options);
147    }
148
149    this.setInstance(instance);
150    await this.postStartAsync(options);
151    return instance;
152  }
153
154  protected abstract startImplementationAsync(
155    options: BundlerStartOptions
156  ): Promise<DevServerInstance>;
157
158  /**
159   * Creates a mock server representation that can be used to estimate URLs for a server started in another process.
160   * This is used for the run commands where you can reuse the server from a previous run.
161   */
162  private async startHeadlessAsync(options: BundlerStartOptions): Promise<DevServerInstance> {
163    if (!options.port)
164      throw new CommandError('HEADLESS_SERVER', 'headless dev server requires a port option');
165    this.urlCreator = this.getUrlCreator(options);
166
167    return {
168      // Create a mock server
169      server: {
170        close: () => {
171          this.instance = null;
172        },
173      },
174      location: {
175        // The port is the main thing we want to send back.
176        port: options.port,
177        // localhost isn't always correct.
178        host: 'localhost',
179        // http is the only supported protocol on native.
180        url: `http://localhost:${options.port}`,
181        protocol: 'http',
182      },
183      middleware: {},
184      messageSocket: {
185        broadcast: () => {
186          throw new CommandError('HEADLESS_SERVER', 'Cannot broadcast messages to headless server');
187        },
188      },
189    };
190  }
191
192  protected async postStartAsync(options: BundlerStartOptions) {
193    if (options.location.hostType === 'tunnel' && !APISettings.isOffline) {
194      await this._startTunnelAsync();
195    }
196    await this.startDevSessionAsync();
197
198    this.watchConfig();
199  }
200
201  protected abstract getConfigModuleIds(): string[];
202
203  protected watchConfig() {
204    const notifier = new FileNotifier(this.projectRoot, this.getConfigModuleIds());
205    notifier.startObserving();
206  }
207
208  /** Create ngrok instance and start the tunnel server. Exposed for testing. */
209  public async _startTunnelAsync(): Promise<AsyncNgrok | null> {
210    const port = this.getInstance()?.location.port;
211    if (!port) return null;
212    Log.debug('[ngrok] connect to port: ' + port);
213    this.ngrok = new AsyncNgrok(this.projectRoot, port);
214    await this.ngrok.startAsync();
215    return this.ngrok;
216  }
217
218  protected async startDevSessionAsync() {
219    // This is used to make Expo Go open the project in either Expo Go, or the web browser.
220    // Must come after ngrok (`startTunnelAsync`) setup.
221
222    if (this.devSession) {
223      this.devSession.stopNotifying();
224    }
225
226    this.devSession = new DevelopmentSession(
227      this.projectRoot,
228      // This URL will be used on external devices so the computer IP won't be relevant.
229      this.isTargetingNative()
230        ? this.getNativeRuntimeUrl()
231        : this.getDevServerUrl({ hostType: 'localhost' })
232    );
233
234    await this.devSession.startAsync({
235      runtime: this.isTargetingNative() ? 'native' : 'web',
236    });
237  }
238
239  public isTargetingNative() {
240    // Temporary hack while we implement multi-bundler dev server proxy.
241    return true;
242  }
243
244  public isTargetingWeb() {
245    return false;
246  }
247
248  /**
249   * Sends a message over web sockets to any connected device,
250   * does nothing when the dev server is not running.
251   *
252   * @param method name of the command. In RN projects `reload`, and `devMenu` are available. In Expo Go, `sendDevCommand` is available.
253   * @param params
254   */
255  public broadcastMessage(
256    method: 'reload' | 'devMenu' | 'sendDevCommand',
257    params?: Record<string, any>
258  ) {
259    this.getInstance()?.messageSocket.broadcast(method, params);
260  }
261
262  /** Get the running dev server instance. */
263  public getInstance() {
264    return this.instance;
265  }
266
267  /** Stop the running dev server instance. */
268  async stopAsync() {
269    // Stop the dev session timer and tell Expo API to remove dev session.
270    await this.devSession?.closeAsync();
271
272    // Stop ngrok if running.
273    await this.ngrok?.stopAsync().catch((e) => {
274      Log.error(`Error stopping ngrok:`);
275      Log.exception(e);
276    });
277
278    return resolveWithTimeout(
279      () =>
280        new Promise<void>((resolve, reject) => {
281          // Close the server.
282          Log.debug(`Stopping dev server (bundler: ${this.name})`);
283
284          if (this.instance?.server) {
285            this.instance.server.close((error) => {
286              Log.debug(`Stopped dev server (bundler: ${this.name})`);
287              this.instance = null;
288              if (error) {
289                reject(error);
290              } else {
291                resolve();
292              }
293            });
294          } else {
295            Log.debug(`Stopped dev server (bundler: ${this.name})`);
296            this.instance = null;
297            resolve();
298          }
299        }),
300      {
301        // NOTE(Bacon): Metro dev server doesn't seem to be closing in time.
302        timeout: 1000,
303        errorMessage: `Timeout waiting for '${this.name}' dev server to close`,
304      }
305    );
306  }
307
308  protected getUrlCreator(options: Partial<Pick<BundlerStartOptions, 'port' | 'location'>> = {}) {
309    if (!this.urlCreator) {
310      assert(options?.port, 'Dev server instance not found');
311      this.urlCreator = new UrlCreator(options.location, {
312        port: options.port,
313        getTunnelUrl: this.getTunnelUrl.bind(this),
314      });
315    }
316    return this.urlCreator;
317  }
318
319  public getNativeRuntimeUrl(opts: Partial<CreateURLOptions> = {}) {
320    return this.isDevClient
321      ? this.getUrlCreator().constructDevClientUrl(opts) ?? this.getDevServerUrl()
322      : this.getUrlCreator().constructUrl({ ...opts, scheme: 'exp' });
323  }
324
325  /** Get the URL for the running instance of the dev server. */
326  public getDevServerUrl(options: { hostType?: 'localhost' } = {}): string | null {
327    const instance = this.getInstance();
328    if (!instance?.location) {
329      return null;
330    }
331    const { location } = instance;
332    if (options.hostType === 'localhost') {
333      return `${location.protocol}://localhost:${location.port}`;
334    }
335    return location.url ?? null;
336  }
337
338  /** Get the tunnel URL from ngrok. */
339  public getTunnelUrl(): string | null {
340    return this.ngrok?.getActiveUrl() ?? null;
341  }
342
343  /** Open the dev server in a runtime. */
344  public async openPlatformAsync(
345    launchTarget: keyof typeof PLATFORM_MANAGERS | 'desktop',
346    resolver: BaseResolveDeviceProps<any> = {}
347  ) {
348    if (launchTarget === 'desktop') {
349      const url = this.getDevServerUrl({ hostType: 'localhost' });
350      await openBrowserAsync(url!);
351      return { url };
352    }
353
354    const runtime = this.isTargetingNative() ? (this.isDevClient ? 'custom' : 'expo') : 'web';
355    const manager = await this.getPlatformManagerAsync(launchTarget);
356    return manager.openAsync({ runtime }, resolver);
357  }
358
359  /** Open the dev server in a runtime. */
360  public async openCustomRuntimeAsync(
361    launchTarget: keyof typeof PLATFORM_MANAGERS,
362    launchProps: Partial<BaseOpenInCustomProps> = {},
363    resolver: BaseResolveDeviceProps<any> = {}
364  ) {
365    const runtime = this.isTargetingNative() ? (this.isDevClient ? 'custom' : 'expo') : 'web';
366    if (runtime !== 'custom') {
367      throw new CommandError(
368        `dev server cannot open custom runtimes either because it does not target native platforms or because it is not targeting dev clients. (target: ${runtime})`
369      );
370    }
371
372    const manager = await this.getPlatformManagerAsync(launchTarget);
373    return manager.openAsync({ runtime: 'custom', props: launchProps }, resolver);
374  }
375
376  /** Should use the interstitial page for selecting which runtime to use. */
377  protected shouldUseInterstitialPage(): boolean {
378    return (
379      env.EXPO_ENABLE_INTERSTITIAL_PAGE &&
380      // Checks if dev client is installed.
381      !!resolveFrom.silent(this.projectRoot, 'expo-dev-launcher')
382    );
383  }
384
385  /** Get the URL for opening in Expo Go. */
386  protected getExpoGoUrl(platform: keyof typeof PLATFORM_MANAGERS): string | null {
387    if (this.shouldUseInterstitialPage()) {
388      const loadingUrl =
389        platform === 'emulator'
390          ? this.urlCreator?.constructLoadingUrl({}, 'android')
391          : this.urlCreator?.constructLoadingUrl({ hostType: 'localhost' }, 'ios');
392      return loadingUrl ?? null;
393    }
394
395    return this.urlCreator?.constructUrl({ scheme: 'exp' }) ?? null;
396  }
397
398  protected async getPlatformManagerAsync(platform: keyof typeof PLATFORM_MANAGERS) {
399    if (!this.platformManagers[platform]) {
400      const Manager = PLATFORM_MANAGERS[platform]();
401      const port = this.getInstance()?.location.port;
402      if (!port || !this.urlCreator) {
403        throw new CommandError(
404          'DEV_SERVER',
405          'Cannot interact with native platforms until dev server has started'
406        );
407      }
408      this.platformManagers[platform] = new Manager(this.projectRoot, port, {
409        getCustomRuntimeUrl: this.urlCreator.constructDevClientUrl.bind(this.urlCreator),
410        getExpoGoUrl: this.getExpoGoUrl.bind(this, platform),
411        getDevServerUrl: this.getDevServerUrl.bind(this, { hostType: 'localhost' }),
412      });
413    }
414    return this.platformManagers[platform];
415  }
416}
417