Unverified Commit 19dcd133 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[instant] Handle more instant declaration patterns (#90251)

Adds handling for 


```tsx
export { unstable_instant } from './config'
       ^
```
```tsx
const unstable_instant = ...
                         ^
export { unstable_instant }
```
```tsx
const instant = ...
                ^
export { instant as unstable_instant }
```
We're not following assignments recursively and stop at the first declaration:
```tsx
const _instant = ...
const instant = _instant
                ^
export { instant as unstable_instant }
```
parent f33b8af4
......@@ -17,22 +17,94 @@ struct DebugInstantStack {
instant_export_span: Option<Span>,
}
/// Given an export specifier, returns `Some((exported_name, local_name))` if
/// the exported name is `unstable_instant`.
fn get_instant_specifier_names(specifier: &ExportSpecifier) -> Option<(&Ident, &Ident)> {
match specifier {
// `export { orig as unstable_instant }`
ExportSpecifier::Named(ExportNamedSpecifier {
exported: Some(ModuleExportName::Ident(exported)),
orig: ModuleExportName::Ident(orig),
..
}) if exported.sym == "unstable_instant" => Some((exported, orig)),
// `export { unstable_instant }`
ExportSpecifier::Named(ExportNamedSpecifier {
exported: None,
orig: ModuleExportName::Ident(orig),
..
}) if orig.sym == "unstable_instant" => Some((orig, orig)),
_ => None,
}
}
/// Find the initializer span of a variable declaration with the given name.
fn find_var_init_span(items: &[ModuleItem], local_name: &str) -> Option<Span> {
for item in items {
let decl = match item {
ModuleItem::Stmt(Stmt::Decl(Decl::Var(var_decl))) => var_decl,
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) => {
if let Decl::Var(var_decl) = &export_decl.decl {
var_decl
} else {
continue;
}
}
_ => continue,
};
for d in &decl.decls {
if let Pat::Ident(ident) = &d.name {
if ident.id.sym == local_name {
if let Some(init) = &d.init {
return Some(init.span());
}
}
}
}
}
None
}
impl Fold for DebugInstantStack {
fn fold_module_items(&mut self, items: Vec<ModuleItem>) -> Vec<ModuleItem> {
// Scan for `export const unstable_instant = ...`
for item in &items {
if let ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) = item {
if let Decl::Var(var_decl) = &export_decl.decl {
for decl in &var_decl.decls {
if let Pat::Ident(ident) = &decl.name {
if ident.id.sym == "unstable_instant" {
if let Some(init) = &decl.init {
self.instant_export_span = Some(init.span());
match item {
// `export const unstable_instant = ...`
ModuleItem::ModuleDecl(ModuleDecl::ExportDecl(export_decl)) => {
if let Decl::Var(var_decl) = &export_decl.decl {
for decl in &var_decl.decls {
if let Pat::Ident(ident) = &decl.name {
if ident.id.sym == "unstable_instant" {
if let Some(init) = &decl.init {
self.instant_export_span = Some(init.span());
}
}
}
}
}
}
// `export { unstable_instant }` or `export { x as unstable_instant }`
// with or without `from '...'`
ModuleItem::ModuleDecl(ModuleDecl::ExportNamed(named)) => {
for specifier in &named.specifiers {
if let Some((_exported, orig)) = get_instant_specifier_names(specifier) {
if named.src.is_some() {
// Re-export: `export { unstable_instant } from './config'`
// Point at the export specifier itself
self.instant_export_span = Some(specifier.span());
} else {
// Local named export: try to find the variable's initializer
let local_name = &orig.sym;
if let Some(init_span) = find_var_init_span(&items, local_name) {
self.instant_export_span = Some(init_span);
} else {
// Fallback to the export specifier span
self.instant_export_span = Some(specifier.span());
}
}
}
}
}
_ => {}
}
}
......
const instant = { prefetch: 'static' }
export { instant as unstable_instant }
export default function Page() {
return <div>Hello</div>
}
const instant = {
prefetch: 'static'
};
export { instant as unstable_instant };
export default function Page() {
return <div>Hello</div>;
}
export const __debugCreateInstantConfigStack = process.env.NODE_ENV !== 'production' ? function unstable_instant() {
const error = new Error(' ');
error.name = 'Instant Validation';
return error;
} : null;
{"version":3,"sources":["input.js"],"sourcesContent":["const instant = { prefetch: 'static' }\nexport { instant as unstable_instant }\n\nexport default function Page() {\n return <div>Hello</div>\n}\n"],"names":[],"mappings":"AAAA,MAAM,UAAU;IAAE,UAAU;AAAS;AACrC,SAAS,WAAW,gBAAgB,GAAE;AAEtC,eAAe,SAAS;IACtB,QAAQ,IAAI,KAAK,EAAE;AACrB;uFALgB;kBAAA"}
const _instant = { prefetch: 'static' }
const instant = _instant
export { instant as unstable_instant }
export default function Page() {
return <div>Hello</div>
}
const _instant = {
prefetch: 'static'
};
const instant = _instant;
export { instant as unstable_instant };
export default function Page() {
return <div>Hello</div>;
}
export const __debugCreateInstantConfigStack = process.env.NODE_ENV !== 'production' ? function unstable_instant() {
const error = new Error(' ');
error.name = 'Instant Validation';
return error;
} : null;
{"version":3,"sources":["input.js"],"sourcesContent":["const _instant = { prefetch: 'static' }\nconst instant = _instant\nexport { instant as unstable_instant }\n\nexport default function Page() {\n return <div>Hello</div>\n}\n"],"names":[],"mappings":"AAAA,MAAM,WAAW;IAAE,UAAU;AAAS;AACtC,MAAM,UAAU;AAChB,SAAS,WAAW,gBAAgB,GAAE;AAEtC,eAAe,SAAS;IACtB,QAAQ,IAAI,KAAK,EAAE;AACrB;uFALgB;kBAAA"}
const unstable_instant = { prefetch: 'static' }
export { unstable_instant }
export default function Page() {
return <div>Hello</div>
}
const unstable_instant = {
prefetch: 'static'
};
export { unstable_instant };
export default function Page() {
return <div>Hello</div>;
}
export const __debugCreateInstantConfigStack = process.env.NODE_ENV !== 'production' ? function unstable_instant() {
const error = new Error(' ');
error.name = 'Instant Validation';
return error;
} : null;
{"version":3,"sources":["input.js"],"sourcesContent":["const unstable_instant = { prefetch: 'static' }\nexport { unstable_instant }\n\nexport default function Page() {\n return <div>Hello</div>\n}\n"],"names":[],"mappings":"AAAA,MAAM,mBAAmB;IAAE,UAAU;AAAS;AAC9C,SAAS,gBAAgB,GAAE;AAE3B,eAAe,SAAS;IACtB,QAAQ,IAAI,KAAK,EAAE;AACrB;uFALyB;kBAAA"}
export { unstable_instant } from './config'
export default function Page() {
return <div>Hello</div>
}
export { unstable_instant } from './config';
export default function Page() {
return <div>Hello</div>;
}
export const __debugCreateInstantConfigStack = process.env.NODE_ENV !== 'production' ? function unstable_instant() {
const error = new Error(' ');
error.name = 'Instant Validation';
return error;
} : null;
{"version":3,"sources":["input.js"],"sourcesContent":["export { unstable_instant } from './config'\n\nexport default function Page() {\n return <div>Hello</div>\n}\n"],"names":[],"mappings":"AAAA,SAAS,gBAAgB,QAAQ,WAAU;AAE3C,eAAe,SAAS;IACtB,QAAQ,IAAI,KAAK,EAAE;AACrB;uFAJS;kBAAA"}
import { cookies } from 'next/headers'
const instant = { prefetch: 'static' }
export { instant as unstable_instant }
export default async function Page() {
await cookies()
return <p>aliased export</p>
}
import { cookies } from 'next/headers'
const _instant = { prefetch: 'static' }
const instant = _instant
export { instant as unstable_instant }
export default async function Page() {
await cookies()
return <p>indirect export</p>
}
import { connection } from 'next/server'
import { ReactNode, Suspense } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<Suspense fallback={<div>Root suspense boundary...</div>}>
<html>
<body style={{ fontFamily: 'monospace' }}>
<Header />
<hr />
{children}
</body>
</html>
</Suspense>
)
}
function Header() {
return (
<header>
<a href="/">Home</a>{' '}
<Suspense fallback="...">
<div id="root-layout-timestamp">
<Now />
</div>
</Suspense>
</header>
)
}
async function Now() {
await connection()
return Date.now()
}
import { cookies } from 'next/headers'
const unstable_instant = { prefetch: 'static' }
export { unstable_instant }
export default async function Page() {
await cookies()
return <p>named export</p>
}
export const unstable_instant = { prefetch: 'static' }
import { cookies } from 'next/headers'
export { unstable_instant } from './config'
export default async function Page() {
await cookies()
return <p>reexport</p>
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from '../../../lib/next-test-utils'
describe('instant validation causes', () => {
const { next, skipped, isNextDev } = nextTestSetup({
files: __dirname,
skipDeployment: true,
env: {
NEXT_TEST_LOG_VALIDATION: '1',
},
})
if (skipped) return
if (!isNextDev) {
it.skip('Only implemented in dev', () => {})
return
}
let currentCliOutputIndex = 0
beforeEach(() => {
currentCliOutputIndex = next.cliOutput.length
})
function getCliOutputSinceMark(): string {
if (next.cliOutput.length < currentCliOutputIndex) {
currentCliOutputIndex = 0
}
return next.cliOutput.slice(currentCliOutputIndex)
}
type ValidationEvent =
| { type: 'validation_start'; requestId: string; url: string }
| { type: 'validation_end'; requestId: string; url: string }
function parseValidationMessages(output: string): ValidationEvent[] {
const messageRe = /<VALIDATION_MESSAGE>(.*?)<\/VALIDATION_MESSAGE>/g
const events: ValidationEvent[] = []
let match: RegExpExecArray | null
while ((match = messageRe.exec(output)) !== null) {
try {
events.push(JSON.parse(match[1]))
} catch (err) {
throw new Error(`Failed to parse message '${match[1]}'`, {
cause: err,
})
}
}
return events
}
function normalizeValidationUrl(url: string): string {
const parsed = new URL(url, 'http://n')
parsed.searchParams.delete('_rsc')
return parsed.pathname + parsed.search + parsed.hash
}
async function waitForValidation(targetUrl: string) {
const parsedTargetUrl = new URL(targetUrl)
const relativeTargetUrl =
parsedTargetUrl.pathname + parsedTargetUrl.search + parsedTargetUrl.hash
const requestId = await retry(
async () => {
const events = parseValidationMessages(getCliOutputSinceMark())
const start = events.find(
(e) =>
e.type === 'validation_start' &&
normalizeValidationUrl(e.url) === relativeTargetUrl
)
expect(start).toBeDefined()
return start!.requestId
},
undefined,
undefined,
`wait for validation of '${relativeTargetUrl}' to start`
)
await retry(
async () => {
const events = parseValidationMessages(getCliOutputSinceMark())
const end = events.find(
(e) => e.type === 'validation_end' && e.requestId === requestId
)
expect(end).toBeDefined()
},
undefined,
undefined,
'wait for validation to end'
)
}
it('named export - export { unstable_instant }', async () => {
const browser = await next.browser('/named-export')
await waitForValidation(await browser.url())
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"message": " ",
"source": "app/named-export/page.tsx (3:26) @ unstable_instant
> 3 | const unstable_instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/named-export/page.tsx (3:26)",
"Set.forEach <anonymous>",
],
},
],
"description": "Runtime data was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
To fix this:
Provide a fallback UI using <Suspense> around this component.
or
Move the Runtime data access into a deeper component wrapped in <Suspense>.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/named-export/page.tsx (7:16) @ Page
> 7 | await cookies()
| ^",
"stack": [
"Page app/named-export/page.tsx (7:16)",
],
}
`)
})
it('aliased export - export { instant as unstable_instant }', async () => {
const browser = await next.browser('/aliased-export')
await waitForValidation(await browser.url())
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"message": " ",
"source": "app/aliased-export/page.tsx (3:17) @ unstable_instant
> 3 | const instant = { prefetch: 'static' }
| ^",
"stack": [
"unstable_instant app/aliased-export/page.tsx (3:17)",
"Set.forEach <anonymous>",
],
},
],
"description": "Runtime data was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
To fix this:
Provide a fallback UI using <Suspense> around this component.
or
Move the Runtime data access into a deeper component wrapped in <Suspense>.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/aliased-export/page.tsx (7:16) @ Page
> 7 | await cookies()
| ^",
"stack": [
"Page app/aliased-export/page.tsx (7:16)",
],
}
`)
})
it('re-export - export { unstable_instant } from "./config"', async () => {
const browser = await next.browser('/reexport')
await waitForValidation(await browser.url())
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"message": " ",
"source": "app/reexport/page.tsx (3:10) @ unstable_instant
> 3 | export { unstable_instant } from './config'
| ^",
"stack": [
"unstable_instant app/reexport/page.tsx (3:10)",
"Set.forEach <anonymous>",
],
},
],
"description": "Runtime data was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
To fix this:
Provide a fallback UI using <Suspense> around this component.
or
Move the Runtime data access into a deeper component wrapped in <Suspense>.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/reexport/page.tsx (6:16) @ Page
> 6 | await cookies()
| ^",
"stack": [
"Page app/reexport/page.tsx (6:16)",
],
}
`)
})
it('indirect export - const instant = _instant; export { instant as unstable_instant }', async () => {
const browser = await next.browser('/indirect-export')
await waitForValidation(await browser.url())
// Ideally we'd be pointing at the original value declaration.
// We're not following declarations recursively mostly to keep the implementation simpler
// presuming that almost all configs are just `export const instant = ...`
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"message": " ",
"source": "app/indirect-export/page.tsx (4:17) @ unstable_instant
> 4 | const instant = _instant
| ^",
"stack": [
"unstable_instant app/indirect-export/page.tsx (4:17)",
"Set.forEach <anonymous>",
],
},
],
"description": "Runtime data was accessed outside of <Suspense>
This delays the entire page from rendering, resulting in a slow user experience. Next.js uses this error to ensure your app loads instantly on every navigation. cookies(), headers(), and searchParams, are examples of Runtime data that can only come from a user request.
To fix this:
Provide a fallback UI using <Suspense> around this component.
or
Move the Runtime data access into a deeper component wrapped in <Suspense>.
In either case this allows Next.js to stream its contents to the user when they request the page, while still providing an initial UI that is prerendered and prefetchable for instant navigations.
Learn more: https://nextjs.org/docs/messages/blocking-route",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/indirect-export/page.tsx (8:16) @ Page
> 8 | await cookies()
| ^",
"stack": [
"Page app/indirect-export/page.tsx (8:16)",
],
}
`)
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
productionBrowserSourceMaps: true,
typescript: {
ignoreBuildErrors: true,
},
}
export default nextConfig
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