import type { FindComponentsResult, NodeRequestHandler } from '../next-server' import type { LoadComponentsReturnType } from '../load-components' import type { Options as ServerOptions } from '../next-server' import type { Params } from '../request/params' import type { ParsedUrl } from '../../shared/lib/router/utils/parse-url' import type { ParsedUrlQuery } from 'querystring' import type { UrlWithParsedQuery } from 'url' import type { MiddlewareRoutingItem } from '../base-server' import type { RouteDefinition } from '../route-definitions/route-definition' import type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager' import { addRequestMeta, getRequestMeta, type NextParsedUrlQuery, type NextUrlWithParsedQuery, } from '../request-meta' import type { DevBundlerService } from '../lib/dev-bundler-service' import type { IncrementalCache } from '../lib/incremental-cache' import type { UnwrapPromise } from '../../lib/coalesced-function' import type { NodeNextResponse, NodeNextRequest } from '../base-http/node' import type { RouteEnsurer } from '../route-matcher-managers/dev-route-matcher-manager' import type { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin' import * as React from 'react' import fs from 'fs' import { Worker } from 'next/dist/compiled/jest-worker' import { join as pathJoin } from 'path' import { ampValidation } from '../../build/output' import { PUBLIC_DIR_MIDDLEWARE_CONFLICT } from '../../lib/constants' import { findPagesDir } from '../../lib/find-pages-dir' import { PHASE_DEVELOPMENT_SERVER, PAGES_MANIFEST, APP_PATHS_MANIFEST, COMPILER_NAMES, PRERENDER_MANIFEST, } from '../../shared/lib/constants' import Server, { WrappedBuildError } from '../next-server' import { normalizePagePath } from '../../shared/lib/page-path/normalize-page-path' import { pathHasPrefix } from '../../shared/lib/router/utils/path-has-prefix' import { removePathPrefix } from '../../shared/lib/router/utils/remove-path-prefix' import { Telemetry } from '../../telemetry/storage' import { type Span, setGlobal, trace } from '../../trace' import { findPageFile } from '../lib/find-page-file' import { getFormattedNodeOptionsWithoutInspect } from '../lib/utils' import { withCoalescedInvoke } from '../../lib/coalesced-function' import { loadDefaultErrorComponents } from '../load-default-error-components' import { DecodeError, MiddlewareNotFoundError } from '../../shared/lib/utils' import * as Log from '../../build/output/log' import isError, { getProperError } from '../../lib/is-error' import { isMiddlewareFile } from '../../build/utils' import { formatServerError } from '../../lib/format-server-error' import { DevRouteMatcherManager } from '../route-matcher-managers/dev-route-matcher-manager' import { DevPagesRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-route-matcher-provider' import { DevPagesAPIRouteMatcherProvider } from '../route-matcher-providers/dev/dev-pages-api-route-matcher-provider' import { DevAppPageRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-page-route-matcher-provider' import { DevAppRouteRouteMatcherProvider } from '../route-matcher-providers/dev/dev-app-route-route-matcher-provider' import { NodeManifestLoader } from '../route-matcher-providers/helpers/manifest-loaders/node-manifest-loader' import { BatchedFileReader } from '../route-matcher-providers/dev/helpers/file-reader/batched-file-reader' import { DefaultFileReader } from '../route-matcher-providers/dev/helpers/file-reader/default-file-reader' import { LRUCache } from '../lib/lru-cache' import { getMiddlewareRouteMatcher } from '../../shared/lib/router/utils/middleware-route-matcher' import { DetachedPromise } from '../../lib/detached-promise' import { isPostpone } from '../lib/router-utils/is-postpone' import { generateInterceptionRoutesRewrites } from '../../lib/generate-interception-routes-rewrites' import { buildCustomRoute } from '../../lib/build-custom-route' import { decorateServerError } from '../../shared/lib/error-source' import type { ServerOnInstrumentationRequestError } from '../app-render/types' import type { ServerComponentsHmrCache } from '../response-cache' import { logRequests } from './log-requests' import { FallbackMode, fallbackModeToFallbackField } from '../../lib/fallback' import type { PagesDevOverlayBridgeType } from '../../next-devtools/userspace/pages/pages-dev-overlay-setup' import { ensureInstrumentationRegistered, getInstrumentationModule, } from '../lib/router-utils/instrumentation-globals.external' import type { PrerenderManifest } from '../../build' import { getRouteRegex } from '../../shared/lib/router/utils/route-regex' // Load ReactDevOverlay only when needed let PagesDevOverlayBridgeImpl: PagesDevOverlayBridgeType const ReactDevOverlay: PagesDevOverlayBridgeType = (props) => { if (PagesDevOverlayBridgeImpl === undefined) { PagesDevOverlayBridgeImpl = ( require('../../next-devtools/userspace/pages/pages-dev-overlay-setup') as typeof import('../../next-devtools/userspace/pages/pages-dev-overlay-setup') ).PagesDevOverlayBridge } return React.createElement(PagesDevOverlayBridgeImpl, props) } export interface Options extends ServerOptions { /** * Tells of Next.js is running from the `next dev` command */ isNextDevCommand?: boolean /** * Interface to the development bundler. */ bundlerService: DevBundlerService /** * Trace span for server startup. */ startServerSpan: Span } export default class DevServer extends Server { /** * The promise that resolves when the server is ready. When this is unset * the server is ready. */ private ready? = new DetachedPromise() protected sortedRoutes?: string[] private pagesDir?: string private appDir?: string private actualMiddlewareFile?: string private actualInstrumentationHookFile?: string private middleware?: MiddlewareRoutingItem private readonly bundlerService: DevBundlerService private staticPathsCache: LRUCache< UnwrapPromise> > private startServerSpan: Span private readonly serverComponentsHmrCache: | ServerComponentsHmrCache | undefined protected staticPathsWorker?: { [key: string]: any } & { loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths } private getStaticPathsWorker(): { [key: string]: any } & { loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths } { const worker = new Worker(require.resolve('./static-paths-worker'), { maxRetries: 1, // For dev server, it's not necessary to spin up too many workers as long as you are not doing a load test. // This helps reusing the memory a lot. numWorkers: 1, enableWorkerThreads: this.nextConfig.experimental.workerThreads, forkOptions: { env: { ...process.env, // discard --inspect/--inspect-brk flags from process.env.NODE_OPTIONS. Otherwise multiple Node.js debuggers // would be started if user launch Next.js in debugging mode. The number of debuggers is linked to // the number of workers Next.js tries to launch. The only worker users are interested in debugging // is the main Next.js one NODE_OPTIONS: getFormattedNodeOptionsWithoutInspect(), }, }, }) as Worker & { loadStaticPaths: typeof import('./static-paths-worker').loadStaticPaths } worker.getStdout().pipe(process.stdout) worker.getStderr().pipe(process.stderr) return worker } constructor(options: Options) { try { // Increase the number of stack frames on the server Error.stackTraceLimit = 50 } catch {} super({ ...options, dev: true }) this.bundlerService = options.bundlerService this.startServerSpan = options.startServerSpan ?? trace('start-next-dev-server') this.renderOpts.dev = true this.renderOpts.ErrorDebug = ReactDevOverlay this.staticPathsCache = new LRUCache( // 5MB 5 * 1024 * 1024, function length(value) { return JSON.stringify(value.staticPaths)?.length ?? 0 } ) this.renderOpts.ampSkipValidation = this.nextConfig.experimental?.amp?.skipValidation ?? false this.renderOpts.ampValidator = async (html: string, pathname: string) => { const { getAmpValidatorInstance, getBundledAmpValidatorFilepath } = require('../../export/helpers/get-amp-html-validator') as typeof import('../../export/helpers/get-amp-html-validator') const validatorPath = this.nextConfig.experimental?.amp?.validator || getBundledAmpValidatorFilepath() const validator = await getAmpValidatorInstance(validatorPath) const result = validator.validateString(html) ampValidation( pathname, result.errors .filter((error) => { if (error.severity === 'ERROR') { // Unclear yet if these actually prevent the page from being indexed by the AMP cache. // These are coming from React so all we can do is ignore them for now. // // https://github.com/ampproject/amphtml/issues/40279 if ( error.code === 'DISALLOWED_ATTR' && error.params[0] === 'blocking' && error.params[1] === 'link' ) { return false } //