ui.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. const { log, error, openBrowser } = require('@vue/cli-shared-utils')
  2. const { portfinder, server } = require('@vue/cli-ui/server')
  3. const shortid = require('shortid')
  4. function simpleCorsValidation (allowedHost) {
  5. return function (req, socket) {
  6. const { host, origin } = req.headers
  7. // maybe we should just use strict string equal?
  8. const hostRegExp = new RegExp(`^https?://(${host}|${allowedHost}|localhost)(:\\d+)?$`)
  9. if (!origin || !hostRegExp.test(origin)) {
  10. socket.destroy()
  11. }
  12. }
  13. }
  14. async function ui (options = {}, context = process.cwd()) {
  15. const host = options.host || 'localhost'
  16. let port = options.port
  17. if (!port) {
  18. port = await portfinder.getPortPromise()
  19. }
  20. // Config
  21. process.env.VUE_APP_CLI_UI_URL = ''
  22. // Optimize express
  23. const nodeEnv = process.env.NODE_ENV
  24. process.env.NODE_ENV = 'production'
  25. // Dev mode
  26. if (options.dev) {
  27. process.env.VUE_APP_CLI_UI_DEBUG = true
  28. }
  29. if (!process.env.VUE_CLI_IPC) {
  30. // Prevent IPC id conflicts
  31. process.env.VUE_CLI_IPC = `vue-cli-${shortid()}`
  32. }
  33. if (!options.quiet) log(`🚀 Starting GUI...`)
  34. const opts = {
  35. host,
  36. port,
  37. graphqlPath: '/graphql',
  38. subscriptionsPath: '/graphql',
  39. enableMocks: false,
  40. enableEngine: false,
  41. cors: {
  42. origin: host
  43. },
  44. timeout: 1000000,
  45. quiet: true,
  46. paths: {
  47. typeDefs: require.resolve('@vue/cli-ui/apollo-server/type-defs.js'),
  48. resolvers: require.resolve('@vue/cli-ui/apollo-server/resolvers.js'),
  49. context: require.resolve('@vue/cli-ui/apollo-server/context.js'),
  50. pubsub: require.resolve('@vue/cli-ui/apollo-server/pubsub.js'),
  51. server: require.resolve('@vue/cli-ui/apollo-server/server.js'),
  52. directives: require.resolve('@vue/cli-ui/apollo-server/directives.js')
  53. }
  54. }
  55. const { httpServer } = server(opts, () => {
  56. // Reset for yarn/npm to work correctly
  57. if (typeof nodeEnv === 'undefined') {
  58. delete process.env.NODE_ENV
  59. } else {
  60. process.env.NODE_ENV = nodeEnv
  61. }
  62. // Open browser
  63. const url = `http://${host}:${port}`
  64. if (!options.quiet) log(`🌠 Ready on ${url}`)
  65. if (options.headless) {
  66. console.log(port)
  67. } else {
  68. openBrowser(url)
  69. }
  70. })
  71. httpServer.on('upgrade', simpleCorsValidation(host))
  72. }
  73. module.exports = (...args) => {
  74. return ui(...args).catch(err => {
  75. error(err)
  76. if (!process.env.VUE_CLI_TEST) {
  77. process.exit(1)
  78. }
  79. })
  80. }