Unverified Commit 48355fdc authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add writeStandaloneDirectory (#60162)

## What?

Moves the creation of the `standalone` directory when using `output:
'standalone'` into a separate function. Also added a type for
`RequiredServerFilesManifest` as it was missing.

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


Closes NEXT-1959
parent 09af522f
...@@ -9,7 +9,7 @@ import type { Revalidate } from '../server/lib/revalidate' ...@@ -9,7 +9,7 @@ import type { Revalidate } from '../server/lib/revalidate'
import '../lib/setup-exception-listeners' import '../lib/setup-exception-listeners'
import { loadEnvConfig } from '@next/env' import { loadEnvConfig, type LoadedEnvFiles } from '@next/env'
import { bold, yellow, green } from '../lib/picocolors' import { bold, yellow, green } from '../lib/picocolors'
import crypto from 'crypto' import crypto from 'crypto'
import { isMatch, makeRe } from 'next/dist/compiled/micromatch' import { isMatch, makeRe } from 'next/dist/compiled/micromatch'
...@@ -105,7 +105,7 @@ import { generateBuildId } from './generate-build-id' ...@@ -105,7 +105,7 @@ import { generateBuildId } from './generate-build-id'
import { isWriteable } from './is-writeable' import { isWriteable } from './is-writeable'
import * as Log from './output/log' import * as Log from './output/log'
import createSpinner from './spinner' import createSpinner from './spinner'
import { trace, flushAllTraces, setGlobal } from '../trace' import { trace, flushAllTraces, setGlobal, type Span } from '../trace'
import { import {
detectConflictingPaths, detectConflictingPaths,
computeFromManifest, computeFromManifest,
...@@ -423,6 +423,107 @@ async function writeClientSsgManifest( ...@@ -423,6 +423,107 @@ async function writeClientSsgManifest(
) )
} }
interface RequiredServerFilesManifest {
version: number
config: NextConfigComplete
appDir: string
relativeAppDir: string
files: string[]
ignore: string[]
}
async function writeRequiredServerFilesManifest(
distDir: string,
requiredServerFiles: RequiredServerFilesManifest
) {
await writeManifest(
path.join(distDir, SERVER_FILES_MANIFEST),
requiredServerFiles
)
}
const STANDALONE_DIRECTORY = 'standalone' as const
async function writeStandaloneDirectory(
nextBuildSpan: Span,
distDir: string,
pageKeys: { pages: string[]; app: string[] | undefined },
denormalizedAppPages: string[] | undefined,
outputFileTracingRoot: string,
requiredServerFiles: RequiredServerFilesManifest,
middlewareManifest: MiddlewareManifest,
hasInstrumentationHook: boolean,
staticPages: Set<string>,
loadedEnvFiles: LoadedEnvFiles,
appDir: string | undefined
) {
await nextBuildSpan
.traceChild('write-standalone-directory')
.traceAsyncFn(async () => {
await copyTracedFiles(
// requiredServerFiles.appDir Refers to the application directory, not App Router.
requiredServerFiles.appDir,
distDir,
pageKeys.pages,
denormalizedAppPages,
outputFileTracingRoot,
requiredServerFiles.config,
middlewareManifest,
hasInstrumentationHook,
staticPages
)
for (const file of [
...requiredServerFiles.files,
path.join(requiredServerFiles.config.distDir, SERVER_FILES_MANIFEST),
...loadedEnvFiles.reduce<string[]>((acc, envFile) => {
if (['.env', '.env.production'].includes(envFile.path)) {
acc.push(envFile.path)
}
return acc
}, []),
]) {
// requiredServerFiles.appDir Refers to the application directory, not App Router.
const filePath = path.join(requiredServerFiles.appDir, file)
const outputPath = path.join(
distDir,
STANDALONE_DIRECTORY,
path.relative(outputFileTracingRoot, filePath)
)
await fs.mkdir(path.dirname(outputPath), {
recursive: true,
})
await fs.copyFile(filePath, outputPath)
}
await recursiveCopy(
path.join(distDir, SERVER_DIRECTORY, 'pages'),
path.join(
distDir,
STANDALONE_DIRECTORY,
path.relative(outputFileTracingRoot, distDir),
SERVER_DIRECTORY,
'pages'
),
{ overwrite: true }
)
if (appDir) {
const originalServerApp = path.join(distDir, SERVER_DIRECTORY, 'app')
if (existsSync(originalServerApp)) {
await recursiveCopy(
originalServerApp,
path.join(
distDir,
STANDALONE_DIRECTORY,
path.relative(outputFileTracingRoot, distDir),
SERVER_DIRECTORY,
'app'
),
{ overwrite: true }
)
}
}
})
}
export default async function build( export default async function build(
dir: string, dir: string,
reactProductionProfiling = false, reactProductionProfiling = false,
...@@ -1000,9 +1101,10 @@ export default async function build( ...@@ -1000,9 +1101,10 @@ export default async function build(
const { incrementalCacheHandlerPath } = config.experimental const { incrementalCacheHandlerPath } = config.experimental
const requiredServerFiles = nextBuildSpan const requiredServerFilesManifest = nextBuildSpan
.traceChild('generate-required-server-files') .traceChild('generate-required-server-files')
.traceFn(() => ({ .traceFn(() => {
const serverFilesManifest: RequiredServerFilesManifest = {
version: 1, version: 1,
config: { config: {
...config, ...config,
...@@ -1019,6 +1121,7 @@ export default async function build( ...@@ -1019,6 +1121,7 @@ export default async function build(
? path.relative(distDir, incrementalCacheHandlerPath) ? path.relative(distDir, incrementalCacheHandlerPath)
: undefined, : undefined,
// @ts-expect-error internal field TODO: fix this, should use a separate mechanism to pass the info.
isExperimentalCompile: isCompileMode, isExperimentalCompile: isCompileMode,
}, },
}, },
...@@ -1086,7 +1189,10 @@ export default async function build( ...@@ -1086,7 +1189,10 @@ export default async function build(
.filter(nonNullable) .filter(nonNullable)
.map((file) => path.join(config.distDir, file)), .map((file) => path.join(config.distDir, file)),
ignore: [] as string[], ignore: [] as string[],
})) }
return serverFilesManifest
})
async function turbopackBuild() { async function turbopackBuild() {
const turboNextBuildStart = process.hrtime() const turboNextBuildStart = process.hrtime()
...@@ -1940,7 +2046,7 @@ export default async function build( ...@@ -1940,7 +2046,7 @@ export default async function build(
} }
if (!hasSsrAmpPages) { if (!hasSsrAmpPages) {
requiredServerFiles.ignore.push( requiredServerFilesManifest.ignore.push(
path.relative( path.relative(
dir, dir,
path.join( path.join(
...@@ -2038,7 +2144,7 @@ export default async function build( ...@@ -2038,7 +2144,7 @@ export default async function build(
) )
}) })
requiredServerFiles.files.push( requiredServerFilesManifest.files.push(
...cssFilePaths.map((filePath) => ...cssFilePaths.map((filePath) =>
path.join(config.distDir, 'static', filePath) path.join(config.distDir, 'static', filePath)
) )
...@@ -2068,9 +2174,9 @@ export default async function build( ...@@ -2068,9 +2174,9 @@ export default async function build(
}) })
) )
await writeManifest( await writeRequiredServerFilesManifest(
path.join(distDir, SERVER_FILES_MANIFEST), distDir,
requiredServerFiles requiredServerFilesManifest
) )
const middlewareManifest: MiddlewareManifest = await readManifest( const middlewareManifest: MiddlewareManifest = await readManifest(
...@@ -3016,75 +3122,20 @@ export default async function build( ...@@ -3016,75 +3122,20 @@ export default async function build(
await buildTracesPromise await buildTracesPromise
if (config.output === 'standalone') { if (config.output === 'standalone') {
await nextBuildSpan await writeStandaloneDirectory(
.traceChild('copy-traced-files') nextBuildSpan,
.traceAsyncFn(async () => {
await copyTracedFiles(
dir,
distDir, distDir,
pageKeys.pages, pageKeys,
denormalizedAppPages, denormalizedAppPages,
outputFileTracingRoot, outputFileTracingRoot,
requiredServerFiles.config, requiredServerFilesManifest,
middlewareManifest, middlewareManifest,
hasInstrumentationHook, hasInstrumentationHook,
staticPages staticPages,
) loadedEnvFiles,
appDir
for (const file of [
...requiredServerFiles.files,
path.join(config.distDir, SERVER_FILES_MANIFEST),
...loadedEnvFiles.reduce<string[]>((acc, envFile) => {
if (['.env', '.env.production'].includes(envFile.path)) {
acc.push(envFile.path)
}
return acc
}, []),
]) {
const filePath = path.join(dir, file)
const outputPath = path.join(
distDir,
'standalone',
path.relative(outputFileTracingRoot, filePath)
)
await fs.mkdir(path.dirname(outputPath), {
recursive: true,
})
await fs.copyFile(filePath, outputPath)
}
await recursiveCopy(
path.join(distDir, SERVER_DIRECTORY, 'pages'),
path.join(
distDir,
'standalone',
path.relative(outputFileTracingRoot, distDir),
SERVER_DIRECTORY,
'pages'
),
{ overwrite: true }
)
if (appDir) {
const originalServerApp = path.join(
distDir,
SERVER_DIRECTORY,
'app'
)
if (existsSync(originalServerApp)) {
await recursiveCopy(
originalServerApp,
path.join(
distDir,
'standalone',
path.relative(outputFileTracingRoot, distDir),
SERVER_DIRECTORY,
'app'
),
{ overwrite: true }
) )
} }
}
})
}
if (buildTracesSpinner) { if (buildTracesSpinner) {
buildTracesSpinner.stopAndPersist() buildTracesSpinner.stopAndPersist()
......
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