Commit c6a4c5cb 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 f1033c39
...@@ -430,6 +430,18 @@ jobs: ...@@ -430,6 +430,18 @@ jobs:
name: next-swc-binaries-${{ matrix.settings.target }} name: next-swc-binaries-${{ matrix.settings.target }}
path: packages/next-swc/native/next-swc.*.node 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 - name: Upload turbo summary artifact
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
with: with:
...@@ -539,6 +551,28 @@ jobs: ...@@ -539,6 +551,28 @@ jobs:
merge-multiple: true merge-multiple: true
path: crates/wasm 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 - name: Create tarballs
# github.event.after is available on push and pull_request#synchronize events. # github.event.after is available on push and pull_request#synchronize events.
# For workflow_dispatch events, github.sha is the head commit. # For workflow_dispatch events, github.sha is the head commit.
...@@ -604,6 +638,28 @@ jobs: ...@@ -604,6 +638,28 @@ jobs:
merge-multiple: true merge-multiple: true
path: crates/wasm 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: 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: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
- run: ./scripts/publish-native.js - run: ./scripts/publish-native.js
......
...@@ -66,3 +66,7 @@ test-timings.json ...@@ -66,3 +66,7 @@ test-timings.json
# Storybook # Storybook
*storybook.log *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-*
...@@ -4332,6 +4332,10 @@ dependencies = [ ...@@ -4332,6 +4332,10 @@ dependencies = [
"turbopack-trace-utils", "turbopack-trace-utils",
] ]
[[package]]
name = "next-cli"
version = "0.1.0"
[[package]] [[package]]
name = "next-core" name = "next-core"
version = "0.1.0" version = "0.1.0"
......
...@@ -8,6 +8,7 @@ members = [ ...@@ -8,6 +8,7 @@ members = [
"crates/next-api", "crates/next-api",
"crates/next-build-test", "crates/next-build-test",
"crates/next-build", "crates/next-build",
"crates/next-cli",
"crates/next-core", "crates/next-core",
"crates/next-custom-transforms", "crates/next-custom-transforms",
"crates/next-taskless", "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
//!
//! Ultra-fast native binary that handles the restart loop for Next.js CLI.
//! Exit code 77 signals "restart needed" (e.g., config change during dev).
//!
//! This eliminates ~70ms of Node.js parent process bootstrap overhead.
use std::{
env,
process::{Command, exit},
};
/// Exit code used by Next.js to signal restart needed
const EXIT_CODE_RESTART: i32 = 77;
fn main() {
let args: Vec<String> = env::args().collect();
// Get the directory where this binary lives (packages/next/bin/)
let bin_dir = env::current_exe()
.expect("failed to get executable path")
.parent()
.expect("failed to get parent directory")
.to_path_buf();
// Script is at ../dist/bin/next relative to bin/
let script = bin_dir.parent().unwrap().join("dist/bin/next");
// Build NODE_OPTIONS for dev command
let node_options = if args.get(1).map(|s| s.as_str()) == Some("dev") {
build_dev_node_options(&args)
} else {
env::var("NODE_OPTIONS").unwrap_or_default()
};
// Restart loop: exit code 77 means "restart me"
loop {
let mut cmd = Command::new("node");
cmd.arg(&script).args(&args[1..]);
if !node_options.is_empty() {
cmd.env("NODE_OPTIONS", &node_options);
}
// macOS workaround: limit file watchers to avoid slow close
// https://github.com/nodejs/node/issues/29949
#[cfg(target_os = "macos")]
if args.get(1).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 != EXIT_CODE_RESTART {
exit(code);
}
}
}
/// Build NODE_OPTIONS for dev command
/// - Enables source maps (unless --disable-source-maps)
/// - Handles --inspect flag
fn build_dev_node_options(args: &[String]) -> String {
let mut options: Vec<String> = Vec::new();
// Start with existing NODE_OPTIONS
if let Ok(existing) = env::var("NODE_OPTIONS") {
options.push(existing);
}
// Check for --disable-source-maps flag
let disable_source_maps = args.iter().any(|a| a == "--disable-source-maps");
// Enable source maps by default unless disabled
if !disable_source_maps {
let has_source_maps = options.iter().any(|o| o.contains("enable-source-maps"));
if !has_source_maps {
options.push("--enable-source-maps".to_string());
}
}
// Handle --inspect flag
for (i, arg) in args.iter().enumerate() {
if arg == "--inspect" {
// Check if next arg is a port/address (doesn't start with -)
let addr = args.get(i + 1).filter(|a| !a.starts_with('-'));
if let Some(addr) = addr {
options.push(format!("--inspect={}", addr));
} else {
options.push("--inspect".to_string());
}
break;
} else if arg.starts_with("--inspect=") {
options.push(arg.clone());
break;
}
}
options.join(" ")
}
#!/bin/sh
DIR="$(dirname "$0")"
# Development: local binary
[ -x "$DIR/next-native" ] && exec "$DIR/next-native" "$@"
# Production: check installed @next/cli-* package (npm installs only the matching one)
for pkg in "$DIR"/../node_modules/@next/cli-*/next; do
[ -x "$pkg" ] && exec "$pkg" "$@"
done
# Fallback: Node.js
exec node "$DIR/../dist/bin/next" "$@"
@echo off
setlocal
set "DIR=%~dp0"
:: Try native binary from @next/cli-* package
if exist "%DIR%..\node_modules\@next\cli-win32-x64-msvc\next.exe" (
"%DIR%..\node_modules\@next\cli-win32-x64-msvc\next.exe" %*
exit /b %errorlevel%
)
if exist "%DIR%..\node_modules\@next\cli-win32-arm64-msvc\next.exe" (
"%DIR%..\node_modules\@next\cli-win32-arm64-msvc\next.exe" %*
exit /b %errorlevel%
)
:: Try local native binary (for development)
if exist "%DIR%next-native.exe" (
"%DIR%next-native.exe" %*
exit /b %errorlevel%
)
:: Fall back to Node.js entry point
node "%DIR%..\dist\bin\next" %*
...@@ -29,6 +29,8 @@ const sharedExternals = [ ...@@ -29,6 +29,8 @@ const sharedExternals = [
'next/dist/compiled/@opentelemetry/api', 'next/dist/compiled/@opentelemetry/api',
'next/dist/compiled/@mswjs/interceptors/ClientRequest', 'next/dist/compiled/@mswjs/interceptors/ClientRequest',
'next/dist/compiled/ws', 'next/dist/compiled/ws',
'next/dist/compiled/tar',
'next/dist/compiled/@modelcontextprotocol/sdk/server/mcp',
] ]
// Dev server specific externals // Dev server specific externals
...@@ -51,10 +53,14 @@ const externalPatterns = [ ...@@ -51,10 +53,14 @@ const externalPatterns = [
/hot-reloader-turbopack/, /hot-reloader-turbopack/,
/hot-reloader-webpack/, /hot-reloader-webpack/,
/hot-reloader-rspack/, /hot-reloader-rspack/,
// MCP server - only needed when clients connect
/\/mcp\//,
// Turbopack internals - native bindings // Turbopack internals - native bindings
/turbopack/, /turbopack/,
// SWC bindings - native (matches ./swc, build/swc, etc.) // SWC bindings - native (matches ./swc, build/swc, etc.)
/\/swc($|\/)/, /\/swc($|\/)/,
// Download SWC - only needed for fallback, loads tar
/download-swc/,
// Sandbox - manipulates require.cache // Sandbox - manipulates require.cache
/web\/sandbox/, /web\/sandbox/,
// Require hook - uses require.resolve with user-facing packages // Require hook - uses require.resolve with user-facing packages
......
...@@ -72,10 +72,11 @@ ...@@ -72,10 +72,11 @@
"experimental/testmode/playwright/msw.js", "experimental/testmode/playwright/msw.js",
"experimental/testmode/playwright/msw.d.ts", "experimental/testmode/playwright/msw.d.ts",
"experimental/testmode/proxy.js", "experimental/testmode/proxy.js",
"experimental/testmode/proxy.d.ts" "experimental/testmode/proxy.d.ts",
"bin"
], ],
"bin": { "bin": {
"next": "./dist/bin/next" "next": "./bin/next"
}, },
"scripts": { "scripts": {
"dev": "cross-env NEXT_SERVER_NO_MANGLE=1 taskr", "dev": "cross-env NEXT_SERVER_NO_MANGLE=1 taskr",
......
...@@ -6,7 +6,8 @@ import * as Log from '../output/log' ...@@ -6,7 +6,8 @@ import * as Log from '../output/log'
import { getParserOptions } from './options' import { getParserOptions } from './options'
import { eventSwcLoadFailure } from '../../telemetry/events/swc-load-failure' import { eventSwcLoadFailure } from '../../telemetry/events/swc-load-failure'
import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile' import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile'
import { downloadNativeNextSwc, downloadWasmSwc } from '../../lib/download-swc' // Lazy loaded - only needed for fallback download
// import { downloadNativeNextSwc, downloadWasmSwc } from '../../lib/download-swc'
import type { import type {
NextConfigComplete, NextConfigComplete,
TurbopackLoaderBuiltinCondition, TurbopackLoaderBuiltinCondition,
...@@ -315,6 +316,8 @@ async function tryLoadNativeWithFallback(attempts: Array<string>) { ...@@ -315,6 +316,8 @@ async function tryLoadNativeWithFallback(attempts: Array<string>) {
) )
if (!downloadNativeBindingsPromise) { if (!downloadNativeBindingsPromise) {
const { downloadNativeNextSwc } =
require('../../lib/download-swc') as typeof import('../../lib/download-swc')
downloadNativeBindingsPromise = downloadNativeNextSwc( downloadNativeBindingsPromise = downloadNativeNextSwc(
nextVersion, nextVersion,
nativeBindingsDirectory, nativeBindingsDirectory,
...@@ -358,6 +361,8 @@ async function tryLoadWasmWithFallback( ...@@ -358,6 +361,8 @@ async function tryLoadWasmWithFallback(
'wasm' 'wasm'
) )
if (!downloadWasmPromise) { if (!downloadWasmPromise) {
const { downloadWasmSwc } =
require('../../lib/download-swc') as typeof import('../../lib/download-swc')
downloadWasmPromise = downloadWasmSwc(nextVersion, wasmDirectory) downloadWasmPromise = downloadWasmSwc(nextVersion, wasmDirectory)
} }
await downloadWasmPromise await downloadWasmPromise
......
This diff is collapsed.
...@@ -19,19 +19,23 @@ export type ServerInitResult = { ...@@ -19,19 +19,23 @@ export type ServerInitResult = {
let initializations: Record<string, Promise<ServerInitResult> | undefined> = {} let initializations: Record<string, Promise<ServerInitResult> | undefined> = {}
// Lazy loaded - only needed when edge functions are used
let sandboxContext: undefined | typeof import('../web/sandbox/context') let sandboxContext: undefined | typeof import('../web/sandbox/context')
if (process.env.NODE_ENV !== 'production') { function getSandboxContext() {
if (process.env.NODE_ENV !== 'production' && !sandboxContext) {
sandboxContext = sandboxContext =
require('../web/sandbox/context') as typeof import('../web/sandbox/context') require('../web/sandbox/context') as typeof import('../web/sandbox/context')
}
return sandboxContext
} }
export function clearAllModuleContexts() { export function clearAllModuleContexts() {
return sandboxContext?.clearAllModuleContexts() return getSandboxContext()?.clearAllModuleContexts()
} }
export function clearModuleContext(target: string) { export function clearModuleContext(target: string) {
return sandboxContext?.clearModuleContext(target) return getSandboxContext()?.clearModuleContext(target)
} }
export async function getServerField( export async function getServerField(
......
// Measure fork/spawn overhead - must be at the very top
const childStartTime = Date.now()
const forkTime = process.env.NEXT_PRIVATE_FORK_TIME
? childStartTime - parseInt(process.env.NEXT_PRIVATE_FORK_TIME, 10)
: null
// Start CPU profile if it wasn't already started. // Start CPU profile if it wasn't already started.
import './cpu-profile' import './cpu-profile'
import { getNetworkHost } from '../../lib/get-network-host' import { getNetworkHost } from '../../lib/get-network-host'
...@@ -23,7 +17,6 @@ import v8 from 'v8' ...@@ -23,7 +17,6 @@ import v8 from 'v8'
import path from 'path' import path from 'path'
import http from 'http' import http from 'http'
import https from 'https' import https from 'https'
import os from 'os'
import { exec } from 'child_process' import { exec } from 'child_process'
import Watchpack from 'next/dist/compiled/watchpack' import Watchpack from 'next/dist/compiled/watchpack'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
...@@ -46,12 +39,6 @@ import type { ConfiguredExperimentalFeature } from '../config' ...@@ -46,12 +39,6 @@ import type { ConfiguredExperimentalFeature } from '../config'
const debug = setupDebug('next:start-server') const debug = setupDebug('next:start-server')
let startServerSpan: Span | undefined let startServerSpan: Span | undefined
// Log fork/spawn timing
const moduleLoadTime = Date.now() - childStartTime
if (forkTime !== null) {
debug(`fork/spawn overhead: ${forkTime}ms, module load: ${moduleLoadTime}ms`)
}
/** /**
* Get the process ID (PID) of the process using the specified port * Get the process ID (PID) of the process using the specified port
*/ */
...@@ -534,35 +521,3 @@ export async function startServer( ...@@ -534,35 +521,3 @@ export async function startServer(
}) })
} }
} }
if (process.env.NEXT_PRIVATE_WORKER && process.send) {
// Read server options from env to eliminate IPC handshake latency
const workerOptions = process.env.NEXT_PRIVATE_WORKER_OPTIONS
? JSON.parse(process.env.NEXT_PRIVATE_WORKER_OPTIONS)
: null
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) { ...@@ -2408,6 +2408,47 @@ export async function bin(task, opts) {
.target('dist/bin', { mode: '0755' }) .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) { export async function cli(task, opts) {
await task await task
.source('src/cli/**/*.+(js|ts|tsx)') .source('src/cli/**/*.+(js|ts|tsx)')
......
...@@ -22,20 +22,28 @@ import fsp from 'fs/promises' ...@@ -22,20 +22,28 @@ import fsp from 'fs/promises'
) )
try { try {
// if installed swc package version matches monorepo version // if installed swc and cli package versions match monorepo version
// we can skip re-installing // we can skip re-installing
let hasSwc = false
let hasCli = false
for (const pkg of fs.readdirSync(path.join(cwd, 'node_modules', '@next'))) { for (const pkg of fs.readdirSync(path.join(cwd, 'node_modules', '@next'))) {
if ( const pkgVersion = JSON.parse(
pkg.startsWith('swc-') &&
JSON.parse(
fs.readFileSync( fs.readFileSync(
path.join(cwd, 'node_modules', '@next', pkg, 'package.json') path.join(cwd, 'node_modules', '@next', pkg, 'package.json')
) )
).version === nextVersion ).version
) { if (pkg.startsWith('swc-') && pkgVersion === nextVersion) {
console.log(`@next/${pkg}@${nextVersion} already installed, skipping`) hasSwc = true
return }
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 {} } catch {}
...@@ -54,6 +62,14 @@ import fsp from 'fs/promises' ...@@ -54,6 +62,14 @@ import fsp from 'fs/promises'
'@next/swc-linux-x64-musl': nextVersion, '@next/swc-linux-x64-musl': nextVersion,
'@next/swc-win32-arm64-msvc': nextVersion, '@next/swc-win32-arm64-msvc': nextVersion,
'@next/swc-win32-x64-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, packageManager,
} }
...@@ -86,6 +102,6 @@ import fsp from 'fs/promises' ...@@ -86,6 +102,6 @@ import fsp from 'fs/promises'
console.log('Installed the following binary packages:', pkgs) console.log('Installed the following binary packages:', pkgs)
} catch (e) { } catch (e) {
console.error(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() ...@@ -19,6 +19,12 @@ const cwd = process.cwd()
(name) => !name.startsWith('.') (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( await Promise.all(
platforms.map(async (platform) => { platforms.map(async (platform) => {
await publishSema.acquire() await publishSema.acquire()
...@@ -128,6 +134,66 @@ const cwd = process.cwd() ...@@ -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 // Update optional dependencies versions
let nextPkg = JSON.parse( let nextPkg = JSON.parse(
await readFile(path.join(cwd, 'packages/next/package.json')) await readFile(path.join(cwd, 'packages/next/package.json'))
...@@ -137,6 +203,12 @@ const cwd = process.cwd() ...@@ -137,6 +203,12 @@ const cwd = process.cwd()
optionalDependencies['@next/swc-' + platform] = version optionalDependencies['@next/swc-' + platform] = version
nextPkg.optionalDependencies = optionalDependencies 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( await writeFile(
path.join(path.join(cwd, 'packages/next/package.json')), path.join(path.join(cwd, 'packages/next/package.json')),
JSON.stringify(nextPkg, null, 2) 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