Commit 837a44a8 authored by Josh Story's avatar Josh Story

Decouple synchronous IO and console file tracking from node-environment setup

The random, date, web-crypto, and node-crypto environment extensions imported io-utils.tsx which pulled in dynamic-rendering, work-unit-async-storage, and other server runtime modules. Similarly, console-file imported formatConsoleArgs and getFileLogger. These modules should be bundled when used — not loaded as raw Node.js requires from the environment setup path where module aliasing and React resolution aren't configured.

This splits the IO and console-file tracking into thin dispatchers and registered handlers:

  - sync-io-utils.external.tsx exports syncIO() (a no-op until registered) and registerSyncIOHandler(). The extensions call syncIO() without importing any server runtime modules.
  - sync-io-handler.tsx in app-render/ contains the full sync IO implementation with all server runtime dependencies. It's intentionally not .external so its imports go through the bundler.
  - console-file.external.tsx exports registerConsoleFileHandler() and dispatches to the registered handler. The formatting and file logger logic moves to console-file-handler.tsx in app-render/.
  - attach-node-environment-handlers.tsx in app-render/ is a single module that wires up all handlers. Both app-page/module.ts and app-route/module.ts import it with one line.

All node-environment files and extensions are renamed with the .external suffix so the bundler always externalizes them via commonjs require(). Each extension imports node-environment.external directly so the environment is guaranteed to be ready regardless of load order. next-server.ts no longer imports node-environment since the extensions handle their own setup.
parent 5dab0e7e
...@@ -578,7 +578,7 @@ export async function handleBuildComplete({ ...@@ -578,7 +578,7 @@ export async function handleBuildComplete({
if (bundler !== Bundler.Turbopack) { if (bundler !== Bundler.Turbopack) {
// These are modules that are necessary for bootstrapping node env // These are modules that are necessary for bootstrapping node env
const necessaryNodeDependencies = [ const necessaryNodeDependencies = [
require.resolve('next/dist/server/node-environment'), require.resolve('next/dist/server/node-environment.external'),
require.resolve('next/dist/server/require-hook'), require.resolve('next/dist/server/require-hook'),
require.resolve('next/dist/server/node-polyfill-crypto'), require.resolve('next/dist/server/node-polyfill-crypto'),
...Object.values(defaultOverrides).filter((item) => ...Object.values(defaultOverrides).filter((item) =>
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
// as expected without require `next-server` // as expected without require `next-server`
if (process.env.NEXT_RUNTIME !== 'edge') { if (process.env.NEXT_RUNTIME !== 'edge') {
// eslint-disable-next-line @next/internal/typechecked-require // eslint-disable-next-line @next/internal/typechecked-require
require('next/dist/server/node-environment') require('next/dist/server/node-environment.external')
// eslint-disable-next-line @next/internal/typechecked-require // eslint-disable-next-line @next/internal/typechecked-require
require('next/dist/server/require-hook') require('next/dist/server/require-hook')
// eslint-disable-next-line @next/internal/typechecked-require // eslint-disable-next-line @next/internal/typechecked-require
......
...@@ -36,7 +36,7 @@ import type { NextComponentType } from '../shared/lib/utils' ...@@ -36,7 +36,7 @@ import type { NextComponentType } from '../shared/lib/utils'
import '../server/require-hook' import '../server/require-hook'
import '../server/node-polyfill-crypto' import '../server/node-polyfill-crypto'
import '../server/node-environment' import '../server/node-environment.external'
import { bold, cyan, green, red, underline, yellow } from '../lib/picocolors' import { bold, cyan, green, red, underline, yellow } from '../lib/picocolors'
import textTable from 'next/dist/compiled/text-table' import textTable from 'next/dist/compiled/text-table'
......
...@@ -10,7 +10,7 @@ import type { ...@@ -10,7 +10,7 @@ import type {
import type { AppPageModule } from '../server/route-modules/app-page/module' import type { AppPageModule } from '../server/route-modules/app-page/module'
import type { PagesModule } from '../server/route-modules/pages/module.compiled' import type { PagesModule } from '../server/route-modules/pages/module.compiled'
import '../server/node-environment' import '../server/node-environment.external'
process.env.NEXT_IS_EXPORT_WORKER = 'true' process.env.NEXT_IS_EXPORT_WORKER = 'true'
...@@ -53,7 +53,7 @@ import type { PagesRenderContext, PagesSharedContext } from '../server/render' ...@@ -53,7 +53,7 @@ import type { PagesRenderContext, PagesSharedContext } from '../server/render'
import type { AppSharedContext } from '../server/app-render/app-render' import type { AppSharedContext } from '../server/app-render/app-render'
import { MultiFileWriter } from '../lib/multi-file-writer' import { MultiFileWriter } from '../lib/multi-file-writer'
import { createRenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache' import { createRenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'
import { installGlobalBehaviors } from '../server/node-environment-extensions/global-behaviors' import { installGlobalBehaviors } from '../server/node-environment-extensions/global-behaviors.external'
;(globalThis as any).__NEXT_DATA__ = { ;(globalThis as any).__NEXT_DATA__ = {
nextExport: true, nextExport: true,
} }
......
/**
* Attaches bundled handler implementations to the node-environment extensions.
*
* The node-environment extensions (random, date, crypto, console-file) patch
* globals at process startup and dispatch to registered handlers at runtime.
* The handlers live here in app-render/ because they depend on server runtime
* modules that must go through the bundler for correct React resolution.
*
* This module should be imported once from each bundled entry point
* (app-page/module.ts, app-route/module.ts) to wire up the handlers.
*/
import { registerSyncIOHandler } from '../node-environment-extensions/sync-io-utils.external'
import { handleSyncIO } from './sync-io-handler'
registerSyncIOHandler(handleSyncIO)
import { workAsyncStorage } from '../app-render/work-async-storage.external' /**
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external' * The real IO handler implementation. This module depends on app router
import { abortOnSynchronousPlatformIOAccess } from '../app-render/dynamic-rendering' * internals (dynamic-rendering, work-unit-async-storage, etc.) and must only
* be imported when the app router rendering runtime is loaded — never at
* environment setup time.
*
* Registered via registerIOHandler() in the app-page route module.
*/
import { workAsyncStorage } from './work-async-storage.external'
import { workUnitAsyncStorage } from './work-unit-async-storage.external'
import { abortOnSynchronousPlatformIOAccess } from './dynamic-rendering'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { RenderStage } from '../app-render/staged-rendering' import { RenderStage } from './staged-rendering'
import { getServerReact, getClientReact } from '../runtime-reacts.external' import { getServerReact, getClientReact } from '../runtime-reacts.external'
type ApiType = 'time' | 'random' | 'crypto' type ApiType = 'time' | 'random' | 'crypto'
export function io(expression: string, type: ApiType) { export function handleSyncIO(expression: string, type: ApiType): void {
const workUnitStore = workUnitAsyncStorage.getStore() const workUnitStore = workUnitAsyncStorage.getStore()
const workStore = workAsyncStorage.getStore() const workStore = workAsyncStorage.getStore()
......
...@@ -9,7 +9,7 @@ import type { ...@@ -9,7 +9,7 @@ import type {
} from '../route-modules/app-route/module.compiled' } from '../route-modules/app-route/module.compiled'
import '../require-hook' import '../require-hook'
import '../node-environment' import '../node-environment.external'
import { collectSegments } from '../../build/segment-config/app/app-segments' import { collectSegments } from '../../build/segment-config/app/app-segments'
import type { StaticPathsResult } from '../../build/static-paths/types' import type { StaticPathsResult } from '../../build/static-paths/types'
......
...@@ -4,7 +4,7 @@ import type { DevBundler, ServerFields } from './router-utils/setup-dev-bundler' ...@@ -4,7 +4,7 @@ import type { DevBundler, ServerFields } from './router-utils/setup-dev-bundler'
import type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta' import type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta'
// This is required before other imports to ensure the require hook is setup. // This is required before other imports to ensure the require hook is setup.
import '../node-environment' import '../node-environment.external'
import '../require-hook' import '../require-hook'
import url from 'url' import url from 'url'
......
import './node-environment'
import './require-hook' import './require-hook'
import './node-polyfill-crypto' import './node-polyfill-crypto'
...@@ -128,8 +127,8 @@ import { ...@@ -128,8 +127,8 @@ import {
RouterServerContextSymbol, RouterServerContextSymbol,
routerServerGlobal, routerServerGlobal,
} from './lib/router-utils/router-server-context' } from './lib/router-utils/router-server-context'
import { installGlobalBehaviors } from './node-environment-extensions/global-behaviors' import { installGlobalBehaviors } from './node-environment-extensions/global-behaviors.external'
import { installProcessErrorHandlers } from './node-environment-extensions/process-error-handlers' import { installProcessErrorHandlers } from './node-environment-extensions/process-error-handlers.external'
export * from './base-server' export * from './base-server'
......
...@@ -132,7 +132,7 @@ describe('console-exit patches', () => { ...@@ -132,7 +132,7 @@ describe('console-exit patches', () => {
} }
// Install patches - this wraps the current console.log // Install patches - this wraps the current console.log
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
// Test outside storage context // Test outside storage context
console.log('outside') console.log('outside')
...@@ -160,7 +160,7 @@ describe('console-exit patches', () => { ...@@ -160,7 +160,7 @@ describe('console-exit patches', () => {
} = require('next/dist/server/app-render/work-unit-async-storage.external') } = require('next/dist/server/app-render/work-unit-async-storage.external')
// Install patches first // Install patches first
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
// Assign a new console.log after patching - this will NOT be wrapped // Assign a new console.log after patching - this will NOT be wrapped
console.log = function (...args) { console.log = function (...args) {
...@@ -206,7 +206,7 @@ describe('console-exit patches', () => { ...@@ -206,7 +206,7 @@ describe('console-exit patches', () => {
}) })
// install patch // install patch
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
// Test that patched methods preserve name and other properties // Test that patched methods preserve name and other properties
reportResult({ reportResult({
...@@ -247,7 +247,7 @@ describe('console-exit patches', () => { ...@@ -247,7 +247,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.log('inside') console.log('inside')
...@@ -279,7 +279,7 @@ describe('console-exit patches', () => { ...@@ -279,7 +279,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.error('inside') console.error('inside')
...@@ -311,7 +311,7 @@ describe('console-exit patches', () => { ...@@ -311,7 +311,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.warn('inside') console.warn('inside')
...@@ -343,7 +343,7 @@ describe('console-exit patches', () => { ...@@ -343,7 +343,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.info('inside') console.info('inside')
...@@ -375,7 +375,7 @@ describe('console-exit patches', () => { ...@@ -375,7 +375,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.debug('inside') console.debug('inside')
...@@ -407,7 +407,7 @@ describe('console-exit patches', () => { ...@@ -407,7 +407,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.trace('inside') console.trace('inside')
...@@ -439,7 +439,7 @@ describe('console-exit patches', () => { ...@@ -439,7 +439,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.dir('inside') console.dir('inside')
...@@ -471,7 +471,7 @@ describe('console-exit patches', () => { ...@@ -471,7 +471,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.dirxml('inside') console.dirxml('inside')
...@@ -503,7 +503,7 @@ describe('console-exit patches', () => { ...@@ -503,7 +503,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.table('inside') console.table('inside')
...@@ -535,7 +535,7 @@ describe('console-exit patches', () => { ...@@ -535,7 +535,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.assert('inside') console.assert('inside')
...@@ -567,7 +567,7 @@ describe('console-exit patches', () => { ...@@ -567,7 +567,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.group('inside') console.group('inside')
...@@ -599,7 +599,7 @@ describe('console-exit patches', () => { ...@@ -599,7 +599,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.groupCollapsed('inside') console.groupCollapsed('inside')
...@@ -631,7 +631,7 @@ describe('console-exit patches', () => { ...@@ -631,7 +631,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
console.groupEnd() console.groupEnd()
...@@ -665,7 +665,7 @@ describe('console-exit patches', () => { ...@@ -665,7 +665,7 @@ describe('console-exit patches', () => {
}) })
} }
require('next/dist/server/node-environment-extensions/console-exit') require('next/dist/server/node-environment-extensions/console-exit.external')
workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => { workUnitAsyncStorage.run({ type: 'request' } as WorkUnitStore, () => {
// @ts-expect-error - calling our custom property // @ts-expect-error - calling our custom property
......
...@@ -9,12 +9,12 @@ ...@@ -9,12 +9,12 @@
* *
* The extensions here never error nor alter the underlying Date objects, strings, and numbers created and thus should be transparent to callers. * The extensions here never error nor alter the underlying Date objects, strings, and numbers created and thus should be transparent to callers.
*/ */
import { io } from './io-utils' import { syncIO } from './sync-io-utils.external'
function createNow(originalNow: typeof Date.now) { function createNow(originalNow: typeof Date.now) {
return { return {
now: function now() { now: function now() {
io('`Date.now()`', 'time') syncIO('`Date.now()`', 'time')
return originalNow() return originalNow()
}, },
}['now'.slice() as 'now'].bind(null) }['now'.slice() as 'now'].bind(null)
...@@ -31,11 +31,11 @@ function createDate(originalConstructor: typeof Date): typeof Date { ...@@ -31,11 +31,11 @@ function createDate(originalConstructor: typeof Date): typeof Date {
// Ideally this should not minify the name. // Ideally this should not minify the name.
function Date() { function Date() {
if (new.target === undefined) { if (new.target === undefined) {
io('`Date()`', 'time') syncIO('`Date()`', 'time')
return apply(originalConstructor, undefined, arguments) return apply(originalConstructor, undefined, arguments)
} }
if (arguments.length === 0) { if (arguments.length === 0) {
io('`new Date()`', 'time') syncIO('`new Date()`', 'time')
} }
return construct(originalConstructor, arguments, new.target) return construct(originalConstructor, arguments, new.target)
}, },
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
* The extensions here never error nor alter the underlying return values and thus should be transparent to callers. * The extensions here never error nor alter the underlying return values and thus should be transparent to callers.
*/ */
import { io } from './io-utils' import { syncIO } from './sync-io-utils.external'
if (process.env.NEXT_RUNTIME === 'edge') { if (process.env.NEXT_RUNTIME === 'edge') {
// nothing to patch // nothing to patch
...@@ -23,7 +23,7 @@ if (process.env.NEXT_RUNTIME === 'edge') { ...@@ -23,7 +23,7 @@ if (process.env.NEXT_RUNTIME === 'edge') {
try { try {
const _randomUUID = nodeCrypto.randomUUID const _randomUUID = nodeCrypto.randomUUID
nodeCrypto.randomUUID = function randomUUID() { nodeCrypto.randomUUID = function randomUUID() {
io(randomUUIDExpression, 'random') syncIO(randomUUIDExpression, 'random')
return _randomUUID.apply(this, arguments as any) return _randomUUID.apply(this, arguments as any)
} }
} catch { } catch {
...@@ -39,7 +39,7 @@ if (process.env.NEXT_RUNTIME === 'edge') { ...@@ -39,7 +39,7 @@ if (process.env.NEXT_RUNTIME === 'edge') {
nodeCrypto.randomBytes = function randomBytes() { nodeCrypto.randomBytes = function randomBytes() {
if (typeof arguments[1] !== 'function') { if (typeof arguments[1] !== 'function') {
// randomBytes is sync if the second arg is undefined // randomBytes is sync if the second arg is undefined
io(randomBytesExpression, 'random') syncIO(randomBytesExpression, 'random')
} }
return _randomBytes.apply(this, arguments as any) return _randomBytes.apply(this, arguments as any)
} }
...@@ -55,7 +55,7 @@ if (process.env.NEXT_RUNTIME === 'edge') { ...@@ -55,7 +55,7 @@ if (process.env.NEXT_RUNTIME === 'edge') {
const _randomFillSync = nodeCrypto.randomFillSync const _randomFillSync = nodeCrypto.randomFillSync
// @ts-expect-error -- TODO: tell TS the overloads are preserved // @ts-expect-error -- TODO: tell TS the overloads are preserved
nodeCrypto.randomFillSync = function randomFillSync() { nodeCrypto.randomFillSync = function randomFillSync() {
io(randomFillSyncExpression, 'random') syncIO(randomFillSyncExpression, 'random')
return _randomFillSync.apply(this, arguments as any) return _randomFillSync.apply(this, arguments as any)
} }
} catch { } catch {
...@@ -71,7 +71,7 @@ if (process.env.NEXT_RUNTIME === 'edge') { ...@@ -71,7 +71,7 @@ if (process.env.NEXT_RUNTIME === 'edge') {
nodeCrypto.randomInt = function randomInt() { nodeCrypto.randomInt = function randomInt() {
if (typeof arguments[2] !== 'function') { if (typeof arguments[2] !== 'function') {
// randomInt is sync if the third arg is undefined // randomInt is sync if the third arg is undefined
io(randomIntExpression, 'random') syncIO(randomIntExpression, 'random')
} }
return _randomInt.apply(this, arguments as any) return _randomInt.apply(this, arguments as any)
} }
...@@ -87,7 +87,7 @@ if (process.env.NEXT_RUNTIME === 'edge') { ...@@ -87,7 +87,7 @@ if (process.env.NEXT_RUNTIME === 'edge') {
const _generatePrimeSync = nodeCrypto.generatePrimeSync const _generatePrimeSync = nodeCrypto.generatePrimeSync
// @ts-expect-error -- TODO: tell TS the overloads are preserved // @ts-expect-error -- TODO: tell TS the overloads are preserved
nodeCrypto.generatePrimeSync = function generatePrimeSync() { nodeCrypto.generatePrimeSync = function generatePrimeSync() {
io(generatePrimeSyncExpression, 'random') syncIO(generatePrimeSyncExpression, 'random')
return _generatePrimeSync.apply(this, arguments as any) return _generatePrimeSync.apply(this, arguments as any)
} }
} catch { } catch {
...@@ -102,7 +102,7 @@ if (process.env.NEXT_RUNTIME === 'edge') { ...@@ -102,7 +102,7 @@ if (process.env.NEXT_RUNTIME === 'edge') {
const _generateKeyPairSync = nodeCrypto.generateKeyPairSync const _generateKeyPairSync = nodeCrypto.generateKeyPairSync
// @ts-expect-error -- TODO: tell TS the overloads are preserved // @ts-expect-error -- TODO: tell TS the overloads are preserved
nodeCrypto.generateKeyPairSync = function generateKeyPairSync() { nodeCrypto.generateKeyPairSync = function generateKeyPairSync() {
io(generateKeyPairSyncExpression, 'random') syncIO(generateKeyPairSyncExpression, 'random')
return _generateKeyPairSync.apply(this, arguments as any) return _generateKeyPairSync.apply(this, arguments as any)
} }
} catch { } catch {
...@@ -116,7 +116,7 @@ if (process.env.NEXT_RUNTIME === 'edge') { ...@@ -116,7 +116,7 @@ if (process.env.NEXT_RUNTIME === 'edge') {
try { try {
const _generateKeySync = nodeCrypto.generateKeySync const _generateKeySync = nodeCrypto.generateKeySync
nodeCrypto.generateKeySync = function generateKeySync() { nodeCrypto.generateKeySync = function generateKeySync() {
io(generateKeySyncExpression, 'random') syncIO(generateKeySyncExpression, 'random')
return _generateKeySync.apply(this, arguments as any) return _generateKeySync.apply(this, arguments as any)
} }
} catch { } catch {
......
...@@ -6,13 +6,13 @@ ...@@ -6,13 +6,13 @@
* The extensions here never error nor alter the random generation itself and thus should be transparent to callers. * The extensions here never error nor alter the random generation itself and thus should be transparent to callers.
*/ */
import { io } from './io-utils' import { syncIO } from './sync-io-utils.external'
const expression = '`Math.random()`' const expression = '`Math.random()`'
try { try {
const _random = Math.random const _random = Math.random
Math.random = function random() { Math.random = function random() {
io(expression, 'random') syncIO(expression, 'random')
return _random.apply(null, arguments as any) return _random.apply(null, arguments as any)
// We bind here to alter the `toString` printing to match `Math.random`'s native `toString`. // We bind here to alter the `toString` printing to match `Math.random`'s native `toString`.
......
/**
* Thin dispatcher for synchronous IO tracking in node-environment extensions.
*
* The extensions (random, date, crypto) patch globals at environment setup
* time and call syncIO() on every invocation. The actual implementation lives
* in sync-io-handler.tsx and is registered when the app router rendering
* runtime loads. This avoids pulling server runtime modules into the
* environment setup path.
*/
type ApiType = 'time' | 'random' | 'crypto'
type SyncIOHandler = (expression: string, type: ApiType) => void
let handler: SyncIOHandler | null = null
export function registerSyncIOHandler(syncIOHandler: SyncIOHandler): void {
handler = syncIOHandler
}
export function syncIO(expression: string, type: ApiType): void {
if (handler !== null) {
handler(expression, type)
}
}
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
* The extensions here never error nor alter the underlying return values and thus should be transparent to callers. * The extensions here never error nor alter the underlying return values and thus should be transparent to callers.
*/ */
import { io } from './io-utils' import { syncIO } from './sync-io-utils.external'
let webCrypto: typeof crypto let webCrypto: typeof crypto
if (process.env.NEXT_RUNTIME === 'edge') { if (process.env.NEXT_RUNTIME === 'edge') {
...@@ -26,7 +26,7 @@ const getRandomValuesExpression = '`crypto.getRandomValues()`' ...@@ -26,7 +26,7 @@ const getRandomValuesExpression = '`crypto.getRandomValues()`'
try { try {
const _getRandomValues = webCrypto.getRandomValues const _getRandomValues = webCrypto.getRandomValues
webCrypto.getRandomValues = function getRandomValues() { webCrypto.getRandomValues = function getRandomValues() {
io(getRandomValuesExpression, 'crypto') syncIO(getRandomValuesExpression, 'crypto')
return _getRandomValues.apply(webCrypto, arguments as any) return _getRandomValues.apply(webCrypto, arguments as any)
} }
} catch { } catch {
...@@ -39,7 +39,7 @@ const randomUUIDExpression = '`crypto.randomUUID()`' ...@@ -39,7 +39,7 @@ const randomUUIDExpression = '`crypto.randomUUID()`'
try { try {
const _randomUUID = webCrypto.randomUUID const _randomUUID = webCrypto.randomUUID
webCrypto.randomUUID = function randomUUID() { webCrypto.randomUUID = function randomUUID() {
io(randomUUIDExpression, 'crypto') syncIO(randomUUIDExpression, 'crypto')
return _randomUUID.apply(webCrypto, arguments as any) return _randomUUID.apply(webCrypto, arguments as any)
} as typeof _randomUUID } as typeof _randomUUID
} catch { } catch {
......
// This file should be imported before any others. It sets up the environment // This file should be imported before any others. It sets up the environment
// for later imports to work properly. // for later imports to work properly.
import './node-environment-baseline' import './node-environment-baseline.external'
// Import as early as possible so that unexpected errors in other extensions are properly formatted. // Import as early as possible so that unexpected errors in other extensions are properly formatted.
// Has to come after baseline since error-inspect requires AsyncLocalStorage that baseline provides. // Has to come after baseline since error-inspect requires AsyncLocalStorage that baseline provides.
import './node-environment-extensions/error-inspect' import './node-environment-extensions/error-inspect.external'
// console file needs to go first because we want to be in a dimmed scope before // console file needs to go first because we want to be in a dimmed scope before
// deciding if we ought to write the log to file. // deciding if we ought to write the log to file.
import './node-environment-extensions/console-file' import './node-environment-extensions/console-file.external'
import './node-environment-extensions/console-exit' import './node-environment-extensions/console-exit.external'
import './node-environment-extensions/console-dim.external' import './node-environment-extensions/console-dim.external'
import './node-environment-extensions/unhandled-rejection.external' import './node-environment-extensions/unhandled-rejection.external'
import './node-environment-extensions/random' import './node-environment-extensions/random.external'
import './node-environment-extensions/date' import './node-environment-extensions/date.external'
import './node-environment-extensions/web-crypto' import './node-environment-extensions/web-crypto.external'
import './node-environment-extensions/node-crypto' import './node-environment-extensions/node-crypto.external'
import './node-environment-extensions/fast-set-immediate.external' import './node-environment-extensions/fast-set-immediate.external'
import '../../app-render/attach-node-environment-handlers'
import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition' import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition'
import type RenderResult from '../../render-result' import type RenderResult from '../../render-result'
import type { RenderOpts } from '../../app-render/types' import type { RenderOpts } from '../../app-render/types'
......
import '../../app-render/attach-node-environment-handlers'
import type { NextConfig } from '../../config-shared' import type { NextConfig } from '../../config-shared'
import type { AppRouteRouteDefinition } from '../../route-definitions/app-route-route-definition' import type { AppRouteRouteDefinition } from '../../route-definitions/app-route-route-definition'
import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config' import type { AppSegmentConfig } from '../../../build/segment-config/app/app-segment-config'
......
...@@ -948,7 +948,7 @@ export abstract class RouteModule< ...@@ -948,7 +948,7 @@ export abstract class RouteModule<
if (process.env.NEXT_RUNTIME !== 'edge') { if (process.env.NEXT_RUNTIME !== 'edge') {
const { installProcessErrorHandlers } = const { installProcessErrorHandlers } =
require('../node-environment-extensions/process-error-handlers') as typeof import('../node-environment-extensions/process-error-handlers') require('../node-environment-extensions/process-error-handlers.external') as typeof import('../node-environment-extensions/process-error-handlers.external')
installProcessErrorHandlers( installProcessErrorHandlers(
Boolean( Boolean(
......
...@@ -19,7 +19,7 @@ async function main() { ...@@ -19,7 +19,7 @@ async function main() {
const port = await getPort() const port = await getPort()
const hostname = 'localhost' const hostname = 'localhost'
require('next/dist/server/node-environment') require('next/dist/server/node-environment.external')
const entrypointPath = path.join( const entrypointPath = path.join(
__dirname, __dirname,
......
...@@ -441,8 +441,10 @@ async function readNormalizedNFT(next, name) { ...@@ -441,8 +441,10 @@ async function readNormalizedNFT(next, name) {
) )
expect(trace).toMatchInlineSnapshot(` expect(trace).toMatchInlineSnapshot(`
[ [
"/node_modules/@swc/helpers/cjs/_interop_require_default.cjs",
"/node_modules/client-only/index.js", "/node_modules/client-only/index.js",
"/node_modules/next/dist/client/components/app-router-headers.js", "/node_modules/next/dist/client/components/app-router-headers.js",
"/node_modules/next/dist/client/lib/console.js",
"/node_modules/next/dist/compiled/@opentelemetry/api/index.js", "/node_modules/next/dist/compiled/@opentelemetry/api/index.js",
"/node_modules/next/dist/compiled/babel-code-frame/index.js", "/node_modules/next/dist/compiled/babel-code-frame/index.js",
"/node_modules/next/dist/compiled/babel/code-frame.js", "/node_modules/next/dist/compiled/babel/code-frame.js",
...@@ -458,6 +460,7 @@ async function readNormalizedNFT(next, name) { ...@@ -458,6 +460,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/lib/interop-default.js", "/node_modules/next/dist/lib/interop-default.js",
"/node_modules/next/dist/lib/is-error.js", "/node_modules/next/dist/lib/is-error.js",
"/node_modules/next/dist/lib/picocolors.js", "/node_modules/next/dist/lib/picocolors.js",
"/node_modules/next/dist/next-devtools/server/shared.js",
"/node_modules/next/dist/server/app-render/after-task-async-storage-instance.js", "/node_modules/next/dist/server/app-render/after-task-async-storage-instance.js",
"/node_modules/next/dist/server/app-render/after-task-async-storage.external.js", "/node_modules/next/dist/server/app-render/after-task-async-storage.external.js",
"/node_modules/next/dist/server/app-render/async-local-storage.js", "/node_modules/next/dist/server/app-render/async-local-storage.js",
...@@ -468,18 +471,35 @@ async function readNormalizedNFT(next, name) { ...@@ -468,18 +471,35 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/server/app-render/work-async-storage.external.js", "/node_modules/next/dist/server/app-render/work-async-storage.external.js",
"/node_modules/next/dist/server/app-render/work-unit-async-storage-instance.js", "/node_modules/next/dist/server/app-render/work-unit-async-storage-instance.js",
"/node_modules/next/dist/server/app-render/work-unit-async-storage.external.js", "/node_modules/next/dist/server/app-render/work-unit-async-storage.external.js",
"/node_modules/next/dist/server/dev/browser-logs/file-logger.js",
"/node_modules/next/dist/server/lib/incremental-cache/memory-cache.external.js", "/node_modules/next/dist/server/lib/incremental-cache/memory-cache.external.js",
"/node_modules/next/dist/server/lib/incremental-cache/shared-cache-controls.external.js", "/node_modules/next/dist/server/lib/incremental-cache/shared-cache-controls.external.js",
"/node_modules/next/dist/server/lib/incremental-cache/tags-manifest.external.js", "/node_modules/next/dist/server/lib/incremental-cache/tags-manifest.external.js",
"/node_modules/next/dist/server/lib/lru-cache.js", "/node_modules/next/dist/server/lib/lru-cache.js",
"/node_modules/next/dist/server/lib/parse-stack.js",
"/node_modules/next/dist/server/lib/router-utils/instrumentation-globals.external.js", "/node_modules/next/dist/server/lib/router-utils/instrumentation-globals.external.js",
"/node_modules/next/dist/server/lib/router-utils/instrumentation-node-extensions.js", "/node_modules/next/dist/server/lib/router-utils/instrumentation-node-extensions.js",
"/node_modules/next/dist/server/lib/router-utils/is-postpone.js",
"/node_modules/next/dist/server/lib/source-maps.js",
"/node_modules/next/dist/server/lib/trace/constants.js", "/node_modules/next/dist/server/lib/trace/constants.js",
"/node_modules/next/dist/server/lib/trace/tracer.js", "/node_modules/next/dist/server/lib/trace/tracer.js",
"/node_modules/next/dist/server/load-manifest.external.js", "/node_modules/next/dist/server/load-manifest.external.js",
"/node_modules/next/dist/server/node-environment-baseline.external.js",
"/node_modules/next/dist/server/node-environment-extensions/console-dim.external.js", "/node_modules/next/dist/server/node-environment-extensions/console-dim.external.js",
"/node_modules/next/dist/server/node-environment-extensions/console-exit.external.js",
"/node_modules/next/dist/server/node-environment-extensions/console-file.external.js",
"/node_modules/next/dist/server/node-environment-extensions/date.external.js",
"/node_modules/next/dist/server/node-environment-extensions/error-inspect.external.js",
"/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.js", "/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.js",
"/node_modules/next/dist/server/node-environment-extensions/global-behaviors.external.js",
"/node_modules/next/dist/server/node-environment-extensions/node-crypto.external.js",
"/node_modules/next/dist/server/node-environment-extensions/process-error-handlers.external.js",
"/node_modules/next/dist/server/node-environment-extensions/random.external.js",
"/node_modules/next/dist/server/node-environment-extensions/sync-io-utils.external.js",
"/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.js", "/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.js",
"/node_modules/next/dist/server/node-environment-extensions/web-crypto.external.js",
"/node_modules/next/dist/server/node-environment.external.js",
"/node_modules/next/dist/server/patch-error-inspect.js",
"/node_modules/next/dist/server/response-cache/types.js", "/node_modules/next/dist/server/response-cache/types.js",
"/node_modules/next/dist/server/route-modules/app-page/module.compiled.js", "/node_modules/next/dist/server/route-modules/app-page/module.compiled.js",
"/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.js", "/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.js",
...@@ -503,6 +523,7 @@ async function readNormalizedNFT(next, name) { ...@@ -503,6 +523,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/server/runtime-reacts.external.js", "/node_modules/next/dist/server/runtime-reacts.external.js",
"/node_modules/next/dist/shared/lib/deep-freeze.js", "/node_modules/next/dist/shared/lib/deep-freeze.js",
"/node_modules/next/dist/shared/lib/invariant-error.js", "/node_modules/next/dist/shared/lib/invariant-error.js",
"/node_modules/next/dist/shared/lib/is-internal.js",
"/node_modules/next/dist/shared/lib/is-plain-object.js", "/node_modules/next/dist/shared/lib/is-plain-object.js",
"/node_modules/next/dist/shared/lib/is-thenable.js", "/node_modules/next/dist/shared/lib/is-thenable.js",
"/node_modules/next/dist/shared/lib/no-fallback-error.external.js", "/node_modules/next/dist/shared/lib/no-fallback-error.external.js",
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment