You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.0 KiB

4 years ago
  1. 'use strict';
  2. /* eslint-disable
  3. class-methods-use-this,
  4. func-names
  5. */
  6. const sockjs = require('sockjs');
  7. const BaseServer = require('./BaseServer');
  8. // Workaround for sockjs@~0.3.19
  9. // sockjs will remove Origin header, however Origin header is required for checking host.
  10. // See https://github.com/webpack/webpack-dev-server/issues/1604 for more information
  11. {
  12. const SockjsSession = require('sockjs/lib/transport').Session;
  13. const decorateConnection = SockjsSession.prototype.decorateConnection;
  14. SockjsSession.prototype.decorateConnection = function(req) {
  15. decorateConnection.call(this, req);
  16. const connection = this.connection;
  17. if (
  18. connection.headers &&
  19. !('origin' in connection.headers) &&
  20. 'origin' in req.headers
  21. ) {
  22. connection.headers.origin = req.headers.origin;
  23. }
  24. };
  25. }
  26. module.exports = class SockJSServer extends BaseServer {
  27. // options has: error (function), debug (function), server (http/s server), path (string)
  28. constructor(server) {
  29. super(server);
  30. this.socket = sockjs.createServer({
  31. // Use provided up-to-date sockjs-client
  32. sockjs_url: '/__webpack_dev_server__/sockjs.bundle.js',
  33. // Limit useless logs
  34. log: (severity, line) => {
  35. if (severity === 'error') {
  36. this.server.log.error(line);
  37. } else {
  38. this.server.log.debug(line);
  39. }
  40. },
  41. });
  42. this.socket.installHandlers(this.server.listeningApp, {
  43. prefix: this.server.sockPath,
  44. });
  45. }
  46. send(connection, message) {
  47. // prevent cases where the server is trying to send data while connection is closing
  48. if (connection.readyState !== 1) {
  49. return;
  50. }
  51. connection.write(message);
  52. }
  53. close(connection) {
  54. connection.close();
  55. }
  56. // f should be passed the resulting connection and the connection headers
  57. onConnection(f) {
  58. this.socket.on('connection', (connection) => {
  59. f(connection, connection ? connection.headers : null);
  60. });
  61. }
  62. onConnectionClose(connection, f) {
  63. connection.on('close', f);
  64. }
  65. };