Commit 4b79b55b authored by Luke Sandberg's avatar Luke Sandberg Committed by Jiachi Liu

[turbopack] Make it possible to synchronously access native bindings (#85787)

## Enable synchronous access to native bindings

## What?
This PR refactors the SWC bindings loading mechanism to support synchronous access to bindings after they've been loaded. It introduces new functions `installBindings()` and `getBindingsSync()` to properly manage the bindings lifecycle.

`installBindings` is called early by tools that rely on them.

There were of course  a few complexities:

* webpack loaders need to defensively install bindings to support being run by webpack
* the hacky `loadNativeSync` method used by `transformSync` remains required due to the jest-transformer API (i didn't see a clear initialization location).
* the `experimental.useWasmBinary` configuration is broken by design
   * if the config is `next.config.ts` when we load SWC to transpile it, but that requires the native bindings, so we might load native bindings even when you ask for wasm.  I added a warning message for this case and the workaround is to use the node native transpilation support.
   * this should probably be a command line flag if it is important
* we need to lazily load the `swc/index.ts` module since it transitively loads `react` which reads `NODE_ENV` and various next entrypoints might modify that.

## Why?

This makes it clearer that we are correctly applying the `useWasmBinary` option and can simplify some code paths that now don't need to be `async`.  This will be important in a future PR where i move some parts of issue formatting into rust/wasm.  Having those APIs be async will decrease their usability.
parent 14a45e4d
...@@ -903,5 +903,7 @@ ...@@ -903,5 +903,7 @@
"902": "Invalid handler fields configured for \"cacheHandlers\":\\n%s", "902": "Invalid handler fields configured for \"cacheHandlers\":\\n%s",
"903": "The file \"%s\" must export a function, either as a default export or as a named \"%s\" export.\\nThis function is what Next.js runs for every request handled by this %s.\\n\\nWhy this happens:\\n%s- The file exists but doesn't export a function.\\n- The export is not a function (e.g., an object or constant).\\n- There's a syntax error preventing the export from being recognized.\\n\\nTo fix it:\\n- Ensure this file has either a default or \"%s\" function export.\\n\\nLearn more: https://nextjs.org/docs/messages/middleware-to-proxy", "903": "The file \"%s\" must export a function, either as a default export or as a named \"%s\" export.\\nThis function is what Next.js runs for every request handled by this %s.\\n\\nWhy this happens:\\n%s- The file exists but doesn't export a function.\\n- The export is not a function (e.g., an object or constant).\\n- There's a syntax error preventing the export from being recognized.\\n\\nTo fix it:\\n- Ensure this file has either a default or \"%s\" function export.\\n\\nLearn more: https://nextjs.org/docs/messages/middleware-to-proxy",
"904": "The file \"%s\" must export a function, either as a default export or as a named \"%s\" export.", "904": "The file \"%s\" must export a function, either as a default export or as a named \"%s\" export.",
"905": "Page \"%s\" cannot use \\`export const unstable_prefetch = ...\\` without enabling \\`cacheComponents\\`." "905": "Page \"%s\" cannot use \\`export const unstable_prefetch = ...\\` without enabling \\`cacheComponents\\`.",
"906": "Bindings not loaded yet, but they are being loaded, did you forget to await?",
"907": "bindings not loaded yet. Either call `loadBindings` to wait for them to be available or ensure that `installBindings` has already been called."
} }
...@@ -17,6 +17,7 @@ import { ...@@ -17,6 +17,7 @@ import {
} from './util' } from './util'
import * as Log from '../../output/log' import * as Log from '../../output/log'
import { isReactCompilerRequired } from '../../swc' import { isReactCompilerRequired } from '../../swc'
import { installBindings } from '../../swc/install-bindings'
/** /**
* An internal (non-exported) type used by babel. * An internal (non-exported) type used by babel.
...@@ -570,6 +571,10 @@ export default async function getConfig( ...@@ -570,6 +571,10 @@ export default async function getConfig(
inputSourceMap?: SourceMap | undefined inputSourceMap?: SourceMap | undefined
} }
): Promise<ResolvedBabelConfig | null> { ): Promise<ResolvedBabelConfig | null> {
// Install bindings early so they are definitely available to the loader.
// When run by webpack in next this is already done with correct configuration so this is a no-op.
// In turbopack loaders are run in a subprocess so it may or may not be done.
await installBindings()
const cacheCharacteristics = await getCacheCharacteristics( const cacheCharacteristics = await getCacheCharacteristics(
loaderOptions, loaderOptions,
source, source,
......
...@@ -151,6 +151,7 @@ import type { NextError } from '../lib/is-error' ...@@ -151,6 +151,7 @@ import type { NextError } from '../lib/is-error'
import { isEdgeRuntime } from '../lib/is-edge-runtime' import { isEdgeRuntime } from '../lib/is-edge-runtime'
import { recursiveCopy } from '../lib/recursive-copy' import { recursiveCopy } from '../lib/recursive-copy'
import { lockfilePatchPromise, teardownTraceSubscriber } from './swc' import { lockfilePatchPromise, teardownTraceSubscriber } from './swc'
import { installBindings } from './swc/install-bindings'
import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex' import { getNamedRouteRegex } from '../shared/lib/router/utils/route-regex'
import { getFilesInDir } from '../lib/get-files-in-dir' import { getFilesInDir } from '../lib/get-files-in-dir'
import { eventSwcPlugins } from '../telemetry/events/swc-plugins' import { eventSwcPlugins } from '../telemetry/events/swc-plugins'
...@@ -964,6 +965,8 @@ export default async function build( ...@@ -964,6 +965,8 @@ export default async function build(
// Reading the config can modify environment variables that influence the bundler selection. // Reading the config can modify environment variables that influence the bundler selection.
bundler = finalizeBundlerFromConfig(bundler) bundler = finalizeBundlerFromConfig(bundler)
nextBuildSpan.setAttribute('bundler', getBundlerForTelemetry(bundler)) nextBuildSpan.setAttribute('bundler', getBundlerForTelemetry(bundler))
// Install the native bindings early so we can have synchronous access later.
await installBindings(config.experimental?.useWasmBinary)
process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || '' process.env.NEXT_DEPLOYMENT_ID = config.deploymentId || ''
NextBuildContext.config = config NextBuildContext.config = config
......
...@@ -5,7 +5,8 @@ import { PHASE_TEST } from '../../shared/lib/constants' ...@@ -5,7 +5,8 @@ import { PHASE_TEST } from '../../shared/lib/constants'
import loadJsConfig from '../load-jsconfig' import loadJsConfig from '../load-jsconfig'
import * as Log from '../output/log' import * as Log from '../output/log'
import { findPagesDir } from '../../lib/find-pages-dir' import { findPagesDir } from '../../lib/find-pages-dir'
import { loadBindings, lockfilePatchPromise } from '../swc' import { lockfilePatchPromise } from '../swc'
import { installBindings } from '../swc/install-bindings'
import type { JestTransformerConfig } from '../swc/jest-transformer' import type { JestTransformerConfig } from '../swc/jest-transformer'
import type { Config } from '@jest/types' import type { Config } from '@jest/types'
...@@ -96,7 +97,7 @@ export default function nextJest(options: { dir?: string } = {}) { ...@@ -96,7 +97,7 @@ export default function nextJest(options: { dir?: string } = {}) {
: customJestConfig) ?? {} : customJestConfig) ?? {}
// eagerly load swc bindings instead of waiting for transform calls // eagerly load swc bindings instead of waiting for transform calls
await loadBindings(nextConfig?.experimental?.useWasmBinary) await installBindings(nextConfig?.experimental?.useWasmBinary)
if (lockfilePatchPromise.cur) { if (lockfilePatchPromise.cur) {
await lockfilePatchPromise.cur await lockfilePatchPromise.cur
......
import fs from 'fs/promises' import fs from 'fs/promises'
import path from 'path' import path from 'path'
import { loadBindings } from './swc' import { getBindingsSync } from './swc'
// NOTE: this should be updated if this loader file is moved. // NOTE: this should be updated if this loader file is moved.
const PACKAGE_ROOT = path.normalize(path.join(__dirname, '../..')) const PACKAGE_ROOT = path.normalize(path.join(__dirname, '../..'))
...@@ -39,14 +39,12 @@ export async function loadEntrypoint( ...@@ -39,14 +39,12 @@ export async function loadEntrypoint(
injections?: Record<string, string>, injections?: Record<string, string>,
imports?: Record<string, string | null> imports?: Record<string, string | null>
): Promise<string> { ): Promise<string> {
let bindings = await loadBindings()
const templatePath = path.resolve( const templatePath = path.resolve(
path.join(TEMPLATES_ESM_FOLDER, `${entrypoint}.js`) path.join(TEMPLATES_ESM_FOLDER, `${entrypoint}.js`)
) )
let content = await fs.readFile(templatePath) let content = await fs.readFile(templatePath)
return bindings.expandNextJsTemplate( return getBindingsSync().expandNextJsTemplate(
content, content,
// Ensure that we use unix-style path separators for the import paths // Ensure that we use unix-style path separators for the import paths
path.join(TEMPLATE_SRC_FOLDER, `${entrypoint}.js`).replace(/\\/g, '/'), path.join(TEMPLATE_SRC_FOLDER, `${entrypoint}.js`).replace(/\\/g, '/'),
......
import { bold, cyan } from '../lib/picocolors' import { bold, cyan } from '../lib/picocolors'
import * as Log from './output/log' import * as Log from './output/log'
import { getBindingsSync } from './swc'
import type { Binding, Lockfile as NativeLockfile } from './swc/types' import type { Binding, Lockfile as NativeLockfile } from './swc/types'
...@@ -56,16 +57,11 @@ export class Lockfile { ...@@ -56,16 +57,11 @@ export class Lockfile {
* - If we fail to acquire the lock, we return `undefined`. * - If we fail to acquire the lock, we return `undefined`.
* - If we're on wasm, this always returns a dummy `Lockfile` object. * - If we're on wasm, this always returns a dummy `Lockfile` object.
*/ */
static async tryAcquire( static tryAcquire(
path: string, path: string,
unlockOnExit: boolean = true unlockOnExit: boolean = true
): Promise<Lockfile | undefined> { ): Lockfile | undefined {
const { loadBindings } = require('./swc') as typeof import('./swc') const bindings = getBindingsSync()
// Ideally we could provide a sync version of `tryAcquire`, but
// `loadBindings` is async. We're okay with skipping async-loaded wasm
// bindings and the internal `loadNative` function is synchronous, but it
// lacks some checks that `loadBindings` has.
const bindings = await loadBindings()
if (bindings.isWasm) { if (bindings.isWasm) {
Log.info( Log.info(
`Skipping creating a lockfile at ${cyan(path)} because we're using WASM bindings` `Skipping creating a lockfile at ${cyan(path)} because we're using WASM bindings`
...@@ -74,7 +70,7 @@ export class Lockfile { ...@@ -74,7 +70,7 @@ export class Lockfile {
} else { } else {
let nativeLockfile let nativeLockfile
try { try {
nativeLockfile = await bindings.lockfileTryAcquire(path) nativeLockfile = bindings.lockfileTryAcquireSync(path)
} catch (e) { } catch (e) {
// this happens if there's an IO error (e.g. `ENOENT`), which is // this happens if there's an IO error (e.g. `ENOENT`), which is
// different than if we just didn't acquire the lock // different than if we just didn't acquire the lock
...@@ -123,7 +119,7 @@ export class Lockfile { ...@@ -123,7 +119,7 @@ export class Lockfile {
const startMs = Date.now() const startMs = Date.now()
let lockfile let lockfile
while (Date.now() - startMs < MAX_RETRY_MS) { while (Date.now() - startMs < MAX_RETRY_MS) {
lockfile = await Lockfile.tryAcquire(path, unlockOnExit) lockfile = Lockfile.tryAcquire(path, unlockOnExit)
if (lockfile !== undefined) break if (lockfile !== undefined) break
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS)) await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS))
} }
......
...@@ -177,8 +177,9 @@ async function handleCJS({ ...@@ -177,8 +177,9 @@ async function handleCJS({
const nextConfigString = await readFile(nextConfigPath, 'utf8') const nextConfigString = await readFile(nextConfigPath, 'utf8')
// lazy require swc since it loads React before even setting NODE_ENV // lazy require swc since it loads React before even setting NODE_ENV
// resulting loading Development React on Production // resulting loading Development React on Production
const { transform } = require('../swc') as typeof import('../swc') const { loadBindings } = require('../swc') as typeof import('../swc')
const { code } = await transform(nextConfigString, swcOptions) const bindings = await loadBindings()
const { code } = await bindings.transform(nextConfigString, swcOptions)
// register require hook only if require exists // register require hook only if require exists
if (code.includes('require(')) { if (code.includes('require(')) {
...@@ -187,7 +188,21 @@ async function handleCJS({ ...@@ -187,7 +188,21 @@ async function handleCJS({
} }
// filename & extension don't matter here // filename & extension don't matter here
return requireFromString(code, resolve(cwd, 'next.config.compiled.js')) const config = requireFromString(
code,
resolve(cwd, 'next.config.compiled.js')
)
// At this point we have already loaded the bindings without this configuration setting due to the `transform` call above.
// Possibly we fell back to wasm in which case, it all works out but if not we need to warn
// that the configuration was ignored.
if (config?.experimental?.useWasmBinary && !bindings.isWasm) {
warn(
'Using a next.config.ts file is incompatible with `experimental.useWasmBinary` unless ' +
'`--experimental-next-config-strip-types` is also passed.\nSetting `useWasmBinary` to `false'
)
config.experimental.useWasmBinary = false
}
return config
} catch (error) { } catch (error) {
throw error throw error
} finally { } finally {
......
...@@ -160,21 +160,33 @@ let lastNativeBindingsLoadErrorCode: ...@@ -160,21 +160,33 @@ let lastNativeBindingsLoadErrorCode:
| 'unsupported_target' | 'unsupported_target'
| string | string
| undefined = undefined | undefined = undefined
// Used to cache calls to `loadBindings` // Used to cache racing calls to `loadBindings`
let pendingBindings: Promise<Binding> let pendingBindings: Promise<Binding> | undefined
// some things call `loadNative` directly instead of `loadBindings`... Cache calls to that // The cached loaded bindings
// separately. let loadedBindings: Binding | undefined = undefined
let nativeBindings: Binding
// can allow hacky sync access to bindings for loadBindingsSync
let wasmBindings: Binding
let downloadWasmPromise: any let downloadWasmPromise: any
let swcTraceFlushGuard: any let swcTraceFlushGuard: any
let downloadNativeBindingsPromise: Promise<void> | undefined = undefined let downloadNativeBindingsPromise: Promise<void> | undefined = undefined
export const lockfilePatchPromise: { cur?: Promise<void> } = {} export const lockfilePatchPromise: { cur?: Promise<void> } = {}
/** Access the native bindings which should already have been loaded via `installBindings. Throws if they are not available. */
export function getBindingsSync(): Binding {
if (!loadedBindings) {
if (pendingBindings) {
throw new Error(
'Bindings not loaded yet, but they are being loaded, did you forget to await?'
)
}
throw new Error(
'bindings not loaded yet. Either call `loadBindings` to wait for them to be available or ensure that `installBindings` has already been called.'
)
}
return loadedBindings
}
/** /**
* Attempts to load a native or wasm binding. * Loads the native or wasm binding.
* *
* By default, this first tries to use a native binding, falling back to a wasm binding if that * By default, this first tries to use a native binding, falling back to a wasm binding if that
* fails. * fails.
...@@ -184,6 +196,9 @@ export const lockfilePatchPromise: { cur?: Promise<void> } = {} ...@@ -184,6 +196,9 @@ export const lockfilePatchPromise: { cur?: Promise<void> } = {}
export async function loadBindings( export async function loadBindings(
useWasmBinary: boolean = false useWasmBinary: boolean = false
): Promise<Binding> { ): Promise<Binding> {
if (loadedBindings) {
return loadedBindings
}
if (pendingBindings) { if (pendingBindings) {
return pendingBindings return pendingBindings
} }
...@@ -281,7 +296,9 @@ export async function loadBindings( ...@@ -281,7 +296,9 @@ export async function loadBindings(
logLoadFailure(attempts, true) logLoadFailure(attempts, true)
}) })
return pendingBindings loadedBindings = await pendingBindings
pendingBindings = undefined
return loadedBindings
} }
async function tryLoadNativeWithFallback(attempts: Array<string>) { async function tryLoadNativeWithFallback(attempts: Array<string>) {
...@@ -363,12 +380,6 @@ function loadBindingsSync() { ...@@ -363,12 +380,6 @@ function loadBindingsSync() {
attempts = attempts.concat(a) attempts = attempts.concat(a)
} }
// HACK: we can leverage the wasm bindings if they are already loaded
// this may introduce race conditions
if (wasmBindings) {
return wasmBindings
}
logLoadFailure(attempts) logLoadFailure(attempts)
throw new Error('Failed to load bindings', { cause: attempts }) throw new Error('Failed to load bindings', { cause: attempts })
} }
...@@ -1182,7 +1193,7 @@ async function loadWasm(importPath = '') { ...@@ -1182,7 +1193,7 @@ async function loadWasm(importPath = '') {
// Note wasm binary does not support async intefaces yet, all async // Note wasm binary does not support async intefaces yet, all async
// interface coereces to sync interfaces. // interface coereces to sync interfaces.
wasmBindings = { let wasmBindings = {
css: { css: {
lightning: { lightning: {
transform: function (_options: any) { transform: function (_options: any) {
...@@ -1312,8 +1323,8 @@ async function loadWasm(importPath = '') { ...@@ -1312,8 +1323,8 @@ async function loadWasm(importPath = '') {
* wasm fallback. * wasm fallback.
*/ */
function loadNative(importPath?: string) { function loadNative(importPath?: string) {
if (nativeBindings) { if (loadedBindings) {
return nativeBindings return loadedBindings
} }
if (process.env.NEXT_TEST_WASM) { if (process.env.NEXT_TEST_WASM) {
...@@ -1379,7 +1390,7 @@ function loadNative(importPath?: string) { ...@@ -1379,7 +1390,7 @@ function loadNative(importPath?: string) {
} }
if (bindings) { if (bindings) {
nativeBindings = { loadedBindings = {
isWasm: false, isWasm: false,
transform(src: string, options: any) { transform(src: string, options: any) {
const isModule = const isModule =
...@@ -1518,7 +1529,7 @@ function loadNative(importPath?: string) { ...@@ -1518,7 +1529,7 @@ function loadNative(importPath?: string) {
return bindings.lockfileUnlockSync(lockfile) return bindings.lockfileUnlockSync(lockfile)
}, },
} }
return nativeBindings return loadedBindings
} }
throw attempts throw attempts
...@@ -1539,54 +1550,40 @@ function toBuffer(t: any) { ...@@ -1539,54 +1550,40 @@ function toBuffer(t: any) {
return Buffer.from(JSON.stringify(t)) return Buffer.from(JSON.stringify(t))
} }
export async function isWasm(): Promise<boolean> {
let bindings = await loadBindings()
return bindings.isWasm
}
export async function transform(src: string, options?: any): Promise<any> { export async function transform(src: string, options?: any): Promise<any> {
let bindings = await loadBindings() let bindings = getBindingsSync()
return bindings.transform(src, options) return bindings.transform(src, options)
} }
/** Synchronously transforms the source and loads the native bindings. */
export function transformSync(src: string, options?: any): any { export function transformSync(src: string, options?: any): any {
let bindings = loadBindingsSync() const bindings = loadBindingsSync()
return bindings.transformSync(src, options) return bindings.transformSync(src, options)
} }
export async function minify( export function minify(
src: string, src: string,
options: any options: any
): Promise<{ code: string; map: any }> { ): Promise<{ code: string; map: any }> {
let bindings = await loadBindings() const bindings = getBindingsSync()
return bindings.minify(src, options) return bindings.minify(src, options)
} }
export async function isReactCompilerRequired( export function isReactCompilerRequired(filename: string): Promise<boolean> {
filename: string const bindings = getBindingsSync()
): Promise<boolean> {
let bindings = await loadBindings()
return bindings.reactCompiler.isReactCompilerRequired(filename) return bindings.reactCompiler.isReactCompilerRequired(filename)
} }
export async function parse(src: string, options: any): Promise<any> { export async function parse(src: string, options: any): Promise<any> {
let bindings = await loadBindings() const bindings = getBindingsSync()
let parserOptions = getParserOptions(options) const parserOptions = getParserOptions(options)
return bindings const parsed = await bindings.parse(src, parserOptions)
.parse(src, parserOptions) return JSON.parse(parsed)
.then((astStr: any) => JSON.parse(astStr))
} }
export function getBinaryMetadata() { export function getBinaryMetadata() {
let bindings
try {
bindings = loadNative()
} catch (e) {
// Suppress exceptions, this fn allows to fail to load native bindings
}
return { return {
target: bindings?.getTargetTriple?.(), target: loadedBindings?.getTargetTriple?.(),
} }
} }
...@@ -1597,8 +1594,8 @@ export function getBinaryMetadata() { ...@@ -1597,8 +1594,8 @@ export function getBinaryMetadata() {
export function initCustomTraceSubscriber(traceFileName?: string) { export function initCustomTraceSubscriber(traceFileName?: string) {
if (!swcTraceFlushGuard) { if (!swcTraceFlushGuard) {
// Wasm binary doesn't support trace emission // Wasm binary doesn't support trace emission
let bindings = loadNative() swcTraceFlushGuard =
swcTraceFlushGuard = bindings.initCustomTraceSubscriber?.(traceFileName) getBindingsSync().initCustomTraceSubscriber?.(traceFileName)
} }
} }
...@@ -1625,9 +1622,8 @@ function once(fn: () => void): () => void { ...@@ -1625,9 +1622,8 @@ function once(fn: () => void): () => void {
*/ */
export const teardownTraceSubscriber = once(() => { export const teardownTraceSubscriber = once(() => {
try { try {
let bindings = loadNative()
if (swcTraceFlushGuard) { if (swcTraceFlushGuard) {
bindings.teardownTraceSubscriber?.(swcTraceFlushGuard) getBindingsSync().teardownTraceSubscriber?.(swcTraceFlushGuard)
} }
} catch (e) { } catch (e) {
// Suppress exceptions, this fn allows to fail to load native bindings // Suppress exceptions, this fn allows to fail to load native bindings
...@@ -1637,14 +1633,12 @@ export const teardownTraceSubscriber = once(() => { ...@@ -1637,14 +1633,12 @@ export const teardownTraceSubscriber = once(() => {
export async function getModuleNamedExports( export async function getModuleNamedExports(
resourcePath: string resourcePath: string
): Promise<string[]> { ): Promise<string[]> {
const bindings = await loadBindings() return getBindingsSync().rspack.getModuleNamedExports(resourcePath)
return bindings.rspack.getModuleNamedExports(resourcePath)
} }
export async function warnForEdgeRuntime( export async function warnForEdgeRuntime(
source: string, source: string,
isProduction: boolean isProduction: boolean
): Promise<NapiSourceDiagnostic[]> { ): Promise<NapiSourceDiagnostic[]> {
const bindings = await loadBindings() return getBindingsSync().rspack.warnForEdgeRuntime(source, isProduction)
return bindings.rspack.warnForEdgeRuntime(source, isProduction)
} }
/**
* This module provides a way to install SWC bindings without eagerly loading the entire swc/index module.
*
* The swc/index module can transitively load other modules (like webpack-config) that import React,
* and React's entry point checks process.env.NODE_ENV at require time to decide whether to load
* the development or production bundle. By deferring the require of swc/index until this function
* is called, we ensure NODE_ENV is set before React is loaded.
*/
/**
* Loads and caches the native bindings. This is idempotent and should be called early so bindings
* can be accessed synchronously later.
*
* @param useWasmBinary - Whether to use WASM bindings instead of native bindings
*/
export async function installBindings(
useWasmBinary: boolean = false
): Promise<void> {
// Lazy require to avoid loading swc/index (and transitively webpack-config/React)
// before NODE_ENV is set
const { loadBindings } = require('./index') as typeof import('./index')
await loadBindings(useWasmBinary)
}
...@@ -2,7 +2,8 @@ import path from 'path' ...@@ -2,7 +2,8 @@ import path from 'path'
import { validateTurboNextConfig } from '../../lib/turbopack-warning' import { validateTurboNextConfig } from '../../lib/turbopack-warning'
import { isFileSystemCacheEnabledForBuild } from '../../shared/lib/turbopack/utils' import { isFileSystemCacheEnabledForBuild } from '../../shared/lib/turbopack/utils'
import { NextBuildContext } from '../build-context' import { NextBuildContext } from '../build-context'
import { createDefineEnv, loadBindings } from '../swc' import { createDefineEnv, getBindingsSync } from '../swc'
import { installBindings } from '../swc/install-bindings'
import { import {
handleRouteType, handleRouteType,
rawEntrypointsToEntrypoints, rawEntrypointsToEntrypoints,
...@@ -42,7 +43,7 @@ export async function turbopackBuild(): Promise<{ ...@@ -42,7 +43,7 @@ export async function turbopackBuild(): Promise<{
const currentNodeJsVersion = process.versions.node const currentNodeJsVersion = process.versions.node
const startTime = process.hrtime() const startTime = process.hrtime()
const bindings = await loadBindings(config?.experimental?.useWasmBinary) const bindings = getBindingsSync() // our caller should have already loaded these
const dev = false const dev = false
const supportedBrowsers = getSupportedBrowsers(dir, dev) const supportedBrowsers = getSupportedBrowsers(dir, dev)
...@@ -221,15 +222,14 @@ export async function workerMain(workerData: { ...@@ -221,15 +222,14 @@ export async function workerMain(workerData: {
Object.assign(NextBuildContext, workerData.buildContext) Object.assign(NextBuildContext, workerData.buildContext)
/// load the config because it's not serializable /// load the config because it's not serializable
NextBuildContext.config = await loadConfig( const config = (NextBuildContext.config = await loadConfig(
PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_BUILD,
NextBuildContext.dir!, NextBuildContext.dir!,
{ {
debugPrerender: NextBuildContext.debugPrerender, debugPrerender: NextBuildContext.debugPrerender,
reactProductionProfiling: NextBuildContext.reactProductionProfiling, reactProductionProfiling: NextBuildContext.reactProductionProfiling,
} }
) ))
// Matches handling in build/index.ts // Matches handling in build/index.ts
// https://github.com/vercel/next.js/blob/84f347fc86f4efc4ec9f13615c215e4b9fb6f8f0/packages/next/src/build/index.ts#L815-L818 // https://github.com/vercel/next.js/blob/84f347fc86f4efc4ec9f13615c215e4b9fb6f8f0/packages/next/src/build/index.ts#L815-L818
// Ensures the `config.distDir` option is matched. // Ensures the `config.distDir` option is matched.
...@@ -242,6 +242,8 @@ export async function workerMain(workerData: { ...@@ -242,6 +242,8 @@ export async function workerMain(workerData: {
distDir: NextBuildContext.config.distDir, distDir: NextBuildContext.config.distDir,
}) })
setGlobal('telemetry', telemetry) setGlobal('telemetry', telemetry)
// Install bindings early so we can access synchronously later
await installBindings(config.experimental?.useWasmBinary)
const { const {
shutdownPromise: resultShutdownPromise, shutdownPromise: resultShutdownPromise,
......
...@@ -41,6 +41,7 @@ import type { UnwrapPromise } from '../../lib/coalesced-function' ...@@ -41,6 +41,7 @@ import type { UnwrapPromise } from '../../lib/coalesced-function'
import origDebug from 'next/dist/compiled/debug' import origDebug from 'next/dist/compiled/debug'
import { Telemetry } from '../../telemetry/storage' import { Telemetry } from '../../telemetry/storage'
import { durationToString, hrtimeToSeconds } from '../duration-to-string' import { durationToString, hrtimeToSeconds } from '../duration-to-string'
import { installBindings } from '../swc/install-bindings'
const debug = origDebug('next:build:webpack-build') const debug = origDebug('next:build:webpack-build')
...@@ -383,14 +384,15 @@ export async function workerMain(workerData: { ...@@ -383,14 +384,15 @@ export async function workerMain(workerData: {
resumePluginState(NextBuildContext.pluginState) resumePluginState(NextBuildContext.pluginState)
/// load the config because it's not serializable /// load the config because it's not serializable
NextBuildContext.config = await loadConfig( const config = (NextBuildContext.config = await loadConfig(
PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_BUILD,
NextBuildContext.dir!, NextBuildContext.dir!,
{ {
debugPrerender: NextBuildContext.debugPrerender, debugPrerender: NextBuildContext.debugPrerender,
reactProductionProfiling: NextBuildContext.reactProductionProfiling, reactProductionProfiling: NextBuildContext.reactProductionProfiling,
} }
) ))
await installBindings(config.experimental?.useWasmBinary)
NextBuildContext.nextBuildSpan = trace( NextBuildContext.nextBuildSpan = trace(
`worker-main-${workerData.compilerName}` `worker-main-${workerData.compilerName}`
) )
......
...@@ -61,7 +61,6 @@ import loadJsConfig, { ...@@ -61,7 +61,6 @@ import loadJsConfig, {
type JsConfig, type JsConfig,
type ResolvedBaseUrl, type ResolvedBaseUrl,
} from './load-jsconfig' } from './load-jsconfig'
import { loadBindings } from './swc'
import { SubresourceIntegrityPlugin } from './webpack/plugins/subresource-integrity-plugin' import { SubresourceIntegrityPlugin } from './webpack/plugins/subresource-integrity-plugin'
import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plugin' import { NextFontManifestPlugin } from './webpack/plugins/next-font-manifest-plugin'
import { getSupportedBrowsers } from './utils' import { getSupportedBrowsers } from './utils'
...@@ -422,11 +421,6 @@ export default async function getBaseWebpackConfig( ...@@ -422,11 +421,6 @@ export default async function getBaseWebpackConfig(
loggedSwcDisabled = true loggedSwcDisabled = true
} }
// eagerly load swc bindings instead of waiting for transform calls
if (!babelConfigFile && isClient) {
await loadBindings(config.experimental.useWasmBinary)
}
// since `pages` doesn't always bundle by default we need to // since `pages` doesn't always bundle by default we need to
// auto-include optimizePackageImports in transpilePackages // auto-include optimizePackageImports in transpilePackages
const finalTranspilePackages: string[] = ( const finalTranspilePackages: string[] = (
......
...@@ -19,6 +19,8 @@ import { ...@@ -19,6 +19,8 @@ import {
} from '../../css-loader/src/utils' } from '../../css-loader/src/utils'
import { stringifyRequest } from '../../../stringify-request' import { stringifyRequest } from '../../../stringify-request'
import { ECacheKey } from './interface' import { ECacheKey } from './interface'
import { getBindingsSync } from '../../../../../build/swc'
import { installBindings } from '../../../../../build/swc/install-bindings'
const encoder = new TextEncoder() const encoder = new TextEncoder()
...@@ -266,6 +268,10 @@ export async function LightningCssLoader( ...@@ -266,6 +268,10 @@ export async function LightningCssLoader(
): Promise<void> { ): Promise<void> {
const done = this.async() const done = this.async()
const options = this.getOptions() const options = this.getOptions()
// Install bindings early so they are definitely available to the loader.
// When run by webpack in next this is already done with correct configuration so this is a no-op.
// In turbopack loaders are run in a subprocess so it may or may not be done.
await installBindings()
const { implementation, targets: userTargets, ...opts } = options const { implementation, targets: userTargets, ...opts } = options
options.modules ??= {} options.modules ??= {}
...@@ -305,12 +311,8 @@ export async function LightningCssLoader( ...@@ -305,12 +311,8 @@ export async function LightningCssLoader(
), ),
}) })
} }
const { loadBindings } =
require('../../../../../build/swc') as typeof import('../../../../../build/swc')
const transform = const transform =
implementation?.transformCss ?? implementation?.transformCss ?? getBindingsSync().css.lightning.transform
(await loadBindings()).css.lightning.transform
const replacedUrls = new Map<number, string>() const replacedUrls = new Map<number, string>()
const icssReplacedUrls = new Map<number, string>() const icssReplacedUrls = new Map<number, string>()
......
...@@ -7,6 +7,7 @@ import { ECacheKey } from './interface' ...@@ -7,6 +7,7 @@ import { ECacheKey } from './interface'
import type { Compilation, Compiler } from 'webpack' import type { Compilation, Compiler } from 'webpack'
import { getTargets } from './utils' import { getTargets } from './utils'
import { Buffer } from 'buffer' import { Buffer } from 'buffer'
import { getBindingsSync } from '../../../../../build/swc'
const PLUGIN_NAME = 'lightning-css-minify' const PLUGIN_NAME = 'lightning-css-minify'
const CSS_FILE_REG = /\.css(?:\?.*)?$/i const CSS_FILE_REG = /\.css(?:\?.*)?$/i
...@@ -66,9 +67,7 @@ export class LightningCssMinifyPlugin { ...@@ -66,9 +67,7 @@ export class LightningCssMinifyPlugin {
} = compilation.compiler } = compilation.compiler
if (!this.transform) { if (!this.transform) {
const { loadBindings } = this.transform = getBindingsSync().css.lightning.transform
require('../../../../../build/swc') as typeof import('../../../../../build/swc')
this.transform = (await loadBindings()).css.lightning.transform
} }
const sourcemap = const sourcemap =
......
...@@ -38,7 +38,9 @@ import { PARALLEL_ROUTE_DEFAULT_PATH } from '../../../../client/components/built ...@@ -38,7 +38,9 @@ import { PARALLEL_ROUTE_DEFAULT_PATH } from '../../../../client/components/built
import type { Compilation } from 'webpack' import type { Compilation } from 'webpack'
import { createAppRouteCode } from './create-app-route-code' import { createAppRouteCode } from './create-app-route-code'
import { MissingDefaultParallelRouteError } from '../../../../shared/lib/errors/missing-default-parallel-route-error' import { MissingDefaultParallelRouteError } from '../../../../shared/lib/errors/missing-default-parallel-route-error'
import { normalizePathSep } from '../../../../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../../../../shared/lib/page-path/normalize-path-sep'
import { installBindings } from '../../../swc/install-bindings'
export type AppLoaderOptions = { export type AppLoaderOptions = {
name: string name: string
...@@ -636,6 +638,11 @@ const filesInDirMapMap: WeakMap< ...@@ -636,6 +638,11 @@ const filesInDirMapMap: WeakMap<
Map<string, Promise<Set<string>>> Map<string, Promise<Set<string>>>
> = new WeakMap() > = new WeakMap()
const nextAppLoader: AppLoader = async function nextAppLoader() { const nextAppLoader: AppLoader = async function nextAppLoader() {
// install native bindings early so they are always available.
// When run by webpack, next will have already done this, so this will be fast,
// but if run by turbopack in a subprocess it is required. In that case we cannot pass the
// `useWasmBinary` flag, but that is ok since turbopack doesn't currently support wasm.
await installBindings()
const loaderOptions = this.getOptions() const loaderOptions = this.getOptions()
const { const {
name, name,
......
...@@ -88,6 +88,7 @@ import type webpack from 'webpack' ...@@ -88,6 +88,7 @@ import type webpack from 'webpack'
import path from 'path' import path from 'path'
import { transform } from '../../swc' import { transform } from '../../swc'
import { installBindings } from '../../swc/install-bindings'
// This is a in-memory cache for the mapping of barrel exports. This only applies // This is a in-memory cache for the mapping of barrel exports. This only applies
// to the packages that we optimize. It will never change (e.g. upgrading packages) // to the packages that we optimize. It will never change (e.g. upgrading packages)
...@@ -251,6 +252,10 @@ const NextBarrelLoader = async function ( ...@@ -251,6 +252,10 @@ const NextBarrelLoader = async function (
) { ) {
this.async() this.async()
this.cacheable(true) this.cacheable(true)
// Install bindings early so they are definitely available.
// When run by webpack in next this is already done with correct configuration so this is a no-op.
// In turbopack loaders are run in a subprocess so it may or may not be done.
await installBindings()
const { names, swcCacheDir } = this.getOptions() const { names, swcCacheDir } = this.getOptions()
......
...@@ -16,6 +16,7 @@ import { WEBPACK_RESOURCE_QUERIES } from '../../../lib/constants' ...@@ -16,6 +16,7 @@ import { WEBPACK_RESOURCE_QUERIES } from '../../../lib/constants'
import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep' import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'
import type { PageExtensions } from '../../page-extensions-type' import type { PageExtensions } from '../../page-extensions-type'
import { getLoaderModuleNamedExports } from './utils' import { getLoaderModuleNamedExports } from './utils'
import { installBindings } from '../../swc/install-bindings'
interface Options { interface Options {
segment: string segment: string
...@@ -30,6 +31,10 @@ async function nextMetadataImageLoader( ...@@ -30,6 +31,10 @@ async function nextMetadataImageLoader(
this: webpack.LoaderContext<Options>, this: webpack.LoaderContext<Options>,
content: Buffer content: Buffer
) { ) {
// Install bindings early so they are definitely available to the loader.
// When run by webpack in next this is already done with correct configuration so this is a no-op.
// In turbopack loaders are run in a subprocess so it may or may not be done.
await installBindings()
const options: Options = this.getOptions() const options: Options = this.getOptions()
const { type, segment, pageExtensions, basePath } = options const { type, segment, pageExtensions, basePath } = options
const { resourcePath, rootContext: context } = this const { resourcePath, rootContext: context } = this
......
...@@ -3,6 +3,7 @@ import fs from 'fs' ...@@ -3,6 +3,7 @@ import fs from 'fs'
import path from 'path' import path from 'path'
import { imageExtMimeTypeMap } from '../../../lib/mime-type' import { imageExtMimeTypeMap } from '../../../lib/mime-type'
import { getLoaderModuleNamedExports } from './utils' import { getLoaderModuleNamedExports } from './utils'
import { installBindings } from '../../swc/install-bindings'
function errorOnBadHandler(resourcePath: string) { function errorOnBadHandler(resourcePath: string) {
return ` return `
...@@ -373,6 +374,10 @@ async function getSitemapRouteCode( ...@@ -373,6 +374,10 @@ async function getSitemapRouteCode(
// TODO-METADATA: improve the cache control strategy // TODO-METADATA: improve the cache control strategy
const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction<MetadataRouteLoaderOptions> = const nextMetadataRouterLoader: webpack.LoaderDefinitionFunction<MetadataRouteLoaderOptions> =
async function () { async function () {
// Install bindings early so they are definitely available to the loader.
// When run by webpack in next this is already done with correct configuration so this is a no-op.
// In turbopack loaders are run in a subprocess so it may or may not be done.
await installBindings()
const { isDynamicRouteExtension, filePath } = this.getOptions() const { isDynamicRouteExtension, filePath } = this.getOptions()
const { name: fileBaseName } = getFilenameAndExtension(filePath) const { name: fileBaseName } = getFilenameAndExtension(filePath)
this.addDependency(filePath) this.addDependency(filePath)
......
...@@ -28,7 +28,8 @@ DEALINGS IN THE SOFTWARE. ...@@ -28,7 +28,8 @@ DEALINGS IN THE SOFTWARE.
import type { NextConfig } from '../../../types' import type { NextConfig } from '../../../types'
import { type WebpackLayerName, WEBPACK_LAYERS } from '../../../lib/constants' import { type WebpackLayerName, WEBPACK_LAYERS } from '../../../lib/constants'
import { isWasm, transform } from '../../swc' import { getBindingsSync, transform } from '../../swc'
import { installBindings } from '../../swc/install-bindings'
import { getLoaderSWCOptions } from '../../swc/options' import { getLoaderSWCOptions } from '../../swc/options'
import path, { isAbsolute } from 'path' import path, { isAbsolute } from 'path'
import { babelIncludeRegexes } from '../../webpack-config' import { babelIncludeRegexes } from '../../webpack-config'
...@@ -251,7 +252,7 @@ export function pitch(this: any) { ...@@ -251,7 +252,7 @@ export function pitch(this: any) {
!EXCLUDED_PATHS.test(this.resourcePath) && !EXCLUDED_PATHS.test(this.resourcePath) &&
this.loaders.length - 1 === this.loaderIndex && this.loaders.length - 1 === this.loaderIndex &&
isAbsolute(this.resourcePath) && isAbsolute(this.resourcePath) &&
!(await isWasm()) !getBindingsSync().isWasm
) { ) {
this.addDependency(this.resourcePath) this.addDependency(this.resourcePath)
return loaderTransform.call(this) return loaderTransform.call(this)
...@@ -268,13 +269,18 @@ export default function swcLoader( ...@@ -268,13 +269,18 @@ export default function swcLoader(
inputSourceMap: any inputSourceMap: any
) { ) {
const callback = this.async() const callback = this.async()
loaderTransform.call(this, inputSource, inputSourceMap).then( // Install bindings early so they are definitely available to the loader.
([transformedSource, outputSourceMap]: any) => { // When run by webpack in next this is already done with correct configuration so this is a no-op.
callback(null, transformedSource, outputSourceMap || inputSourceMap) // In turbopack loaders are run in a subprocess so it may or may not be done.
}, installBindings().then(() =>
(err: Error) => { loaderTransform.call(this, inputSource, inputSourceMap).then(
callback(err) ([transformedSource, outputSourceMap]: any) => {
} callback(null, transformedSource, outputSourceMap || inputSourceMap)
},
(err: Error) => {
callback(err)
}
)
) )
} }
......
...@@ -32,6 +32,7 @@ import { ...@@ -32,6 +32,7 @@ import {
} from '../server/lib/router-utils/route-types-utils' } from '../server/lib/router-utils/route-types-utils'
import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils' import { writeCacheLifeTypes } from '../server/lib/router-utils/cache-life-type-utils'
import { createValidFileMatcher } from '../server/lib/find-page-file' import { createValidFileMatcher } from '../server/lib/find-page-file'
import { installBindings } from '../build/swc/install-bindings'
export type NextTypegenOptions = { export type NextTypegenOptions = {
dir?: string dir?: string
...@@ -49,6 +50,7 @@ const nextTypegen = async ( ...@@ -49,6 +50,7 @@ const nextTypegen = async (
} }
const nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, baseDir) const nextConfig = await loadConfig(PHASE_PRODUCTION_BUILD, baseDir)
await installBindings(nextConfig.experimental?.useWasmBinary)
const distDir = join(baseDir, nextConfig.distDir) const distDir = join(baseDir, nextConfig.distDir)
const { pagesDir, appDir } = findPagesDir(baseDir) const { pagesDir, appDir } = findPagesDir(baseDir)
......
...@@ -1671,7 +1671,9 @@ export default async function loadConfig( ...@@ -1671,7 +1671,9 @@ export default async function loadConfig(
if (userConfig.experimental?.useLightningcss) { if (userConfig.experimental?.useLightningcss) {
const { loadBindings } = const { loadBindings } =
require('../build/swc') as typeof import('../build/swc') require('../build/swc') as typeof import('../build/swc')
const isLightningSupported = (await loadBindings())?.css?.lightning const isLightningSupported = (
await loadBindings(userConfig.experimental?.useWasmBinary)
)?.css?.lightning
if (!isLightningSupported) { if (!isLightningSupported) {
curLog.warn( curLog.warn(
......
...@@ -24,7 +24,7 @@ import type { ...@@ -24,7 +24,7 @@ import type {
Project, Project,
Entrypoints, Entrypoints,
} from '../../build/swc/types' } from '../../build/swc/types'
import { createDefineEnv } from '../../build/swc' import { createDefineEnv, getBindingsSync } from '../../build/swc'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import { BLOCKED_PAGES } from '../../shared/lib/constants' import { BLOCKED_PAGES } from '../../shared/lib/constants'
import { import {
...@@ -193,10 +193,7 @@ export async function createHotReloaderTurbopack( ...@@ -193,10 +193,7 @@ export async function createHotReloaderTurbopack(
const buildId = 'development' const buildId = 'development'
const { nextConfig, dir: projectPath } = opts const { nextConfig, dir: projectPath } = opts
const { loadBindings } = const bindings = getBindingsSync()
require('../../build/swc') as typeof import('../../build/swc')
let bindings = await loadBindings()
// For the debugging purpose, check if createNext or equivalent next instance setup in test cases // For the debugging purpose, check if createNext or equivalent next instance setup in test cases
// works correctly. Normally `run-test` hides output so only will be visible when `--debug` flag is used. // works correctly. Normally `run-test` hides output so only will be visible when `--debug` flag is used.
......
...@@ -8,6 +8,7 @@ import type { PropagateToWorkersField } from './types' ...@@ -8,6 +8,7 @@ import type { PropagateToWorkersField } from './types'
import type { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types' import type { NextJsHotReloaderInterface } from '../../dev/hot-reloader-types'
import { createDefineEnv } from '../../../build/swc' import { createDefineEnv } from '../../../build/swc'
import { installBindings } from '../../../build/swc/install-bindings'
import fs from 'fs' import fs from 'fs'
import url from 'url' import url from 'url'
import path from 'path' import path from 'path'
...@@ -1280,7 +1281,7 @@ export async function setupDevBundler(opts: SetupOpts) { ...@@ -1280,7 +1281,7 @@ export async function setupDevBundler(opts: SetupOpts) {
const isSrcDir = path const isSrcDir = path
.relative(opts.dir, opts.pagesDir || opts.appDir || '') .relative(opts.dir, opts.pagesDir || opts.appDir || '')
.startsWith('src') .startsWith('src')
await installBindings(opts.nextConfig.experimental?.useWasmBinary)
const result = await startWatcher({ const result = await startWatcher({
...opts, ...opts,
isSrcDir, isSrcDir,
......
/* eslint-env jest */ /* eslint-env jest */
import { transform } from 'next/dist/build/swc' import { transform } from 'next/dist/build/swc'
import { installBindings } from 'next/dist/build/swc/install-bindings'
import path from 'path' import path from 'path'
import fsp from 'fs/promises' import fsp from 'fs/promises'
...@@ -11,6 +12,9 @@ const swc = async (code) => { ...@@ -11,6 +12,9 @@ const swc = async (code) => {
const trim = (s) => s.join('\n').trim().replace(/^\s+/gm, '') const trim = (s) => s.join('\n').trim().replace(/^\s+/gm, '')
describe('next/swc', () => { describe('next/swc', () => {
beforeAll(async () => {
await installBindings()
})
describe('hook_optimizer', () => { describe('hook_optimizer', () => {
it('should leave alone array destructuring of hooks', async () => { it('should leave alone array destructuring of hooks', async () => {
const output = await swc( const output = await swc(
......
import { getPagesPageStaticInfo } from 'next/dist/build/analysis/get-page-static-info' import { getPagesPageStaticInfo } from 'next/dist/build/analysis/get-page-static-info'
import { installBindings } from 'next/dist/build/swc/install-bindings'
import { PAGE_TYPES } from 'next/dist/lib/page-types' import { PAGE_TYPES } from 'next/dist/lib/page-types'
import { join } from 'path' import { join } from 'path'
...@@ -9,6 +10,9 @@ function createNextConfig() { ...@@ -9,6 +10,9 @@ function createNextConfig() {
} }
describe('parse page static info', () => { describe('parse page static info', () => {
beforeAll(async () => {
await installBindings()
})
it('should parse nodejs runtime correctly', async () => { it('should parse nodejs runtime correctly', async () => {
const { runtime, getServerSideProps, getStaticProps } = const { runtime, getServerSideProps, getStaticProps } =
await getPagesPageStaticInfo({ await getPagesPageStaticInfo({
......
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