prepareURLs.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 at
  6. * https://github.com/facebookincubator/create-react-app/blob/master/LICENSE
  7. */
  8. const url = require('url')
  9. const chalk = require('chalk')
  10. const address = require('address')
  11. module.exports = function prepareUrls (protocol, host, port, pathname = '/') {
  12. const formatUrl = hostname =>
  13. url.format({
  14. protocol,
  15. hostname,
  16. port,
  17. pathname
  18. })
  19. const prettyPrintUrl = hostname =>
  20. url.format({
  21. protocol,
  22. hostname,
  23. port: chalk.bold(port),
  24. pathname
  25. })
  26. const isUnspecifiedHost = host === '0.0.0.0' || host === '::'
  27. let prettyHost, lanUrlForConfig
  28. let lanUrlForTerminal = chalk.gray('unavailable')
  29. if (isUnspecifiedHost) {
  30. prettyHost = 'localhost'
  31. try {
  32. // This can only return an IPv4 address
  33. lanUrlForConfig = address.ip()
  34. if (lanUrlForConfig) {
  35. // Check if the address is a private ip
  36. // https://en.wikipedia.org/wiki/Private_network#Private_IPv4_address_spaces
  37. if (
  38. /^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(
  39. lanUrlForConfig
  40. )
  41. ) {
  42. // Address is private, format it for later use
  43. lanUrlForTerminal = prettyPrintUrl(lanUrlForConfig)
  44. } else {
  45. // Address is not private, so we will discard it
  46. lanUrlForConfig = undefined
  47. }
  48. }
  49. } catch (_e) {
  50. // ignored
  51. }
  52. } else {
  53. prettyHost = host
  54. lanUrlForConfig = host
  55. lanUrlForTerminal = prettyPrintUrl(lanUrlForConfig)
  56. }
  57. const localUrlForTerminal = prettyPrintUrl(prettyHost)
  58. const localUrlForBrowser = formatUrl(prettyHost)
  59. return {
  60. lanUrlForConfig,
  61. lanUrlForTerminal,
  62. localUrlForTerminal,
  63. localUrlForBrowser
  64. }
  65. }