File size: 8,689 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 |
import type {
AppType,
DocumentType,
NextComponentType,
} from '../shared/lib/utils'
import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'
import type {
PageConfig,
GetStaticPaths,
GetServerSideProps,
GetStaticProps,
} from '../types'
import type { RouteModule } from './route-modules/route-module'
import type { BuildManifest } from './get-page-files'
import type { ActionManifest } from '../build/webpack/plugins/flight-client-entry-plugin'
import {
BUILD_MANIFEST,
REACT_LOADABLE_MANIFEST,
CLIENT_REFERENCE_MANIFEST,
SERVER_REFERENCE_MANIFEST,
DYNAMIC_CSS_MANIFEST,
SUBRESOURCE_INTEGRITY_MANIFEST,
} from '../shared/lib/constants'
import { join } from 'path'
import { requirePage } from './require'
import { interopDefault } from '../lib/interop-default'
import { getTracer } from './lib/trace/tracer'
import { LoadComponentsSpan } from './lib/trace/constants'
import { evalManifest, loadManifest } from './load-manifest.external'
import { wait } from '../lib/wait'
import { setReferenceManifestsSingleton } from './app-render/encryption-utils'
import { createServerModuleMap } from './app-render/action-utils'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { normalizePagePath } from '../shared/lib/page-path/normalize-page-path'
import { isStaticMetadataRoute } from '../lib/metadata/is-metadata-route'
export type ManifestItem = {
id: number | string
files: string[]
}
export type ReactLoadableManifest = { [moduleId: string]: ManifestItem }
/**
* This manifest prevents removing server rendered <link> tags after client
* navigation. This is only needed under `Pages dir && Production && Webpack`.
* @see https://github.com/vercel/next.js/pull/72959
*/
export type DynamicCssManifest = string[]
/**
* A manifest entry type for the react-loadable-manifest.json.
*
* The whole manifest.json is a type of `Record<pathname, LoadableManifest>`
* where pathname is a string-based key points to the path of the page contains
* each dynamic imports.
*/
export interface LoadableManifest {
[k: string]: { id: string | number; files: string[] }
}
export type LoadComponentsReturnType<NextModule = any> = {
Component: NextComponentType
pageConfig: PageConfig
buildManifest: DeepReadonly<BuildManifest>
subresourceIntegrityManifest?: DeepReadonly<Record<string, string>>
reactLoadableManifest: DeepReadonly<ReactLoadableManifest>
dynamicCssManifest?: DeepReadonly<DynamicCssManifest>
clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>
serverActionsManifest?: any
Document: DocumentType
App: AppType
getStaticProps?: GetStaticProps
getStaticPaths?: GetStaticPaths
getServerSideProps?: GetServerSideProps
ComponentMod: NextModule
routeModule: RouteModule
isAppPath?: boolean
page: string
multiZoneDraftMode?: boolean
}
/**
* Load manifest file with retries, defaults to 3 attempts.
*/
export async function loadManifestWithRetries<T extends object>(
manifestPath: string,
attempts = 3
) {
while (true) {
try {
return loadManifest<T>(manifestPath)
} catch (err) {
attempts--
if (attempts <= 0) throw err
await wait(100)
}
}
}
/**
* Load manifest file with retries, defaults to 3 attempts, or return undefined.
*/
export async function tryLoadManifestWithRetries<T extends object>(
manifestPath: string,
attempts = 3
) {
try {
return await loadManifestWithRetries<T>(manifestPath, attempts)
} catch (err) {
return undefined
}
}
/**
* Load manifest file with retries, defaults to 3 attempts.
*/
export async function evalManifestWithRetries<T extends object>(
manifestPath: string,
attempts = 3
) {
while (true) {
try {
return evalManifest<T>(manifestPath)
} catch (err) {
attempts--
if (attempts <= 0) throw err
await wait(100)
}
}
}
async function tryLoadClientReferenceManifest(
manifestPath: string,
entryName: string,
attempts?: number
) {
try {
const context = await evalManifestWithRetries<{
__RSC_MANIFEST: { [key: string]: ClientReferenceManifest }
}>(manifestPath, attempts)
return context.__RSC_MANIFEST[entryName]
} catch (err) {
return undefined
}
}
async function loadComponentsImpl<N = any>({
distDir,
page,
isAppPath,
isDev,
sriEnabled,
}: {
distDir: string
page: string
isAppPath: boolean
isDev: boolean
sriEnabled: boolean
}): Promise<LoadComponentsReturnType<N>> {
let DocumentMod = {}
let AppMod = {}
if (!isAppPath) {
;[DocumentMod, AppMod] = await Promise.all([
requirePage('/_document', distDir, false),
requirePage('/_app', distDir, false),
])
}
// In dev mode we retry loading a manifest file to handle a race condition
// that can occur while app and pages are compiling at the same time, and the
// build-manifest is still being written to disk while an app path is
// attempting to load.
const manifestLoadAttempts = isDev ? 3 : 1
let reactLoadableManifestPath
if (!process.env.TURBOPACK) {
reactLoadableManifestPath = join(distDir, REACT_LOADABLE_MANIFEST)
} else if (isAppPath) {
reactLoadableManifestPath = join(
distDir,
'server',
'app',
page,
REACT_LOADABLE_MANIFEST
)
} else {
reactLoadableManifestPath = join(
distDir,
'server',
'pages',
normalizePagePath(page),
REACT_LOADABLE_MANIFEST
)
}
// Make sure to avoid loading the manifest for static metadata routes for better performance.
const hasClientManifest = !isStaticMetadataRoute(page)
// Load the manifest files first
//
// Loading page-specific manifests shouldn't throw an error if the manifest couldn't be found, so
// that the `requirePage` call below will throw the correct error in that case
// (a `PageNotFoundError`).
const [
buildManifest,
reactLoadableManifest,
dynamicCssManifest,
clientReferenceManifest,
serverActionsManifest,
subresourceIntegrityManifest,
] = await Promise.all([
loadManifestWithRetries<BuildManifest>(
join(distDir, BUILD_MANIFEST),
manifestLoadAttempts
),
tryLoadManifestWithRetries<ReactLoadableManifest>(
reactLoadableManifestPath,
manifestLoadAttempts
),
// This manifest will only exist in Pages dir && Production && Webpack.
isAppPath || process.env.TURBOPACK
? undefined
: loadManifestWithRetries<DynamicCssManifest>(
join(distDir, `${DYNAMIC_CSS_MANIFEST}.json`),
manifestLoadAttempts
).catch(() => undefined),
isAppPath && hasClientManifest
? tryLoadClientReferenceManifest(
join(
distDir,
'server',
'app',
page.replace(/%5F/g, '_') + '_' + CLIENT_REFERENCE_MANIFEST + '.js'
),
page.replace(/%5F/g, '_'),
manifestLoadAttempts
)
: undefined,
isAppPath
? loadManifestWithRetries<ActionManifest>(
join(distDir, 'server', SERVER_REFERENCE_MANIFEST + '.json'),
manifestLoadAttempts
).catch(() => null)
: null,
sriEnabled
? loadManifestWithRetries<DeepReadonly<Record<string, string>>>(
join(distDir, 'server', SUBRESOURCE_INTEGRITY_MANIFEST + '.json')
).catch(() => undefined)
: undefined,
])
// Before requiring the actual page module, we have to set the reference
// manifests to our global store so Server Action's encryption util can access
// to them at the top level of the page module.
if (serverActionsManifest && clientReferenceManifest) {
setReferenceManifestsSingleton({
page,
clientReferenceManifest,
serverActionsManifest,
serverModuleMap: createServerModuleMap({
serverActionsManifest,
}),
})
}
const ComponentMod = await requirePage(page, distDir, isAppPath)
const Component = interopDefault(ComponentMod)
const Document = interopDefault(DocumentMod)
const App = interopDefault(AppMod)
const { getServerSideProps, getStaticProps, getStaticPaths, routeModule } =
ComponentMod
return {
App,
Document,
Component,
buildManifest,
subresourceIntegrityManifest,
reactLoadableManifest: reactLoadableManifest || {},
dynamicCssManifest,
pageConfig: ComponentMod.config || {},
ComponentMod,
getServerSideProps,
getStaticProps,
getStaticPaths,
clientReferenceManifest,
serverActionsManifest,
isAppPath,
page,
routeModule,
}
}
export const loadComponents = getTracer().wrap(
LoadComponentsSpan.loadComponents,
loadComponentsImpl
)
|