This commit is contained in:
Kismet Hasanaj
2026-05-02 20:07:02 +02:00
parent ce8672e283
commit 34dc9aec52
9428 changed files with 1733330 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
export declare function startTurboTraceServerCli(file: string, port: number | undefined): Promise<void>;
+17
View File
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "startTurboTraceServerCli", {
enumerable: true,
get: function() {
return startTurboTraceServerCli;
}
});
const _swc = require("../../build/swc");
async function startTurboTraceServerCli(file, port) {
let bindings = await (0, _swc.loadBindings)();
bindings.turbo.startTurbopackTraceServer(file, port);
}
//# sourceMappingURL=turbo-trace-server.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/cli/internal/turbo-trace-server.ts"],"sourcesContent":["import { loadBindings } from '../../build/swc'\n\nexport async function startTurboTraceServerCli(\n file: string,\n port: number | undefined\n) {\n let bindings = await loadBindings()\n bindings.turbo.startTurbopackTraceServer(file, port)\n}\n"],"names":["startTurboTraceServerCli","file","port","bindings","loadBindings","turbo","startTurbopackTraceServer"],"mappings":";;;;+BAEsBA;;;eAAAA;;;qBAFO;AAEtB,eAAeA,yBACpBC,IAAY,EACZC,IAAwB;IAExB,IAAIC,WAAW,MAAMC,IAAAA,iBAAY;IACjCD,SAASE,KAAK,CAACC,yBAAyB,CAACL,MAAMC;AACjD","ignoreList":[0]}
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env node
import '../server/lib/cpu-profile';
export type NextAnalyzeOptions = {
experimentalAnalyze?: boolean;
profile?: boolean;
mangling: boolean;
port: number;
output: boolean;
experimentalAppOnly?: boolean;
};
declare const nextAnalyze: (options: NextAnalyzeOptions, directory?: string) => Promise<void>;
export { nextAnalyze };
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "nextAnalyze", {
enumerable: true,
get: function() {
return nextAnalyze;
}
});
const _cpuprofile = require("../server/lib/cpu-profile");
const _fs = require("fs");
const _picocolors = require("../lib/picocolors");
const _analyze = /*#__PURE__*/ _interop_require_default(require("../build/analyze"));
const _log = require("../build/output/log");
const _utils = require("../server/lib/utils");
const _getprojectdir = require("../lib/get-project-dir");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const nextAnalyze = async (options, directory)=>{
process.on('SIGTERM', ()=>{
(0, _cpuprofile.saveCpuProfile)();
process.exit(143);
});
process.on('SIGINT', ()=>{
(0, _cpuprofile.saveCpuProfile)();
process.exit(130);
});
const { profile, mangling, experimentalAppOnly, output, port } = options;
if (!mangling) {
(0, _log.warn)(`Mangling is disabled. ${(0, _picocolors.italic)('Note: This may affect performance and should only be used for debugging purposes.')}`);
}
if (profile) {
(0, _log.warn)(`Profiling is enabled. ${(0, _picocolors.italic)('Note: This may affect performance.')}`);
}
const dir = (0, _getprojectdir.getProjectDir)(directory);
if (!(0, _fs.existsSync)(dir)) {
(0, _utils.printAndExit)(`> No such directory exists as the project root: ${dir}`);
}
return (0, _analyze.default)({
dir,
reactProductionProfiling: profile,
noMangling: !mangling,
appDirOnly: experimentalAppOnly,
output,
port
});
};
//# sourceMappingURL=next-analyze.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/cli/next-analyze.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport '../server/lib/cpu-profile'\nimport { saveCpuProfile } from '../server/lib/cpu-profile'\nimport { existsSync } from 'fs'\nimport { italic } from '../lib/picocolors'\nimport analyze from '../build/analyze'\nimport { warn } from '../build/output/log'\nimport { printAndExit } from '../server/lib/utils'\nimport { getProjectDir } from '../lib/get-project-dir'\n\nexport type NextAnalyzeOptions = {\n experimentalAnalyze?: boolean\n profile?: boolean\n mangling: boolean\n port: number\n output: boolean\n experimentalAppOnly?: boolean\n}\n\nconst nextAnalyze = async (options: NextAnalyzeOptions, directory?: string) => {\n process.on('SIGTERM', () => {\n saveCpuProfile()\n process.exit(143)\n })\n process.on('SIGINT', () => {\n saveCpuProfile()\n process.exit(130)\n })\n\n const { profile, mangling, experimentalAppOnly, output, port } = options\n\n if (!mangling) {\n warn(\n `Mangling is disabled. ${italic('Note: This may affect performance and should only be used for debugging purposes.')}`\n )\n }\n\n if (profile) {\n warn(\n `Profiling is enabled. ${italic('Note: This may affect performance.')}`\n )\n }\n\n const dir = getProjectDir(directory)\n\n if (!existsSync(dir)) {\n printAndExit(`> No such directory exists as the project root: ${dir}`)\n }\n\n return analyze({\n dir,\n reactProductionProfiling: profile,\n noMangling: !mangling,\n appDirOnly: experimentalAppOnly,\n output,\n port,\n })\n}\n\nexport { nextAnalyze }\n"],"names":["nextAnalyze","options","directory","process","on","saveCpuProfile","exit","profile","mangling","experimentalAppOnly","output","port","warn","italic","dir","getProjectDir","existsSync","printAndExit","analyze","reactProductionProfiling","noMangling","appDirOnly"],"mappings":";;;;;+BA4DSA;;;eAAAA;;;4BA1DF;oBAEoB;4BACJ;gEACH;qBACC;uBACQ;+BACC;;;;;;AAW9B,MAAMA,cAAc,OAAOC,SAA6BC;IACtDC,QAAQC,EAAE,CAAC,WAAW;QACpBC,IAAAA,0BAAc;QACdF,QAAQG,IAAI,CAAC;IACf;IACAH,QAAQC,EAAE,CAAC,UAAU;QACnBC,IAAAA,0BAAc;QACdF,QAAQG,IAAI,CAAC;IACf;IAEA,MAAM,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,mBAAmB,EAAEC,MAAM,EAAEC,IAAI,EAAE,GAAGV;IAEjE,IAAI,CAACO,UAAU;QACbI,IAAAA,SAAI,EACF,CAAC,sBAAsB,EAAEC,IAAAA,kBAAM,EAAC,sFAAsF;IAE1H;IAEA,IAAIN,SAAS;QACXK,IAAAA,SAAI,EACF,CAAC,sBAAsB,EAAEC,IAAAA,kBAAM,EAAC,uCAAuC;IAE3E;IAEA,MAAMC,MAAMC,IAAAA,4BAAa,EAACb;IAE1B,IAAI,CAACc,IAAAA,cAAU,EAACF,MAAM;QACpBG,IAAAA,mBAAY,EAAC,CAAC,gDAAgD,EAAEH,KAAK;IACvE;IAEA,OAAOI,IAAAA,gBAAO,EAAC;QACbJ;QACAK,0BAA0BZ;QAC1Ba,YAAY,CAACZ;QACba,YAAYZ;QACZC;QACAC;IACF;AACF","ignoreList":[0]}
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env node
import { saveCpuProfile } from '../server/lib/cpu-profile';
export type NextBuildOptions = {
experimentalAnalyze?: boolean;
debug?: boolean;
debugPrerender?: boolean;
profile?: boolean;
mangling: boolean;
turbo?: boolean;
turbopack?: boolean;
webpack?: boolean;
experimentalDebugMemoryUsage: boolean;
experimentalAppOnly?: boolean;
experimentalTurbo?: boolean;
experimentalBuildMode: 'default' | 'compile' | 'generate' | 'generate-env';
experimentalUploadTrace?: string;
experimentalNextConfigStripTypes?: boolean;
debugBuildPaths?: string;
experimentalCpuProf?: boolean;
};
declare const nextBuild: (options: NextBuildOptions, directory?: string) => Promise<void>;
export { nextBuild, saveCpuProfile };
+115
View File
@@ -0,0 +1,115 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
nextBuild: null,
saveCpuProfile: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
nextBuild: function() {
return nextBuild;
},
saveCpuProfile: function() {
return _cpuprofile.saveCpuProfile;
}
});
const _cpuprofile = require("../server/lib/cpu-profile");
const _fs = require("fs");
const _picocolors = require("../lib/picocolors");
const _build = /*#__PURE__*/ _interop_require_default(require("../build"));
const _log = require("../build/output/log");
const _utils = require("../server/lib/utils");
const _iserror = /*#__PURE__*/ _interop_require_default(require("../lib/is-error"));
const _getprojectdir = require("../lib/get-project-dir");
const _startup = require("../lib/memory/startup");
const _shutdown = require("../lib/memory/shutdown");
const _bundler = require("../lib/bundler");
const _resolvebuildpaths = require("../lib/resolve-build-paths");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const nextBuild = async (options, directory)=>{
process.on('SIGTERM', ()=>{
(0, _cpuprofile.saveCpuProfile)();
process.exit(143);
});
process.on('SIGINT', ()=>{
(0, _cpuprofile.saveCpuProfile)();
process.exit(130);
});
const { experimentalAnalyze, debug, debugPrerender, experimentalDebugMemoryUsage, profile, mangling, experimentalAppOnly, experimentalBuildMode, experimentalUploadTrace, debugBuildPaths } = options;
let traceUploadUrl;
if (experimentalUploadTrace && !process.env.NEXT_TRACE_UPLOAD_DISABLED) {
traceUploadUrl = experimentalUploadTrace;
}
const bundler = (0, _bundler.parseBundlerArgs)(options);
if (experimentalAnalyze && bundler !== _bundler.Bundler.Turbopack) {
(0, _utils.printAndExit)('--experimental-analyze is only compatible with the Turbopack bundler.');
}
if (!mangling) {
(0, _log.warn)(`Mangling is disabled. ${(0, _picocolors.italic)('Note: This may affect performance and should only be used for debugging purposes.')}`);
}
if (profile) {
(0, _log.warn)(`Profiling is enabled. ${(0, _picocolors.italic)('Note: This may affect performance.')}`);
}
if (debugPrerender) {
(0, _log.warn)(`Prerendering is running in debug mode with NODE_ENV='development'. ${(0, _picocolors.italic)('This will affect performance and should not be used for production.')}`);
}
if (experimentalDebugMemoryUsage) {
process.env.EXPERIMENTAL_DEBUG_MEMORY_USAGE = '1';
(0, _startup.enableMemoryDebuggingMode)();
}
const dir = (0, _getprojectdir.getProjectDir)(directory);
if (!(0, _fs.existsSync)(dir)) {
(0, _utils.printAndExit)(`> No such directory exists as the project root: ${dir}`);
}
// Resolve selective build paths
let resolvedBuildPaths;
if (debugBuildPaths) {
try {
const patterns = (0, _resolvebuildpaths.parseBuildPathsInput)(debugBuildPaths);
if (patterns.length > 0) {
const resolved = await (0, _resolvebuildpaths.resolveBuildPaths)(patterns, dir);
resolvedBuildPaths = {
app: resolved.appPaths,
pages: resolved.pagePaths
};
}
} catch (err) {
(0, _utils.printAndExit)(`Failed to resolve build paths: ${(0, _iserror.default)(err) ? err.message : String(err)}`);
}
}
const enabledFeatures = Object.fromEntries(Object.entries({
experimentalDebugMemoryUsage,
experimentalBuildMode: experimentalBuildMode !== 'default' ? experimentalBuildMode : undefined,
experimentalCpuProf: options.experimentalCpuProf
}).filter(([_, value])=>value !== undefined && value !== false));
return (0, _build.default)(dir, experimentalAnalyze, profile, debug || Boolean(process.env.NEXT_DEBUG_BUILD), debugPrerender, !mangling, experimentalAppOnly, bundler, experimentalBuildMode, traceUploadUrl, resolvedBuildPaths, enabledFeatures).catch((err)=>{
if (experimentalDebugMemoryUsage) {
(0, _shutdown.disableMemoryDebuggingMode)();
}
console.error('');
if ((0, _iserror.default)(err) && (err.code === 'INVALID_RESOLVE_ALIAS' || err.code === 'WEBPACK_ERRORS' || err.code === 'BUILD_OPTIMIZATION_FAILED' || err.code === 'NEXT_EXPORT_ERROR' || err.code === 'NEXT_STATIC_GEN_BAILOUT' || err.code === 'EDGE_RUNTIME_UNSUPPORTED_API')) {
(0, _utils.printAndExit)(`> ${err.message}`);
} else {
console.error('> Build error occurred');
(0, _utils.printAndExit)(err);
}
}).finally(()=>{
if (experimentalDebugMemoryUsage) {
(0, _shutdown.disableMemoryDebuggingMode)();
}
});
};
//# sourceMappingURL=next-build.js.map
+1
View File
File diff suppressed because one or more lines are too long
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env node
import '../server/lib/cpu-profile';
import { type DebugAddress } from '../server/lib/utils';
export type NextDevOptions = {
disableSourceMaps: boolean;
inspect?: DebugAddress | true;
turbo?: boolean;
turbopack?: boolean;
webpack?: boolean;
port: number;
hostname?: string;
experimentalHttps?: boolean;
experimentalHttpsKey?: string;
experimentalHttpsCert?: string;
experimentalHttpsCa?: string;
experimentalUploadTrace?: string;
experimentalNextConfigStripTypes?: boolean;
experimentalCpuProf?: boolean;
serverFastRefresh?: boolean;
};
type PortSource = 'cli' | 'default' | 'env';
declare const nextDev: (options: NextDevOptions, portSource: PortSource, directory?: string) => Promise<void>;
export { nextDev };
+366
View File
@@ -0,0 +1,366 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "nextDev", {
enumerable: true,
get: function() {
return nextDev;
}
});
const _cpuprofile = require("../server/lib/cpu-profile");
const _utils = require("../server/lib/utils");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../build/output/log"));
const _getprojectdir = require("../lib/get-project-dir");
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _shared = require("../trace/shared");
const _storage = require("../telemetry/storage");
const _findpagesdir = require("../lib/find-pages-dir");
const _fileexists = require("../lib/file-exists");
const _getnpxcommand = require("../lib/helpers/get-npx-command");
const _mkcert = require("../lib/mkcert");
const _uploadtrace = /*#__PURE__*/ _interop_require_default(require("../trace/upload-trace"));
const _env = require("@next/env");
const _child_process = require("child_process");
const _getreservedport = require("../lib/helpers/get-reserved-port");
const _os = /*#__PURE__*/ _interop_require_default(require("os"));
const _nodeevents = require("node:events");
const _timers = require("timers");
const _trace = require("../trace");
const _bundler = require("../lib/bundler");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
let dir;
let child;
// distDir is received from the child process via IPC, used for telemetry and trace.
let distDir;
let isTurbopack;
let traceUploadUrl;
let sessionStopHandled = false;
const sessionStarted = Date.now();
const sessionSpan = (0, _trace.trace)('next-dev');
// How long should we wait for the child to cleanly exit after sending
// SIGINT/SIGTERM to the child process before sending SIGKILL?
const CHILD_EXIT_TIMEOUT_MS = parseInt(process.env.NEXT_EXIT_TIMEOUT_MS ?? '100', 10);
const handleSessionStop = async (signal)=>{
if (signal != null && (child == null ? void 0 : child.pid)) child.kill(signal);
if (sessionStopHandled) return;
sessionStopHandled = true;
// Capture the child's exit code if it has already exited and caused the
// session stop (via the 'exit' event), otherwise assume success (0).
const exitCode = (child == null ? void 0 : child.exitCode) || 0;
if (signal != null && (child == null ? void 0 : child.pid) && child.exitCode === null && child.signalCode === null) {
let exitTimeout = setTimeout(()=>{
child == null ? void 0 : child.kill('SIGKILL');
}, CHILD_EXIT_TIMEOUT_MS);
await (0, _nodeevents.once)(child, 'exit').catch(()=>{});
(0, _timers.clearTimeout)(exitTimeout);
}
sessionSpan.stop();
try {
const { eventCliSessionStopped } = require('../telemetry/events/session-stopped');
let pagesDir = !!_shared.traceGlobals.get('pagesDir');
let appDir = !!_shared.traceGlobals.get('appDir');
if (typeof _shared.traceGlobals.get('pagesDir') === 'undefined' || typeof _shared.traceGlobals.get('appDir') === 'undefined') {
const pagesResult = (0, _findpagesdir.findPagesDir)(dir);
appDir = !!pagesResult.appDir;
pagesDir = !!pagesResult.pagesDir;
}
let telemetry = _shared.traceGlobals.get('telemetry') || new _storage.Telemetry({
distDir: _path.default.join(dir, distDir || '.next')
});
telemetry.record(eventCliSessionStopped({
cliCommand: 'dev',
turboFlag: isTurbopack,
durationMilliseconds: Date.now() - sessionStarted,
pagesDir,
appDir
}), true);
telemetry.flushDetached('dev', dir);
} catch (_) {
// errors here aren't actionable so don't add
// noise to the output
}
if (traceUploadUrl && distDir) {
(0, _uploadtrace.default)({
traceUploadUrl,
mode: 'dev',
projectDir: dir,
distDir,
isTurboSession: isTurbopack
});
}
// Save CPU profile if it was enabled (before exiting)
(0, _cpuprofile.saveCpuProfile)();
// ensure we re-enable the terminal cursor before exiting
// the program, or the cursor could remain hidden
process.stdout.write('\x1B[?25h');
process.stdout.write('\n');
process.exit(exitCode);
};
process.on('SIGINT', ()=>handleSessionStop('SIGINT'));
process.on('SIGTERM', ()=>handleSessionStop('SIGTERM'));
// exit event must be synchronous
process.on('exit', ()=>child == null ? void 0 : child.kill('SIGKILL'));
const nextDev = async (options, portSource, directory)=>{
// Note: parseBundlerArgs can only decide on Turbopack or webpack.
// Rspack can be configured via next.config.js but next.config.js is not loaded in the main process, only in the child process.
isTurbopack = (0, _bundler.parseBundlerArgs)(options) === _bundler.Bundler.Turbopack;
dir = (0, _getprojectdir.getProjectDir)(process.env.NEXT_PRIVATE_DEV_DIR || directory);
// Check if pages dir exists and warn if not
if (!await (0, _fileexists.fileExists)(dir, _fileexists.FileType.Directory)) {
(0, _utils.printAndExit)(`> No such directory exists as the project root: ${dir}`);
}
if (options.experimentalCpuProf) {
_log.info(`CPU profiling enabled. Profile will be saved to .next/cpu-profiles/ on exit (Ctrl+C).`);
}
async function preflight(skipOnReboot) {
const { getPackageVersion, getDependencies } = await Promise.resolve(require('../lib/get-package-version'));
const [sassVersion, nodeSassVersion] = await Promise.all([
getPackageVersion({
cwd: dir,
name: 'sass'
}),
getPackageVersion({
cwd: dir,
name: 'node-sass'
})
]);
if (sassVersion && nodeSassVersion) {
_log.warn('Your project has both `sass` and `node-sass` installed as dependencies, but should only use one or the other. ' + 'Please remove the `node-sass` dependency from your project. ' + ' Read more: https://nextjs.org/docs/messages/duplicate-sass');
}
if (!skipOnReboot) {
const { dependencies, devDependencies } = await getDependencies({
cwd: dir
});
// Warn if @next/font is installed as a dependency. Ignore `workspace:*` to not warn in the Next.js monorepo.
if (dependencies['@next/font'] || devDependencies['@next/font'] && devDependencies['@next/font'] !== 'workspace:*') {
const command = (0, _getnpxcommand.getNpxCommand)(dir);
_log.warn('Your project has `@next/font` installed as a dependency, please use the built-in `next/font` instead. ' + 'The `@next/font` package will be removed in Next.js 14. ' + `You can migrate by running \`${command} @next/codemod@latest built-in-next-font .\`. Read more: https://nextjs.org/docs/messages/built-in-next-font`);
}
}
}
let port = options.port;
if ((0, _getreservedport.isPortIsReserved)(port)) {
(0, _utils.printAndExit)((0, _getreservedport.getReservedPortExplanation)(port), 1);
}
// If neither --port nor PORT were specified, it's okay to retry new ports.
const allowRetry = portSource === 'default';
// We do not set a default host value here to prevent breaking
// some set-ups that rely on listening on other interfaces
const host = options.hostname;
if (options.experimentalUploadTrace && !process.env.NEXT_TRACE_UPLOAD_DISABLED) {
traceUploadUrl = options.experimentalUploadTrace;
}
const enabledFeatures = Object.fromEntries(Object.entries({
serverFastRefreshDisabled: options.serverFastRefresh === false,
experimentalCpuProf: options.experimentalCpuProf
}).filter(([_, value])=>value));
for (const [key, value] of Object.entries(enabledFeatures)){
sessionSpan.setAttribute(`feature.${key}`, value);
}
(0, _trace.initializeTraceState)({
...(0, _trace.exportTraceState)(),
defaultParentSpanId: sessionSpan.getId()
});
const devServerOptions = {
dir,
port,
allowRetry,
isDev: true,
hostname: host,
serverFastRefresh: options.serverFastRefresh
};
const startServerPath = require.resolve('../server/lib/start-server');
async function startServer(startServerOptions) {
return new Promise((resolve)=>{
let resolved = false;
const defaultEnv = _env.initialEnv || process.env;
const nodeOptions = (0, _utils.getParsedNodeOptions)();
let maxOldSpaceSize = (0, _utils.getMaxOldSpaceSize)();
if (!maxOldSpaceSize && !process.env.NEXT_DISABLE_MEM_OVERRIDE) {
const totalMem = _os.default.totalmem();
const totalMemInMB = Math.floor(totalMem / 1024 / 1024);
maxOldSpaceSize = Math.floor(totalMemInMB * 0.5).toString();
nodeOptions['max-old-space-size'] = maxOldSpaceSize;
// Ensure the max_old_space_size is not also set.
delete nodeOptions['max_old_space_size'];
}
if (options.disableSourceMaps) {
delete nodeOptions['enable-source-maps'];
} else {
nodeOptions['enable-source-maps'] = true;
}
const nodeDebugType = (0, _utils.getNodeDebugType)(nodeOptions);
const originalAddress = nodeDebugType === undefined ? undefined : nodeOptions[nodeDebugType];
delete nodeOptions.inspect;
delete nodeOptions['inspect-brk'];
delete nodeOptions['inspect_brk'];
if (nodeDebugType !== undefined) {
const address = (0, _utils.getParsedDebugAddress)(originalAddress);
address.port = address.port === 0 ? 0 : address.port + 1;
nodeOptions[nodeDebugType] = (0, _utils.formatDebugAddress)(address);
} else if (options.inspect) {
const address = options.inspect === true ? (0, _utils.getParsedDebugAddress)(true) : options.inspect;
nodeOptions.inspect = (0, _utils.formatDebugAddress)(address);
}
const { nodeOptions: formattedNodeOptions, execArgv } = (0, _utils.formatNodeOptions)(nodeOptions);
child = (0, _child_process.fork)(startServerPath, {
stdio: 'inherit',
execArgv,
env: {
...defaultEnv,
...isTurbopack ? {
TURBOPACK: process.env.TURBOPACK
} : undefined,
__NEXT_DEV_SERVER: '1',
NEXT_PRIVATE_START_TIME: process.env.NEXT_PRIVATE_START_TIME,
NEXT_PRIVATE_WORKER: '1',
NEXT_PRIVATE_TRACE_ID: _shared.traceId,
NEXT_PRIVATE_ENABLED_FEATURES: JSON.stringify(enabledFeatures),
NODE_EXTRA_CA_CERTS: startServerOptions.selfSignedCertificate ? startServerOptions.selfSignedCertificate.rootCA : defaultEnv.NODE_EXTRA_CA_CERTS,
NODE_OPTIONS: formattedNodeOptions,
// There is a node.js bug on MacOS which causes closing file watchers to be really slow.
// This limits the number of watchers to mitigate the issue.
// https://github.com/nodejs/node/issues/29949
WATCHPACK_WATCHER_LIMIT: _os.default.platform() === 'darwin' ? '20' : undefined,
// Enable CPU profiling if requested
...options.experimentalCpuProf ? {
NEXT_CPU_PROF: '1',
NEXT_CPU_PROF_DIR: _path.default.join(dir, '.next', 'cpu-profiles'),
__NEXT_PRIVATE_CPU_PROFILE: 'dev-server'
} : undefined
}
});
child.on('message', (msg)=>{
if (msg && typeof msg === 'object') {
if (msg.nextWorkerReady) {
child == null ? void 0 : child.send({
nextWorkerOptions: startServerOptions
});
} else if (msg.nextServerReady && !resolved) {
if (msg.port) {
// Store the used port in case a random one was selected, so that
// it can be re-used on automatic dev server restarts.
port = parseInt(msg.port, 10);
}
if (msg.distDir) {
// Store the distDir from the child process for telemetry and trace uploads.
distDir = msg.distDir;
}
resolved = true;
resolve();
}
}
});
child.on('exit', async (code, signal)=>{
if (sessionStopHandled || signal) {
return;
}
if (code === _utils.RESTART_EXIT_CODE) {
// Starting the dev server will overwrite the `.next/trace` file, so we
// must upload the existing contents before restarting the server to
// preserve the metrics.
if (traceUploadUrl && distDir) {
(0, _uploadtrace.default)({
traceUploadUrl,
mode: 'dev',
projectDir: dir,
distDir,
isTurboSession: isTurbopack,
sync: true
});
}
// Reset the start time so "Ready in X" reflects the restart
// duration, not time since the original process started.
process.env.NEXT_PRIVATE_START_TIME = Date.now().toString();
return startServer({
...startServerOptions,
port
});
}
// Call handler (e.g. upload telemetry). Don't try to send a signal to
// the child, as it has already exited.
await handleSessionStop(/* signal */ null);
});
});
}
const runDevServer = async (reboot)=>{
try {
if (!!options.experimentalHttps) {
_log.warn('Self-signed certificates are currently an experimental feature, use with caution.');
let certificate;
const key = options.experimentalHttpsKey;
const cert = options.experimentalHttpsCert;
const rootCA = options.experimentalHttpsCa;
if (key && cert) {
certificate = {
key: _path.default.resolve(key),
cert: _path.default.resolve(cert),
rootCA: rootCA ? _path.default.resolve(rootCA) : undefined
};
} else {
certificate = await (0, _mkcert.createSelfSignedCertificate)(host);
}
await startServer({
...devServerOptions,
selfSignedCertificate: certificate
});
} else {
await startServer(devServerOptions);
}
await preflight(reboot);
} catch (err) {
console.error(err);
process.exit(1);
}
};
await runDevServer(false);
};
//# sourceMappingURL=next-dev.js.map
+1
View File
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
declare const nextExport: () => never;
export { nextExport };
+20
View File
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "nextExport", {
enumerable: true,
get: function() {
return nextExport;
}
});
const _picocolors = require("../lib/picocolors");
const _log = require("../build/output/log");
const nextExport = ()=>{
(0, _log.error)(`
\`next export\` has been removed in favor of 'output: export' in next.config.js.\nLearn more: ${(0, _picocolors.cyan)('https://nextjs.org/docs/app/building-your-application/deploying/static-exports')}
`);
process.exit(1);
};
//# sourceMappingURL=next-export.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/cli/next-export.ts"],"sourcesContent":["import { cyan } from '../lib/picocolors'\nimport { error } from '../build/output/log'\n\nconst nextExport = () => {\n error(`\n \\`next export\\` has been removed in favor of 'output: export' in next.config.js.\\nLearn more: ${cyan(\n 'https://nextjs.org/docs/app/building-your-application/deploying/static-exports'\n )}\n `)\n\n process.exit(1)\n}\n\nexport { nextExport }\n"],"names":["nextExport","error","cyan","process","exit"],"mappings":";;;;+BAaSA;;;eAAAA;;;4BAbY;qBACC;AAEtB,MAAMA,aAAa;IACjBC,IAAAA,UAAK,EAAC,CAAC;kGACyF,EAAEC,IAAAA,gBAAI,EAClG,kFACA;EACJ,CAAC;IAEDC,QAAQC,IAAI,CAAC;AACf","ignoreList":[0]}
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env node
export type NextInfoOptions = {
verbose?: boolean;
};
/**
* Runs few scripts to collect system information to help with debugging next.js installation issues.
* There are 2 modes, by default it collects basic next.js installation with runtime information. If
* `--verbose` mode is enabled it'll try to collect, verify more data for next-swc installation and others.
*/
declare const nextInfo: (options: NextInfoOptions) => Promise<void>;
export { nextInfo };
+480
View File
@@ -0,0 +1,480 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "nextInfo", {
enumerable: true,
get: function() {
return nextInfo;
}
});
const _os = /*#__PURE__*/ _interop_require_default(require("os"));
const _child_process = /*#__PURE__*/ _interop_require_default(require("child_process"));
const _picocolors = require("../lib/picocolors");
const _constants = require("../shared/lib/constants");
const _config = /*#__PURE__*/ _interop_require_default(require("../server/config"));
const _getregistry = require("../lib/helpers/get-registry");
const _parseversioninfo = require("../server/dev/parse-version-info");
const _versionstaleness = require("../next-devtools/shared/version-staleness");
const _log = require("../build/output/log");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function getPackageVersion(packageName) {
try {
return require(`${packageName}/package.json`).version;
} catch {
return 'N/A';
}
}
async function getNextConfig() {
var _config_experimental;
const config = await (0, _config.default)(_constants.PHASE_INFO, process.cwd());
return {
output: config.output ?? 'N/A',
experimental: {
useWasmBinary: (_config_experimental = config.experimental) == null ? void 0 : _config_experimental.useWasmBinary
}
};
}
/**
* Returns the version of the specified binary, by supplying `--version` argument.
* N/A if it fails to run the binary.
*/ function getBinaryVersion(binaryName) {
try {
return _child_process.default.execFileSync(binaryName, [
'--version'
]).toString().trim();
} catch {
try {
return _child_process.default.execSync(`${binaryName} --version`).toString().trim();
} catch {
return 'N/A';
}
}
}
/**
* Collect basic next.js installation information and print it to stdout.
*/ async function printInfo() {
const installedRelease = getPackageVersion('next');
const nextConfig = await getNextConfig();
let stalenessWithTitle = '';
let title = '';
let versionInfo;
try {
const registry = (0, _getregistry.getRegistry)();
const res = await fetch(`${registry}-/package/next/dist-tags`);
const tags = await res.json();
versionInfo = (0, _parseversioninfo.parseVersionInfo)({
installed: installedRelease,
latest: tags.latest,
canary: tags.canary
});
title = (0, _versionstaleness.getStaleness)(versionInfo).title;
if (title) {
stalenessWithTitle = ` // ${title}`;
}
} catch (e) {
console.warn(`${(0, _picocolors.yellow)((0, _picocolors.bold)('warn'))} - Failed to fetch latest canary version. (Reason: ${e.message}.)
Detected "${installedRelease}". Visit https://github.com/vercel/next.js/releases.
Make sure to try the latest canary version (eg.: \`npm install next@canary\`) to confirm the issue still exists before creating a new issue.
\nLearn more: ${(0, _picocolors.cyan)('https://nextjs.org/docs/messages/opening-an-issue')}`);
}
const cpuCores = _os.default.cpus().length;
let relevantPackages = ` next: ${installedRelease}${stalenessWithTitle}
eslint-config-next: ${getPackageVersion('eslint-config-next')}
react: ${getPackageVersion('react')}
react-dom: ${getPackageVersion('react-dom')}
typescript: ${getPackageVersion('typescript')}`;
if (process.env.NEXT_RSPACK) {
relevantPackages += `
next-rspack: ${getPackageVersion('next-rspack')}`;
}
console.log(`
Operating System:
Platform: ${_os.default.platform()}
Arch: ${_os.default.arch()}
Version: ${_os.default.version()}
Available memory (MB): ${Math.ceil(_os.default.totalmem() / 1024 / 1024)}
Available CPU cores: ${cpuCores > 0 ? cpuCores : 'N/A'}
Binaries:
Node: ${process.versions.node}
npm: ${getBinaryVersion('npm')}
Yarn: ${getBinaryVersion('yarn')}
pnpm: ${getBinaryVersion('pnpm')}
Relevant Packages:
${relevantPackages}
Next.js Config:
output: ${nextConfig.output}`);
if (versionInfo == null ? void 0 : versionInfo.staleness.startsWith('stale')) {
(0, _log.warn)(`${title}
Please try the latest canary version (\`npm install next@canary\`) to confirm the issue still exists before creating a new issue.
Read more - https://nextjs.org/docs/messages/opening-an-issue`);
}
}
/**
* Using system-installed tools per each platform, trying to read shared dependencies of next-swc.
* This is mainly for debugging DLOPEN failure.
*
* We don't / can't install these tools by ourselves, will skip the check if we can't find them.
*/ async function runSharedDependencyCheck(tools, skipMessage) {
var _getSupportedArchTriples_currentPlatform;
const currentPlatform = _os.default.platform();
const spawn = require('next/dist/compiled/cross-spawn');
const { getSupportedArchTriples } = require('../build/swc');
const triples = ((_getSupportedArchTriples_currentPlatform = getSupportedArchTriples()[currentPlatform]) == null ? void 0 : _getSupportedArchTriples_currentPlatform[_os.default.arch()]) ?? [];
// First, check if system have a tool installed. We can't install these by our own.
const availableTools = [];
for (const tool of tools){
try {
const check = spawn.sync(tool.bin, tool.checkArgs);
if (check.status === 0) {
availableTools.push(tool);
}
} catch {
// ignore if existence check fails
}
}
if (availableTools.length === 0) {
return {
messages: skipMessage,
result: 'skipped'
};
}
const outputs = [];
let result = 'fail';
for (const triple of triples){
const triplePkgName = `@next/swc-${triple.platformArchABI}`;
let resolved;
try {
resolved = require.resolve(triplePkgName);
} catch (e) {
return {
messages: 'Cannot find next-swc installation, skipping dependencies check',
result: 'skipped'
};
}
for (const tool of availableTools){
const proc = spawn(tool.bin, [
...tool.args,
resolved
]);
outputs.push(`Running ${tool.bin} ------------- `);
// Captures output, doesn't matter if it fails or not since we'll forward both to output.
const procPromise = new Promise((resolve)=>{
proc.stdout.on('data', function(data) {
outputs.push(data);
});
proc.stderr.on('data', function(data) {
outputs.push(data);
});
proc.on('close', (c)=>resolve(c));
});
let code = await procPromise;
if (code === 0) {
result = 'pass';
}
}
}
return {
output: outputs.join('\n'),
result
};
}
/**
* Collect additional diagnostics information.
*/ async function printVerboseInfo() {
const fs = require('fs');
const currentPlatform = _os.default.platform();
if (currentPlatform !== 'win32' && currentPlatform !== 'linux' && currentPlatform !== 'darwin') {
console.log('Unsupported platform, only win32, linux, darwin are supported.');
return;
}
// List of tasks to run.
const tasks = [
{
title: 'Host system information',
scripts: {
default: async ()=>{
// Node.js diagnostic report contains basic information, i.e OS version, CPU architecture, etc.
// Only collect few addtional details here.
const isWsl = require('next/dist/compiled/is-wsl');
const ciInfo = require('next/dist/compiled/ci-info');
const isDocker = require('next/dist/compiled/is-docker');
const output = `
WSL: ${isWsl}
Docker: ${isDocker()}
CI: ${ciInfo.isCI ? ciInfo.name || 'unknown' : 'false'}
`;
return {
output,
result: 'pass'
};
}
}
},
{
title: 'Next.js installation',
scripts: {
default: async ()=>{
const installedRelease = getPackageVersion('next');
const nextConfig = await getNextConfig();
const output = `
Binaries:
Node: ${process.versions.node}
npm: ${getBinaryVersion('npm')}
Yarn: ${getBinaryVersion('yarn')}
pnpm: ${getBinaryVersion('pnpm')}
Relevant Packages:
next: ${installedRelease}
eslint-config-next: ${getPackageVersion('eslint-config-next')}
react: ${getPackageVersion('react')}
react-dom: ${getPackageVersion('react-dom')}
typescript: ${getPackageVersion('typescript')}
Next.js Config:
output: ${nextConfig.output}
`;
return {
output,
result: 'pass'
};
}
}
},
{
title: 'Node.js diagnostic report',
scripts: {
default: async ()=>{
var _process_report;
const report = (_process_report = process.report) == null ? void 0 : _process_report.getReport();
if (!report) {
return {
messages: 'Node.js diagnostic report is not available.',
result: 'fail'
};
}
const { header, javascriptHeap, sharedObjects } = report;
// Delete some fields potentially containing sensitive information.
header == null ? true : delete header.cwd;
header == null ? true : delete header.commandLine;
header == null ? true : delete header.host;
header == null ? true : delete header.cpus;
header == null ? true : delete header.networkInterfaces;
const reportSummary = {
header,
javascriptHeap,
sharedObjects
};
return {
output: JSON.stringify(reportSummary, null, 2),
result: 'pass'
};
}
}
},
{
title: 'next-swc installation',
scripts: {
default: async ()=>{
var _platformArchTriples_currentPlatform;
const output = [];
// First, try to load next-swc via loadBindings.
try {
var _nextConfig_experimental;
let nextConfig = await getNextConfig();
const { loadBindings } = require('../build/swc');
const bindings = await loadBindings((_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.useWasmBinary);
// Run arbitrary function to verify the bindings are loaded correctly.
const target = bindings.getTargetTriple();
// We think next-swc is installed correctly if getTargetTriple returns.
return {
output: `next-swc is installed correctly for ${target}`,
result: 'pass'
};
} catch (e) {
output.push(`loadBindings() failed: ${e.message}`);
}
const { platformArchTriples } = require('next/dist/compiled/@napi-rs/triples');
const triples = (_platformArchTriples_currentPlatform = platformArchTriples[currentPlatform]) == null ? void 0 : _platformArchTriples_currentPlatform[_os.default.arch()];
if (!triples || triples.length === 0) {
return {
messages: `No target triples found for ${currentPlatform} / ${_os.default.arch()}`,
result: 'fail'
};
}
// Trying to manually resolve corresponding target triples to see if bindings are physically located.
const path = require('path');
let fallbackBindingsDirectory;
try {
const nextPath = path.dirname(require.resolve('next/package.json'));
fallbackBindingsDirectory = path.join(nextPath, 'next-swc-fallback');
} catch (e) {
// Not able to locate next package from current running location, skipping fallback bindings check.
}
const tryResolve = (pkgName)=>{
try {
const resolved = require.resolve(pkgName);
const fileExists = fs.existsSync(resolved);
let loadError;
let loadSuccess;
try {
loadSuccess = !!require(resolved).getTargetTriple();
} catch (e) {
loadError = e.message;
}
output.push(`${pkgName} exists: ${fileExists} for the triple ${loadSuccess}`);
if (loadError) {
output.push(`${pkgName} load failed: ${loadError ?? 'unknown'}`);
}
if (loadSuccess) {
return true;
}
} catch (e) {
output.push(`${pkgName} resolve failed: ${e.message ?? 'unknown'}`);
}
return false;
};
for (const triple of triples){
const triplePkgName = `@next/swc-${triple.platformArchABI}`;
// Check installed optional dependencies. This is the normal way package being installed.
// For the targets have multiple triples (gnu / musl), if any of them loads successfully, we consider as installed.
if (tryResolve(triplePkgName)) {
break;
}
// Check if fallback binaries are installed.
if (!fallbackBindingsDirectory) {
continue;
}
tryResolve(path.join(fallbackBindingsDirectory, triplePkgName));
}
return {
output: output.join('\n'),
result: 'pass'
};
}
}
},
{
// For the simplicity, we only check the correctly installed optional dependencies -
// as this is mainly for checking DLOPEN failure. If user hit MODULE_NOT_FOUND,
// expect above next-swc installation would give some hint instead.
title: 'next-swc shared object dependencies',
scripts: {
linux: async ()=>{
const skipMessage = 'This diagnostics uses system-installed tools (ldd) to check next-swc dependencies, but it is not found. Skipping dependencies check.';
return await runSharedDependencyCheck([
{
bin: 'ldd',
checkArgs: [
'--help'
],
args: [
'--verbose'
]
}
], skipMessage);
},
win32: async ()=>{
const skipMessage = `This diagnostics uses system-installed tools (dumpbin.exe) to check next-swc dependencies, but it was not found in the path. Skipping dependencies check.
dumpbin (https://learn.microsoft.com/en-us/cpp/build/reference/dumpbin-reference) is a part of Microsoft VC toolset,
can be installed with Windows SDK, Windows Build tools or Visual Studio.
Please make sure you have one of them installed and dumpbin.exe is in the path.
`;
return await runSharedDependencyCheck([
{
bin: 'dumpbin.exe',
checkArgs: [
'/summary'
],
args: [
'/imports'
]
}
], skipMessage);
},
darwin: async ()=>{
const skipMessage = 'This diagnostics uses system-installed tools (otools, dyld_info) to check next-swc dependencies, but none of them are found. Skipping dependencies check.';
return await runSharedDependencyCheck([
{
bin: 'otool',
checkArgs: [
'--version'
],
args: [
'-L'
]
},
{
bin: 'dyld_info',
checkArgs: [],
args: []
}
], skipMessage);
}
}
}
];
// Collected output after running all tasks.
const report = [];
console.log('\n');
for (const task of tasks){
if (task.targetPlatform && task.targetPlatform !== currentPlatform) {
report.push({
title: task.title,
result: {
messages: undefined,
output: `[SKIPPED (${_os.default.platform()} / ${task.targetPlatform})] ${task.title}`,
result: 'skipped'
}
});
continue;
}
const taskScript = task.scripts[currentPlatform] ?? task.scripts.default;
let taskResult;
try {
taskResult = await taskScript();
} catch (e) {
taskResult = {
messages: `Unexpected failure while running diagnostics: ${e.message}`,
result: 'fail'
};
}
console.log(`- ${task.title}: ${taskResult.result}`);
if (taskResult.messages) {
console.log(` ${taskResult.messages}`);
}
report.push({
title: task.title,
result: taskResult
});
}
console.log(`\n${(0, _picocolors.bold)('Generated diagnostics report')}`);
console.log(`\nPlease copy below report and paste it into your issue.`);
for (const { title, result } of report){
console.log(`\n### ${title}`);
if (result.messages) {
console.log(result.messages);
}
if (result.output) {
console.log(result.output);
}
}
}
/**
* Runs few scripts to collect system information to help with debugging next.js installation issues.
* There are 2 modes, by default it collects basic next.js installation with runtime information. If
* `--verbose` mode is enabled it'll try to collect, verify more data for next-swc installation and others.
*/ const nextInfo = async (options)=>{
if (options.verbose) {
await printVerboseInfo();
} else {
await printInfo();
}
};
//# sourceMappingURL=next-info.js.map
+1
View File
File diff suppressed because one or more lines are too long
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env node
import '../server/lib/cpu-profile';
import { type DebugAddress } from '../server/lib/utils';
export type NextStartOptions = {
port: number;
hostname?: string;
inspect?: DebugAddress | true;
keepAliveTimeout?: number;
experimentalNextConfigStripTypes?: boolean;
experimentalCpuProf?: boolean;
};
/**
* Start the Next.js server
*
* @param options The options for the start command
* @param directory The directory to start the server in
*/
declare const nextStart: (options: NextStartOptions, directory?: string) => Promise<undefined>;
export { nextStart };
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "nextStart", {
enumerable: true,
get: function() {
return nextStart;
}
});
const _cpuprofile = require("../server/lib/cpu-profile");
const _startserver = require("../server/lib/start-server");
const _utils = require("../server/lib/utils");
const _getprojectdir = require("../lib/get-project-dir");
const _getreservedport = require("../lib/helpers/get-reserved-port");
const _log = /*#__PURE__*/ _interop_require_wildcard(require("../build/output/log"));
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
// Ensure NEXT_PRIVATE_START_TIME is set for accurate "Ready in" timing.
// This should already be set by bin/next.ts, but we set it here as a fallback
// in case the module is loaded through a different code path.
if (!process.env.NEXT_PRIVATE_START_TIME) {
process.env.NEXT_PRIVATE_START_TIME = Date.now().toString();
}
/**
* Start the Next.js server
*
* @param options The options for the start command
* @param directory The directory to start the server in
*/ const nextStart = async (options, directory)=>{
const dir = (0, _getprojectdir.getProjectDir)(directory);
const hostname = options.hostname;
const inspect = options.inspect;
const port = options.port;
const keepAliveTimeout = options.keepAliveTimeout;
if ((0, _getreservedport.isPortIsReserved)(port)) {
(0, _utils.printAndExit)((0, _getreservedport.getReservedPortExplanation)(port), 1);
}
if (inspect) {
const inspector = await import('inspector');
const isInspecting = inspector.url() !== undefined;
if (isInspecting) {
_log.warn(`The Node.js debugger port is already open at ${process.debugPort}. Ignoring '--inspect${inspect === true ? '' : `="${(0, _utils.formatDebugAddress)(inspect)}"`}'.`);
} else {
const inspectAddress = inspect === true ? (0, _utils.getParsedDebugAddress)(true) : inspect;
// TODO: Implement --inspect-wait
const wait = false;
try {
inspector.open(inspectAddress.port, inspectAddress.host, wait);
} catch (error) {
console.error(`Failed to start the Node.js inspector with --inspect="${(0, _utils.formatDebugAddress)(inspectAddress)}":`, error);
return process.exit(1);
}
}
}
if (options.experimentalCpuProf) {
_log.info(`CPU profiling enabled. Profile will be saved on exit (Ctrl+C).`);
// Save CPU profile on shutdown signals, but let start-server.ts handle graceful exit
process.on('SIGTERM', ()=>(0, _cpuprofile.saveCpuProfile)());
process.on('SIGINT', ()=>(0, _cpuprofile.saveCpuProfile)());
}
await (0, _startserver.startServer)({
dir,
isDev: false,
hostname,
port,
keepAliveTimeout
});
};
//# sourceMappingURL=next-start.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/cli/next-start.ts"],"sourcesContent":["#!/usr/bin/env node\n\n// Ensure NEXT_PRIVATE_START_TIME is set for accurate \"Ready in\" timing.\n// This should already be set by bin/next.ts, but we set it here as a fallback\n// in case the module is loaded through a different code path.\nif (!process.env.NEXT_PRIVATE_START_TIME) {\n process.env.NEXT_PRIVATE_START_TIME = Date.now().toString()\n}\n\nimport '../server/lib/cpu-profile'\nimport { saveCpuProfile } from '../server/lib/cpu-profile'\nimport { startServer } from '../server/lib/start-server'\nimport {\n getParsedDebugAddress,\n formatDebugAddress,\n printAndExit,\n type DebugAddress,\n} from '../server/lib/utils'\nimport { getProjectDir } from '../lib/get-project-dir'\nimport {\n getReservedPortExplanation,\n isPortIsReserved,\n} from '../lib/helpers/get-reserved-port'\nimport * as Log from '../build/output/log'\n\nexport type NextStartOptions = {\n port: number\n hostname?: string\n // Commander is not putting `--inspect` through the arg parser\n inspect?: DebugAddress | true\n keepAliveTimeout?: number\n experimentalNextConfigStripTypes?: boolean\n experimentalCpuProf?: boolean\n}\n\n/**\n * Start the Next.js server\n *\n * @param options The options for the start command\n * @param directory The directory to start the server in\n */\nconst nextStart = async (options: NextStartOptions, directory?: string) => {\n const dir = getProjectDir(directory)\n const hostname = options.hostname\n const inspect = options.inspect\n const port = options.port\n const keepAliveTimeout = options.keepAliveTimeout\n\n if (isPortIsReserved(port)) {\n printAndExit(getReservedPortExplanation(port), 1)\n }\n\n if (inspect) {\n const inspector = await import('inspector')\n const isInspecting = inspector.url() !== undefined\n if (isInspecting) {\n Log.warn(\n `The Node.js debugger port is already open at ${process.debugPort}. Ignoring '--inspect${inspect === true ? '' : `=\"${formatDebugAddress(inspect)}\"`}'.`\n )\n } else {\n const inspectAddress: DebugAddress =\n inspect === true ? getParsedDebugAddress(true) : inspect\n // TODO: Implement --inspect-wait\n const wait = false\n try {\n inspector.open(inspectAddress.port, inspectAddress.host, wait)\n } catch (error) {\n console.error(\n `Failed to start the Node.js inspector with --inspect=\"${formatDebugAddress(inspectAddress)}\":`,\n error\n )\n return process.exit(1)\n }\n }\n }\n\n if (options.experimentalCpuProf) {\n Log.info(`CPU profiling enabled. Profile will be saved on exit (Ctrl+C).`)\n // Save CPU profile on shutdown signals, but let start-server.ts handle graceful exit\n process.on('SIGTERM', () => saveCpuProfile())\n process.on('SIGINT', () => saveCpuProfile())\n }\n\n await startServer({\n dir,\n isDev: false,\n hostname,\n port,\n keepAliveTimeout,\n })\n}\n\nexport { nextStart }\n"],"names":["nextStart","process","env","NEXT_PRIVATE_START_TIME","Date","now","toString","options","directory","dir","getProjectDir","hostname","inspect","port","keepAliveTimeout","isPortIsReserved","printAndExit","getReservedPortExplanation","inspector","isInspecting","url","undefined","Log","warn","debugPort","formatDebugAddress","inspectAddress","getParsedDebugAddress","wait","open","host","error","console","exit","experimentalCpuProf","info","on","saveCpuProfile","startServer","isDev"],"mappings":";;;;;+BA4FSA;;;eAAAA;;;4BAnFF;6BAEqB;uBAMrB;+BACuB;iCAIvB;6DACc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AArBrB,wEAAwE;AACxE,8EAA8E;AAC9E,8DAA8D;AAC9D,IAAI,CAACC,QAAQC,GAAG,CAACC,uBAAuB,EAAE;IACxCF,QAAQC,GAAG,CAACC,uBAAuB,GAAGC,KAAKC,GAAG,GAAGC,QAAQ;AAC3D;AA4BA;;;;;CAKC,GACD,MAAMN,YAAY,OAAOO,SAA2BC;IAClD,MAAMC,MAAMC,IAAAA,4BAAa,EAACF;IAC1B,MAAMG,WAAWJ,QAAQI,QAAQ;IACjC,MAAMC,UAAUL,QAAQK,OAAO;IAC/B,MAAMC,OAAON,QAAQM,IAAI;IACzB,MAAMC,mBAAmBP,QAAQO,gBAAgB;IAEjD,IAAIC,IAAAA,iCAAgB,EAACF,OAAO;QAC1BG,IAAAA,mBAAY,EAACC,IAAAA,2CAA0B,EAACJ,OAAO;IACjD;IAEA,IAAID,SAAS;QACX,MAAMM,YAAY,MAAM,MAAM,CAAC;QAC/B,MAAMC,eAAeD,UAAUE,GAAG,OAAOC;QACzC,IAAIF,cAAc;YAChBG,KAAIC,IAAI,CACN,CAAC,6CAA6C,EAAEtB,QAAQuB,SAAS,CAAC,qBAAqB,EAAEZ,YAAY,OAAO,KAAK,CAAC,EAAE,EAAEa,IAAAA,yBAAkB,EAACb,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC;QAE5J,OAAO;YACL,MAAMc,iBACJd,YAAY,OAAOe,IAAAA,4BAAqB,EAAC,QAAQf;YACnD,iCAAiC;YACjC,MAAMgB,OAAO;YACb,IAAI;gBACFV,UAAUW,IAAI,CAACH,eAAeb,IAAI,EAAEa,eAAeI,IAAI,EAAEF;YAC3D,EAAE,OAAOG,OAAO;gBACdC,QAAQD,KAAK,CACX,CAAC,sDAAsD,EAAEN,IAAAA,yBAAkB,EAACC,gBAAgB,EAAE,CAAC,EAC/FK;gBAEF,OAAO9B,QAAQgC,IAAI,CAAC;YACtB;QACF;IACF;IAEA,IAAI1B,QAAQ2B,mBAAmB,EAAE;QAC/BZ,KAAIa,IAAI,CAAC,CAAC,8DAA8D,CAAC;QACzE,qFAAqF;QACrFlC,QAAQmC,EAAE,CAAC,WAAW,IAAMC,IAAAA,0BAAc;QAC1CpC,QAAQmC,EAAE,CAAC,UAAU,IAAMC,IAAAA,0BAAc;IAC3C;IAEA,MAAMC,IAAAA,wBAAW,EAAC;QAChB7B;QACA8B,OAAO;QACP5B;QACAE;QACAC;IACF;AACF","ignoreList":[0]}
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env node
export type NextTelemetryOptions = {
enable?: boolean;
disable?: boolean;
};
declare const nextTelemetry: (options: NextTelemetryOptions, arg: string) => void;
export { nextTelemetry };
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "nextTelemetry", {
enumerable: true,
get: function() {
return nextTelemetry;
}
});
const _picocolors = require("../lib/picocolors");
const _storage = require("../telemetry/storage");
const telemetry = new _storage.Telemetry({
distDir: process.cwd()
});
let isEnabled = telemetry.isEnabled;
const nextTelemetry = (options, arg)=>{
if (options.enable || arg === 'enable') {
telemetry.setEnabled(true);
isEnabled = true;
console.log((0, _picocolors.cyan)('Success!'));
} else if (options.disable || arg === 'disable') {
const path = telemetry.setEnabled(false);
if (isEnabled) {
console.log((0, _picocolors.cyan)(`Your preference has been saved${path ? ` to ${path}` : ''}.`));
} else {
console.log((0, _picocolors.yellow)(`Next.js' telemetry collection is already disabled.`));
}
isEnabled = false;
} else {
console.log((0, _picocolors.bold)('Next.js Telemetry'));
}
console.log(`\nStatus: ${isEnabled ? (0, _picocolors.bold)((0, _picocolors.green)('Enabled')) : (0, _picocolors.bold)((0, _picocolors.red)('Disabled'))}`);
if (isEnabled) {
console.log('\nNext.js telemetry is completely anonymous. Thank you for participating!');
} else {
console.log(`\nYou have opted-out of Next.js' anonymous telemetry program.\nNo data will be collected from your machine.`);
}
console.log(`\nLearn more: ${(0, _picocolors.cyan)('https://nextjs.org/telemetry')}`);
};
//# sourceMappingURL=next-telemetry.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/cli/next-telemetry.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { bold, cyan, green, red, yellow } from '../lib/picocolors'\nimport { Telemetry } from '../telemetry/storage'\n\nexport type NextTelemetryOptions = {\n enable?: boolean\n disable?: boolean\n}\n\nconst telemetry = new Telemetry({ distDir: process.cwd() })\nlet isEnabled = telemetry.isEnabled\n\nconst nextTelemetry = (options: NextTelemetryOptions, arg: string) => {\n if (options.enable || arg === 'enable') {\n telemetry.setEnabled(true)\n isEnabled = true\n\n console.log(cyan('Success!'))\n } else if (options.disable || arg === 'disable') {\n const path = telemetry.setEnabled(false)\n\n if (isEnabled) {\n console.log(\n cyan(`Your preference has been saved${path ? ` to ${path}` : ''}.`)\n )\n } else {\n console.log(yellow(`Next.js' telemetry collection is already disabled.`))\n }\n\n isEnabled = false\n } else {\n console.log(bold('Next.js Telemetry'))\n }\n\n console.log(\n `\\nStatus: ${isEnabled ? bold(green('Enabled')) : bold(red('Disabled'))}`\n )\n\n if (isEnabled) {\n console.log(\n '\\nNext.js telemetry is completely anonymous. Thank you for participating!'\n )\n } else {\n console.log(\n `\\nYou have opted-out of Next.js' anonymous telemetry program.\\nNo data will be collected from your machine.`\n )\n }\n\n console.log(`\\nLearn more: ${cyan('https://nextjs.org/telemetry')}`)\n}\n\nexport { nextTelemetry }\n"],"names":["nextTelemetry","telemetry","Telemetry","distDir","process","cwd","isEnabled","options","arg","enable","setEnabled","console","log","cyan","disable","path","yellow","bold","green","red"],"mappings":";;;;;+BAoDSA;;;eAAAA;;;4BAlDsC;yBACrB;AAO1B,MAAMC,YAAY,IAAIC,kBAAS,CAAC;IAAEC,SAASC,QAAQC,GAAG;AAAG;AACzD,IAAIC,YAAYL,UAAUK,SAAS;AAEnC,MAAMN,gBAAgB,CAACO,SAA+BC;IACpD,IAAID,QAAQE,MAAM,IAAID,QAAQ,UAAU;QACtCP,UAAUS,UAAU,CAAC;QACrBJ,YAAY;QAEZK,QAAQC,GAAG,CAACC,IAAAA,gBAAI,EAAC;IACnB,OAAO,IAAIN,QAAQO,OAAO,IAAIN,QAAQ,WAAW;QAC/C,MAAMO,OAAOd,UAAUS,UAAU,CAAC;QAElC,IAAIJ,WAAW;YACbK,QAAQC,GAAG,CACTC,IAAAA,gBAAI,EAAC,CAAC,8BAA8B,EAAEE,OAAO,CAAC,IAAI,EAAEA,MAAM,GAAG,GAAG,CAAC,CAAC;QAEtE,OAAO;YACLJ,QAAQC,GAAG,CAACI,IAAAA,kBAAM,EAAC,CAAC,kDAAkD,CAAC;QACzE;QAEAV,YAAY;IACd,OAAO;QACLK,QAAQC,GAAG,CAACK,IAAAA,gBAAI,EAAC;IACnB;IAEAN,QAAQC,GAAG,CACT,CAAC,UAAU,EAAEN,YAAYW,IAAAA,gBAAI,EAACC,IAAAA,iBAAK,EAAC,cAAcD,IAAAA,gBAAI,EAACE,IAAAA,eAAG,EAAC,cAAc;IAG3E,IAAIb,WAAW;QACbK,QAAQC,GAAG,CACT;IAEJ,OAAO;QACLD,QAAQC,GAAG,CACT,CAAC,2GAA2G,CAAC;IAEjH;IAEAD,QAAQC,GAAG,CAAC,CAAC,cAAc,EAAEC,IAAAA,gBAAI,EAAC,iCAAiC;AACrE","ignoreList":[0]}
+6
View File
@@ -0,0 +1,6 @@
export interface NextTestOptions {
testRunner?: string;
}
export declare const SUPPORTED_TEST_RUNNERS_LIST: readonly ["playwright"];
export type SupportedTestRunners = (typeof SUPPORTED_TEST_RUNNERS_LIST)[number];
export declare function nextTest(directory?: string, testRunnerArgs?: string[], options?: NextTestOptions): Promise<unknown>;
+170
View File
@@ -0,0 +1,170 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
SUPPORTED_TEST_RUNNERS_LIST: null,
nextTest: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
SUPPORTED_TEST_RUNNERS_LIST: function() {
return SUPPORTED_TEST_RUNNERS_LIST;
},
nextTest: function() {
return nextTest;
}
});
const _fs = require("fs");
const _getprojectdir = require("../lib/get-project-dir");
const _utils = require("../server/lib/utils");
const _config = /*#__PURE__*/ _interop_require_default(require("../server/config"));
const _constants = require("../shared/lib/constants");
const _hasnecessarydependencies = require("../lib/has-necessary-dependencies");
const _installdependencies = require("../lib/install-dependencies");
const _findup = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/find-up"));
const _findpagesdir = require("../lib/find-pages-dir");
const _verifytypescriptsetup = require("../lib/verify-typescript-setup");
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
const _crossspawn = /*#__PURE__*/ _interop_require_default(require("next/dist/compiled/cross-spawn"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
const SUPPORTED_TEST_RUNNERS_LIST = [
'playwright'
];
const requiredPackagesByTestRunner = {
playwright: [
{
file: 'playwright',
pkg: '@playwright/test',
exportsRestrict: false
}
]
};
async function nextTest(directory, testRunnerArgs = [], options = {}) {
// The following mess is in order to support an existing Next.js CLI pattern of optionally, passing a project `directory` as the first argument to execute the command on.
// This is problematic for `next test` because as a wrapper around a test runner's `test` command, it needs to pass through any additional arguments and options.
// Thus, `directory` could either be a valid Next.js project directory (that the user intends to run `next test` on), or it is the first argument for the test runner.
// Unfortunately, since many test runners support passing a path (to a test file or directory containing test files), we must check if `directory` is both a valid path and a valid Next.js project.
let baseDir, nextConfig;
try {
// if directory is `undefined` or a valid path this will succeed.
baseDir = (0, _getprojectdir.getProjectDir)(directory, false);
} catch (err) {
// if that failed, then `directory` is not a valid path, so it must have meant to be the first item for `testRunnerArgs`
// @ts-expect-error directory is a string here since `getProjectDir` will succeed if its undefined
testRunnerArgs.unshift(directory);
// intentionally set baseDir to the resolved '.' path
baseDir = (0, _getprojectdir.getProjectDir)();
}
try {
// but, `baseDir` might not be a Next.js project directory, it could be a path-like argument for the test runner (i.e. `playwright test test/foo.spec.js`)
// if this succeeds, it means that `baseDir` is a Next.js project directory
nextConfig = await (0, _config.default)(_constants.PHASE_PRODUCTION_BUILD, baseDir);
} catch (err) {
// if it doesn't, then most likely `baseDir` is not a Next.js project directory
// @ts-expect-error directory is a string here since `getProjectDir` will succeed if its undefined
testRunnerArgs.unshift(directory);
// intentionally set baseDir to the resolved '.' path
baseDir = (0, _getprojectdir.getProjectDir)();
nextConfig = await (0, _config.default)(_constants.PHASE_PRODUCTION_BUILD, baseDir) // let this error bubble up if the `basePath` is still not a valid Next.js project
;
}
// set the test runner. priority is CLI option > next config > default 'playwright'
const configuredTestRunner = (options == null ? void 0 : options.testRunner) ?? // --test-runner='foo'
nextConfig.experimental.defaultTestRunner ?? // { experimental: { defaultTestRunner: 'foo' }}
'playwright';
if (!nextConfig.experimental.testProxy) {
return (0, _utils.printAndExit)(`\`next experimental-test\` requires the \`experimental.testProxy: true\` configuration option.`);
}
// execute test runner specific function
switch(configuredTestRunner){
case 'playwright':
return runPlaywright(baseDir, nextConfig, testRunnerArgs);
default:
return (0, _utils.printAndExit)(`Test runner ${configuredTestRunner} is not supported.`);
}
}
async function checkRequiredDeps(baseDir, testRunner) {
const deps = (0, _hasnecessarydependencies.hasNecessaryDependencies)(baseDir, requiredPackagesByTestRunner[testRunner]);
if (deps.missing.length > 0) {
await (0, _installdependencies.installDependencies)(baseDir, deps.missing, true);
const playwright = (0, _crossspawn.default)(_path.default.join(baseDir, 'node_modules', '.bin', 'playwright'), [
'install'
], {
cwd: baseDir,
shell: false,
stdio: 'inherit',
env: {
...process.env
}
});
return new Promise((resolve, reject)=>{
playwright.on('close', (c)=>resolve(c));
playwright.on('error', (err)=>reject(err));
});
}
}
async function runPlaywright(baseDir, nextConfig, testRunnerArgs) {
await checkRequiredDeps(baseDir, 'playwright');
const playwrightConfigFile = await (0, _findup.default)([
'playwright.config.js',
'playwright.config.ts'
], {
cwd: baseDir
});
if (!playwrightConfigFile) {
const { pagesDir, appDir } = (0, _findpagesdir.findPagesDir)(baseDir);
const { version: typeScriptVersion } = await (0, _verifytypescriptsetup.verifyAndRunTypeScript)({
dir: baseDir,
distDir: nextConfig.distDir,
strictRouteTypes: Boolean(nextConfig.experimental.strictRouteTypes),
shouldRunTypeCheck: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
typedRoutes: Boolean(nextConfig.typedRoutes),
disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir,
hasPagesDir: !!pagesDir,
appDir: appDir || undefined,
pagesDir: pagesDir || undefined
});
const isUsingTypeScript = !!typeScriptVersion;
const playwrightConfigFilename = isUsingTypeScript ? 'playwright.config.ts' : 'playwright.config.js';
(0, _fs.writeFileSync)(_path.default.join(baseDir, playwrightConfigFilename), defaultPlaywrightConfig(isUsingTypeScript));
return (0, _utils.printAndExit)(`Successfully generated ${playwrightConfigFilename}. Create your first test and then run \`next experimental-test\`.`, 0);
} else {
const playwright = (0, _crossspawn.default)(_path.default.join(baseDir, 'node_modules', '.bin', 'playwright'), [
'test',
...testRunnerArgs
], {
cwd: baseDir,
shell: false,
stdio: 'inherit',
env: {
...process.env
}
});
return new Promise((resolve, reject)=>{
playwright.on('close', (c)=>resolve(c));
playwright.on('error', (err)=>reject(err));
});
}
}
function defaultPlaywrightConfig(typescript) {
const comment = `/*
* Specify any additional Playwright config options here.
* They will be merged with Next.js' default Playwright config.
* You can access the default config by importing \`defaultPlaywrightConfig\` from \`'next/experimental/testmode/playwright'\`.
*/`;
return typescript ? `import { defineConfig } from 'next/experimental/testmode/playwright';\n\n${comment}\nexport default defineConfig({});` : `const { defineConfig } = require('next/experimental/testmode/playwright');\n\n${comment}\nmodule.exports = defineConfig({});`;
}
//# sourceMappingURL=next-test.js.map
+1
View File
File diff suppressed because one or more lines are too long
+6
View File
@@ -0,0 +1,6 @@
#!/usr/bin/env node
export type NextTypegenOptions = {
dir?: string;
};
declare const nextTypegen: (_options: NextTypegenOptions, directory?: string) => Promise<void>;
export { nextTypegen };
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "nextTypegen", {
enumerable: true,
get: function() {
return nextTypegen;
}
});
const _fs = require("fs");
const _path = /*#__PURE__*/ _interop_require_wildcard(require("path"));
const _promises = require("fs/promises");
const _config = /*#__PURE__*/ _interop_require_default(require("../server/config"));
const _utils = require("../server/lib/utils");
const _constants = require("../shared/lib/constants");
const _getprojectdir = require("../lib/get-project-dir");
const _findpagesdir = require("../lib/find-pages-dir");
const _verifytypescriptsetup = require("../lib/verify-typescript-setup");
const _routediscovery = require("../build/route-discovery");
const _routetypesutils = require("../server/lib/router-utils/route-types-utils");
const _cachelifetypeutils = require("../server/lib/router-utils/cache-life-type-utils");
const _installbindings = require("../build/swc/install-bindings");
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _getRequireWildcardCache(nodeInterop) {
if (typeof WeakMap !== "function") return null;
var cacheBabelInterop = new WeakMap();
var cacheNodeInterop = new WeakMap();
return (_getRequireWildcardCache = function(nodeInterop) {
return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
})(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
if (!nodeInterop && obj && obj.__esModule) {
return obj;
}
if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
return {
default: obj
};
}
var cache = _getRequireWildcardCache(nodeInterop);
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {
__proto__: null
};
var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
for(var key in obj){
if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
const nextTypegen = async (_options, directory)=>{
var _nextConfig_experimental;
const baseDir = (0, _getprojectdir.getProjectDir)(directory);
// Check if the provided directory exists
if (!(0, _fs.existsSync)(baseDir)) {
(0, _utils.printAndExit)(`> No such directory exists as the project root: ${baseDir}`);
}
const nextConfig = await (0, _config.default)(_constants.PHASE_PRODUCTION_BUILD, baseDir);
await (0, _installbindings.installBindings)((_nextConfig_experimental = nextConfig.experimental) == null ? void 0 : _nextConfig_experimental.useWasmBinary);
const distDir = (0, _path.join)(baseDir, nextConfig.distDir);
const { pagesDir, appDir } = (0, _findpagesdir.findPagesDir)(baseDir);
const strictRouteTypes = Boolean(nextConfig.experimental.strictRouteTypes);
await (0, _verifytypescriptsetup.verifyAndRunTypeScript)({
dir: baseDir,
distDir: nextConfig.distDir,
strictRouteTypes,
shouldRunTypeCheck: false,
tsconfigPath: nextConfig.typescript.tsconfigPath,
typedRoutes: Boolean(nextConfig.typedRoutes),
disableStaticImages: nextConfig.images.disableStaticImages,
hasAppDir: !!appDir,
hasPagesDir: !!pagesDir,
appDir: appDir || undefined,
pagesDir: pagesDir || undefined
});
console.log('Generating route types...');
const routeTypesFilePath = (0, _path.join)(distDir, 'types', 'routes.d.ts');
const validatorFilePath = (0, _path.join)(distDir, 'types', 'validator.ts');
await (0, _promises.mkdir)((0, _path.join)(distDir, 'types'), {
recursive: true
});
const isSrcDir = _path.default.relative(baseDir, pagesDir || appDir || '').startsWith('src');
// Build all routes (pages + app + slots)
const { pageRoutes, pageApiRoutes, appRoutes, appRouteHandlers, layoutRoutes, slots } = await (0, _routediscovery.discoverRoutes)({
appDir: appDir || undefined,
pagesDir: pagesDir || undefined,
pageExtensions: nextConfig.pageExtensions,
isDev: false,
baseDir,
isSrcDir
});
const routeTypesManifest = await (0, _routetypesutils.createRouteTypesManifest)({
dir: baseDir,
pageRoutes,
appRoutes,
appRouteHandlers,
pageApiRoutes,
layoutRoutes,
slots,
redirects: nextConfig.redirects,
rewrites: nextConfig.rewrites,
validatorFilePath
});
await (0, _routetypesutils.writeRouteTypesManifest)(routeTypesManifest, routeTypesFilePath, nextConfig);
await (0, _routetypesutils.writeValidatorFile)(routeTypesManifest, validatorFilePath, strictRouteTypes);
// Generate cache-life types if cacheLife config exists
const cacheLifeFilePath = (0, _path.join)(distDir, 'types', 'cache-life.d.ts');
(0, _cachelifetypeutils.writeCacheLifeTypes)(nextConfig.cacheLife, cacheLifeFilePath);
console.log('✓ Types generated successfully');
};
//# sourceMappingURL=next-typegen.js.map
File diff suppressed because one or more lines are too long
+6
View File
@@ -0,0 +1,6 @@
interface NextUpgradeOptions {
revision: string;
verbose: boolean;
}
export declare function spawnNextUpgrade(directory: string | undefined, options: NextUpgradeOptions): void;
export {};
+36
View File
@@ -0,0 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "spawnNextUpgrade", {
enumerable: true,
get: function() {
return spawnNextUpgrade;
}
});
const _child_process = require("child_process");
const _getprojectdir = require("../lib/get-project-dir");
const _getnpxcommand = require("../lib/helpers/get-npx-command");
function spawnNextUpgrade(directory, options) {
const baseDir = (0, _getprojectdir.getProjectDir)(directory);
const [upgradeProcessCommand, ...upgradeProcessDefaultArgs] = (0, _getnpxcommand.getNpxCommand)(baseDir).split(' ');
const upgradeProcessCommandArgs = [
...upgradeProcessDefaultArgs,
// Needs to be bleeding edge (canary) to pick up latest codemods.
'@next/codemod@canary',
'upgrade',
options.revision
];
if (options.verbose) {
upgradeProcessCommandArgs.push('--verbose');
}
const upgradeProcess = (0, _child_process.spawn)(upgradeProcessCommand, upgradeProcessCommandArgs, {
stdio: 'inherit',
cwd: baseDir
});
upgradeProcess.on('close', (code)=>{
process.exitCode = code ?? 0;
});
}
//# sourceMappingURL=next-upgrade.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"sources":["../../src/cli/next-upgrade.ts"],"sourcesContent":["import { spawn } from 'child_process'\nimport { getProjectDir } from '../lib/get-project-dir'\nimport { getNpxCommand } from '../lib/helpers/get-npx-command'\n\ninterface NextUpgradeOptions {\n revision: string\n verbose: boolean\n}\n\nexport function spawnNextUpgrade(\n directory: string | undefined,\n options: NextUpgradeOptions\n) {\n const baseDir = getProjectDir(directory)\n const [upgradeProcessCommand, ...upgradeProcessDefaultArgs] =\n getNpxCommand(baseDir).split(' ')\n\n const upgradeProcessCommandArgs = [\n ...upgradeProcessDefaultArgs,\n // Needs to be bleeding edge (canary) to pick up latest codemods.\n '@next/codemod@canary',\n 'upgrade',\n options.revision,\n ]\n if (options.verbose) {\n upgradeProcessCommandArgs.push('--verbose')\n }\n\n const upgradeProcess = spawn(\n upgradeProcessCommand,\n upgradeProcessCommandArgs,\n {\n stdio: 'inherit',\n cwd: baseDir,\n }\n )\n\n upgradeProcess.on('close', (code) => {\n process.exitCode = code ?? 0\n })\n}\n"],"names":["spawnNextUpgrade","directory","options","baseDir","getProjectDir","upgradeProcessCommand","upgradeProcessDefaultArgs","getNpxCommand","split","upgradeProcessCommandArgs","revision","verbose","push","upgradeProcess","spawn","stdio","cwd","on","code","process","exitCode"],"mappings":";;;;+BASgBA;;;eAAAA;;;+BATM;+BACQ;+BACA;AAOvB,SAASA,iBACdC,SAA6B,EAC7BC,OAA2B;IAE3B,MAAMC,UAAUC,IAAAA,4BAAa,EAACH;IAC9B,MAAM,CAACI,uBAAuB,GAAGC,0BAA0B,GACzDC,IAAAA,4BAAa,EAACJ,SAASK,KAAK,CAAC;IAE/B,MAAMC,4BAA4B;WAC7BH;QACH,iEAAiE;QACjE;QACA;QACAJ,QAAQQ,QAAQ;KACjB;IACD,IAAIR,QAAQS,OAAO,EAAE;QACnBF,0BAA0BG,IAAI,CAAC;IACjC;IAEA,MAAMC,iBAAiBC,IAAAA,oBAAK,EAC1BT,uBACAI,2BACA;QACEM,OAAO;QACPC,KAAKb;IACP;IAGFU,eAAeI,EAAE,CAAC,SAAS,CAACC;QAC1BC,QAAQC,QAAQ,GAAGF,QAAQ;IAC7B;AACF","ignoreList":[0]}