1import { ServerRequest, ServerResponse } from './server.types';
2
3const debug = require('debug')(
4  'expo:start:server:middleware:metro-context-modules'
5) as typeof console.log;
6
7/**
8 * Source maps for `require.context` modules aren't supported in the Metro dev server
9 * we should intercept the request and return a noop response to prevent Chrome/Metro
10 * from erroring out.
11 */
12export class ContextModuleSourceMapsMiddleware {
13  getHandler() {
14    return (req: ServerRequest, res: ServerResponse, next: any) => {
15      if (!req?.url || (req.method !== 'GET' && req.method !== 'HEAD')) {
16        return next();
17      }
18
19      if (req.url.match(/%3Fctx=[\d\w\W]+\.map\?/)) {
20        debug('Skipping sourcemap request for context module %s', req.url);
21        // Return a noop response for the sourcemap
22        res.writeHead(200, {
23          'Content-Type': 'application/json',
24        });
25        res.end('{}');
26        return;
27      }
28
29      next();
30    };
31  }
32}
33