1import { ExpoConfig, ExpoGoConfig, getConfig, ProjectConfig } from '@expo/config';
2import findWorkspaceRoot from 'find-yarn-workspace-root';
3import path from 'path';
4import { resolve } from 'url';
5
6import * as Log from '../../../log';
7import { env } from '../../../utils/env';
8import { stripExtension } from '../../../utils/url';
9import * as ProjectDevices from '../../project/devices';
10import { UrlCreator } from '../UrlCreator';
11import { getPlatformBundlers } from '../platformBundlers';
12import { createTemplateHtmlFromExpoConfigAsync } from '../webTemplate';
13import { ExpoMiddleware } from './ExpoMiddleware';
14import { resolveGoogleServicesFile, resolveManifestAssets } from './resolveAssets';
15import { resolveAbsoluteEntryPoint } from './resolveEntryPoint';
16import { parsePlatformHeader, RuntimePlatform } from './resolvePlatform';
17import { ServerHeaders, ServerNext, ServerRequest, ServerResponse } from './server.types';
18
19const debug = require('debug')('expo:start:server:middleware:manifest') as typeof console.log;
20
21/** Wraps `findWorkspaceRoot` and guards against having an empty `package.json` file in an upper directory. */
22export function getWorkspaceRoot(projectRoot: string): string | null {
23  try {
24    return findWorkspaceRoot(projectRoot);
25  } catch (error: any) {
26    if (error.message.includes('Unexpected end of JSON input')) {
27      return null;
28    }
29    throw error;
30  }
31}
32
33export function getEntryWithServerRoot(
34  projectRoot: string,
35  projectConfig: ProjectConfig,
36  platform: string
37) {
38  return path.relative(
39    getMetroServerRoot(projectRoot),
40    resolveAbsoluteEntryPoint(projectRoot, platform, projectConfig)
41  );
42}
43
44export function getMetroServerRoot(projectRoot: string) {
45  if (env.EXPO_USE_METRO_WORKSPACE_ROOT) {
46    return getWorkspaceRoot(projectRoot) ?? projectRoot;
47  }
48
49  return projectRoot;
50}
51
52/** Info about the computer hosting the dev server. */
53export interface HostInfo {
54  host: string;
55  server: 'expo';
56  serverVersion: string;
57  serverDriver: string | null;
58  serverOS: NodeJS.Platform;
59  serverOSVersion: string;
60}
61
62/** Parsed values from the supported request headers. */
63export interface ManifestRequestInfo {
64  /** Should return the signed manifest. */
65  acceptSignature: boolean;
66  /** Platform to serve. */
67  platform: RuntimePlatform;
68  /** Requested host name. */
69  hostname?: string | null;
70}
71
72/** Project related info. */
73export type ResponseProjectSettings = {
74  expoGoConfig: ExpoGoConfig;
75  hostUri: string;
76  bundleUrl: string;
77  exp: ExpoConfig;
78};
79
80export const DEVELOPER_TOOL = 'expo-cli';
81
82export type ManifestMiddlewareOptions = {
83  /** Should start the dev servers in development mode (minify). */
84  mode?: 'development' | 'production';
85  /** Should instruct the bundler to create minified bundles. */
86  minify?: boolean;
87  constructUrl: UrlCreator['constructUrl'];
88  isNativeWebpack?: boolean;
89  privateKeyPath?: string;
90};
91
92/** Base middleware creator for serving the Expo manifest (like the index.html but for native runtimes). */
93export abstract class ManifestMiddleware<
94  TManifestRequestInfo extends ManifestRequestInfo
95> extends ExpoMiddleware {
96  private initialProjectConfig: ProjectConfig;
97
98  constructor(protected projectRoot: string, protected options: ManifestMiddlewareOptions) {
99    super(
100      projectRoot,
101      /**
102       * Only support `/`, `/manifest`, `/index.exp` for the manifest middleware.
103       */
104      ['/', '/manifest', '/index.exp']
105    );
106    this.initialProjectConfig = getConfig(projectRoot);
107  }
108
109  /** Exposed for testing. */
110  public async _resolveProjectSettingsAsync({
111    platform,
112    hostname,
113  }: Pick<TManifestRequestInfo, 'hostname' | 'platform'>): Promise<ResponseProjectSettings> {
114    // Read the config
115    const projectConfig = getConfig(this.projectRoot);
116
117    // Read from headers
118    const mainModuleName = this.resolveMainModuleName(projectConfig, platform);
119
120    // Create the manifest and set fields within it
121    const expoGoConfig = this.getExpoGoConfig({
122      mainModuleName,
123      hostname,
124    });
125
126    const hostUri = this.options.constructUrl({ scheme: '', hostname });
127
128    const bundleUrl = this._getBundleUrl({
129      platform,
130      mainModuleName,
131      hostname,
132    });
133
134    // Resolve all assets and set them on the manifest as URLs
135    await this.mutateManifestWithAssetsAsync(projectConfig.exp, bundleUrl);
136
137    return {
138      expoGoConfig,
139      hostUri,
140      bundleUrl,
141      exp: projectConfig.exp,
142    };
143  }
144
145  /** Get the main entry module ID (file) relative to the project root. */
146  private resolveMainModuleName(projectConfig: ProjectConfig, platform: string): string {
147    let entryPoint = getEntryWithServerRoot(this.projectRoot, projectConfig, platform);
148
149    debug(`Resolved entry point: ${entryPoint} (project root: ${this.projectRoot})`);
150
151    // NOTE(Bacon): Webpack is currently hardcoded to index.bundle on native
152    // in the future (TODO) we should move this logic into a Webpack plugin and use
153    // a generated file name like we do on web.
154    // const server = getDefaultDevServer();
155    // // TODO: Move this into BundlerDevServer and read this info from self.
156    // const isNativeWebpack = server instanceof WebpackBundlerDevServer && server.isTargetingNative();
157    if (this.options.isNativeWebpack) {
158      entryPoint = 'index.js';
159    }
160
161    return stripExtension(entryPoint, 'js');
162  }
163
164  /** Parse request headers into options. */
165  public abstract getParsedHeaders(req: ServerRequest): TManifestRequestInfo;
166
167  /** Store device IDs that were sent in the request headers. */
168  private async saveDevicesAsync(req: ServerRequest) {
169    const deviceIds = req.headers?.['expo-dev-client-id'];
170    if (deviceIds) {
171      await ProjectDevices.saveDevicesAsync(this.projectRoot, deviceIds).catch((e) =>
172        Log.exception(e)
173      );
174    }
175  }
176
177  /** Create the bundle URL (points to the single JS entry file). Exposed for testing. */
178  public _getBundleUrl({
179    platform,
180    mainModuleName,
181    hostname,
182  }: {
183    platform: string;
184    hostname?: string | null;
185    mainModuleName: string;
186  }): string {
187    const path = this._getBundleUrlPath({ platform, mainModuleName });
188
189    return (
190      this.options.constructUrl({
191        scheme: 'http',
192        // hostType: this.options.location.hostType,
193        hostname,
194      }) + path
195    );
196  }
197
198  public _getBundleUrlPath({
199    platform,
200    mainModuleName,
201  }: {
202    platform: string;
203    mainModuleName: string;
204  }): string {
205    const queryParams = new URLSearchParams({
206      platform: encodeURIComponent(platform),
207      dev: String(this.options.mode !== 'production'),
208      // TODO: Is this still needed?
209      hot: String(false),
210    });
211
212    if (this.options.minify) {
213      queryParams.append('minify', String(this.options.minify));
214    }
215
216    return `/${encodeURI(mainModuleName)}.bundle?${queryParams.toString()}`;
217  }
218
219  /** Log telemetry. */
220  protected abstract trackManifest(version?: string): void;
221
222  /** Get the manifest response to return to the runtime. This file contains info regarding where the assets can be loaded from. Exposed for testing. */
223  public abstract _getManifestResponseAsync(options: TManifestRequestInfo): Promise<{
224    body: string;
225    version: string;
226    headers: ServerHeaders;
227  }>;
228
229  private getExpoGoConfig({
230    mainModuleName,
231    hostname,
232  }: {
233    mainModuleName: string;
234    hostname?: string | null;
235  }): ExpoGoConfig {
236    return {
237      // localhost:19000
238      debuggerHost: this.options.constructUrl({ scheme: '', hostname }),
239      // http://localhost:19000/logs -- used to send logs to the CLI for displaying in the terminal.
240      // This is deprecated in favor of the WebSocket connection setup in Metro.
241      logUrl: this.options.constructUrl({ scheme: 'http', hostname }) + '/logs',
242      // Required for Expo Go to function.
243      developer: {
244        tool: DEVELOPER_TOOL,
245        projectRoot: this.projectRoot,
246      },
247      packagerOpts: {
248        // Required for dev client.
249        dev: this.options.mode !== 'production',
250      },
251      // Indicates the name of the main bundle.
252      mainModuleName,
253      // Add this string to make Flipper register React Native / Metro as "running".
254      // Can be tested by running:
255      // `METRO_SERVER_PORT=19000 open -a flipper.app`
256      // Where 19000 is the port where the Expo project is being hosted.
257      __flipperHack: 'React Native packager is running',
258    };
259  }
260
261  /** Resolve all assets and set them on the manifest as URLs */
262  private async mutateManifestWithAssetsAsync(manifest: ExpoConfig, bundleUrl: string) {
263    await resolveManifestAssets(this.projectRoot, {
264      manifest,
265      resolver: async (path) => {
266        if (this.options.isNativeWebpack) {
267          // When using our custom dev server, just do assets normally
268          // without the `assets/` subpath redirect.
269          return resolve(bundleUrl!.match(/^https?:\/\/.*?\//)![0], path);
270        }
271        return bundleUrl!.match(/^https?:\/\/.*?\//)![0] + 'assets/' + path;
272      },
273    });
274    // The server normally inserts this but if we're offline we'll do it here
275    await resolveGoogleServicesFile(this.projectRoot, manifest);
276  }
277
278  public getWebBundleUrl() {
279    const platform = 'web';
280    // Read from headers
281    const mainModuleName = this.resolveMainModuleName(this.initialProjectConfig, platform);
282    return this._getBundleUrlPath({
283      platform,
284      mainModuleName,
285    });
286  }
287
288  /**
289   * Web platforms should create an index.html response using the same script resolution as native.
290   *
291   * Instead of adding a `bundleUrl` to a `manifest.json` (native) we'll add a `<script src="">`
292   * to an `index.html`, this enables the web platform to load JavaScript from the server.
293   */
294  private async handleWebRequestAsync(req: ServerRequest, res: ServerResponse) {
295    // Read from headers
296    const bundleUrl = this.getWebBundleUrl();
297
298    res.setHeader('Content-Type', 'text/html');
299
300    res.end(
301      await createTemplateHtmlFromExpoConfigAsync(this.projectRoot, {
302        exp: this.initialProjectConfig.exp,
303        scripts: [bundleUrl],
304      })
305    );
306  }
307
308  /** Exposed for testing. */
309  async checkBrowserRequestAsync(req: ServerRequest, res: ServerResponse, next: ServerNext) {
310    // Read the config
311    const bundlers = getPlatformBundlers(this.initialProjectConfig.exp);
312    if (bundlers.web === 'metro') {
313      // NOTE(EvanBacon): This effectively disables the safety check we do on custom runtimes to ensure
314      // the `expo-platform` header is included. When `web.bundler=web`, if the user has non-standard Expo
315      // code loading then they'll get a web bundle without a clear assertion of platform support.
316      const platform = parsePlatformHeader(req);
317      // On web, serve the public folder
318      if (!platform || platform === 'web') {
319        // Skip the spa-styled index.html when static generation is enabled.
320        if (env.EXPO_USE_STATIC) {
321          next();
322          return true;
323        } else {
324          await this.handleWebRequestAsync(req, res);
325          return true;
326        }
327      }
328    }
329    return false;
330  }
331
332  async handleRequestAsync(
333    req: ServerRequest,
334    res: ServerResponse,
335    next: ServerNext
336  ): Promise<void> {
337    // First check for standard JavaScript runtimes (aka legacy browsers like Chrome).
338    if (await this.checkBrowserRequestAsync(req, res, next)) {
339      return;
340    }
341
342    // Save device IDs for dev client.
343    await this.saveDevicesAsync(req);
344
345    // Read from headers
346    const options = this.getParsedHeaders(req);
347    const { body, version, headers } = await this._getManifestResponseAsync(options);
348    for (const [headerName, headerValue] of headers) {
349      res.setHeader(headerName, headerValue);
350    }
351    res.end(body);
352
353    // Log analytics
354    this.trackManifest(version ?? null);
355  }
356}
357