import type { StartOptions } from './cli-commands' import type { ResolvedDevToolsConfig } from './config' import { DEVTOOLS_MOUNT_PATH } from '@vitejs/devtools-kit/constants' import { normalizeHttpServerUrl } from 'devframe/internal' import { colors as c } from 'devframe/utils/colors' import { open } from 'devframe/utils/open' import { MARK_NODE } from './constants' export async function startDevTools( options: StartOptions, resolvedConfig?: ResolvedDevToolsConfig, ) { const { host } = options const { getPort } = await import('devframe/utils/get-port') const port = await getPort({ host, port: options.port == null ? undefined : +options.port, portRange: [9999, 15000], }) const { startStandaloneDevTools } = await import('./standalone') const { createDevToolsHub } = await import('./server') const devtools = await startStandaloneDevTools({ config: options.config, cwd: options.root, resolvedConfig, }) // Standalone has no shared HTTP server for the WS upgrade, so the hub opens // a side-car WS server (advertised in `__connection.json`). Its middleware // answers the whole `/__devtools/` surface — the branded hub-ui viewer, the // connection meta, and the client bundles. const { middleware } = await createDevToolsHub({ context: devtools.context, host, renderers: resolvedConfig?.config.renderers, ui: resolvedConfig?.config, }) const { createServer } = await import('node:http') // Nuxt's generated tsconfigs map `h3` to v1 types. // The standalone server uses the H3 v2 API from `h3/node`. const { defineHandler, H3, sendRedirect, toNodeHandler } = await import('h3/node') const { mountStaticHandler } = await import('devframe/utils/serve-static') const { resolveStaticAssetsSource } = await import('devframe/utils/remote-assets') const app = new H3() const projectStorageDir = devtools.context.host.getStorageDir('project') for (const { baseUrl, source } of devtools.context.views.buildStaticDirs) mountStaticHandler(app, baseUrl, resolveStaticAssetsSource(source, projectStorageDir)) app.use('/', defineHandler(event => sendRedirect(event, DEVTOOLS_MOUNT_PATH, 302))) const appHandler = toNodeHandler(app) // Hub first (owns `/__devtools/*`); anything outside its base falls through // to the sub-frame statics + the root redirect. const server = createServer((req, res) => { middleware(req, res, () => appHandler(req, res)) }) server.listen(port, host, async () => { const url = normalizeHttpServerUrl(host, port) // eslint-disable-next-line no-console console.log(c.green`${MARK_NODE} Vite DevTools started at`, c.green(url), '\n') if (options.open) await open(url) }) }