evalSourceMapMiddleware.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. 'use strict';
  8. function base64SourceMap(source) {
  9. const base64 = Buffer.from(JSON.stringify(source.map()), 'utf8').toString(
  10. 'base64'
  11. );
  12. return `data:application/json;charset=utf-8;base64,${base64}`;
  13. }
  14. function getSourceById(server, id) {
  15. const module = Array.from(server._stats.compilation.modules).find(
  16. (m) => server._stats.compilation.chunkGraph.getModuleId(m) == id,
  17. );
  18. return module.originalSource();
  19. }
  20. /*
  21. * Middleware responsible for retrieving a generated source
  22. * Receives a webpack internal url: "webpack-internal:///<module-id>"
  23. * Returns a generated source: "<source-text><sourceMappingURL><sourceURL>"
  24. *
  25. * Based on EvalSourceMapDevToolModuleTemplatePlugin.js
  26. */
  27. module.exports = function createEvalSourceMapMiddleware(server) {
  28. return function handleWebpackInternalMiddleware(req, res, next) {
  29. if (req.url.startsWith('/__get-internal-source')) {
  30. const fileName = req.query.fileName;
  31. const id = fileName.match(/webpack-internal:\/\/\/(.+)/)[1];
  32. if (!id || !server._stats) {
  33. next();
  34. }
  35. const source = getSourceById(server, id);
  36. const sourceMapURL = `//# sourceMappingURL=${base64SourceMap(source)}`;
  37. const sourceURL = `//# sourceURL=webpack-internal:///${module.id}`;
  38. res.end(`${source.source()}\n${sourceMapURL}\n${sourceURL}`);
  39. } else {
  40. next();
  41. }
  42. };
  43. };