File size: 7,861 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 |
import path from 'path'
import { validateTurboNextConfig } from '../../lib/turbopack-warning'
import {
formatIssue,
getTurbopackJsConfig,
isPersistentCachingEnabled,
isRelevantWarning,
} from '../../shared/lib/turbopack/utils'
import { NextBuildContext } from '../build-context'
import { createDefineEnv, loadBindings } from '../swc'
import {
rawEntrypointsToEntrypoints,
handleRouteType,
} from '../handle-entrypoints'
import { TurbopackManifestLoader } from '../../shared/lib/turbopack/manifest-loader'
import { promises as fs } from 'fs'
import { PHASE_PRODUCTION_BUILD } from '../../shared/lib/constants'
import loadConfig from '../../server/config'
import { hasCustomExportOutput } from '../../export/utils'
import { Telemetry } from '../../telemetry/storage'
import { setGlobal } from '../../trace'
import { isCI } from '../../server/ci-info'
import { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compilation-events'
import { getSupportedBrowsers } from '../utils'
import { normalizePath } from '../../lib/normalize-path'
export async function turbopackBuild(): Promise<{
duration: number
buildTraceContext: undefined
shutdownPromise: Promise<void>
}> {
await validateTurboNextConfig({
dir: NextBuildContext.dir!,
isDev: false,
})
const config = NextBuildContext.config!
const dir = NextBuildContext.dir!
const distDir = NextBuildContext.distDir!
const buildId = NextBuildContext.buildId!
const encryptionKey = NextBuildContext.encryptionKey!
const previewProps = NextBuildContext.previewProps!
const hasRewrites = NextBuildContext.hasRewrites!
const rewrites = NextBuildContext.rewrites!
const appDirOnly = NextBuildContext.appDirOnly!
const noMangling = NextBuildContext.noMangling!
const currentNodeJsVersion = process.versions.node
const startTime = process.hrtime()
const bindings = await loadBindings(config?.experimental?.useWasmBinary)
const dev = false
const supportedBrowsers = getSupportedBrowsers(dir, dev)
const persistentCaching = isPersistentCachingEnabled(config)
const rootPath = config.turbopack?.root || config.outputFileTracingRoot || dir
const project = await bindings.turbo.createProject(
{
rootPath: config.turbopack?.root || config.outputFileTracingRoot || dir,
projectPath: normalizePath(path.relative(rootPath, dir) || '.'),
distDir,
nextConfig: config,
jsConfig: await getTurbopackJsConfig(dir, config),
watch: {
enable: false,
},
dev,
env: process.env as Record<string, string>,
defineEnv: createDefineEnv({
isTurbopack: true,
clientRouterFilters: NextBuildContext.clientRouterFilters!,
config,
dev,
distDir,
projectPath: dir,
fetchCacheKeyPrefix: config.experimental.fetchCacheKeyPrefix,
hasRewrites,
// Implemented separately in Turbopack, doesn't have to be passed here.
middlewareMatchers: undefined,
rewrites,
}),
buildId,
encryptionKey,
previewProps,
browserslistQuery: supportedBrowsers.join(', '),
noMangling,
currentNodeJsVersion,
},
{
persistentCaching,
memoryLimit: config.experimental?.turbopackMemoryLimit,
dependencyTracking: persistentCaching,
isCi: isCI,
}
)
try {
backgroundLogCompilationEvents(project)
// Write an empty file in a known location to signal this was built with Turbopack
await fs.writeFile(path.join(distDir, 'turbopack'), '')
await fs.mkdir(path.join(distDir, 'server'), { recursive: true })
await fs.mkdir(path.join(distDir, 'static', buildId), {
recursive: true,
})
await fs.writeFile(
path.join(distDir, 'package.json'),
JSON.stringify(
{
type: 'commonjs',
},
null,
2
)
)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const entrypoints = await project.writeAllEntrypointsToDisk(appDirOnly)
const manifestLoader = new TurbopackManifestLoader({
buildId,
distDir,
encryptionKey,
})
const topLevelErrors = []
const topLevelWarnings = []
for (const issue of entrypoints.issues) {
if (issue.severity === 'error' || issue.severity === 'fatal') {
topLevelErrors.push(formatIssue(issue))
} else if (isRelevantWarning(issue)) {
topLevelWarnings.push(formatIssue(issue))
}
}
if (topLevelWarnings.length > 0) {
console.warn(
`Turbopack build encountered ${
topLevelWarnings.length
} warnings:\n${topLevelWarnings.join('\n')}`
)
}
if (topLevelErrors.length > 0) {
throw new Error(
`Turbopack build failed with ${
topLevelErrors.length
} errors:\n${topLevelErrors.join('\n')}`
)
}
const currentEntrypoints = await rawEntrypointsToEntrypoints(entrypoints)
const promises: Promise<any>[] = []
if (!appDirOnly) {
for (const [page, route] of currentEntrypoints.page) {
promises.push(
handleRouteType({
page,
route,
manifestLoader,
})
)
}
}
for (const [page, route] of currentEntrypoints.app) {
promises.push(
handleRouteType({
page,
route,
manifestLoader,
})
)
}
await Promise.all(promises)
await Promise.all([
manifestLoader.loadBuildManifest('_app'),
manifestLoader.loadPagesManifest('_app'),
manifestLoader.loadFontManifest('_app'),
manifestLoader.loadPagesManifest('_document'),
manifestLoader.loadClientBuildManifest('_error'),
manifestLoader.loadBuildManifest('_error'),
manifestLoader.loadPagesManifest('_error'),
manifestLoader.loadFontManifest('_error'),
entrypoints.instrumentation &&
manifestLoader.loadMiddlewareManifest(
'instrumentation',
'instrumentation'
),
entrypoints.middleware &&
(await manifestLoader.loadMiddlewareManifest(
'middleware',
'middleware'
)),
])
await manifestLoader.writeManifests({
devRewrites: undefined,
productionRewrites: rewrites,
entrypoints: currentEntrypoints,
})
const shutdownPromise = project.shutdown()
const time = process.hrtime(startTime)
return {
duration: time[0] + time[1] / 1e9,
buildTraceContext: undefined,
shutdownPromise,
}
} catch (err) {
await project.shutdown()
throw err
}
}
let shutdownPromise: Promise<void> | undefined
export async function workerMain(workerData: {
buildContext: typeof NextBuildContext
}): Promise<Awaited<ReturnType<typeof turbopackBuild>>> {
// setup new build context from the serialized data passed from the parent
Object.assign(NextBuildContext, workerData.buildContext)
/// load the config because it's not serializable
NextBuildContext.config = await loadConfig(
PHASE_PRODUCTION_BUILD,
NextBuildContext.dir!,
{ debugPrerender: NextBuildContext.debugPrerender }
)
// Matches handling in build/index.ts
// https://github.com/vercel/next.js/blob/84f347fc86f4efc4ec9f13615c215e4b9fb6f8f0/packages/next/src/build/index.ts#L815-L818
// Ensures the `config.distDir` option is matched.
if (hasCustomExportOutput(NextBuildContext.config)) {
NextBuildContext.config.distDir = '.next'
}
// Clone the telemetry for worker
const telemetry = new Telemetry({
distDir: NextBuildContext.config.distDir,
})
setGlobal('telemetry', telemetry)
const result = await turbopackBuild()
shutdownPromise = result.shutdownPromise
return result
}
export async function waitForShutdown(): Promise<void> {
if (shutdownPromise) {
await shutdownPromise
}
}
|