1import { parsePlatformHeader } from './resolvePlatform';
2import { ServerNext, ServerRequest, ServerResponse } from './server.types';
3
4/**
5 * Create a web-only middleware which redirects to the index middleware without losing the path component.
6 * This is useful for things like React Navigation which need to render the index.html and then direct the user in-memory.
7 */
8export class HistoryFallbackMiddleware {
9  constructor(
10    private indexMiddleware: (
11      req: ServerRequest,
12      res: ServerResponse,
13      next: ServerNext
14    ) => Promise<void>
15  ) {}
16  getHandler() {
17    return (req: ServerRequest, res: ServerResponse, next: any) => {
18      const platform = parsePlatformHeader(req);
19
20      if (!platform || platform === 'web') {
21        // Redirect unknown to the manifest handler while preserving the path.
22        // This implements the HTML5 history fallback API.
23        return this.indexMiddleware(req, res, next);
24      }
25
26      return next();
27    };
28  }
29}
30