Commit 07550dc7 authored by Jimmy Lai's avatar Jimmy Lai

perf(cli): single-process dev server with Rust CLI wrapper

Replace fork-based architecture with single Node.js process:

- Add Rust CLI wrapper (`crates/next-cli/`) that handles:
  - NODE_OPTIONS (memory limits, source maps, inspect)
  - WATCHPACK_WATCHER_LIMIT for large projects
  - Restart loop (exit code 77) without Node.js overhead

- Simplify next-dev.ts: remove fork(), IPC, child process management
- Simplify start-server.ts: remove NEXT_PRIVATE_WORKER handling

- Add shell entry points (bin/next, bin/next.cmd) that:
  - Use native binary when available (~10ms overhead)
  - Fall back to Node.js entry point

- Add lazy loading for heavy modules:
  - tar (download-swc) - only needed for fallback download
  - edge-runtime sandbox - only needed for edge functions
  - MCP SDK - only needed when clients connect

- Set up cross-platform release pipeline:
  - Build @next/cli-* for 8 platforms in CI
  - Publish as optional dependencies
  - Update install-native.mjs for development

Saves ~35-50ms on dev server startup by eliminating parent
Node.js process and fork overhead.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: 's avatarClaude Opus 4.5 <noreply@anthropic.com>
parent b556af73
......@@ -430,6 +430,18 @@ jobs:
name: next-swc-binaries-${{ matrix.settings.target }}
path: packages/next-swc/native/next-swc.*.node
# Build next-cli native binary (simple Rust CLI wrapper)
- name: Build next-cli
if: ${{ steps.check-did-build.outputs.DID_BUILD == 'true' }}
run: cargo build --release --target ${{ matrix.settings.target }} -p next-cli
- name: Upload next-cli artifact
if: ${{ steps.check-did-build.outputs.DID_BUILD == 'true' }}
uses: actions/upload-artifact@v4
with:
name: next-cli-${{ matrix.settings.target }}
path: target/${{ matrix.settings.target }}/release/next${{ matrix.settings.target == 'x86_64-pc-windows-msvc' && '.exe' || matrix.settings.target == 'aarch64-pc-windows-msvc' && '.exe' || '' }}
- name: Upload turbo summary artifact
uses: actions/upload-artifact@v4
with:
......@@ -539,6 +551,28 @@ jobs:
merge-multiple: true
path: crates/wasm
- uses: actions/download-artifact@v4
with:
pattern: next-cli-*
merge-multiple: false
path: packages/next/bin
# Rename next-cli binaries to include platform in filename
- name: Organize next-cli binaries
run: |
cd packages/next/bin
for dir in next-cli-*/; do
platform="${dir#next-cli-}"
platform="${platform%/}"
if [[ "$platform" == *"win32"* ]]; then
mv "$dir/next.exe" "next-cli-${platform}.exe" 2>/dev/null || true
else
mv "$dir/next" "next-cli-${platform}" 2>/dev/null || true
fi
rmdir "$dir" 2>/dev/null || true
done
ls -la
- name: Create tarballs
# github.event.after is available on push and pull_request#synchronize events.
# For workflow_dispatch events, github.sha is the head commit.
......@@ -604,6 +638,28 @@ jobs:
merge-multiple: true
path: crates/wasm
- uses: actions/download-artifact@v4
with:
pattern: next-cli-*
merge-multiple: false
path: packages/next/bin
# Rename next-cli binaries to include platform in filename
- name: Organize next-cli binaries
run: |
cd packages/next/bin
for dir in next-cli-*/; do
platform="${dir#next-cli-}"
platform="${platform%/}"
if [[ "$platform" == *"win32"* ]]; then
mv "$dir/next.exe" "next-cli-${platform}.exe" 2>/dev/null || true
else
mv "$dir/next" "next-cli-${platform}" 2>/dev/null || true
fi
rmdir "$dir" 2>/dev/null || true
done
ls -la
- run: npm i -g npm@10.4.0 # need latest version for provenance (pinning to avoid bugs)
- run: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
- run: ./scripts/publish-native.js
......
......@@ -63,3 +63,8 @@ test-timings.json
# Storybook
*storybook.log
# Native CLI binaries (shell scripts next and next.cmd are committed)
packages/next/bin/next-native
packages/next/bin/next-native.exe
packages/next/bin/next-cli-*
......@@ -4343,6 +4343,10 @@ dependencies = [
"turbopack-trace-utils",
]
[[package]]
name = "next-cli"
version = "0.1.0"
[[package]]
name = "next-core"
version = "0.1.0"
......
......@@ -8,6 +8,7 @@ members = [
"crates/next-api",
"crates/next-build-test",
"crates/next-build",
"crates/next-cli",
"crates/next-core",
"crates/next-custom-transforms",
"crates/next-taskless",
......
[package]
name = "next-cli"
version = "0.1.0"
edition = "2021"
description = "Ultra-fast CLI wrapper for Next.js"
license = "MIT"
[[bin]]
name = "next"
path = "src/main.rs"
[dependencies]
# No dependencies - keeps binary tiny and compile fast
{
"name": "@next/cli-darwin-arm64",
"version": "0.0.0",
"description": "Next.js CLI binary for darwin-arm64",
"repository": {
"type": "git",
"url": "https://github.com/vercel/next.js",
"directory": "crates/next-cli"
},
"os": [
"darwin"
],
"cpu": [
"arm64"
],
"bin": {
"next-native": "next"
},
"files": [
"next"
],
"license": "MIT",
"engines": {
"node": ">= 20"
}
}
{
"name": "@next/cli-darwin-x64",
"version": "0.0.0",
"description": "Next.js CLI binary for darwin-x64",
"repository": {
"type": "git",
"url": "https://github.com/vercel/next.js",
"directory": "crates/next-cli"
},
"os": [
"darwin"
],
"cpu": [
"x64"
],
"bin": {
"next-native": "next"
},
"files": [
"next"
],
"license": "MIT",
"engines": {
"node": ">= 20"
}
}
{
"name": "@next/cli-linux-arm64-gnu",
"version": "0.0.0",
"description": "Next.js CLI binary for linux-arm64-gnu",
"repository": {
"type": "git",
"url": "https://github.com/vercel/next.js",
"directory": "crates/next-cli"
},
"os": [
"linux"
],
"cpu": [
"arm64"
],
"bin": {
"next-native": "next"
},
"files": [
"next"
],
"license": "MIT",
"engines": {
"node": ">= 20"
}
}
{
"name": "@next/cli-linux-arm64-musl",
"version": "0.0.0",
"description": "Next.js CLI binary for linux-arm64-musl",
"repository": {
"type": "git",
"url": "https://github.com/vercel/next.js",
"directory": "crates/next-cli"
},
"os": [
"linux"
],
"cpu": [
"arm64"
],
"bin": {
"next-native": "next"
},
"files": [
"next"
],
"license": "MIT",
"engines": {
"node": ">= 20"
}
}
{
"name": "@next/cli-linux-x64-gnu",
"version": "0.0.0",
"description": "Next.js CLI binary for linux-x64-gnu",
"repository": {
"type": "git",
"url": "https://github.com/vercel/next.js",
"directory": "crates/next-cli"
},
"os": [
"linux"
],
"cpu": [
"x64"
],
"bin": {
"next-native": "next"
},
"files": [
"next"
],
"license": "MIT",
"engines": {
"node": ">= 20"
}
}
{
"name": "@next/cli-linux-x64-musl",
"version": "0.0.0",
"description": "Next.js CLI binary for linux-x64-musl",
"repository": {
"type": "git",
"url": "https://github.com/vercel/next.js",
"directory": "crates/next-cli"
},
"os": [
"linux"
],
"cpu": [
"x64"
],
"bin": {
"next-native": "next"
},
"files": [
"next"
],
"license": "MIT",
"engines": {
"node": ">= 20"
}
}
{
"name": "@next/cli-win32-arm64-msvc",
"version": "0.0.0",
"description": "Next.js CLI binary for win32-arm64-msvc",
"repository": {
"type": "git",
"url": "https://github.com/vercel/next.js",
"directory": "crates/next-cli"
},
"os": [
"win32"
],
"cpu": [
"arm64"
],
"bin": {
"next-native": "next.exe"
},
"files": [
"next.exe"
],
"license": "MIT",
"engines": {
"node": ">= 20"
}
}
{
"name": "@next/cli-win32-x64-msvc",
"version": "0.0.0",
"description": "Next.js CLI binary for win32-x64-msvc",
"repository": {
"type": "git",
"url": "https://github.com/vercel/next.js",
"directory": "crates/next-cli"
},
"os": [
"win32"
],
"cpu": [
"x64"
],
"bin": {
"next-native": "next.exe"
},
"files": [
"next.exe"
],
"license": "MIT",
"engines": {
"node": ">= 20"
}
}
//! Next.js CLI Wrapper
//!
//! A fast native binary that handles the restart loop for `next dev`.
//! Exit code 77 signals "restart needed" (e.g., after config changes).
//!
//! ## Production Only
//!
//! This binary is designed for production use when installed via npm.
//! It expects to be located at `node_modules/@next/cli-*/bin/next` with
//! the Next.js script at `node_modules/next/dist/bin/next`.
//!
//! For in-repo development, the shell scripts (`bin/next`) fall back to
//! Node.js directly. This keeps the Rust code simple and focused.
//!
//! ## Node Flags
//!
//! Flags like `--inspect` must be passed to Node.js before the script.
//! This binary detects these flags and reorders them automatically.
use std::{
env,
path::PathBuf,
process::{exit, Command},
};
/// Exit code used by Next.js to signal restart needed
const RESTART_EXIT_CODE: i32 = 77;
/// Parsed command-line arguments
struct ParsedArgs {
/// Flags that must be passed to Node.js (e.g., --inspect)
node_flags: Vec<String>,
/// Arguments for the Next.js script
script_args: Vec<String>,
/// Whether to enable source maps
enable_source_maps: bool,
}
/// Parse arguments, separating Node.js flags from script arguments
fn parse_args(args: &[String]) -> ParsedArgs {
let mut node_flags = Vec::new();
let mut script_args = Vec::new();
let mut enable_source_maps = true;
for arg in args.iter().skip(1) {
if arg.starts_with("--inspect") {
node_flags.push(arg.clone());
} else {
if arg == "--disable-source-maps" {
enable_source_maps = false;
}
script_args.push(arg.clone());
}
}
ParsedArgs {
node_flags,
script_args,
enable_source_maps,
}
}
/// Get the path to the Next.js script
fn get_script_path() -> PathBuf {
// Production path: binary at @next/cli-*/bin/next
// Script at node_modules/next/dist/bin/next (sibling package)
env::current_exe()
.expect("failed to get executable path")
.canonicalize()
.expect("failed to canonicalize path")
.parent()
.expect("failed to get bin dir")
.parent()
.expect("failed to get package dir")
.parent()
.expect("failed to get node_modules dir")
.join("next/dist/bin/next")
}
/// Check if user has already set memory limit in NODE_OPTIONS
fn user_set_memory_limit() -> bool {
env::var("NODE_OPTIONS")
.map(|opts| opts.contains("max-old-space-size") || opts.contains("max_old_space_size"))
.unwrap_or(false)
}
/// Get total system memory in MB
fn get_system_memory_mb() -> Option<u64> {
#[cfg(target_os = "linux")]
{
parse_linux_meminfo(&std::fs::read_to_string("/proc/meminfo").ok()?)
}
#[cfg(target_os = "macos")]
{
let output = Command::new("sysctl")
.args(["-n", "hw.memsize"])
.output()
.ok()?;
let bytes: u64 = String::from_utf8_lossy(&output.stdout)
.trim()
.parse()
.ok()?;
Some(bytes / 1024 / 1024)
}
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
{
None
}
}
/// Parse Linux /proc/meminfo content to get total memory in MB
#[cfg(target_os = "linux")]
fn parse_linux_meminfo(content: &str) -> Option<u64> {
for line in content.lines() {
if let Some(rest) = line.strip_prefix("MemTotal:") {
// Format: "MemTotal: 16384000 kB"
let kb: u64 = rest.split_whitespace().next()?.parse().ok()?;
return Some(kb / 1024);
}
}
None
}
fn main() {
let args: Vec<String> = env::args().collect();
let parsed = parse_args(&args);
let script = get_script_path();
// Calculate memory limit once (50% of system memory)
let memory_limit_mb = get_system_memory_mb().map(|mb| mb / 2);
let should_set_memory = memory_limit_mb.is_some() && !user_set_memory_limit();
// Restart loop: exit code 77 means "restart me"
loop {
let mut cmd = Command::new("node");
// Node.js flags (must come before script)
if parsed.enable_source_maps {
cmd.arg("--enable-source-maps");
}
if let (true, Some(mb)) = (should_set_memory, memory_limit_mb) {
cmd.arg(format!("--max-old-space-size={}", mb));
}
// User's Node.js flags (--inspect, etc.)
cmd.args(&parsed.node_flags);
// Script and script arguments
cmd.arg(&script).args(&parsed.script_args);
// Environment variables
cmd.env("NEXT_RUST_CLI", "1");
// macOS: limit file watchers to avoid slow cleanup
// https://github.com/nodejs/node/issues/29949
#[cfg(target_os = "macos")]
if parsed.script_args.first().map(|s| s.as_str()) == Some("dev") {
cmd.env("WATCHPACK_WATCHER_LIMIT", "20");
}
let status = cmd.status().expect("failed to execute node");
let code = status.code().unwrap_or(1);
if code != RESTART_EXIT_CODE {
exit(code);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_args_basic() {
let args = vec!["next".into(), "dev".into()];
let parsed = parse_args(&args);
assert!(parsed.node_flags.is_empty());
assert_eq!(parsed.script_args, vec!["dev"]);
assert!(parsed.enable_source_maps);
}
#[test]
fn test_parse_args_with_inspect() {
let args = vec!["next".into(), "dev".into(), "--inspect".into()];
let parsed = parse_args(&args);
assert_eq!(parsed.node_flags, vec!["--inspect"]);
assert_eq!(parsed.script_args, vec!["dev"]);
}
#[test]
fn test_parse_args_with_inspect_port() {
let args = vec!["next".into(), "--inspect=9229".into(), "dev".into()];
let parsed = parse_args(&args);
assert_eq!(parsed.node_flags, vec!["--inspect=9229"]);
assert_eq!(parsed.script_args, vec!["dev"]);
}
#[test]
fn test_parse_args_with_inspect_brk() {
let args = vec!["next".into(), "dev".into(), "--inspect-brk".into()];
let parsed = parse_args(&args);
assert_eq!(parsed.node_flags, vec!["--inspect-brk"]);
assert_eq!(parsed.script_args, vec!["dev"]);
}
#[test]
fn test_parse_args_disable_source_maps() {
let args = vec!["next".into(), "dev".into(), "--disable-source-maps".into()];
let parsed = parse_args(&args);
assert!(!parsed.enable_source_maps);
assert_eq!(parsed.script_args, vec!["dev", "--disable-source-maps"]);
}
#[test]
fn test_parse_args_complex() {
let args = vec![
"next".into(),
"--inspect=9229".into(),
"dev".into(),
"--port".into(),
"3001".into(),
"--inspect-brk=9230".into(),
];
let parsed = parse_args(&args);
assert_eq!(
parsed.node_flags,
vec!["--inspect=9229", "--inspect-brk=9230"]
);
assert_eq!(parsed.script_args, vec!["dev", "--port", "3001"]);
assert!(parsed.enable_source_maps);
}
#[cfg(target_os = "linux")]
#[test]
fn test_parse_linux_meminfo() {
let content = "MemTotal: 16384000 kB\nMemFree: 1234567 kB\n";
assert_eq!(parse_linux_meminfo(content), Some(16000)); // 16384000 / 1024 = 16000
let content = "MemTotal: 8000000 kB\n";
assert_eq!(parse_linux_meminfo(content), Some(7812)); // 8000000 / 1024 = 7812
let content = "SomeOther: 12345 kB\n";
assert_eq!(parse_linux_meminfo(content), None);
}
}
#!/bin/sh
# Next.js CLI entry point
#
# Tries to use the native Rust binary for faster restarts, falls back to Node.js.
# The Rust binary is distributed via @next/cli-* platform-specific packages.
DIR="$(dirname "$0")"
# Production: check installed @next/cli-* package (hoisted to node_modules/@next/cli-*)
for pkg in "$DIR"/../../@next/cli-*/next; do
[ -x "$pkg" ] && exec "$pkg" "$@"
done
# Fallback: Node.js (also used for in-repo development)
exec node "$DIR/../dist/bin/next" "$@"
@echo off
:: Next.js CLI entry point
::
:: Tries to use the native Rust binary for faster restarts, falls back to Node.js.
:: The Rust binary is distributed via @next/cli-* platform-specific packages.
setlocal
set "DIR=%~dp0"
:: Production: try native binary from @next/cli-* package (hoisted to node_modules/@next/cli-*)
if exist "%DIR%..\..\@next\cli-win32-x64-msvc\next.exe" (
"%DIR%..\..\@next\cli-win32-x64-msvc\next.exe" %*
exit /b %errorlevel%
)
if exist "%DIR%..\..\@next\cli-win32-arm64-msvc\next.exe" (
"%DIR%..\..\@next\cli-win32-arm64-msvc\next.exe" %*
exit /b %errorlevel%
)
:: Fallback: Node.js (also used for in-repo development)
node "%DIR%..\dist\bin\next" %*
......@@ -72,10 +72,11 @@
"experimental/testmode/playwright/msw.js",
"experimental/testmode/playwright/msw.d.ts",
"experimental/testmode/proxy.js",
"experimental/testmode/proxy.d.ts"
"experimental/testmode/proxy.d.ts",
"bin"
],
"bin": {
"next": "./dist/bin/next"
"next": "./bin/next"
},
"scripts": {
"dev": "cross-env NEXT_SERVER_NO_MANGLE=1 taskr",
......
......@@ -2,17 +2,8 @@
import '../server/lib/cpu-profile'
import type { StartServerOptions } from '../server/lib/start-server'
import {
RESTART_EXIT_CODE,
getNodeDebugType,
getParsedDebugAddress,
getMaxOldSpaceSize,
printAndExit,
formatNodeOptions,
formatDebugAddress,
getParsedNodeOptions,
type DebugAddress,
} from '../server/lib/utils'
import { printAndExit } from '../server/lib/utils'
import type { DebugAddress } from '../server/lib/utils'
import * as Log from '../build/output/log'
import { getProjectDir } from '../lib/get-project-dir'
import { PHASE_DEVELOPMENT_SERVER } from '../shared/lib/constants'
......@@ -28,18 +19,11 @@ import { traceGlobals } from '../trace/shared'
// import uploadTrace from '../trace/upload-trace' - loaded only with --experimental-upload-trace
import type { SelfSignedCertificate } from '../lib/mkcert'
import { fileExists, FileType } from '../lib/file-exists'
import { initialEnv } from '@next/env'
import { fork } from 'child_process'
import type { ChildProcess } from 'child_process'
import {
getReservedPortExplanation,
isPortIsReserved,
} from '../lib/helpers/get-reserved-port'
import os from 'os'
import { once } from 'node:events'
import { clearTimeout } from 'timers'
import { flushAllTraces, trace } from '../trace'
import { traceId } from '../trace/shared'
import {
Bundler,
finalizeBundlerFromConfig,
......@@ -66,7 +50,6 @@ export type NextDevOptions = {
type PortSource = 'cli' | 'default' | 'env'
let dir: string
let child: undefined | ChildProcess
// The config in next-dev is only used to access config.distDir for telemetry and trace.
let config: NextConfigComplete
let bundler: Bundler
......@@ -75,35 +58,10 @@ let sessionStopHandled = false
const sessionStarted = Date.now()
const sessionSpan = trace('next-dev')
// How long should we wait for the child to cleanly exit after sending
// SIGINT/SIGTERM to the child process before sending SIGKILL?
const CHILD_EXIT_TIMEOUT_MS = parseInt(
process.env.NEXT_EXIT_TIMEOUT_MS ?? '100',
10
)
const handleSessionStop = async (signal: NodeJS.Signals | number | null) => {
if (signal != null && child?.pid) child.kill(signal)
const handleSessionStop = async () => {
if (sessionStopHandled) return
sessionStopHandled = true
// Capture the child's exit code if it has already exited and caused the
// session stop (via the 'exit' event), otherwise assume success (0).
const exitCode = child?.exitCode || 0
if (
signal != null &&
child?.pid &&
child.exitCode === null &&
child.signalCode === null
) {
let exitTimeout = setTimeout(() => {
child?.kill('SIGKILL')
}, CHILD_EXIT_TIMEOUT_MS)
await once(child, 'exit').catch(() => {})
clearTimeout(exitTimeout)
}
sessionSpan.stop()
await flushAllTraces({ end: true })
......@@ -177,14 +135,11 @@ const handleSessionStop = async (signal: NodeJS.Signals | number | null) => {
// the program, or the cursor could remain hidden
process.stdout.write('\x1B[?25h')
process.stdout.write('\n')
process.exit(exitCode)
process.exit(0)
}
process.on('SIGINT', () => handleSessionStop('SIGINT'))
process.on('SIGTERM', () => handleSessionStop('SIGTERM'))
// exit event must be synchronous
process.on('exit', () => child?.kill('SIGKILL'))
process.on('SIGINT', () => handleSessionStop())
process.on('SIGTERM', () => handleSessionStop())
const nextDev = async (
options: NextDevOptions,
......@@ -268,142 +223,24 @@ const nextDev = async (
hostname: host,
}
const startServerPath = require.resolve(
'../server/lib/start-server-with-cache'
)
async function startServer(startServerOptions: StartServerOptions) {
return new Promise<void>((resolve) => {
let resolved = false
const defaultEnv = (initialEnv || process.env) as typeof process.env
const nodeOptions = getParsedNodeOptions()
let maxOldSpaceSize: string | number | undefined = getMaxOldSpaceSize()
if (!maxOldSpaceSize && !process.env.NEXT_DISABLE_MEM_OVERRIDE) {
const totalMem = os.totalmem()
const totalMemInMB = Math.floor(totalMem / 1024 / 1024)
maxOldSpaceSize = Math.floor(totalMemInMB * 0.5).toString()
nodeOptions['max-old-space-size'] = maxOldSpaceSize
// Ensure the max_old_space_size is not also set.
delete nodeOptions['max_old_space_size']
}
if (options.disableSourceMaps) {
delete nodeOptions['enable-source-maps']
} else {
nodeOptions['enable-source-maps'] = true
}
const nodeDebugType = getNodeDebugType(nodeOptions)
const originalAddress =
nodeDebugType === undefined ? undefined : nodeOptions[nodeDebugType]
delete nodeOptions.inspect
delete nodeOptions['inspect-brk']
delete nodeOptions['inspect_brk']
if (nodeDebugType !== undefined) {
const address = getParsedDebugAddress(originalAddress)
address.port = address.port === 0 ? 0 : address.port + 1
nodeOptions[nodeDebugType] = formatDebugAddress(address)
} else if (options.inspect) {
const address: DebugAddress =
options.inspect === true
? getParsedDebugAddress(true)
: options.inspect
nodeOptions.inspect = formatDebugAddress(address)
}
child = fork(startServerPath, {
stdio: 'inherit',
env: {
...defaultEnv,
...(bundler === Bundler.Turbopack
? { TURBOPACK: process.env.TURBOPACK }
: undefined),
NEXT_PRIVATE_WORKER: '1',
NEXT_PRIVATE_TRACE_ID: traceId,
// Pass server options via env to eliminate IPC handshake latency
NEXT_PRIVATE_WORKER_OPTIONS: JSON.stringify(startServerOptions),
NODE_EXTRA_CA_CERTS: startServerOptions.selfSignedCertificate
? startServerOptions.selfSignedCertificate.rootCA
: defaultEnv.NODE_EXTRA_CA_CERTS,
NODE_OPTIONS: formatNodeOptions(nodeOptions),
// There is a node.js bug on MacOS which causes closing file watchers to be really slow.
// This limits the number of watchers to mitigate the issue.
// https://github.com/nodejs/node/issues/29949
WATCHPACK_WATCHER_LIMIT:
os.platform() === 'darwin' ? '20' : undefined,
},
})
child.on('message', (msg: any) => {
if (msg && typeof msg === 'object') {
if (msg.nextServerReady && !resolved) {
if (msg.port) {
// Store the used port in case a random one was selected, so that
// it can be re-used on automatic dev server restarts.
port = parseInt(msg.port, 10)
}
resolved = true
resolve()
}
}
})
child.on('exit', async (code, signal) => {
if (sessionStopHandled || signal) {
return
}
if (code === RESTART_EXIT_CODE) {
// Starting the dev server will overwrite the `.next/trace` file, so we
// must upload the existing contents before restarting the server to
// preserve the metrics.
if (traceUploadUrl) {
// Postpone loading next config when we need to get
// config.distDir for upload trace.
const loadConfig = (
require('../server/config') as typeof import('../server/config')
).default
config =
config ||
(await loadConfig(PHASE_DEVELOPMENT_SERVER, dir, {
silent: true,
}))
bundler = finalizeBundlerFromConfig(bundler)
const uploadTrace = (
require('../trace/upload-trace') as typeof import('../trace/upload-trace')
).default
uploadTrace({
traceUploadUrl,
mode: 'dev',
projectDir: dir,
distDir: config.distDir,
isTurboSession: bundler === Bundler.Turbopack,
sync: true,
})
}
return startServer({ ...startServerOptions, port })
}
// Call handler (e.g. upload telemetry). Don't try to send a signal to
// the child, as it has already exited.
await handleSessionStop(/* signal */ null)
})
})
// Set TURBOPACK env if using turbopack bundler
if (bundler === Bundler.Turbopack) {
process.env.TURBOPACK = '1'
}
const runDevServer = async (reboot: boolean) => {
try {
// Load startServer from bundled version with optional bytecode caching
// The Rust wrapper handles restarts via exit code 77
const { startServer } =
require('../server/lib/start-server-with-cache') as typeof import('../server/lib/start-server-with-cache')
let certificate: SelfSignedCertificate | undefined
if (!!options.experimentalHttps) {
Log.warn(
'Self-signed certificates are currently an experimental feature, use with caution.'
)
let certificate: SelfSignedCertificate | undefined
const key = options.experimentalHttpsKey
const cert = options.experimentalHttpsCert
const rootCA = options.experimentalHttpsCa
......@@ -419,15 +256,15 @@ const nextDev = async (
require('../lib/mkcert') as typeof import('../lib/mkcert')
certificate = await createSelfSignedCertificate(host)
}
await startServer({
...devServerOptions,
selfSignedCertificate: certificate,
})
} else {
await startServer(devServerOptions)
}
// Start server directly in this process
// Exit code 77 (from config watcher) will be handled by Rust wrapper
await startServer({
...devServerOptions,
selfSignedCertificate: certificate,
})
await preflight(reboot)
} catch (err) {
console.error(err)
......
......@@ -17,7 +17,6 @@ import v8 from 'v8'
import path from 'path'
import http from 'http'
import https from 'https'
import os from 'os'
import { exec } from 'child_process'
import Watchpack from 'next/dist/compiled/watchpack'
import * as Log from '../../build/output/log'
......@@ -520,43 +519,3 @@ export async function startServer(
})
}
}
if (process.env.NEXT_PRIVATE_WORKER && process.send) {
// Read server options from env to eliminate IPC handshake latency
let workerOptions = null
if (process.env.NEXT_PRIVATE_WORKER_OPTIONS) {
try {
workerOptions = JSON.parse(process.env.NEXT_PRIVATE_WORKER_OPTIONS)
} catch (err) {
console.error(
'Failed to parse NEXT_PRIVATE_WORKER_OPTIONS:',
err instanceof Error ? err.message : err
)
}
}
if (workerOptions) {
// Start server immediately without waiting for IPC message
;(async () => {
startServerSpan = trace('start-dev-server', undefined, {
cpus: String(os.cpus().length),
platform: os.platform(),
'memory.freeMem': String(os.freemem()),
'memory.totalMem': String(os.totalmem()),
'memory.heapSizeLimit': String(v8.getHeapStatistics().heap_size_limit),
})
await startServerSpan.traceAsyncFn(() => startServer(workerOptions))
const memoryUsage = process.memoryUsage()
startServerSpan.setAttribute('memory.rss', String(memoryUsage.rss))
startServerSpan.setAttribute(
'memory.heapTotal',
String(memoryUsage.heapTotal)
)
startServerSpan.setAttribute(
'memory.heapUsed',
String(memoryUsage.heapUsed)
)
process.send!({ nextServerReady: true, port: process.env.PORT })
})()
}
}
......@@ -2408,6 +2408,47 @@ export async function bin(task, opts) {
.target('dist/bin', { mode: '0755' })
}
// Build the native CLI wrapper binary (Rust)
// This is a simple binary that handles the restart loop for dev server
export async function cli_native(task, opts) {
const { execSync } = require('child_process')
const fs = require('fs')
const path = require('path')
const crateDir = path.join(__dirname, '../../crates/next-cli')
const binDir = path.join(__dirname, 'bin')
// Ensure bin directory exists
if (!fs.existsSync(binDir)) {
fs.mkdirSync(binDir, { recursive: true })
}
// Build the Rust binary
console.log('Building next-cli native binary...')
execSync('cargo build --release', {
cwd: crateDir,
stdio: 'inherit',
})
// Copy the binary to packages/next/bin/
const targetDir = path.join(__dirname, '../../target/release')
const binaryName = process.platform === 'win32' ? 'next.exe' : 'next'
const targetName =
process.platform === 'win32' ? 'next-native.exe' : 'next-native'
fs.copyFileSync(
path.join(targetDir, binaryName),
path.join(binDir, targetName)
)
// Make executable on Unix
if (process.platform !== 'win32') {
fs.chmodSync(path.join(binDir, targetName), 0o755)
}
console.log(`Built next-cli native binary: bin/${targetName}`)
}
export async function cli(task, opts) {
await task
.source('src/cli/**/*.+(js|ts|tsx)')
......
......@@ -22,20 +22,28 @@ import fsp from 'fs/promises'
)
try {
// if installed swc package version matches monorepo version
// if installed swc and cli package versions match monorepo version
// we can skip re-installing
let hasSwc = false
let hasCli = false
for (const pkg of fs.readdirSync(path.join(cwd, 'node_modules', '@next'))) {
if (
pkg.startsWith('swc-') &&
JSON.parse(
fs.readFileSync(
path.join(cwd, 'node_modules', '@next', pkg, 'package.json')
)
).version === nextVersion
) {
console.log(`@next/${pkg}@${nextVersion} already installed, skipping`)
return
const pkgVersion = JSON.parse(
fs.readFileSync(
path.join(cwd, 'node_modules', '@next', pkg, 'package.json')
)
).version
if (pkg.startsWith('swc-') && pkgVersion === nextVersion) {
hasSwc = true
}
if (pkg.startsWith('cli-') && pkgVersion === nextVersion) {
hasCli = true
}
}
if (hasSwc && hasCli) {
console.log(
`@next/swc and @next/cli packages @${nextVersion} already installed, skipping`
)
return
}
} catch {}
......@@ -54,6 +62,14 @@ import fsp from 'fs/promises'
'@next/swc-linux-x64-musl': nextVersion,
'@next/swc-win32-arm64-msvc': nextVersion,
'@next/swc-win32-x64-msvc': nextVersion,
'@next/cli-darwin-arm64': nextVersion,
'@next/cli-darwin-x64': nextVersion,
'@next/cli-linux-arm64-gnu': nextVersion,
'@next/cli-linux-arm64-musl': nextVersion,
'@next/cli-linux-x64-gnu': nextVersion,
'@next/cli-linux-x64-musl': nextVersion,
'@next/cli-win32-arm64-msvc': nextVersion,
'@next/cli-win32-x64-msvc': nextVersion,
},
packageManager,
}
......@@ -86,6 +102,6 @@ import fsp from 'fs/promises'
console.log('Installed the following binary packages:', pkgs)
} catch (e) {
console.error(e)
console.error('Failed to load @next/swc binary packages')
console.error('Failed to load @next/swc and @next/cli binary packages')
}
})()
......@@ -19,6 +19,12 @@ const cwd = process.cwd()
(name) => !name.startsWith('.')
)
// Also publish next-cli packages
let cliPackagesDir = path.join(cwd, 'crates/next-cli/npm')
let cliPlatforms = (await readdir(cliPackagesDir)).filter(
(name) => !name.startsWith('.')
)
await Promise.all(
platforms.map(async (platform) => {
await publishSema.acquire()
......@@ -128,6 +134,66 @@ const cwd = process.cwd()
})
)
// Publish next-cli platform packages
await Promise.all(
cliPlatforms.map(async (platform) => {
await publishSema.acquire()
let output = ''
try {
// Map platform name to binary name
const isWindows = platform.startsWith('win32')
const binaryName = isWindows ? 'next.exe' : 'next'
await cp(
path.join(
cwd,
'packages/next/bin',
`next-cli-${platform}${isWindows ? '.exe' : ''}`
),
path.join(cliPackagesDir, platform, binaryName)
)
let pkg = JSON.parse(
await readFile(path.join(cliPackagesDir, platform, 'package.json'))
)
pkg.version = version
await writeFile(
path.join(cliPackagesDir, platform, 'package.json'),
JSON.stringify(pkg, null, 2)
)
const child = execa(
`npm`,
[
`publish`,
`${path.join(cliPackagesDir, platform)}`,
`--access`,
`public`,
...(version.includes('canary') ? ['--tag', 'canary'] : []),
],
{ stdio: 'inherit' }
)
const handleData = (type) => (chunk) => {
process[type].write(chunk)
output += chunk.toString()
}
child.stdout?.on('data', handleData('stdout'))
child.stderr?.on('data', handleData('stderr'))
await child
} catch (err) {
console.error(`Failed to publish next-cli`, platform, err)
if (
output.includes(
'cannot publish over the previously published versions'
)
) {
console.error('Ignoring already published error', platform, err)
}
} finally {
publishSema.release()
}
})
)
// Update optional dependencies versions
let nextPkg = JSON.parse(
await readFile(path.join(cwd, 'packages/next/package.json'))
......@@ -137,6 +203,12 @@ const cwd = process.cwd()
optionalDependencies['@next/swc-' + platform] = version
nextPkg.optionalDependencies = optionalDependencies
}
// Add next-cli optional dependencies
for (let platform of cliPlatforms) {
let optionalDependencies = nextPkg.optionalDependencies || {}
optionalDependencies['@next/cli-' + platform] = version
nextPkg.optionalDependencies = optionalDependencies
}
await writeFile(
path.join(path.join(cwd, 'packages/next/package.json')),
JSON.stringify(nextPkg, null, 2)
......
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