diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ad953e62..009ad89c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -28,3 +28,34 @@ jobs:
- run: pnpm test:types
- run: pnpm lint
- run: pnpm test
+
+ # Nuxt 5 is still a pre-release: this job tracks it and may fail without blocking merges.
+ nuxt-5:
+ runs-on: ubuntu-latest
+ continue-on-error: true
+ steps:
+ - uses: actions/checkout@0c366fd6a839edf440554fa01a7085ccba70ac98
+ - uses: pnpm/action-setup@6e7bdbda5fe05107efc88b23b7ed00aa05f84ca0
+ name: Install pnpm
+ - name: Install Node.js
+ uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f
+ with:
+ node-version: 24.22.0
+ cache: 'pnpm'
+ - name: Point the workspace at the Nuxt 5 nightly
+ run: |
+ sed -i \
+ -e "s#^ nuxt: .*# nuxt: npm:nuxt-nightly@5x#" \
+ -e "s#^ '@nuxt/kit': .*# '@nuxt/kit': npm:@nuxt/kit-nightly@5x#" \
+ -e "s#^ '@nuxt/schema': .*# '@nuxt/schema': npm:@nuxt/schema-nightly@5x#" \
+ -e "s#^ '@nuxt/vite-builder': .*# '@nuxt/vite-builder': npm:@nuxt/vite-builder-nightly@5x#" \
+ -e "s#^ '@nuxt/nitro-server': .*# '@nuxt/nitro-server': npm:@nuxt/nitro-server-nightly@5x#" \
+ pnpm-workspace.yaml
+ cat pnpm-workspace.yaml
+ # fail loudly if the overrides block drifted and nothing was substituted
+ test "$(grep -c -- '-nightly@5x' pnpm-workspace.yaml)" -eq 5
+ - run: pnpm install --no-frozen-lockfile
+ - run: pnpm dev:prepare
+ - run: pnpm prepack
+ - run: pnpm test:types
+ - run: pnpm test
diff --git a/.npmrc b/.npmrc
deleted file mode 100644
index cf040424..00000000
--- a/.npmrc
+++ /dev/null
@@ -1,2 +0,0 @@
-shamefully-hoist=true
-strict-peer-dependencies=false
diff --git a/client/.nuxtrc b/client/.nuxtrc
index b463ecaa..c673d423 100644
--- a/client/.nuxtrc
+++ b/client/.nuxtrc
@@ -1,2 +1,2 @@
imports.autoImport=true
-setups.@nuxt/test-utils="4.3.3"
\ No newline at end of file
+setups.@nuxt/test-utils="4.4.0"
\ No newline at end of file
diff --git a/client/app/app.vue b/client/app/app.vue
index 16adbd8c..27ae0af9 100644
--- a/client/app/app.vue
+++ b/client/app/app.vue
@@ -1,14 +1,21 @@
-
+
+
+
+
Lost connection to the DevTools server ({{ status }})
+
+
+
+
diff --git a/client/app/components/n/Badge.vue b/client/app/components/n/Badge.vue
new file mode 100644
index 00000000..ec1a7d25
--- /dev/null
+++ b/client/app/components/n/Badge.vue
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/client/app/components/n/Button.vue b/client/app/components/n/Button.vue
new file mode 100644
index 00000000..1db10396
--- /dev/null
+++ b/client/app/components/n/Button.vue
@@ -0,0 +1,29 @@
+
+
+
+
+
diff --git a/client/app/components/n/Card.vue b/client/app/components/n/Card.vue
new file mode 100644
index 00000000..39292390
--- /dev/null
+++ b/client/app/components/n/Card.vue
@@ -0,0 +1,5 @@
+
+
+
+
+
diff --git a/client/app/components/n/Loading.vue b/client/app/components/n/Loading.vue
new file mode 100644
index 00000000..256b9a9d
--- /dev/null
+++ b/client/app/components/n/Loading.vue
@@ -0,0 +1,9 @@
+
+
+
+ Loading...
+
+
diff --git a/client/app/components/n/Tip.vue b/client/app/components/n/Tip.vue
new file mode 100644
index 00000000..c951a075
--- /dev/null
+++ b/client/app/components/n/Tip.vue
@@ -0,0 +1,36 @@
+
+
+
+
+
+
+
diff --git a/client/app/composables/devtools.ts b/client/app/composables/devtools.ts
new file mode 100644
index 00000000..e80855b9
--- /dev/null
+++ b/client/app/composables/devtools.ts
@@ -0,0 +1,113 @@
+import type { NuxtDevtoolsHostClient } from '@nuxt/devtools-kit/types'
+import type { DevToolsRpcClient } from '@vitejs/devtools-kit/client'
+import { getDevToolsRpcClient } from '@vitejs/devtools-kit/client'
+import { computed, shallowRef } from 'vue'
+import { RPC_NAMESPACE } from '../../../src/runtime/core/rpc-types'
+
+function scopedRpc(client: DevToolsRpcClient) {
+ return client.scope(RPC_NAMESPACE).rpc
+}
+export type HintsRpc = ReturnType
+export type HostClient = NuxtDevtoolsHostClient
+export type ConnectionStatus = DevToolsRpcClient['status']
+
+const kit = shallowRef()
+const status = shallowRef('connecting')
+const host = shallowRef()
+let started = false
+
+type HostWindow = Window & { __NUXT_DEVTOOLS_HOST__?: NuxtDevtoolsHostClient }
+
+function readHost(): NuxtDevtoolsHostClient | undefined {
+ const candidates: (Window | undefined)[] = []
+ try {
+ // the app window is usually the direct parent; older layouts nested the dock once more
+ candidates.push(window.parent, window.parent?.parent)
+ }
+ catch {
+ // cross-origin parent: no host client reachable
+ }
+ for (const candidate of candidates) {
+ try {
+ const client = (candidate as HostWindow | undefined)?.__NUXT_DEVTOOLS_HOST__
+ if (client?.nuxt) return client
+ }
+ catch {
+ // cross-origin access
+ }
+ }
+ return undefined
+}
+
+function start() {
+ if (started || import.meta.server) return
+ started = true
+
+ getDevToolsRpcClient().then((client) => {
+ kit.value = client
+ status.value = client.status
+ client.events.on('connection:status', (next) => {
+ status.value = next
+ })
+ }).catch((error) => {
+ status.value = 'error'
+ console.warn('[@nuxt/hints] Could not connect to the DevTools RPC', error)
+ })
+
+ const poll = () => {
+ const client = readHost()
+ if (client) {
+ host.value = client
+ return
+ }
+ setTimeout(poll, 100)
+ }
+ poll()
+}
+
+/** The connected Vite DevTools RPC client, `undefined` until the connection is up. */
+export function useDevtoolsKit() {
+ start()
+ return kit
+}
+
+/** The live connection status of the Vite DevTools RPC client. */
+export function useDevtoolsStatus() {
+ start()
+ return status
+}
+
+/** The Nuxt DevTools host client of the user's app, `undefined` until it is reachable. */
+export function useDevtoolsHost() {
+ start()
+ return host
+}
+
+/** The Hints RPC scope: `call('get-hydration-mismatches')`, `register(...)`. */
+export function useHintsRpc() {
+ start()
+ return computed(() => kit.value && scopedRpc(kit.value))
+}
+
+/** The window the user's app runs in, for overlays and measurements. */
+export function useHostWindow(): Window {
+ try {
+ return window.parent?.parent || window.parent || window
+ }
+ catch {
+ return window
+ }
+}
+
+/**
+ * Open a file in the user's editor through Nuxt DevTools' own server RPC
+ * (`nuxt:devtools:openInEditor`).
+ */
+export async function openInEditor(filepath: string) {
+ const client = kit.value
+ if (!client) {
+ console.warn('[@nuxt/hints] DevTools RPC is not connected, cannot open', filepath)
+ return false
+ }
+ return client.call('nuxt:devtools:openInEditor', filepath) as Promise
+}
diff --git a/client/app/composables/element-highlighter.ts b/client/app/composables/element-highlighter.ts
index 249b0ea4..7cdbbe4c 100644
--- a/client/app/composables/element-highlighter.ts
+++ b/client/app/composables/element-highlighter.ts
@@ -1,19 +1,9 @@
-import { useDevtoolsClient } from '@nuxt/devtools-kit/iframe-client'
+import { useDevtoolsHost, useHostWindow } from './devtools'
import { openElementSourceComponent } from './vue-tracer'
let overlay: HTMLDivElement | null = null
-// Get the parent window where the actual app is running
-function getTargetWindow() {
- try {
- // The devtools client iframe structure is: parent -> devtools iframe -> client iframe
- // We need to access the parent window (the actual app window)
- return window.parent?.parent || window.parent || window
- }
- catch {
- return window
- }
-}
+const getTargetWindow = useHostWindow
function createOverlay() {
if (overlay)
@@ -44,7 +34,7 @@ function removeOverlay() {
}
export function useElementHighlighter() {
- const client = useDevtoolsClient()
+ const host = useDevtoolsHost()
const highlightElement = (element: HTMLElement | undefined) => {
if (!element) {
@@ -74,8 +64,7 @@ export function useElementHighlighter() {
if (!element)
return
- const clientValue = client.value
- if (!clientValue)
+ if (!host.value)
return
// Use devtools inspector to open element in editor
diff --git a/client/app/composables/features.ts b/client/app/composables/features.ts
index 2ceb29fb..49a71d40 100644
--- a/client/app/composables/features.ts
+++ b/client/app/composables/features.ts
@@ -1,5 +1,5 @@
import type { FeaturesName } from '../../../src/runtime/core/types'
-import { useDevtoolsClient } from '@nuxt/devtools-kit/iframe-client'
+import { useDevtoolsHost } from './devtools'
export function useHintsConfig() {
const hostNuxt = useHostNuxt()
@@ -8,8 +8,8 @@ export function useHintsConfig() {
}
export function useEnabledHintsFeatures(): Record {
- const client = useDevtoolsClient().value
- if (!client?.host?.nuxt) {
+ const host = useDevtoolsHost().value
+ if (!host?.nuxt) {
return { hydration: true, lazyLoad: true, webVitals: false, thirdPartyScripts: false, htmlValidate: true }
}
const config = useHintsConfig()
@@ -22,8 +22,8 @@ export function useEnabledHintsFeatures(): Record {
}
export function useHintsFeature(feature: FeaturesName): boolean {
- const client = useDevtoolsClient().value
- if (!client?.host?.nuxt) return true
+ const host = useDevtoolsHost().value
+ if (!host?.nuxt) return true
const config = useHintsConfig()
return typeof config.features[feature] === 'object' ? config.features[feature].devtools !== false : Boolean(config.features[feature])
}
diff --git a/client/app/composables/host.ts b/client/app/composables/host.ts
index fdd764dd..2228db02 100644
--- a/client/app/composables/host.ts
+++ b/client/app/composables/host.ts
@@ -1,17 +1,13 @@
-import { useDevtoolsClient } from '@nuxt/devtools-kit/iframe-client'
+import { useDevtoolsHost } from './devtools'
import type { CLSMetricWithAttribution, INPMetricWithAttribution, LCPMetricWithAttribution } from 'web-vitals/attribution'
import { computed, onScopeDispose, ref } from 'vue'
export function useHostThirdPartyScripts() {
- const client = useDevtoolsClient().value
-
- if (!client) {
- throw new Error('`useHostThirdPartyScripts` must be used when the devtools client is connected')
- }
+ const hostNuxt = useHostNuxt()
return {
- scripts: client.host.nuxt.payload.__hints.thirdPartyScripts,
- isUsingNuxtScripts: Boolean(client.host.nuxt.$scripts),
+ scripts: hostNuxt.payload.__hints.thirdPartyScripts,
+ isUsingNuxtScripts: Boolean(hostNuxt.$scripts),
}
}
@@ -55,11 +51,11 @@ export function useHostBaseURL() {
}
export function useHostNuxt() {
- const client = useDevtoolsClient().value
+ const host = useDevtoolsHost().value
- if (!client?.host?.nuxt) {
+ if (!host?.nuxt) {
throw new Error('`useHostNuxt` must be used when the devtools client is connected to a host app')
}
- return client.host.nuxt
+ return host.nuxt
}
diff --git a/client/app/composables/vue-tracer.ts b/client/app/composables/vue-tracer.ts
index 53e8ec7d..e0a29a45 100644
--- a/client/app/composables/vue-tracer.ts
+++ b/client/app/composables/vue-tracer.ts
@@ -1,11 +1,11 @@
-import { useDevtoolsClient } from '@nuxt/devtools-kit/iframe-client'
+import { openInEditor, useDevtoolsHost } from './devtools'
export function findClosestTraceInfo(el: Element) {
- const client = useDevtoolsClient().value
- if (!client || !client.host.inspector) {
+ const host = useDevtoolsHost().value
+ if (!host || !host.inspector) {
throw new Error('`findClosestWithTraceInfo` must be used when the devtools client is connected')
}
- const { findTraceFromElement } = client.host.nuxt.__tracerRecord
+ const { findTraceFromElement } = host.nuxt.__tracerRecord
const traceInfo = findTraceFromElement(el)
if (!traceInfo && el.parentElement) {
@@ -15,19 +15,20 @@ export function findClosestTraceInfo(el: Element) {
}
export function openElementSourceComponent(el: Element) {
- const client = useDevtoolsClient().value
- if (!client || !client.host.inspector) {
+ const host = useDevtoolsHost().value
+ if (!host || !host.inspector) {
throw new Error('`openElementSourceComponent` must be used when the devtools client is connected')
}
- const { findTraceFromElement } = client.host.nuxt.__tracerRecord
+ const { findTraceFromElement } = host.nuxt.__tracerRecord
const traceInfo = findTraceFromElement(el)
if (!traceInfo && el.parentElement) {
return openElementSourceComponent(el.parentElement)
}
if (traceInfo) {
- client.devtools.rpc.openInEditor(traceInfo.filepath)
+ openInEditor(traceInfo.filepath)
+ return
}
console.info('[@nuxt/hints] Source component not found for element', el)
}
diff --git a/client/app/pages/component-lazy-load.vue b/client/app/pages/component-lazy-load.vue
index c3fae94d..523d85f9 100644
--- a/client/app/pages/component-lazy-load.vue
+++ b/client/app/pages/component-lazy-load.vue
@@ -1,5 +1,5 @@
`,
- )
- nitro.hooks.callHook(HTML_VALIDATE_REPORT_HOOK, data).catch((error) => {
- nitro.captureError(error instanceof Error ? error : new Error(String(error)), { event })
- })
+ if (results.errorCount > 0) {
+ const data: HtmlValidateReport = {
+ id: randomUUID(),
+ path: getRequestPath(event),
+ html: formattedBody,
+ results: results.results,
}
+ htmlContext.bodyAppend.push(``)
+ await reportToDevServer(data)
}
- catch (error) {
- // https://github.com/nuxt/hints/issues/360
- // html validate can throw errors for some html
- console.warn('HTML Validate error:', error instanceof Error ? error.message : String(error))
- }
+ }
+ catch (error) {
+ // https://github.com/nuxt/hints/issues/360
+ // html validate can throw errors for some html
+ console.warn('HTML Validate error:', error instanceof Error ? error.message : String(error))
}
})
}
diff --git a/src/runtime/hydration/composables.ts b/src/runtime/hydration/composables.ts
index e6c9b9b9..857c6736 100644
--- a/src/runtime/hydration/composables.ts
+++ b/src/runtime/hydration/composables.ts
@@ -1,5 +1,5 @@
import { getCurrentInstance, inject, markRaw, onMounted } from 'vue'
-import { useNuxtApp } from '#imports'
+import { $fetch, useNuxtApp } from '#imports'
import { HYDRATION_ROUTE, formatHTML, logger, normalizeHTMLForComparison } from './utils'
import type { HydrationMismatchPayload } from './types'
import { clientOnlySymbol } from '#app/components/client-only'
diff --git a/src/runtime/hydration/handlers.ts b/src/runtime/hydration/handlers.ts
index b7779682..bd3e6015 100644
--- a/src/runtime/hydration/handlers.ts
+++ b/src/runtime/hydration/handlers.ts
@@ -1,6 +1,6 @@
-import { createError, defineEventHandler, readBody, setResponseStatus } from 'h3'
import type { HydrationMismatchPayload } from './types'
import { getRPC } from '../core/rpc'
+import { errorResponse, jsonResponse, readJsonBody } from '../core/server/types'
export const hydrationMismatches: HydrationMismatchPayload[] = []
@@ -18,11 +18,15 @@ export function clearHydrationMismatches(ids: string[]) {
getRPC()?.onHydrationCleared(ids)
}
-export const getHandler = defineEventHandler(() => getHydrationMismatches())
+export function getHandler() {
+ return jsonResponse(getHydrationMismatches())
+}
-export const postHandler = defineEventHandler(async (event) => {
- const body = await readBody>(event)
- assertPayload(body)
+export async function postHandler(request: Request) {
+ const body = await readJsonBody>(request)
+ if (!isPayload(body)) {
+ return errorResponse(400, 'Invalid payload')
+ }
const payload: HydrationMismatchPayload = {
id: crypto.randomUUID(),
htmlPreHydration: body.htmlPreHydration,
@@ -38,29 +42,23 @@ export const postHandler = defineEventHandler(async (event) => {
}
}
getRPC()?.onHydrationMismatch(payload)
- setResponseStatus(event, 201)
- return payload
-})
+ return jsonResponse(payload, { status: 201 })
+}
-export const deleteHandler = defineEventHandler(async (event) => {
- const body = await readBody<{ id: string[] }>(event)
+export async function deleteHandler(request: Request) {
+ const body = await readJsonBody<{ id: string[] }>(request)
if (!body || !Array.isArray(body.id)) {
- throw createError({ statusCode: 400, statusMessage: 'Invalid payload' })
+ return errorResponse(400, 'Invalid payload')
}
clearHydrationMismatches(body.id)
- setResponseStatus(event, 204)
-})
+ return new Response(null, { status: 204 })
+}
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function assertPayload(body: any): asserts body is Omit {
- if (
- !body
- || typeof body !== 'object'
- || (body.htmlPreHydration !== undefined && typeof body.htmlPreHydration !== 'string')
- || (body.htmlPostHydration !== undefined && typeof body.htmlPostHydration !== 'string')
- || (body.componentName !== undefined && typeof body.componentName !== 'string')
- || typeof body.fileLocation !== 'string'
- ) {
- throw createError({ statusCode: 400, statusMessage: 'Invalid payload' })
- }
+function isPayload(body: unknown): body is Omit {
+ if (!body || typeof body !== 'object') return false
+ const candidate = body as Record
+ return (candidate.htmlPreHydration === undefined || typeof candidate.htmlPreHydration === 'string')
+ && (candidate.htmlPostHydration === undefined || typeof candidate.htmlPostHydration === 'string')
+ && (candidate.componentName === undefined || typeof candidate.componentName === 'string')
+ && typeof candidate.fileLocation === 'string'
}
diff --git a/src/runtime/lazy-load/handlers.ts b/src/runtime/lazy-load/handlers.ts
index aed46a3e..39023187 100644
--- a/src/runtime/lazy-load/handlers.ts
+++ b/src/runtime/lazy-load/handlers.ts
@@ -1,8 +1,8 @@
-import { createError, defineEventHandler, readBody, setResponseStatus } from 'h3'
import type { ComponentLazyLoadData } from './schema'
import { ComponentLazyLoadDataSchema } from './schema'
import { parse, ValiError } from 'valibot'
import { getRPC } from '../core/rpc'
+import { errorResponse, jsonResponse, readJsonBody } from '../core/server/types'
export const lazyLoadData: ComponentLazyLoadData[] = []
@@ -17,18 +17,19 @@ export function clearLazyLoadHint(id: string) {
getRPC()?.onLazyLoadCleared(id)
}
-export const getHandler = defineEventHandler(() => getLazyLoadHints())
+export function getHandler() {
+ return jsonResponse(getLazyLoadHints())
+}
-export const postHandler = defineEventHandler(async (event) => {
- const body = await readBody(event)
+export async function postHandler(request: Request) {
+ const body = await readJsonBody(request)
let parsed: ComponentLazyLoadData
try {
parsed = parse(ComponentLazyLoadDataSchema, body)
}
catch (error) {
if (error instanceof ValiError) {
- setResponseStatus(event, 400)
- return { error: 'Validation failed', message: error.message }
+ return jsonResponse({ error: 'Validation failed', message: error.message }, { status: 400 })
}
throw error
}
@@ -37,21 +38,17 @@ export const postHandler = defineEventHandler(async (event) => {
lazyLoadData.push(parsed)
getRPC()?.onLazyLoadReport(parsed)
}
- setResponseStatus(event, 201)
-})
+ return new Response(null, { status: 201 })
+}
-export const deleteHandler = defineEventHandler(async (event) => {
- const id = event.context.params?.id
+export function deleteHandler(_request: Request, id: string | undefined) {
if (!id) {
- throw createError({ statusCode: 400, message: 'ID is required' })
+ return errorResponse(400, 'ID is required')
}
const hasEntry = lazyLoadData.some(item => item.id === id)
if (!hasEntry) {
- throw createError({ statusCode: 404, message: 'Entry not found' })
+ return errorResponse(404, 'Entry not found')
}
- const next = lazyLoadData.filter(item => item.id !== id)
- lazyLoadData.length = 0
- lazyLoadData.push(...next)
- getRPC()?.onLazyLoadCleared(id)
- setResponseStatus(event, 204)
-})
+ clearLazyLoadHint(id)
+ return new Response(null, { status: 204 })
+}
diff --git a/src/runtime/lazy-load/plugin.client.ts b/src/runtime/lazy-load/plugin.client.ts
index 9dc7bf42..5ebbcb58 100644
--- a/src/runtime/lazy-load/plugin.client.ts
+++ b/src/runtime/lazy-load/plugin.client.ts
@@ -1,4 +1,4 @@
-import { defineNuxtPlugin, useNuxtApp, useRoute } from '#imports'
+import { $fetch, defineNuxtPlugin, useNuxtApp, useRoute } from '#imports'
import { defu } from 'defu'
import type { DirectImportInfo, ComponentLazyLoadState, ComponentLazyLoadData } from './schema'
import { useLazyComponentTracking } from './composables'
diff --git a/src/runtime/nitro.d.ts b/src/runtime/nitro.d.ts
deleted file mode 100644
index fa1b7601..00000000
--- a/src/runtime/nitro.d.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import type { HtmlValidateReport } from './html-validate/types'
-
-declare module 'nitropack/types' {
- interface NitroRuntimeHooks {
- 'hints:html-validate:report': (report: HtmlValidateReport) => void
- }
-}
diff --git a/src/runtime/third-party-scripts/nitro.plugin.ts b/src/runtime/third-party-scripts/nitro.plugin.ts
index 40d67607..ffb15b45 100644
--- a/src/runtime/third-party-scripts/nitro.plugin.ts
+++ b/src/runtime/third-party-scripts/nitro.plugin.ts
@@ -1,7 +1,7 @@
-import type { NitroApp } from 'nitropack/types'
+import { useServerHooks } from 'nuxt/server'
-export default function (nitroApp: NitroApp) {
- nitroApp.hooks.hook('render:html', ({ head }) => {
+export default function thirdPartyScriptsPlugin() {
+ useServerHooks().hook('render:html', ({ head }) => {
head.unshift(`
'],
})
- const callHook = vi.fn(async (name: string, payload: unknown) => {
- const handler = hookHandlers.get(name)
- await handler?.(payload)
- })
- const captureError = vi.fn()
+ expect(html).toBe('a')
+ })
- plugin({
- captureError,
- hooks: {
- hook,
- callHook,
- },
- } as never)
+ it('validates the rendered page on render:html and reports to the dev-server API', async () => {
+ plugin()
- const renderResponse = hookHandlers.get('render:response')
- const reportHook = hookHandlers.get('hints:html-validate:report')
+ const renderHtml = hookHandlers.get('render:html')
+ expect(renderHtml).toBeTypeOf('function')
- expect(renderResponse).toBeTypeOf('function')
- expect(reportHook).toBeTypeOf('function')
+ const htmlContext = createHtmlContext()
+ const event = { url: new URL('http://localhost/demo'), req: new Request('http://localhost/demo') }
- const event = {
- path: '/demo',
- context: {},
- }
- const response = {
- body: '',
- headers: {
- 'content-type': 'text/html',
- },
- }
-
- await renderResponse?.(response, { event })
+ await renderHtml?.(htmlContext, { event })
- expect(response.body).toContain('hints-html-validate')
- expect(globalThis.fetch).not.toHaveBeenCalled()
- expect(htmlValidateReports).toHaveLength(1)
- expect(htmlValidateReports[0]).toMatchObject({
+ expect(validateString).toHaveBeenCalledWith(renderHTMLDocument({ ...htmlContext, bodyAppend: [] }))
+ expect(htmlContext.bodyAppend.join('')).toContain('')
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [URL, RequestInit]
+ expect(url.href).toBe('http://localhost:3000/__nuxt_hints/html-validate')
+ expect(init.method).toBe('POST')
+ expect(JSON.parse(init.body as string)).toMatchObject({
id: 'report-1',
path: '/demo',
- html: '',
results: reportResults,
})
- expect(callHook).toHaveBeenCalledTimes(1)
- expect(callHook).toHaveBeenCalledWith('hints:html-validate:report', expect.objectContaining({ id: 'report-1' }))
- expect(rpcMock.onHtmlValidateReport).toHaveBeenCalledTimes(1)
- expect(rpcMock.onHtmlValidateReport).toHaveBeenCalledWith(expect.objectContaining({ id: 'report-1' }))
- expect(captureError).not.toHaveBeenCalled()
+ })
+
+ it('never derives the report destination from request headers', async () => {
+ plugin()
+ const htmlContext = createHtmlContext()
+ const headers = { 'host': 'evil.example', 'x-forwarded-proto': 'http://collector.example/' }
+ const nodeReq = { url: '/demo', headers }
+ const event = { path: '/demo', req: nodeReq, node: { req: nodeReq }, headers: new Headers(headers) }
+
+ await hookHandlers.get('render:html')?.(htmlContext, { event })
+
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [URL, RequestInit]
+ expect(url.href).toBe('http://localhost:3000/__nuxt_hints/html-validate')
+ expect(JSON.parse(init.body as string)).toMatchObject({ path: '/demo' })
+ })
+
+ it('does not post a report when the Hints API is not registered (devtools off)', async () => {
+ devServerOrigin.value = null
+ plugin()
+ const htmlContext = createHtmlContext()
+
+ await hookHandlers.get('render:html')?.(htmlContext, { event: { url: new URL('http://localhost/demo') } })
+
+ // the page still carries the report for the browser overlay
+ expect(htmlContext.bodyAppend.join('')).toContain('hints-html-validate')
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('skips streamed renders', async () => {
+ plugin()
+ const htmlContext = createHtmlContext()
+
+ await hookHandlers.get('render:html')?.(htmlContext, { event: { url: new URL('http://localhost/demo') }, streaming: true })
+
+ expect(validateString).not.toHaveBeenCalled()
+ expect(htmlContext.bodyAppend).toHaveLength(0)
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('does not inject anything when the page is valid', async () => {
+ validateString.mockResolvedValueOnce({ errorCount: 0, results: [] })
+ plugin()
+ const htmlContext = createHtmlContext()
- await reportHook?.(htmlValidateReports[0])
+ await hookHandlers.get('render:html')?.(htmlContext, { event: { url: new URL('http://localhost/ok') } })
- expect(htmlValidateReports).toHaveLength(1)
- expect(rpcMock.onHtmlValidateReport).toHaveBeenCalledTimes(1)
+ expect(htmlContext.bodyAppend).toHaveLength(0)
+ expect(fetchMock).not.toHaveBeenCalled()
})
})