Unverified Commit 3b47db01 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Improve Request Insights request and fetch details

Co-authored-by: 's avatarDavid Ilie <david@davidilie.com>
Co-authored-by: 's avatarWill Binns-Smith <755844+wbinnssmith@users.noreply.github.com>
parent 7e01b92f
import { getFetchUrlPresentation, truncateMiddle } from './fetch-label'
describe('request insight fetch labels', () => {
it('classifies same-origin and external fetches by full web origin', () => {
expect(
getFetchUrlPresentation('/api/items?token=redacted', 'https://app.test')
).toEqual({
fullUrl: 'https://app.test/api/items?token=redacted',
path: '/api/items?token=redacted',
originKind: 'same-origin',
originLabel: 'Same origin',
})
expect(
getFetchUrlPresentation('https://api.test:445/items', 'https://app.test')
).toEqual({
fullUrl: 'https://api.test:445/items',
path: '/items',
originKind: 'external',
originLabel: 'External origin · api.test:445',
})
expect(
getFetchUrlPresentation('http://app.test/items', 'https://app.test')
).toEqual({
fullUrl: 'http://app.test/items',
path: '/items',
originKind: 'external',
originLabel: 'External origin · http://app.test',
})
})
it('does not guess origin semantics without a usable browser origin', () => {
expect(
getFetchUrlPresentation('https://api.test/items', undefined)
).toEqual({
fullUrl: 'https://api.test/items',
path: '/items',
originKind: 'unknown',
originLabel: 'https://api.test',
})
expect(getFetchUrlPresentation('/api/items', undefined)).toEqual({
fullUrl: '/api/items',
path: '/api/items',
originKind: 'unknown',
originLabel: 'Origin unavailable',
})
})
it('middle-truncates labels while retaining their distinguishing suffix', () => {
const value = '/api/a/very/long/path/to/tail-marker?token=redacted'
const truncated = truncateMiddle(value, 28)
expect(truncated).toHaveLength(28)
expect(truncated).toContain('…')
expect(truncated).toMatch(/token=redacted$/)
expect(truncateMiddle('😀abc', 3)).toBe('😀…c')
expect(truncateMiddle('secret', 1)).toBe('…')
expect(truncateMiddle('secret', 0)).toBe('')
})
})
export type FetchOriginKind = 'same-origin' | 'external' | 'unknown'
export type FetchUrlPresentation = {
fullUrl: string
path: string
originKind: FetchOriginKind
originLabel: string
}
const DEFAULT_PATH_LENGTH = 48
const DEFAULT_ORIGIN_LENGTH = 36
export function getFetchUrlPresentation(
url: string | undefined,
currentOrigin: string | undefined,
pathLength = DEFAULT_PATH_LENGTH,
originLength = DEFAULT_ORIGIN_LENGTH
): FetchUrlPresentation {
if (!url) {
return {
fullUrl: 'Unknown URL',
path: 'Unknown URL',
originKind: 'unknown',
originLabel: 'Origin unavailable',
}
}
const baseUrl = parseHttpUrl(currentOrigin)
try {
const parsedUrl = baseUrl ? new URL(url, baseUrl) : new URL(url)
if (!isHttpUrl(parsedUrl)) {
return {
fullUrl: url,
path: truncateMiddle(url, pathLength),
originKind: 'unknown',
originLabel: 'Origin unavailable',
}
}
const sameOrigin = baseUrl?.origin === parsedUrl.origin
const originKind = baseUrl
? sameOrigin
? 'same-origin'
: 'external'
: 'unknown'
const compactOrigin =
baseUrl?.protocol === parsedUrl.protocol
? parsedUrl.host
: parsedUrl.origin
return {
fullUrl: parsedUrl.href,
path: truncateMiddle(
`${parsedUrl.pathname}${parsedUrl.search}`,
pathLength
),
originKind,
originLabel:
originKind === 'same-origin'
? 'Same origin'
: originKind === 'external'
? `External origin · ${truncateMiddle(compactOrigin, originLength)}`
: truncateMiddle(parsedUrl.origin, originLength),
}
} catch {
return {
fullUrl: url,
path: truncateMiddle(url, pathLength),
originKind: 'unknown',
originLabel: 'Origin unavailable',
}
}
}
export function truncateMiddle(value: string, maxLength: number): string {
if (maxLength <= 0) {
return ''
}
const characters = Array.from(value)
if (characters.length <= maxLength) {
return value
}
if (maxLength === 1) {
return '…'
}
const availableLength = maxLength - 1
const prefixLength = Math.floor(availableLength / 2)
const suffixLength = availableLength - prefixLength
return `${characters.slice(0, prefixLength).join('')}…${characters
.slice(-suffixLength)
.join('')}`
}
function parseHttpUrl(value: string | undefined): URL | undefined {
if (!value) {
return undefined
}
try {
const url = new URL(value)
return isHttpUrl(url) ? url : undefined
} catch {
return undefined
}
}
function isHttpUrl(url: URL): boolean {
return url.protocol === 'http:' || url.protocol === 'https:'
}
.request-insights-panel-container {
container-type: inline-size;
height: 100%;
min-height: 0;
}
.request-insights-panel {
display: grid;
grid-template-columns: minmax(210px, 320px) minmax(420px, 1fr);
......@@ -22,6 +28,7 @@
.request-insights-list {
border-right: 1px solid var(--color-gray-400);
overflow: auto;
overscroll-behavior: contain;
min-width: 0;
}
......@@ -414,6 +421,7 @@
min-width: 0;
min-height: 0;
overflow: auto;
overscroll-behavior: contain;
}
.request-insights-summary {
......@@ -464,15 +472,63 @@
}
.request-insights-overview span {
overflow: hidden;
max-width: 100%;
min-width: 0;
border: 1px solid var(--color-gray-400);
border-radius: 4px;
padding: 2px 6px;
color: var(--color-gray-900);
font-size: var(--size-12);
text-overflow: ellipsis;
white-space: nowrap;
}
.request-insights-overview .request-insights-route-template {
border-style: dashed;
font-family: var(--font-mono);
}
.request-insights-params-trigger {
border: 0;
padding: 0;
background: transparent;
color: inherit;
cursor: help;
font: inherit;
}
.request-insights-params-trigger:focus-visible {
outline: var(--focus-ring);
outline-offset: 2px;
}
.request-insights-params-tooltip,
.request-insights-fetch-tooltip,
.request-insights-trace-tooltip {
--tooltip-background: var(--color-background-100);
border: 1px solid var(--color-gray-alpha-400);
box-shadow: 0 4px 14px rgb(0 0 0 / 16%);
color: var(--color-gray-1000);
}
.request-insights-params-tooltip {
max-width: min(420px, calc(100vw - 32px));
font-family: var(--font-mono);
overflow-wrap: anywhere;
text-align: left;
white-space: pre-wrap;
}
.request-insights-fetch-tooltip,
.request-insights-trace-tooltip {
max-width: min(640px, calc(100vw - 32px));
font-family: var(--font-mono);
overflow-wrap: anywhere;
white-space: normal;
}
.request-insights-error {
padding: 8px 16px;
border-bottom: 1px solid var(--color-gray-400);
......@@ -598,11 +654,20 @@
flex-direction: column;
}
.request-insights-trace-rows:focus-visible {
outline: var(--focus-ring);
outline-offset: -1px;
}
.request-insights-span-row {
min-height: 28px;
border-bottom: 1px solid var(--color-gray-300);
}
.request-insights-span-row[data-active='true'] {
background: var(--color-gray-200);
}
.request-insights-span-row:last-child {
border-bottom: 0;
}
......@@ -644,7 +709,6 @@
background: var(--color-red-800);
}
.request-insights-fetch-host,
.request-insights-cache-reason {
min-width: 0;
overflow: hidden;
......@@ -722,7 +786,52 @@
gap: 8px;
}
@media (max-width: 900px) {
.request-insights-fetch-url-trigger {
display: flex;
min-width: 0;
align-items: center;
gap: 8px;
cursor: help;
}
.request-insights-fetch-path,
.request-insights-fetch-origin {
min-width: 0;
overflow: hidden;
white-space: nowrap;
}
.request-insights-fetch-path {
color: var(--color-gray-1000);
text-overflow: ellipsis;
}
.request-insights-fetch-origin {
max-width: 240px;
flex-shrink: 0;
border: 1px solid var(--color-gray-400);
border-radius: 999px;
padding: 0 5px;
color: var(--color-gray-800);
font-family: inherit;
font-size: var(--size-10);
text-overflow: ellipsis;
}
.request-insights-fetch-origin[data-origin='external'] {
border-color: var(--color-purple-500);
color: var(--color-purple-900);
}
@media (forced-colors: active) {
.request-insights-trace-rows:focus-visible,
.request-insights-span-row[data-active='true'] {
outline: 1px solid Highlight;
outline-offset: -1px;
}
}
@container (width <= 900px) {
.request-insights-summary {
align-items: flex-start;
}
......@@ -732,7 +841,7 @@
}
}
@media (max-width: 700px) {
@container (width < 630px) {
.request-insights-panel {
grid-template-columns: 1fr;
}
......
import { useMemo, useState } from 'react'
import {
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
type KeyboardEvent,
type PointerEvent,
} from 'react'
import { Menu } from '@base-ui-components/react/menu'
import {
getRequestInsightKey,
......@@ -10,7 +19,9 @@ import { useDevOverlayContext } from '../../../dev-overlay.browser'
import { ACTION_DEVTOOLS_CONFIG } from '../../shared'
import { saveDevToolsConfig } from '../../utils/save-devtools-config'
import { CopyButton } from '../copy-button'
import { Tooltip } from '../tooltip/tooltip'
import GearIcon from '../../icons/gear-icon'
import { getFetchUrlPresentation } from './fetch-label'
import { formatDuration } from './format-duration'
import {
getRequestInsightFilterResult,
......@@ -18,6 +29,12 @@ import {
toggleRequestInsightFilter,
type RequestInsightFilter,
} from './request-filters'
import {
formatRequestRouteParams,
getRequestDisplayUrl,
getRequestListDisplayUrl,
getRequestRouteParams,
} from './request-label'
import {
getActiveRequestKey,
getRequestInsightRowType,
......@@ -29,6 +46,7 @@ import {
} from './request-list'
import {
getTraceItems,
getTraceNavigationIndex,
getTracePosition,
getTraceRange,
type TraceItem,
......@@ -180,7 +198,9 @@ export function RequestInsightsPanel() {
className="request-insights-settings-item"
closeOnClick={false}
onCheckedChange={(checked) =>
setRequestInsightsConfig({ showInternal: checked })
setRequestInsightsConfig({
showInternal: checked,
})
}
>
<span
......@@ -367,14 +387,17 @@ function RequestRow({
}) {
const isInstantInsights =
getRequestInsightKind(request) === 'instant-insights'
const route = request.route ?? request.url ?? 'Unknown route'
const requestType = getRequestInsightRowType(request, pageLoad)
const requestUrl = getRequestListDisplayUrl(
request,
requestType.type === 'rsc'
)
const clockTime = formatClockTime(request.startTime)
const bypassesProxy = request.proxyStatus === 'bypassed'
return (
<button
aria-label={`${isInstantInsights ? `Instant Insights for ${route}` : route}, ${requestType.accessibleLabel}, ${bypassesProxy ? 'Did not match the configured proxy, ' : ''}${formatDuration(request.durationMs)}, ${clockTime}`}
aria-label={`${isInstantInsights ? `Instant Insights for ${requestUrl}` : requestUrl}, ${requestType.accessibleLabel}, ${bypassesProxy ? 'Did not match the configured proxy, ' : ''}${formatDuration(request.durationMs)}, ${clockTime}`}
className="request-insights-row"
data-internal={isInstantInsights || undefined}
data-nested={nested || undefined}
......@@ -387,7 +410,7 @@ function RequestRow({
<span className="request-insights-route">
{nested ? <NestedArrowIcon /> : null}
<span className="request-insights-route-label">
{isInstantInsights ? 'Instant Insights' : route}
{isInstantInsights ? 'Instant Insights' : requestUrl}
</span>
</span>
<span className="request-insights-duration">
......@@ -461,11 +484,17 @@ function RequestDetails({
verbose: boolean
}) {
const traceItems = useMemo(
() => getTraceItems(request, verbose),
() =>
getTraceItems(
request,
verbose,
typeof window === 'undefined' ? undefined : window.location.origin
),
[request, verbose]
)
const overview = useMemo(() => getRequestOverview(request), [request])
const diagnosis = verbose ? getDiagnosis(request, traceItems) : null
const requestUrl = getRequestDisplayUrl(request)
return (
<div className="request-insights-details">
......@@ -474,8 +503,8 @@ function RequestDetails({
<div className="request-insights-title-row">
<div className="request-insights-title">
{getRequestInsightKind(request) === 'instant-insights'
? `Instant Insights · ${request.route ?? request.url ?? request.requestId}`
: (request.route ?? request.url ?? request.requestId)}
? `Instant Insights · ${requestUrl}`
: requestUrl}
</div>
<CopyButton
actionLabel="Copy request JSON"
......@@ -498,7 +527,11 @@ function RequestDetails({
<div className="request-insights-diagnosis">{diagnosis}</div>
) : null}
<Trace items={traceItems} request={request} />
<Trace
items={traceItems}
key={getRequestInsightKey(request)}
request={request}
/>
<FetchTable fetches={request.fetches} />
</div>
......@@ -518,6 +551,27 @@ function RequestOverview({
<span>{overview.fetchSummary}</span>
<span>{overview.cacheSummary}</span>
<span>{overview.spanSummary}</span>
{overview.route ? (
<span className="request-insights-route-template">
Route {overview.route}
</span>
) : null}
{overview.routeParams?.length ? (
<Tooltip
className="request-insights-params-tooltip"
title={formatRequestRouteParams(overview.routeParams)}
>
<button
aria-label={`Route parameters: ${overview.routeParams
.map(({ name }) => name)
.join(', ')}`}
className="request-insights-params-trigger"
type="button"
>
Params {overview.routeParams.map(({ name }) => name).join(', ')}
</button>
</Tooltip>
) : null}
</div>
)
}
......@@ -529,7 +583,43 @@ function Trace({
request: RequestInsight
items: TraceItem[]
}) {
const [activeItemId, setActiveItemId] = useState<string | null>(
items[0]?.id ?? null
)
const [activeTraceRow, setActiveTraceRow] = useState<HTMLElement | null>(null)
const [isTraceFocused, setIsTraceFocused] = useState(false)
const [isTraceTooltipOpen, setIsTraceTooltipOpen] = useState(false)
const traceRowsRef = useRef<HTMLDivElement>(null)
const shouldScrollActiveItemIntoViewRef = useRef(false)
const traceId = useId()
const range = getTraceRange(request)
const activeItemIndex = items.findIndex((item) => item.id === activeItemId)
const safeActiveItemIndex =
items.length === 0 ? -1 : Math.max(activeItemIndex, 0)
const activeItem = items[safeActiveItemIndex]
const activeItemDescription = activeItem
? getTraceItemDescription(activeItem, range)
: null
useEffect(() => {
if (
!shouldScrollActiveItemIntoViewRef.current ||
safeActiveItemIndex === -1
) {
return
}
shouldScrollActiveItemIntoViewRef.current = false
const activeOption =
traceRowsRef.current?.children.item(safeActiveItemIndex)
if (activeOption instanceof HTMLElement) {
activeOption.scrollIntoView({
block: 'nearest',
inline: 'nearest',
})
}
}, [safeActiveItemIndex])
const ticks = Array.from({ length: TRACE_TICK_COUNT }, (_, index) => {
const position = index / (TRACE_TICK_COUNT - 1)
return {
......@@ -537,6 +627,52 @@ function Trace({
position: position * 100,
}
})
const handleTraceKeyDown = useCallback(
(event: KeyboardEvent<HTMLDivElement>) => {
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return
}
const nextIndex = getTraceNavigationIndex(
activeItemIndex,
items.length,
event.key
)
if (nextIndex === undefined) {
return
}
event.preventDefault()
shouldScrollActiveItemIntoViewRef.current = true
setActiveItemId(items[nextIndex]?.id ?? null)
},
[activeItemIndex, items]
)
const handleTracePointerMove = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
const target = event.target
if (!(target instanceof Element)) {
return
}
const row = target.closest<HTMLElement>('[data-trace-index]')
if (row === null || !event.currentTarget.contains(row)) {
return
}
const index = Number(row.dataset.traceIndex)
if (Number.isSafeInteger(index)) {
shouldScrollActiveItemIntoViewRef.current = false
const itemId = items[index]?.id
if (itemId !== undefined) {
setActiveItemId((currentItemId) =>
currentItemId === itemId ? currentItemId : itemId
)
}
}
},
[items]
)
return (
<div className="request-insights-section">
......@@ -548,7 +684,10 @@ function Trace({
</div>
</div>
<div className="request-insights-trace-viewport">
<div className="request-insights-trace">
<div
className="request-insights-trace"
onPointerMove={handleTracePointerMove}
>
<div className="request-insights-trace-header">
<span>Span</span>
<span className="request-insights-trace-axis">
......@@ -573,54 +712,101 @@ function Trace({
Duration
</span>
</div>
<div className="request-insights-trace-rows">
{items.map((item) => {
const position = getTracePosition(item, range)
return (
<div
className="request-insights-span-row"
data-kind={item.kind}
key={item.id}
title={`${item.label} · +${formatDuration(position.offsetMs)} · ${formatDuration(item.durationMs)}`}
>
<span
className="request-insights-span-name"
style={{ paddingLeft: `${item.depth * 14 + 4}px` }}
<Tooltip
anchor={activeTraceRow}
asChild
className="request-insights-trace-tooltip"
direction="top"
onOpenChange={setIsTraceTooltipOpen}
open={isTraceFocused || isTraceTooltipOpen}
title={activeItemDescription}
>
<div
aria-activedescendant={
safeActiveItemIndex === -1
? undefined
: `${traceId}-item-${safeActiveItemIndex}`
}
aria-label={`Trace spans, ${items.length} item${items.length === 1 ? '' : 's'}. Use arrow keys to inspect timing.`}
className="request-insights-trace-rows"
onBlur={() => setIsTraceFocused(false)}
onFocus={() => setIsTraceFocused(true)}
onKeyDown={handleTraceKeyDown}
ref={traceRowsRef}
role="listbox"
tabIndex={items.length === 0 ? undefined : 0}
>
{items.map((item, index) => {
const position = getTracePosition(item, range)
const description = getTraceItemDescription(item, range)
return (
<div
aria-label={description}
aria-selected={index === safeActiveItemIndex}
className="request-insights-span-row"
data-active={index === safeActiveItemIndex || undefined}
data-kind={item.kind}
data-trace-item-id={item.id}
data-trace-index={index}
id={`${traceId}-item-${index}`}
key={item.id}
ref={
index === safeActiveItemIndex
? setActiveTraceRow
: undefined
}
role="option"
>
<span className="request-insights-span-label">
<span
className="request-insights-span-name"
style={{ paddingLeft: `${item.depth * 14 + 4}px` }}
>
<span className="request-insights-span-label">
<span
className="request-insights-span-marker"
data-kind={item.kind}
data-status={item.status}
/>
<span>{item.label}</span>
</span>
</span>
<span className="request-insights-span-track">
<span
className="request-insights-span-marker"
data-kind={item.kind}
className="request-insights-span-bar"
data-status={item.status}
style={{
left: `${position.left}%`,
width: `${position.width}%`,
}}
/>
<span>{item.label}</span>
</span>
</span>
<span className="request-insights-span-track">
<span
className="request-insights-span-bar"
data-status={item.status}
style={{
left: `${position.left}%`,
width: `${position.width}%`,
}}
/>
</span>
<span className="request-insights-span-duration">
{formatDuration(item.durationMs)}
</span>
</div>
)
})}
</div>
<span className="request-insights-span-duration">
{formatDuration(item.durationMs)}
</span>
</div>
)
})}
</div>
</Tooltip>
</div>
</div>
</div>
)
}
function getTraceItemDescription(
item: TraceItem,
range: ReturnType<typeof getTraceRange>
): string {
const position = getTracePosition(item, range)
return `${item.fullLabel ?? item.label} · +${formatDuration(position.offsetMs)} · ${formatDuration(item.durationMs)}`
}
function FetchTable({ fetches }: { fetches: RequestInsightFetch[] }) {
const currentOrigin =
typeof window === 'undefined' ? undefined : window.location.origin
return (
<div className="request-insights-section">
<div className="request-insights-section-title">Fetches</div>
......@@ -639,19 +825,33 @@ function FetchTable({ fetches }: { fetches: RequestInsightFetch[] }) {
<span>Reason</span>
</div>
{fetches.map((fetch, index) => {
const urlParts = formatUrl(fetch.url)
const url = getFetchUrlPresentation(fetch.url, currentOrigin)
return (
<div className="request-insights-fetch" key={index}>
<div
className="request-insights-fetch"
data-origin={url.originKind}
key={index}
>
<span className="request-insights-method">
{fetch.method ?? 'GET'}
</span>
<span className="request-insights-fetch-url">
<span>{urlParts.path}</span>
{urlParts.host ? (
<span className="request-insights-fetch-host">
{urlParts.host}
<Tooltip
className="request-insights-fetch-tooltip"
title={url.fullUrl}
>
<span className="request-insights-fetch-url-trigger">
<span className="request-insights-fetch-path">
{url.path}
</span>
<span
className="request-insights-fetch-origin"
data-origin={url.originKind}
>
{url.originLabel}
</span>
</span>
) : null}
</Tooltip>
</span>
<span>{formatDuration(fetch.durationMs)}</span>
<span>{fetch.statusCode ?? '-'}</span>
......@@ -694,6 +894,10 @@ function getRequestOverview(request: RequestInsight) {
{ hit: 0, miss: 0, skip: 0, unknown: 0 }
)
const knownCacheCount = cacheCounts.hit + cacheCounts.miss + cacheCounts.skip
const omittedSpans = request.spans.reduce((count, span) => {
const omitted = span.attributes?.['next.request_insights.omitted_spans']
return count + (typeof omitted === 'number' ? omitted : 0)
}, 0)
return {
method,
......@@ -711,7 +915,9 @@ function getRequestOverview(request: RequestInsight) {
: `Cache ${cacheCounts.hit} hit, ${cacheCounts.miss} miss, ${cacheCounts.skip} skip${
cacheCounts.unknown ? `, ${cacheCounts.unknown} unknown` : ''
}`,
spanSummary: `${request.spans.length} span${request.spans.length === 1 ? '' : 's'}`,
spanSummary: `${request.spans.length} span${request.spans.length === 1 ? '' : 's'}${omittedSpans ? `, ${omittedSpans} omitted` : ''}`,
route: request.route,
routeParams: getRequestRouteParams(request),
errorSummary,
}
}
......@@ -744,8 +950,11 @@ function getDiagnosis(
(!criticalItem ||
(slowestFetch.durationMs ?? 0) >= (criticalItem.durationMs ?? 0))
) {
const urlParts = formatUrl(slowestFetch.url)
return `Slowest recorded operation: ${urlParts.path} · ${formatDuration(slowestFetch.durationMs)}${getCacheSummary(slowestFetch)}.`
const url = getFetchUrlPresentation(
slowestFetch.url,
typeof window === 'undefined' ? undefined : window.location.origin
)
return `Slowest recorded operation: ${url.path} · ${formatDuration(slowestFetch.durationMs)}${getCacheSummary(slowestFetch)}.`
}
if (criticalItem) {
......@@ -783,24 +992,6 @@ function getMethodFromName(name: string | undefined): string | undefined {
return match?.[1]
}
function formatUrl(url: string | undefined): { path: string; host?: string } {
if (!url) {
return { path: 'Unknown URL' }
}
try {
const parsedUrl = new URL(url, window.location.origin)
const path = `${parsedUrl.pathname}${parsedUrl.search}`
const sameHost = parsedUrl.host === window.location.host
return {
path,
host: sameHost ? undefined : parsedUrl.host,
}
} catch {
return { path: url }
}
}
function formatClockTime(timestamp: number): string {
return new Date(timestamp).toLocaleTimeString(undefined, {
hour: '2-digit',
......
import {
formatRequestRouteParams,
getRequestDisplayUrl,
getRequestListDisplayUrl,
getRequestRouteParams,
} from './request-label'
describe('request insight request labels', () => {
it('prefers the concrete URL and hides the transport-only RSC query', () => {
const request = {
requestId: 'request-1',
route: '/products/[id]',
url: '/products/blue?tab=details&_rsc=redacted#summary',
}
expect(getRequestDisplayUrl(request)).toBe(
'/products/blue?tab=details&_rsc=redacted#summary'
)
expect(getRequestListDisplayUrl(request, true)).toBe(
'/products/blue?tab=details#summary'
)
expect(getRequestListDisplayUrl(request, false)).toBe(
'/products/blue?tab=details&_rsc=redacted#summary'
)
expect(
getRequestListDisplayUrl(
{
requestId: 'request-2',
route: '/products/[id]',
url: '//example.test/products/blue?_rsc=redacted',
},
true
)
).toBe('//example.test/products/blue')
})
it('extracts dynamic, catch-all, and optional catch-all parameters', () => {
expect(
getRequestRouteParams({
route: '/products/[category]/[...slug]',
url: '/products/widgets/blue/large?sort=redacted',
})
).toEqual([
{ name: 'category', value: 'widgets' },
{ name: 'slug', value: ['blue', 'large'] },
])
expect(
getRequestRouteParams({
route: '/docs/[[...slug]]',
url: '/docs',
})
).toEqual([{ name: 'slug', value: [] }])
})
it('handles base paths and encoded route values', () => {
const params = getRequestRouteParams(
{
route: '/products/[category]/[...slug]',
url: '/shop/products/home%20goods/blue%2Flarge',
},
'/shop'
)
expect(params).toEqual([
{ name: 'category', value: 'home goods' },
{ name: 'slug', value: ['blue/large'] },
])
expect(formatRequestRouteParams(params!)).toBe(
'{\n "category": "home goods",\n "slug": [\n "blue/large"\n ]\n}'
)
})
it('does not guess parameters from malformed or mismatched routes', () => {
expect(
getRequestRouteParams({ route: '/products/[id]', url: '/users/1' })
).toBeUndefined()
expect(
getRequestRouteParams({ route: '/products/[id]', url: '/products/%zz' })
).toBeUndefined()
expect(
getRequestRouteParams({
route: '/products/[id]/[id]',
url: '/products/one/two',
})
).toBeUndefined()
})
})
import type { RequestInsight } from '../../../shared/request-insights'
import { removePathPrefix } from '../../../../shared/lib/router/utils/remove-path-prefix'
type RequestIdentity = Pick<RequestInsight, 'requestId' | 'route' | 'url'>
export type RequestRouteParam = {
name: string
value: string | string[]
}
export function getRequestDisplayUrl(request: RequestIdentity): string {
return request.url ?? request.route ?? request.requestId
}
export function getRequestListDisplayUrl(
request: RequestIdentity,
rscRequest: boolean
): string {
const displayUrl = getRequestDisplayUrl(request)
if (!rscRequest) {
return displayUrl
}
try {
const protocolRelative = displayUrl.startsWith('//')
const rootRelative = !protocolRelative && displayUrl.startsWith('/')
const parsed = new URL(displayUrl, 'http://next.local')
if (!parsed.searchParams.has('_rsc')) {
return displayUrl
}
parsed.searchParams.delete('_rsc')
return protocolRelative
? `//${parsed.host}${parsed.pathname}${parsed.search}${parsed.hash}`
: rootRelative
? `${parsed.pathname}${parsed.search}${parsed.hash}`
: parsed.toString()
} catch {
return displayUrl
}
}
export function getRequestRouteParams(
request: Pick<RequestIdentity, 'route' | 'url'>,
basePath = process.env.__NEXT_ROUTER_BASEPATH || ''
): RequestRouteParam[] | undefined {
if (!request.route || !request.url) {
return undefined
}
const pathname = getPathname(request.url)
if (!pathname) {
return undefined
}
const routeSegments = splitPathname(request.route)
const pathnameSegments = splitPathname(removePathPrefix(pathname, basePath))
if (!routeSegments || !pathnameSegments) {
return undefined
}
const params: RequestRouteParam[] = []
const names = new Set<string>()
let pathnameIndex = 0
for (const routeSegment of routeSegments) {
const dynamicSegment = parseDynamicSegment(routeSegment)
if (!dynamicSegment) {
if (
routeSegment.includes('[') ||
routeSegment.includes(']') ||
pathnameSegments[pathnameIndex] !== routeSegment
) {
return undefined
}
pathnameIndex += 1
continue
}
if (names.has(dynamicSegment.name)) {
return undefined
}
names.add(dynamicSegment.name)
if (dynamicSegment.catchAll) {
const value = pathnameSegments.slice(pathnameIndex)
if (value.length === 0 && !dynamicSegment.optional) {
return undefined
}
params.push({ name: dynamicSegment.name, value })
pathnameIndex = pathnameSegments.length
continue
}
const value = pathnameSegments[pathnameIndex]
if (value === undefined) {
return undefined
}
params.push({ name: dynamicSegment.name, value })
pathnameIndex += 1
}
return pathnameIndex === pathnameSegments.length ? params : undefined
}
export function formatRequestRouteParams(params: RequestRouteParam[]): string {
return JSON.stringify(
Object.fromEntries(params.map(({ name, value }) => [name, value])),
null,
2
)
}
function getPathname(url: string): string | undefined {
try {
if (url.startsWith('/')) {
return new URL(url, 'http://next.local').pathname
}
const parsed = new URL(url)
return parsed.protocol === 'http:' || parsed.protocol === 'https:'
? parsed.pathname
: undefined
} catch {
return undefined
}
}
function splitPathname(pathname: string): string[] | undefined {
if (!pathname.startsWith('/')) {
return undefined
}
const segments = pathname.split('/').slice(1)
if (segments.at(-1) === '') {
segments.pop()
}
const decoded: string[] = []
for (const segment of segments) {
const value = decodeSegment(segment)
if (value === undefined) {
return undefined
}
decoded.push(value)
}
return decoded
}
function decodeSegment(segment: string): string | undefined {
try {
return decodeURIComponent(segment)
} catch {
return undefined
}
}
function parseDynamicSegment(segment: string):
| {
name: string
catchAll: boolean
optional: boolean
}
| undefined {
const optionalCatchAll = segment.match(/^\[\[\.\.\.([^[/\]]+)\]\]$/)
const catchAll = segment.match(/^\[\.\.\.([^[/\]]+)\]$/)
const dynamic = segment.match(/^\[([^[/\]]+)\]$/)
const match = optionalCatchAll ?? catchAll ?? dynamic
if (!match) {
return undefined
}
return {
name: match[1],
catchAll: optionalCatchAll !== null || catchAll !== null,
optional: optionalCatchAll !== null,
}
}
......@@ -9,7 +9,12 @@ import {
getRequestListEntries,
isPageLoadRequest,
} from './request-list'
import { getTraceItems, getTracePosition, getTraceRange } from './trace-viewer'
import {
getTraceItems,
getTraceNavigationIndex,
getTracePosition,
getTraceRange,
} from './trace-viewer'
function createRequest(
overrides: Partial<RequestInsight> = {}
......@@ -28,6 +33,18 @@ function createRequest(
}
describe('request insights trace viewer', () => {
it('moves the active trace row without leaving the listbox', () => {
expect(getTraceNavigationIndex(0, 3, 'ArrowDown')).toBe(1)
expect(getTraceNavigationIndex(2, 3, 'ArrowDown')).toBe(2)
expect(getTraceNavigationIndex(2, 3, 'ArrowUp')).toBe(1)
expect(getTraceNavigationIndex(1, 3, 'Home')).toBe(0)
expect(getTraceNavigationIndex(1, 3, 'End')).toBe(2)
expect(getTraceNavigationIndex(1, 3, 'ArrowRight')).toBeUndefined()
expect(getTraceNavigationIndex(1, 3, 'ArrowLeft')).toBeUndefined()
expect(getTraceNavigationIndex(0, 0, 'ArrowDown')).toBeUndefined()
expect(getTraceNavigationIndex(0, 3, 'Enter')).toBeUndefined()
})
it('keeps the active request selected when newer requests arrive', () => {
const selectedRequest = createRequest({ requestId: 'selected' })
const newerRequest = createRequest({ requestId: 'newer' })
......@@ -287,6 +304,40 @@ describe('request insights trace viewer', () => {
)
})
it('distinguishes same-origin and external fetches in the trace', () => {
const request = createRequest({
fetches: [
{
method: 'GET',
url: 'https://app.test/api/data?token=%3Credacted%3E',
startTime: 110,
durationMs: 10,
},
{
method: 'POST',
url: 'https://api.example.test/api/data',
startTime: 120,
durationMs: 20,
},
],
})
expect(
getTraceItems(request, true, 'https://app.test').map(
({ label, fullLabel }) => ({ label, fullLabel })
)
).toEqual([
{
label: 'GET /api/data?token=%3Credacted%3E · Same origin',
fullLabel: 'GET https://app.test/api/data?token=%3Credacted%3E',
},
{
label: 'POST /api/data · External origin · api.example.test',
fullLabel: 'POST https://api.example.test/api/data',
},
])
})
it('orders spans by their recorded parent-child hierarchy', () => {
const request = createRequest({
spans: [
......
......@@ -3,6 +3,7 @@ import type {
RequestInsightFetch,
RequestInsightSpan,
} from '../../../shared/request-insights'
import { getFetchUrlPresentation } from './fetch-label'
export type TraceItem = {
id: string
......@@ -11,6 +12,7 @@ export type TraceItem = {
spanType?: string
category: 'nextjs' | 'application'
label: string
fullLabel?: string
startTime: number
durationMs?: number
status: 'ok' | 'error' | 'pending'
......@@ -23,6 +25,32 @@ export type TraceRange = {
durationMs: number
}
export function getTraceNavigationIndex(
currentIndex: number,
itemCount: number,
key: string
): number | undefined {
if (itemCount <= 0) {
return undefined
}
const lastIndex = itemCount - 1
const safeCurrentIndex = Math.min(Math.max(currentIndex, 0), lastIndex)
switch (key) {
case 'ArrowDown':
return Math.min(safeCurrentIndex + 1, lastIndex)
case 'ArrowUp':
return Math.max(safeCurrentIndex - 1, 0)
case 'Home':
return 0
case 'End':
return lastIndex
default:
return undefined
}
}
type UnnestedTraceItem = Omit<TraceItem, 'depth'>
const FETCH_SPAN_TYPE = 'AppRender.fetch'
......@@ -77,7 +105,8 @@ const SPAN_WORD_CASE: Record<string, string> = {
export function getTraceItems(
request: RequestInsight,
verbose: boolean
verbose: boolean,
currentOrigin?: string
): TraceItem[] {
const fetchSpansByIndex = new Map<number, RequestInsightSpan>()
......@@ -111,7 +140,7 @@ export function getTraceItems(
request.fetches.forEach((fetch, index) => {
const matchingSpan =
fetch.index === undefined ? undefined : fetchSpansByIndex.get(fetch.index)
const item = getFetchTraceItem(fetch, index, matchingSpan)
const item = getFetchTraceItem(fetch, index, matchingSpan, currentOrigin)
if (item) {
items.push(item)
}
......@@ -174,20 +203,25 @@ function getSpanTraceItem(
function getFetchTraceItem(
fetch: RequestInsightFetch,
index: number,
matchingSpan: RequestInsightSpan | undefined
matchingSpan: RequestInsightSpan | undefined,
currentOrigin: string | undefined
): UnnestedTraceItem | null {
const startTime = fetch.startTime ?? matchingSpan?.startTime
if (startTime === undefined) {
return null
}
const method = fetch.method ?? 'GET'
const url = getFetchUrlPresentation(fetch.url, currentOrigin)
return {
id: `fetch:${matchingSpan?.spanId ?? fetch.index ?? index}:${startTime}`,
spanId: matchingSpan?.spanId,
parentSpanId: matchingSpan?.parentSpanId,
spanType: FETCH_SPAN_TYPE,
category: matchingSpan ? getSpanCategory(matchingSpan) : 'application',
label: `${fetch.method ?? 'GET'} ${getUrlPath(fetch.url)}`,
label: `${method} ${url.path}${currentOrigin ? ` · ${url.originLabel}` : ''}`,
fullLabel: `${method} ${url.fullUrl}`,
startTime,
durationMs: fetch.durationMs ?? matchingSpan?.durationMs,
status:
......@@ -395,16 +429,3 @@ function getSpanLabel(span: RequestInsightSpan): string {
return words.join(' ')
}
function getUrlPath(url: string | undefined): string {
if (!url) {
return 'Unknown URL'
}
try {
const parsedUrl = new URL(url, 'http://localhost')
return `${parsedUrl.pathname}${parsedUrl.search}`
} catch {
return url
}
}
......@@ -5,6 +5,8 @@
}
.tooltip {
--tooltip-background: var(--color-gray-1000);
position: relative;
padding: 6px 12px;
border-radius: 8px;
......@@ -12,7 +14,7 @@
line-height: 1.4;
pointer-events: none;
color: var(--color-gray-100);
background-color: var(--color-gray-1000);
background-color: var(--tooltip-background);
}
.tooltip-arrow {
......@@ -27,7 +29,7 @@
.tooltip-arrow--top {
border-width: var(--arrow-size, 6px) var(--arrow-size, 6px) 0
var(--arrow-size, 6px);
border-top-color: var(--color-gray-1000);
border-top-color: var(--tooltip-background);
bottom: 0;
transform: translateY(100%);
}
......@@ -35,7 +37,7 @@
.tooltip-arrow--bottom {
border-width: 0 var(--arrow-size, 6px) var(--arrow-size, 6px)
var(--arrow-size, 6px);
border-bottom-color: var(--color-gray-1000);
border-bottom-color: var(--tooltip-background);
top: 0;
transform: translateY(-100%);
}
......@@ -43,7 +45,7 @@
.tooltip-arrow--left {
border-width: var(--arrow-size, 6px) 0 var(--arrow-size, 6px)
var(--arrow-size, 6px);
border-left-color: var(--color-gray-1000);
border-left-color: var(--tooltip-background);
right: 0;
transform: translateX(100%);
}
......@@ -51,7 +53,7 @@
.tooltip-arrow--right {
border-width: var(--arrow-size, 6px) var(--arrow-size, 6px)
var(--arrow-size, 6px) 0;
border-right-color: var(--color-gray-1000);
border-right-color: var(--tooltip-background);
left: 0;
transform: translateX(-100%);
}
......
import { forwardRef } from 'react'
import { forwardRef, isValidElement } from 'react'
import { Tooltip as BaseTooltip } from '@base-ui-components/react/tooltip'
import { useDevOverlayContext } from '../../../dev-overlay.browser'
import { cx } from '../../utils/cx'
......@@ -9,72 +9,84 @@ type TooltipDirection = 'top' | 'bottom' | 'left' | 'right'
interface TooltipProps {
children: React.ReactNode
title: string | null
open?: React.ComponentProps<typeof BaseTooltip.Root>['open']
onOpenChange?: React.ComponentProps<typeof BaseTooltip.Root>['onOpenChange']
anchor?: React.ComponentProps<typeof BaseTooltip.Positioner>['anchor']
asChild?: boolean
direction?: TooltipDirection
arrowSize?: number
offset?: number
className?: string
}
export const Tooltip = forwardRef<HTMLDivElement, TooltipProps>(
function Tooltip(
{
className,
children,
title,
direction = 'top',
arrowSize = 6,
offset = 8,
},
ref
) {
const { shadowRoot } = useDevOverlayContext()
if (!title) {
return children
}
return (
<BaseTooltip.Provider>
<BaseTooltip.Root delay={400}>
<BaseTooltip.Trigger
ref={ref}
render={(triggerProps) => {
return <span {...triggerProps}>{children}</span>
}}
/>
export const Tooltip = forwardRef<HTMLElement, TooltipProps>(function Tooltip(
{
className,
children,
title,
open,
onOpenChange,
anchor,
asChild = false,
direction = 'top',
arrowSize = 6,
offset = 8,
},
ref
) {
const { shadowRoot } = useDevOverlayContext()
if (!title) {
return children
}
return (
<BaseTooltip.Provider>
<BaseTooltip.Root delay={400} onOpenChange={onOpenChange} open={open}>
<BaseTooltip.Trigger
ref={ref}
render={
asChild && isValidElement<Record<string, unknown>>(children)
? children
: (triggerProps) => {
return <span {...triggerProps}>{children}</span>
}
}
/>
<BaseTooltip.Portal container={shadowRoot}>
<BaseTooltip.Positioner
side={direction}
sideOffset={offset + arrowSize}
className="tooltip-positioner"
<BaseTooltip.Portal container={shadowRoot}>
<BaseTooltip.Positioner
anchor={anchor}
positionMethod={anchor ? 'fixed' : undefined}
side={direction}
sideOffset={offset + arrowSize}
className="tooltip-positioner"
style={
{
'--anchor-width': `${arrowSize}px`,
'--anchor-height': `${arrowSize}px`,
} as React.CSSProperties
}
>
<BaseTooltip.Popup
className={cx('tooltip', className)}
style={
{
'--anchor-width': `${arrowSize}px`,
'--anchor-height': `${arrowSize}px`,
'--arrow-size': `${arrowSize}px`,
} as React.CSSProperties
}
>
<BaseTooltip.Popup
className={cx('tooltip', className)}
{title}
<BaseTooltip.Arrow
className={cx('tooltip-arrow', `tooltip-arrow--${direction}`)}
style={
{
'--arrow-size': `${arrowSize}px`,
} as React.CSSProperties
}
>
{title}
<BaseTooltip.Arrow
className={cx('tooltip-arrow', `tooltip-arrow--${direction}`)}
style={
{
'--arrow-size': `${arrowSize}px`,
} as React.CSSProperties
}
/>
</BaseTooltip.Popup>
</BaseTooltip.Positioner>
</BaseTooltip.Portal>
</BaseTooltip.Root>
</BaseTooltip.Provider>
)
}
)
/>
</BaseTooltip.Popup>
</BaseTooltip.Positioner>
</BaseTooltip.Portal>
</BaseTooltip.Root>
</BaseTooltip.Provider>
)
})
......@@ -374,6 +374,7 @@ export const PanelRouter = () => {
{isAppRouter && !!process.env.__NEXT_REQUEST_INSIGHTS && (
<PanelRoute name="request-insights">
<DynamicPanel
containerProps={{ className: 'request-insights-panel-container' }}
sharePanelSizeGlobally={false}
sharePanelPositionGlobally={false}
draggable
......
......@@ -612,17 +612,18 @@ describe('request insights', () => {
it('redacts sensitive request insight payload fields', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
const secret = 'Q2_SECRET_SENTINEL'
recordSpan({
name: 'fetch GET https://example.vercel.sh/api',
name: `fetch GET https://example.vercel.sh/api?token=${secret}`,
startTime: 100,
durationMs: 10,
requestId: 'req_4',
route: '/account',
attributes: {
'next.span_type': 'AppRender.fetch',
'http.url':
'https://user:pass@example.vercel.sh/api?access_token=abc&delay=1&signature=sig',
'http.url': `https://user:pass@example.vercel.sh/api?access_token=${secret}&delay=1&signature=sig`,
'http.method': 'GET',
'next.span_name': `fetch GET https://user:pass@example.vercel.sh/api?access_token=${secret}`,
'custom.secret': 'should not be exposed',
},
events: [
......@@ -662,11 +663,13 @@ describe('request insights', () => {
expect.objectContaining({
spans: [
expect.objectContaining({
name: 'fetch GET https://example.vercel.sh/api?query=redacted',
attributes: {
'next.span_type': 'AppRender.fetch',
'http.url':
'https://example.vercel.sh/api?access_token=redacted&delay=1&signature=redacted',
'http.url': 'https://example.vercel.sh/api?query=redacted',
'http.method': 'GET',
'next.span_name':
'fetch GET https://example.vercel.sh/api?query=redacted',
},
events: [
{
......@@ -688,13 +691,95 @@ describe('request insights', () => {
],
fetches: [
expect.objectContaining({
url: 'https://example.vercel.sh/api?access_token=redacted&delay=1&signature=redacted',
url: 'https://example.vercel.sh/api?query=redacted',
}),
expect.objectContaining({
url: 'https://example.vercel.sh/api?token=redacted&keep=1',
url: 'https://example.vercel.sh/api?query=redacted',
}),
],
})
)
expect(JSON.stringify(getRequestInsightsSnapshot())).not.toContain(secret)
})
it('only exposes bounded URLs without query payloads', () => {
process.env.__NEXT_REQUEST_INSIGHTS = 'true'
const cases = [
{
requestId: 'relative',
input: '/products/blue?sort=price#details',
expected: '/products/blue?query=redacted',
},
{
requestId: 'protocol-relative',
input: '//example.com/items?cursor=secret',
expected: '//example.com/items?query=redacted',
},
{
requestId: 'absolute',
input: 'https://user:password@example.com/items?visible=value#details',
expected: 'https://example.com/items?query=redacted',
},
{
requestId: 'opaque',
input: 'data:text/plain,secret',
expected: 'data:redacted',
},
{
requestId: 'untrusted-relative',
input: 'items?token=secret',
expected: undefined,
},
] as const
for (const testCase of cases) {
recordRequestInsightFetch(
{ requestId: testCase.requestId },
{ url: testCase.input, startTime: 100, durationMs: 1 }
)
}
const requests = new Map(
getRequestInsightsSnapshot().requests.map((request) => [
request.requestId,
request,
])
)
for (const testCase of cases) {
expect(requests.get(testCase.requestId)?.fetches[0]?.url).toBe(
testCase.expected
)
}
recordRequestInsightFetch(
{ requestId: 'oversized' },
{
url: `https://example.com/${'x'.repeat(64 * 1024)}`,
startTime: 100,
durationMs: 1,
}
)
expect(
getRequestInsightsSnapshot().requests.find(
(request) => request.requestId === 'oversized'
)?.fetches[0]?.url
).toBeUndefined()
recordRequestInsightFetch(
{ requestId: 'query-name' },
{
url: 'https://example.com/items?sk_live_SENTINEL',
startTime: 100,
durationMs: 1,
}
)
expect(
JSON.stringify(
getRequestInsightsSnapshot().requests.find(
(request) => request.requestId === 'query-name'
)
)
).not.toContain('sk_live_SENTINEL')
})
})
......@@ -29,6 +29,8 @@ import { reparentLocalSpans } from './local-span-recorder'
export { isRequestInsightsEnabled } from './span-store'
const MAX_REQUEST_INSIGHTS = 100
const MAX_REQUEST_INSIGHT_URL_LENGTH = 2048
const MAX_REQUEST_INSIGHT_RAW_URL_LENGTH = 64 * 1024
const REQUEST_INSIGHTS_STORE_KEY = Symbol.for('@next/request-insights-store')
const CLIENT_COMPONENT_LOADING_SPAN_TYPE =
'NextNodeServer.clientComponentLoading'
......@@ -63,9 +65,6 @@ const SAFE_SPAN_ATTRIBUTE_KEYS = new Set([
'next.span_name',
'next.span_type',
])
const SENSITIVE_PARAM_NAME_RE =
/(?:^|[_-])(?:access[_-]?token|api[_-]?key|auth|authorization|code|cookie|credential|id[_-]?token|jwt|key|password|secret|session|signature|sig|token)(?:$|[_-])/i
class InMemoryRequestInsightsStore {
private readonly requests = new Map<string, RequestInsight>()
private readonly requestTimings = new Map<
......@@ -123,7 +122,7 @@ class InMemoryRequestInsightsStore {
: insight.status
insight.spans.push({
name: span.name,
name: sanitizeSpanName(span),
startTime: spanStartTime,
durationMs: span.durationMs,
status: span.status,
......@@ -510,17 +509,45 @@ function sanitizeSpanAttributes(
}
const sanitized: NonNullable<SpanStoreRecord['attributes']> = {}
const sanitizedFetchSpanName =
attributes['next.span_type'] === 'AppRender.fetch'
? getSanitizedFetchSpanName(attributes)
: undefined
for (const [key, value] of Object.entries(attributes)) {
if (!SAFE_SPAN_ATTRIBUTE_KEYS.has(key)) {
continue
}
sanitized[key] = key === 'http.url' ? sanitizeUrlAttribute(value) : value
sanitized[key] =
key === 'http.url'
? sanitizeUrlAttribute(value)
: key === 'next.span_name' && sanitizedFetchSpanName
? sanitizedFetchSpanName
: value
}
return Object.keys(sanitized).length > 0 ? sanitized : undefined
}
function sanitizeSpanName(span: SpanStoreRecord): string {
if (span.attributes?.['next.span_type'] !== 'AppRender.fetch') {
return span.name
}
return getSanitizedFetchSpanName(span.attributes, span.url)
}
function getSanitizedFetchSpanName(
attributes: NonNullable<SpanStoreRecord['attributes']>,
fallbackUrl?: string
): string {
const method = getStringAttribute(attributes['http.method'])
const url = sanitizeUrl(
getStringAttribute(attributes['http.url']) ?? fallbackUrl
)
return ['fetch', method, url].filter(Boolean).join(' ')
}
function sanitizeSpanEvents(
events: SpanStoreRecord['events']
): SpanStoreRecord['events'] {
......@@ -548,24 +575,67 @@ function sanitizeUrl(value: string | undefined): string | undefined {
return value
}
const isRelativeUrl = value.startsWith('/')
if (value.length > MAX_REQUEST_INSIGHT_RAW_URL_LENGTH) {
return undefined
}
const isProtocolRelativeUrl = value.startsWith('//')
const isRootRelativeUrl = !isProtocolRelativeUrl && value.startsWith('/')
const hasProtocol = /^[a-z][a-z\d+.-]*:/i.test(value)
if (!isProtocolRelativeUrl && !isRootRelativeUrl && !hasProtocol) {
return undefined
}
try {
const url = isRelativeUrl ? new URL(value, 'http://n') : new URL(value)
const url =
isProtocolRelativeUrl || isRootRelativeUrl
? new URL(value, 'http://n')
: new URL(value)
if (
url.protocol !== 'http:' &&
url.protocol !== 'https:' &&
!isProtocolRelativeUrl &&
!isRootRelativeUrl
) {
return `${url.protocol}${REDACTED_VALUE}`
}
url.username = ''
url.password = ''
url.hash = ''
for (const name of Array.from(url.searchParams.keys())) {
if (SENSITIVE_PARAM_NAME_RE.test(name)) {
url.searchParams.set(name, REDACTED_VALUE)
}
}
const hasApplicationQuery = Array.from(url.searchParams.keys()).some(
(name) => name !== '_rsc'
)
url.search = hasApplicationQuery ? `?query=${REDACTED_VALUE}` : ''
const sanitizedUrl = isProtocolRelativeUrl
? `//${url.host}${url.pathname}${url.search}`
: isRootRelativeUrl
? `${url.pathname}${url.search}`
: url.href
return isRelativeUrl ? `${url.pathname}${url.search}${url.hash}` : url.href
return truncateText(sanitizedUrl, MAX_REQUEST_INSIGHT_URL_LENGTH)
} catch {
return undefined
}
}
function truncateText(value: string, maxLength: number): string {
if (value.length <= maxLength) {
return value
}
let end = Math.max(0, maxLength - 1)
if (end > 0) {
const lastCharCode = value.charCodeAt(end - 1)
if (lastCharCode >= 0xd800 && lastCharCode <= 0xdbff) {
end--
}
}
return `${value.slice(0, end)}…`
}
function getStringAttribute(value: AttributeValue | undefined) {
......
import { EmitRequestInsightsSnapshot } from './snapshot-button'
export const instant = { level: 'experimental-error' }
export default function Page() {
return <p>instant insights</p>
return (
<>
<p>instant insights</p>
<EmitRequestInsightsSnapshot />
</>
)
}
'use client'
import { dispatcher } from 'next/dist/compiled/next-devtools'
export function EmitRequestInsightsSnapshot() {
return (
<button
id="emit-request-insights-snapshot"
onClick={() => {
const startTime = Date.now()
dispatcher.onRequestInsightsSnapshot({
requests: [
...Array.from({ length: 40 }, (_, index) => ({
requestId: `synthetic-request-${index}`,
kind: 'request' as const,
source: 'page' as const,
htmlRequestId: `synthetic-document-${index}`,
route: `/synthetic-${index}`,
url: `/synthetic-${index}`,
startTime: startTime + index,
durationMs: index + 1,
status: 'ok' as const,
spans: [],
fetches: [],
})),
{
requestId: 'synthetic-internal-request',
kind: 'instant-insights',
source: 'instant-insights',
htmlRequestId: 'synthetic-internal-document',
route: '/synthetic-internal',
url: '/synthetic-internal',
startTime: startTime + 40,
durationMs: 1,
status: 'ok',
spans: [
{
name: 'Run validation',
startTime: startTime + 40,
durationMs: 1,
status: 'ok',
attributes: {
'next.span_type': 'AppRender.instantInsights.runValidation',
'next.request_insights.omitted_spans': 3,
},
},
],
fetches: [],
},
],
})
}}
type="button"
>
Emit Request Insights snapshot
</button>
)
}
import { headers } from 'next/headers'
import { connection } from 'next/server'
export const instant = false
export default async function ProductPage({
params,
}: {
params: Promise<{ id: string }>
}) {
await connection()
const { id } = await params
const host = (await headers()).get('host')
if (!host) {
throw new Error('Missing request host')
}
await fetch(`http://${host}/api/source?token=Q2_SECRET_SENTINEL`, {
cache: 'no-store',
})
return <p id="product-id">{id}</p>
}
......@@ -507,6 +507,113 @@ describe('request insights', () => {
})
})
it('restores Internal activity across an overlay reload', async () => {
const browser = await next.browser('/instant-insights')
shouldResetRequestInsightsConfig = true
await patchRequestInsightsConfig({ showInternal: true })
await retry(async () => {
const config = JSON.parse(
await next.readFile('build/dev/cache/next-devtools-config.json')
)
expect(config.requestInsights?.showInternal).toBe(true)
})
await browser.refresh()
await browser.elementById('emit-request-insights-snapshot').click()
await openRequestInsightsPanel(browser)
await browser.elementByCss('.request-insights-settings-trigger').click()
await retry(async () => {
const state = await browser.eval(() => {
const root = document.querySelector('nextjs-portal')?.shadowRoot
const item = Array.from(
root?.querySelectorAll('.request-insights-settings-item') ?? []
).find((candidate) =>
candidate.textContent?.includes('Internal activity')
)
return {
checked:
item
?.querySelector('.request-insights-settings-checkbox')
?.getAttribute('data-checked') ?? null,
syntheticInternalVisible: Array.from(
root?.querySelectorAll(
'.request-insights-row[data-internal="true"]'
) ?? []
).some((row) =>
row.getAttribute('aria-label')?.includes('/synthetic-internal')
),
}
})
expect(state).toEqual({
checked: 'true',
syntheticInternalVisible: true,
})
})
await browser.elementByCss('.request-insights-settings-trigger').click()
await browser
.elementByCss('.request-insights-row[aria-label*="/synthetic-internal"]')
.click()
await retry(async () => {
expect(
await browser.elementByCss('.request-insights-overview').text()
).toContain('1 span, 3 omitted')
})
})
it('contains Request Insights scrolling inside the overlay panes', async () => {
const browser = await next.browser('/instant-insights')
await browser.elementById('emit-request-insights-snapshot').click()
await openRequestInsightsPanel(browser)
await retry(async () => {
const state = await browser.eval(() => {
document.body.style.minHeight = '300vh'
window.scrollTo(0, 200)
const root = document.querySelector('nextjs-portal')?.shadowRoot
const list = root?.querySelector<HTMLElement>('.request-insights-list')
const details = root?.querySelector<HTMLElement>(
'.request-insights-details'
)
const pageScrollBefore = window.scrollY
if (list) {
list.scrollTop = list.scrollHeight
list.scrollBy({ top: 100 })
}
return {
detailsOverscroll: details
? getComputedStyle(details).overscrollBehaviorY
: null,
listOverflow: list ? getComputedStyle(list).overflowY : null,
listOverscroll: list
? getComputedStyle(list).overscrollBehaviorY
: null,
listScrollable: list
? list.scrollHeight > list.clientHeight && list.scrollTop > 0
: false,
pageScrollBefore,
pageScrollAfter: window.scrollY,
}
})
expect(state).toEqual({
detailsOverscroll: 'contain',
listOverflow: 'auto',
listOverscroll: 'contain',
listScrollable: true,
pageScrollBefore: 200,
pageScrollAfter: 200,
})
})
})
it('hides internal activity behind the settings menu', async () => {
const browser = await next.browser('/instant-insights')
shouldResetRequestInsightsConfig = true
......@@ -752,9 +859,259 @@ describe('request insights', () => {
})
})
it('shows concrete request URLs, route params, and fetch origins', async () => {
const browser = await next.browser('/products/blue?tab=details')
await retry(async () => {
expect(await browser.elementById('product-id').text()).toBe('blue')
})
await openRequestInsightsPanel(browser)
await retry(async () => {
const selected = await browser.eval(() => {
const root = document.querySelector('nextjs-portal')?.shadowRoot
const row = Array.from(
root?.querySelectorAll<HTMLButtonElement>('.request-insights-row') ??
[]
).find((candidate) =>
candidate.textContent?.includes('/products/blue?query=redacted')
)
row?.click()
return row !== undefined
})
expect(selected).toBe(true)
})
await retry(async () => {
const details = await browser.eval(() => {
const root = document.querySelector('nextjs-portal')?.shadowRoot
const panel = root?.querySelector('.request-insights-details')
return {
text: panel?.textContent ?? '',
paramsLabel:
panel?.querySelector('.request-insights-params-trigger')
?.textContent ?? '',
fetchOrigins: Array.from(
panel?.querySelectorAll('.request-insights-fetch-origin') ?? []
).map((element) => element.textContent ?? ''),
fetchTraceLabels: Array.from(
panel?.querySelectorAll(
'.request-insights-span-row[data-kind="fetch"] .request-insights-span-label'
) ?? []
).map((element) => element.textContent ?? ''),
}
})
expect(details.text).toContain('/products/blue?query=redacted')
expect(details.text).toContain('Route /products/[id]')
expect(details.paramsLabel).toBe('Params id')
expect(details.fetchOrigins).toContain('Same origin')
expect(
details.fetchTraceLabels.some((label) => label.includes('Same origin'))
).toBe(true)
expect(details.text).not.toContain('Q2_SECRET_SENTINEL')
})
})
it('keeps trace inspection anchored while the panel is resized', async () => {
const browser = await next.browser('/products/blue?tab=details')
await openRequestInsightsPanel(browser)
await retry(async () => {
const selected = await browser.eval(() => {
const root = document.querySelector('nextjs-portal')?.shadowRoot
const row = Array.from(
root?.querySelectorAll<HTMLButtonElement>('.request-insights-row') ??
[]
).find((candidate) =>
candidate.textContent?.includes('/products/blue?query=redacted')
)
row?.click()
return row !== undefined
})
expect(selected).toBe(true)
})
await browser
.locator('nextjs-portal .request-insights-span-row[data-active="true"]')
.hover()
await browser.locator('nextjs-portal .request-insights-trace-rows').focus()
const readTraceState = () =>
browser.eval(() => {
const root = document.querySelector('nextjs-portal')?.shadowRoot
const panel = root?.querySelector<HTMLElement>(
'.request-insights-panel-container'
)
const listbox = root?.querySelector<HTMLElement>(
'.request-insights-trace-rows'
)
const activeDescendant = listbox?.getAttribute('aria-activedescendant')
const activeRow = listbox?.querySelector<HTMLElement>(
'.request-insights-span-row[data-active="true"]'
)
const firstRow = listbox?.querySelector<HTMLElement>(
'.request-insights-span-row'
)
const tooltip = root?.querySelector<HTMLElement>(
'.request-insights-trace-tooltip'
)
const panelRect = panel?.getBoundingClientRect()
const rowRect = activeRow?.getBoundingClientRect()
const tooltipRect = tooltip?.getBoundingClientRect()
return {
activeDescendant,
activeRowId: activeRow?.id ?? null,
activeTraceItemId: activeRow?.dataset.traceItemId ?? null,
firstRowId: firstRow?.id ?? null,
activeLabel: activeRow?.getAttribute('aria-label') ?? null,
focused: root?.activeElement === listbox,
horizontalOverlap:
!!rowRect &&
!!tooltipRect &&
tooltipRect.right >= rowRect.left &&
tooltipRect.left <= rowRect.right,
tooltipLabel: tooltip?.textContent?.trim() ?? null,
tooltipNearPanel:
!!panelRect &&
!!tooltipRect &&
tooltipRect.right >= panelRect.left - 100 &&
tooltipRect.left <= panelRect.right + 100 &&
tooltipRect.bottom >= panelRect.top - 100 &&
tooltipRect.top <= panelRect.bottom + 100,
verticalGap:
rowRect && tooltipRect
? Math.min(
Math.abs(tooltipRect.bottom - rowRect.top),
Math.abs(tooltipRect.top - rowRect.bottom)
)
: Number.POSITIVE_INFINITY,
}
})
const expectAnchoredTrace = async (expectedTraceItemId?: string | null) =>
retry(async () => {
const state = await readTraceState()
expect(state.activeDescendant).toEqual(expect.any(String))
if (expectedTraceItemId !== undefined) {
expect(state.activeTraceItemId).toBe(expectedTraceItemId)
}
expect(state.activeRowId).toBe(state.activeDescendant)
expect(state.activeLabel).toBe(state.tooltipLabel)
expect(state.focused).toBe(true)
expect(state.horizontalOverlap).toBe(true)
expect(state.tooltipNearPanel).toBe(true)
expect(state.verticalGap).toBeLessThan(160)
return state
})
const initialState = await expectAnchoredTrace()
await browser.eval(() => {
const root = document.querySelector('nextjs-portal')?.shadowRoot
root
?.querySelector<HTMLElement>('.request-insights-trace-rows')
?.dispatchEvent(
new KeyboardEvent('keydown', {
altKey: true,
bubbles: true,
key: 'ArrowDown',
})
)
})
expect((await readTraceState()).activeTraceItemId).toBe(
initialState.activeTraceItemId
)
await browser.keydown('ArrowDown')
await browser.keyup('ArrowDown')
const nextState = await retry(async () => {
const state = await readTraceState()
expect(state.activeTraceItemId).not.toBe(initialState.activeTraceItemId)
return state
})
await expectAnchoredTrace(nextState.activeTraceItemId)
const columnCountAtPanelWidth = async (width: number): Promise<number> => {
return await browser.eval(`(() => {
const root = document.querySelector('nextjs-portal').shadowRoot
const panelContainer = root.querySelector('.dynamic-panel-container')
panelContainer.style.width = '${width}px'
const panel = root.querySelector('.request-insights-panel')
return getComputedStyle(panel).gridTemplateColumns.split(' ').length
})()`)
}
await retry(async () => {
expect(await columnCountAtPanelWidth(760)).toBe(2)
})
await expectAnchoredTrace()
await retry(async () => {
expect(await columnCountAtPanelWidth(560)).toBe(1)
})
await expectAnchoredTrace()
await retry(async () => {
expect(await columnCountAtPanelWidth(760)).toBe(2)
})
await expectAnchoredTrace()
await browser
.locator('nextjs-portal .request-insights-row[aria-label^="/api/source"]')
.first()
.click()
await retry(async () => {
const selection = await browser.eval(() => {
const root = document.querySelector('nextjs-portal')?.shadowRoot
const row = Array.from(
root?.querySelectorAll<HTMLButtonElement>('.request-insights-row') ??
[]
).find((candidate) => candidate.textContent?.includes('/api/source'))
return {
found: row !== undefined,
selected: row?.dataset.selected,
title: root
?.querySelector<HTMLElement>('.request-insights-title')
?.textContent?.trim(),
activeRowId: root?.querySelector<HTMLElement>(
'.request-insights-span-row[data-active="true"]'
)?.id,
firstRowId: root?.querySelector<HTMLElement>(
'.request-insights-span-row'
)?.id,
}
})
expect(selection.found).toBe(true)
expect(selection.selected).toBe('true')
expect(selection.title).toBe('/api/source?query=redacted')
expect(selection.firstRowId).toEqual(expect.any(String))
expect(selection.activeRowId).toBe(selection.firstRowId)
})
await browser
.locator('nextjs-portal .request-insights-span-row[data-active="true"]')
.hover()
await browser.locator('nextjs-portal .request-insights-trace-rows').focus()
const switchedState = await expectAnchoredTrace()
expect(switchedState.activeDescendant).toBe(switchedState.firstRowId)
})
it('classifies an App Route before its handler completes', async () => {
const existingRequestIds = new Set(
(
(await next
.fetch('/_next/development/request-insights')
.then((response) => response.json())) as {
requests: RequestInsight[]
}
).requests.map((request) => request.requestId)
)
const waitKey = `active-${Date.now()}`
const requestPath = `/api/app-stream-lifecycle?wait=${waitKey}`
const recordedRequestPath = '/api/app-stream-lifecycle?query=redacted'
const responsePromise = next.fetch(requestPath)
try {
......@@ -765,7 +1122,10 @@ describe('request insights', () => {
requests: RequestInsight[]
}
const matchingRequests = snapshot.requests.filter(
(request) => request.url === requestPath
(request) =>
!existingRequestIds.has(request.requestId) &&
request.url === recordedRequestPath &&
request.kind !== 'instant-insights'
)
expect(matchingRequests).toHaveLength(1)
......@@ -798,7 +1158,12 @@ describe('request insights', () => {
}
const matchingRequests = snapshot.requests.filter(
(request) =>
request.url === requestPath && request.kind !== 'instant-insights'
!existingRequestIds.has(request.requestId) &&
request.url === recordedRequestPath &&
request.kind !== 'instant-insights' &&
request.spans.some(
(span) => span.attributes?.['http.method'] === 'GET'
)
)
expect(matchingRequests).toHaveLength(1)
......@@ -817,7 +1182,17 @@ describe('request insights', () => {
})
it('classifies a Page after proxy completes', async () => {
const existingRequestIds = new Set(
(
(await next
.fetch('/_next/development/request-insights')
.then((response) => response.json())) as {
requests: RequestInsight[]
}
).requests.map((request) => request.requestId)
)
const requestPath = `/api/proxied-page?run=${Date.now()}`
const recordedRequestPath = '/api/proxied-page?query=redacted'
const response = await next.fetch(requestPath)
expect(response.status).toBe(200)
expect(await response.text()).toContain('proxied page')
......@@ -830,7 +1205,9 @@ describe('request insights', () => {
}
const matchingRequests = snapshot.requests.filter(
(request) =>
request.url === requestPath && request.kind !== 'instant-insights'
!existingRequestIds.has(request.requestId) &&
request.url === recordedRequestPath &&
request.kind !== 'instant-insights'
)
expect(matchingRequests).toHaveLength(1)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment