added fonts
This commit is contained in:
1 parent
4134e3a234
commit
142d2986b6
9079 files changed
+1498421
-2
No files matched your search
+433
@@ -0,0 +1,433 @@
|
||||
// Manual additions to make the generated types below work.
|
||||
|
||||
import type { TurbopackResult } from './types'
|
||||
|
||||
export type TurboTasks = { readonly __tag: unique symbol }
|
||||
export type ExternalEndpoint = { readonly __tag: unique symbol }
|
||||
export type NextTurboTasks = { readonly __tag: unique symbol }
|
||||
export type RefCell = { readonly __tag: unique symbol }
|
||||
export type NapiRouteHas = {
|
||||
type: string
|
||||
key?: string
|
||||
value?: string
|
||||
readonly __tag: unique symbol
|
||||
}
|
||||
|
||||
export function lightningCssTransform(args: object): Promise<unknown>
|
||||
export function lightningCssTransformStyleAttribute(
|
||||
args: object
|
||||
): Promise<unknown>
|
||||
|
||||
// GENERATED-TYPES-BELOW
|
||||
// DO NOT MANUALLY EDIT THESE TYPES
|
||||
// You can regenerate this file by running `pnpm swc-build-native` in the root of the repo.
|
||||
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
|
||||
/* auto-generated by NAPI-RS */
|
||||
|
||||
export class ExternalObject<T> {
|
||||
readonly '': {
|
||||
readonly '': unique symbol
|
||||
[K: symbol]: T
|
||||
}
|
||||
}
|
||||
export interface TransformOutput {
|
||||
code: string
|
||||
map?: string
|
||||
output?: string
|
||||
diagnostics: Array<string>
|
||||
}
|
||||
export declare function mdxCompile(
|
||||
value: string,
|
||||
option: Buffer,
|
||||
signal?: AbortSignal | undefined | null
|
||||
): Promise<unknown>
|
||||
export declare function mdxCompileSync(value: string, option: Buffer): string
|
||||
export declare function minify(
|
||||
input: Buffer,
|
||||
opts: Buffer,
|
||||
signal?: AbortSignal | undefined | null
|
||||
): Promise<TransformOutput>
|
||||
export declare function minifySync(input: Buffer, opts: Buffer): TransformOutput
|
||||
export interface NapiEndpointConfig {}
|
||||
export interface NapiServerPath {
|
||||
path: string
|
||||
contentHash: string
|
||||
}
|
||||
export interface NapiWrittenEndpoint {
|
||||
type: string
|
||||
entryPath?: string
|
||||
clientPaths: Array<string>
|
||||
serverPaths: Array<NapiServerPath>
|
||||
config: NapiEndpointConfig
|
||||
}
|
||||
export declare function endpointWriteToDisk(endpoint: {
|
||||
__napiType: 'Endpoint'
|
||||
}): Promise<TurbopackResult>
|
||||
export declare function endpointServerChangedSubscribe(
|
||||
endpoint: { __napiType: 'Endpoint' },
|
||||
issues: boolean,
|
||||
func: (...args: any[]) => any
|
||||
): { __napiType: 'RootTask' }
|
||||
export declare function endpointClientChangedSubscribe(
|
||||
endpoint: { __napiType: 'Endpoint' },
|
||||
func: (...args: any[]) => any
|
||||
): { __napiType: 'RootTask' }
|
||||
export interface NapiEnvVar {
|
||||
name: string
|
||||
value: string
|
||||
}
|
||||
export interface NapiDraftModeOptions {
|
||||
previewModeId: string
|
||||
previewModeEncryptionKey: string
|
||||
previewModeSigningKey: string
|
||||
}
|
||||
export interface NapiWatchOptions {
|
||||
/** Whether to watch the filesystem for file changes. */
|
||||
enable: boolean
|
||||
/**
|
||||
* Enable polling at a certain interval if the native file watching doesn't work (e.g.
|
||||
* docker).
|
||||
*/
|
||||
pollIntervalMs?: number
|
||||
}
|
||||
export interface NapiProjectOptions {
|
||||
/**
|
||||
* A root path from which all files must be nested under. Trying to access
|
||||
* a file outside this root will fail. Think of this as a chroot.
|
||||
*/
|
||||
rootPath: string
|
||||
/** A path inside the root_path which contains the app/pages directories. */
|
||||
projectPath: string
|
||||
/**
|
||||
* next.config's distDir. Project initialization occurs eariler than
|
||||
* deserializing next.config, so passing it as separate option.
|
||||
*/
|
||||
distDir: string
|
||||
/** Filesystem watcher options. */
|
||||
watch: NapiWatchOptions
|
||||
/** The contents of next.config.js, serialized to JSON. */
|
||||
nextConfig: string
|
||||
/** The contents of ts/config read by load-jsconfig, serialized to JSON. */
|
||||
jsConfig: string
|
||||
/** A map of environment variables to use when compiling code. */
|
||||
env: Array<NapiEnvVar>
|
||||
/**
|
||||
* A map of environment variables which should get injected at compile
|
||||
* time.
|
||||
*/
|
||||
defineEnv: NapiDefineEnv
|
||||
/** The mode in which Next.js is running. */
|
||||
dev: boolean
|
||||
/** The server actions encryption key. */
|
||||
encryptionKey: string
|
||||
/** The build id. */
|
||||
buildId: string
|
||||
/** Options for draft mode. */
|
||||
previewProps: NapiDraftModeOptions
|
||||
/** The browserslist query to use for targeting browsers. */
|
||||
browserslistQuery: string
|
||||
/**
|
||||
* When the code is minified, this opts out of the default mangling of
|
||||
* local names for variables, functions etc., which can be useful for
|
||||
* debugging/profiling purposes.
|
||||
*/
|
||||
noMangling: boolean
|
||||
}
|
||||
/** [NapiProjectOptions] with all fields optional. */
|
||||
export interface NapiPartialProjectOptions {
|
||||
/**
|
||||
* A root path from which all files must be nested under. Trying to access
|
||||
* a file outside this root will fail. Think of this as a chroot.
|
||||
*/
|
||||
rootPath?: string
|
||||
/** A path inside the root_path which contains the app/pages directories. */
|
||||
projectPath?: string
|
||||
/**
|
||||
* next.config's distDir. Project initialization occurs eariler than
|
||||
* deserializing next.config, so passing it as separate option.
|
||||
*/
|
||||
distDir?: string | undefined | null
|
||||
/** Filesystem watcher options. */
|
||||
watch?: NapiWatchOptions
|
||||
/** The contents of next.config.js, serialized to JSON. */
|
||||
nextConfig?: string
|
||||
/** The contents of ts/config read by load-jsconfig, serialized to JSON. */
|
||||
jsConfig?: string
|
||||
/** A map of environment variables to use when compiling code. */
|
||||
env?: Array<NapiEnvVar>
|
||||
/**
|
||||
* A map of environment variables which should get injected at compile
|
||||
* time.
|
||||
*/
|
||||
defineEnv?: NapiDefineEnv
|
||||
/** The mode in which Next.js is running. */
|
||||
dev?: boolean
|
||||
/** The server actions encryption key. */
|
||||
encryptionKey?: string
|
||||
/** The build id. */
|
||||
buildId?: string
|
||||
/** Options for draft mode. */
|
||||
previewProps?: NapiDraftModeOptions
|
||||
/** The browserslist query to use for targeting browsers. */
|
||||
browserslistQuery?: string
|
||||
/**
|
||||
* When the code is minified, this opts out of the default mangling of
|
||||
* local names for variables, functions etc., which can be useful for
|
||||
* debugging/profiling purposes.
|
||||
*/
|
||||
noMangling?: boolean
|
||||
}
|
||||
export interface NapiDefineEnv {
|
||||
client: Array<NapiEnvVar>
|
||||
edge: Array<NapiEnvVar>
|
||||
nodejs: Array<NapiEnvVar>
|
||||
}
|
||||
export interface NapiTurboEngineOptions {
|
||||
/** Use the new backend with persistent caching enabled. */
|
||||
persistentCaching?: boolean
|
||||
/** An upper bound of memory that turbopack will attempt to stay under. */
|
||||
memoryLimit?: number
|
||||
/** Track dependencies between tasks. If false, any change during build will error. */
|
||||
dependencyTracking?: boolean
|
||||
}
|
||||
export declare function projectNew(
|
||||
options: NapiProjectOptions,
|
||||
turboEngineOptions: NapiTurboEngineOptions
|
||||
): Promise<{ __napiType: 'Project' }>
|
||||
export declare function projectUpdate(
|
||||
project: { __napiType: 'Project' },
|
||||
options: NapiPartialProjectOptions
|
||||
): Promise<void>
|
||||
/**
|
||||
* Runs exit handlers for the project registered using the [`ExitHandler`] API.
|
||||
*
|
||||
* This is called by `project_shutdown`, so if you're calling that API, you shouldn't call this
|
||||
* one.
|
||||
*/
|
||||
export declare function projectOnExit(project: {
|
||||
__napiType: 'Project'
|
||||
}): Promise<void>
|
||||
/**
|
||||
* Runs `project_on_exit`, and then waits for turbo_tasks to gracefully shut down.
|
||||
*
|
||||
* This is used in builds where it's important that we completely persist turbo-tasks to disk, but
|
||||
* it's skipped in the development server (`project_on_exit` is used instead with a short timeout),
|
||||
* where we prioritize fast exit and user responsiveness over all else.
|
||||
*/
|
||||
export declare function projectShutdown(project: {
|
||||
__napiType: 'Project'
|
||||
}): Promise<void>
|
||||
export interface AppPageNapiRoute {
|
||||
/** The relative path from project_path to the route file */
|
||||
originalName?: string
|
||||
htmlEndpoint?: ExternalObject<ExternalEndpoint>
|
||||
rscEndpoint?: ExternalObject<ExternalEndpoint>
|
||||
}
|
||||
export interface NapiRoute {
|
||||
/** The router path */
|
||||
pathname: string
|
||||
/** The relative path from project_path to the route file */
|
||||
originalName?: string
|
||||
/** The type of route, eg a Page or App */
|
||||
type: string
|
||||
pages?: Array<AppPageNapiRoute>
|
||||
endpoint?: ExternalObject<ExternalEndpoint>
|
||||
htmlEndpoint?: ExternalObject<ExternalEndpoint>
|
||||
rscEndpoint?: ExternalObject<ExternalEndpoint>
|
||||
dataEndpoint?: ExternalObject<ExternalEndpoint>
|
||||
}
|
||||
export interface NapiMiddleware {
|
||||
endpoint: ExternalObject<ExternalEndpoint>
|
||||
}
|
||||
export interface NapiInstrumentation {
|
||||
nodeJs: ExternalObject<ExternalEndpoint>
|
||||
edge: ExternalObject<ExternalEndpoint>
|
||||
}
|
||||
export interface NapiEntrypoints {
|
||||
routes: Array<NapiRoute>
|
||||
middleware?: NapiMiddleware
|
||||
instrumentation?: NapiInstrumentation
|
||||
pagesDocumentEndpoint: ExternalObject<ExternalEndpoint>
|
||||
pagesAppEndpoint: ExternalObject<ExternalEndpoint>
|
||||
pagesErrorEndpoint: ExternalObject<ExternalEndpoint>
|
||||
}
|
||||
export declare function projectWriteAllEntrypointsToDisk(
|
||||
project: { __napiType: 'Project' },
|
||||
appDirOnly: boolean
|
||||
): Promise<TurbopackResult>
|
||||
export declare function projectEntrypointsSubscribe(
|
||||
project: { __napiType: 'Project' },
|
||||
func: (...args: any[]) => any
|
||||
): { __napiType: 'RootTask' }
|
||||
export declare function projectHmrEvents(
|
||||
project: { __napiType: 'Project' },
|
||||
identifier: string,
|
||||
func: (...args: any[]) => any
|
||||
): { __napiType: 'RootTask' }
|
||||
export interface HmrIdentifiers {
|
||||
identifiers: Array<string>
|
||||
}
|
||||
export declare function projectHmrIdentifiersSubscribe(
|
||||
project: { __napiType: 'Project' },
|
||||
func: (...args: any[]) => any
|
||||
): { __napiType: 'RootTask' }
|
||||
export interface NapiUpdateMessage {
|
||||
updateType: string
|
||||
value?: NapiUpdateInfo
|
||||
}
|
||||
export interface NapiUpdateInfo {
|
||||
duration: number
|
||||
tasks: number
|
||||
}
|
||||
/**
|
||||
* Subscribes to lifecycle events of the compilation.
|
||||
*
|
||||
* Emits an [UpdateMessage::Start] event when any computation starts.
|
||||
* Emits an [UpdateMessage::End] event when there was no computation for the
|
||||
* specified time (`aggregation_ms`). The [UpdateMessage::End] event contains
|
||||
* information about the computations that happened since the
|
||||
* [UpdateMessage::Start] event. It contains the duration of the computation
|
||||
* (excluding the idle time that was spend waiting for `aggregation_ms`), and
|
||||
* the number of tasks that were executed.
|
||||
*
|
||||
* The signature of the `func` is `(update_message: UpdateMessage) => void`.
|
||||
*/
|
||||
export declare function projectUpdateInfoSubscribe(
|
||||
project: { __napiType: 'Project' },
|
||||
aggregationMs: number,
|
||||
func: (...args: any[]) => any
|
||||
): void
|
||||
export interface StackFrame {
|
||||
isServer: boolean
|
||||
isInternal?: boolean
|
||||
originalFile?: string
|
||||
file: string
|
||||
line?: number
|
||||
column?: number
|
||||
methodName?: string
|
||||
}
|
||||
export declare function projectTraceSource(
|
||||
project: { __napiType: 'Project' },
|
||||
frame: StackFrame,
|
||||
currentDirectoryFileUrl: string
|
||||
): Promise<StackFrame | null>
|
||||
export declare function projectGetSourceForAsset(
|
||||
project: { __napiType: 'Project' },
|
||||
filePath: string
|
||||
): Promise<string | null>
|
||||
export declare function projectGetSourceMap(
|
||||
project: { __napiType: 'Project' },
|
||||
filePath: string
|
||||
): Promise<string | null>
|
||||
export declare function projectGetSourceMapSync(
|
||||
project: { __napiType: 'Project' },
|
||||
filePath: string
|
||||
): string | null
|
||||
export declare function rootTaskDispose(rootTask: {
|
||||
__napiType: 'RootTask'
|
||||
}): void
|
||||
export interface NapiIssue {
|
||||
severity: string
|
||||
stage: string
|
||||
filePath: string
|
||||
title: any
|
||||
description?: any
|
||||
detail?: any
|
||||
source?: NapiIssueSource
|
||||
documentationLink: string
|
||||
subIssues: Array<NapiIssue>
|
||||
}
|
||||
export interface NapiIssueSource {
|
||||
source: NapiSource
|
||||
range?: NapiIssueSourceRange
|
||||
}
|
||||
export interface NapiIssueSourceRange {
|
||||
start: NapiSourcePos
|
||||
end: NapiSourcePos
|
||||
}
|
||||
export interface NapiSource {
|
||||
ident: string
|
||||
content?: string
|
||||
}
|
||||
export interface NapiSourcePos {
|
||||
line: number
|
||||
column: number
|
||||
}
|
||||
export interface NapiDiagnostic {
|
||||
category: string
|
||||
name: string
|
||||
payload: Record<string, string>
|
||||
}
|
||||
export declare function parse(
|
||||
src: string,
|
||||
options: Buffer,
|
||||
filename?: string | undefined | null,
|
||||
signal?: AbortSignal | undefined | null
|
||||
): Promise<string>
|
||||
export declare function isReactCompilerRequired(
|
||||
filename: string,
|
||||
signal?: AbortSignal | undefined | null
|
||||
): Promise<boolean>
|
||||
export declare function transform(
|
||||
src: string | Buffer | undefined,
|
||||
isModule: boolean,
|
||||
options: Buffer,
|
||||
signal?: AbortSignal | undefined | null
|
||||
): Promise<unknown>
|
||||
export declare function transformSync(
|
||||
src: string | Buffer | undefined,
|
||||
isModule: boolean,
|
||||
options: Buffer
|
||||
): object
|
||||
export declare function startTurbopackTraceServer(path: string): void
|
||||
export interface NextBuildContext {
|
||||
/** The root directory of the workspace. */
|
||||
root?: string
|
||||
/** The project's directory. */
|
||||
dir?: string
|
||||
/**
|
||||
* next.config.js's distDir. Current there's some early stage setup
|
||||
* requires this Before construct a context to read next.config.js,
|
||||
* which we passes separately here.
|
||||
*/
|
||||
distDir?: string
|
||||
/** The build ID. */
|
||||
buildId?: string
|
||||
/** The rewrites, as computed by Next.js. */
|
||||
rewrites?: NapiRewrites
|
||||
defineEnv: NapiDefineEnv
|
||||
}
|
||||
/** Keep in sync with [`next_core::next_config::Rewrites`] */
|
||||
export interface NapiRewrites {
|
||||
fallback: Array<NapiRewrite>
|
||||
afterFiles: Array<NapiRewrite>
|
||||
beforeFiles: Array<NapiRewrite>
|
||||
}
|
||||
/** Keep in sync with [`next_core::next_config::Rewrite`] */
|
||||
export interface NapiRewrite {
|
||||
source: string
|
||||
destination: string
|
||||
basePath?: boolean
|
||||
locale?: boolean
|
||||
has?: Array<NapiRouteHas>
|
||||
missing?: Array<NapiRouteHas>
|
||||
}
|
||||
export declare function getTargetTriple(): string
|
||||
/**
|
||||
* Initialize tracing subscriber to emit traces. This configures subscribers
|
||||
* for Trace Event Format <https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview>.
|
||||
*/
|
||||
export declare function initCustomTraceSubscriber(
|
||||
traceOutFilePath?: string | undefined | null
|
||||
): ExternalObject<RefCell>
|
||||
/**
|
||||
* Teardown currently running tracing subscriber to flush out remaining traces.
|
||||
* This should be called when parent node.js process exits, otherwise generated
|
||||
* trace may drop traces in the buffer.
|
||||
*/
|
||||
export declare function teardownTraceSubscriber(
|
||||
guardExternal: ExternalObject<RefCell>
|
||||
): void
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
// DO NOT MANUALLY EDIT THESE TYPES
|
||||
// You can regenerate this file by running `pnpm swc-build-wasm` in the root of the repo.
|
||||
|
||||
/* tslint:disable */
|
||||
/* eslint-disable */
|
||||
/**
|
||||
* @param {string} s
|
||||
* @param {any} opts
|
||||
* @returns {any}
|
||||
*/
|
||||
export function minifySync(s: string, opts: any): any
|
||||
/**
|
||||
* @param {string} s
|
||||
* @param {any} opts
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
export function minify(s: string, opts: any): Promise<any>
|
||||
/**
|
||||
* @param {any} s
|
||||
* @param {any} opts
|
||||
* @returns {any}
|
||||
*/
|
||||
export function transformSync(s: any, opts: any): any
|
||||
/**
|
||||
* @param {any} s
|
||||
* @param {any} opts
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
export function transform(s: any, opts: any): Promise<any>
|
||||
/**
|
||||
* @param {string} s
|
||||
* @param {any} opts
|
||||
* @returns {any}
|
||||
*/
|
||||
export function parseSync(s: string, opts: any): any
|
||||
/**
|
||||
* @param {string} s
|
||||
* @param {any} opts
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
export function parse(s: string, opts: any): Promise<any>
|
||||
/**
|
||||
* @param {string} value
|
||||
* @param {any} opts
|
||||
* @returns {any}
|
||||
*/
|
||||
export function mdxCompileSync(value: string, opts: any): any
|
||||
/**
|
||||
* @param {string} value
|
||||
* @param {any} opts
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
export function mdxCompile(value: string, opts: any): Promise<any>
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
export function __nextjs_pure(expr) {
|
||||
return expr;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=helpers.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/build/swc/helpers.ts"],"sourcesContent":["export function __nextjs_pure<T>(expr: T): T {\n return expr\n}\n"],"names":["__nextjs_pure","expr"],"mappings":"AAAA,OAAO,SAASA,cAAiBC,IAAO;IACtC,OAAOA;AACT"}
|
||||
+976
@@ -0,0 +1,976 @@
|
||||
/* eslint-disable @typescript-eslint/no-use-before-define */ import path from 'path';
|
||||
import { pathToFileURL } from 'url';
|
||||
import { arch, platform } from 'os';
|
||||
import { platformArchTriples } from 'next/dist/compiled/@napi-rs/triples';
|
||||
import * as Log from '../output/log';
|
||||
import { getParserOptions } from './options';
|
||||
import { eventSwcLoadFailure } from '../../telemetry/events/swc-load-failure';
|
||||
import { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile';
|
||||
import { downloadNativeNextSwc, downloadWasmSwc } from '../../lib/download-swc';
|
||||
import { isDeepStrictEqual } from 'util';
|
||||
import { getDefineEnv } from '../webpack/plugins/define-env-plugin';
|
||||
import { getReactCompilerLoader } from '../get-babel-loader-config';
|
||||
import { TurbopackInternalError } from '../../shared/lib/turbopack/utils';
|
||||
const nextVersion = "15.3.4";
|
||||
const ArchName = arch();
|
||||
const PlatformName = platform();
|
||||
function infoLog(...args) {
|
||||
if (process.env.NEXT_PRIVATE_BUILD_WORKER) {
|
||||
return;
|
||||
}
|
||||
if (process.env.DEBUG) {
|
||||
Log.info(...args);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Based on napi-rs's target triples, returns triples that have corresponding next-swc binaries.
|
||||
*/ export function getSupportedArchTriples() {
|
||||
const { darwin, win32, linux, freebsd, android } = platformArchTriples;
|
||||
return {
|
||||
darwin,
|
||||
win32: {
|
||||
arm64: win32.arm64,
|
||||
ia32: win32.ia32.filter((triple)=>triple.abi === 'msvc'),
|
||||
x64: win32.x64.filter((triple)=>triple.abi === 'msvc')
|
||||
},
|
||||
linux: {
|
||||
// linux[x64] includes `gnux32` abi, with x64 arch.
|
||||
x64: linux.x64.filter((triple)=>triple.abi !== 'gnux32'),
|
||||
arm64: linux.arm64,
|
||||
// This target is being deprecated, however we keep it in `knownDefaultWasmFallbackTriples` for now
|
||||
arm: linux.arm
|
||||
},
|
||||
// Below targets are being deprecated, however we keep it in `knownDefaultWasmFallbackTriples` for now
|
||||
freebsd: {
|
||||
x64: freebsd.x64
|
||||
},
|
||||
android: {
|
||||
arm64: android.arm64,
|
||||
arm: android.arm
|
||||
}
|
||||
};
|
||||
}
|
||||
const triples = (()=>{
|
||||
var _supportedArchTriples_PlatformName, _platformArchTriples_PlatformName;
|
||||
const supportedArchTriples = getSupportedArchTriples();
|
||||
const targetTriple = (_supportedArchTriples_PlatformName = supportedArchTriples[PlatformName]) == null ? void 0 : _supportedArchTriples_PlatformName[ArchName];
|
||||
// If we have supported triple, return it right away
|
||||
if (targetTriple) {
|
||||
return targetTriple;
|
||||
}
|
||||
// If there isn't corresponding target triple in `supportedArchTriples`, check if it's excluded from original raw triples
|
||||
// Otherwise, it is completely unsupported platforms.
|
||||
let rawTargetTriple = (_platformArchTriples_PlatformName = platformArchTriples[PlatformName]) == null ? void 0 : _platformArchTriples_PlatformName[ArchName];
|
||||
if (rawTargetTriple) {
|
||||
Log.warn(`Trying to load next-swc for target triple ${rawTargetTriple}, but there next-swc does not have native bindings support`);
|
||||
} else {
|
||||
Log.warn(`Trying to load next-swc for unsupported platforms ${PlatformName}/${ArchName}`);
|
||||
}
|
||||
return [];
|
||||
})();
|
||||
// Allow to specify an absolute path to the custom turbopack binary to load.
|
||||
// If one of env variables is set, `loadNative` will try to use specified
|
||||
// binary instead. This is thin, naive interface
|
||||
// - `loadBindings` will not validate neither path nor the binary.
|
||||
//
|
||||
// Note these are internal flag: there's no stability, feature guarantee.
|
||||
const __INTERNAL_CUSTOM_TURBOPACK_BINDINGS = process.env.__INTERNAL_CUSTOM_TURBOPACK_BINDINGS;
|
||||
function checkVersionMismatch(pkgData) {
|
||||
const version = pkgData.version;
|
||||
if (version && version !== nextVersion) {
|
||||
Log.warn(`Mismatching @next/swc version, detected: ${version} while Next.js is on ${nextVersion}. Please ensure these match`);
|
||||
}
|
||||
}
|
||||
// These are the platforms we'll try to load wasm bindings first,
|
||||
// only try to load native bindings if loading wasm binding somehow fails.
|
||||
// Fallback to native binding is for migration period only,
|
||||
// once we can verify loading-wasm-first won't cause visible regressions,
|
||||
// we'll not include native bindings for these platform at all.
|
||||
const knownDefaultWasmFallbackTriples = [
|
||||
'x86_64-unknown-freebsd',
|
||||
'aarch64-linux-android',
|
||||
'arm-linux-androideabi',
|
||||
'armv7-unknown-linux-gnueabihf',
|
||||
'i686-pc-windows-msvc'
|
||||
];
|
||||
// The last attempt's error code returned when cjs require to native bindings fails.
|
||||
// If node.js throws an error without error code, this should be `unknown` instead of undefined.
|
||||
// For the wasm-first targets (`knownDefaultWasmFallbackTriples`) this will be `unsupported_target`.
|
||||
let lastNativeBindingsLoadErrorCode = undefined;
|
||||
let nativeBindings;
|
||||
let wasmBindings;
|
||||
let downloadWasmPromise;
|
||||
let pendingBindings;
|
||||
let swcTraceFlushGuard;
|
||||
let downloadNativeBindingsPromise = undefined;
|
||||
export const lockfilePatchPromise = {};
|
||||
export async function loadBindings(useWasmBinary = false) {
|
||||
// Increase Rust stack size as some npm packages being compiled need more than the default.
|
||||
if (!process.env.RUST_MIN_STACK) {
|
||||
process.env.RUST_MIN_STACK = '8388608';
|
||||
}
|
||||
if (pendingBindings) {
|
||||
return pendingBindings;
|
||||
}
|
||||
// rust needs stdout to be blocking, otherwise it will throw an error (on macOS at least) when writing a lot of data (logs) to it
|
||||
// see https://github.com/napi-rs/napi-rs/issues/1630
|
||||
// and https://github.com/nodejs/node/blob/main/doc/api/process.md#a-note-on-process-io
|
||||
if (process.stdout._handle != null) {
|
||||
// @ts-ignore
|
||||
process.stdout._handle.setBlocking == null ? void 0 : process.stdout._handle.setBlocking.call(process.stdout._handle, true);
|
||||
}
|
||||
if (process.stderr._handle != null) {
|
||||
// @ts-ignore
|
||||
process.stderr._handle.setBlocking == null ? void 0 : process.stderr._handle.setBlocking.call(process.stderr._handle, true);
|
||||
}
|
||||
pendingBindings = new Promise(async (resolve, _reject)=>{
|
||||
if (!lockfilePatchPromise.cur) {
|
||||
// always run lockfile check once so that it gets patched
|
||||
// even if it doesn't fail to load locally
|
||||
lockfilePatchPromise.cur = patchIncorrectLockfile(process.cwd()).catch(console.error);
|
||||
}
|
||||
let attempts = [];
|
||||
const disableWasmFallback = process.env.NEXT_DISABLE_SWC_WASM;
|
||||
const unsupportedPlatform = triples.some((triple)=>!!(triple == null ? void 0 : triple.raw) && knownDefaultWasmFallbackTriples.includes(triple.raw));
|
||||
const isWebContainer = process.versions.webcontainer;
|
||||
// Normal execution relies on the param `useWasmBinary` flag to load, but
|
||||
// in certain cases where there isn't a native binary we always load wasm fallback first.
|
||||
const shouldLoadWasmFallbackFirst = !disableWasmFallback && useWasmBinary || unsupportedPlatform || isWebContainer;
|
||||
if (!unsupportedPlatform && useWasmBinary) {
|
||||
Log.warn(`experimental.useWasmBinary is not an option for supported platform ${PlatformName}/${ArchName} and will be ignored.`);
|
||||
}
|
||||
if (shouldLoadWasmFallbackFirst) {
|
||||
lastNativeBindingsLoadErrorCode = 'unsupported_target';
|
||||
const fallbackBindings = await tryLoadWasmWithFallback(attempts);
|
||||
if (fallbackBindings) {
|
||||
return resolve(fallbackBindings);
|
||||
}
|
||||
}
|
||||
// Trickle down loading `fallback` bindings:
|
||||
//
|
||||
// - First, try to load native bindings installed in node_modules.
|
||||
// - If that fails with `ERR_MODULE_NOT_FOUND`, treat it as case of https://github.com/npm/cli/issues/4828
|
||||
// that host system where generated package lock is not matching to the guest system running on, try to manually
|
||||
// download corresponding target triple and load it. This won't be triggered if native bindings are failed to load
|
||||
// with other reasons than `ERR_MODULE_NOT_FOUND`.
|
||||
// - Lastly, falls back to wasm binding where possible.
|
||||
try {
|
||||
return resolve(loadNative());
|
||||
} catch (a) {
|
||||
if (Array.isArray(a) && a.every((m)=>m.includes('it was not installed'))) {
|
||||
let fallbackBindings = await tryLoadNativeWithFallback(attempts);
|
||||
if (fallbackBindings) {
|
||||
return resolve(fallbackBindings);
|
||||
}
|
||||
}
|
||||
attempts = attempts.concat(a);
|
||||
}
|
||||
// For these platforms we already tried to load wasm and failed, skip reattempt
|
||||
if (!shouldLoadWasmFallbackFirst && !disableWasmFallback) {
|
||||
const fallbackBindings = await tryLoadWasmWithFallback(attempts);
|
||||
if (fallbackBindings) {
|
||||
return resolve(fallbackBindings);
|
||||
}
|
||||
}
|
||||
logLoadFailure(attempts, true);
|
||||
});
|
||||
return pendingBindings;
|
||||
}
|
||||
async function tryLoadNativeWithFallback(attempts) {
|
||||
const nativeBindingsDirectory = path.join(path.dirname(require.resolve('next/package.json')), 'next-swc-fallback');
|
||||
if (!downloadNativeBindingsPromise) {
|
||||
downloadNativeBindingsPromise = downloadNativeNextSwc(nextVersion, nativeBindingsDirectory, triples.map((triple)=>triple.platformArchABI));
|
||||
}
|
||||
await downloadNativeBindingsPromise;
|
||||
try {
|
||||
return loadNative(nativeBindingsDirectory);
|
||||
} catch (a) {
|
||||
attempts.push(...[].concat(a));
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
async function tryLoadWasmWithFallback(attempts) {
|
||||
try {
|
||||
let bindings = await loadWasm('');
|
||||
// @ts-expect-error TODO: this event has a wrong type.
|
||||
eventSwcLoadFailure({
|
||||
wasm: 'enabled',
|
||||
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode
|
||||
});
|
||||
return bindings;
|
||||
} catch (a) {
|
||||
attempts.push(...[].concat(a));
|
||||
}
|
||||
try {
|
||||
// if not installed already download wasm package on-demand
|
||||
// we download to a custom directory instead of to node_modules
|
||||
// as node_module import attempts are cached and can't be re-attempted
|
||||
// x-ref: https://github.com/nodejs/modules/issues/307
|
||||
const wasmDirectory = path.join(path.dirname(require.resolve('next/package.json')), 'wasm');
|
||||
if (!downloadWasmPromise) {
|
||||
downloadWasmPromise = downloadWasmSwc(nextVersion, wasmDirectory);
|
||||
}
|
||||
await downloadWasmPromise;
|
||||
let bindings = await loadWasm(wasmDirectory);
|
||||
// @ts-expect-error TODO: this event has a wrong type.
|
||||
eventSwcLoadFailure({
|
||||
wasm: 'fallback',
|
||||
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode
|
||||
});
|
||||
// still log native load attempts so user is
|
||||
// aware it failed and should be fixed
|
||||
for (const attempt of attempts){
|
||||
Log.warn(attempt);
|
||||
}
|
||||
return bindings;
|
||||
} catch (a) {
|
||||
attempts.push(...[].concat(a));
|
||||
}
|
||||
}
|
||||
function loadBindingsSync() {
|
||||
let attempts = [];
|
||||
try {
|
||||
return loadNative();
|
||||
} catch (a) {
|
||||
attempts = attempts.concat(a);
|
||||
}
|
||||
// we can leverage the wasm bindings if they are already
|
||||
// loaded
|
||||
if (wasmBindings) {
|
||||
return wasmBindings;
|
||||
}
|
||||
logLoadFailure(attempts);
|
||||
throw Object.defineProperty(new Error('Failed to load bindings', {
|
||||
cause: attempts
|
||||
}), "__NEXT_ERROR_CODE", {
|
||||
value: "E424",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
let loggingLoadFailure = false;
|
||||
function logLoadFailure(attempts, triedWasm = false) {
|
||||
// make sure we only emit the event and log the failure once
|
||||
if (loggingLoadFailure) return;
|
||||
loggingLoadFailure = true;
|
||||
for (let attempt of attempts){
|
||||
Log.warn(attempt);
|
||||
}
|
||||
// @ts-expect-error TODO: this event has a wrong type.
|
||||
eventSwcLoadFailure({
|
||||
wasm: triedWasm ? 'failed' : undefined,
|
||||
nativeBindingsErrorCode: lastNativeBindingsLoadErrorCode
|
||||
}).then(()=>lockfilePatchPromise.cur || Promise.resolve()).finally(()=>{
|
||||
Log.error(`Failed to load SWC binary for ${PlatformName}/${ArchName}, see more info here: https://nextjs.org/docs/messages/failed-loading-swc`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
export function createDefineEnv({ isTurbopack, clientRouterFilters, config, dev, distDir, fetchCacheKeyPrefix, hasRewrites, middlewareMatchers }) {
|
||||
let defineEnv = {
|
||||
client: [],
|
||||
edge: [],
|
||||
nodejs: []
|
||||
};
|
||||
for (const variant of Object.keys(defineEnv)){
|
||||
defineEnv[variant] = rustifyEnv(getDefineEnv({
|
||||
isTurbopack,
|
||||
clientRouterFilters,
|
||||
config,
|
||||
dev,
|
||||
distDir,
|
||||
fetchCacheKeyPrefix,
|
||||
hasRewrites,
|
||||
isClient: variant === 'client',
|
||||
isEdgeServer: variant === 'edge',
|
||||
isNodeOrEdgeCompilation: variant === 'nodejs' || variant === 'edge',
|
||||
isNodeServer: variant === 'nodejs',
|
||||
middlewareMatchers
|
||||
}));
|
||||
}
|
||||
return defineEnv;
|
||||
}
|
||||
function rustifyEnv(env) {
|
||||
return Object.entries(env).filter(([_, value])=>value != null).map(([name, value])=>({
|
||||
name,
|
||||
value
|
||||
}));
|
||||
}
|
||||
// TODO(sokra) Support wasm option.
|
||||
function bindingToApi(binding, _wasm) {
|
||||
const cancel = new class Cancel extends Error {
|
||||
}();
|
||||
/**
|
||||
* Utility function to ensure all variants of an enum are handled.
|
||||
*/ function invariant(never, computeMessage) {
|
||||
throw Object.defineProperty(new Error(`Invariant: ${computeMessage(never)}`), "__NEXT_ERROR_CODE", {
|
||||
value: "E193",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
async function withErrorCause(fn) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (nativeError) {
|
||||
throw TurbopackInternalError.createAndRecordTelemetry(nativeError);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Calls a native function and streams the result.
|
||||
* If useBuffer is true, all values will be preserved, potentially buffered
|
||||
* if consumed slower than produced. Else, only the latest value will be
|
||||
* preserved.
|
||||
*/ function subscribe(useBuffer, nativeFunction) {
|
||||
// A buffer of produced items. This will only contain values if the
|
||||
// consumer is slower than the producer.
|
||||
let buffer = [];
|
||||
// A deferred value waiting for the next produced item. This will only
|
||||
// exist if the consumer is faster than the producer.
|
||||
let waiting;
|
||||
let canceled = false;
|
||||
// The native function will call this every time it emits a new result. We
|
||||
// either need to notify a waiting consumer, or buffer the new result until
|
||||
// the consumer catches up.
|
||||
function emitResult(err, value) {
|
||||
if (waiting) {
|
||||
let { resolve, reject } = waiting;
|
||||
waiting = undefined;
|
||||
if (err) reject(err);
|
||||
else resolve(value);
|
||||
} else {
|
||||
const item = {
|
||||
err,
|
||||
value
|
||||
};
|
||||
if (useBuffer) buffer.push(item);
|
||||
else buffer[0] = item;
|
||||
}
|
||||
}
|
||||
async function* createIterator() {
|
||||
const task = await withErrorCause(()=>nativeFunction(emitResult));
|
||||
try {
|
||||
while(!canceled){
|
||||
if (buffer.length > 0) {
|
||||
const item = buffer.shift();
|
||||
if (item.err) throw item.err;
|
||||
yield item.value;
|
||||
} else {
|
||||
// eslint-disable-next-line no-loop-func
|
||||
yield new Promise((resolve, reject)=>{
|
||||
waiting = {
|
||||
resolve,
|
||||
reject
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (e === cancel) return;
|
||||
if (e instanceof Error) {
|
||||
throw TurbopackInternalError.createAndRecordTelemetry(e);
|
||||
}
|
||||
throw e;
|
||||
} finally{
|
||||
if (task) {
|
||||
binding.rootTaskDispose(task);
|
||||
}
|
||||
}
|
||||
}
|
||||
const iterator = createIterator();
|
||||
iterator.return = async ()=>{
|
||||
canceled = true;
|
||||
if (waiting) waiting.reject(cancel);
|
||||
return {
|
||||
value: undefined,
|
||||
done: true
|
||||
};
|
||||
};
|
||||
return iterator;
|
||||
}
|
||||
async function rustifyProjectOptions(options) {
|
||||
return {
|
||||
...options,
|
||||
nextConfig: await serializeNextConfig(options.nextConfig, options.projectPath),
|
||||
jsConfig: JSON.stringify(options.jsConfig),
|
||||
env: rustifyEnv(options.env)
|
||||
};
|
||||
}
|
||||
async function rustifyPartialProjectOptions(options) {
|
||||
return {
|
||||
...options,
|
||||
nextConfig: options.nextConfig && await serializeNextConfig(options.nextConfig, options.projectPath),
|
||||
jsConfig: options.jsConfig && JSON.stringify(options.jsConfig),
|
||||
env: options.env && rustifyEnv(options.env)
|
||||
};
|
||||
}
|
||||
class ProjectImpl {
|
||||
constructor(nativeProject){
|
||||
this._nativeProject = nativeProject;
|
||||
}
|
||||
async update(options) {
|
||||
await withErrorCause(async ()=>binding.projectUpdate(this._nativeProject, await rustifyPartialProjectOptions(options)));
|
||||
}
|
||||
async writeAllEntrypointsToDisk(appDirOnly) {
|
||||
return await withErrorCause(async ()=>{
|
||||
const napiEndpoints = await binding.projectWriteAllEntrypointsToDisk(this._nativeProject, appDirOnly);
|
||||
return napiEntrypointsToRawEntrypoints(napiEndpoints);
|
||||
});
|
||||
}
|
||||
entrypointsSubscribe() {
|
||||
const subscription = subscribe(false, async (callback)=>binding.projectEntrypointsSubscribe(this._nativeProject, callback));
|
||||
return async function*() {
|
||||
for await (const entrypoints of subscription){
|
||||
yield napiEntrypointsToRawEntrypoints(entrypoints);
|
||||
}
|
||||
}();
|
||||
}
|
||||
hmrEvents(identifier) {
|
||||
return subscribe(true, async (callback)=>binding.projectHmrEvents(this._nativeProject, identifier, callback));
|
||||
}
|
||||
hmrIdentifiersSubscribe() {
|
||||
return subscribe(false, async (callback)=>binding.projectHmrIdentifiersSubscribe(this._nativeProject, callback));
|
||||
}
|
||||
traceSource(stackFrame, currentDirectoryFileUrl) {
|
||||
return binding.projectTraceSource(this._nativeProject, stackFrame, currentDirectoryFileUrl);
|
||||
}
|
||||
getSourceForAsset(filePath) {
|
||||
return binding.projectGetSourceForAsset(this._nativeProject, filePath);
|
||||
}
|
||||
getSourceMap(filePath) {
|
||||
return binding.projectGetSourceMap(this._nativeProject, filePath);
|
||||
}
|
||||
getSourceMapSync(filePath) {
|
||||
return binding.projectGetSourceMapSync(this._nativeProject, filePath);
|
||||
}
|
||||
updateInfoSubscribe(aggregationMs) {
|
||||
return subscribe(true, async (callback)=>binding.projectUpdateInfoSubscribe(this._nativeProject, aggregationMs, callback));
|
||||
}
|
||||
shutdown() {
|
||||
return binding.projectShutdown(this._nativeProject);
|
||||
}
|
||||
onExit() {
|
||||
return binding.projectOnExit(this._nativeProject);
|
||||
}
|
||||
}
|
||||
class EndpointImpl {
|
||||
constructor(nativeEndpoint){
|
||||
this._nativeEndpoint = nativeEndpoint;
|
||||
}
|
||||
async writeToDisk() {
|
||||
return await withErrorCause(()=>binding.endpointWriteToDisk(this._nativeEndpoint));
|
||||
}
|
||||
async clientChanged() {
|
||||
const clientSubscription = subscribe(false, async (callback)=>binding.endpointClientChangedSubscribe(await this._nativeEndpoint, callback));
|
||||
await clientSubscription.next();
|
||||
return clientSubscription;
|
||||
}
|
||||
async serverChanged(includeIssues) {
|
||||
const serverSubscription = subscribe(false, async (callback)=>binding.endpointServerChangedSubscribe(await this._nativeEndpoint, includeIssues, callback));
|
||||
await serverSubscription.next();
|
||||
return serverSubscription;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Returns a new copy of next.js config object to avoid mutating the original.
|
||||
*
|
||||
* Also it does some augmentation to the configuration as well, for example set the
|
||||
* turbopack's rules if `experimental.reactCompilerOptions` is set.
|
||||
*/ function augmentNextConfig(originalNextConfig, projectPath) {
|
||||
var _nextConfig_experimental;
|
||||
let nextConfig = {
|
||||
...originalNextConfig
|
||||
};
|
||||
const reactCompilerOptions = (_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.reactCompiler;
|
||||
// It is not easy to set the rules inside of rust as resolving, and passing the context identical to the webpack
|
||||
// config is bit hard, also we can reuse same codes between webpack config in here.
|
||||
if (reactCompilerOptions) {
|
||||
var _nextConfig_turbopack;
|
||||
const ruleKeys = [
|
||||
'*.ts',
|
||||
'*.js',
|
||||
'*.jsx',
|
||||
'*.tsx'
|
||||
];
|
||||
if (Object.keys((nextConfig == null ? void 0 : (_nextConfig_turbopack = nextConfig.turbopack) == null ? void 0 : _nextConfig_turbopack.rules) ?? []).some((key)=>ruleKeys.includes(key))) {
|
||||
Log.warn(`The React Compiler cannot be enabled automatically because 'turbopack.rules' contains a rule for '*.ts', '*.js', '*.jsx', and '*.tsx'. Remove this rule, or add 'babel-loader' and 'babel-plugin-react-compiler' to the Turbopack configuration manually.`);
|
||||
} else {
|
||||
if (!nextConfig.turbopack) {
|
||||
nextConfig.turbopack = {};
|
||||
}
|
||||
if (!nextConfig.turbopack.rules) {
|
||||
nextConfig.turbopack.rules = {};
|
||||
}
|
||||
for (const key of [
|
||||
'*.ts',
|
||||
'*.js',
|
||||
'*.jsx',
|
||||
'*.tsx'
|
||||
]){
|
||||
nextConfig.turbopack.rules[key] = {
|
||||
browser: {
|
||||
foreign: false,
|
||||
loaders: [
|
||||
getReactCompilerLoader(originalNextConfig.experimental.reactCompiler, projectPath, nextConfig.dev, false, undefined)
|
||||
]
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return nextConfig;
|
||||
}
|
||||
async function serializeNextConfig(nextConfig, projectPath) {
|
||||
var _nextConfigSerializable_experimental_turbo, _nextConfigSerializable_experimental;
|
||||
// Avoid mutating the existing `nextConfig` object.
|
||||
let nextConfigSerializable = augmentNextConfig(nextConfig, projectPath);
|
||||
nextConfigSerializable.generateBuildId = await (nextConfig.generateBuildId == null ? void 0 : nextConfig.generateBuildId.call(nextConfig));
|
||||
// TODO: these functions takes arguments, have to be supported in a different way
|
||||
nextConfigSerializable.exportPathMap = {};
|
||||
nextConfigSerializable.webpack = nextConfig.webpack && {};
|
||||
if ((_nextConfigSerializable_experimental = nextConfigSerializable.experimental) == null ? void 0 : (_nextConfigSerializable_experimental_turbo = _nextConfigSerializable_experimental.turbo) == null ? void 0 : _nextConfigSerializable_experimental_turbo.rules) {
|
||||
var _nextConfigSerializable_turbopack;
|
||||
ensureLoadersHaveSerializableOptions((_nextConfigSerializable_turbopack = nextConfigSerializable.turbopack) == null ? void 0 : _nextConfigSerializable_turbopack.rules);
|
||||
}
|
||||
nextConfigSerializable.modularizeImports = nextConfigSerializable.modularizeImports ? Object.fromEntries(Object.entries(nextConfigSerializable.modularizeImports).map(([mod, config])=>[
|
||||
mod,
|
||||
{
|
||||
...config,
|
||||
transform: typeof config.transform === 'string' ? config.transform : Object.entries(config.transform).map(([key, value])=>[
|
||||
key,
|
||||
value
|
||||
])
|
||||
}
|
||||
])) : undefined;
|
||||
// loaderFile is an absolute path, we need it to be relative for turbopack.
|
||||
if (nextConfigSerializable.images.loaderFile) {
|
||||
nextConfigSerializable.images = {
|
||||
...nextConfig.images,
|
||||
loaderFile: './' + path.relative(projectPath, nextConfig.images.loaderFile)
|
||||
};
|
||||
}
|
||||
return JSON.stringify(nextConfigSerializable, null, 2);
|
||||
}
|
||||
function ensureLoadersHaveSerializableOptions(turbopackRules) {
|
||||
for (const [glob, rule] of Object.entries(turbopackRules)){
|
||||
if (Array.isArray(rule)) {
|
||||
checkLoaderItems(rule, glob);
|
||||
} else {
|
||||
checkConfigItem(rule, glob);
|
||||
}
|
||||
}
|
||||
function checkConfigItem(rule, glob) {
|
||||
if (!rule) return;
|
||||
if ('loaders' in rule) {
|
||||
checkLoaderItems(rule.loaders, glob);
|
||||
} else {
|
||||
for(const key in rule){
|
||||
const inner = rule[key];
|
||||
if (typeof inner === 'object' && inner) {
|
||||
checkConfigItem(inner, glob);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function checkLoaderItems(loaderItems, glob) {
|
||||
for (const loaderItem of loaderItems){
|
||||
if (typeof loaderItem !== 'string' && !isDeepStrictEqual(loaderItem, JSON.parse(JSON.stringify(loaderItem)))) {
|
||||
throw Object.defineProperty(new Error(`loader ${loaderItem.loader} for match "${glob}" does not have serializable options. Ensure that options passed are plain JavaScript objects and values.`), "__NEXT_ERROR_CODE", {
|
||||
value: "E491",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function napiEntrypointsToRawEntrypoints(entrypoints) {
|
||||
const routes = new Map();
|
||||
for (const { pathname, ...nativeRoute } of entrypoints.routes){
|
||||
let route;
|
||||
const routeType = nativeRoute.type;
|
||||
switch(routeType){
|
||||
case 'page':
|
||||
route = {
|
||||
type: 'page',
|
||||
htmlEndpoint: new EndpointImpl(nativeRoute.htmlEndpoint),
|
||||
dataEndpoint: new EndpointImpl(nativeRoute.dataEndpoint)
|
||||
};
|
||||
break;
|
||||
case 'page-api':
|
||||
route = {
|
||||
type: 'page-api',
|
||||
endpoint: new EndpointImpl(nativeRoute.endpoint)
|
||||
};
|
||||
break;
|
||||
case 'app-page':
|
||||
route = {
|
||||
type: 'app-page',
|
||||
pages: nativeRoute.pages.map((page)=>({
|
||||
originalName: page.originalName,
|
||||
htmlEndpoint: new EndpointImpl(page.htmlEndpoint),
|
||||
rscEndpoint: new EndpointImpl(page.rscEndpoint)
|
||||
}))
|
||||
};
|
||||
break;
|
||||
case 'app-route':
|
||||
route = {
|
||||
type: 'app-route',
|
||||
originalName: nativeRoute.originalName,
|
||||
endpoint: new EndpointImpl(nativeRoute.endpoint)
|
||||
};
|
||||
break;
|
||||
case 'conflict':
|
||||
route = {
|
||||
type: 'conflict'
|
||||
};
|
||||
break;
|
||||
default:
|
||||
const _exhaustiveCheck = routeType;
|
||||
invariant(nativeRoute, ()=>`Unknown route type: ${_exhaustiveCheck}`);
|
||||
}
|
||||
routes.set(pathname, route);
|
||||
}
|
||||
const napiMiddlewareToMiddleware = (middleware)=>({
|
||||
endpoint: new EndpointImpl(middleware.endpoint),
|
||||
runtime: middleware.runtime,
|
||||
matcher: middleware.matcher
|
||||
});
|
||||
const middleware = entrypoints.middleware ? napiMiddlewareToMiddleware(entrypoints.middleware) : undefined;
|
||||
const napiInstrumentationToInstrumentation = (instrumentation)=>({
|
||||
nodeJs: new EndpointImpl(instrumentation.nodeJs),
|
||||
edge: new EndpointImpl(instrumentation.edge)
|
||||
});
|
||||
const instrumentation = entrypoints.instrumentation ? napiInstrumentationToInstrumentation(entrypoints.instrumentation) : undefined;
|
||||
return {
|
||||
routes,
|
||||
middleware,
|
||||
instrumentation,
|
||||
pagesDocumentEndpoint: new EndpointImpl(entrypoints.pagesDocumentEndpoint),
|
||||
pagesAppEndpoint: new EndpointImpl(entrypoints.pagesAppEndpoint),
|
||||
pagesErrorEndpoint: new EndpointImpl(entrypoints.pagesErrorEndpoint),
|
||||
issues: entrypoints.issues,
|
||||
diagnostics: entrypoints.diagnostics
|
||||
};
|
||||
}
|
||||
return async function createProject(options, turboEngineOptions) {
|
||||
return new ProjectImpl(await binding.projectNew(await rustifyProjectOptions(options), turboEngineOptions || {}));
|
||||
};
|
||||
}
|
||||
async function loadWasm(importPath = '') {
|
||||
if (wasmBindings) {
|
||||
return wasmBindings;
|
||||
}
|
||||
let attempts = [];
|
||||
for (let pkg of [
|
||||
'@next/swc-wasm-nodejs',
|
||||
'@next/swc-wasm-web'
|
||||
]){
|
||||
try {
|
||||
let pkgPath = pkg;
|
||||
if (importPath) {
|
||||
// the import path must be exact when not in node_modules
|
||||
pkgPath = path.join(importPath, pkg, 'wasm.js');
|
||||
}
|
||||
let bindings = await import(pathToFileURL(pkgPath).toString());
|
||||
if (pkg === '@next/swc-wasm-web') {
|
||||
bindings = await bindings.default();
|
||||
}
|
||||
infoLog('next-swc build: wasm build @next/swc-wasm-web');
|
||||
// Note wasm binary does not support async intefaces yet, all async
|
||||
// interface coereces to sync interfaces.
|
||||
wasmBindings = {
|
||||
css: {
|
||||
lightning: {
|
||||
transform: function(_options) {
|
||||
throw Object.defineProperty(new Error('`css.lightning.transform` is not supported by the wasm bindings.'), "__NEXT_ERROR_CODE", {
|
||||
value: "E330",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
},
|
||||
transformStyleAttr: function(_options) {
|
||||
throw Object.defineProperty(new Error('`css.lightning.transformStyleAttr` is not supported by the wasm bindings.'), "__NEXT_ERROR_CODE", {
|
||||
value: "E324",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
isWasm: true,
|
||||
transform (src, options) {
|
||||
// TODO: we can remove fallback to sync interface once new stable version of next-swc gets published (current v12.2)
|
||||
return (bindings == null ? void 0 : bindings.transform) ? bindings.transform(src.toString(), options) : Promise.resolve(bindings.transformSync(src.toString(), options));
|
||||
},
|
||||
transformSync (src, options) {
|
||||
return bindings.transformSync(src.toString(), options);
|
||||
},
|
||||
minify (src, options) {
|
||||
return (bindings == null ? void 0 : bindings.minify) ? bindings.minify(src.toString(), options) : Promise.resolve(bindings.minifySync(src.toString(), options));
|
||||
},
|
||||
minifySync (src, options) {
|
||||
return bindings.minifySync(src.toString(), options);
|
||||
},
|
||||
parse (src, options) {
|
||||
return (bindings == null ? void 0 : bindings.parse) ? bindings.parse(src.toString(), options) : Promise.resolve(bindings.parseSync(src.toString(), options));
|
||||
},
|
||||
getTargetTriple () {
|
||||
return undefined;
|
||||
},
|
||||
turbo: {
|
||||
createProject: function(_options, _turboEngineOptions) {
|
||||
throw Object.defineProperty(new Error('`turbo.createProject` is not supported by the wasm bindings.'), "__NEXT_ERROR_CODE", {
|
||||
value: "E403",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
},
|
||||
startTurbopackTraceServer: function(_traceFilePath) {
|
||||
throw Object.defineProperty(new Error('`turbo.startTurbopackTraceServer` is not supported by the wasm bindings.'), "__NEXT_ERROR_CODE", {
|
||||
value: "E13",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
},
|
||||
mdx: {
|
||||
compile (src, options) {
|
||||
return bindings.mdxCompile(src, getMdxOptions(options));
|
||||
},
|
||||
compileSync (src, options) {
|
||||
return bindings.mdxCompileSync(src, getMdxOptions(options));
|
||||
}
|
||||
},
|
||||
reactCompiler: {
|
||||
isReactCompilerRequired (_filename) {
|
||||
return Promise.resolve(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
return wasmBindings;
|
||||
} catch (e) {
|
||||
// Only log attempts for loading wasm when loading as fallback
|
||||
if (importPath) {
|
||||
if ((e == null ? void 0 : e.code) === 'ERR_MODULE_NOT_FOUND') {
|
||||
attempts.push(`Attempted to load ${pkg}, but it was not installed`);
|
||||
} else {
|
||||
attempts.push(`Attempted to load ${pkg}, but an error occurred: ${e.message ?? e}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
throw attempts;
|
||||
}
|
||||
function loadNative(importPath) {
|
||||
if (nativeBindings) {
|
||||
return nativeBindings;
|
||||
}
|
||||
const customBindings = !!__INTERNAL_CUSTOM_TURBOPACK_BINDINGS ? require(__INTERNAL_CUSTOM_TURBOPACK_BINDINGS) : null;
|
||||
let bindings = customBindings;
|
||||
let attempts = [];
|
||||
const NEXT_TEST_NATIVE_DIR = process.env.NEXT_TEST_NATIVE_DIR;
|
||||
for (const triple of triples){
|
||||
if (NEXT_TEST_NATIVE_DIR) {
|
||||
try {
|
||||
// Use the binary directly to skip `pnpm pack` for testing as it's slow because of the large native binary.
|
||||
bindings = require(`${NEXT_TEST_NATIVE_DIR}/next-swc.${triple.platformArchABI}.node`);
|
||||
infoLog('next-swc build: local built @next/swc from NEXT_TEST_NATIVE_DIR');
|
||||
break;
|
||||
} catch (e) {}
|
||||
} else {
|
||||
try {
|
||||
bindings = require(`@next/swc/native/next-swc.${triple.platformArchABI}.node`);
|
||||
infoLog('next-swc build: local built @next/swc');
|
||||
break;
|
||||
} catch (e) {}
|
||||
}
|
||||
}
|
||||
if (!bindings) {
|
||||
for (const triple of triples){
|
||||
let pkg = importPath ? path.join(importPath, `@next/swc-${triple.platformArchABI}`, `next-swc.${triple.platformArchABI}.node`) : `@next/swc-${triple.platformArchABI}`;
|
||||
try {
|
||||
bindings = require(pkg);
|
||||
if (!importPath) {
|
||||
checkVersionMismatch(require(`${pkg}/package.json`));
|
||||
}
|
||||
break;
|
||||
} catch (e) {
|
||||
if ((e == null ? void 0 : e.code) === 'MODULE_NOT_FOUND') {
|
||||
attempts.push(`Attempted to load ${pkg}, but it was not installed`);
|
||||
} else {
|
||||
attempts.push(`Attempted to load ${pkg}, but an error occurred: ${e.message ?? e}`);
|
||||
}
|
||||
lastNativeBindingsLoadErrorCode = (e == null ? void 0 : e.code) ?? 'unknown';
|
||||
}
|
||||
}
|
||||
}
|
||||
if (bindings) {
|
||||
nativeBindings = {
|
||||
isWasm: false,
|
||||
transform (src, options) {
|
||||
var _options_jsc;
|
||||
const isModule = typeof src !== 'undefined' && typeof src !== 'string' && !Buffer.isBuffer(src);
|
||||
options = options || {};
|
||||
if (options == null ? void 0 : (_options_jsc = options.jsc) == null ? void 0 : _options_jsc.parser) {
|
||||
options.jsc.parser.syntax = options.jsc.parser.syntax ?? 'ecmascript';
|
||||
}
|
||||
return bindings.transform(isModule ? JSON.stringify(src) : src, isModule, toBuffer(options));
|
||||
},
|
||||
transformSync (src, options) {
|
||||
var _options_jsc;
|
||||
if (typeof src === 'undefined') {
|
||||
throw Object.defineProperty(new Error("transformSync doesn't implement reading the file from filesystem"), "__NEXT_ERROR_CODE", {
|
||||
value: "E292",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
} else if (Buffer.isBuffer(src)) {
|
||||
throw Object.defineProperty(new Error("transformSync doesn't implement taking the source code as Buffer"), "__NEXT_ERROR_CODE", {
|
||||
value: "E387",
|
||||
enumerable: false,
|
||||
configurable: true
|
||||
});
|
||||
}
|
||||
const isModule = typeof src !== 'string';
|
||||
options = options || {};
|
||||
if (options == null ? void 0 : (_options_jsc = options.jsc) == null ? void 0 : _options_jsc.parser) {
|
||||
options.jsc.parser.syntax = options.jsc.parser.syntax ?? 'ecmascript';
|
||||
}
|
||||
return bindings.transformSync(isModule ? JSON.stringify(src) : src, isModule, toBuffer(options));
|
||||
},
|
||||
minify (src, options) {
|
||||
return bindings.minify(toBuffer(src), toBuffer(options ?? {}));
|
||||
},
|
||||
minifySync (src, options) {
|
||||
return bindings.minifySync(toBuffer(src), toBuffer(options ?? {}));
|
||||
},
|
||||
parse (src, options) {
|
||||
return bindings.parse(src, toBuffer(options ?? {}));
|
||||
},
|
||||
getTargetTriple: bindings.getTargetTriple,
|
||||
initCustomTraceSubscriber: bindings.initCustomTraceSubscriber,
|
||||
teardownTraceSubscriber: bindings.teardownTraceSubscriber,
|
||||
turbo: {
|
||||
createProject: bindingToApi(customBindings ?? bindings, false),
|
||||
startTurbopackTraceServer (traceFilePath) {
|
||||
Log.warn('Turbopack trace server started. View trace at https://turbo-trace-viewer.vercel.app/');
|
||||
(customBindings ?? bindings).startTurbopackTraceServer(traceFilePath);
|
||||
}
|
||||
},
|
||||
mdx: {
|
||||
compile (src, options) {
|
||||
return bindings.mdxCompile(src, toBuffer(getMdxOptions(options)));
|
||||
},
|
||||
compileSync (src, options) {
|
||||
bindings.mdxCompileSync(src, toBuffer(getMdxOptions(options)));
|
||||
}
|
||||
},
|
||||
css: {
|
||||
lightning: {
|
||||
transform (transformOptions) {
|
||||
return bindings.lightningCssTransform(transformOptions);
|
||||
},
|
||||
transformStyleAttr (transformAttrOptions) {
|
||||
return bindings.lightningCssTransformStyleAttribute(transformAttrOptions);
|
||||
}
|
||||
}
|
||||
},
|
||||
reactCompiler: {
|
||||
isReactCompilerRequired: (filename)=>{
|
||||
return bindings.isReactCompilerRequired(filename);
|
||||
}
|
||||
}
|
||||
};
|
||||
return nativeBindings;
|
||||
}
|
||||
throw attempts;
|
||||
}
|
||||
/// Build a mdx options object contains default values that
|
||||
/// can be parsed with serde_wasm_bindgen.
|
||||
function getMdxOptions(options = {}) {
|
||||
return {
|
||||
...options,
|
||||
development: options.development ?? false,
|
||||
jsx: options.jsx ?? false,
|
||||
mdxType: options.mdxType ?? 'commonMark'
|
||||
};
|
||||
}
|
||||
function toBuffer(t) {
|
||||
return Buffer.from(JSON.stringify(t));
|
||||
}
|
||||
export async function isWasm() {
|
||||
let bindings = await loadBindings();
|
||||
return bindings.isWasm;
|
||||
}
|
||||
export async function transform(src, options) {
|
||||
let bindings = await loadBindings();
|
||||
return bindings.transform(src, options);
|
||||
}
|
||||
export function transformSync(src, options) {
|
||||
let bindings = loadBindingsSync();
|
||||
return bindings.transformSync(src, options);
|
||||
}
|
||||
export async function minify(src, options) {
|
||||
let bindings = await loadBindings();
|
||||
return bindings.minify(src, options);
|
||||
}
|
||||
export async function isReactCompilerRequired(filename) {
|
||||
let bindings = await loadBindings();
|
||||
return bindings.reactCompiler.isReactCompilerRequired(filename);
|
||||
}
|
||||
export async function parse(src, options) {
|
||||
let bindings = await loadBindings();
|
||||
let parserOptions = getParserOptions(options);
|
||||
return bindings.parse(src, parserOptions).then((astStr)=>JSON.parse(astStr));
|
||||
}
|
||||
export function getBinaryMetadata() {
|
||||
var _bindings_getTargetTriple;
|
||||
let bindings;
|
||||
try {
|
||||
bindings = loadNative();
|
||||
} catch (e) {
|
||||
// Suppress exceptions, this fn allows to fail to load native bindings
|
||||
}
|
||||
return {
|
||||
target: bindings == null ? void 0 : (_bindings_getTargetTriple = bindings.getTargetTriple) == null ? void 0 : _bindings_getTargetTriple.call(bindings)
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Initialize trace subscriber to emit traces.
|
||||
*
|
||||
*/ export function initCustomTraceSubscriber(traceFileName) {
|
||||
if (swcTraceFlushGuard) {
|
||||
// Wasm binary doesn't support trace emission
|
||||
let bindings = loadNative();
|
||||
swcTraceFlushGuard = bindings.initCustomTraceSubscriber == null ? void 0 : bindings.initCustomTraceSubscriber.call(bindings, traceFileName);
|
||||
}
|
||||
}
|
||||
function once(fn) {
|
||||
let executed = false;
|
||||
return function() {
|
||||
if (!executed) {
|
||||
executed = true;
|
||||
fn();
|
||||
}
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Teardown swc's trace subscriber if there's an initialized flush guard exists.
|
||||
*
|
||||
* This is workaround to amend behavior with process.exit
|
||||
* (https://github.com/vercel/next.js/blob/4db8c49cc31e4fc182391fae6903fb5ef4e8c66e/packages/next/bin/next.ts#L134=)
|
||||
* seems preventing napi's cleanup hook execution (https://github.com/swc-project/swc/blob/main/crates/node/src/util.rs#L48-L51=),
|
||||
*
|
||||
* instead parent process manually drops guard when process gets signal to exit.
|
||||
*/ export const teardownTraceSubscriber = once(()=>{
|
||||
try {
|
||||
let bindings = loadNative();
|
||||
if (swcTraceFlushGuard) {
|
||||
bindings.teardownTraceSubscriber == null ? void 0 : bindings.teardownTraceSubscriber.call(bindings, swcTraceFlushGuard);
|
||||
}
|
||||
} catch (e) {
|
||||
// Suppress exceptions, this fn allows to fail to load native bindings
|
||||
}
|
||||
});
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/build/swc/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-use-before-define */\nimport path from 'path'\nimport { pathToFileURL } from 'url'\nimport { arch, platform } from 'os'\nimport { platformArchTriples } from 'next/dist/compiled/@napi-rs/triples'\nimport * as Log from '../output/log'\nimport { getParserOptions } from './options'\nimport { eventSwcLoadFailure } from '../../telemetry/events/swc-load-failure'\nimport { patchIncorrectLockfile } from '../../lib/patch-incorrect-lockfile'\nimport { downloadNativeNextSwc, downloadWasmSwc } from '../../lib/download-swc'\nimport type {\n NextConfigComplete,\n TurbopackLoaderItem,\n TurbopackRuleConfigItem,\n TurbopackRuleConfigItemOptions,\n TurbopackRuleConfigItemOrShortcut,\n} from '../../server/config-shared'\nimport { isDeepStrictEqual } from 'util'\nimport {\n type DefineEnvPluginOptions,\n getDefineEnv,\n} from '../webpack/plugins/define-env-plugin'\nimport { getReactCompilerLoader } from '../get-babel-loader-config'\nimport type {\n NapiPartialProjectOptions,\n NapiProjectOptions,\n} from './generated-native'\nimport type {\n Binding,\n DefineEnv,\n Endpoint,\n HmrIdentifiers,\n Project,\n ProjectOptions,\n RawEntrypoints,\n Route,\n TurboEngineOptions,\n TurbopackResult,\n TurbopackStackFrame,\n Update,\n UpdateMessage,\n WrittenEndpoint,\n} from './types'\nimport { TurbopackInternalError } from '../../shared/lib/turbopack/utils'\n\ntype RawBindings = typeof import('./generated-native')\ntype RawWasmBindings = typeof import('./generated-wasm') & {\n default?(): Promise<typeof import('./generated-wasm')>\n}\n\nconst nextVersion = process.env.__NEXT_VERSION as string\n\nconst ArchName = arch()\nconst PlatformName = platform()\n\nfunction infoLog(...args: any[]) {\n if (process.env.NEXT_PRIVATE_BUILD_WORKER) {\n return\n }\n if (process.env.DEBUG) {\n Log.info(...args)\n }\n}\n\n/**\n * Based on napi-rs's target triples, returns triples that have corresponding next-swc binaries.\n */\nexport function getSupportedArchTriples(): Record<string, any> {\n const { darwin, win32, linux, freebsd, android } = platformArchTriples\n\n return {\n darwin,\n win32: {\n arm64: win32.arm64,\n ia32: win32.ia32.filter((triple) => triple.abi === 'msvc'),\n x64: win32.x64.filter((triple) => triple.abi === 'msvc'),\n },\n linux: {\n // linux[x64] includes `gnux32` abi, with x64 arch.\n x64: linux.x64.filter((triple) => triple.abi !== 'gnux32'),\n arm64: linux.arm64,\n // This target is being deprecated, however we keep it in `knownDefaultWasmFallbackTriples` for now\n arm: linux.arm,\n },\n // Below targets are being deprecated, however we keep it in `knownDefaultWasmFallbackTriples` for now\n freebsd: {\n x64: freebsd.x64,\n },\n android: {\n arm64: android.arm64,\n arm: android.arm,\n },\n }\n}\n\nconst triples = (() => {\n const supportedArchTriples = getSupportedArchTriples()\n const targetTriple = supportedArchTriples[PlatformName]?.[ArchName]\n\n // If we have supported triple, return it right away\n if (targetTriple) {\n return targetTriple\n }\n\n // If there isn't corresponding target triple in `supportedArchTriples`, check if it's excluded from original raw triples\n // Otherwise, it is completely unsupported platforms.\n let rawTargetTriple = platformArchTriples[PlatformName]?.[ArchName]\n\n if (rawTargetTriple) {\n Log.warn(\n `Trying to load next-swc for target triple ${rawTargetTriple}, but there next-swc does not have native bindings support`\n )\n } else {\n Log.warn(\n `Trying to load next-swc for unsupported platforms ${PlatformName}/${ArchName}`\n )\n }\n\n return []\n})()\n\n// Allow to specify an absolute path to the custom turbopack binary to load.\n// If one of env variables is set, `loadNative` will try to use specified\n// binary instead. This is thin, naive interface\n// - `loadBindings` will not validate neither path nor the binary.\n//\n// Note these are internal flag: there's no stability, feature guarantee.\nconst __INTERNAL_CUSTOM_TURBOPACK_BINDINGS =\n process.env.__INTERNAL_CUSTOM_TURBOPACK_BINDINGS\n\nfunction checkVersionMismatch(pkgData: any) {\n const version = pkgData.version\n\n if (version && version !== nextVersion) {\n Log.warn(\n `Mismatching @next/swc version, detected: ${version} while Next.js is on ${nextVersion}. Please ensure these match`\n )\n }\n}\n\n// These are the platforms we'll try to load wasm bindings first,\n// only try to load native bindings if loading wasm binding somehow fails.\n// Fallback to native binding is for migration period only,\n// once we can verify loading-wasm-first won't cause visible regressions,\n// we'll not include native bindings for these platform at all.\nconst knownDefaultWasmFallbackTriples = [\n 'x86_64-unknown-freebsd',\n 'aarch64-linux-android',\n 'arm-linuLine truncated
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
Copyright (c) 2021 The swc Project Developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
||||
*/ import vm from 'vm';
|
||||
import { transformSync } from './index';
|
||||
import { getJestSWCOptions } from './options';
|
||||
// Jest use the `vm` [Module API](https://nodejs.org/api/vm.html#vm_class_vm_module) for ESM.
|
||||
// see https://github.com/facebook/jest/issues/9430
|
||||
const isSupportEsm = 'Module' in vm;
|
||||
function getJestConfig(jestConfig) {
|
||||
return 'config' in jestConfig ? jestConfig.config : jestConfig;
|
||||
}
|
||||
function isEsm(isEsmProject, filename, jestConfig) {
|
||||
var _jestConfig_extensionsToTreatAsEsm;
|
||||
return /\.jsx?$/.test(filename) && isEsmProject || ((_jestConfig_extensionsToTreatAsEsm = jestConfig.extensionsToTreatAsEsm) == null ? void 0 : _jestConfig_extensionsToTreatAsEsm.some((ext)=>filename.endsWith(ext)));
|
||||
}
|
||||
const createTransformer = (inputOptions)=>({
|
||||
process (src, filename, jestOptions) {
|
||||
const jestConfig = getJestConfig(jestOptions);
|
||||
const swcTransformOpts = getJestSWCOptions({
|
||||
isServer: jestConfig.testEnvironment === 'node' || jestConfig.testEnvironment.includes('jest-environment-node'),
|
||||
filename,
|
||||
jsConfig: inputOptions == null ? void 0 : inputOptions.jsConfig,
|
||||
resolvedBaseUrl: inputOptions == null ? void 0 : inputOptions.resolvedBaseUrl,
|
||||
pagesDir: inputOptions == null ? void 0 : inputOptions.pagesDir,
|
||||
serverComponents: inputOptions == null ? void 0 : inputOptions.serverComponents,
|
||||
modularizeImports: inputOptions == null ? void 0 : inputOptions.modularizeImports,
|
||||
swcPlugins: inputOptions == null ? void 0 : inputOptions.swcPlugins,
|
||||
compilerOptions: inputOptions == null ? void 0 : inputOptions.compilerOptions,
|
||||
serverReferenceHashSalt: '',
|
||||
esm: isSupportEsm && isEsm(Boolean(inputOptions == null ? void 0 : inputOptions.isEsmProject), filename, jestConfig)
|
||||
});
|
||||
return transformSync(src, {
|
||||
...swcTransformOpts,
|
||||
filename
|
||||
});
|
||||
}
|
||||
});
|
||||
module.exports = {
|
||||
createTransformer
|
||||
};
|
||||
|
||||
//# sourceMappingURL=jest-transformer.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/build/swc/jest-transformer.ts"],"sourcesContent":["/*\nCopyright (c) 2021 The swc Project Developers\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n*/\n\nimport vm from 'vm'\nimport { transformSync } from './index'\nimport { getJestSWCOptions } from './options'\nimport type {\n TransformerCreator,\n TransformOptions,\n SyncTransformer,\n} from '@jest/transform'\nimport type { Config } from '@jest/types'\nimport type { NextConfig, ExperimentalConfig } from '../../server/config-shared'\nimport type { ResolvedBaseUrl } from '../load-jsconfig'\n\ntype TransformerConfig = Config.TransformerConfig[1]\nexport interface JestTransformerConfig extends TransformerConfig {\n jsConfig: any\n resolvedBaseUrl?: ResolvedBaseUrl\n pagesDir?: string\n serverComponents?: boolean\n isEsmProject: boolean\n modularizeImports?: NextConfig['modularizeImports']\n swcPlugins: ExperimentalConfig['swcPlugins']\n compilerOptions: NextConfig['compiler']\n}\n\n// Jest use the `vm` [Module API](https://nodejs.org/api/vm.html#vm_class_vm_module) for ESM.\n// see https://github.com/facebook/jest/issues/9430\nconst isSupportEsm = 'Module' in vm\n\nfunction getJestConfig(\n jestConfig: TransformOptions<JestTransformerConfig>\n): Config.ProjectConfig {\n return 'config' in jestConfig\n ? // jest 27\n jestConfig.config\n : // jest 26\n (jestConfig as unknown as Config.ProjectConfig)\n}\n\nfunction isEsm(\n isEsmProject: boolean,\n filename: string,\n jestConfig: Config.ProjectConfig\n): boolean {\n return (\n (/\\.jsx?$/.test(filename) && isEsmProject) ||\n jestConfig.extensionsToTreatAsEsm?.some((ext: any) =>\n filename.endsWith(ext)\n )\n )\n}\n\nconst createTransformer: TransformerCreator<\n SyncTransformer<JestTransformerConfig>,\n JestTransformerConfig\n> = (inputOptions) => ({\n process(src, filename, jestOptions) {\n const jestConfig = getJestConfig(jestOptions)\n\n const swcTransformOpts = getJestSWCOptions({\n isServer:\n jestConfig.testEnvironment === 'node' ||\n jestConfig.testEnvironment.includes('jest-environment-node'),\n filename,\n jsConfig: inputOptions?.jsConfig,\n resolvedBaseUrl: inputOptions?.resolvedBaseUrl,\n pagesDir: inputOptions?.pagesDir,\n serverComponents: inputOptions?.serverComponents,\n modularizeImports: inputOptions?.modularizeImports,\n swcPlugins: inputOptions?.swcPlugins,\n compilerOptions: inputOptions?.compilerOptions,\n serverReferenceHashSalt: '',\n esm:\n isSupportEsm &&\n isEsm(Boolean(inputOptions?.isEsmProject), filename, jestConfig),\n })\n\n return transformSync(src, { ...swcTransformOpts, filename })\n },\n})\n\nmodule.exports = { createTransformer }\n"],"names":["vm","transformSync","getJestSWCOptions","isSupportEsm","getJestConfig","jestConfig","config","isEsm","isEsmProject","filename","test","extensionsToTreatAsEsm","some","ext","endsWith","createTransformer","inputOptions","process","src","jestOptions","swcTransformOpts","isServer","testEnvironment","includes","jsConfig","resolvedBaseUrl","pagesDir","serverComponents","modularizeImports","swcPlugins","compilerOptions","serverReferenceHashSalt","esm","Boolean","module","exports"],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,GAEA,OAAOA,QAAQ,KAAI;AACnB,SAASC,aAAa,QAAQ,UAAS;AACvC,SAASC,iBAAiB,QAAQ,YAAW;AAsB7C,6FAA6F;AAC7F,mDAAmD;AACnD,MAAMC,eAAe,YAAYH;AAEjC,SAASI,cACPC,UAAmD;IAEnD,OAAO,YAAYA,aAEfA,WAAWC,MAAM,GAEhBD;AACP;AAEA,SAASE,MACPC,YAAqB,EACrBC,QAAgB,EAChBJ,UAAgC;QAI9BA;IAFF,OACE,AAAC,UAAUK,IAAI,CAACD,aAAaD,kBAC7BH,qCAAAA,WAAWM,sBAAsB,qBAAjCN,mCAAmCO,IAAI,CAAC,CAACC,MACvCJ,SAASK,QAAQ,CAACD;AAGxB;AAEA,MAAME,oBAGF,CAACC,eAAkB,CAAA;QACrBC,SAAQC,GAAG,EAAET,QAAQ,EAAEU,WAAW;YAChC,MAAMd,aAAaD,cAAce;YAEjC,MAAMC,mBAAmBlB,kBAAkB;gBACzCmB,UACEhB,WAAWiB,eAAe,KAAK,UAC/BjB,WAAWiB,eAAe,CAACC,QAAQ,CAAC;gBACtCd;gBACAe,QAAQ,EAAER,gCAAAA,aAAcQ,QAAQ;gBAChCC,eAAe,EAAET,gCAAAA,aAAcS,eAAe;gBALine truncated
|
||||
+354
@@ -0,0 +1,354 @@
|
||||
import path from 'path';
|
||||
import { WEBPACK_LAYERS } from '../../lib/constants';
|
||||
import { isWebpackServerOnlyLayer, isWebpackAppPagesLayer } from '../utils';
|
||||
import { escapeStringRegexp } from '../../shared/lib/escape-regexp';
|
||||
const nextDirname = path.dirname(require.resolve('next/package.json'));
|
||||
const nextDistPath = new RegExp(`${escapeStringRegexp(nextDirname)}[\\/]dist[\\/](shared[\\/]lib|client|pages)`);
|
||||
const nodeModulesPath = /[\\/]node_modules[\\/]/;
|
||||
const regeneratorRuntimePath = require.resolve('next/dist/compiled/regenerator-runtime');
|
||||
function isTypeScriptFile(filename) {
|
||||
return filename.endsWith('.ts') || filename.endsWith('.tsx');
|
||||
}
|
||||
function isCommonJSFile(filename) {
|
||||
return filename.endsWith('.cjs');
|
||||
}
|
||||
// Ensure Next.js internals and .cjs files are output as CJS modules,
|
||||
// By default all modules are output as ESM or will treated as CJS if next-swc/auto-cjs plugin detects file is CJS.
|
||||
function shouldOutputCommonJs(filename) {
|
||||
return isCommonJSFile(filename) || nextDistPath.test(filename);
|
||||
}
|
||||
export function getParserOptions({ filename, jsConfig, ...rest }) {
|
||||
var _jsConfig_compilerOptions;
|
||||
const isTSFile = filename.endsWith('.ts');
|
||||
const hasTsSyntax = isTypeScriptFile(filename);
|
||||
const enableDecorators = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions.experimentalDecorators);
|
||||
return {
|
||||
...rest,
|
||||
syntax: hasTsSyntax ? 'typescript' : 'ecmascript',
|
||||
dynamicImport: true,
|
||||
decorators: enableDecorators,
|
||||
// Exclude regular TypeScript files from React transformation to prevent e.g. generic parameters and angle-bracket type assertion from being interpreted as JSX tags.
|
||||
[hasTsSyntax ? 'tsx' : 'jsx']: !isTSFile,
|
||||
importAssertions: true
|
||||
};
|
||||
}
|
||||
function getBaseSWCOptions({ filename, jest, development, hasReactRefresh, globalWindow, esm, modularizeImports, swcPlugins, compilerOptions, resolvedBaseUrl, jsConfig, supportedBrowsers, swcCacheDir, serverComponents, serverReferenceHashSalt, bundleLayer, isDynamicIo, cacheHandlers, useCacheEnabled }) {
|
||||
var _jsConfig_compilerOptions, _jsConfig_compilerOptions1, _jsConfig_compilerOptions2, _jsConfig_compilerOptions3, _jsConfig_compilerOptions4, _jsConfig_experimental;
|
||||
const isReactServerLayer = isWebpackServerOnlyLayer(bundleLayer);
|
||||
const isAppRouterPagesLayer = isWebpackAppPagesLayer(bundleLayer);
|
||||
const parserConfig = getParserOptions({
|
||||
filename,
|
||||
jsConfig
|
||||
});
|
||||
const paths = jsConfig == null ? void 0 : (_jsConfig_compilerOptions = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions.paths;
|
||||
const enableDecorators = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions1 = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions1.experimentalDecorators);
|
||||
const emitDecoratorMetadata = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions2 = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions2.emitDecoratorMetadata);
|
||||
const useDefineForClassFields = Boolean(jsConfig == null ? void 0 : (_jsConfig_compilerOptions3 = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions3.useDefineForClassFields);
|
||||
const plugins = (swcPlugins ?? []).filter(Array.isArray).map(([name, options])=>[
|
||||
require.resolve(name),
|
||||
options
|
||||
]);
|
||||
return {
|
||||
jsc: {
|
||||
...resolvedBaseUrl && paths ? {
|
||||
baseUrl: resolvedBaseUrl.baseUrl,
|
||||
paths
|
||||
} : {},
|
||||
externalHelpers: !process.versions.pnp && !jest,
|
||||
parser: parserConfig,
|
||||
experimental: {
|
||||
keepImportAttributes: true,
|
||||
emitAssertForImportAttributes: true,
|
||||
plugins,
|
||||
cacheRoot: swcCacheDir
|
||||
},
|
||||
transform: {
|
||||
// Enables https://github.com/swc-project/swc/blob/0359deb4841be743d73db4536d4a22ac797d7f65/crates/swc_ecma_ext_transforms/src/jest.rs
|
||||
...jest ? {
|
||||
hidden: {
|
||||
jest: true
|
||||
}
|
||||
} : {},
|
||||
legacyDecorator: enableDecorators,
|
||||
decoratorMetadata: emitDecoratorMetadata,
|
||||
useDefineForClassFields: useDefineForClassFields,
|
||||
react: {
|
||||
importSource: (jsConfig == null ? void 0 : (_jsConfig_compilerOptions4 = jsConfig.compilerOptions) == null ? void 0 : _jsConfig_compilerOptions4.jsxImportSource) ?? ((compilerOptions == null ? void 0 : compilerOptions.emotion) && !isReactServerLayer ? '@emotion/react' : 'react'),
|
||||
runtime: 'automatic',
|
||||
pragmaFrag: 'React.Fragment',
|
||||
throwIfNamespace: true,
|
||||
development: !!development,
|
||||
useBuiltins: true,
|
||||
refresh: !!hasReactRefresh
|
||||
},
|
||||
optimizer: {
|
||||
simplify: false,
|
||||
globals: jest ? null : {
|
||||
typeofs: {
|
||||
window: globalWindow ? 'object' : 'undefined'
|
||||
},
|
||||
envs: {
|
||||
NODE_ENV: development ? '"development"' : '"production"'
|
||||
}
|
||||
}
|
||||
},
|
||||
regenerator: {
|
||||
importPath: regeneratorRuntimePath
|
||||
}
|
||||
}
|
||||
},
|
||||
sourceMaps: jest ? 'inline' : undefined,
|
||||
removeConsole: compilerOptions == null ? void 0 : compilerOptions.removeConsole,
|
||||
// disable "reactRemoveProperties" when "jest" is true
|
||||
// otherwise the setting from next.config.js will be used
|
||||
reactRemoveProperties: jest ? false : compilerOptions == null ? void 0 : compilerOptions.reactRemoveProperties,
|
||||
// Map the k-v map to an array of pairs.
|
||||
modularizeImports: modularizeImports ? Object.fromEntries(Object.entries(modularizeImports).map(([mod, config])=>[
|
||||
mod,
|
||||
{
|
||||
...config,
|
||||
transform: typeof config.transform === 'string' ? config.transform : Object.entries(config.transform).map(([key, value])=>[
|
||||
key,
|
||||
value
|
||||
])
|
||||
}
|
||||
])) : undefined,
|
||||
relay: compilerOptions == null ? void 0 : compilerOptions.relay,
|
||||
// Always transform styled-jsx and error when `client-only` condition is triggered
|
||||
styledJsx: (compilerOptions == null ? void 0 : compilerOptions.styledJsx) ?? {
|
||||
useLightningcss: (jsConfig == null ? void 0 : (_jsConfig_experimental = jsConfig.experimental) == null ? void 0 : _jsConfig_experimental.useLightningcss) ?? false
|
||||
},
|
||||
// Disable css-in-js libs (without client-only integration) transform on server layer for server components
|
||||
...!isReactServerLayer && {
|
||||
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
||||
emotion: getEmotionOptions(compilerOptions == null ? void 0 : compilerOptions.emotion, development),
|
||||
// eslint-disable-next-line @typescript-eslint/no-use-before-define
|
||||
styledComponents: getStyledComponentsOptions(compilerOptions == null ? void 0 : compilerOptions.styledComponents, development)
|
||||
},
|
||||
serverComponents: serverComponents && !jest ? {
|
||||
isReactServerLayer,
|
||||
dynamicIoEnabled: isDynamicIo,
|
||||
useCacheEnabled
|
||||
} : undefined,
|
||||
serverActions: isAppRouterPagesLayer && !jest ? {
|
||||
isReactServerLayer,
|
||||
isDevelopment: development,
|
||||
useCacheEnabled,
|
||||
hashSalt: serverReferenceHashSalt,
|
||||
cacheKinds: [
|
||||
'default',
|
||||
'remote'
|
||||
].concat(cacheHandlers ? Object.keys(cacheHandlers) : [])
|
||||
} : undefined,
|
||||
// For app router we prefer to bundle ESM,
|
||||
// On server side of pages router we prefer CJS.
|
||||
preferEsm: esm,
|
||||
lintCodemodComments: true,
|
||||
debugFunctionName: development,
|
||||
...supportedBrowsers && supportedBrowsers.length > 0 ? {
|
||||
cssEnv: {
|
||||
targets: supportedBrowsers
|
||||
}
|
||||
} : {}
|
||||
};
|
||||
}
|
||||
function getStyledComponentsOptions(styledComponentsConfig, development) {
|
||||
if (!styledComponentsConfig) {
|
||||
return null;
|
||||
} else if (typeof styledComponentsConfig === 'object') {
|
||||
return {
|
||||
...styledComponentsConfig,
|
||||
displayName: styledComponentsConfig.displayName ?? Boolean(development)
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
displayName: Boolean(development)
|
||||
};
|
||||
}
|
||||
}
|
||||
function getEmotionOptions(emotionConfig, development) {
|
||||
if (!emotionConfig) {
|
||||
return null;
|
||||
}
|
||||
let autoLabel = !!development;
|
||||
switch(typeof emotionConfig === 'object' && emotionConfig.autoLabel){
|
||||
case 'never':
|
||||
autoLabel = false;
|
||||
break;
|
||||
case 'always':
|
||||
autoLabel = true;
|
||||
break;
|
||||
case 'dev-only':
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return {
|
||||
enabled: true,
|
||||
autoLabel,
|
||||
sourcemap: development,
|
||||
...typeof emotionConfig === 'object' && {
|
||||
importMap: emotionConfig.importMap,
|
||||
labelFormat: emotionConfig.labelFormat,
|
||||
sourcemap: development && emotionConfig.sourceMap
|
||||
}
|
||||
};
|
||||
}
|
||||
export function getJestSWCOptions({ isServer, filename, esm, modularizeImports, swcPlugins, compilerOptions, jsConfig, resolvedBaseUrl, pagesDir, serverReferenceHashSalt }) {
|
||||
let baseOptions = getBaseSWCOptions({
|
||||
filename,
|
||||
jest: true,
|
||||
development: false,
|
||||
hasReactRefresh: false,
|
||||
globalWindow: !isServer,
|
||||
modularizeImports,
|
||||
swcPlugins,
|
||||
compilerOptions,
|
||||
jsConfig,
|
||||
resolvedBaseUrl,
|
||||
supportedBrowsers: undefined,
|
||||
esm,
|
||||
// Don't apply server layer transformations for Jest
|
||||
// Disable server / client graph assertions for Jest
|
||||
bundleLayer: undefined,
|
||||
serverComponents: false,
|
||||
serverReferenceHashSalt
|
||||
});
|
||||
const useCjsModules = shouldOutputCommonJs(filename);
|
||||
return {
|
||||
...baseOptions,
|
||||
env: {
|
||||
targets: {
|
||||
// Targets the current version of Node.js
|
||||
node: process.versions.node
|
||||
}
|
||||
},
|
||||
module: {
|
||||
type: esm && !useCjsModules ? 'es6' : 'commonjs'
|
||||
},
|
||||
disableNextSsg: true,
|
||||
disablePageConfig: true,
|
||||
pagesDir
|
||||
};
|
||||
}
|
||||
export function getLoaderSWCOptions({ // This is not passed yet as "paths" resolving is handled by webpack currently.
|
||||
// resolvedBaseUrl,
|
||||
filename, development, isServer, pagesDir, appDir, isPageFile, isDynamicIo, hasReactRefresh, modularizeImports, optimizeServerReact, optimizePackageImports, swcPlugins, compilerOptions, jsConfig, supportedBrowsers, swcCacheDir, relativeFilePathFromRoot, serverComponents, serverReferenceHashSalt, bundleLayer, esm, cacheHandlers, useCacheEnabled }) {
|
||||
let baseOptions = getBaseSWCOptions({
|
||||
filename,
|
||||
development,
|
||||
globalWindow: !isServer,
|
||||
hasReactRefresh,
|
||||
modularizeImports,
|
||||
swcPlugins,
|
||||
compilerOptions,
|
||||
jsConfig,
|
||||
// resolvedBaseUrl,
|
||||
supportedBrowsers,
|
||||
swcCacheDir,
|
||||
bundleLayer,
|
||||
serverComponents,
|
||||
serverReferenceHashSalt,
|
||||
esm: !!esm,
|
||||
isDynamicIo,
|
||||
cacheHandlers,
|
||||
useCacheEnabled
|
||||
});
|
||||
baseOptions.fontLoaders = {
|
||||
fontLoaders: [
|
||||
'next/font/local',
|
||||
'next/font/google'
|
||||
],
|
||||
relativeFilePathFromRoot
|
||||
};
|
||||
baseOptions.cjsRequireOptimizer = {
|
||||
packages: {
|
||||
'next/server': {
|
||||
transforms: {
|
||||
NextRequest: 'next/dist/server/web/spec-extension/request',
|
||||
NextResponse: 'next/dist/server/web/spec-extension/response',
|
||||
ImageResponse: 'next/dist/server/web/spec-extension/image-response',
|
||||
userAgentFromString: 'next/dist/server/web/spec-extension/user-agent',
|
||||
userAgent: 'next/dist/server/web/spec-extension/user-agent'
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
if (optimizeServerReact && isServer && !development) {
|
||||
baseOptions.optimizeServerReact = {
|
||||
optimize_use_state: false
|
||||
};
|
||||
}
|
||||
// Modularize import optimization for barrel files
|
||||
if (optimizePackageImports) {
|
||||
baseOptions.autoModularizeImports = {
|
||||
packages: optimizePackageImports
|
||||
};
|
||||
}
|
||||
const isNodeModules = nodeModulesPath.test(filename);
|
||||
const isAppBrowserLayer = bundleLayer === WEBPACK_LAYERS.appPagesBrowser;
|
||||
const moduleResolutionConfig = shouldOutputCommonJs(filename) ? {
|
||||
module: {
|
||||
type: 'commonjs'
|
||||
}
|
||||
} : {};
|
||||
let options;
|
||||
if (isServer) {
|
||||
options = {
|
||||
...baseOptions,
|
||||
...moduleResolutionConfig,
|
||||
// Disables getStaticProps/getServerSideProps tree shaking on the server compilation for pages
|
||||
disableNextSsg: true,
|
||||
disablePageConfig: true,
|
||||
isDevelopment: development,
|
||||
isServerCompiler: isServer,
|
||||
pagesDir,
|
||||
appDir,
|
||||
preferEsm: !!esm,
|
||||
isPageFile,
|
||||
env: {
|
||||
targets: {
|
||||
// Targets the current version of Node.js
|
||||
node: process.versions.node
|
||||
}
|
||||
}
|
||||
};
|
||||
} else {
|
||||
options = {
|
||||
...baseOptions,
|
||||
...moduleResolutionConfig,
|
||||
disableNextSsg: !isPageFile,
|
||||
isDevelopment: development,
|
||||
isServerCompiler: isServer,
|
||||
pagesDir,
|
||||
appDir,
|
||||
isPageFile,
|
||||
...supportedBrowsers && supportedBrowsers.length > 0 ? {
|
||||
env: {
|
||||
targets: supportedBrowsers
|
||||
}
|
||||
} : {}
|
||||
};
|
||||
if (!options.env) {
|
||||
// Matches default @babel/preset-env behavior
|
||||
options.jsc.target = 'es5';
|
||||
}
|
||||
}
|
||||
// For node_modules in app browser layer, we don't need to do any server side transformation.
|
||||
// Only keep server actions transform to discover server actions from client components.
|
||||
if (isAppBrowserLayer && isNodeModules) {
|
||||
var _options_jsc_transform_optimizer_globals;
|
||||
options.disableNextSsg = true;
|
||||
options.disablePageConfig = true;
|
||||
options.isPageFile = false;
|
||||
options.optimizeServerReact = undefined;
|
||||
options.cjsRequireOptimizer = undefined;
|
||||
// Disable optimizer for node_modules in app browser layer, to avoid unnecessary replacement.
|
||||
// e.g. typeof window could result differently in js worker or browser.
|
||||
if (((_options_jsc_transform_optimizer_globals = options.jsc.transform.optimizer.globals) == null ? void 0 : _options_jsc_transform_optimizer_globals.typeofs) && !filename.includes(nextDirname)) {
|
||||
delete options.jsc.transform.optimizer.globals.typeofs.window;
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
//# sourceMappingURL=options.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/build/swc/options.ts"],"sourcesContent":["import path from 'path'\nimport { WEBPACK_LAYERS, type WebpackLayerName } from '../../lib/constants'\nimport type {\n NextConfig,\n ExperimentalConfig,\n EmotionConfig,\n StyledComponentsConfig,\n} from '../../server/config-shared'\nimport type { ResolvedBaseUrl } from '../load-jsconfig'\nimport { isWebpackServerOnlyLayer, isWebpackAppPagesLayer } from '../utils'\nimport { escapeStringRegexp } from '../../shared/lib/escape-regexp'\n\nconst nextDirname = path.dirname(require.resolve('next/package.json'))\n\nconst nextDistPath = new RegExp(\n `${escapeStringRegexp(nextDirname)}[\\\\/]dist[\\\\/](shared[\\\\/]lib|client|pages)`\n)\n\nconst nodeModulesPath = /[\\\\/]node_modules[\\\\/]/\n\nconst regeneratorRuntimePath = require.resolve(\n 'next/dist/compiled/regenerator-runtime'\n)\n\nfunction isTypeScriptFile(filename: string) {\n return filename.endsWith('.ts') || filename.endsWith('.tsx')\n}\n\nfunction isCommonJSFile(filename: string) {\n return filename.endsWith('.cjs')\n}\n\n// Ensure Next.js internals and .cjs files are output as CJS modules,\n// By default all modules are output as ESM or will treated as CJS if next-swc/auto-cjs plugin detects file is CJS.\nfunction shouldOutputCommonJs(filename: string) {\n return isCommonJSFile(filename) || nextDistPath.test(filename)\n}\n\nexport function getParserOptions({ filename, jsConfig, ...rest }: any) {\n const isTSFile = filename.endsWith('.ts')\n const hasTsSyntax = isTypeScriptFile(filename)\n const enableDecorators = Boolean(\n jsConfig?.compilerOptions?.experimentalDecorators\n )\n return {\n ...rest,\n syntax: hasTsSyntax ? 'typescript' : 'ecmascript',\n dynamicImport: true,\n decorators: enableDecorators,\n // Exclude regular TypeScript files from React transformation to prevent e.g. generic parameters and angle-bracket type assertion from being interpreted as JSX tags.\n [hasTsSyntax ? 'tsx' : 'jsx']: !isTSFile,\n importAssertions: true,\n }\n}\n\nfunction getBaseSWCOptions({\n filename,\n jest,\n development,\n hasReactRefresh,\n globalWindow,\n esm,\n modularizeImports,\n swcPlugins,\n compilerOptions,\n resolvedBaseUrl,\n jsConfig,\n supportedBrowsers,\n swcCacheDir,\n serverComponents,\n serverReferenceHashSalt,\n bundleLayer,\n isDynamicIo,\n cacheHandlers,\n useCacheEnabled,\n}: {\n filename: string\n jest?: boolean\n development: boolean\n hasReactRefresh: boolean\n globalWindow: boolean\n esm: boolean\n modularizeImports?: NextConfig['modularizeImports']\n compilerOptions: NextConfig['compiler']\n swcPlugins: ExperimentalConfig['swcPlugins']\n resolvedBaseUrl?: ResolvedBaseUrl\n jsConfig: any\n supportedBrowsers: string[] | undefined\n swcCacheDir?: string\n serverComponents?: boolean\n serverReferenceHashSalt: string\n bundleLayer?: WebpackLayerName\n isDynamicIo?: boolean\n cacheHandlers?: ExperimentalConfig['cacheHandlers']\n useCacheEnabled?: boolean\n}) {\n const isReactServerLayer = isWebpackServerOnlyLayer(bundleLayer)\n const isAppRouterPagesLayer = isWebpackAppPagesLayer(bundleLayer)\n const parserConfig = getParserOptions({ filename, jsConfig })\n const paths = jsConfig?.compilerOptions?.paths\n const enableDecorators = Boolean(\n jsConfig?.compilerOptions?.experimentalDecorators\n )\n const emitDecoratorMetadata = Boolean(\n jsConfig?.compilerOptions?.emitDecoratorMetadata\n )\n const useDefineForClassFields = Boolean(\n jsConfig?.compilerOptions?.useDefineForClassFields\n )\n const plugins = (swcPlugins ?? [])\n .filter(Array.isArray)\n .map(([name, options]: any) => [require.resolve(name), options])\n\n return {\n jsc: {\n ...(resolvedBaseUrl && paths\n ? {\n baseUrl: resolvedBaseUrl.baseUrl,\n paths,\n }\n : {}),\n externalHelpers: !process.versions.pnp && !jest,\n parser: parserConfig,\n experimental: {\n keepImportAttributes: true,\n emitAssertForImportAttributes: true,\n plugins,\n cacheRoot: swcCacheDir,\n },\n transform: {\n // Enables https://github.com/swc-project/swc/blob/0359deb4841be743d73db4536d4a22ac797d7f65/crates/swc_ecma_ext_transforms/src/jest.rs\n ...(jest\n ? {\n hidden: {\n jest: true,\n },\n }\n : {}),\n legacyDecorator: enableDecorators,\n decoratorMetadata: emitDecoratorMetadata,\n useDefineForClassFields: useDefineForClassFields,\n react: {\n importSource:\n jsConfig?.compilerOptions?.jsxImportSource ??\n (compilerOptions?.emotion && !isReactServerLayer\n ? '@emotion/react'\n : 'react'),\n runtime: 'automatic',\n pragmaFrag: 'React.Fragment',\n throwIfNamespace: true,\n development: !!development,\n useBuiltins:Line truncated
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
export { };
|
||||
|
||||
//# sourceMappingURL=types.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/build/swc/types.ts"],"sourcesContent":["import type { NextConfigComplete } from '../../server/config-shared'\nimport type { __ApiPreviewProps } from '../../server/api-utils'\nimport type {\n ExternalObject,\n RefCell,\n NapiTurboEngineOptions,\n} from './generated-native'\n\nexport type { NapiTurboEngineOptions as TurboEngineOptions }\n\nexport interface Binding {\n isWasm: boolean\n turbo: {\n createProject(\n options: ProjectOptions,\n turboEngineOptions?: NapiTurboEngineOptions\n ): Promise<Project>\n startTurbopackTraceServer(traceFilePath: string): void\n\n nextBuild?: any\n }\n mdx: {\n compile(src: string, options: any): any\n compileSync(src: string, options: any): any\n }\n minify(src: string, options: any): Promise<any>\n minifySync(src: string, options: any): any\n transform(src: string, options: any): Promise<any>\n transformSync(src: string, options: any): any\n parse(src: string, options: any): Promise<string>\n\n getTargetTriple(): string | undefined\n\n initCustomTraceSubscriber?(traceOutFilePath?: string): ExternalObject<RefCell>\n teardownTraceSubscriber?(guardExternal: ExternalObject<RefCell>): void\n css: {\n lightning: {\n transform(transformOptions: any): Promise<any>\n transformStyleAttr(transformAttrOptions: any): Promise<any>\n }\n }\n\n reactCompiler: {\n isReactCompilerRequired(filename: string): Promise<boolean>\n }\n}\n\nexport type StyledString =\n | {\n type: 'text'\n value: string\n }\n | {\n type: 'code'\n value: string\n }\n | {\n type: 'strong'\n value: string\n }\n | {\n type: 'stack'\n value: StyledString[]\n }\n | {\n type: 'line'\n value: StyledString[]\n }\n\nexport interface Issue {\n severity: string\n stage: string\n filePath: string\n title: StyledString\n description?: StyledString\n detail?: StyledString\n source?: {\n source: {\n ident: string\n content?: string\n }\n range?: {\n start: {\n // 0-indexed\n line: number\n // 0-indexed\n column: number\n }\n end: {\n // 0-indexed\n line: number\n // 0-indexed\n column: number\n }\n }\n }\n documentationLink: string\n subIssues: Issue[]\n}\n\nexport interface Diagnostics {\n category: string\n name: string\n payload: unknown\n}\n\nexport type TurbopackResult<T = {}> = T & {\n issues: Issue[]\n diagnostics: Diagnostics[]\n}\n\nexport interface Middleware {\n endpoint: Endpoint\n}\n\nexport interface Instrumentation {\n nodeJs: Endpoint\n edge: Endpoint\n}\n\nexport interface RawEntrypoints {\n routes: Map<string, Route>\n middleware?: Middleware\n instrumentation?: Instrumentation\n pagesDocumentEndpoint: Endpoint\n pagesAppEndpoint: Endpoint\n pagesErrorEndpoint: Endpoint\n}\n\ninterface BaseUpdate {\n resource: {\n headers: unknown\n path: string\n }\n diagnostics: unknown[]\n issues: Issue[]\n}\n\ninterface IssuesUpdate extends BaseUpdate {\n type: 'issues'\n}\n\ninterface EcmascriptMergedUpdate {\n type: 'EcmascriptMergedUpdate'\n chunks: { [moduleName: string]: { type: 'partial' } }\n entries: { [moduleName: string]: { code: string; map: string; url: string } }\n}\n\ninterface PartialUpdate extends BaseUpdate {\n type: 'partial'\n instruction: {\n type: 'ChunkListUpdate'\n merged: EcmascriptMergedUpdate[] | undefined\n }\n}\n\nexport type Update = IssuesUpdate | PartialUpdate\n\nexport interface HmrIdentifiers {\n identifiers: string[]\n}\n\n/** @see https://github.com/vercel/next.js/blob/415cd74b9a220b6f50da64da68c13043e9b02995/packages/next-swc/crates/napi/src/next_api/project.rs#L824-L833 */\nexport interface TurbopackStackFrame {\n isServer: boolean\n isInternal?: boolean\n file: string\n originalFile?: string\n /** 1-indexed, unlike source map tokens */\n line?: number\n /** 1-indexed, unlike source map tokens */\n column?: number\n methodName?: string\n}\n\nexport type UpdateMessage =\n | {\n updateType: 'start'\n }\n | {\n updateType: 'end'\n value: UpdateInfo\n }\n\nexport interface UpdateInfo {\n duration: number\n tasks: number\n}\n\nexport interface Project {\n update(options: Partial<ProjectOptions>): Promise<void>\n\n writeAllEntrypointsToDisk(\n appDirOnly: boolean\n ): Promise<TurbopackResult<RawEntrypoints>>\n\n entrypointsSubscribe(): AsyncIterableIterator<TurbopackResult<RawEntrypoints>>\n\n hmrEvents(identifier: string): AsyncIterableIterator<TurbopackResult<Update>>\n\n hmrIdentifiersSubscribe(): AsyncIterableIterator<\n TurbopackResult<HmrIdentifiers>\n >\n\n getSourceForAsset(filePath: string): Promise<string | null>\n\n getSourceMap(filePath: string): Promise<string | null>\n getSourceMapSync(filePath: string): string | null\n\n traceSource(\n stackFrame: TurbopackStackFrame,\n currentDirectoryFileUrl: string\n ): PLine truncated
|
||||
Reference in new issue
Block a user