/* disable this rule _here_ to avoid conflict with ongoing changes */ import ms from 'ms'; import bytes from 'bytes'; import { readFileSync, unlinkSync } from 'fs'; import { delimiter, dirname, join } from 'path'; import { fork, type ChildProcess } from 'child_process'; import { createFunction } from '@vercel/fun'; import { initializeFunRuntime } from './fun-runtime'; import { type Builder, type BuildOptions, type Env, Lambda, FileBlob, FileFsRef, normalizePath, isBackendFramework, isPythonFramework, type BuildResultVX, getNodeExecPath, } from '@vercel/build-utils'; import { isStaticRuntime } from '@vercel/fs-detectors'; import plural from 'pluralize'; import minimatch from 'minimatch'; import highlight from '../output/highlight'; import { treeKill } from '../tree-kill'; import { relative } from '../path-helpers'; import { LambdaSizeExceededError } from '../errors-ts'; import type DevServer from './server'; import type { VercelConfig, BuildMatch, BuildResult, BuilderInputs, BuilderOutput, BuildResultV3, BuilderOutputs, EnvConfigs, BuiltLambda, } from './types'; import { normalizeRoutes, type Route } from '@vercel/routing-utils'; import { importBuilders } from '../../builders/import-builders'; import { getUnsupportedBuilderVersionError } from './unsupported-builder-version'; import output from '../../output-manager'; import { isNativeBinaryInstall } from '../native-install'; import { dev } from './diagnostics'; interface BuildMessage { type: string; } /** JSON-ified Buffer as serialized by Node.js IPC */ interface SerializedBuffer { type: 'Buffer'; data: number[]; } /** * JSON-ified Lambda object received over IPC from the builder worker. * Buffer objects are serialized as { type: 'Buffer', data: number[] }. * Large zipBuffers may be written to temp files and sent as zipBufferPath instead. */ interface SerializedLambda { type: 'Lambda'; zipBuffer?: SerializedBuffer; zipBufferPath?: string; [key: string]: unknown; } /** JSON-ified FileBlob received over IPC */ interface SerializedFileBlob { type: 'FileBlob'; data: SerializedBuffer; [key: string]: unknown; } /** JSON-ified FileFsRef received over IPC */ interface SerializedFileFsRef { type: 'FileFsRef'; [key: string]: unknown; } /** Union of all serialized output types received over IPC */ type SerializedOutput = | SerializedLambda | SerializedFileBlob | SerializedFileFsRef; /** Serialized build outputs received over IPC (before deserialization) */ type SerializedBuildOutputs = Record; /** * Deserialize a single output object from its IPC-serialized form. * Converts JSON-ified Buffers back to real Buffers and reads temp files for large zipBuffers. */ async function deserializeOutput( obj: SerializedOutput ): Promise { switch (obj.type) { case 'FileFsRef': { return Object.assign(Object.create(FileFsRef.prototype), obj); } case 'FileBlob': { const fileBlob: FileBlob = Object.assign( Object.create(FileBlob.prototype), obj ); fileBlob.data = Buffer.from(obj.data.data); return fileBlob; } case 'Lambda': { const lambda: BuiltLambda = Object.assign( Object.create(Lambda.prototype), obj ); // Convert the JSON-ified Buffer object back into an actual Buffer, // or read from temp file if it was too large for IPC if (obj.zipBufferPath) { lambda.zipBuffer = readFileSync(obj.zipBufferPath); // Clean up the temp file after reading try { unlinkSync(obj.zipBufferPath); } catch { // Ignore cleanup errors } } else if (obj.zipBuffer) { lambda.zipBuffer = Buffer.from(obj.zipBuffer.data); } return lambda; } } } /** * Deserialize all build outputs from their IPC-serialized form. */ async function deserializeBuildOutputs( serialized: SerializedBuildOutputs ): Promise { const result: BuilderOutputs = {}; for (const [name, obj] of Object.entries(serialized)) { result[name] = await deserializeOutput(obj); } return result; } /** Serialized BuildResult received over IPC */ interface SerializedBuildResult { output: SerializedBuildOutputs; routes: Route[]; watch: string[]; distPath?: string; } /** Serialized BuildResultV3 received over IPC */ interface SerializedBuildResultV3 { output: SerializedLambda; routes: Route[]; watch: string[]; distPath?: string; } interface BuildMessageResult extends BuildMessage { type: 'buildResult'; result?: | SerializedBuildOutputs | SerializedBuildResult | SerializedBuildResultV3; error?: object; } async function createBuildProcess( match: BuildMatch, envConfigs: EnvConfigs, workPath: string ): Promise { output.debug(`Creating build process for "${match.entrypoint}"`); const builderWorkerPath = join(__dirname, 'builder-worker.cjs'); const nodeExecPath = getNodeExecPath(); // Ensure that `node` is in the builder's `PATH` const PATH = `${dirname(nodeExecPath)}${delimiter}${process.env.PATH}`; const env: Env = { ...process.env, PATH, ...envConfigs.allEnv, }; const buildProcess = fork(builderWorkerPath, [], { cwd: workPath, execArgv: [], // The native entrypoint dispatches bundled workers inside its snapshot. // An external Node process cannot read the virtual worker path. execPath: isNativeBinaryInstall() ? process.execPath : nodeExecPath, env, }); match.buildProcess = buildProcess; buildProcess.on('close', (code, signal) => { output.debug( `Build process for "${match.entrypoint}" exited with ${signal || code}` ); match.buildProcess = undefined; }); return new Promise((resolve, reject) => { // The first message that the builder process sends is the `ready` event buildProcess.once('message', data => { if ( data !== null && typeof data === 'object' && (data as { type: string }).type !== 'ready' ) { reject(new Error('Did not get "ready" event from builder')); } else { resolve(buildProcess); } }); }); } export async function executeBuild( vercelConfig: VercelConfig, devServer: DevServer, files: BuilderInputs, match: BuildMatch, requestPath: string | null, isInitialBuild: boolean, filesChanged?: string[], filesRemoved?: string[] ): Promise { const { builderWithPkg: { path: requirePath, builder, pkg }, } = match; const { entrypoint, use } = match; const isStatic = isStaticRuntime(use); const { envConfigs, cwd: workPath, devCacheDir } = devServer; const debug = output.isDebugEnabled(); const startTime = Date.now(); const showBuildTimestamp = !isStatic && (!isInitialBuild || debug); if (showBuildTimestamp) { output.log(`Building ${use}:${entrypoint}`); output.debug( `Using \`${pkg.name}${pkg.version ? `@${pkg.version}` : ''}\`` ); } const config = match.config || {}; let result: BuildResult; let { buildProcess } = match; if (!isStatic && !buildProcess) { buildProcess = await createBuildProcess(match, envConfigs, workPath); } const serviceRoutePrefix = config.routePrefix; const serviceWorkspace = config.workspace; const buildOptions: BuildOptions = { files, entrypoint, workPath, repoRootPath: workPath, config, meta: { isDev: true, requestPath, devCacheDir, filesChanged, filesRemoved, // This env distiniction is only necessary to maintain // backwards compatibility with the `@vercel/next` builder. env: { ...envConfigs.runEnv }, buildEnv: { ...envConfigs.buildEnv }, }, ...(typeof serviceRoutePrefix === 'string' || typeof serviceWorkspace === 'string' ? { service: { routePrefix: typeof serviceRoutePrefix === 'string' ? serviceRoutePrefix : undefined, workspace: typeof serviceWorkspace === 'string' ? serviceWorkspace : undefined, }, } : undefined), }; let buildResultOrOutputs; if (buildProcess) { buildProcess.send({ type: 'build', requirePath, buildOptions, }); buildResultOrOutputs = await new Promise((resolve, reject) => { function onMessage({ type, result, error }: BuildMessageResult) { cleanup(); if (type === 'buildResult') { if (result) { resolve(result); } else if (error) { reject(Object.assign(new Error(), error)); } } else { reject(new Error(`Got unexpected message type: ${type}`)); } } function onExit(code: number | null, signal: string | null) { cleanup(); const err = new Error( `Builder exited with ${signal || code} before sending build result` ); reject(err); } function cleanup() { buildProcess!.removeListener('close', onExit); buildProcess!.removeListener('message', onMessage); } buildProcess!.on('close', onExit); buildProcess!.on('message', onMessage); }); } else { buildResultOrOutputs = await builder.build(buildOptions); } // Unwrap BuildResultVX (version === -1) to the actual V2 or V3 result. // When using a build process, builder-worker.cjs sends back the already- // unwrapped result, so we detect V2 vs V3 by output shape. // If builder.build() was called directly (no build process), the raw VX // wrapper is returned and we use resultVersion to unwrap it. let effectiveVersion: number = builder.version; if (effectiveVersion === -1) { if ('resultVersion' in (buildResultOrOutputs as object)) { const vx = buildResultOrOutputs as BuildResultVX; effectiveVersion = vx.resultVersion; buildResultOrOutputs = vx.result; } else { effectiveVersion = (buildResultOrOutputs as BuildResultV3).output?.type === 'Lambda' ? 3 : 2; } } // Sort out build result to builder v2 shape if (!effectiveVersion || effectiveVersion === 1) { // `BuilderOutputs` map was returned (Now Builder v1 behavior) result = { output: buildResultOrOutputs as BuilderOutputs, routes: [], watch: [], }; } else if (effectiveVersion === 2) { result = buildResultOrOutputs as BuildResult; } else if (effectiveVersion === 3) { const { output, ...rest } = buildResultOrOutputs as BuildResultV3; if (!output || (output as BuilderOutput).type !== 'Lambda') { throw dev.DEV_BUILDER_RESULT_NOT_LAMBDA(); } if (output.maxDuration) { throw dev.DEV_BUILDER_RESULT_HAS_MAXDURATION(); } if (output.affinity) { throw new Error( 'The result of "builder.build()" must not contain `affinity`' ); } if (output.maxConcurrency) { throw new Error( 'The result of "builder.build()" must not contain `maxConcurrency`' ); } if (output.memory) { throw dev.DEV_BUILDER_RESULT_HAS_MEMORY(); } for (const [src, func] of Object.entries(config.functions || {})) { if (src === entrypoint || minimatch(entrypoint, src)) { if (func.maxDuration) { output.maxDuration = func.maxDuration; } if (func.affinity) { output.affinity = func.affinity; } if (func.maxConcurrency) { output.maxConcurrency = func.maxConcurrency; } if (func.memory) { output.memory = func.memory; } break; } } result = { ...rest, output: { [entrypoint]: output, }, } as BuildResult; } else { throw await getUnsupportedBuilderVersionError((builder as any).version); } // Normalize Builder Routes const normalized = normalizeRoutes(result.routes); if (normalized.error) { throw dev.DEV_INVALID_ROUTES({ message: normalized.error.message }); } else { result.routes = normalized.routes || []; } const { output: buildOutput } = result; const { cleanUrls } = vercelConfig; // Mimic fmeta-util and perform file renaming for (const [originalPath, value] of Object.entries(buildOutput)) { let path = normalizePath(originalPath); if (cleanUrls && path.endsWith('.html')) { path = path.slice(0, -5); if (value.type === 'FileBlob' || value.type === 'FileFsRef') { value.contentType = value.contentType || 'text/html; charset=utf-8'; } } const extensionless = devServer.getExtensionlessFile(path); if (extensionless) { path = extensionless; } buildOutput[path] = value; } // Convert the JSON-ified output map back into their corresponding `File` // subclass type instances. At this point, the objects are still in their // serialized IPC form (Buffers as {type:'Buffer',data:[...]}, etc). const deserializedOutput = await deserializeBuildOutputs( buildOutput as unknown as SerializedBuildOutputs ); for (const [name, output] of Object.entries(deserializedOutput)) { buildOutput[name] = output; } // The `watch` array must not have "./" prefix, so if the builder returned // watched files that contain "./" strip them here for ease of writing the // builder. result.watch = (result.watch || []).map((w: string) => { if (w.startsWith('./')) { return w.substring(2); } return w; }); // The `entrypoint` should always be watched, since we know that it was used // to produce the build output. This is for builders that don't implement // a fully featured `watch` return value. if (!result.watch.includes(entrypoint)) { result.watch.push(entrypoint); } // Enforce the lambda zip size soft watermark const maxLambdaBytes = bytes('50mb'); for (const asset of Object.values(result.output)) { if ( asset.type === 'Lambda' && !( typeof asset.runtime === 'string' && asset.runtime.startsWith('python') ) && // Container Lambdas carry an OCI image reference in `handler`, not a code // bundle — there is no zip to size-check. They are built and run locally // by the builder's `startDevServer`, not by `fun`. asset.runtime !== 'container' ) { const size = asset.zipBuffer.length; if (size > maxLambdaBytes) { throw new LambdaSizeExceededError(size, maxLambdaBytes); } } } // Create function for all 'Lambda' type output await Promise.all( Object.entries(result.output).map(async entry => { const path: string = entry[0]; const asset: BuilderOutput = entry[1]; // Container Lambdas are an OCI image reference, not a zip-based function: // they have no `zipBuffer`/`createZip` and cannot run under `fun`. The // builder's `startDevServer` builds and runs the image locally instead, // so skip the `fun` function creation here. if (asset.type === 'Lambda' && asset.runtime !== 'container') { // Tear down the previous `fun` Lambda instance for this asset const oldAsset = match.buildOutput && match.buildOutput[path]; if (oldAsset && oldAsset.type === 'Lambda' && oldAsset.fn) { await oldAsset.fn.destroy(); } const ZipFile = asset.zipBuffer || (await asset.createZip()); await initializeFunRuntime(asset.runtime); asset.fn = await createFunction({ Code: { ZipFile }, Handler: asset.handler, Runtime: asset.runtime, MemorySize: asset.memory || 3009, Environment: { Variables: { ...vercelConfig.env, ...asset.environment, ...envConfigs.runEnv, }, }, }); } match.buildTimestamp = Date.now(); }) ); match.buildResultVersion = effectiveVersion; match.buildResults.set(requestPath, result); Object.assign(match.buildOutput, result.output); if (showBuildTimestamp) { const endTime = Date.now(); output.log(`Built ${use}:${entrypoint} [${ms(endTime - startTime)}]`); } } export async function getBuildMatches( vercelConfig: VercelConfig, cwd: string, devServer: DevServer, fileList: string[] ): Promise { const matches: BuildMatch[] = []; if (fileList.length === 0) { // If there's no files in the cwd then we know there won't be any build // matches, so bail eagerly, and avoid printing the "no matches" message. return matches; } const noMatches: Builder[] = []; const builds = vercelConfig.builds || [{ src: '**', use: '@vercel/static' }]; const builderSpecs = new Set(builds.map(b => b.use).filter(Boolean)); const buildersWithPkgs = await importBuilders(builderSpecs, cwd); for (const buildConfig of builds) { let { src = '**', use, config = {} } = buildConfig; if (!use) { continue; } if (src[0] === '/') { // Remove a leading slash so that the globbing is relative to `cwd` // instead of the root of the filesystem. This matches the behavior // of Vercel deployments. src = src.substring(1); } // FIXME: hono-cleanup - we need to specify a src that we know exists // so the rest of the script doesn't choke on it. But the framework preset // needs to `index.js` so the BOA entry is index.func. BuildResultV2 allows // us to return a different value from what the preset provides, but we need // to use BuildResultV3 so that we can run the dev server with the startDevServer // function exported from backend frameworks. if (isBackendFramework(buildConfig.config?.framework)) { src = 'package.json'; } // lambda function files are trimmed of their file extension const mapToEntrypoint = new Map(); // The Python builder handles entrypoint discovery itself via . // We still need to match a real file so the dev server creates a BuildMatch, // but we preserve the original src (e.g. "") as the entrypoint // passed to startDevServer/build. if ( buildConfig.config?.framework && isPythonFramework(buildConfig.config?.framework) ) { const originalSrc = src; const pythonManifestFiles = [ 'pyproject.toml', 'requirements.txt', 'Pipfile', ]; const existing = pythonManifestFiles.filter(p => fileList.includes(p)); if (existing.length > 0) { src = existing[0]; mapToEntrypoint.set(src, originalSrc); } } // The Node framework preset uses `package.json` as a stable build src, // while @vercel/backends discovers the actual server entrypoint. A // package.json is optional, so match a detected server file in dev while // preserving the sentinel passed to the builder. if (buildConfig.config?.framework === 'node' && !fileList.includes(src)) { const originalSrc = src; const existing = fileList.find(path => /^(?:src\/)?server\.[cm]?[jt]s$/.test(path) ); if (existing) { src = existing; mapToEntrypoint.set(src, originalSrc); } } // The Go framework preset keeps `index.go` as the stable build src for // deployment routing. In dev, if that sentinel file is absent, match one // of the known standalone entrypoints but still pass `index.go` through // as the builder entrypoint so @vercel/go performs the final resolution. if (buildConfig.config?.framework === 'go' && !fileList.includes(src)) { const originalSrc = src; const goEntrypoints = [ 'main.go', 'cmd/api/main.go', 'cmd/server/main.go', ]; const existing = goEntrypoints.filter(p => fileList.includes(p)); if (existing.length > 0) { src = existing[0]; mapToEntrypoint.set(src, originalSrc); } } // If the Rust preset's `src/main.rs` is absent (e.g. a `[[bin]]`-only // project), match `Cargo.toml` but keep `src/main.rs` as the builder // entrypoint so @vercel/rust resolves the binary via `cargo metadata`. if ( buildConfig.config?.framework === 'rust' && src === 'src/main.rs' && !fileList.includes(src) ) { const originalSrc = src; if (fileList.includes('Cargo.toml')) { src = 'Cargo.toml'; mapToEntrypoint.set(src, originalSrc); } } // The container framework preset resolves its entrypoint via ``, // which @vercel/container expands to a discovered Dockerfile at build time. // Inside `services` the orchestrator owns this, but for a top-level // container build the dev server needs to match a real Dockerfile so a // BuildMatch is created — while still passing the original sentinel src // through as the builder entrypoint. if ( buildConfig.config?.framework === 'container' && !fileList.includes(src) ) { const originalSrc = src; const dockerfileCandidates = [ 'Dockerfile.vercel', 'Containerfile.vercel', 'Dockerfile', 'Containerfile', ]; const existing = dockerfileCandidates.find(p => fileList.includes(p)); if (existing) { src = existing; mapToEntrypoint.set(src, originalSrc); } } const extensionless = devServer.getExtensionlessFile(src); if (extensionless) { mapToEntrypoint.set(extensionless, src); src = extensionless; } const files = fileList .filter(name => name === src || minimatch(name, src, { dot: true })) .map(name => join(cwd, name)); if (files.length === 0) { // Don't warn about zero-config static builders (e.g. public/**) // when the directory simply doesn't exist. if (!(config.zeroConfig && use === '@vercel/static')) { noMatches.push(buildConfig); } } for (const file of files) { src = relative(cwd, file); const entrypoint = mapToEntrypoint.get(src) || src; // Remove the output directory prefix if (config.zeroConfig && config.outputDirectory) { const outputMatch = config.outputDirectory + '/'; if (src.startsWith(outputMatch)) { src = src.slice(outputMatch.length); } } const builderWithPkg = buildersWithPkgs.get(use); if (!builderWithPkg) { throw dev.DEV_BUILDER_LOAD_FAILED({ use }); } matches.push({ ...buildConfig, src, entrypoint, builderWithPkg, buildOutput: {}, buildResults: new Map(), buildTimestamp: 0, }); } } if (noMatches.length > 0) { output.warn( `You defined ${plural( 'build', noMatches.length, true )} that did not match any source files (please ensure they are NOT defined in ${highlight( '.vercelignore' )}):` ); for (const buildConfig of noMatches) { output.print(`- ${JSON.stringify(buildConfig)}\n`); } } return matches; } export async function shutdownBuilder(match: BuildMatch): Promise { const ops: Promise[] = []; if (match.buildProcess) { const { pid } = match.buildProcess; output.debug(`Killing builder sub-process with PID ${pid}`); const killPromise = treeKill(pid!) .then(() => { output.debug(`Killed builder with PID ${pid}`); }) .catch((err: Error) => { output.debug(`Failed to kill builder with PID ${pid}: ${err}`); }); ops.push(killPromise); delete match.buildProcess; } if (match.buildOutput) { for (const asset of Object.values(match.buildOutput)) { if (asset.type === 'Lambda' && asset.fn) { output.debug(`Shutting down Lambda function`); ops.push(asset.fn.destroy()); } } } await Promise.all(ops); }