ws.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. 'use strict'
  2. var websocket = require('websocket-stream')
  3. var urlModule = require('url')
  4. var WSS_OPTIONS = [
  5. 'rejectUnauthorized',
  6. 'ca',
  7. 'cert',
  8. 'key',
  9. 'pfx',
  10. 'passphrase'
  11. ]
  12. var IS_BROWSER = process.title === 'browser'
  13. function buildUrl (opts, client) {
  14. var url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path
  15. if (typeof (opts.transformWsUrl) === 'function') {
  16. url = opts.transformWsUrl(url, opts, client)
  17. }
  18. return url
  19. }
  20. function setDefaultOpts (opts) {
  21. if (!opts.hostname) {
  22. opts.hostname = 'localhost'
  23. }
  24. if (!opts.port) {
  25. if (opts.protocol === 'wss') {
  26. opts.port = 443
  27. } else {
  28. opts.port = 80
  29. }
  30. }
  31. if (!opts.path) {
  32. opts.path = '/'
  33. }
  34. if (!opts.wsOptions) {
  35. opts.wsOptions = {}
  36. }
  37. if (!IS_BROWSER && opts.protocol === 'wss') {
  38. // Add cert/key/ca etc options
  39. WSS_OPTIONS.forEach(function (prop) {
  40. if (opts.hasOwnProperty(prop) && !opts.wsOptions.hasOwnProperty(prop)) {
  41. opts.wsOptions[prop] = opts[prop]
  42. }
  43. })
  44. }
  45. }
  46. function createWebSocket (client, opts) {
  47. var websocketSubProtocol =
  48. (opts.protocolId === 'MQIsdp') && (opts.protocolVersion === 3)
  49. ? 'mqttv3.1'
  50. : 'mqtt'
  51. setDefaultOpts(opts)
  52. var url = buildUrl(opts, client)
  53. return websocket(url, [websocketSubProtocol], opts.wsOptions)
  54. }
  55. function buildBuilder (client, opts) {
  56. return createWebSocket(client, opts)
  57. }
  58. function buildBuilderBrowser (client, opts) {
  59. if (!opts.hostname) {
  60. opts.hostname = opts.host
  61. }
  62. if (!opts.hostname) {
  63. // Throwing an error in a Web Worker if no `hostname` is given, because we
  64. // can not determine the `hostname` automatically. If connecting to
  65. // localhost, please supply the `hostname` as an argument.
  66. if (typeof (document) === 'undefined') {
  67. throw new Error('Could not determine host. Specify host manually.')
  68. }
  69. var parsed = urlModule.parse(document.URL)
  70. opts.hostname = parsed.hostname
  71. if (!opts.port) {
  72. opts.port = parsed.port
  73. }
  74. }
  75. return createWebSocket(client, opts)
  76. }
  77. if (IS_BROWSER) {
  78. module.exports = buildBuilderBrowser
  79. } else {
  80. module.exports = buildBuilder
  81. }