Unverified Commit 7de4c072 authored by Jude Gao's avatar Jude Gao Committed by GitHub

(feat) support client-side instrumentation (#76916)

parent afa3c94b
...@@ -244,6 +244,7 @@ pub async fn get_next_client_import_map( ...@@ -244,6 +244,7 @@ pub async fn get_next_client_import_map(
} }
insert_turbopack_dev_alias(&mut import_map).await?; insert_turbopack_dev_alias(&mut import_map).await?;
insert_instrumentation_client_alias(&mut import_map, project_path).await?;
Ok(import_map.cell()) Ok(import_map.cell())
} }
...@@ -1143,6 +1144,26 @@ async fn insert_turbopack_dev_alias(import_map: &mut ImportMap) -> Result<()> { ...@@ -1143,6 +1144,26 @@ async fn insert_turbopack_dev_alias(import_map: &mut ImportMap) -> Result<()> {
Ok(()) Ok(())
} }
/// Handles instrumentation-client.ts bundling logic
async fn insert_instrumentation_client_alias(
import_map: &mut ImportMap,
project_path: ResolvedVc<FileSystemPath>,
) -> Result<()> {
insert_alias_to_alternatives(
import_map,
"private-next-instrumentation-client",
vec![
request_to_import_mapping(project_path, "./src/instrumentation-client"),
request_to_import_mapping(project_path, "./src/instrumentation-client.ts"),
request_to_import_mapping(project_path, "./instrumentation-client"),
request_to_import_mapping(project_path, "./instrumentation-client.ts"),
ImportMapping::Ignore.resolved_cell(),
],
);
Ok(())
}
/// Creates a direct import mapping to the result of resolving a request /// Creates a direct import mapping to the result of resolving a request
/// in a context. /// in a context.
fn request_to_import_mapping( fn request_to_import_mapping(
......
...@@ -139,6 +139,19 @@ export function createWebpackAliases({ ...@@ -139,6 +139,19 @@ export function createWebpackAliases({
...(pagesDir ? { [PAGES_DIR_ALIAS]: pagesDir } : {}), ...(pagesDir ? { [PAGES_DIR_ALIAS]: pagesDir } : {}),
...(appDir ? { [APP_DIR_ALIAS]: appDir } : {}), ...(appDir ? { [APP_DIR_ALIAS]: appDir } : {}),
[ROOT_DIR_ALIAS]: dir, [ROOT_DIR_ALIAS]: dir,
...(isClient
? {
'private-next-instrumentation-client': [
path.join(dir, 'src', 'instrumentation-client'),
path.join(dir, 'instrumentation-client'),
'private-next-empty-module',
],
// disable typechecker, webpack5 allows aliases to be set to false to create a no-op module
'private-next-empty-module': false as any,
}
: {}),
[DOT_NEXT_ALIAS]: distDir, [DOT_NEXT_ALIAS]: distDir,
...(isClient || isEdgeServer ? getOptimizedModuleAliases() : {}), ...(isClient || isEdgeServer ? getOptimizedModuleAliases() : {}),
...(reactProductionProfiling ? getReactProfilingInProduction() : {}), ...(reactProductionProfiling ? getReactProfilingInProduction() : {}),
......
...@@ -240,6 +240,9 @@ export function getDefineEnv({ ...@@ -240,6 +240,9 @@ export function getDefineEnv({
'process.env.__NEXT_TELEMETRY_DISABLED': Boolean( 'process.env.__NEXT_TELEMETRY_DISABLED': Boolean(
process.env.NEXT_TELEMETRY_DISABLED process.env.NEXT_TELEMETRY_DISABLED
), ),
'process.env.__NEXT_EXPERIMENTAL_CLIENT_INSTRUMENTATION_HOOK': Boolean(
config.experimental.clientInstrumentationHook
),
...(isNodeOrEdgeCompilation ...(isNodeOrEdgeCompilation
? { ? {
// Fix bad-actors in the npm ecosystem (e.g. `node-formidable`) // Fix bad-actors in the npm ecosystem (e.g. `node-formidable`)
......
...@@ -225,6 +225,7 @@ function Root({ children }: React.PropsWithChildren<{}>) { ...@@ -225,6 +225,7 @@ function Root({ children }: React.PropsWithChildren<{}>) {
// eslint-disable-next-line react-hooks/rules-of-hooks // eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => { React.useEffect(() => {
window.__NEXT_HYDRATED = true window.__NEXT_HYDRATED = true
window.__NEXT_HYDRATED_AT = performance.now()
window.__NEXT_HYDRATED_CB?.() window.__NEXT_HYDRATED_CB?.()
}, []) }, [])
} }
......
// TODO-APP: hydration warning // TODO-APP: hydration warning
import './app-webpack' import './app-webpack'
import '../lib/require-instrumentation-client'
import { appBootstrap } from './app-bootstrap' import { appBootstrap } from './app-bootstrap'
import { initializeDevBuildIndicatorForAppRouter } from './dev/dev-build-indicator/initialize-for-app-router' import { initializeDevBuildIndicatorForAppRouter } from './dev/dev-build-indicator/initialize-for-app-router'
......
// TODO-APP: hydration warning // TODO-APP: hydration warning
import '../lib/require-instrumentation-client'
import { appBootstrap } from './app-bootstrap' import { appBootstrap } from './app-bootstrap'
window.next.version += '-turbo' window.next.version += '-turbo'
......
// This import must go first because it needs to patch webpack chunk loading // This import must go first because it needs to patch webpack chunk loading
// before React patches chunk loading. // before React patches chunk loading.
import './app-webpack' import './app-webpack'
import '../lib/require-instrumentation-client'
import { appBootstrap } from './app-bootstrap' import { appBootstrap } from './app-bootstrap'
appBootstrap(() => { appBootstrap(() => {
......
...@@ -55,6 +55,7 @@ declare global { ...@@ -55,6 +55,7 @@ declare global {
interface Window { interface Window {
/* test fns */ /* test fns */
__NEXT_HYDRATED?: boolean __NEXT_HYDRATED?: boolean
__NEXT_HYDRATED_AT?: number
__NEXT_HYDRATED_CB?: () => void __NEXT_HYDRATED_CB?: () => void
/* prod */ /* prod */
...@@ -612,6 +613,7 @@ function Root({ ...@@ -612,6 +613,7 @@ function Root({
// eslint-disable-next-line react-hooks/rules-of-hooks // eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => { React.useEffect(() => {
window.__NEXT_HYDRATED = true window.__NEXT_HYDRATED = true
window.__NEXT_HYDRATED_AT = performance.now()
if (window.__NEXT_HYDRATED_CB) { if (window.__NEXT_HYDRATED_CB) {
window.__NEXT_HYDRATED_CB() window.__NEXT_HYDRATED_CB()
......
// A client-side entry point for Turbopack builds. Includes logic to load chunks, // A client-side entry point for Turbopack builds. Includes logic to load chunks,
// but does not include development-time features like hot module reloading. // but does not include development-time features like hot module reloading.
import '../lib/require-instrumentation-client'
// TODO: Remove use of `any` type. // TODO: Remove use of `any` type.
import { initialize, version, router, emitter, hydrate } from './' import { initialize, version, router, emitter, hydrate } from './'
// TODO: This seems necessary, but is a module in the `dev` directory. // TODO: This seems necessary, but is a module in the `dev` directory.
......
import './webpack' import './webpack'
import '../lib/require-instrumentation-client'
import { initialize, hydrate, version, router, emitter } from './' import { initialize, hydrate, version, router, emitter } from './'
declare global { declare global {
......
import '../lib/require-instrumentation-client'
import { hydrate, router } from './' import { hydrate, router } from './'
import initOnDemandEntries from './dev/on-demand-entries-client' import initOnDemandEntries from './dev/on-demand-entries-client'
import { devBuildIndicator } from './dev/dev-build-indicator/internal/dev-build-indicator' import { devBuildIndicator } from './dev/dev-build-indicator/internal/dev-build-indicator'
......
/**
* This module imports the client instrumentation hook from the project root.
*
* The `private-next-instrumentation-client` module is automatically aliased to
* the `instrumentation-client.ts` file in the project root by webpack or turbopack.
*/
if (process.env.__NEXT_EXPERIMENTAL_CLIENT_INSTRUMENTATION_HOOK) {
require('private-next-instrumentation-client')
}
...@@ -455,6 +455,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -455,6 +455,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
buildTimeThresholdMs: z.number().int(), buildTimeThresholdMs: z.number().int(),
}) })
.optional(), .optional(),
clientInstrumentationHook: z.boolean().optional(),
}) })
.optional(), .optional(),
exportPathMap: z exportPathMap: z
......
...@@ -601,6 +601,15 @@ export interface ExperimentalConfig { ...@@ -601,6 +601,15 @@ export interface ExperimentalConfig {
*/ */
buildTimeThresholdMs: number buildTimeThresholdMs: number
} }
/**
* Enables the client instrumentation hook.
* Loads the instrumentation-client.ts file from the project root
* and executes it on the client side before hydration.
*
* Note: Use with caution as this can negatively impact page loading performance.
*/
clientInstrumentationHook?: boolean
} }
export type ExportPathMap = { export type ExportPathMap = {
......
import React from 'react'
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import React from 'react'
export default function Page() {
return <h1>App</h1>
}
;(window as any).__INSTRUMENTATION_CLIENT_EXECUTED_AT = performance.now()
module.exports = {
experimental: {
clientInstrumentationHook: true,
},
}
module.exports = {
experimental: {
clientInstrumentationHook: true,
},
}
import React from 'react'
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import React from 'react'
export default function Page() {
return <h1>App with src folder</h1>
}
;(window as any).__INSTRUMENTATION_CLIENT_EXECUTED_AT = performance.now()
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import path from 'path'
describe('Instrumentation Client Hook', () => {
const testCases = [
{
name: 'With src folder',
appDir: 'app-with-src',
},
{
name: 'App Router',
appDir: 'app-router',
},
{
name: 'Pages Router',
appDir: 'pages-router',
},
]
testCases.forEach(({ name, appDir }) => {
describe(name, () => {
const { next } = nextTestSetup({
files: path.join(__dirname, appDir),
})
it(`should execute instrumentation-client from ${name.toLowerCase()} before hydration`, async () => {
const browser = await next.browser('/')
const instrumentationTime = await browser.eval(
`window.__INSTRUMENTATION_CLIENT_EXECUTED_AT`
)
const hydrationTime = await browser.eval(`window.__NEXT_HYDRATED_AT`)
expect(instrumentationTime).toBeDefined()
expect(hydrationTime).toBeDefined()
expect(instrumentationTime).toBeLessThan(hydrationTime)
})
})
})
describe('HMR in development mode', () => {
const { next, isNextDev } = nextTestSetup({
files: path.join(__dirname, 'app-router'),
})
if (isNextDev) {
it('should reload instrumentation-client when modified', async () => {
const browser = await next.browser('/')
const initialTime = await browser.eval(
`window.__INSTRUMENTATION_CLIENT_EXECUTED_AT`
)
expect(initialTime).toBeDefined()
// Modify the instrumentation-client.ts file
const instrumentationPath = 'instrumentation-client.ts'
const originalContent = await next.readFile(instrumentationPath)
await next.patchFile(
instrumentationPath,
`
window.__INSTRUMENTATION_CLIENT_EXECUTED_AT = Date.now();
window.__INSTRUMENTATION_CLIENT_UPDATED = true;
`
)
await retry(async () => {
// Check if the updated instrumentation client was executed
const updatedFlag = await browser.eval(
`window.__INSTRUMENTATION_CLIENT_UPDATED`
)
expect(updatedFlag).toBe(true)
// Verify new execution time
const newTime = await browser.eval(
`window.__INSTRUMENTATION_CLIENT_EXECUTED_AT`
)
expect(newTime).toBeDefined()
expect(newTime).toBeGreaterThan(initialTime)
})
// Restore the original file
await next.patchFile(instrumentationPath, originalContent)
})
} else {
// Add a dummy test when not in dev mode
it('skips tests in non-dev mode', () => {
console.log(
'Skipping instrumentation-client-hook tests in non-dev mode'
)
})
}
})
})
;(window as any).__INSTRUMENTATION_CLIENT_EXECUTED_AT = performance.now()
module.exports = {
experimental: {
clientInstrumentationHook: true,
},
}
import React from 'react'
export default function Page() {
return <h1>Pages Router</h1>
}
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