From a7d0367bc837c8cd35fa97b19b6efd6a1f1046f5 Mon Sep 17 00:00:00 2001 From: TUFYIK <2499123744@qq.com> Date: Wed, 2 Dec 2026 19:43:41 +0800 Subject: [PATCH] fix(devtools): prefix client module resolution URL with effective Vite base --- packages/devtools/src/module-main.ts | 32 +- .../src/utils/client-module-resolution.ts | 75 +++ .../test/client-module-resolution.test.ts | 485 ++++++++++++++++++ 3 files changed, 591 insertions(+), 1 deletion(-) create mode 100644 packages/devtools/src/utils/client-module-resolution.ts create mode 100644 packages/devtools/test/client-module-resolution.test.ts diff --git a/packages/devtools/src/module-main.ts b/packages/devtools/src/module-main.ts index d87bb7ffde..f2d7ffc258 100644 --- a/packages/devtools/src/module-main.ts +++ b/packages/devtools/src/module-main.ts @@ -1,4 +1,4 @@ -import type { PluginWithDevTools } from '@vitejs/devtools-kit' +import type { PluginWithDevTools, ViteDevToolsNodeContext } from '@vitejs/devtools-kit' import type { DevToolsConfig } from '@vitejs/devtools/config' import type { StaticAssetsSource } from 'devframe' import type { Nuxt } from 'nuxt/schema' @@ -21,6 +21,7 @@ import { createDefaultTabOptions, setServerTasksEnabledByDefault } from './const import { packageDir, runtimeDir } from './dirs' import { setupRPC } from './server-rpc' import { skipInSSR } from './server-rpc/skip-in-ssr' +import { applyClientModuleResolution } from './utils/client-module-resolution' import { createDevListenerPlugin } from './utils/dev-listener' import { readLocalOptions } from './utils/local-options' import { resolveSetupMode } from './utils/setup-mode' @@ -234,8 +235,21 @@ export async function enableModule(options: ModuleOptions, nuxt: Nuxt) { // property, so `@vitejs/devtools` silently drops the dock entry. The // original client-vs-server RPC race is already handled by the guard inside // `connectDevToolsKit` (`if (devtoolsKitCtx) return`). + let clientDevToolsCtx: ViteDevToolsNodeContext | undefined + addVitePlugin(defineViteDevToolsPlugin({ name: 'nuxt:devtools', + configureServer: { + order: 'post', + handler(server) { + if (server.config.build?.ssr) + return + return () => { + if (clientDevToolsCtx) + applyClientModuleResolution(clientDevToolsCtx, nuxt, server.config) + } + }, + }, devtools: { async setup(ctx) { // Only the browser-serving client Vite context registers the `Nuxt` @@ -243,6 +257,22 @@ export async function enableModule(options: ModuleOptions, nuxt: Nuxt) { // setup callback too, and would otherwise create a second, inert // group + hub member. See `skipInSSR`. if (!skipInSSR(ctx)) { + clientDevToolsCtx = ctx + applyClientModuleResolution(ctx, nuxt) + // `@vitejs/devtools` calls `initHub({ clientModuleResolution: '/@id/{specifier}' })` + // after `devtools.setup(ctx)`, overwriting `ctx.staticConfig.dock.clientModuleResolution` + // right before `provideConnectionMeta` runs. Re-apply Nuxt's effective Vite base there + // (and in the `configureServer` post hook) so `/__devtools/__connection.json` and + // `/__devtools/__client-imports.js` advertise `@id/{specifier}`. + const host = ctx.host as typeof ctx.host & { provideConnectionMeta?: (getter: () => unknown) => void } + if (host.provideConnectionMeta) { + const provideConnectionMeta = host.provideConnectionMeta.bind(host) + host.provideConnectionMeta = (getter) => { + applyClientModuleResolution(ctx, nuxt) + return provideConnectionMeta(getter) + } + } + const resolveViteOrigin = ctx.host.resolveOrigin.bind(ctx.host) ctx.host.resolveOrigin = () => publicDevServerOrigin || resolveViteOrigin() diff --git a/packages/devtools/src/utils/client-module-resolution.ts b/packages/devtools/src/utils/client-module-resolution.ts new file mode 100644 index 0000000000..af652d2a8b --- /dev/null +++ b/packages/devtools/src/utils/client-module-resolution.ts @@ -0,0 +1,75 @@ +import type { ViteDevToolsNodeContext } from '@vitejs/devtools-kit' +import type { Nuxt } from 'nuxt/schema' +import type { ResolvedConfig } from 'vite' +import { cleanDoubleSlashes, joinURL, withLeadingSlash, withTrailingSlash } from 'devframe/utils/url' + +const CLIENT_MODULE_RESOLUTION_TEMPLATE = '/@id/{specifier}' +const DEFAULT_BUILD_ASSETS_DIR = '/_nuxt/' +const PROTOCOL_RE = /^[\w+.-]{2,}:\/\// +const RELATIVE_PREFIX_RE = /^\.(?:\/+|$)/ + +export interface ClientModuleResolutionOptions { + baseURL?: string + buildAssetsDir?: string + viteBase?: string + viteServerBase?: string +} + +type ViteConfigLike = Partial> & { + server?: (Partial & { base?: string }) +} + +function normalizeBasePath(input: string): string { + const value = input.trim() + if (!value) + return '/' + if (PROTOCOL_RE.test(value)) { + try { + return withTrailingSlash(cleanDoubleSlashes(withLeadingSlash(new URL(value).pathname || '/'))) + } + catch { + return '/' + } + } + const stripped = value.replace(RELATIVE_PREFIX_RE, '/') + return withTrailingSlash(cleanDoubleSlashes(withLeadingSlash(stripped))) +} + +/** + * Build the `ConnectionMeta.configs.dock.clientModuleResolution` URL template + * (`@id/{specifier}`) so bare-specifier dock client scripts (such as + * `vite-plugin-vue-tracer/client/vite-devtools`) load through Nuxt's mounted + * Vite dev server rather than falling through to the Nuxt page router at `/`. + */ +export function resolveClientModuleResolution(options: ClientModuleResolutionOptions = {}): string { + const explicitBase = options.viteServerBase?.trim() || options.viteBase?.trim() + if (explicitBase) + return joinURL(normalizeBasePath(explicitBase), CLIENT_MODULE_RESOLUTION_TEMPLATE) + + const baseURL = normalizeBasePath(options.baseURL || '/') + const rawAssetsDir = options.buildAssetsDir ?? DEFAULT_BUILD_ASSETS_DIR + const assetsDir = rawAssetsDir.trim().replace(RELATIVE_PREFIX_RE, '/') + const effectiveBase = normalizeBasePath(joinURL(baseURL, assetsDir)) + return joinURL(effectiveBase, CLIENT_MODULE_RESOLUTION_TEMPLATE) +} + +export function applyClientModuleResolution( + ctx: Pick & { staticConfig?: ViteDevToolsNodeContext['staticConfig'] }, + nuxt: Pick, + viteConfig?: ViteConfigLike, +): string { + const activeViteConfig = (viteConfig ?? ctx.viteConfig) as ViteConfigLike | undefined + const userViteConfig = nuxt.options.vite as ViteConfigLike | undefined + const clientModuleResolution = resolveClientModuleResolution({ + baseURL: nuxt.options.app.baseURL, + buildAssetsDir: nuxt.options.app.buildAssetsDir, + viteBase: activeViteConfig?.base || userViteConfig?.base, + viteServerBase: activeViteConfig?.server?.base || userViteConfig?.server?.base, + }) + ctx.staticConfig ||= {} + ctx.staticConfig.dock = { + ...ctx.staticConfig.dock, + clientModuleResolution, + } + return clientModuleResolution +} diff --git a/packages/devtools/test/client-module-resolution.test.ts b/packages/devtools/test/client-module-resolution.test.ts new file mode 100644 index 0000000000..934397d68c --- /dev/null +++ b/packages/devtools/test/client-module-resolution.test.ts @@ -0,0 +1,485 @@ +import type { IncomingMessage, ServerResponse } from 'node:http' +import type { Plugin, ViteDevServer } from 'vite' +import type { ClientModuleResolutionOptions } from '../src/utils/client-module-resolution' +import { Buffer } from 'node:buffer' +import { EventEmitter } from 'node:events' +import { resolveClientModuleSpecifier } from '@devframes/hub/client' +import { DevTools } from '@vitejs/devtools' +import { VueTracer } from 'vite-plugin-vue-tracer' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { applyClientModuleResolution, resolveClientModuleResolution } from '../src/utils/client-module-resolution' +import { fakeNuxt } from './fake-nuxt' + +const mocks = vi.hoisted(() => ({ + vitePlugins: [] as Plugin[], +})) + +vi.mock('@nuxt/kit', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + addImports: vi.fn(), + addPlugin: vi.fn(), + addTemplate: vi.fn(), + addVitePlugin: vi.fn((plugin: Plugin | Plugin[]) => { + mocks.vitePlugins.push(...(Array.isArray(plugin) + ? plugin + : [plugin])) + }), + extendViteConfig: vi.fn(), + } +}) + +interface MiddlewareLayer { + route: string + handle: (req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void) => void +} + +function createFakeMiddlewares() { + const stack: MiddlewareLayer[] = [] + return { + stack, + use( + routeOrHandle: string | MiddlewareLayer['handle'], + maybeHandle?: MiddlewareLayer['handle'], + ) { + if (typeof routeOrHandle === 'function') + stack.push({ route: '', handle: routeOrHandle }) + else if (maybeHandle) + stack.push({ route: routeOrHandle, handle: maybeHandle }) + }, + async dispatch(url: string): Promise<{ statusCode: number, body: string, headers: Record }> { + const headers: Record = {} + const chunks: string[] = [] + let ended = false + + const req = Object.assign(new EventEmitter(), { + method: 'GET', + url, + originalUrl: url, + headers: { host: 'localhost:3000' }, + socket: { encrypted: false, remoteAddress: '127.0.0.1' }, + }) as unknown as IncomingMessage + + let resolveDone!: () => void + const donePromise = new Promise((resolve) => { + resolveDone = resolve + }) + + const rawRes = Object.assign(new EventEmitter(), { + statusCode: 200, + writableEnded: false, + headersSent: false, + setHeader(name: string, value: string | string[]) { + headers[name.toLowerCase()] = Array.isArray(value) + ? value.join(', ') + : String(value) + return rawRes + }, + getHeader(name: string) { + return headers[name.toLowerCase()] + }, + writeHead(statusCode: number, head?: Record) { + rawRes.statusCode = statusCode + if (head) { + for (const [k, v] of Object.entries(head)) + headers[k.toLowerCase()] = String(v) + } + return rawRes + }, + write(chunk: unknown, encodingOrCb?: unknown, maybeCb?: unknown) { + const cb = typeof encodingOrCb === 'function' + ? encodingOrCb + : typeof maybeCb === 'function' + ? maybeCb + : undefined + if (chunk != null && typeof chunk !== 'function') { + chunks.push(typeof chunk === 'string' + ? chunk + : Buffer.from(chunk as Uint8Array).toString('utf8')) + } + cb?.() + return true + }, + end(chunk?: unknown, encodingOrCb?: unknown, maybeCb?: unknown) { + const cb = typeof chunk === 'function' + ? chunk + : typeof encodingOrCb === 'function' + ? encodingOrCb + : typeof maybeCb === 'function' + ? maybeCb + : undefined + if (ended) { + cb?.() + return rawRes + } + ended = true + rawRes.writableEnded = true + if (chunk != null && typeof chunk !== 'function') { + chunks.push(typeof chunk === 'string' + ? chunk + : Buffer.from(chunk as Uint8Array).toString('utf8')) + } + cb?.() + rawRes.emit('finish') + resolveDone() + return rawRes + }, + }) + const res = rawRes as unknown as ServerResponse + + let index = 0 + const next = (err?: unknown): void => { + if (err) + throw err + if (ended || index >= stack.length) { + if (!ended) { + res.statusCode = 404 + res.end('') + } + return + } + const layer = stack[index++]! + const [pathname = ''] = (req.url ?? '').split('?') + if (layer.route && pathname !== layer.route && !pathname.startsWith(`${layer.route}/`)) + return next() + + const prevUrl = req.url ?? '' + if (layer.route) { + const stripped = prevUrl.slice(layer.route.length) + req.url = stripped.startsWith('/') || stripped.startsWith('?') || stripped === '' + ? stripped || '/' + : `/${stripped}` + } + layer.handle(req, res, (nextErr) => { + req.url = prevUrl + next(nextErr) + }) + } + + queueMicrotask(() => req.emit('end')) + next() + await donePromise + + return { + statusCode: res.statusCode, + body: chunks.join(''), + headers, + } + }, + } +} + +async function bootDevToolsHub(options: { + baseURL?: string + buildAssetsDir?: string + viteBase?: string + runPostHooks?: boolean +} = {}) { + vi.stubEnv('NODE_ENV', 'development') + vi.stubEnv('TEST', '') + + const nuxt = fakeNuxt() + if (options.baseURL !== undefined) + nuxt.options.app.baseURL = options.baseURL + if (options.buildAssetsDir !== undefined) + nuxt.options.app.buildAssetsDir = options.buildAssetsDir + + const { enableModule } = await import('../src/module-main') + await enableModule({ + disableAuthorization: true, + dataInspector: false, + viteInspect: false, + componentInspector: false, + vueDevTools: false, + codeServer: { enabled: false }, + } as any, nuxt) + + const nuxtDevToolsPlugin = mocks.vitePlugins.find(p => p.name === 'nuxt:devtools')! + const vueTracerPlugin = VueTracer({ + viteDevtools: { onPick: 'none' }, + }) as Plugin + const devToolsPlugins = await DevTools({ + clientAuth: false, + builtinDevTools: false, + }) + const allPlugins = [ + ...devToolsPlugins, + vueTracerPlugin, + nuxtDevToolsPlugin, + ] + + const middlewares = createFakeMiddlewares() + const viteServer = { + httpServer: null, + middlewares, + config: { + command: 'serve', + root: nuxt.options.rootDir, + base: options.viteBase, + build: { ssr: false }, + server: { host: 'localhost', port: 3000 }, + plugins: allPlugins, + }, + } as unknown as ViteDevServer + + const postHooks: Array<(() => void) | undefined> = [] + for (const plugin of allPlugins) { + const hook = plugin.configureServer + if (!hook) + continue + const handler = typeof hook === 'function' + ? hook + : hook.handler + const post = await handler.call({} as any, viteServer) + if (typeof post === 'function') + postHooks.push(post) + } + + if (options.runPostHooks !== false) { + for (const post of postHooks) + post?.() + } + + const close = async () => { + for (const plugin of allPlugins) { + const hook = plugin.closeBundle + if (!hook) + continue + const handler = typeof hook === 'function' + ? hook + : hook.handler + await handler.call({} as any) + } + } + + return { middlewares, close } +} + +afterEach(() => { + mocks.vitePlugins.length = 0 + vi.unstubAllEnvs() +}) + +describe('resolveClientModuleResolution', () => { + it.each<[string, ClientModuleResolutionOptions | undefined, string]>([ + ['defaults to /_nuxt/@id/{specifier}', undefined, '/_nuxt/@id/{specifier}'], + [ + 'combines custom baseURL and default buildAssetsDir', + { baseURL: '/docs/' }, + '/docs/_nuxt/@id/{specifier}', + ], + [ + 'normalizes missing leading and trailing slashes', + { baseURL: 'docs', buildAssetsDir: '_assets' }, + '/docs/_assets/@id/{specifier}', + ], + [ + 'handles nested baseURL and custom buildAssetsDir with slashes', + { baseURL: '/org/app/', buildAssetsDir: '/_build/' }, + '/org/app/_build/@id/{specifier}', + ], + [ + 'collapses duplicate slashes across segments', + { baseURL: '//org//app//', buildAssetsDir: '///_nuxt///' }, + '/org/app/_nuxt/@id/{specifier}', + ], + [ + 'handles root / buildAssetsDir on root baseURL without double slashes', + { baseURL: '/', buildAssetsDir: '/' }, + '/@id/{specifier}', + ], + [ + 'handles empty buildAssetsDir on root baseURL', + { baseURL: '/', buildAssetsDir: '' }, + '/@id/{specifier}', + ], + [ + 'handles root / buildAssetsDir under a subpath baseURL', + { baseURL: '/subpath/', buildAssetsDir: '/' }, + '/subpath/@id/{specifier}', + ], + [ + 'normalizes relative ./ prefixes to root-relative paths', + { baseURL: './', buildAssetsDir: './_nuxt/' }, + '/_nuxt/@id/{specifier}', + ], + [ + 'uses explicit viteBase when provided', + { baseURL: '/', buildAssetsDir: '/_nuxt/', viteBase: '/custom-vite' }, + '/custom-vite/@id/{specifier}', + ], + [ + 'supports explicit root / viteBase', + { viteBase: '/' }, + '/@id/{specifier}', + ], + [ + 'normalizes relative ./ viteBase to root /', + { viteBase: './' }, + '/@id/{specifier}', + ], + [ + 'extracts pathname when viteBase is a full URL', + { viteBase: 'https://cdn.example.com/sub/_nuxt/' }, + '/sub/_nuxt/@id/{specifier}', + ], + [ + 'prefers viteServerBase over viteBase and app options', + { + baseURL: '/app/', + buildAssetsDir: '/_nuxt/', + viteBase: '/vite/', + viteServerBase: '/server-base', + }, + '/server-base/@id/{specifier}', + ], + ])('%s', (_label, input, expected) => { + expect(resolveClientModuleResolution(input)).toBe(expected) + }) +}) + +describe('applyClientModuleResolution', () => { + it('preserves existing dock staticConfig properties while updating clientModuleResolution', () => { + const nuxt = fakeNuxt() + nuxt.options.app.baseURL = '/portal/' + nuxt.options.app.buildAssetsDir = '/_assets/' + + const ctx: any = { + viteConfig: { + command: 'serve', + build: { ssr: false }, + }, + staticConfig: { + dock: { + clientModuleResolution: '/@id/{specifier}', + extra: true, + }, + }, + } + + const resolved = applyClientModuleResolution(ctx, nuxt) + expect(resolved).toBe('/portal/_assets/@id/{specifier}') + expect(ctx.staticConfig.dock).toEqual({ + clientModuleResolution: '/portal/_assets/@id/{specifier}', + extra: true, + }) + }) +}) + +describe('vite DevTools client module resolution in Nuxt', () => { + it('prefixes bare-specifier dock imports (vue-tracer picker) with default /_nuxt/ base', async () => { + const hub = await bootDevToolsHub({ viteBase: '/_nuxt/' }) + try { + const metaRes = await hub.middlewares.dispatch('/__devtools/__connection.json') + expect(metaRes.statusCode).toBe(200) + const meta = JSON.parse(metaRes.body) + expect(meta.configs?.dock?.clientModuleResolution).toBe('/_nuxt/@id/{specifier}') + + const resolvedPickerUrl = resolveClientModuleSpecifier( + 'vite-plugin-vue-tracer/client/vite-devtools', + { + template: meta.configs?.dock?.clientModuleResolution, + metaBaseUrl: 'http://localhost:3000/__devtools/', + }, + ) + expect(resolvedPickerUrl).toBe('http://localhost:3000/_nuxt/@id/vite-plugin-vue-tracer/client/vite-devtools') + + const importsRes = await hub.middlewares.dispatch('/__devtools/__client-imports.js') + expect(importsRes.statusCode).toBe(200) + expect(importsRes.body).toContain('import("/_nuxt/@id/vite-plugin-vue-tracer/client/vite-devtools")') + } + finally { + await hub.close() + } + }) + + it('keeps the Nuxt Vite base even before configureServer post hooks run', async () => { + const hub = await bootDevToolsHub({ + viteBase: '/_nuxt/', + runPostHooks: false, + }) + try { + const metaRes = await hub.middlewares.dispatch('/__devtools/__connection.json') + const meta = JSON.parse(metaRes.body) + expect(meta.configs?.dock?.clientModuleResolution).toBe('/_nuxt/@id/{specifier}') + } + finally { + await hub.close() + } + }) + + it('derives custom app.baseURL + app.buildAssetsDir when viteConfig.base is unset', async () => { + const hub = await bootDevToolsHub({ + baseURL: '/docs', + buildAssetsDir: '_assets', + }) + try { + const metaRes = await hub.middlewares.dispatch('/__devtools/__connection.json') + const meta = JSON.parse(metaRes.body) + expect(meta.configs?.dock?.clientModuleResolution).toBe('/docs/_assets/@id/{specifier}') + + const resolvedPickerUrl = resolveClientModuleSpecifier( + 'vite-plugin-vue-tracer/client/vite-devtools', + { + template: meta.configs?.dock?.clientModuleResolution, + metaBaseUrl: 'http://localhost:3000/__devtools/', + }, + ) + expect(resolvedPickerUrl).toBe('http://localhost:3000/docs/_assets/@id/vite-plugin-vue-tracer/client/vite-devtools') + } + finally { + await hub.close() + } + }) + + it('handles root / Vite base without double slashes', async () => { + const hub = await bootDevToolsHub({ + baseURL: '/', + buildAssetsDir: '/', + viteBase: '/', + }) + try { + const metaRes = await hub.middlewares.dispatch('/__devtools/__connection.json') + const meta = JSON.parse(metaRes.body) + expect(meta.configs?.dock?.clientModuleResolution).toBe('/@id/{specifier}') + + const resolvedPickerUrl = resolveClientModuleSpecifier( + 'vite-plugin-vue-tracer/client/vite-devtools', + { + template: meta.configs?.dock?.clientModuleResolution, + metaBaseUrl: 'http://localhost:3000/__devtools/', + }, + ) + expect(resolvedPickerUrl).toBe('http://localhost:3000/@id/vite-plugin-vue-tracer/client/vite-devtools') + } + finally { + await hub.close() + } + }) + + it('skips SSR Vite contexts during plugin setup', async () => { + vi.stubEnv('NODE_ENV', 'development') + vi.stubEnv('TEST', '') + const nuxt = fakeNuxt() + const { enableModule } = await import('../src/module-main') + await enableModule({ + dataInspector: false, + viteInspect: false, + componentInspector: false, + vueDevTools: false, + codeServer: { enabled: false }, + } as any, nuxt) + + const plugin = mocks.vitePlugins.find(p => p.name === 'nuxt:devtools') as any + const ssrCtx = { + viteConfig: { + command: 'build', + build: { ssr: true }, + }, + staticConfig: {}, + } + await plugin.devtools.setup(ssrCtx) + expect(ssrCtx.staticConfig).toEqual({}) + }) +})