Skip to content

Commit

Permalink
refactor: eliminate originalPathname to use page
Browse files Browse the repository at this point in the history
  • Loading branch information
wyattjoh committed May 7, 2024
1 parent 4b9ddef commit 7a3f9a6
Show file tree
Hide file tree
Showing 22 changed files with 110 additions and 73 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ pub async fn get_app_page_entry(
indexmap! {
"VAR_DEFINITION_PAGE" => page.to_string(),
"VAR_DEFINITION_PATHNAME" => pathname.clone(),
"VAR_ORIGINAL_PATHNAME" => original_name.clone(),
// TODO(alexkirsz) Support custom global error.
"VAR_MODULE_GLOBAL_ERROR" => "next/dist/client/components/error-boundary".to_string(),
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ pub async fn get_app_route_entry(
"VAR_DEFINITION_FILENAME" => path.file_stem().await?.as_ref().unwrap().clone(),
// TODO(alexkirsz) Is this necessary?
"VAR_DEFINITION_BUNDLE_PATH" => "".to_string(),
"VAR_ORIGINAL_PATHNAME" => original_name.clone(),
"VAR_RESOLVED_PAGE_PATH" => path.to_string().await?.clone_value(),
"VAR_USERLAND" => INNER.to_string(),
},
Expand Down
1 change: 0 additions & 1 deletion packages/next/src/build/templates/app-page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ declare const __next_app_load_chunk__: any
// INJECT:__next_app_require__
// INJECT:__next_app_load_chunk__

export const originalPathname = 'VAR_ORIGINAL_PATHNAME'
export const __next_app__ = {
require: __next_app_require__,
loadChunk: __next_app_load_chunk__,
Expand Down
3 changes: 0 additions & 3 deletions packages/next/src/build/templates/app-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,6 @@ const routeModule = new AppRouteRouteModule({
const { requestAsyncStorage, staticGenerationAsyncStorage, serverHooks } =
routeModule

const originalPathname = 'VAR_ORIGINAL_PATHNAME'

function patchFetch() {
return _patchFetch({ serverHooks, staticGenerationAsyncStorage })
}
Expand All @@ -46,6 +44,5 @@ export {
requestAsyncStorage,
staticGenerationAsyncStorage,
serverHooks,
originalPathname,
patchFetch,
}
6 changes: 3 additions & 3 deletions packages/next/src/build/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ import type { PageExtensions } from './page-extensions-type'
import { formatDynamicImportPath } from '../lib/format-dynamic-import-path'
import { isInterceptionRouteAppPath } from '../server/future/helpers/interception-routes'
import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr'
import type { AppRouteModule } from '../server/future/route-modules/app-route/module.compiled'

export type ROUTER_TYPE = 'pages' | 'app'

Expand Down Expand Up @@ -1345,7 +1346,7 @@ export async function buildAppStaticPaths({
cacheHandler?: string
maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders']
ComponentMod: AppPageModule
ComponentMod: AppPageModule | AppRouteModule
}) {
ComponentMod.patchFetch()

Expand Down Expand Up @@ -1385,9 +1386,8 @@ export async function buildAppStaticPaths({
return StaticGenerationAsyncStorageWrapper.wrap(
ComponentMod.staticGenerationAsyncStorage,
{
url: { pathname: page },
page,
renderOpts: {
originalPathname: page,
incrementalCache,
supportsDynamicHTML: true,
isRevalidate: false,
Expand Down
2 changes: 0 additions & 2 deletions packages/next/src/build/webpack/loaders/next-app-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,6 @@ async function createAppRouteCode({
VAR_DEFINITION_FILENAME: filename,
VAR_DEFINITION_BUNDLE_PATH: bundlePath,
VAR_RESOLVED_PAGE_PATH: resolvedPagePath,
VAR_ORIGINAL_PATHNAME: page,
},
{
nextConfigOutput: JSON.stringify(nextConfigOutput),
Expand Down Expand Up @@ -773,7 +772,6 @@ const nextAppLoader: AppLoader = async function nextAppLoader() {
VAR_DEFINITION_PAGE: page,
VAR_DEFINITION_PATHNAME: pathname,
VAR_MODULE_GLOBAL_ERROR: treeCodeResult.globalError,
VAR_ORIGINAL_PATHNAME: page,
},
{
tree: treeCodeResult.treeCode,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,27 @@ import { staticGenerationAsyncStorage } from './static-generation-async-storage-

export interface StaticGenerationStore {
readonly isStaticGeneration: boolean
readonly pagePath?: string
/**
* The page that is being rendered. This is the path to the page file.
*/
readonly page: string

/**
* The URL of the request. This only specifies the pathname and the search
* part of the URL. The other parts aren't accepted so they shouldn't be used.
* part of the URL.
*/
readonly url: { readonly pathname: string; readonly search: string }
readonly url?: {
/**
* The pathname of the requested URL.
*/
readonly pathname: string

/**
* The search part of the requested URL. If the request did not provide a
* search part, this will be undefined.
*/
readonly search?: string
}
readonly incrementalCache?: IncrementalCache
readonly isOnDemandRevalidate?: boolean
readonly isPrerendering?: boolean
Expand Down
1 change: 0 additions & 1 deletion packages/next/src/export/routes/app-route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@ export async function exportAppRoute(
notFoundRoutes: [],
},
renderOpts: {
originalPathname: page,
nextExport: true,
supportsDynamicHTML: false,
incrementalCache,
Expand Down
1 change: 0 additions & 1 deletion packages/next/src/export/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,6 @@ async function exportPageImpl(
fontManifest: optimizeFonts ? requireFontManifest(distDir) : undefined,
locale,
supportsDynamicHTML: false,
originalPathname: page,
experimental: {
...input.renderOpts.experimental,
isRoutePPREnabled,
Expand Down
17 changes: 9 additions & 8 deletions packages/next/src/server/app-render/app-render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ async function generateFlight(
},
getDynamicParamFromSegment,
appUsingSizeAdjustment,
staticGenerationStore: { url },
staticGenerationStore: { page, url },
query,
requestId,
flightRouterState,
Expand All @@ -321,7 +321,7 @@ async function generateFlight(
if (!options?.skipFlight) {
const [MetadataTree, MetadataOutlet] = createMetadataComponents({
tree: loaderTree,
pathname: url.pathname,
pathname: url?.pathname ?? page,
trailingSlash: ctx.renderOpts.trailingSlash,
query,
getDynamicParamFromSegment,
Expand Down Expand Up @@ -434,7 +434,7 @@ async function ReactServerApp({ tree, ctx, asNotFound }: ReactServerAppProps) {
GlobalError,
createDynamicallyTrackedSearchParams,
},
staticGenerationStore: { url },
staticGenerationStore: { page, url },
} = ctx
const initialTree = createFlightRouterStateFromLoaderTree(
tree,
Expand All @@ -445,7 +445,7 @@ async function ReactServerApp({ tree, ctx, asNotFound }: ReactServerAppProps) {
const [MetadataTree, MetadataOutlet] = createMetadataComponents({
tree,
errorType: asNotFound ? 'not-found' : undefined,
pathname: url.pathname,
pathname: url?.pathname ?? page,
trailingSlash: ctx.renderOpts.trailingSlash,
query,
getDynamicParamFromSegment: getDynamicParamFromSegment,
Expand Down Expand Up @@ -481,7 +481,7 @@ async function ReactServerApp({ tree, ctx, asNotFound }: ReactServerAppProps) {
<AppRouter
buildId={ctx.renderOpts.buildId}
assetPrefix={ctx.assetPrefix}
initialCanonicalUrl={url.pathname + url.search}
initialCanonicalUrl={url ? url.pathname + url.search : page}
// This is the router state tree.
initialTree={initialTree}
// This is the tree of React nodes that are seeded into the cache
Expand Down Expand Up @@ -526,14 +526,14 @@ async function ReactServerError({
GlobalError,
createDynamicallyTrackedSearchParams,
},
staticGenerationStore: { url },
staticGenerationStore: { page, url },
requestId,
res,
} = ctx

const [MetadataTree] = createMetadataComponents({
tree,
pathname: url.pathname,
pathname: url?.pathname ?? page,
trailingSlash: ctx.renderOpts.trailingSlash,
errorType,
query,
Expand Down Expand Up @@ -576,7 +576,7 @@ async function ReactServerError({
<AppRouter
buildId={ctx.renderOpts.buildId}
assetPrefix={ctx.assetPrefix}
initialCanonicalUrl={url.pathname + url.search}
initialCanonicalUrl={url ? url.pathname + url.search : page}
initialTree={initialTree}
initialHead={head}
globalErrorComponent={GlobalError}
Expand Down Expand Up @@ -1499,6 +1499,7 @@ export const renderToHTMLOrFlight: AppPageRender = (
StaticGenerationAsyncStorageWrapper.wrap(
renderOpts.ComponentMod.staticGenerationAsyncStorage,
{
page: renderOpts.routeModule?.definition.page,
url,
renderOpts,
requestEndedState: { ended: false },
Expand Down
6 changes: 4 additions & 2 deletions packages/next/src/server/app-render/create-component-tree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ async function createComponentTreeInternal({
if (typeof layoutOrPageMod?.revalidate !== 'undefined') {
validateRevalidate(
layoutOrPageMod?.revalidate,
staticGenerationStore.url.pathname
staticGenerationStore.url?.pathname ?? staticGenerationStore.page
)
}

Expand Down Expand Up @@ -537,7 +537,9 @@ async function createComponentTreeInternal({
<Postpone
prerenderState={staticGenerationStore.prerenderState}
reason='dynamic = "force-dynamic" was used'
pathname={staticGenerationStore.url.pathname}
pathname={
staticGenerationStore.url?.pathname ?? staticGenerationStore.page
}
/>,
loadingData,
],
Expand Down
12 changes: 9 additions & 3 deletions packages/next/src/server/app-render/dynamic-rendering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,8 @@ export function markCurrentScopeAsDynamic(
store: StaticGenerationStore,
expression: string
): void {
const { pathname } = store.url
const { page, url } = store
const pathname = url?.pathname ?? page
if (store.isUnstableCacheCallback) {
// inside cache scopes marking a scope as dynamic has no effect because the outer cache scope
// creates a cache boundary. This is subtly different from reading a dynamic data source which is
Expand Down Expand Up @@ -122,7 +123,8 @@ export function trackDynamicDataAccessed(
store: StaticGenerationStore,
expression: string
): void {
const { pathname } = store.url
const { page, url } = store
const pathname = url?.pathname ?? page
if (store.isUnstableCacheCallback) {
throw new Error(
`Route ${pathname} used "${expression}" inside a function cached with "unstable_cache(...)". Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use "${expression}" outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
Expand Down Expand Up @@ -183,7 +185,11 @@ export function trackDynamicFetch(
// don't need to postpone.
if (!store.prerenderState || store.isUnstableCacheCallback) return

postponeWithTracking(store.prerenderState, expression, store.url.pathname)
postponeWithTracking(
store.prerenderState,
expression,
store.url?.pathname ?? store.page
)
}

function postponeWithTracking(
Expand Down
1 change: 0 additions & 1 deletion packages/next/src/server/app-render/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ export interface RenderOptsPartial {
nextExport?: boolean
nextConfigOutput?: 'standalone' | 'export'
appDirDevErrorLogger?: (err: any) => Promise<void>
originalPathname?: string
isDraftMode?: boolean
deploymentId?: string
onUpdateCookies?: (cookies: string[]) => void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,27 @@ import { createPrerenderState } from '../../server/app-render/dynamic-rendering'
import type { FetchMetric } from '../base-http'

export type StaticGenerationContext = {
/**
* The page that is being rendered. This relates to the path to the page file.
*/
page: string

/**
* The URL of the request. This only specifies the pathname and the search
* part of the URL. The other parts aren't accepted so they shouldn't be used.
* part of the URL.
*/
url: { pathname: string; search?: string }
url?: {
/**
* The pathname of the requested URL.
*/
pathname: string

/**
* The search part of the requested URL. If the request did not provide a
* search part, this will be an empty string.
*/
search?: string
}
requestEndedState?: { ended?: boolean }
renderOpts: {
incrementalCache?: IncrementalCache
Expand Down Expand Up @@ -40,7 +56,6 @@ export type StaticGenerationContext = {
// Pull some properties from RenderOptsPartial so that the docs are also
// mirrored.
RenderOptsPartial,
| 'originalPathname'
| 'supportsDynamicHTML'
| 'isRevalidate'
| 'nextExport'
Expand All @@ -55,7 +70,7 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper<
> = {
wrap<Result>(
storage: AsyncLocalStorage<StaticGenerationStore>,
{ url, renderOpts, requestEndedState }: StaticGenerationContext,
{ page, url, renderOpts, requestEndedState }: StaticGenerationContext,
callback: (store: StaticGenerationStore) => Result
): Result {
/**
Expand Down Expand Up @@ -87,14 +102,13 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper<

const store: StaticGenerationStore = {
isStaticGeneration,
page,
// Rather than just using the whole `url` here, we pull the parts we want
// to ensure we don't use parts of the URL that we shouldn't. This also
// lets us avoid requiring an empty string for `search` in the type.
url: {
pathname: url.pathname,
search: url.search ?? '',
},
pagePath: renderOpts.originalPathname,
url: url
? { pathname: url.pathname, search: url.search ?? '' }
: undefined,
incrementalCache:
// we fallback to a global incremental cache for edge-runtime locally
// so that it can access the fs cache without mocks
Expand Down
2 changes: 0 additions & 2 deletions packages/next/src/server/base-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2281,7 +2281,6 @@ export default abstract class Server<
// it is not a dynamic RSC request then it is a revalidation
// request.
isRevalidate: isSSG && !postponed && !isDynamicRSCRequest,
originalPathname: components.ComponentMod.originalPathname,
serverActions: this.nextConfig.experimental.serverActions,
}
: {}),
Expand Down Expand Up @@ -2344,7 +2343,6 @@ export default abstract class Server<
params: opts.params,
prerenderManifest,
renderOpts: {
originalPathname: components.ComponentMod.originalPathname,
supportsDynamicHTML,
incrementalCache,
isRevalidate: isSSG,
Expand Down
Loading

0 comments on commit 7a3f9a6

Please sign in to comment.