{"version":3,"sources":["../../../../src/server/dev/hot-reloader-turbopack.ts"],"sourcesContent":["import type { Socket } from 'net'\nimport { mkdir, writeFile } from 'fs/promises'\nimport { realpathSync } from 'fs'\nimport * as inspector from 'inspector'\nimport { join, extname, relative, isAbsolute, sep } from 'path'\nimport { fileURLToPath, pathToFileURL } from 'url'\n\nimport ws from 'next/dist/compiled/ws'\n\nimport type { OutputState } from '../../build/output/store'\nimport { store as consoleStore } from '../../build/output/store'\nimport type {\n  CompilationError,\n  HmrMessageSentToBrowser,\n  NextJsHotReloaderInterface,\n  ReloadPageMessage,\n  SyncMessage,\n  TurbopackConnectedMessage,\n} from './hot-reloader-types'\nimport { HMR_MESSAGE_SENT_TO_BROWSER } from './hot-reloader-types'\nimport type {\n  Update as TurbopackUpdate,\n  Endpoint,\n  WrittenEndpoint,\n  TurbopackResult,\n  Project,\n  Entrypoints,\n  NodeJsHmrUpdate,\n  NodeJsPartialHmrUpdate,\n} from '../../build/swc/types'\nimport { createDefineEnv, getBindingsSync, HmrTarget } from '../../build/swc'\nimport * as Log from '../../build/output/log'\nimport { BLOCKED_PAGES } from '../../shared/lib/constants'\nimport {\n  getOverlayMiddleware,\n  getSourceMapMiddleware,\n  getOriginalStackFrames,\n} from './middleware-turbopack'\nimport { PageNotFoundError } from '../../shared/lib/utils'\nimport { debounce } from '../utils'\nimport { clearManifestCache } from '../load-manifest.external'\nimport { deleteCache } from './require-cache'\nimport {\n  dropDevValidationWorker,\n  mirrorModuleStateToDevValidationWorker,\n} from './dev-validation-worker-pool'\nimport {\n  clearAllModuleContexts,\n  clearModuleContext,\n} from '../lib/render-server'\nimport { denormalizePagePath } from '../../shared/lib/page-path/denormalize-page-path'\nimport { trace } from '../../trace'\nimport {\n  AssetMapper,\n  type ChangeSubscriptions,\n  type ClientState,\n  handleEntrypoints,\n  handlePagesErrorRoute,\n  handleRouteType,\n  hasEntrypointForKey,\n  msToNs,\n  type ReadyIds,\n  type SendHmr,\n  type StartBuilding,\n  processTopLevelIssues,\n  printNonFatalIssue,\n  normalizedPageToTurbopackStructureRoute,\n  type StartChangeSubscription,\n} from './turbopack-utils'\nimport {\n  propagateServerField,\n  type ServerFields,\n  type SetupOpts,\n} from '../lib/router-utils/setup-dev-bundler'\nimport { TurbopackManifestLoader } from '../../shared/lib/turbopack/manifest-loader'\nimport { findPagePathData } from './on-demand-entry-handler'\nimport type { RouteDefinition } from '../route-definitions/route-definition'\nimport {\n  type EntryKey,\n  getEntryKey,\n  splitEntryKey,\n} from '../../shared/lib/turbopack/entry-key'\nimport {\n  createBinaryHmrMessageData,\n  FAST_REFRESH_RUNTIME_RELOAD,\n} from './messages'\nimport { generateEncryptionKeyBase64 } from '../app-render/encryption-utils-server'\nimport { isAppPageRouteDefinition } from '../route-definitions/app-page-route-definition'\nimport { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'\nimport type { ModernSourceMapPayload } from '../lib/source-maps'\nimport { isDeferredEntry } from '../../build/entries'\nimport { isMetadataRouteFile } from '../../lib/metadata/is-metadata-route'\nimport { setBundlerFindSourceMapImplementation } from '../patch-error-inspect'\nimport { setBundlerFindSourceMapURLImplementation } from '../lib/source-maps'\nimport { getNextErrorFeedbackMiddleware } from '../../next-devtools/server/get-next-error-feedback-middleware'\nimport {\n  formatIssue,\n  isFileSystemCacheEnabledForDev,\n  isWellKnownError,\n  ModuleBuildError,\n  processIssues,\n  renderStyledStringToErrorAnsi,\n  type EntryIssuesMap,\n  type IssuesMap,\n  type TopLevelIssuesMap,\n} from '../../shared/lib/turbopack/utils'\nimport { getDevOverlayFontMiddleware } from '../../next-devtools/server/font/get-dev-overlay-font-middleware'\nimport { devIndicatorServerState } from './dev-indicator-server-state'\nimport { getDisableDevIndicatorMiddleware } from '../../next-devtools/server/dev-indicator-middleware'\nimport { getRestartDevServerMiddleware } from '../../next-devtools/server/restart-dev-server-middleware'\nimport { backgroundLogCompilationEvents } from '../../shared/lib/turbopack/compilation-events'\nimport { DeferredEmit } from '../../shared/lib/turbopack/deferred-emit'\nimport { getSupportedBrowsers } from '../../build/get-supported-browsers'\nimport { printBuildErrors } from '../../build/print-build-errors'\nimport { receiveBrowserLogsTurbopack } from './browser-logs/receive-logs'\nimport { normalizePath } from '../../lib/normalize-path'\nimport { seedTurbopackCacheIfNeeded } from '../../lib/turbopack-cache-seed'\nimport {\n  devToolsConfigMiddleware,\n  getDevToolsConfig,\n} from '../../next-devtools/server/devtools-config-middleware'\nimport { getAttachNodejsDebuggerMiddleware } from '../../next-devtools/server/attach-nodejs-debugger-middleware'\nimport {\n  connectReactDebugChannel,\n  connectReactDebugChannelForHtmlRequest,\n  deleteReactDebugChannelForHtmlRequest,\n  setReactDebugChannelForHtmlRequest,\n} from './debug-channel'\nimport {\n  getVersionInfo,\n  matchNextPageBundleRequest,\n} from './hot-reloader-shared-utils'\nimport { getMcpMiddleware } from '../mcp/get-mcp-middleware'\nimport { formatCompilationIssues } from '../mcp/tools/utils/format-compilation-issues'\nimport {\n  getRequestInsightsSnapshot,\n  isRequestInsightsEnabled,\n} from '../lib/trace/request-insights'\nimport { resolvePathToRoute } from '../mcp/tools/utils/resolve-path-to-route'\nimport { handleErrorStateResponse } from '../mcp/tools/get-errors'\nimport { handlePageMetadataResponse } from '../mcp/tools/get-page-metadata'\nimport { setStackFrameResolver } from '../mcp/tools/utils/format-errors'\nimport { recordMcpTelemetry } from '../mcp/mcp-telemetry-tracker'\nimport { getFileLogger } from './browser-logs/file-logger'\nimport type { ServerCacheStatus } from '../../next-devtools/dev-overlay/cache-indicator'\nimport type { Lockfile } from '../../build/lockfile'\nimport {\n  sendSerializedErrorsToClient,\n  sendSerializedErrorsToClientForHtmlRequest,\n  setErrorsRscStreamForHtmlRequest,\n} from './serialized-errors'\n\nconst wsServer = new ws.Server({ noServer: true })\nconst isTestMode = !!(\n  process.env.NEXT_TEST_MODE ||\n  process.env.__NEXT_TEST_MODE ||\n  process.env.DEBUG\n)\n\nconst sessionId = Math.floor(Number.MAX_SAFE_INTEGER * Math.random())\n\n/** Output directory (relative to `distDir`) of server-HMR-managed chunks. */\nconst SERVER_HMR_CHUNKS_DIR = join('server', 'chunks')\n\ndeclare const __next__clear_chunk_cache__: (() => void) | null | undefined\n\ndeclare const __turbopack_server_hmr_apply__:\n  | ((update: NodeJsPartialHmrUpdate) => void)\n  | undefined\n\ndeclare global {\n  /**\n   * Sync with  `turbopack/crates/turbopack-ecmascript-runtime/js/src/nodejs/runtime/nodejs-globals.d.ts`.\n   */\n  var __turbopack_server_hmr_handlers__: Map<string, unknown> | undefined\n}\n\n/**\n * Collects the output chunk paths touched by a partial HMR update. Both\n * single-chunk `EcmascriptMergedUpdate`s and `ChunkListUpdate`s (which nest\n * per-chunk deltas inside `merged`) are flattened so the manifest cache can be\n * invalidated for every affected chunk after a successful apply.\n */\nfunction collectUpdatedChunkPaths(\n  instruction: NodeJsPartialHmrUpdate['instruction']\n): string[] {\n  const paths = new Set<string>()\n  if (instruction.type === 'EcmascriptMergedUpdate') {\n    for (const chunkPath of Object.keys(instruction.chunks ?? {})) {\n      paths.add(chunkPath)\n    }\n  } else if (instruction.type === 'ChunkListUpdate') {\n    for (const chunkPath of Object.keys(instruction.chunks ?? {})) {\n      paths.add(chunkPath)\n    }\n    for (const merged of instruction.merged ?? []) {\n      for (const chunkPath of Object.keys(merged.chunks ?? {})) {\n        paths.add(chunkPath)\n      }\n    }\n  } else {\n    throw new Error(\n      `[Server HMR] unreachable: unknown HMR instruction type ${(instruction as { type: string }).type}`\n    )\n  }\n  return Array.from(paths)\n}\n\nfunction setupServerHmr(\n  project: Project,\n  {\n    reEvaluateAllModulesExpensive,\n    onApplied,\n  }: {\n    reEvaluateAllModulesExpensive: () => void | Promise<void>\n    onApplied: (chunkPaths: string[]) => void | Promise<void>\n  }\n) {\n  async function runSubscription() {\n    const subscription = project.allHmrEvents(HmrTarget.Server)\n\n    // Subscribing immediately emits one event describing the current state.\n    // There's no previous state to diff it against, so it never carries anything\n    // to apply. Drop it; real updates start with the second event.\n    await subscription.next()\n\n    for await (const result of subscription) {\n      const update = result as NodeJsHmrUpdate\n\n      // A 'restart' from the wire protocol means the update can't be applied\n      // incrementally, so we must fully re-evaluate all chunks from disk. This\n      // clears the module cache and notifies browsers to refetch RSC.\n      const requiresFullReEvaluation = update.type === 'restart'\n      if (requiresFullReEvaluation) {\n        await reEvaluateAllModulesExpensive()\n        continue\n      }\n\n      if (update.type !== 'partial') {\n        continue\n      }\n\n      // `EcmascriptMergedUpdate` is the only instruction the Node.js runtime\n      // knows how to apply; `ChunkListUpdate` is browser-only. Anything else is\n      // unknown to us, so ignore it rather than evicting the module cache.\n      const instruction = update.instruction\n      if (\n        !instruction ||\n        (instruction.type !== 'EcmascriptMergedUpdate' &&\n          instruction.type !== 'ChunkListUpdate')\n      ) {\n        throw new Error(\n          `[Server HMR] unreachable: unexpected update instruction type ${(instruction as { type: string }).type}`\n        )\n      }\n\n      // No handler registered yet (before first request, or right after\n      // reEvaluateAllModulesExpensive()) — nothing live to update, so skip\n      // until the next request.\n      const handlers = globalThis.__turbopack_server_hmr_handlers__\n      if (!handlers || handlers.size === 0) {\n        continue\n      }\n\n      if (typeof __turbopack_server_hmr_apply__ === 'function') {\n        try {\n          __turbopack_server_hmr_apply__(update)\n          // The validation worker keeps its own copy of the module graph, and\n          // applies the same update to it.\n          mirrorModuleStateToDevValidationWorker({ type: 'apply', update })\n        } catch {\n          // A matching runtime tried the apply and threw. Evict require.cache\n          // so the next request loads fresh, then skip onApplied. (A no-match\n          // update is a no-op and does not throw.)\n          await reEvaluateAllModulesExpensive()\n          continue\n        }\n\n        const updatedChunkPaths = collectUpdatedChunkPaths(instruction)\n        // An empty partial only advances the version state (e.g. the seed\n        // transition or a new endpoint); nothing changed on disk, so don't\n        // invalidate manifests or ping browsers to refetch RSC.\n        if (updatedChunkPaths.length > 0) {\n          await onApplied(updatedChunkPaths)\n        }\n      } else {\n        await reEvaluateAllModulesExpensive()\n      }\n    }\n  }\n\n  // Start listening for changes in background. Re-subscribe on error so\n  // server Fast Refresh continues working for the rest of the dev session.\n  // The delay keeps a persistently-failing subscription (which throws on the\n  // initial read) from hot-looping through reEvaluateAllModulesExpensive().\n  ;(async () => {\n    for (;;) {\n      try {\n        await runSubscription()\n        return\n      } catch (err) {\n        console.error('[Server HMR] Subscription error, resubscribing:', err)\n        await reEvaluateAllModulesExpensive()\n        await new Promise((resolve) => setTimeout(resolve, 1000))\n      }\n    }\n  })()\n}\n\nfunction getSourceMapFromTurbopack(\n  project: Project,\n  sourceURL: string\n): ModernSourceMapPayload | undefined {\n  let sourceMapJson: string | null = null\n\n  try {\n    sourceMapJson = project.getSourceMapSync(sourceURL)\n  } catch (err) {}\n\n  if (sourceMapJson === null) {\n    return undefined\n  } else {\n    return JSON.parse(sourceMapJson)\n  }\n}\n\nfunction getSourceMapURLFromTurbopack(\n  distDir: string,\n  scriptNameOrSourceURL: string\n): string | null {\n  // React invokes this with the raw stack-frame filename, which arrives\n  // either as an absolute filesystem path or as a `file:` URL. Anything else\n  // (`file:` URLs with a query are eval'd server HMR modules carrying inline\n  // source maps, `webpack-internal://`, `node:internal/...`, `<anonymous>`,\n  // ...) is not something we have an emitted source map for.\n  let scriptPath = scriptNameOrSourceURL\n  if (scriptNameOrSourceURL.startsWith('file://')) {\n    if (scriptNameOrSourceURL.includes('?')) {\n      return null\n    }\n    try {\n      scriptPath = fileURLToPath(scriptNameOrSourceURL)\n    } catch {\n      return null\n    }\n  }\n  if (!isAbsolute(scriptPath)) {\n    return null\n  }\n\n  // Only chunks emitted into `distDir` have an on-disk source map to point at.\n  const relativePath = relative(distDir, scriptPath)\n  if (\n    relativePath.startsWith('..') ||\n    // On Windows an absolute path on a different drive is returned unchanged\n    // rather than as a `..`-prefixed relative path.\n    isAbsolute(relativePath)\n  ) {\n    return null\n  }\n\n  // The emitted source map lives next to its chunk with a `.map` suffix (see\n  // `SourceMapAsset::path`). Encode through `pathToFileURL` so any special\n  // characters in the path are escaped into a well-formed `file:` URL.\n  return pathToFileURL(scriptPath + '.map').href\n}\n\nexport async function createHotReloaderTurbopack(\n  opts: SetupOpts & { isSrcDir: boolean },\n  serverFields: ServerFields,\n  distDir: string,\n  resetFetch: () => void,\n  lockfile: Lockfile | undefined,\n  serverFastRefresh?: boolean\n): Promise<NextJsHotReloaderInterface> {\n  const dev = true\n  const buildId = 'development'\n  const { nextConfig, dir: projectPath } = opts\n\n  const bindings = getBindingsSync()\n\n  // Turbopack requires native bindings and cannot run with WASM bindings.\n  // Detect this early and give a clear, actionable error message.\n  if (bindings.isWasm) {\n    throw new Error(\n      `Turbopack is not supported on this platform (${process.platform}/${process.arch}) because native bindings are not available. ` +\n        `Only WebAssembly (WASM) bindings were loaded, and Turbopack requires native bindings.\\n\\n` +\n        `To use Next.js on this platform, use Webpack instead:\\n` +\n        `  next dev --webpack\\n\\n` +\n        `For more information, see: https://nextjs.org/docs/app/api-reference/turbopack#supported-platforms`\n    )\n  }\n\n  // For the debugging purpose, check if createNext or equivalent next instance setup in test cases\n  // works correctly. Normally `run-test` hides output so only will be visible when `--debug` flag is used.\n  if (isTestMode) {\n    ;(require('console') as typeof import('console')).log(\n      'Creating turbopack project',\n      {\n        dir: projectPath,\n        testMode: isTestMode,\n      }\n    )\n  }\n\n  const hasRewrites =\n    opts.fsChecker.rewrites.afterFiles.length > 0 ||\n    opts.fsChecker.rewrites.beforeFiles.length > 0 ||\n    opts.fsChecker.rewrites.fallback.length > 0\n\n  const hotReloaderSpan = trace('hot-reloader', undefined, {\n    version: process.env.__NEXT_VERSION as string,\n  })\n  // Ensure the hotReloaderSpan is flushed immediately as it's the parentSpan for all processing\n  // of the current `next dev` invocation.\n  hotReloaderSpan.stop()\n\n  // Initialize log monitor for file logging\n  // Enable logging by default in development mode\n  const mcpServerEnabled = !!nextConfig.experimental.mcpServer\n  const fileLogger = getFileLogger()\n  fileLogger.initialize(distDir, mcpServerEnabled)\n\n  const encryptionKey = await generateEncryptionKeyBase64({\n    isBuild: false,\n    distDir,\n  })\n\n  // TODO: Implement\n  let clientRouterFilters: any\n  if (nextConfig.experimental.clientRouterFilter) {\n    // TODO this need to be set correctly for filesystem cache to work\n  }\n\n  const supportedBrowsers = getSupportedBrowsers(projectPath, dev)\n  const currentNodeJsVersion = process.versions.node\n\n  const rootPath =\n    opts.nextConfig.turbopack?.root ||\n    opts.nextConfig.outputFileTracingRoot ||\n    projectPath\n\n  if (nextConfig.experimental.turbopackSeedCacheFromWorktree) {\n    seedTurbopackCacheIfNeeded({\n      projectDir: projectPath,\n      distDir,\n    })\n  }\n\n  const project = await bindings.turbo.createProject(\n    {\n      rootPath,\n      projectPath: normalizePath(relative(rootPath, projectPath) || '.'),\n      distDir,\n      nextConfig: opts.nextConfig,\n      watch: {\n        enable: dev,\n        pollIntervalMs: nextConfig.watchOptions?.pollIntervalMs,\n      },\n      dev,\n      env: process.env as Record<string, string>,\n      defineEnv: createDefineEnv({\n        isTurbopack: true,\n        clientRouterFilters,\n        config: nextConfig,\n        dev,\n        distDir,\n        projectPath,\n        fetchCacheKeyPrefix: opts.nextConfig.experimental.fetchCacheKeyPrefix,\n        hasRewrites,\n        // TODO: Implement\n        middlewareMatchers: undefined,\n        rewrites: opts.fsChecker.rewrites,\n      }),\n      buildId,\n      encryptionKey,\n      previewProps: opts.fsChecker.previewProps,\n      browserslistQuery: supportedBrowsers.join(', '),\n      noMangling: false,\n      writeRoutesHashesManifest: false,\n      currentNodeJsVersion,\n      isPersistentCachingEnabled: isFileSystemCacheEnabledForDev(\n        opts.nextConfig\n      ),\n      nextVersion: process.env.__NEXT_VERSION as string,\n      serverHmr: serverFastRefresh,\n    },\n    {\n      turbopackMemoryEviction:\n        opts.nextConfig.experimental.turbopackMemoryEvictionMode,\n      isShortSession: false,\n    }\n  )\n  backgroundLogCompilationEvents(project, {\n    eventTypes: [\n      'StartupCacheInvalidationEvent',\n      'TimingEvent',\n      'SlowFilesystemEvent',\n      'TraceEvent',\n    ],\n    parentSpan: hotReloaderSpan,\n  })\n  setBundlerFindSourceMapImplementation(\n    getSourceMapFromTurbopack.bind(null, project)\n  )\n\n  let canonicalDistDir = distDir\n  try {\n    canonicalDistDir = realpathSync(distDir)\n  } catch {}\n  setBundlerFindSourceMapURLImplementation(\n    getSourceMapURLFromTurbopack.bind(null, canonicalDistDir)\n  )\n\n  // Set up code frame renderer using native bindings\n  const { installCodeFrameSupport } =\n    require('../lib/install-code-frame') as typeof import('../lib/install-code-frame')\n  installCodeFrameSupport()\n\n  opts.onDevServerCleanup?.(async () => {\n    setBundlerFindSourceMapImplementation(() => undefined)\n    setBundlerFindSourceMapURLImplementation(() => null)\n    await project.onExit()\n    await lockfile?.unlock()\n  })\n  const entrypointsSubscription = project.entrypointsSubscribe()\n\n  const currentWrittenEntrypoints: Map<EntryKey, WrittenEndpoint> = new Map()\n  const currentEntrypoints: Entrypoints = {\n    global: {\n      app: undefined,\n      document: undefined,\n      error: undefined,\n\n      middleware: undefined,\n      instrumentation: undefined,\n    },\n\n    page: new Map(),\n    app: new Map(),\n  }\n\n  const currentTopLevelIssues: TopLevelIssuesMap = new Map()\n  const currentEntryIssues: EntryIssuesMap = new Map()\n\n  const manifestLoader = new TurbopackManifestLoader({\n    buildId,\n    distDir,\n    encryptionKey,\n    dev: true,\n    sriEnabled: false,\n  })\n\n  // Dev specific\n  const changeSubscriptions: ChangeSubscriptions = new Map()\n  const serverPathState = new Map<string, string>()\n  const readyIds: ReadyIds = new Set()\n  let currentEntriesHandlingResolve: ((value?: unknown) => void) | undefined\n  let currentEntriesHandling = new Promise(\n    (resolve) => (currentEntriesHandlingResolve = resolve)\n  )\n\n  const assetMapper = new AssetMapper()\n\n  // Deferred entries state management\n  const deferredEntriesConfig = nextConfig.experimental.deferredEntries\n  const hasDeferredEntriesConfig =\n    deferredEntriesConfig && deferredEntriesConfig.length > 0\n  let onBeforeDeferredEntriesCalled = false\n  let onBeforeDeferredEntriesPromise: Promise<void> | null = null\n  // Track non-deferred entries that are currently being built\n  const nonDeferredBuildingEntries: Set<string> = new Set()\n\n  // Function to wait for all non-deferred entries to be built\n  async function waitForNonDeferredEntries(): Promise<void> {\n    return new Promise<void>((resolve) => {\n      const checkEntries = () => {\n        // Check if there are any non-deferred entries that are still building\n        if (nonDeferredBuildingEntries.size === 0) {\n          resolve()\n        } else {\n          // Check again after a short delay\n          setTimeout(checkEntries, 100)\n        }\n      }\n      checkEntries()\n    })\n  }\n\n  // Function to handle deferred entry processing\n  async function processDeferredEntry(): Promise<void> {\n    if (!hasDeferredEntriesConfig) return\n\n    // Wait for all non-deferred entries to be built\n    await waitForNonDeferredEntries()\n\n    // Call the onBeforeDeferredEntries callback once\n    if (!onBeforeDeferredEntriesCalled) {\n      onBeforeDeferredEntriesCalled = true\n\n      if (nextConfig.experimental.onBeforeDeferredEntries) {\n        if (!onBeforeDeferredEntriesPromise) {\n          onBeforeDeferredEntriesPromise =\n            nextConfig.experimental.onBeforeDeferredEntries()\n        }\n        await onBeforeDeferredEntriesPromise\n      }\n    } else if (onBeforeDeferredEntriesPromise) {\n      // Wait for any in-progress callback\n      await onBeforeDeferredEntriesPromise\n    }\n  }\n\n  // Track whether HMR is pending - used to call callback once after HMR settles\n  let hmrPendingDeferredCallback = false\n\n  // Debounced function to call onBeforeDeferredEntries after HMR\n  // This prevents rapid-fire calls when turbopack fires many update events\n  // Use 500ms debounce to ensure all rapid updates are batched together\n  const callOnBeforeDeferredEntriesAfterHMR = debounce(() => {\n    // Only call if HMR triggered a need for the callback\n    if (hasDeferredEntriesConfig && hmrPendingDeferredCallback) {\n      hmrPendingDeferredCallback = false\n      onBeforeDeferredEntriesCalled = true\n      if (nextConfig.experimental.onBeforeDeferredEntries) {\n        onBeforeDeferredEntriesPromise =\n          nextConfig.experimental.onBeforeDeferredEntries()\n      }\n    }\n  }, 500)\n\n  function clearRequireCache(\n    key: EntryKey,\n    writtenEndpoint: WrittenEndpoint,\n    {\n      force,\n    }: {\n      // Always clear the cache, don't check if files have changed\n      force?: boolean\n    } = {}\n  ): boolean {\n    if (force) {\n      for (const { path, contentHash } of writtenEndpoint.serverPaths) {\n        // We ignore source maps\n        if (path.endsWith('.map')) continue\n        const localKey = `${key}:${path}`\n        serverPathState.set(localKey, contentHash)\n        serverPathState.set(path, contentHash)\n      }\n    } else {\n      // Figure out if the server files have changed\n      let hasChange = false\n      const currentPaths = new Set<string>()\n      for (const { path, contentHash } of writtenEndpoint.serverPaths) {\n        // We ignore source maps\n        if (path.endsWith('.map')) continue\n        currentPaths.add(path)\n        const localKey = `${key}:${path}`\n        const localHash = serverPathState.get(localKey)\n        const globalHash = serverPathState.get(path)\n        if (\n          (localHash && localHash !== contentHash) ||\n          (globalHash && globalHash !== contentHash)\n        ) {\n          hasChange = true\n          serverPathState.set(localKey, contentHash)\n          serverPathState.set(path, contentHash)\n        } else {\n          if (!localHash) {\n            serverPathState.set(localKey, contentHash)\n          }\n          if (!globalHash) {\n            serverPathState.set(path, contentHash)\n          }\n        }\n      }\n\n      const localKeyPrefix = `${key}:`\n      for (const pathKey of serverPathState.keys()) {\n        if (\n          pathKey.startsWith(localKeyPrefix) &&\n          !currentPaths.has(pathKey.slice(localKeyPrefix.length))\n        ) {\n          serverPathState.delete(pathKey)\n          hasChange = true\n        }\n      }\n\n      if (!hasChange) {\n        return false\n      }\n    }\n\n    // Edge does not participate in server HMR.\n    if (writtenEndpoint.type === 'edge') {\n      void clearAllModuleContexts()\n    }\n\n    const serverPaths = writtenEndpoint.serverPaths.map(({ path: p }) =>\n      join(distDir, p)\n    )\n\n    const { type: entryType } = splitEntryKey(key)\n\n    // Server HMR applies to App Router entries built with the Turbopack Node.js\n    // runtime: app pages and route handlers (including metadata routes). Edge\n    // routes, Pages Router pages, and middleware/instrumentation are excluded.\n    const usesServerHmr =\n      serverFastRefresh &&\n      entryType === 'app' &&\n      writtenEndpoint.type !== 'edge'\n\n    const serverChunksPrefix = SERVER_HMR_CHUNKS_DIR + sep\n    const filesToDelete: string[] = []\n    for (const file of serverPaths) {\n      clearModuleContext(file)\n\n      const relativePath = relative(distDir, file)\n      if (\n        // For Pages Router, edge routes, middleware, and any entry not\n        // participating in server HMR: clear the sharedCache in\n        // evalManifest(), Node.js require.cache, and edge runtime module\n        // contexts.\n        force ||\n        !usesServerHmr ||\n        !relativePath.startsWith(serverChunksPrefix)\n      ) {\n        filesToDelete.push(file)\n      }\n    }\n    deleteCache(filesToDelete)\n\n    // Reset the fetch patch so patchFetch() can re-wrap on the next request.\n    if (serverPaths.length > 0) {\n      resetFetch()\n    }\n\n    // Clear Turbopack's chunk-loading cache so chunks are re-required from disk on\n    // the next request.\n    //\n    // For App Router with server HMR, this is normally skipped as server HMR\n    // manages module updates in-place. However, it *is* required when force is `true`\n    // (like for .env file or tsconfig changes).\n    if (\n      (!usesServerHmr || force) &&\n      typeof __next__clear_chunk_cache__ === 'function'\n    ) {\n      __next__clear_chunk_cache__()\n    }\n\n    return true\n  }\n\n  const buildingIds = new Set()\n\n  const startBuilding: StartBuilding = (id, requestUrl, forceRebuild) => {\n    if (!forceRebuild && readyIds.has(id)) {\n      return () => {}\n    }\n    if (buildingIds.size === 0) {\n      consoleStore.setState(\n        {\n          loading: true,\n          trigger: id,\n          url: requestUrl,\n        } as OutputState,\n        true\n      )\n    }\n    buildingIds.add(id)\n    return function finishBuilding() {\n      if (buildingIds.size === 0) {\n        return\n      }\n      readyIds.add(id)\n      buildingIds.delete(id)\n      if (buildingIds.size === 0) {\n        hmrEventHappened = false\n        consoleStore.setState(\n          {\n            loading: false,\n          } as OutputState,\n          true\n        )\n      }\n    }\n  }\n\n  let hmrEventHappened = false\n  // A counter identifying the current version of the compiled output, included\n  // by `\"use cache\"` in dev cache keys so that cached entries revalidate after\n  // an edit. It advances once per HMR change event (for App Router pages that\n  // is an RSC change, which is what a cached render depends on), independent of\n  // how many clients are connected. It deliberately does not advance on `BUILT`\n  // messages: those are sent per connected client on every compilation, so\n  // advancing there would both churn the hash without an edit and fail to\n  // advance it at all when no client is connected.\n  let hmrHash = 0\n\n  // HACK: Defer sending `building` messages. Turbopack emits a compile pass for every\n  // foreground-job cycle, including empty no-op recompiles scheduled by\n  // request/render activity that changed no files. This allows us to prevent\n  // sending them if we quickly get a `built` message after a `building` message.\n  const pendingBuilding = new DeferredEmit()\n\n  const clientsWithoutHtmlRequestId = new Set<ws>()\n  const clientsByHtmlRequestId = new Map<string, ws>()\n  const cacheStatusesByHtmlRequestId = new Map<string, ServerCacheStatus>()\n  const clientStates = new WeakMap<ws, ClientState>()\n\n  function sendToClient(client: ws, message: HmrMessageSentToBrowser) {\n    const data =\n      typeof message.type === 'number'\n        ? createBinaryHmrMessageData(message)\n        : JSON.stringify(message)\n\n    client.send(data)\n  }\n\n  let updateInProgress = false\n  let pendingServerComponentChanges = false\n\n  function sendServerComponentChanges() {\n    sendHmr('server-component-changes', {\n      type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,\n    })\n  }\n\n  // Each announcement makes every client refetch its page, so an update's\n  // changes are announced once, on the update's end.\n  function handleServerComponentChanges() {\n    if (updateInProgress) {\n      pendingServerComponentChanges = true\n    } else {\n      sendServerComponentChanges()\n    }\n  }\n\n  function hasCompilationErrors() {\n    for (const [, issueMap] of currentEntryIssues) {\n      if (\n        [...issueMap.values()].filter((i) => i.severity !== 'warning').length >\n        0\n      ) {\n        return true\n      }\n    }\n    return false\n  }\n\n  function sendEnqueuedMessages() {\n    if (hasCompilationErrors()) {\n      // During compilation errors we want to delay the HMR events until errors are fixed\n      return\n    }\n\n    for (const client of [\n      ...clientsWithoutHtmlRequestId,\n      ...clientsByHtmlRequestId.values(),\n    ]) {\n      const state = clientStates.get(client)\n      if (!state) {\n        continue\n      }\n\n      for (const [, issueMap] of state.clientIssues) {\n        if (\n          [...issueMap.values()].filter((i) => i.severity !== 'warning')\n            .length > 0\n        ) {\n          // During compilation errors we want to delay the HMR events until errors are fixed\n          return\n        }\n      }\n\n      for (const message of state.messages.values()) {\n        sendToClient(client, message)\n      }\n      state.messages.clear()\n\n      if (state.turbopackUpdates.length > 0) {\n        sendToClient(client, {\n          type: HMR_MESSAGE_SENT_TO_BROWSER.TURBOPACK_MESSAGE,\n          data: state.turbopackUpdates,\n        })\n        state.turbopackUpdates.length = 0\n      }\n    }\n  }\n  const sendEnqueuedMessagesDebounce = debounce(sendEnqueuedMessages, 2)\n\n  const sendHmr: SendHmr = (id: string, message: HmrMessageSentToBrowser) => {\n    pendingBuilding.flush()\n    for (const client of [\n      ...clientsWithoutHtmlRequestId,\n      ...clientsByHtmlRequestId.values(),\n    ]) {\n      clientStates.get(client)?.messages.set(id, message)\n    }\n\n    hmrEventHappened = true\n    sendEnqueuedMessagesDebounce()\n  }\n\n  function sendTurbopackMessage(payload: TurbopackUpdate) {\n    // TODO(PACK-2049): For some reason we end up emitting hundreds of issues messages on bigger apps,\n    //   a lot of which are duplicates.\n    //   They are currently not handled on the client at all, so might as well not send them for now.\n    payload.diagnostics = []\n    payload.issues = []\n    pendingBuilding.flush()\n\n    for (const client of [\n      ...clientsWithoutHtmlRequestId,\n      ...clientsByHtmlRequestId.values(),\n    ]) {\n      clientStates.get(client)?.turbopackUpdates.push(payload)\n    }\n\n    hmrEventHappened = true\n    sendEnqueuedMessagesDebounce()\n  }\n\n  async function subscribeToClientChanges(\n    key: EntryKey,\n    includeIssues: boolean,\n    endpoint: Endpoint,\n    createMessage: (\n      change: TurbopackResult,\n      hash: string\n    ) => Promise<HmrMessageSentToBrowser> | HmrMessageSentToBrowser | void,\n    onError?: (\n      error: Error\n    ) => Promise<HmrMessageSentToBrowser> | HmrMessageSentToBrowser | void\n  ) {\n    if (changeSubscriptions.has(key)) {\n      return\n    }\n\n    const { side } = splitEntryKey(key)\n\n    const changedPromise = endpoint[`${side}Changed`](includeIssues)\n    changeSubscriptions.set(key, changedPromise)\n    try {\n      const changed = await changedPromise\n\n      for await (const change of changed) {\n        processIssues(currentEntryIssues, key, change, false, true)\n        // TODO: Get an actual content hash from Turbopack.\n        const message = await createMessage(change, String(++hmrHash))\n        if (message) {\n          sendHmr(key, message)\n        }\n      }\n    } catch (e) {\n      changeSubscriptions.delete(key)\n      const payload = await onError?.(e as Error)\n      if (payload) {\n        sendHmr(key, payload)\n      }\n      return\n    }\n    changeSubscriptions.delete(key)\n  }\n\n  async function unsubscribeFromClientChanges(key: EntryKey) {\n    const subscription = await changeSubscriptions.get(key)\n    if (subscription) {\n      await subscription.return?.()\n      changeSubscriptions.delete(key)\n    }\n    currentEntryIssues.delete(key)\n  }\n\n  async function subscribeToClientHmrEvents(client: ws, id: string) {\n    const key = getEntryKey('assets', 'client', id)\n    if (!hasEntrypointForKey(currentEntrypoints, key, assetMapper)) {\n      // maybe throw an error / force the client to reload?\n      return\n    }\n\n    const state = clientStates.get(client)\n    if (!state || state.subscriptions.has(id)) {\n      return\n    }\n\n    const subscription = project!.hmrEvents(id, HmrTarget.Client)\n    state.subscriptions.set(id, subscription)\n\n    // The subscription will always emit once, which is the initial\n    // computation. This is not a change, so swallow it.\n    try {\n      await subscription.next()\n\n      for await (const data of subscription) {\n        processIssues(state.clientIssues, key, data, false, true)\n        if (data.type !== 'issues') {\n          sendTurbopackMessage(data as TurbopackUpdate)\n        }\n      }\n    } catch (e) {\n      // The client might be using an HMR session from a previous server, tell them\n      // to fully reload the page to resolve the issue. We can't use\n      // `hotReloader.send` since that would force every connected client to\n      // reload, only this client is out of date.\n      const reloadMessage: ReloadPageMessage = {\n        type: HMR_MESSAGE_SENT_TO_BROWSER.RELOAD_PAGE,\n        data: `error in HMR event subscription for ${id}: ${e}`,\n      }\n      sendToClient(client, reloadMessage)\n      client.close()\n      return\n    }\n  }\n\n  function unsubscribeFromClientHmrEvents(client: ws, id: string) {\n    const state = clientStates.get(client)\n    if (!state) {\n      return\n    }\n\n    const subscription = state.subscriptions.get(id)\n    subscription?.return!()\n\n    const key = getEntryKey('assets', 'client', id)\n    state.clientIssues.delete(key)\n  }\n\n  async function handleEntrypointsSubscription() {\n    for await (const entrypoints of entrypointsSubscription) {\n      if (!currentEntriesHandlingResolve) {\n        currentEntriesHandling = new Promise(\n          // eslint-disable-next-line no-loop-func\n          (resolve) => (currentEntriesHandlingResolve = resolve)\n        )\n      }\n\n      // Always process issues/diagnostics, even if there are no entrypoints yet\n      processTopLevelIssues(currentTopLevelIssues, entrypoints)\n\n      // Certain crtical issues prevent any entrypoints from being constructed so return early\n      if (!('routes' in entrypoints)) {\n        printBuildErrors(entrypoints, true)\n\n        currentEntriesHandlingResolve!()\n        currentEntriesHandlingResolve = undefined\n        continue\n      }\n\n      const routes = entrypoints.routes\n      const existingRoutes = [\n        ...currentEntrypoints.app.keys(),\n        ...currentEntrypoints.page.keys(),\n      ]\n      const newRoutes = [...routes.keys()]\n\n      const addedRoutes = newRoutes.filter(\n        (route) =>\n          !currentEntrypoints.app.has(route) &&\n          !currentEntrypoints.page.has(route)\n      )\n      const removedRoutes = existingRoutes.filter((route) => !routes.has(route))\n\n      await handleEntrypoints({\n        entrypoints: entrypoints as any,\n\n        currentEntrypoints,\n\n        currentEntryIssues,\n        manifestLoader,\n        devRewrites: opts.fsChecker.rewrites,\n        productionRewrites: undefined,\n        logErrors: true,\n\n        dev: {\n          assetMapper,\n          changeSubscriptions,\n          clients: [\n            ...clientsWithoutHtmlRequestId,\n            ...clientsByHtmlRequestId.values(),\n          ],\n          clientStates,\n          serverFields,\n\n          hooks: {\n            handleWrittenEndpoint: (id, result, forceDeleteCache) => {\n              currentWrittenEntrypoints.set(id, result)\n              return clearRequireCache(id, result, { force: forceDeleteCache })\n            },\n            propagateServerField: propagateServerField.bind(null, opts),\n            sendHmr,\n            startBuilding,\n            subscribeToChanges: subscribeToClientChanges,\n            unsubscribeFromChanges: unsubscribeFromClientChanges,\n            unsubscribeFromHmrEvents: unsubscribeFromClientHmrEvents,\n          },\n        },\n      })\n\n      // Reload matchers when the files have been compiled\n      await propagateServerField(opts, 'reloadMatchers', undefined)\n\n      if (addedRoutes.length > 0 || removedRoutes.length > 0) {\n        // When the list of routes changes a new manifest should be fetched for Pages Router.\n        hotReloader.send({\n          type: HMR_MESSAGE_SENT_TO_BROWSER.DEV_PAGES_MANIFEST_UPDATE,\n          data: [\n            {\n              devPagesManifest: true,\n            },\n          ],\n        })\n      }\n\n      for (const route of addedRoutes) {\n        hotReloader.send({\n          type: HMR_MESSAGE_SENT_TO_BROWSER.ADDED_PAGE,\n          data: [route],\n        })\n      }\n\n      for (const route of removedRoutes) {\n        hotReloader.send({\n          type: HMR_MESSAGE_SENT_TO_BROWSER.REMOVED_PAGE,\n          data: [route],\n        })\n      }\n\n      currentEntriesHandlingResolve!()\n      currentEntriesHandlingResolve = undefined\n    }\n  }\n\n  await mkdir(join(distDir, 'server'), { recursive: true })\n  await mkdir(join(distDir, 'static', buildId), { recursive: true })\n  await writeFile(\n    join(distDir, 'package.json'),\n    JSON.stringify(\n      {\n        type: 'commonjs',\n      },\n      null,\n      2\n    )\n  )\n\n  const middlewares = [\n    getOverlayMiddleware({\n      project,\n      projectPath,\n      isSrcDir: opts.isSrcDir,\n    }),\n    getSourceMapMiddleware(project),\n    getNextErrorFeedbackMiddleware(opts.telemetry),\n    getDevOverlayFontMiddleware(),\n    getDisableDevIndicatorMiddleware(),\n    getRestartDevServerMiddleware({\n      telemetry: opts.telemetry,\n      turbopackProject: project,\n    }),\n    devToolsConfigMiddleware({\n      distDir,\n      sendUpdateSignal: (data) => {\n        hotReloader.send({\n          type: HMR_MESSAGE_SENT_TO_BROWSER.DEVTOOLS_CONFIG,\n          data,\n        })\n      },\n    }),\n    getAttachNodejsDebuggerMiddleware(),\n    ...(nextConfig.experimental.mcpServer\n      ? [\n          getMcpMiddleware({\n            projectPath,\n            distDir,\n            nextConfig,\n            pagesDir: opts.pagesDir,\n            appDir: opts.appDir,\n            sendHmrMessage: (message) => hotReloader.send(message),\n            getActiveConnectionCount: () =>\n              clientsWithoutHtmlRequestId.size + clientsByHtmlRequestId.size,\n            getDevServerUrl: () => process.env.__NEXT_PRIVATE_ORIGIN,\n            getTurbopackProject: () => project,\n            compileRoute: async ({ routeSpecifier, path }) => {\n              // Resolve the caller's input to a concrete route specifier. The\n              // path-mode branch reuses the dev router's own live route table\n              // (opts.fsChecker) — the same one resolve-routes.ts consults on\n              // every incoming HTTP request — so first-match ordering and live\n              // route updates are inherited for free.\n              let page: string\n              if (routeSpecifier != null) {\n                page = routeSpecifier\n              } else if (path != null) {\n                const resolved = resolvePathToRoute(path, {\n                  appFiles: opts.fsChecker.appFiles,\n                  pageFiles: opts.fsChecker.pageFiles,\n                  dynamicRoutes: opts.fsChecker.getDynamicRoutes(),\n                })\n                if ('notFound' in resolved) {\n                  const err: NodeJS.ErrnoException = new Error(\n                    `no route matched for path \"${resolved.pathname}\"`\n                  )\n                  err.code = 'ENOENT'\n                  throw err\n                }\n                page = resolved.routeSpecifier\n              } else {\n                // Tool handler rejects the empty case; defend the boundary.\n                throw new Error(\n                  'compileRoute: either routeSpecifier or path is required'\n                )\n              }\n\n              // ensurePage uses findPagePathData when no definition is provided,\n              // which calls normalizePagePath(\"/\") → \"/index\" then findPageFile\n              // looking for \"index.tsx\" — neither of which matches \"page.tsx\" in\n              // the app dir. Pass a synthetic definition instead.\n              //\n              // currentEntrypoints.app is keyed by originalName which includes the\n              // trailing /page or /route segment (e.g. \"/page\" for the root route,\n              // \"/blog/[slug]/page\" for a dynamic page). Use normalizeAppPath to\n              // strip that suffix and find the entry matching the user-facing route.\n              let extraOptions: object | undefined = undefined\n              for (const [name] of currentEntrypoints.app) {\n                if (normalizeAppPath(name) === page) {\n                  extraOptions = {\n                    // Synthesize a definition so ensurePage bypasses findPagePathData.\n                    // Only page and bundlePath are used from the definition:\n                    // - page: the originalName used as the route key for currentEntrypoints lookup\n                    // - bundlePath: must start with \"app/\" to set isInsideAppDir=true\n                    definition: {\n                      page: name,\n                      bundlePath: `app${name}`,\n                      filename: '',\n                    } as any,\n                  }\n                  break\n                }\n              }\n              const ensureOpts = {\n                page,\n                // Compile both server and client bundles, matching what happens\n                // on a real page navigation. Client-only compilation isn't a\n                // meaningful MCP use case so we don't expose it as a knob.\n                clientOnly: false,\n                // Skip wiring HMR subscriptions: there is no client to receive\n                // updates for routes compiled this way, and these subscriptions\n                // are never unsubscribed (see TODOs in handleRouteType).\n                subscribeToChanges: false,\n                ...extraOptions,\n              }\n\n              // Snapshot the current issue maps before compilation so we can\n              // identify which entry keys were added or updated by this call.\n              // processIssues always creates a new Map() reference, so identity\n              // comparison detects changes even for re-compilations.\n              const snapshotBefore = new Map(currentEntryIssues)\n\n              // For app-page routes, processIssues is called with throwIssue=true,\n              // meaning it throws ModuleBuildError when there are compile errors—but\n              // it still writes the issues into currentEntryIssues before throwing.\n              // Catch ModuleBuildError so we can read those issues and return them\n              // as structured output rather than propagating the throw.\n              let moduleBuildError: ModuleBuildError | undefined\n              try {\n                await hotReloader.ensurePage(ensureOpts)\n              } catch (err) {\n                if (err instanceof ModuleBuildError) {\n                  moduleBuildError = err\n                } else {\n                  throw err\n                }\n              }\n\n              const rawIssues = []\n              for (const [key, issueMap] of currentEntryIssues) {\n                if (snapshotBefore.get(key) !== issueMap) {\n                  rawIssues.push(...issueMap.values())\n                }\n              }\n\n              // If ensurePage threw ModuleBuildError but we found no new issues in\n              // the map (shouldn't happen, but be safe), re-surface the original\n              // error so its message and stack are preserved.\n              if (moduleBuildError && rawIssues.length === 0) {\n                throw moduleBuildError\n              }\n\n              return {\n                routeSpecifier: page,\n                issues: formatCompilationIssues(rawIssues),\n              }\n            },\n          }),\n        ]\n      : []),\n  ]\n\n  setStackFrameResolver(async (request) => {\n    return getOriginalStackFrames({\n      project,\n      projectPath,\n      isServer: request.isServer,\n      isEdgeServer: request.isEdgeServer,\n      isAppDirectory: request.isAppDirectory,\n      frames: request.frames,\n    })\n  })\n\n  let versionInfoCached: ReturnType<typeof getVersionInfo> | undefined\n  // This fetch, even though not awaited, is not kicked off eagerly because the first `fetch()` in\n  // Node.js adds roughly 20ms main-thread blocking to load the SSL certificate cache\n  // We don't want that blocking time to be in the hot path for the `ready in` logging.\n  // Instead, the fetch is kicked off lazily when the first `getVersionInfoCached()` is called.\n  const getVersionInfoCached = (): ReturnType<typeof getVersionInfo> => {\n    if (!versionInfoCached) {\n      versionInfoCached = getVersionInfo()\n    }\n    return versionInfoCached\n  }\n\n  let devtoolsFrontendUrl: string | undefined\n  const inspectorURLRaw = inspector.url()\n  if (inspectorURLRaw !== undefined) {\n    const inspectorURL = new URL(inspectorURLRaw)\n\n    let debugInfo\n    try {\n      const debugInfoList = await fetch(\n        `http://${inspectorURL.host}/json/list`\n      ).then((res) => res.json())\n      debugInfo = debugInfoList[0]\n    } catch {}\n    if (debugInfo) {\n      devtoolsFrontendUrl = debugInfo.devtoolsFrontendUrl\n    }\n  }\n\n  const hotReloader: NextJsHotReloaderInterface = {\n    turbopackProject: project,\n    activeWebpackConfigs: undefined,\n    serverStats: null,\n    edgeServerStats: null,\n    async run(req, res, _parsedUrl) {\n      // intercept page chunks request and ensure them with turbopack\n      if (req.url?.startsWith('/_next/static/chunks/pages/')) {\n        const params = matchNextPageBundleRequest(req.url)\n\n        if (params) {\n          const decodedPagePath = `/${params.path\n            .map((param: string) => decodeURIComponent(param))\n            .join('/')}`\n\n          const denormalizedPagePath = denormalizePagePath(decodedPagePath)\n\n          await hotReloader\n            .ensurePage({\n              page: denormalizedPagePath,\n              clientOnly: false,\n              definition: undefined,\n              url: req.url,\n            })\n            .catch(console.error)\n        }\n      }\n\n      for (const middleware of middlewares) {\n        let calledNext = false\n\n        await middleware(req, res, () => {\n          calledNext = true\n        })\n\n        if (!calledNext) {\n          return { finished: true }\n        }\n      }\n\n      // Request was not finished.\n      return { finished: undefined }\n    },\n\n    // TODO: Figure out if socket type can match the NextJsHotReloaderInterface\n    onHMR(req, socket: Socket, head, onUpgrade) {\n      wsServer.handleUpgrade(req, socket, head, (client) => {\n        const clientIssues: EntryIssuesMap = new Map()\n        const subscriptions: Map<string, AsyncIterator<any>> = new Map()\n\n        const htmlRequestId = req.url\n          ? new URL(req.url, 'http://n').searchParams.get('id')\n          : null\n\n        // Clients with a request ID are inferred App Router clients. If Cache\n        // Components is not enabled, we consider those legacy clients. Pages\n        // Router clients are also considered legacy clients. TODO: Maybe mark\n        // clients as App Router / Pages Router clients explicitly, instead of\n        // inferring it from the presence of a request ID.\n        if (htmlRequestId) {\n          clientsByHtmlRequestId.set(htmlRequestId, client)\n          const enableCacheComponents = nextConfig.cacheComponents\n          if (enableCacheComponents) {\n            onUpgrade(client, { isLegacyClient: false })\n            const cacheStatus = cacheStatusesByHtmlRequestId.get(htmlRequestId)\n            if (cacheStatus !== undefined) {\n              sendToClient(client, {\n                type: HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR,\n                state: cacheStatus,\n              })\n              cacheStatusesByHtmlRequestId.delete(htmlRequestId)\n            }\n          } else {\n            onUpgrade(client, { isLegacyClient: true })\n          }\n\n          connectReactDebugChannelForHtmlRequest(\n            htmlRequestId,\n            sendToClient.bind(null, client)\n          )\n\n          sendSerializedErrorsToClientForHtmlRequest(\n            htmlRequestId,\n            sendToClient.bind(null, client)\n          )\n        } else {\n          clientsWithoutHtmlRequestId.add(client)\n          onUpgrade(client, { isLegacyClient: true })\n        }\n\n        clientStates.set(client, {\n          clientIssues,\n          messages: new Map(),\n          turbopackUpdates: [],\n          subscriptions,\n        })\n\n        client.on('close', () => {\n          // Remove active subscriptions\n          for (const subscription of subscriptions.values()) {\n            subscription.return?.()\n          }\n          clientStates.delete(client)\n\n          if (htmlRequestId) {\n            clientsByHtmlRequestId.delete(htmlRequestId)\n            deleteReactDebugChannelForHtmlRequest(htmlRequestId)\n          } else {\n            clientsWithoutHtmlRequestId.delete(client)\n          }\n        })\n\n        client.addEventListener('message', async ({ data }) => {\n          const parsedData = JSON.parse(\n            typeof data !== 'string' ? data.toString() : data\n          )\n\n          // Next.js messages\n          switch (parsedData.event) {\n            case 'span-end': {\n              hotReloaderSpan.manualTraceChild(\n                parsedData.spanName,\n                msToNs(parsedData.startTime),\n                msToNs(parsedData.endTime),\n                parsedData.attributes\n              )\n              break\n            }\n            case 'client-hmr-latency': // { id, startTime, endTime, page, updatedModules, isPageHidden }\n              hotReloaderSpan.manualTraceChild(\n                parsedData.event,\n                msToNs(parsedData.startTime),\n                msToNs(parsedData.endTime),\n                {\n                  updatedModules: parsedData.updatedModules,\n                  page: parsedData.page,\n                  isPageHidden: parsedData.isPageHidden,\n                }\n              )\n              break\n\n            case 'client-error': // { errorCount, clientId }\n            case 'client-warning': // { warningCount, clientId }\n            case 'client-success': // { clientId }\n            case 'server-component-reload-page': // { clientId }\n            case 'client-reload-page': // { clientId }\n            case 'client-removed-page': // { page }\n            case 'client-full-reload': // { stackTrace, hadRuntimeError }\n              const { hadRuntimeError, dependencyChain } = parsedData\n              if (hadRuntimeError) {\n                Log.warn(FAST_REFRESH_RUNTIME_RELOAD)\n              }\n              if (\n                Array.isArray(dependencyChain) &&\n                typeof dependencyChain[0] === 'string'\n              ) {\n                const cleanedModulePath = dependencyChain[0]\n                  .replace(/^\\[project\\]/, '.')\n                  .replace(/ \\[.*\\] \\(.*\\)$/, '')\n                Log.warn(\n                  `Fast Refresh had to perform a full reload when ${cleanedModulePath} changed. Read more: https://nextjs.org/docs/messages/fast-refresh-reload`\n                )\n              }\n              break\n            case 'client-added-page':\n              // TODO\n              break\n            case 'browser-logs': {\n              await receiveBrowserLogsTurbopack({\n                entries: parsedData.entries,\n                router: parsedData.router,\n                sourceType: parsedData.sourceType,\n                project,\n                projectPath,\n                distDir,\n                config:\n                  (nextConfig.logging &&\n                    nextConfig.logging.browserToTerminal) ||\n                  false,\n              })\n              break\n            }\n            case 'ping': {\n              // Handle ping events to keep WebSocket connections alive\n              // No-op - just acknowledge the ping\n              break\n            }\n\n            case 'mcp-error-state-response': {\n              handleErrorStateResponse(\n                parsedData.requestId,\n                parsedData.errorState,\n                parsedData.url\n              )\n              break\n            }\n\n            case 'mcp-page-metadata-response': {\n              handlePageMetadataResponse(\n                parsedData.requestId,\n                parsedData.segmentTrieData,\n                parsedData.url\n              )\n              break\n            }\n\n            default:\n              // Might be a Turbopack message...\n              if (!parsedData.type) {\n                throw new Error(`unrecognized HMR message \"${data}\"`)\n              }\n          }\n\n          // Turbopack messages\n          switch (parsedData.type) {\n            case 'turbopack-subscribe':\n              subscribeToClientHmrEvents(client, parsedData.path)\n              break\n\n            case 'turbopack-unsubscribe':\n              unsubscribeFromClientHmrEvents(client, parsedData.path)\n              break\n\n            default:\n              if (!parsedData.event) {\n                throw new Error(`unrecognized Turbopack HMR message \"${data}\"`)\n              }\n          }\n        })\n\n        const turbopackConnectedMessage: TurbopackConnectedMessage = {\n          type: HMR_MESSAGE_SENT_TO_BROWSER.TURBOPACK_CONNECTED,\n          data: { sessionId },\n        }\n        sendToClient(client, turbopackConnectedMessage)\n\n        const errors: CompilationError[] = []\n\n        for (const entryIssues of currentEntryIssues.values()) {\n          for (const issue of entryIssues.values()) {\n            if (issue.severity !== 'warning') {\n              errors.push({\n                message: formatIssue(issue),\n              })\n            } else {\n              printNonFatalIssue(issue)\n            }\n          }\n        }\n\n        if (devIndicatorServerState.disabledUntil < Date.now()) {\n          devIndicatorServerState.disabledUntil = 0\n        }\n\n        ;(async function () {\n          const versionInfo = await getVersionInfoCached()\n          const devToolsConfig = await getDevToolsConfig(distDir)\n\n          const syncMessage: SyncMessage = {\n            type: HMR_MESSAGE_SENT_TO_BROWSER.SYNC,\n            errors,\n            warnings: [],\n            hash: '',\n            versionInfo,\n            debug: {\n              devtoolsFrontendUrl,\n            },\n            devIndicator: devIndicatorServerState,\n            devToolsConfig,\n            requestInsights:\n              nextConfig.experimental.requestInsights ||\n              isRequestInsightsEnabled()\n                ? getRequestInsightsSnapshot()\n                : undefined,\n          }\n\n          sendToClient(client, syncMessage)\n        })()\n      })\n    },\n\n    send(action) {\n      const payload = JSON.stringify(action)\n\n      for (const client of [\n        ...clientsWithoutHtmlRequestId,\n        ...clientsByHtmlRequestId.values(),\n      ]) {\n        client.send(payload)\n      }\n    },\n\n    getServerComponentsHmrRefreshHash() {\n      // The current server-components generation. Only the change subscription\n      // (an actual recompile) advances `hmrHash`; reloads and config\n      // invalidations don't, so the value stays stable across requests until a\n      // real edit. Returned unconditionally (`\"0\"` before the first edit) so\n      // `\"use cache\"` keys are present and consistent for every request,\n      // mirroring webpack's always-present `stats.hash`.\n      return String(hmrHash)\n    },\n\n    sendToLegacyClients(action) {\n      const payload = JSON.stringify(action)\n\n      // Clients with a request ID are inferred App Router clients. If Cache\n      // Components is not enabled, we consider those legacy clients. Pages\n      // Router clients are also considered legacy clients. TODO: Maybe mark\n      // clients as App Router / Pages Router clients explicitly, instead of\n      // inferring it from the presence of a request ID.\n\n      if (!nextConfig.cacheComponents) {\n        for (const client of clientsByHtmlRequestId.values()) {\n          client.send(payload)\n        }\n      }\n\n      for (const client of clientsWithoutHtmlRequestId) {\n        client.send(payload)\n      }\n    },\n\n    setCacheStatus(status: ServerCacheStatus, htmlRequestId: string): void {\n      // Legacy clients don't have Cache Components.\n      const client = clientsByHtmlRequestId.get(htmlRequestId)\n      if (client !== undefined) {\n        sendToClient(client, {\n          type: HMR_MESSAGE_SENT_TO_BROWSER.CACHE_INDICATOR,\n          state: status,\n        })\n      } else {\n        // If the client is not connected, store the status so that we can send it\n        // when the client connects.\n        cacheStatusesByHtmlRequestId.set(htmlRequestId, status)\n      }\n    },\n\n    setReactDebugChannel(debugChannel, htmlRequestId, requestId) {\n      const client = clientsByHtmlRequestId.get(htmlRequestId)\n\n      if (htmlRequestId === requestId) {\n        // The debug channel is for the HTML request.\n        if (client) {\n          // If the client is connected, we can connect the debug channel for\n          // the HTML request immediately.\n          connectReactDebugChannel(\n            htmlRequestId,\n            debugChannel,\n            sendToClient.bind(null, client)\n          )\n        } else {\n          // Otherwise, we'll do that when the client connects and just store\n          // the debug channel.\n          setReactDebugChannelForHtmlRequest(htmlRequestId, debugChannel)\n        }\n      } else if (client) {\n        // The debug channel is for a subsequent request (e.g. client-side\n        // navigation for server function call). If the client is not connected\n        // anymore, we don't need to connect the debug channel.\n        connectReactDebugChannel(\n          requestId,\n          debugChannel,\n          sendToClient.bind(null, client)\n        )\n      }\n    },\n\n    sendErrorsToBrowser(errorsRscStream, htmlRequestId) {\n      const client = clientsByHtmlRequestId.get(htmlRequestId)\n\n      if (client) {\n        // If the client is connected, we can send the errors immediately.\n        sendSerializedErrorsToClient(\n          errorsRscStream,\n          sendToClient.bind(null, client)\n        )\n      } else {\n        // Otherwise, store the errors stream so that we can send it when the\n        // client connects.\n        setErrorsRscStreamForHtmlRequest(htmlRequestId, errorsRscStream)\n      }\n    },\n\n    setHmrServerError(_error) {\n      // Not implemented yet.\n    },\n    clearHmrServerError() {\n      // Not implemented yet.\n    },\n    async start() {},\n    async getCompilationErrors(page) {\n      const appEntryKey = getEntryKey('app', 'server', page)\n      const pagesEntryKey = getEntryKey('pages', 'server', page)\n\n      const topLevelIssues = currentTopLevelIssues.values()\n\n      const thisEntryIssues =\n        currentEntryIssues.get(appEntryKey) ??\n        currentEntryIssues.get(pagesEntryKey)\n\n      if (thisEntryIssues !== undefined && thisEntryIssues.size > 0) {\n        // If there is an error related to the requesting page we display it instead of the first error\n        return [...topLevelIssues, ...thisEntryIssues.values()]\n          .map((issue) => {\n            const formattedIssue = formatIssue(issue)\n            if (issue.severity === 'warning') {\n              printNonFatalIssue(issue)\n              return null\n            } else if (isWellKnownError(issue)) {\n              Log.error(formattedIssue)\n            }\n\n            return new Error(formattedIssue)\n          })\n          .filter((error) => error !== null)\n      }\n\n      // Otherwise, return all errors across pages\n      const errors = []\n      for (const issue of topLevelIssues) {\n        if (issue.severity !== 'warning') {\n          errors.push(new Error(formatIssue(issue)))\n        }\n      }\n      for (const entryIssues of currentEntryIssues.values()) {\n        for (const issue of entryIssues.values()) {\n          if (issue.severity !== 'warning') {\n            const message = formatIssue(issue)\n            errors.push(new Error(message))\n          } else {\n            printNonFatalIssue(issue)\n          }\n        }\n      }\n      return errors\n    },\n    async invalidate({\n      // .env files or tsconfig/jsconfig change\n      reloadAfterInvalidation,\n    }) {\n      if (reloadAfterInvalidation) {\n        for (const [key, entrypoint] of currentWrittenEntrypoints) {\n          clearRequireCache(key, entrypoint, { force: true })\n        }\n\n        await clearAllModuleContexts()\n        this.send({\n          type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,\n        })\n      }\n    },\n    async buildFallbackError() {\n      // Not implemented yet.\n    },\n    async ensurePage({\n      page: inputPage,\n      // Unused parameters\n      // clientOnly,\n      appPaths,\n      definition,\n      isApp,\n      url: requestUrl,\n      subscribeToChanges = true,\n    }) {\n      // When there is no route definition this is an internal file not a route the user added.\n      // Middleware and instrumentation are handled in turbopack-utils.ts handleEntrypoints instead.\n      if (!definition) {\n        if (inputPage === '/middleware') return\n        if (inputPage === '/src/middleware') return\n        if (inputPage === '/instrumentation') return\n        if (inputPage === '/src/instrumentation') return\n      }\n\n      return hotReloaderSpan\n        .traceChild('ensure-page', {\n          inputPage,\n        })\n        .traceAsyncFn(async () => {\n          if (BLOCKED_PAGES.includes(inputPage) && inputPage !== '/_error') {\n            return\n          }\n\n          await currentEntriesHandling\n\n          // TODO We shouldn't look into the filesystem again. This should use the information from entrypoints\n          let routeDef: Pick<\n            RouteDefinition,\n            'filename' | 'bundlePath' | 'page'\n          > =\n            definition ??\n            (await findPagePathData(\n              projectPath,\n              inputPage,\n              nextConfig.pageExtensions,\n              opts.pagesDir,\n              opts.appDir,\n              !!nextConfig.experimental.globalNotFound\n            ))\n\n          // If the route is actually an app page route, then we should have access\n          // to the app route definition, and therefore, the appPaths from it.\n          if (!appPaths && definition && isAppPageRouteDefinition(definition)) {\n            appPaths = definition.appPaths\n          }\n\n          // Check if this is a deferred entry and wait for non-deferred entries first\n          if (hasDeferredEntriesConfig) {\n            const isDeferred = isDeferredEntry(\n              routeDef.page,\n              deferredEntriesConfig\n            )\n            if (isDeferred) {\n              await processDeferredEntry()\n            } else {\n              // Track non-deferred entry as building\n              nonDeferredBuildingEntries.add(routeDef.page)\n            }\n          }\n\n          let page = routeDef.page\n          if (appPaths) {\n            const normalizedPage = normalizeAppPath(page)\n\n            // filter out paths that are not exact matches (e.g. catchall)\n            const matchingAppPaths = appPaths.filter(\n              (path) => normalizeAppPath(path) === normalizedPage\n            )\n\n            // the last item in the array is the root page, if there are parallel routes\n            page = matchingAppPaths[matchingAppPaths.length - 1]\n          }\n\n          const pathname = definition?.pathname ?? inputPage\n\n          if (page === '/_error') {\n            let finishBuilding = startBuilding(pathname, requestUrl, false)\n            try {\n              await handlePagesErrorRoute({\n                currentEntryIssues,\n                entrypoints: currentEntrypoints,\n                manifestLoader,\n                devRewrites: opts.fsChecker.rewrites,\n                productionRewrites: undefined,\n                logErrors: true,\n                hooks: {\n                  subscribeToChanges: subscribeToClientChanges,\n                  handleWrittenEndpoint: (id, result, forceDeleteCache) => {\n                    currentWrittenEntrypoints.set(id, result)\n                    assetMapper.setPathsForKey(id, result.clientPaths)\n                    return clearRequireCache(id, result, {\n                      force: forceDeleteCache,\n                    })\n                  },\n                },\n              })\n            } finally {\n              finishBuilding()\n            }\n            return\n          }\n\n          const isInsideAppDir = routeDef.bundlePath.startsWith('app/')\n          const isEntryMetadataRouteFile = isMetadataRouteFile(\n            routeDef.filename.replace(opts.appDir || '', ''),\n            nextConfig.pageExtensions,\n            true\n          )\n          const normalizedAppPage = isEntryMetadataRouteFile\n            ? normalizedPageToTurbopackStructureRoute(\n                page,\n                extname(routeDef.filename)\n              )\n            : page\n\n          const route = isInsideAppDir\n            ? currentEntrypoints.app.get(normalizedAppPage)\n            : currentEntrypoints.page.get(page)\n\n          if (!route) {\n            // TODO: why is this entry missing in turbopack?\n            if (page === '/middleware') return\n            if (page === '/src/middleware') return\n            if (page === '/proxy') return\n            if (page === '/src/proxy') return\n            if (page === '/instrumentation') return\n            if (page === '/src/instrumentation') return\n\n            throw new PageNotFoundError(`route not found ${page}`)\n          }\n\n          // We don't throw on ensureOpts.isApp === true for page-api\n          // since this can happen when app pages make\n          // api requests to page API routes.\n          if (isApp && route.type === 'page') {\n            throw new Error(`mis-matched route type: isApp && page for ${page}`)\n          }\n\n          const finishBuilding = startBuilding(pathname, requestUrl, false)\n          try {\n            await handleRouteType({\n              dev,\n              page,\n              pathname,\n              route,\n              currentEntryIssues,\n              entrypoints: currentEntrypoints,\n              manifestLoader,\n              readyIds,\n              devRewrites: opts.fsChecker.rewrites,\n              productionRewrites: undefined,\n              logErrors: true,\n\n              hooks: {\n                // Pass a no-o subscribeToChanges to skip wiring HMR subscriptions for\n                // one-shot compilations (e.g. compile_route MCP tool).\n                subscribeToChanges: subscribeToChanges\n                  ? subscribeToClientChanges\n                  : ((async () => {}) as StartChangeSubscription),\n                handleServerComponentChanges,\n                handleWrittenEndpoint: (id, result, forceDeleteCache) => {\n                  currentWrittenEntrypoints.set(id, result)\n                  assetMapper.setPathsForKey(id, result.clientPaths)\n                  return clearRequireCache(id, result, {\n                    force: forceDeleteCache,\n                  })\n                },\n                serverFastRefresh,\n              },\n            })\n          } finally {\n            finishBuilding()\n            // Remove non-deferred entry from building set\n            if (hasDeferredEntriesConfig) {\n              nonDeferredBuildingEntries.delete(routeDef.page)\n            }\n          }\n        })\n    },\n    close() {\n      // Report MCP telemetry if MCP server is enabled\n      recordMcpTelemetry(opts.telemetry)\n\n      for (const wsClient of [\n        ...clientsWithoutHtmlRequestId,\n        ...clientsByHtmlRequestId.values(),\n      ]) {\n        // it's okay to not cleanly close these websocket connections, this is dev\n        wsClient.terminate()\n      }\n      clientsWithoutHtmlRequestId.clear()\n      clientsByHtmlRequestId.clear()\n    },\n  }\n\n  handleEntrypointsSubscription().catch((err) => {\n    console.error(err)\n    process.exit(1)\n  })\n\n  // Write empty manifests\n  await currentEntriesHandling\n  await manifestLoader.writeManifests({\n    devRewrites: opts.fsChecker.rewrites,\n    productionRewrites: undefined,\n    entrypoints: currentEntrypoints,\n  })\n\n  async function handleProjectUpdates() {\n    const BUILDING_MESSAGE_DEFER_MS = 100\n    for await (const updateMessage of project.updateInfoSubscribe(30)) {\n      switch (updateMessage.updateType) {\n        case 'start': {\n          updateInProgress = true\n          pendingBuilding.schedule(BUILDING_MESSAGE_DEFER_MS, () => {\n            hotReloader.send({ type: HMR_MESSAGE_SENT_TO_BROWSER.BUILDING })\n          })\n          // Mark that HMR has started and we need to call the callback after it settles\n          // This ensures onBeforeDeferredEntries will be called again during HMR\n          if (hasDeferredEntriesConfig) {\n            hmrPendingDeferredCallback = true\n            onBeforeDeferredEntriesCalled = false\n            onBeforeDeferredEntriesPromise = null\n          }\n          break\n        }\n        case 'end': {\n          updateInProgress = false\n          pendingBuilding.cancel()\n          if (pendingServerComponentChanges) {\n            pendingServerComponentChanges = false\n            sendServerComponentChanges()\n          }\n          sendEnqueuedMessages()\n\n          function addToErrorsMap(\n            errorsMap: Map<string, CompilationError>,\n            issueMap: IssuesMap\n          ) {\n            for (const [key, issue] of issueMap) {\n              if (issue.severity === 'warning') continue\n              if (errorsMap.has(key)) continue\n\n              const message = formatIssue(issue)\n\n              errorsMap.set(key, {\n                message,\n                details: issue.detail\n                  ? renderStyledStringToErrorAnsi(issue.detail)\n                  : undefined,\n              })\n            }\n          }\n\n          function addErrors(\n            errorsMap: Map<string, CompilationError>,\n            issues: EntryIssuesMap\n          ) {\n            for (const issueMap of issues.values()) {\n              addToErrorsMap(errorsMap, issueMap)\n            }\n          }\n\n          const errors = new Map<string, CompilationError>()\n          addToErrorsMap(errors, currentTopLevelIssues)\n          addErrors(errors, currentEntryIssues)\n\n          for (const client of [\n            ...clientsWithoutHtmlRequestId,\n            ...clientsByHtmlRequestId.values(),\n          ]) {\n            const state = clientStates.get(client)\n            if (!state) {\n              continue\n            }\n\n            const clientErrors = new Map(errors)\n            addErrors(clientErrors, state.clientIssues)\n\n            sendToClient(client, {\n              type: HMR_MESSAGE_SENT_TO_BROWSER.BUILT,\n              // Report the current version without advancing it: a completed\n              // compilation is not itself an edit, and this hash is not\n              // consumed by the Turbopack client.\n              hash: String(hmrHash),\n              errors: [...clientErrors.values()],\n              warnings: [],\n            })\n          }\n\n          if (hmrEventHappened) {\n            const time = updateMessage.value.duration\n            const timeMessage =\n              time > 2000 ? `${Math.round(time / 100) / 10}s` : `${time}ms`\n            Log.event(`Compiled in ${timeMessage}`)\n            hmrEventHappened = false\n          }\n\n          // Call onBeforeDeferredEntries after compilation completes during HMR\n          // This ensures the callback is invoked even when non-deferred entries change\n          // Use debounced function to prevent rapid-fire calls from turbopack updates\n          if (hasDeferredEntriesConfig) {\n            callOnBeforeDeferredEntriesAfterHMR()\n          }\n          break\n        }\n        default:\n      }\n    }\n  }\n\n  handleProjectUpdates().catch((err) => {\n    console.error(err)\n    process.exit(1)\n  })\n\n  // Tell browsers to refetch RSC (soft refresh, not full page reload).\n  // Skip while there are outstanding compilation errors: an RSC refetch would\n  // 500 and force a full-page navigation, losing client state (e.g. recovering\n  // from a syntax error). A subsequent successful compile/apply fires this\n  // again to refresh.\n  function notifyServerComponentChanges() {\n    if (hasCompilationErrors()) return\n    hotReloader.send({\n      type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,\n    })\n  }\n\n  if (serverFastRefresh) {\n    setupServerHmr(project, {\n      reEvaluateAllModulesExpensive: async () => {\n        // Evict every server-HMR-managed chunk from `require.cache`.\n        // Trailing `sep` so e.g. `server/chunks-other/...` doesn't match.\n        const serverChunksDir = join(distDir, SERVER_HMR_CHUNKS_DIR) + sep\n        const chunkPaths = Object.keys(require.cache).filter((p) =>\n          p.startsWith(serverChunksDir)\n        )\n        deleteCache(chunkPaths)\n\n        // Clear Turbopack's runtime caches\n        if (typeof __next__clear_chunk_cache__ === 'function') {\n          __next__clear_chunk_cache__()\n        }\n\n        // Reset the server HMR handler registry. All server runtime chunks are\n        // cleared from require.cache above; when they're next required they'll\n        // re-register into this Map and reinstall the routing dispatcher.\n        globalThis.__turbopack_server_hmr_handlers__ = new Map()\n\n        // Clear all edge contexts\n        await clearAllModuleContexts()\n\n        resetFetch()\n\n        // This thread gave up on repairing its module graph in place. The\n        // validation worker cannot repair its own either, so it is dropped and\n        // the next validation loads the build output afresh.\n        dropDevValidationWorker()\n\n        notifyServerComponentChanges()\n      },\n      onApplied: (chunkPaths: string[]) => {\n        // Clear the evalManifest() shared cache for each updated chunk so the\n        // next RSC render picks up the HMR-applied module changes. Unlike\n        // a full restart, this does NOT clear require.cache — the HMR-applied\n        // modules in devModuleCache must persist for dep preservation.\n        const manifestPaths = chunkPaths.map((chunkPath) =>\n          join(distDir, chunkPath)\n        )\n\n        for (const manifestPath of manifestPaths) {\n          clearManifestCache(manifestPath)\n        }\n\n        // This path clears the manifest cache without going through\n        // `deleteCache`, so `onCacheInvalidation` does not report it to the\n        // validation worker. Report it here instead.\n        mirrorModuleStateToDevValidationWorker({\n          type: 'invalidate',\n          filePaths: manifestPaths,\n          evictModules: false,\n        })\n\n        notifyServerComponentChanges()\n      },\n    })\n  }\n\n  return hotReloader\n}\n"],"names":["mkdir","writeFile","realpathSync","inspector","join","extname","relative","isAbsolute","sep","fileURLToPath","pathToFileURL","ws","store","consoleStore","HMR_MESSAGE_SENT_TO_BROWSER","createDefineEnv","getBindingsSync","HmrTarget","Log","BLOCKED_PAGES","getOverlayMiddleware","getSourceMapMiddleware","getOriginalStackFrames","PageNotFoundError","debounce","clearManifestCache","deleteCache","dropDevValidationWorker","mirrorModuleStateToDevValidationWorker","clearAllModuleContexts","clearModuleContext","denormalizePagePath","trace","AssetMapper","handleEntrypoints","handlePagesErrorRoute","handleRouteType","hasEntrypointForKey","msToNs","processTopLevelIssues","printNonFatalIssue","normalizedPageToTurbopackStructureRoute","propagateServerField","TurbopackManifestLoader","findPagePathData","getEntryKey","splitEntryKey","createBinaryHmrMessageData","FAST_REFRESH_RUNTIME_RELOAD","generateEncryptionKeyBase64","isAppPageRouteDefinition","normalizeAppPath","isDeferredEntry","isMetadataRouteFile","setBundlerFindSourceMapImplementation","setBundlerFindSourceMapURLImplementation","getNextErrorFeedbackMiddleware","formatIssue","isFileSystemCacheEnabledForDev","isWellKnownError","ModuleBuildError","processIssues","renderStyledStringToErrorAnsi","getDevOverlayFontMiddleware","devIndicatorServerState","getDisableDevIndicatorMiddleware","getRestartDevServerMiddleware","backgroundLogCompilationEvents","DeferredEmit","getSupportedBrowsers","printBuildErrors","receiveBrowserLogsTurbopack","normalizePath","seedTurbopackCacheIfNeeded","devToolsConfigMiddleware","getDevToolsConfig","getAttachNodejsDebuggerMiddleware","connectReactDebugChannel","connectReactDebugChannelForHtmlRequest","deleteReactDebugChannelForHtmlRequest","setReactDebugChannelForHtmlRequest","getVersionInfo","matchNextPageBundleRequest","getMcpMiddleware","formatCompilationIssues","getRequestInsightsSnapshot","isRequestInsightsEnabled","resolvePathToRoute","handleErrorStateResponse","handlePageMetadataResponse","setStackFrameResolver","recordMcpTelemetry","getFileLogger","sendSerializedErrorsToClient","sendSerializedErrorsToClientForHtmlRequest","setErrorsRscStreamForHtmlRequest","wsServer","Server","noServer","isTestMode","process","env","NEXT_TEST_MODE","__NEXT_TEST_MODE","DEBUG","sessionId","Math","floor","Number","MAX_SAFE_INTEGER","random","SERVER_HMR_CHUNKS_DIR","collectUpdatedChunkPaths","instruction","paths","Set","type","chunkPath","Object","keys","chunks","add","merged","Error","Array","from","setupServerHmr","project","reEvaluateAllModulesExpensive","onApplied","runSubscription","subscription","allHmrEvents","next","result","update","requiresFullReEvaluation","handlers","globalThis","__turbopack_server_hmr_handlers__","size","__turbopack_server_hmr_apply__","updatedChunkPaths","length","err","console","error","Promise","resolve","setTimeout","getSourceMapFromTurbopack","sourceURL","sourceMapJson","getSourceMapSync","undefined","JSON","parse","getSourceMapURLFromTurbopack","distDir","scriptNameOrSourceURL","scriptPath","startsWith","includes","relativePath","href","createHotReloaderTurbopack","opts","serverFields","resetFetch","lockfile","serverFastRefresh","nextConfig","dev","buildId","dir","projectPath","bindings","isWasm","platform","arch","require","log","testMode","hasRewrites","fsChecker","rewrites","afterFiles","beforeFiles","fallback","hotReloaderSpan","version","__NEXT_VERSION","stop","mcpServerEnabled","experimental","mcpServer","fileLogger","initialize","encryptionKey","isBuild","clientRouterFilters","clientRouterFilter","supportedBrowsers","currentNodeJsVersion","versions","node","rootPath","turbopack","root","outputFileTracingRoot","turbopackSeedCacheFromWorktree","projectDir","turbo","createProject","watch","enable","pollIntervalMs","watchOptions","defineEnv","isTurbopack","config","fetchCacheKeyPrefix","middlewareMatchers","previewProps","browserslistQuery","noMangling","writeRoutesHashesManifest","isPersistentCachingEnabled","nextVersion","serverHmr","turbopackMemoryEviction","turbopackMemoryEvictionMode","isShortSession","eventTypes","parentSpan","bind","canonicalDistDir","installCodeFrameSupport","onDevServerCleanup","onExit","unlock","entrypointsSubscription","entrypointsSubscribe","currentWrittenEntrypoints","Map","currentEntrypoints","global","app","document","middleware","instrumentation","page","currentTopLevelIssues","currentEntryIssues","manifestLoader","sriEnabled","changeSubscriptions","serverPathState","readyIds","currentEntriesHandlingResolve","currentEntriesHandling","assetMapper","deferredEntriesConfig","deferredEntries","hasDeferredEntriesConfig","onBeforeDeferredEntriesCalled","onBeforeDeferredEntriesPromise","nonDeferredBuildingEntries","waitForNonDeferredEntries","checkEntries","processDeferredEntry","onBeforeDeferredEntries","hmrPendingDeferredCallback","callOnBeforeDeferredEntriesAfterHMR","clearRequireCache","key","writtenEndpoint","force","path","contentHash","serverPaths","endsWith","localKey","set","hasChange","currentPaths","localHash","get","globalHash","localKeyPrefix","pathKey","has","slice","delete","map","p","entryType","usesServerHmr","serverChunksPrefix","filesToDelete","file","push","__next__clear_chunk_cache__","buildingIds","startBuilding","id","requestUrl","forceRebuild","setState","loading","trigger","url","finishBuilding","hmrEventHappened","hmrHash","pendingBuilding","clientsWithoutHtmlRequestId","clientsByHtmlRequestId","cacheStatusesByHtmlRequestId","clientStates","WeakMap","sendToClient","client","message","data","stringify","send","updateInProgress","pendingServerComponentChanges","sendServerComponentChanges","sendHmr","SERVER_COMPONENT_CHANGES","handleServerComponentChanges","hasCompilationErrors","issueMap","values","filter","i","severity","sendEnqueuedMessages","state","clientIssues","messages","clear","turbopackUpdates","TURBOPACK_MESSAGE","sendEnqueuedMessagesDebounce","flush","sendTurbopackMessage","payload","diagnostics","issues","subscribeToClientChanges","includeIssues","endpoint","createMessage","onError","side","changedPromise","changed","change","String","e","unsubscribeFromClientChanges","return","subscribeToClientHmrEvents","subscriptions","hmrEvents","Client","reloadMessage","RELOAD_PAGE","close","unsubscribeFromClientHmrEvents","handleEntrypointsSubscription","entrypoints","routes","existingRoutes","newRoutes","addedRoutes","route","removedRoutes","devRewrites","productionRewrites","logErrors","clients","hooks","handleWrittenEndpoint","forceDeleteCache","subscribeToChanges","unsubscribeFromChanges","unsubscribeFromHmrEvents","hotReloader","DEV_PAGES_MANIFEST_UPDATE","devPagesManifest","ADDED_PAGE","REMOVED_PAGE","recursive","middlewares","isSrcDir","telemetry","turbopackProject","sendUpdateSignal","DEVTOOLS_CONFIG","pagesDir","appDir","sendHmrMessage","getActiveConnectionCount","getDevServerUrl","__NEXT_PRIVATE_ORIGIN","getTurbopackProject","compileRoute","routeSpecifier","resolved","appFiles","pageFiles","dynamicRoutes","getDynamicRoutes","pathname","code","extraOptions","name","definition","bundlePath","filename","ensureOpts","clientOnly","snapshotBefore","moduleBuildError","ensurePage","rawIssues","request","isServer","isEdgeServer","isAppDirectory","frames","versionInfoCached","getVersionInfoCached","devtoolsFrontendUrl","inspectorURLRaw","inspectorURL","URL","debugInfo","debugInfoList","fetch","host","then","res","json","activeWebpackConfigs","serverStats","edgeServerStats","run","req","_parsedUrl","params","decodedPagePath","param","decodeURIComponent","denormalizedPagePath","catch","calledNext","finished","onHMR","socket","head","onUpgrade","handleUpgrade","htmlRequestId","searchParams","enableCacheComponents","cacheComponents","isLegacyClient","cacheStatus","CACHE_INDICATOR","on","addEventListener","parsedData","toString","event","manualTraceChild","spanName","startTime","endTime","attributes","updatedModules","isPageHidden","hadRuntimeError","dependencyChain","warn","isArray","cleanedModulePath","replace","entries","router","sourceType","logging","browserToTerminal","requestId","errorState","segmentTrieData","turbopackConnectedMessage","TURBOPACK_CONNECTED","errors","entryIssues","issue","disabledUntil","Date","now","versionInfo","devToolsConfig","syncMessage","SYNC","warnings","hash","debug","devIndicator","requestInsights","action","getServerComponentsHmrRefreshHash","sendToLegacyClients","setCacheStatus","status","setReactDebugChannel","debugChannel","sendErrorsToBrowser","errorsRscStream","setHmrServerError","_error","clearHmrServerError","start","getCompilationErrors","appEntryKey","pagesEntryKey","topLevelIssues","thisEntryIssues","formattedIssue","invalidate","reloadAfterInvalidation","entrypoint","buildFallbackError","inputPage","appPaths","isApp","traceChild","traceAsyncFn","routeDef","pageExtensions","globalNotFound","isDeferred","normalizedPage","matchingAppPaths","setPathsForKey","clientPaths","isInsideAppDir","isEntryMetadataRouteFile","normalizedAppPage","wsClient","terminate","exit","writeManifests","handleProjectUpdates","BUILDING_MESSAGE_DEFER_MS","updateMessage","updateInfoSubscribe","updateType","schedule","BUILDING","cancel","addToErrorsMap","errorsMap","details","detail","addErrors","clientErrors","BUILT","time","value","duration","timeMessage","round","notifyServerComponentChanges","serverChunksDir","chunkPaths","cache","manifestPaths","manifestPath","filePaths","evictModules"],"mappings":"AACA,SAASA,KAAK,EAAEC,SAAS,QAAQ,cAAa;AAC9C,SAASC,YAAY,QAAQ,KAAI;AACjC,YAAYC,eAAe,YAAW;AACtC,SAASC,IAAI,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,UAAU,EAAEC,GAAG,QAAQ,OAAM;AAC/D,SAASC,aAAa,EAAEC,aAAa,QAAQ,MAAK;AAElD,OAAOC,QAAQ,wBAAuB;AAGtC,SAASC,SAASC,YAAY,QAAQ,2BAA0B;AAShE,SAASC,2BAA2B,QAAQ,uBAAsB;AAWlE,SAASC,eAAe,EAAEC,eAAe,EAAEC,SAAS,QAAQ,kBAAiB;AAC7E,YAAYC,SAAS,yBAAwB;AAC7C,SAASC,aAAa,QAAQ,6BAA4B;AAC1D,SACEC,oBAAoB,EACpBC,sBAAsB,EACtBC,sBAAsB,QACjB,yBAAwB;AAC/B,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,QAAQ,QAAQ,WAAU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