it('should not bundle the root level package', () => {
  const modules = Array.from(__turbopack_modules__.keys())
  expect(modules).toContainEqual(
    expect.stringMatching(/input\/dir\/node_modules\/the-package\/index/)
  )
  expect(modules).not.toContainEqual(
    expect.stringMatching(/input\/node_modules\/the-package\/index/)
  )
})

it('should not bundle the other exports conditions', () => {
  require('package-with-exports/entry2')
  const modules = Array.from(__turbopack_modules__.keys())
  expect

ect(modules).not.toContainEqual(
    expect.stringMatching(/input\/node_modules\/package-with-exports\/b/)
  )
  expect(modules).not.toContainEqual(
    expect.stringMatching(/input\/node_modules\/package-with-exports\/c/)
  )
  expect(modules).not.toConta

(modules).toContainEqual(
    expect.stringMatching(/input\/node_modules\/package-with-exports\/a/)
  )
  expect(modules).not.toContainEqual(
    expect.stringMatching(/input\/node_modules\/package-with-exports\/index/)
  )
  exp


, () => {
  expect(require.resolve('./resolved.js')).toBe(
    '[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/require-resolve/input/resolved.js [test] (ecmascript)'
  )
})

it('should support require.resolve with extensions', () => {
  expect(require.resolve('./resolved')).toBe(
    '[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/require-resolve/input/resolved.js [test] (ecmascript)'
  )
})

it('should support require.resolve on the current mo

)).toBe(
    '[project]/turbopack/crates/turbopack-tests/tests/execution/turbopack/resolving/require-resolve/input/index.js [test] (ecmascript)'
  )
  // Check if static evaluation is not hanging
  if (require.resolve('./index.js') == '') {
    throw new E

dule', () => {
  expect(require.resolve('./index.js'


'as' option is not supported — should still produce a glob with defaults
const withAs = import.meta.glob('./dir/*.js', { as: 'raw' })

// Warning: non-constant eager — should default to lazy (eager: false)
const nonConstEager = import.meta.glob('./dir2/*.js', {
  eager: Math.random() > -1,
})

// Warning: unknown option — should be ignored, glob still works
const unknown = import.meta.glob(['./dir/*.js', './dir2/*.js'], {
  exhaust: true,
})

it('should still produce a lazy glob when "as" option is used', (

 default to lazy mode when eager is non-constant', () => {
  const keys = Object.keys(nonConstEager).sort()
  expect(keys).toEqual(['./dir2/qux.js'])
  // Should be lazy (thunks), since non-constant eager defaults to false
  expect(typeof nonConstEager['./

) => {
  const keys = Object.keys(withAs).sort()
  expect(keys).toEqual(['./dir/bar.js', './dir/foo.js'])
  // Should be lazy (thunks), since `as` is ignored
  expect(typeof withAs['./dir/foo.js']).toBe('function')
})

it('should


lass.js'
import * as liveExports from './live_exports.js'
import * as constDefaultExportFunction from './const_default_export_function.js'

it('hoisted declarations are live', () => {
  expect(liveExports.bar()).toBe('bar')
  liveExports.setBar(() => 'patched')
  expect(liveExports.bar()).toBe('patched')
})

it('default class export declarations are live', () => {
  expect(liveDefaultClass.default.default()).toBe('defaultClass')
  liveDefaultClass.setDefaultClass(
    class {
      static default() {

ts.setDefaultFunction(() => 'patched')
  expect(liveExports.default()).toBe('patched')
})

it('exported lets are live', () => {
  expect(liveExports.foo).toBe('foo')
  liveExports.setFoo('new')
  expect(liveExports.foo).toBe('new')
})

it('exported binding

  return 'patched'
      }
    }
  )
  expect(liveDefaultClass.default.default()).toBe('patched')
})

it('default function export declarations are live', () => {
  expect(liveExports.default()).toBe('defaultFunction')
  liveExpor


a, foo, bar, fooViaSelf, barViaSelf, nestedSelfFoo } from './data'
import * as DataNs from './data'
import {
  Data as ChainedData,
  foo as chainedFoo,
  bar as chainedBar,
} from './reexport'

it('should re-export own namespace correctly', () => {
  expect(Data.foo()).toBe('foo')
  expect(Data.bar()).toBe('bar')
})

it('should expose named exports alongside the self-namespace', () => {
  expect(foo()).toBe('foo')
  expect(bar()).toBe('bar')
})

it('should allow using the self-namespace from inside the mod

('foo')
  expect(Data.Data.Data.bar()).toBe('bar')
})

it('should expose the same self-namespace via a star-namespace import', () => {
  expect(DataNs.Data).toBe(Data)
  expect(DataNs.Data.foo).toBe(foo)
})

it('should re-export the self-namespace through

ule', () => {
  expect(fooViaSelf()).toBe('foo')
  expect(barViaSelf()).toBe('bar')
  expect(nestedSelfFoo()).toBe('foo')
})

it('should let the self-namespace reference itself recursively', () => {
  expect(Data.Data.foo()).toBe


const os = require('os')
const path = require('path')

function writeChunk(filePath, chunkModules) {
  fs.writeFileSync(filePath, `module.exports = ${chunkModules};\n`)
}

it('reuses the existing group factory for missing IDs', () => {
  const repoRoot = path.resolve(process.cwd(), '../../../../../../../..')
  const runtimePath = path.join(
    repoRoot,
    'turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js'
  )
  const createRuntime = eval('require

actory-group-'))
  try {
    const firstChunk = path.join(tempDir, 'first.js')
    const mixedChunk = path.join(tempDir, 'mixed.js')

    writeChunk(
      firstChunk,
      `[
        ${JSON.stringify(moduleA)},
        function (__turbopack_context__, mo

')(runtimePath)

  const suffix = `${Date.now()}-${Math.random().toString(16).slice(2)}`
  const moduleA = `module-a-${suffix}`
  const moduleB = `module-b-${suffix}`

  const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tp-f


'package/dep2.js'
import { something3 } from 'package-directive/dep.js'

it('should not include a module that is side effect free and exports are not used due to static analysis', () => {
  const modules = Array.from(__turbopack_modules__.keys())
  expect(modules).toContainEqual(
    expect.stringMatching(/input\/node_modules\/package\/dep2\.js/)
  )
  expect(modules).not.toContainEqual(
    expect.stringMatching(/input\/node_modules\/package\/dep\.js/)
  )

  if (true) {
    something2()
    return
  }
  s

is side effect free via directive and exports are not used due to static analysis', () => {
  const modules = Array.from(__turbopack_modules__.keys())
  expect(modules).not.toContainEqual(
    expect.stringMatching(/input\/node_modules\/package-directive\/

omething()
})

it('should not include a module that


rect facade from async modules', async () => {
  expect(await import('tla/local')).toEqual(
    expect.objectContaining({
      tla: 'tla',
      reexported: 'reexported',
      reexported2: 'reexported',
    })
  )
  expect(await import('tla/reexport')).toEqual(
    expect.objectContaining({
      local: 'local',
      tlaReexported: 'tla-reexported',
      tlaReexported2: 'tla-reexported',
    })
  )
  expect(await import('tla/both')).toEqual(
    expect.objectContaining({
      tla: 'tla',
      tlaReexp

amespace object from async modules', async () => {
  expect(tlaLocal).toEqual(
    expect.objectContaining({
      tla: 'tla',
      reexported: 'reexported',
      reexported2: 'reexported',
    })
  )
  expect(tlaReexport).toEqual(
    expect.objectConta

orted: 'tla-reexported',
      tlaReexported2: 'tla-reexported',
    })
  )
})

import * as tlaLocal from 'tla/local'
import * as tlaReexport from 'tla/reexport'
import * as tlaBoth from 'tla/both'
it('should generate a correct n


nst bool = true
    if (bool) {
      count++
    } else {
      throw Error('this branch is not taken')
    }
  })

  it('handles static expression', () => {
    let bool = false
    bool = true
    if (bool) {
      count++
    } else {
      throw Error('this branch is not taken')
    }
  })

  it('handles dynamic declaration', () => {
    function dynamic() {
      return true
    }
    const bool = dynamic()
    if (bool) {
      count++
    } else {
      throw Error('this branch is not taken')
    }

    }
  })
})

describe('Object Patterns', () => {
  it('handles static declaration', () => {
    const { bool } = {
      bool: true,
    }
    if (bool) {
      count++
    } else {
      throw Error('this branch is not taken')
    }
  })

  it('handles

  })

  it('handles dynamic expression', () => {
    function dynamic() {
      return true
    }
    let bool = false
    bool = dynamic()
    if (bool) {
      count++
    } else {
      throw Error('this branch is not taken')


package-reexport-side-effect'
import { effects as effects6 } from 'package-reexport-side-effect/check-side-effect'
it('should run side effects of a reexporting module with side effects', () => {
  expect(a6).toBe('a')
  expect(effects6).toEqual(['side-effect.js', 'side-effect2.js', 'index.js'])
})

import { a as a7 } from 'package-reexport-tla-side-effect'
import { effects as effects7 } from 'package-reexport-tla-side-effect/check-side-effect'
it('should run side effects of a reexporting module with side ef

ld run side effects of a reexporting module with side effects (async modules)', () => {
  expect(effects8).toEqual([])
  require('package-require-side-effect')
  expect(effects8).toEqual(['side-effect.js', 'side-effect2.js', 'index.js'])
})

import { a as

fects (async modules)', () => {
  expect(a7).toBe('a')
  expect(effects7).toEqual(['side-effect.js', 'side-effect2.js', 'index.js'])
})

import { effects as effects8 } from 'package-require-side-effect/check-side-effect'
it('shou


, c as c1 } from './side-effects/reexport-internal.js'

const cases = {
  'async module with side effects via dynamic import': () =>
    import('./side-effects/reexport-internal.js'),
  'async module with side effects via esm import': async () =>
    (await import('./side-effects/reexport-internal-test.js')).default,
  'async module with side effects via require': () =>
    require('./side-effects/reexport-internal.js'),
  'async module flagged side-effect-free via dynamic import': () =>
    import('./side-

quire': () =>
    require('./side-effect-free/reexport-internal.js'),
  'module with externals with side effects via dynamic import': () =>
    import('./side-effects/reexport-external.js'),
  'module with externals with side effects via esm import': async

effect-free/reexport-internal.js'),
  'async module flagged side-effect-free via esm import': async () =>
    (await import('./side-effect-free/reexport-internal-test.js')).default,
  'async module flagged side-effect-free via re


ort() doesn't care about whether a module is an async module or not
const UserApi = import('./UserAPI.js')

export const CreateUserAction = async (name) => {
  console.log('Creating user', name)
  // These are normal awaits, because they are in an async function
  const { createUser } = await UserApi
  return await createUser(name)
}

// You can place import() where you like
// Placing it at top-level will start loading and evaluating on
//   module evaluation.
//   see CreateUserAction above
//   Here: Con

  see AlternativeCreateUserAction below
//   Here: Connecting to the DB starts when AlternativeCreateUserAction
//         is called
export const AlternativeCreateUserAction = async (name) => {
  const { createUser } = await import('./UserAPI.js')
  return

necting to the DB starts when the application starts
// Placing it inside of an (async) function will start loading
//   and evaluating when the function is called for the first time
//   which basically makes it lazy-loaded.
//


ould handle bound function expressions', function (done) {
  require.ensure(
    [],
    function (require) {
      expect(this).toEqual({ test: true })
      require('./empty?test')
      expect(process.nextTick).toBeTypeOf('function') // check if injection still works
      require.ensure(
        [],
        function (require) {
          expect(this).toEqual({ test: true })
          done()
        }.bind(this)
      )
    }.bind({ test: true })
  )
})

it('should handle require.ensure without function

on () {
      expect(require('./empty?require.ensure:test')).toEqual({})
      return function f() {
        done()
      }
    })()
  )
})

it('should accept an already included module', function (done) {
  if (Math.random() < 0) require('./require.includ

expression', function (done) {
  function f() {
    done()
  }
  require.ensure([], f)
})

it("should parse expression in require.ensure, which isn't a function expression", function (done) {
  require.ensure(
    [],
    (functi


 sync = true
    load('one', 1, function () {
      expect(sync).toBe(false)
      load('three', 3, function () {
        var sync = true
        load('two', 2, function () {
          expect(sync).toBe(true)
          done()
        })
        Promise.resolve()
          .then(function () {})
          .then(function () {})
          .then(function () {
            sync = false
          })
      })
    })
    Promise.resolve().then(function () {
      sync = false
    })
  })
}

it('should be able to use

 load(name, expected, callback) {
    import('./dir/' + name)
      .then(function (result) {
        expect(result).toEqual(
          nsObj({
            default: expected,
          })
        )
        callback()
      })
      .catch(function (err) {

expressions in import', function (done) {
  function


nction (require) {
      require('./empty?a')
      require('./empty?b')
      testLoad()
      sync = true
      process.nextTick(function () {
        sync = false
      })
    },
    'named-chunk'
  )
  function testLoad() {
    require.ensure(
      [],
      function (require) {
        require('./empty?c')
        require('./empty?d')
        expect(sync).toBeTruthy()
        done()
      },
      'named-chunk'
    )
  }
})

it('should handle empty named chunks', function (done) {
  var sync = false

y-named-chunk'
  )
  sync = true
  setImmediate(function () {
    sync = false
  })
})

it('should handle named chunks when there is an error callback', function (done) {
  var sync = false
  require.ensure(
    [],
    function (require) {
      require('

 require.ensure(
    [],
    function (require) {
      expect(sync).toBeTruthy()
    },
    'empty-named-chunk'
  )
  require.ensure(
    [],
    function (require) {
      expect(sync).toBeTruthy()
      done()
    },
    'empt


t */
it('should handle duplicate chunks', function (done) {
  var firstOne = false,
    secondOne = false
  require.ensure([], function (require) {
    require('./acircular')
    require('./duplicate')
    require('./duplicate2')
    firstOne = true
    if (secondOne) done()
  })
  require.ensure([], function (require) {
    require('./acircular2')
    require('./duplicate')
    require('./duplicate2')
    secondOne = true
    if (firstOne) done()
  })
})

it('should not load a chunk which is included in a

done(e)
    }
  })
  Promise.resolve()
    .then(function () {})
    .then(function () {})
    .then(function () {
      asyncFlag = true
    })
  function loadChunk() {
    var sync = true
    require.ensure(['./empty?x', './empty?y'], function (require)

already loaded one', function (done) {
  var asyncFlag = false
  require.ensure(['./empty?x', './empty?y', './empty?z'], function (require) {
    try {
      expect(asyncFlag).toBe(true)
      loadChunk()
    } catch (e) {


ould not bundle context requires with asyncMode === 'weak'", function () {
  var contextRequire = require.context('.', false, /two/, 'weak')
  expect(function () {
    contextRequire('./two')
  }).toThrowError(/not available/)
})

it("should not bundle context requires with asyncMode === 'weak' using import.meta.webpackContext", function () {
  const contextRequire = import.meta.webpackContext('.', {
    recursive: false,
    regExp: /two/,
    mode: 'weak',
  })
  expect(function () {
    contextRequire('.

ree')).toBe(3)
  require('./three') // in a real app would be served as a separate chunk
})

it("should find module with asyncMode === 'weak' when required elsewhere (recursive)", function () {
  var contextRequire = require.context('.', true, /.+/, 'weak'

/two')
  }).toThrowError(/not available/)
})

it("should find module with asyncMode === 'weak' when required elsewhere", function () {
  var contextRequire = require.context('.', false, /.+/, 'weak')
  expect(contextRequire('./th


e able to use lazy-once mode', function () {
  function load(name) {
    return import(/* webpackMode: "lazy-once" */ './dir2/' + name)
  }
  return testChunkLoading(load, false, true)
})

it('should be able to use lazy-once mode with name', function () {
  function load(name) {
    return import(
      /* webpackMode: "lazy-once", webpackChunkName: "name-lazy-once" */ './dir3/' +
        name
    )
  }
  return testChunkLoading(load, false, true)
})

it('should be able to use lazy mode', function () {
  fu

urn import(
      /* webpackMode: "lazy", webpackChunkName: "name-lazy" */ './dir5/' + name
    )
  }
  return testChunkLoading(load, false, false)
})

it('should be able to use lazy mode with name and placeholder', function () {
  function load(name) {

nction load(name) {
    return import(/* webpackMode: "lazy" */ './dir4/' + name)
  }
  return testChunkLoading(load, false, false)
})

it('should be able to use lazy mode with name', function () {
  function load(name) {
    ret


ORT, EXPORT2, EXPORT3, EXPORT4, EXPORT5, EXPORT6 } from './inner'

export function f1() {
  // no using EXPORT
}

export function f2() {
  return EXPORT
}

function f3() {
  return EXPORT
}

const f4 = function () {
  return EXPORT
}

const f5 = () => {
  return EXPORT
}

let f6 = () => {
  return EXPORT
}

const f7 = () => {
  return EXPORT5()
}

const f8 = () => {
  return EXPORT6()
}

export function g2() {
  return f2()
}

export function g3() {
  return f3()
}

export var g4 = () => f4()

export let g5

 = () => {
  return f5()
}

function ga6() {
  return f6() || gb6()
}

function gb6() {
  return ga6()
}

export class g7 {
  static f() {
    return EXPORT
  }
}

export const pure1 = EXPORT
export const pure2 = /*#__PURE__*/ f6


sion,
  LogicalExpression,
} from './dep2?decl'
import {
  A3,
  B3,
  C3,
  D3,
  E3,
  F3,
  Pure3,
  ConditionalExpression3,
  LogicalExpression3,
} from './dep3?decl'

export class A1 extends A {
  render() {
    return new A2()
  }
}

export class B1 extends B {
  render() {
    return new B2()
  }
}

// prettier-ignore
export class C1 extends /*#__PURE__*/ getC() {
	render() {
		return new C2();
	}
}

// prettier-ignore
export class D1 extends /*@__PURE__*/ getD() {
	render() {
		return new D2();
	}
}

tic prop = 42
  static a = foo(this).prop
  static b = foo(Bar).prop
  static c = foo(super.Bar).prop
  static inStatic1
  static inStatic2
  static inStatic3
  static {
    this.inStatic1 = new Bar().prop
    this.inStatic2 = new super.Bar().prop
    this

export class E1 extends getE() {
  render() {
    return new E2()
  }
}

export class F1 extends getF() {
  render() {
    return new F2()
  }
}

function foo(instance) {
  return new instance()
}

class Bar extends Foo {
  sta


,
  B,
  DateFormatter,
  getC,
  getD,
  getE,
  getF,
  Pure,
  ConditionalExpression,
  LogicalExpression,
} from './dep2?expr'
import { A3, B3, C3, D3, E3, F3, Pure3 } from './dep3?expr'

export const A1 = class extends A {
  render() {
    return new A2()
  }
}

export const B1 = class extends B {
  render() {
    return new B2()
  }
}

// prettier-ignore
export const C1 = class extends /*#__PURE__*/ getC() {
	render() {
		return new C2();
	}
}

// prettier-ignore
export const D1 = class extends /*@__P

ExtendsPure = class extends Pure {
  render() {
    return new Pure3()
  }
}

export class DateBar extends DateFormatter {
  constructor() {
    super()
  }
  render() {}
}

export class ConditionalExpression1 extends ConditionalExpression {
  render() {

URE__*/ getD() {
	render() {
		return new D2();
	}
}

export const E1 = class extends getE() {
  render() {
    return new E2()
  }
}

export const F1 = class extends getF() {
  render() {
    return new F2()
  }
}

export const


 A {}
export class B {}
export const getC = () => class C {}
export const getD = () => class D {}
export const getE = () => class E {}
export const getF = () => class F {}
export class Foo {
  static Bar = Foo
}
export class Pure {}
export class DateFormatter extends Date {
  constructor() {
    super()
    this.date = this.getDate()
  }
}
export class ConditionalExpression extends (true ? A : B) {}
export class LogicalExpression extends (A || B) {}

export const exportsInfoForA = __webpack_exports_info__.A

 = __webpack_exports_info__.getE.used
export const exportsInfoForF = __webpack_exports_info__.getF.used
export const exportsInfoForFoo = __webpack_exports_info__.Foo.used
export const exportsInfoForPure = __webpack_exports_info__.Pure.used
export const exp

.used
export const exportsInfoForB = __webpack_exports_info__.B.used
export const exportsInfoForC = __webpack_exports_info__.getC.used
export const exportsInfoForD = __webpack_exports_info__.getD.used
export const exportsInfoForE


orB as declB,
  exportsInfoForC as declC,
  exportsInfoForD as declD,
  exportsInfoForE as declE,
  exportsInfoForF as declF,
  exportsInfoForFoo as declFoo,
  exportsInfoForPure as declPure,
  exportsInfoForDateFormatter as declDateFormatter,
  exportsInfoForConditionalExpression as declConditionalExpression,
  exportsInfoForLogicalExpression as declLogicalExpression,
} from './dep2?decl'
import {
  exportsInfoForA as exprA,
  exportsInfoForB as exprB,
  exportsInfoForC as exprC,
  exportsInfoForD as exprD

ogicalExpression as exprLogicalExpression,
} from './dep2?expr'

it('should load module correctly', () => {
  require('./module-decl')
  require('./module-expr')
})

it('A should be used', () => {
  expect(declA).toBe(true)
  expect(exprA).toBe(true)
})

i

,
  exportsInfoForE as exprE,
  exportsInfoForF as exprF,
  exportsInfoForPure as exprPure,
  exportsInfoForDateFormatter as exprDateFormatter,
  exportsInfoForConditionalExpression as exprConditionalExpression,
  exportsInfoForL


aaaaaaaaaaaaaaaaaaa',
  'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa


mport { used } from './json.js'
import { used as used2 } from './js.js'
import { used as used3 } from './cjs.js'

it('should tree shake all unused modules', () => {
  expect(used).toEqual({ used: true })
  expect(used2).toBe(true)
  expect(used3).toBe(true)

  const modules = Array.from(__turbopack_modules__.keys())
  expect(modules).toContainEqual(expect.stringMatching(/input\/json\.js/))
  expect(modules).toContainEqual(expect.stringMatching(/input\/used\.json/))
  expect(modules).not.toContainEqual(

qual(expect.stringMatching(/input\/unused\.js/))
  expect(modules).toContainEqual(expect.stringMatching(/input\/cjs\.js/))
  expect(modules).toContainEqual(expect.stringMatching(/input\/used\.cjs/))
  expect(modules).not.toContainEqual(
    expect.stringMa

expect.stringMatching(/input\/unused\.json/)
  )
  expect(modules).toContainEqual(expect.stringMatching(/input\/js\.js/))
  expect(modules).toContainEqual(expect.stringMatching(/input\/used\.js/))
  expect(modules).not.toContainE


e('node:worker_threads')
const path = require('path')

if (isMainThread) {
  it('should run a worker thread with separate file', async () => {
    const worker = new Worker(path.join(__dirname, 'worker.js'))

    const message = await new Promise((resolve, reject) => {
      worker.on('message', resolve)
      worker.on('error', reject)
      worker.on('exit', (code) => {
        if (code !== 0) {
          reject(new Error(`Worker stopped with exit code ${code}`))
        }
      })

      worker.postMessa

ge('ping')
    })

    expect(message).toBe('pong')
    await worker.terminate()
  })

  it('should handle self-referencing worker (__filename)', async () => {
    const worker = new Worker(__filename)

    const message = await


Cjs, loadInvalidEsm } from 'esm-package'
import { auto, autoPlain } from 'auto-package'

it('should have the commonjs module as default export in specified ESM', () => {
  expect(esm).toMatchObject({
    __esModule: true,
    named: 'named',
  })
  expect(esmPlain).toMatchObject({
    named: 'named',
  })
})

it('should not have the commonjs module as default export in specified ESM', () => {
  expect(auto).toMatchObject({
    __esModule: true,
    named: 'named',
  })
  expect(autoPlain).toMatchObject({

lid esm exports', async () => {
  let value = await loadInvalidEsm()
  expect(value).toMatchObject({
    __esModule: true,
  })
})

it('should error for invalid cjs exports', async () => {
  let value = await loadInvalidCjs()
  expect(value).toMatchObject(

  named: 'named',
  })
})

it('should error for inva


 work correctly
// This ensures conditional guards are preserved and don't get optimized away incorrectly

let initPromise = null
let callCount = 0

async function doInit() {
  callCount++
}

function initAsync() {
  if (!initPromise) {
    initPromise = doInit()
  }
  return initPromise
}

it('should only initialize once when called multiple times', async () => {
  // Reset state
  initPromise = null
  callCount = 0

  // Call multiple times
  const promise1 = initAsync()
  const promise2 = initAsync()
  c

the same promise instance
  expect(promise1).toBe(promise2)
  expect(promise2).toBe(promise3)

  // Wait for all to resolve
  await Promise.all([promise1, promise2, promise3])

  // Should have only called the expensive init once
  expect(callCount).toBe(1

onst promise3 = initAsync()

  // All should return


andle right shift assignment in conditional for number', () => {
  let value = 16
  let entered = false
  if ((value >>= 2)) {
    entered = true
  }
  expect(value).toBe(4)
  expect(entered).toBe(true)
})

it('should handle right shift assignment in conditional for bigint', () => {
  let value = 16n
  let entered = false
  if ((value >>= 2n)) {
    entered = true
  }
  expect(value).toBe(4n)
  expect(entered).toBe(true)
})

it('should handle left shift assignment in conditional for number', () => {
  let v

lue = 16
  let entered = false
  if ((value >>>= 2)) {
    entered = true
  }
  expect(value).toBe(4)
  expect(entered).toBe(true)
})

it('should handle bitwise OR assignment in conditional', () => {
  let value = 0
  let entered = false
  if ((value |= 5)

alue = 3
  let entered = false
  if ((value <<= 2)) {
    entered = true
  }
  expect(value).toBe(12)
  expect(entered).toBe(true)
})

it('should handle unsigned right shift assignment in conditional for number', () => {
  let va


lThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_import-meta_esm_input_0m4yc4r._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm/input/mod.mjs [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";

__turbopack_context__.s([]);
var __TURBOPACK__import$2e$meta__ = {
    get url () {
        return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm/input/mod.mjs")

;
    }
};
console.log(__TURBOPACK__import$2e$meta__.url);
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";

__turbopa


"TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_import-meta_esm-multiple_input_0__oir9._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-multiple/input/mod.mjs [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";

__turbopack_context__.s([]);
var __TURBOPACK__import$2e$meta__ = {
    get url () {
        return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-multiple

s/tests/snapshot/import-meta/esm-multiple/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";

__turbopack_context__.s([]);
var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$

/input/mod.mjs");
    }
};
function foo() {
    console.log(__TURBOPACK__import$2e$meta__.url);
}
function bar() {
    console.log(__TURBOPACK__import$2e$meta__.url);
}
foo();
bar();
}),
"[project]/turbopack/crates/turbopack-test


|| (globalThis["TURBOPACK"] = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_import-meta_url_input_0jbqiqv._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url/input/asset.txt (static in ecmascript)", ((__turbopack_context__) => {

__turbopack_context__.q("/static/asset.1z1abqqd69ldl.txt");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url/input/mod.mjs [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";

__turbopack_

opack_context__.U(__turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url/input/asset.txt (static in ecmascript)"));
console.log(assetUrl);
fetch(assetUrl).then((res)=>res.text()).then(console.log);
}),
"[project]

context__.s([]);
var __TURBOPACK__import$2e$meta__ = {
    get url () {
        return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/url/input/mod.mjs");
    }
};
const assetUrl = new __turb


r hmr support
            module = createModuleWithDirection(id);
        } else {
            module = createModuleObject(id);
        }
        moduleCache[id] = module;
    }
    return module;
}
/**
 * Creates the module object. Only done here to ensure all module objects have the same shape.
 */ function createModuleObject(id) {
    return {
        exports: {},
        error: undefined,
        id,
        namespaceObject: undefined
    };
}
function createModuleWithDirection(id) {
    return {

sm(exports, bindings) {
    defineProp(exports, '__esModule', {
        value: true
    });
    if (toStringTag) defineProp(exports, toStringTag, {
        value: 'Module'
    });
    let i = 0;
    while(i < bindings.length){
        const propName = bind

  exports: {},
        error: undefined,
        id,
        namespaceObject: undefined,
        parents: [],
        children: []
    };
}
const BindingTag_Value = 0;
/**
 * Adds the getters to the exports object.
 */ function e


|| (globalThis["TURBOPACK"] = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_basic_input_0z18is9._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js (static in ecmascript)", ((__turbopack_context__) => {

__turbopack_context__.q("/static/worker.2-qnq-strt8dn.js");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => {

__turbopack_con

ut_worker_11ygioo.js","output/1i9t_crates_turbopack-tests_tests_snapshot_workers_basic_input_worker_0yr5fg0.js"], opts);
});
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/basic/input/index.js [test] (ecmascript)", ((__turbopack_con

text__.v(function(Ctor, opts) {
    return __turbopack_context__.b(Ctor, "output/0uxq_crates_turbopack-tests_tests_snapshot_workers_basic_output_0uy0mni._.js", ["output/1do3_crates_turbopack-tests_tests_snapshot_workers_basic_inp


{
function abort(message) {
    console.error(message);
    throw new Error(message);
}
if (
    typeof self["WorkerGlobalScope"] === "undefined" ||
    !(self instanceof self["WorkerGlobalScope"])
) {
    abort("Worker entrypoint must be loaded in a worker context");
}

// Try querystring first (SharedWorker), then hash (regular Worker)
var url = new URL(location.href);
var paramsString = url.searchParams.get("params");
if (!paramsString && url.hash.startsWith("#params=")) {
    paramsString = decodeURICom

 Array.isArray(params[0]) ? params[0] : [];

Object.assign(self, {
    TURBOPACK_NEXT_CHUNK_URLS: chunkUrls,
    TURBOPACK_ASSET_SUFFIX: param(1)
});

if (chunkUrls.length > 0) {
    var scriptsToLoad = [];
    for (var i = 0; i < chunkUrls.length; i++) {

ponent(url.hash.slice("#params=".length));
}

if (!paramsString) abort("Missing worker bootstrap config");

var params = JSON.parse(paramsString);
var param = (n) => typeof params[n] === 'string' ? params[n] : '';
var chunkUrls =


|| (globalThis["TURBOPACK"] = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_workers_shared_input_0g-vw3t._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js (static in ecmascript)", ((__turbopack_context__) => {

__turbopack_context__.q("/static/worker.1n36e5vaxakik.js");}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/worker.js [test] (ecmascript, worker loader)", ((__turbopack_context__) => {

__turbopack_

d_input_worker_1u1i0a1.js","output/1i9t_crates_turbopack-tests_tests_snapshot_workers_shared_input_worker_1xw116u.js"], opts);
});
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/workers/shared/input/index.js [test] (ecmascript)", ((__turbop

context__.v(function(Ctor, opts) {
    return __turbopack_context__.b(Ctor, "output/0uxq_crates_turbopack-tests_tests_snapshot_workers_shared_output_0uy0mni._.js", ["output/1do3_crates_turbopack-tests_tests_snapshot_workers_share


ction toFixed(value, maxDecimals, roundingFunction, optionals) {
  var splitValue = value.toString().split('.'),
    minDecimals = maxDecimals - (optionals || 0),
    optionalsRegExp,
    power,
    output
  var boundedPrecisions
  // var unused = 'xxxx';
  // Use the smallest precision value possible to avoid errors from floating point representation
  if (splitValue.length === 2) {
    boundedPrecisions = Math.min(
      Math.max(splitValue[1].length, minDecimals),
      maxDecimals
    )
  } else {
    b

power).toFixed(
    boundedPrecisions
  )
  if (optionals > maxDecimals - boundedPrecisions) {
    optionalsRegExp = new RegExp(
      '\\.?0{1,' + (optionals - (maxDecimals - boundedPrecisions)) + '}$'
    )
    output = output.replace(optionalsRegExp, ''

oundedPrecisions = minDecimals
  }
  power = Math.pow(10, boundedPrecisions)
  // Multiply up by precision, round accurately, then divide and use native toFixed():
  output = (roundingFunction(value + 'e+' + boundedPrecisions) /


llowing tests would fail if they require("fail")
  expect(() => {
    require('./not-existing-file')
  }).toThrow()
})

function maybeReturn(x) {
  if (x) {
    return true
  }
}

function func() {
  if (false) {
    require('fail')
    import('fail')
  }
  if (true) {
    require('./ok')
  }
  if (true) {
    require('./ok')
  } else {
    require('fail')
    import('fail')
  }
  if (false) {
    require('fail')
    import('fail')
  } else {
    require('./ok')
  }
}

it('should not follow conditional refe

quire('./ok') : require('fail')
  true ? require('./ok') : (require('fail'), import('fail'))
  true
    ? require('./ok')
    : (() => {
        require('fail')
        import('fail')
      })()
  const value = false
    ? (() => {
        require('fail')

rences', () => {
  func()

  expect(func.toString()).not.toContain('import(')
})

function funcTenary() {
  false ? require('fail') : undefined
  false ? import('fail') : undefined
  true ? require('./ok') : undefined
  true ? re


] = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_export-alls_cjs-2_input_212xd9j._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/export-alls/cjs-2/input/commonjs.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => {

// commonjs.js
exports.hello = 'World';
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/export-alls/cjs-2/input/c.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";

__turbopack_context__.s([]);
// c.js
v

_.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/export-alls/cjs-2/input/commonjs.js [test] (ecmascript)"); // This would be handled by existing logic
__turbopack_context__.j(__TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates


"TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_import-meta_esm-object_input_0akuaiy._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-object/input/mod.mjs [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";

__turbopack_context__.s([]);
var __TURBOPACK__import$2e$meta__ = {
    get url () {
        return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-object/input

/mod.mjs");
    }
};
console.log(__TURBOPACK__import$2e$meta__);
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-object/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict


 for hmr support
            module = createModuleWithDirection(id);
        } else {
            module = createModuleObject(id);
        }
        moduleCache[id] = module;
    }
    return module;
}
/**
 * Creates the module object. Only done here to ensure all module objects have the same shape.
 */ function createModuleObject(id) {
    return {
        exports: {},
        error: undefined,
        id,
        namespaceObject: undefined
    };
}
function createModuleWithDirection(id) {
    return {

n esm(exports, bindings) {
    defineProp(exports, '__esModule', {
        value: true
    });
    if (toStringTag) defineProp(exports, toStringTag, {
        value: 'Module'
    });
    let i = 0;
    while(i < bindings.length){
        const propName = b

     exports: {},
        error: undefined,
        id,
        namespaceObject: undefined,
        parents: [],
        children: []
    };
}
const BindingTag_Value = 0;
/**
 * Adds the getters to the exports object.
 */ functio


aaaaaaaaaaaaaaaaaaa',
  'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa


 await import('./modules/all')
  expect(lib.cat).toBe('cat')
  expect(lib.exportsInfo.cat.used).toBe(true)
  expect(lib.exportsInfo.dog.used).toBe(true)
})

it('should tree-shake unused exports with const destructured dynamic import', async () => {
  const { cat, exportsInfo } = await import('./modules/const')
  expect(cat).toBe('cat')
  expect(exportsInfo.cat.used).toBe(true)
  expect(exportsInfo.dog.used).toBe(false)
})

it('should tree-shake unused exports with let destructured dynamic import', async ()

ructured dynamic import', async () => {
  var { cat, exportsInfo } = await import('./modules/var')
  expect(cat).toBe('cat')
  expect(exportsInfo.cat.used).toBe(true)
  expect(exportsInfo.dog.used).toBe(false)
})

it('should tree-shake all exports with emp

=> {
  let { cat, exportsInfo } = await import('./modules/let')
  expect(cat).toBe('cat')
  expect(exportsInfo.cat.used).toBe(true)
  expect(exportsInfo.dog.used).toBe(false)
})

it('should tree-shake unused exports with var dest


"TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_import-meta_esm-mutable_input_20u-wgb._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-mutable/input/mod.mjs [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";

__turbopack_context__.s([]);
var __TURBOPACK__import$2e$meta__ = {
    get url () {
        return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-mutable/in

put/mod.mjs");
    }
};
__TURBOPACK__import$2e$meta__.foo = 1;
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/esm-mutable/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict"


es for hmr support
            module = createModuleWithDirection(id);
        } else {
            module = createModuleObject(id);
        }
        moduleCache[id] = module;
    }
    return module;
}
/**
 * Creates the module object. Only done here to ensure all module objects have the same shape.
 */ function createModuleObject(id) {
    return {
        exports: {},
        error: undefined,
        id,
        namespaceObject: undefined
    };
}
function createModuleWithDirection(id) {
    return {

ion esm(exports, bindings) {
    defineProp(exports, '__esModule', {
        value: true
    });
    if (toStringTag) defineProp(exports, toStringTag, {
        value: 'Module'
    });
    let i = 0;
    while(i < bindings.length){
        const propName =

       exports: {},
        error: undefined,
        id,
        namespaceObject: undefined,
        parents: [],
        children: []
    };
}
const BindingTag_Value = 0;
/**
 * Adds the getters to the exports object.
 */ funct


r function declaration', () => {
  function withDefault(value = this.prop) {
    return value
  }

  const obj = { prop: 42 }
  expect(withDefault.call(obj)).toBe(42)
})

it('should handle this in default parameters for function expression', () => {
  const funcExpr = function (value = this.prop) {
    return value
  }

  const obj = { prop: 55 }
  expect(funcExpr.call(obj)).toBe(55)
})

it('should handle this in default parameters for arrow function', () => {
  const obj = {
    prop: 77,
    test() {

eturn arrow()
    },
  }
  expect(obj.test()).toBe(77)
})

it('should handle this in default parameters for object method', () => {
  const obj = {
    prop: 100,
    method(value = this.prop) {
      return value
    },
  }
  expect(obj.method()).toBe(100

  const arrow = (value = this.prop) => value
      r


lThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/turbopack_crates_turbopack-tests_tests_snapshot_import-meta_cjs_input_1uw7l3k._.js",
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/cjs/input/mod.cjs [test] (ecmascript)", ((__turbopack_context__, module, exports) => {

var __TURBOPACK__import$2e$meta__ = {
    get url () {
        return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/import-meta/cjs/input/mod.cjs");
    }
};
console.log(__T

URBOPACK__import$2e$meta__.url);
}),
"[project]/turbopack/crates/turbopack-tests/tests/snapshot/import-meta/cjs/input/index.js [test] (ecmascript)", ((__turbopack_context__) => {
"use strict";

__turbopack_context__.s([]);
var __


for hmr support
            module = createModuleWithDirection(id);
        } else {
            module = createModuleObject(id);
        }
        moduleCache[id] = module;
    }
    return module;
}
/**
 * Creates the module object. Only done here to ensure all module objects have the same shape.
 */ function createModuleObject(id) {
    return {
        exports: {},
        error: undefined,
        id,
        namespaceObject: undefined
    };
}
function createModuleWithDirection(id) {
    return {

 esm(exports, bindings) {
    defineProp(exports, '__esModule', {
        value: true
    });
    if (toStringTag) defineProp(exports, toStringTag, {
        value: 'Module'
    });
    let i = 0;
    while(i < bindings.length){
        const propName = bi

    exports: {},
        error: undefined,
        id,
        namespaceObject: undefined,
        parents: [],
        children: []
    };
}
const BindingTag_Value = 0;
/**
 * Adds the getters to the exports object.
 */ function


lob/canary/packages/next/src/client/dev/error-overlay/websocket.ts

import type { HmrMessage } from '@vercel/turbopack-ecmascript-runtime/browser/dev/hmr-client/hmr-client'

let source: WebSocket
const messageCallbacks: ((message: HmrMessage) => void)[] = []

// TODO: add timeout again
// let lastActivity = Date.now()

function getSocketProtocol(assetPrefix: string): string {
  let protocol = location.protocol

  try {
    // assetPrefix is a url
    protocol = new URL(assetPrefix).protocol
  } catch (_) {}

!== source.OPEN) return
  return source.send(data)
}

export type HMROptions = {
  path: string
  assetPrefix: string
  timeout?: number
  log?: boolean
}

// This is not used by Next.js, but it is used by the standalone turbopack-cli
export function conne

  return protocol === 'http:' ? 'ws' : 'wss'
}

export function addMessageListener(cb: (message: HmrMessage) => void) {
  messageCallbacks.push(cb)
}

export function sendMessage(data: any) {
  if (!source || source.readyState


)
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')

const WORKING_PATH = '/root/actions-runner/_work/next.js/next.js/'

const INITIALIZING_TEST_CASES = [
  'compile successfully',
  'should build successfully',
]

// please make sure this is sorted alphabetically when making changes.
const SKIPPED_TEST_SUITES = {}

const { argv } = yargs(hideBin(process.argv))
  .choices('bundler', ['turbopack', 'rspack'])
  .describe('bundler', 'The JavaScript bundler the tests were run aga

  .default('branch', 'canary')
  .boolean('override')
  .describe(
    'override',
    "Don't merge with existing test results, allowing tests to transition to " +
      'a failed state'
  )

const manifestJsonPath = `${__dirname}/${argv.bundler}-${argv.te

inst')
  .choices('test-suite', ['dev', 'build'])
  .describe('test-suite', 'Test group to update')
  .demandOption(['bundler', 'test-suite'])
  .string('branch')
  .describe('branch', 'the git branch to filter CI artifacts to')


rs'

interface TestResponse {
  appDir: string
  type: 'e2e' | 'production' | 'development' | 'unit'
  name: string
}

interface ErrorResponse {
  name: string
  title: string
  why: string
  fix: string
}

function validateNonEmptyString(field: string) {
  return function (value: string) {
    if (/.+/.test(value)) {
      return true
    }
    return `${field} is required`
  }
}

export default function generator(plop: NodePlopAPI): void {
  // make our custom helpers available for use in templates as han

y?',
        default: true,
      },
      {
        type: 'input',
        name: 'name',
        message: 'Test name',
        validate: validateNonEmptyString('test name'),
      },
      {
        type: 'list',
        name: 'type',
        message: 'Te

dlebars helpers
  helpers.init(plop)

  plop.setGenerator('test', {
    description: 'Create a new test',
    prompts: [
      {
        type: 'confirm',
        name: 'appDir',
        message: 'Is this test for the app director


{}
export class B {}
export class C {}
export class Y {}
export class Z {}
export function mixin1(_class) {
  return _class
}
export function mixin2(_class) {
  return _class
}
export function mixin3(_class) {
  return _class
}
export function mixin4(_class) {
  return _class
}
export function mixin5(_class) {
  return _class
}
export function getField() {
  return 'test'
}
export class BaseError extends Error {}
export class BaseError1 extends Error {}
export class BaseError2 extends Error {}
export class

bpack_exports_info__.B.used
export const exportsInfoForC = __webpack_exports_info__.C.used
export const exportsInfoForY = __webpack_exports_info__.Y.used
export const exportsInfoForZ = __webpack_exports_info__.Z.used
export const exportsInfoForW = __webpac

BaseError3 extends Error {}
export class W {}
export class J {}
export class K {}
var SuperClass = class {}
export { SuperClass }

export const exportsInfoForA = __webpack_exports_info__.A.used
export const exportsInfoForB = __we


A,
  exportsInfoForB,
  exportsInfoForC,
  exportsInfoForY,
  exportsInfoForZ,
  exportsInfoForW,
  exportsInfoForJ,
  exportsInfoForK,
  exportsInfoForMixin1,
  exportsInfoForMixin2,
  exportsInfoForMixin3,
  exportsInfoForMixin4,
  exportsInfoForMixin5,
  exportsInfoForBaseError,
  exportsInfoForBaseError1,
  exportsInfoForBaseError2,
  exportsInfoForBaseError3,
  exportsInfoForSuperClass,
} from './dep2'

it('should load modules correctly', () => {
  require('./module1')
  require('./module2')
  require(

sed', () => {
    expect(exportsInfoForJ).toBe(false)
    expect(exportsInfoForW).toBe(false)
  })

  it('Keep extends with constructor', () => {
    expect(exportsInfoForBaseError).toBe(true)
    expect(exportsInfoForBaseError1).toBe(true)
    expect(expo

'./module3')
  require('./module4')
  require('./module5')
  require('./module6')
  require('./module7')
  require('./module8')
  require('./module9')
})

if (process.env.NODE_ENV === 'production') {
  it('W and J should not be u


import { Block, Inline, Document } from './some-module'

function getType(obj) {
  return obj.type
}

// Local functions
function doSomethingWithBlock(obj) {
  return Block.doSomething(obj)
}

function doSomethingWithInline(obj) {
  return Inline.doSomething(obj)
}

function doSomethingWithDocument(obj) {
  return Document.doSomething(obj)
}

// Exported functions
function doSomething(obj) {
  const type = getType(obj)

  switch (type) {
    case 'document':
      return doSomethingWithDocument(obj)
    cas

   return doSomethingWithBlock(obj)
    case 'inline':
      return doSomethingWithInline(obj)
    default:
      throw new Error()
  }
}

function useDocument(obj) {
  return doSomethingWithDocument(obj)
}

export { useDocument }
export default doSomethin


*
 * Production Node.js runtime.
 * Uses ModuleWithDirection and simple module instantiation without HMR support.
 */

// moduleCache and moduleFactories are declared in runtime-base.ts

// this is read in runtime-utils.ts so it creates a module with direction for hmr
createModuleWithDirectionFlag = true

interface TurbopackNodeBuildContext
  extends TurbopackBaseContext<ModuleWithDirection> {
  R: ResolvePathFromModule
  x: ExternalRequire
  y: ExternalImport
  C: typeof clearChunkCache
}

const nodeContex

leCache as ModuleCache<ModuleWithDirection>
nodeContextPrototype.R = resolvePathFromModule
nodeContextPrototype.b = createWorker
nodeContextPrototype.C = clearChunkCache

function instantiateModule(
  id: ModuleId,
  sourceType: SourceType,
  sourceData: S

tPrototype = Context.prototype as TurbopackNodeBuildContext

nodeContextPrototype.q = exportUrl
nodeContextPrototype.M = moduleFactories
// Cast moduleCache to ModuleWithDirection for production mode
nodeContextPrototype.c = modu


 <reference path="../../shared/runtime/dev-extensions.ts" />
/// <reference path="../../shared/runtime/hmr-runtime.ts" />

/**
 * Development Node.js runtime.
 * Uses HotModule and shared HMR logic for hot module replacement support.
 */

// Cast the module cache to HotModule for development mode
// (hmr-runtime.ts declares devModuleCache as `let` variable expecting assignment)
// This is safe because HotModule extends Module
devModuleCache = moduleCache as ModuleCache<HotModule>

// this is read in runtime

_turbopack_runtime_modules__

interface TurbopackNodeDevBuildContext extends TurbopackBaseContext<HotModule> {
  R: ResolvePathFromModule
  x: ExternalRequire
  y: ExternalImport
  C: typeof clearChunkCache
}

const nodeDevContextPrototype =
  Context.prot

-utils.ts so it creates a module with direction for hmr
createModuleWithDirectionFlag = true

if (!globalThis.__turbopack_runtime_modules__) {
  globalThis.__turbopack_runtime_modules__ = new Set()
}
runtimeModules = globalThis._


/>

/**
 * Note: hmr-runtime.ts is embedded before this file, so its functions
 * (initializeServerHmr, emitMessage) are available in the same scope.
 */

// Initialize server HMR client (connects to shared HMR infrastructure)
let hmrClientInitialized = false
function ensureHmrClientInitialized() {
  if (hmrClientInitialized) return
  hmrClientInitialized = true

  // initializeServerHmr is from hmr-client.ts (embedded before this file)
  // moduleFactories is from dev-runtime.ts
  // devModuleCache is the

tMessage returns false if any listener failed to apply the update
    return emitMessage({
      type: 'turbopack-message',
      data: update,
    })
  } catch (err) {
    console.error('[Server HMR] Failed to apply update:', err)
    return false
  }
}

HotModule-typed cache from dev-runtime.ts
  initializeServerHmr(moduleFactories, devModuleCache)
}

function __turbopack_server_hmr_apply__(update: NodeJsHmrPayload): boolean {
  try {
    ensureHmrClientInitialized()

    // emi


>

/**
 * Extensions to the shared runtime types that are specific to the development
 * runtime (e.g. `module.hot`).
 */

declare const enum HotUpdateStatus {
  idle = 'idle',
}

type HotUpdateStatusHandler = (status: HotUpdateStatus) => void

interface HotData {
  prevExports?: Exports
}

// Used through reference comments
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface HotState {
  selfAccepted: boolean | Function
  selfDeclined: boolean
  selfInvalidated: boolean
  disposeHandler

e AcceptErrorHandler = (
  err: Error,
  context: { moduleId: ModuleId; dependencyId: ModuleId }
) => void
type AcceptCallback = (outdatedDependencies: ModuleId[]) => void

interface AcceptFunction {
  // accept updates for self
  (errorHandler?: AcceptErr

s: ((data: object) => void)[]
  acceptedDependencies: Record<ModuleId, AcceptCallback | (() => void)>
  acceptedErrorHandlers: Record<ModuleId, AcceptErrorHandler | undefined>
  declinedDependencies: Record<ModuleId, true>
}

typ


instantiated as part of the runtime of a chunk.
 */
let runtimeModules: Set<ModuleId>

/**
 * Maps module IDs to persisted data between executions of their hot module
 * implementation (`hot.data`).
 */
const moduleHotData: Map<ModuleId, HotData> = new Map()

/**
 * Maps module instances to their hot module state.
 * Uses WeakMap so it works with both HotModule and ModuleWithDirection.
 */
const moduleHotState: WeakMap<any, HotState> = new WeakMap()

/**
 * Modules that call `module.hot.invalidate()` (while

duleId[]) {
    super(message)
    this.dependencyChain = dependencyChain
  }
}

type ModuleEffect =
  | {
      type: 'unaccepted'
      dependencyChain: ModuleId[]
    }
  | {
      type: 'self-declined'
      dependencyChain: ModuleId[]
      moduleId:

 being updated).
 */
const queuedInvalidatedModules: Set<ModuleId> = new Set()

class UpdateApplyError extends Error {
  name = 'UpdateApplyError'

  dependencyChain: ModuleId[]

  constructor(message: string, dependencyChain: Mo


*
 * It is separate from `runtime-utils.ts` because it can be used outside of
 * runtime code, hence it should not contain any function declarations that are
 * specific to the runtime context.
 */

type CurrentScript = { src: ChunkUrl | null }
type ChunkListPath = string & { readonly brand: unique symbol }
type ChunkListScript = CurrentScript & { readonly brand: unique symbol }
/**
 * The path of a chunk (an internal identifier used by Turbopack for tracking chunk loading), i.e.
 * excluding CHUNK_BASE_PAT

l be requested from the server), i.e. including CHUNK_BASE_PATH and
 * CHUNK_SUFFIX), e.g. `/_next/static/chunks/21a106126841c540.js?dpl=1123123`
 */
type ChunkUrl = string & { readonly brand: unique symbol }
/** The dependency specifier when importing ext

H and CHUNK_SUFFIX, e.g. `static/chunks/21a106126841c540.js`
 */
type ChunkPath = string & { readonly brand: unique symbol }
type ChunkScript = CurrentScript & { readonly brand: unique symbol }
/**
 * The URL of a chunk (what wil


ript-eslint/no-unused-vars */

declare var RUNTIME_PUBLIC_PATH: string
declare var RELATIVE_ROOT_PATH: string
declare var ASSET_PREFIX: string

const path = require('path')

const relativePathToRuntimeRoot = path.relative(RUNTIME_PUBLIC_PATH, '.')
// Compute the relative path to the `distDir`.
const relativePathToDistRoot = path.join(
  relativePathToRuntimeRoot,
  RELATIVE_ROOT_PATH
)
const RUNTIME_ROOT = path.resolve(__filename, relativePathToRuntimeRoot)
// Compute the absolute path to the root, by strip

 a file or a directory.
 *
 * This fn allows to calculate an absolute path for some global static values, such as
 * `__dirname` or `import.meta.url` that Turbopack will not embeds in compile time.
 * See ImportMetaBinding::code_generation for the usage.

ping distDir from the absolute path to this file.
const ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot)

/**
 * Returns an absolute path to the given module path.
 * Module path should be relative, either path to


* eslint-disable @typescript-eslint/no-unused-vars */

/// <reference path="../shared/runtime/runtime-utils.ts" />

function readWebAssemblyAsResponse(path: string) {
  const { createReadStream } = require('fs') as typeof import('fs')
  const { Readable } = require('stream') as typeof import('stream')

  const stream = createReadStream(path)

  // @ts-ignore unfortunately there's a slight type mismatch with the stream.
  return new Response(Readable.toWeb(stream), {
    headers: {
      'content-type': 'app

async function instantiateWebAssemblyFromPath(
  path: string,
  importsObj: WebAssembly.Imports
): Promise<Exports> {
  const response = readWebAssemblyAsResponse(path)

  const { instance } = await WebAssembly.instantiateStreaming(
    response,
    im

lication/wasm',
    },
  })
}

async function compileWebAssemblyFromPath(
  path: string
): Promise<WebAssembly.Module> {
  const response = readWebAssemblyAsResponse(path)

  return await WebAssembly.compileStreaming(response)
}


rection
createModuleWithDirectionFlag = true

// This file must not use `import` and `export` statements. Otherwise, it
// becomes impossible to augment interfaces declared in `<reference>`d files
// (e.g. `Module`). Hence, the need for `import()` here.
type RefreshRuntimeGlobals =
  import('@next/react-refresh-utils/dist/runtime').RefreshRuntimeGlobals

declare var $RefreshHelpers$: RefreshRuntimeGlobals['$RefreshHelpers$']
declare var $RefreshReg$: RefreshRuntimeGlobals['$RefreshReg$']
declare var $Refres

ignature: RefreshRuntimeGlobals['$RefreshSig$']
  registerExports: typeof registerExportsAndSetupBoundaryForReactRefresh
}

type RefreshHelpers = RefreshRuntimeGlobals['$RefreshHelpers$']

type ModuleFactory = (
  this: Module['exports'],
  context: Turbop

hSig$: RefreshRuntimeGlobals['$RefreshSig$']
declare var $RefreshInterceptModuleExecution$: RefreshRuntimeGlobals['$RefreshInterceptModuleExecution$']

type RefreshContext = {
  register: RefreshRuntimeGlobals['$RefreshReg$']
  s


pt-eslint/no-unused-vars */

/// <reference path="../base/runtime-base.ts" />
/// <reference path="../base/dev-base.ts" />
/// <reference path="./runtime-backend-dom.ts" />
/// <reference path="../../../shared/require-type.d.ts" />

let DEV_BACKEND: DevRuntimeBackend
;(() => {
  DEV_BACKEND = {
    unloadChunk(chunkUrl) {
      deleteResolver(chunkUrl)

      // Strip query string so we match links regardless of cache-busting
      // params (e.g. ?ts=) that may differ between HMR updates.
      const baseC

 document.querySelectorAll(
          `link[href="${baseChunkUrl}"],link[href^="${baseChunkUrl}?"],link[href="${decodedBaseChunkUrl}"],link[href^="${decodedBaseChunkUrl}?"]`
        )
        for (const link of Array.from(links)) {
          link.remove()

hunkUrl = chunkUrl.split('?')[0]
      // TODO(PACK-2140): remove this once all filenames are guaranteed to be escaped.
      const decodedBaseChunkUrl = decodeURI(baseChunkUrl)

      if (isCss(chunkUrl)) {
        const links =


/// <reference path="../../../browser/runtime/base/runtime-base.ts" />
/// <reference path="../../../shared/runtime/runtime-types.d.ts" />

function getAssetSuffixFromScriptSrc() {
  // TURBOPACK_ASSET_SUFFIX is set in web workers
  if (self.TURBOPACK_ASSET_SUFFIX != null) return self.TURBOPACK_ASSET_SUFFIX
  const src = document?.currentScript?.getAttribute?.('src') ?? ''
  const qi = src.indexOf('?')
  return qi >= 0 ? src.slice(qi) : ''
}

type ChunkResolver = {
  resolved: boolean
  loadingStarted: bo

 new Map()

;(() => {
  BACKEND = {
    async registerChunk(chunk, params) {
      let chunkPath = getPathFromScript(chunk)
      let chunkUrl = getUrlFromScript(chunk)

      const resolver = getOrCreateResolver(chunkUrl)
      resolver.resolve()

      i

olean
  resolve: () => void
  reject: (error?: Error) => void
  promise: Promise<any>
}

let BACKEND: RuntimeBackend

/**
 * Maps chunk paths to the corresponding resolver.
 */
const chunkResolvers: Map<ChunkUrl, ChunkResolver> =


) {
  return manifests.reduce((mergedManifest, manifest) => {
    if (!mergedManifest) {
      return structuredClone(manifest)
    }

    if (manifest.version === 2) {
      for (const suite in manifest.suites) {
        if (mergedManifest.suites[suite]) {
          const mergedSuite = mergedManifest.suites[suite]
          const currentSuite = manifest.suites[suite]
          mergedSuite.failed = [
            ...(mergedSuite.failed || []),
            ...(currentSuite.failed || []),
          ]

}
      }
      mergedManifest.rules.include.push(...(manifest.rules.include || []))
      mergedManifest.rules.exclude.push(...(manifest.rules.exclude || []))
      return mergedManifest
    }

    throw new Error(`Merging manifests is only supported for

 mergedSuite.flakey = [
            ...(mergedSuite.flakey || []),
            ...(currentSuite.flakey || []),
          ]
        } else {
          mergedManifest.suites[suite] = structuredClone(manifest.suites[suite])


ormalize line endings (fixes Windows CRLF issues)
// The issue: jscodeshift's printer (recast) outputs CRLF on Windows, but test fixtures use LF
// We need to patch both defineTest (which uses internal closure references) and runInlineTest
if (process.platform === 'win32') {
  try {
    const testUtils = require('jscodeshift/dist/testUtils')
    const fs = require('fs')
    const path = require('path')

    // Helper to normalize line endings
    // - Convert CRLF to LF
    // - Remove trailing whitespace f

: string) =>
      str
        .replace(/\r\n/g, '\n')
        .replace(/[ \t]+$/gm, '')
        .replace(/\n*$/, '\n')

    // Patch runInlineTest to normalize both transform output and expected
    testUtils.runInlineTest = function (
      module: any,

rom each line (not meaningful for code)
    // - Ensure exactly one trailing newline (POSIX convention for text files)
    //   Using \n*$ to handle case where transform output has no trailing newline
    const normalizeLF = (str


tick'

it('should execute async modules in to correct order and without additional ticks (case a)', async () => {
  tick.start()
  await require('./case-a/f')
  expect(tick.stop()).toEqual([
    'e 0',
    'async before 0',
    'async middle 1',
    'async after 2',
    'b 3',
    'c 3',
    'a 3',
    'd 3',
    'async2 before 3',
    'async2 middle 4',
    'async2 after 5',
    'f 6',
  ])
})

it('should execute async modules in to correct order and without additional ticks (case b)', async () => {
  tick

async after 5',
  ])
})

it('should execute async modules in to correct order and without additional ticks (case c)', async () => {
  tick.start()
  await require('./case-c/a')
  expect(tick.stop()).toEqual(['b 0', 'a before 0', 'a after 1'])
})

it('shoul

.start()
  await require('./case-b/e')
  expect(tick.stop()).toEqual([
    'async before 0',
    'async middle 1',
    'async after 2',
    'c 3',
    'b 3',
    'a 3',
    'd 3',
    'async before 3',
    'async middle 4',
    '


l type definitions for Node.js Turbopack runtime.
 * These properties are stored on globalThis to persist across chunk reloads during HMR.
 */

declare global {
  var __turbopack_module_factories__: ModuleFactories
  var __turbopack_module_cache__: Record<ModuleId, any>
  var __turbopack_runtime_modules__: Set<ModuleId>
  /**
   * Shared registry of per-runtime server HMR handler entries, keyed by the
   * runtime file's __filename. Map.set() naturally replaces stale entries when
   * a runtime file is re-e

   * full cache reset.
   */
  // NodeJsHmrPayload is only in scope inside the concatenated runtime chunk, not
  // in this .d.ts file, so the handler parameter must use any here.

  var __turbopack_server_hmr_handlers__:
    | Map<string, { handler: (upda

valuated. Reset to undefined by the hot-reloader on


ime/hmr-runtime.ts" />

/* eslint-disable @typescript-eslint/no-unused-vars */

type NodeJsHmrPayload = {
  resource: {
    path: string
    headers?: Record<string, string>
  }
  issues: Issue[]
  type: 'partial'
  instruction: EcmascriptMergedUpdate
}

/**
 * Appends the module code with //# sourceURL and //# sourceMappingURL so
 * that Node.js can resolve stack frames from `eval`ed server HMR modules back to
 * their original source files. Mirrors the browser's _eval in dev-backend-dom.ts.
 */
function i

  const sourceURL = moduleId ? `${fileHref}?${moduleId}` : fileHref
  let code = entry.code + '\n\n//# sourceURL=' + sourceURL
  if (entry.map) {
    code +=
      '\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,' +
      Buffer.from(ent

nlineSourcemaps(entry: EcmascriptModuleEntry): string {
  const [chunkPath, moduleId] = entry.url.split('?', 2)
  const absolutePath = path.resolve(RUNTIME_ROOT, chunkPath)
  const fileHref = url.pathToFileURL(absolutePath).href


e
   * update.
   * SourceData is an array of ModuleIds or undefined.
   */
  Update = 2,
}

type SourceData = ChunkPath | ModuleId | ModuleId[] | undefined

// @ts-ignore Defined in `dev-base.ts`
declare function getOrInstantiateModuleFromParent<M>(
  id: ModuleId,
  sourceModule: M
): M

// @ts-ignore Defined in `hmr-runtime.ts` (dev mode only)
declare let devModuleCache: Record<ModuleId, any> | undefined

/**
 * Flag indicating which module object type to create when a module is merged. Set to `true`
 *

WithDirectionFlag = false

const REEXPORTED_OBJECTS = new WeakMap<Module, ReexportedObjects>()

/**
 * Constructs the `__turbopack_context__` object for a module.
 */
function Context(
  this: TurbopackBaseContext<Module>,
  module: Module,
  exports: Expo

by each runtime that uses ModuleWithDirection (browser dev-base.ts, nodejs dev-base.ts,
 * nodejs build-base.ts). Browser production (build-base.ts) leaves it as `false` since it
 * uses plain Module objects.
 */
let createModule


hared/runtime/runtime-utils.ts" />

/// A 'base' utilities to support runtime can have externals.
/// Currently this is for node.js / edge runtime both.
/// If a fn requires node.js specific behavior, it should be placed in `node-external-utils` instead.

async function externalImport(id: DependencySpecifier) {
  let raw
  try {
    raw = await import(id)
  } catch (err) {
    // TODO(alexkirsz) This can happen when a client-side module tries to load
    // an external module we don't provide a shim for (e.

.default && 'default' in raw.default) {
    return interopEsm(raw.default, createNS(raw), true)
  }

  return raw
}
contextPrototype.y = externalImport

function externalRequire(
  id: ModuleId,
  thunk: () => any,
  esm: boolean = false
): Exports | EsmNa

g. querystring, url).
    // For now, we fail semi-silently, but in the future this should be a
    // compilation error.
    throw new Error(`Failed to load external module ${id}: ${err}`)
  }

  if (raw && raw.__esModule && raw


d in WebWorkers to tell the runtime about the chunk suffix
declare var TURBOPACK_ASSET_SUFFIX: string
// Used in WebWorkers to tell the runtime about the current chunk url since it
// can't be detected via `document.currentScript`. Note it's stored in reversed
// order to use `push` and `pop`
declare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined

// Injected by rust code
declare var CHUNK_BASE_PATH: string
/**
 * Custom base path for Web Worker URLs (the entrypoint and the module
 * chunks loaded in

differs from
 * the worker's own origin, so the override has to apply to both — using
 * `WORKER_BASE_PATH` only for the entrypoint would leave the worker unable
 * to load any chunks when `CHUNK_BASE_PATH` is on a different origin.
 */
declare var WORKER_

side the worker). Mirrors webpack's
 * `output.workerPublicPath`. `null` means "use CHUNK_BASE_PATH"; an empty
 * string is a literal empty prefix (not a fallback).
 *
 * The worker's bootstrap rejects module chunks whose origin


ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin')

module.exports = {
  mode: 'development',
  resolve: {
    extensions: ['.jsx', '...'],
  },
  module: {
    unsafeCache: true,
    rules: [
      {
        test: /\.jsx$/,
        loader: 'swc-loader',
        options: {
          jsc: {
            parser: {
              syntax: 'ecmascript',
              jsx: true,
              dynamicImport: true,
              privateMethod: true,
              functionBind: true,

    },
            externalHelpers: true,
            transform: {
              react: {
                runtime: 'automatic',
                refresh: true,
              },
            },
          },
        },
      },
    ],
  },
  devServer: {
    h

     classPrivateProperty: true,
              exportDefaultFrom: true,
              exportNamespaceFrom: true,
              decorators: true,
              decoratorsBeforeExport: true,
              importMeta: true,


rt './b'
import './c'
import D from './d'
import './e'
import './f'

import a from './dep?a'
import b from './dep?b'
import c from './dep?c'
import d from './dep?d'
import e from './dep?e'
import f from './dep?f'

it('should generate valid code', () => {
  expect(A()).toBe('x')
  expect(new D().method()).toBe('x')
})

it('a should be used', () => {
  expect(a).toBe(true)
})

if (process.env.NODE_ENV === 'production') {
  it('b should be unused', () => {
    expect(b).toBe(false)
  })
}

it('c should be used

xpect(c).toBe(true)
})

if (process.env.NODE_ENV === 'production') {
  it('d should be used', () => {
    expect(d).toBe(true)
  })

  it('e should be unused', () => {
    expect(e).toBe(false)
  })
}

it('f should be used', () => {
  expect(f).toBe(true)


h="../../shared-node/node-externals-utils.ts" />
/// <reference path="../../shared-node/node-wasm-utils.ts" />
/// <reference path="./nodejs-globals.d.ts" />

/**
 * Base Node.js runtime shared between production and development.
 * Contains chunk loading, module caching, and other non-HMR functionality.
 */

process.env.TURBOPACK = '1'

const url = require('url') as typeof import('url')

const moduleFactories: ModuleFactories = new Map()
const moduleCache: ModuleCache<Module> = Object.create(null)

/**
 *

ult ?? exported
  if (typeof exportedPath !== 'string') {
    return exported as any
  }

  const strippedAssetPrefix = exportedPath.slice(ASSET_PREFIX.length)
  const resolved = path.resolve(RUNTIME_ROOT, strippedAssetPrefix)

  return url.pathToFileURL(r

Returns an absolute path to the given module's id.
 */
function resolvePathFromModule(
  this: TurbopackBaseContext<Module>,
  moduleId: string
): string {
  const exported = this.r(moduleId)
  const exportedPath = exported?.defa


runtime (e.g. for Edge).
 *
 * It will be appended to the base development runtime code.
 */

/* eslint-disable @typescript-eslint/no-unused-vars */

/// <reference path="../base/runtime-base.ts" />
/// <reference path="../../../shared/require-type.d.ts" />
/// <reference path="../../../shared-node/base-externals-utils.ts" />

type ChunkRunner = {
  requiredChunks: Set<ChunkPath>
  chunkPath: ChunkPath
  runtimeModuleIds: ModuleId[]
}

let BACKEND: RuntimeBackend
;(() => {
  BACKEND = {
    // The "none" ru

erChunk(chunk, params) {
      let chunkPath = getPathFromScript(chunk)

      registeredChunks.add(chunkPath)
      instantiateDependentChunks(chunkPath)

      if (params == null) {
        return
      }

      if (params.otherChunks.length === 0) {

ntime expects all chunks within the same chunk group to be
    // registered before any of them are instantiated.
    // Furthermore, modules must be instantiated synchronously, hence we don't
    // use promises here.
    regist


erence path="./dummy.ts" />

const moduleCache: ModuleCache<Module> = {}
contextPrototype.c = moduleCache

/**
 * Gets or instantiates a runtime module.
 */
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function getOrInstantiateRuntimeModule(
  chunkPath: ChunkPath,
  moduleId: ModuleId
): Module {
  const module = moduleCache[moduleId]
  if (module) {
    if (module.error) {
      throw module.error
    }
    return module
  }

  return instantiateModule(moduleId, SourceType.R

oduleFromParent: GetOrInstantiateModuleFromParent<
  Module
> = (id, sourceModule) => {
  const module = moduleCache[id]

  if (module) {
    if (module.error) {
      throw module.error
    }
    return module
  }

  return instantiateModule(id, SourceTyp

untime, chunkPath)
}

/**
 * Retrieves a module from the cache, or instantiate it if it is not cached.
 */
// Used by the backend
// @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const getOrInstantiateM


ould allow to import an rejected async module again', async () => {
  await expect(require('./main')).rejects.toEqual(
    expect.objectContaining({
      message: expect.stringContaining('expected rejection 1'),
    })
  )
  await expect(require('./module')).rejects.toEqual(
    expect.objectContaining({
      message: expect.stringContaining('expected rejection 1'),
    })
  )
  await expect(require('./module?2')).rejects.toEqual(
    expect.objectContaining({
      message: expect.stringContaining('expec

ire('./module?3')).rejects.toEqual(
      expect.objectContaining({
        message: expect.stringContaining('expected rejection 3'),
      })
    ),
    expect(require('./module?4')).rejects.toEqual(
      expect.objectContaining({
        message: expect

ted rejection 2'),
    })
  )
  await expect(require('./reexport?2')).rejects.toEqual(
    expect.objectContaining({
      message: expect.stringContaining('expected rejection 1'),
    })
  )
  await Promise.all([
    expect(requ


ack-message'
      data: Record<string, any>
    }

export type ClientOptions = {
  addMessageListener: (cb: (msg: WebSocketMessage) => void) => void
  sendMessage: SendMessage
  onUpdateError: (err: unknown) => void
}

export function connect({
  addMessageListener,
  sendMessage,
  onUpdateError = console.error,
}: ClientOptions) {
  addMessageListener((msg) => {
    switch (msg.type) {
      case 'turbopack-connected':
        handleSocketConnected(sendMessage)
        break
      default:
        try {

.data as ServerMessage)
          }
          applyAggregatedUpdates()
        } catch (e: unknown) {
          console.warn(
            '[Fast Refresh] performing full reload\n\n' +
              "Fast Refresh will perform a full reload when you edit a f

          if (Array.isArray(msg.data)) {
            for (let i = 0; i < msg.data.length; i++) {
              handleSocketMessage(msg.data[i] as ServerMessage)
            }
          } else {
            handleSocketMessage(msg


 communicate between the
 * Turbopack runtime and the Turbopack server for issue reporting and HMR.
 */
type PartialServerMessage = {
  resource: ResourceIdentifier
  issues: Issue[]
  type: 'partial'
  instruction: PartialUpdate
}

// string encoding of a module factory (used in hmr updates)
type ModuleFactoryString = string

type ServerMessage = {
  resource: ResourceIdentifier
  issues: Issue[]
} & (
  | {
      type: 'restart'
    }
  | {
      type: 'notFound'
    }
  | PartialServerMessage
  | {

: 'ChunkListUpdate'
  chunks?: Record<ChunkPath, ChunkUpdate>
  merged?: MergedChunkUpdate[]
}

type ChunkUpdate =
  | {
      type: 'added'
    }
  | { type: 'deleted' }
  | { type: 'total' }
  // We currently don't have any chunks that can be updated par

 type: 'issues'
    }
  | UnknownType
)

type UnknownType = {
  type: 'future-type-marker-do-not-use-or-you-will-be-fired'
}

type PartialUpdate =
  | ChunkListUpdate
  | {
      type: never
    }

type ChunkListUpdate = {
  type


etRedboxDescriptionWarning,
  getRedboxErrorLink,
} from './next-test-utils'
import type { NextInstance } from './next-modes/base'
import type { Playwright } from './browsers/playwright'

export async function waitForHydration(browser: Playwright) {
  await browser.eval(() => {
    return new Promise<void>((resolve) => {
      if ((window as any).__NEXT_HYDRATED) {
        resolve()
      } else {
        var timeout = setTimeout(resolve, 30 * 1000)
        ;(window as any).__NEXT_HYDRATED_CB = function ()

: string = '/',
  webDriverOptions:
    | Parameters<NextInstance['browser']>[1]
    | undefined = undefined
) {
  let unwrappedByTypeScriptUsingKeyword = false

  try {
    await next.stop()
    await next.clean()
    if (initialFiles) {
      for (const

{
          clearTimeout(timeout)
          resolve()
        }
      }
    })
  })
}

export async function createSandbox(
  next: NextInstance,
  initialFiles?: Map<string, string | ((contents: string) => string)>,
  initialUrl


assName="z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex">

          Get started by editing!!
          app/page.tsx

ame="pointer-events-none flex place-items-center gap-2 p-8 lg:pointer-events-auto lg:p-0"
            href="https://vercel.com?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
            target="_blank"
            rel="

      <div className="fixed bottom-0 left-0 flex h-48 w-full items-end justify-center bg-gradient-to-t from-white via-white dark:from-black dark:via-black lg:static lg:h-auto lg:w-auto lg:bg-none">
          <a
            classN


 { join } from 'path'
import { tmpdir } from 'os'
import execa from 'execa'

describe('merge-errors-json driver', () => {
  it('should correctly merge errors.json files with conflicting new entries', async () => {
    const base = {
      '1': 'Original message 1',
      '2': 'Original message 2',
    }
    const current = {
      ...base,
      '3': 'From a conflicting branch that was merged first 1',
      '4': 'From a conflicting branch that was merged first 2',
    }
    const rebased = await simulateRe

1',
      '6': 'From our branch 2',
    })
  })

  it('should handle empty base file', async () => {
    const base = {}
    const current = {
      '1': 'Message from a conflicting branch that was merged first',
    }
    const rebased = await simulateReb

base({
      base,
      current,
      incoming: {
        ...base,
        '3': 'From our branch 1',
        '4': 'From our branch 2',
      },
    })
    expect(rebased).toEqual({
      ...current,
      '5': 'From our branch


 from 'e2e-utils'
import stripAnsi from 'strip-ansi'

describe('build-error-logs', () => {
  const { next, isTurbopack, isRspack } = nextTestSetup({
    files: __dirname,
  })

  it('should only log error a single time', async () => {
    await next.fetch('/')
    const output = stripAnsi(next.cliOutput)

    expect(output).toContain('Module not found')

    const moduleNotFoundLogs = output
      .split('\n')
      .filter((line) => line.includes('Module not found'))

    if (isTurbopack) {
      expect(mo

gs).toHaveLength(1)
    } else if (isRspack) {
      expect([2, 3]).toContain(moduleNotFoundLogs.length)
    } else {
      // FIXME: next with webpack still logs the same error too many times
      expect(moduleNotFoundLogs).toHaveLength(3)
    }
  })
})


  getRedboxDescription,
  getRedboxSource,
  waitForRedbox,
} from 'next-test-utils'
import { outdent } from 'outdent'

describe('ecmascript-error-title', () => {
  const { next, isTurbopack } = nextTestSetup({
    files: __dirname,
  })

  it('should show the specific SWC error message as title for syntax errors', async () => {
    const browser = await next.browser('/')
    expect(await browser.elementByCss('p').text()).toBe('hello world')

    await next.patchFile(
      'app/page.tsx',
      outdent`

t waitForRedbox(browser)
      const description = await getRedboxDescription(browser)
      expect(description).toBe("Expected '>', got '<eof>'")

      const source = await getRedboxSource(browser)
      expect(source).toContain("Expected '>', got '<eof>

      export default () => <div/
      `
    )

    if (isTurbopack) {
      // The redbox description should show the specific SWC error message
      // instead of the generic "Parsing ecmascript source code failed".
      awai


getRedboxDescription,
  getRedboxSource,
} from 'next-test-utils'

// FIXME: er-enable when we have a better implementation of node binary resolving
describe.skip('externalize-node-binary-browser-error', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should error when import node binary on browser side', async () => {
    const browser = await next.browser('/')
    await waitForRedbox(browser)
    const redbox = {
      description: await getRedboxDescription(browser),
      so

ect(redbox.description).toBe('Failed to compile')
    expect(redbox.source).toMatchInlineSnapshot(`
        "./node_modules/foo-browser-import-binary/binary.node
        Error: Node.js binary module ./node_modules/foo-browser-import-binary/binary.node is n

urce: await getRedboxSource(browser),
    }

    exp


from 'e2e-utils'
import {
  waitForDevToolsIndicator,
  assertNoDevToolsIndicator,
  toggleDevToolsIndicatorPopover,
  waitFor,
} from 'next-test-utils'

const COOLDOWN = 3000

describe('dev indicator - Hide DevTools Button', () => {
  const { next } = nextTestSetup({
    files: __dirname,
    env: {
      __NEXT_DEV_INDICATOR_COOLDOWN_MS: `${COOLDOWN}`,
    },
  })

  it('should show the dev indicator when the server is manually restarted', async () => {
    const browser = await next.browser('/')

    awa

.stop()
    await next.start()

    const browser2 = await next.browser('/')
    await browser2.refresh()
    await waitForDevToolsIndicator(browser2)
  })

  it('should still hide the dev indicator after reloading the page', async () => {
    const browse

it toggleDevToolsIndicatorPopover(browser)
    await browser.elementByCss('[data-preferences]').click()
    await browser.elementByCss('[data-hide-dev-tools]').click()

    await assertNoDevToolsIndicator(browser)

    await next


from 'e2e-utils'
import { waitForStaticIndicator } from 'next-test-utils'

describe('app dir dev indicator - route type', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should have route type as static by default for static page', async () => {
    const browser = await next.browser('/')

    await waitForStaticIndicator(browser, 'Static')
  })

  it('should have route type as dynamic when changing to dynamic page', async () => {
    const browser = await next.browser('/')

')
    } finally {
      await next.patchFile('app/page.tsx', origContent)
    }
  })

  it('should have route type as dynamic when on load of dynamic page', async () => {
    const origContent = await next.readFile('app/page.tsx')

    await next.patchFil

const origContent = await next.readFile('app/page.tsx')

    await next.patchFile(
      'app/page.tsx',
      origContent.replace('// headers()', 'headers()')
    )

    try {
      await waitForStaticIndicator(browser, 'Dynamic


xSource,
} from 'next-test-utils'

describe('app-dir - server-component-next-dynamic-ssr-false', () => {
  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should error when use dynamic ssr:false in server component', async () => {
    const browser = await next.browser('/')
    await waitForRedbox(browser)
    const redbox = {
      description: await getRedboxDescription(browser),
      source: await getRedboxSource(browser),
    }

    if (process.env.IS_TURBOPACK_TEST) {
      expect(r

      "./app/page.js (3:23)
       \`ssr: false\` is not allowed with \`next/dynamic\` in Server Components. Please move it into a Client Component.
         1 | import dynamic from 'next/dynamic'
         2 |
       > 3 | const DynamicClient = dynamic(()

edbox.description).toMatchInlineSnapshot(
        `"\`ssr: false\` is not allowed with \`next/dynamic\` in Server Components. Please move it into a Client Component."`
      )
      expect(redbox.source).toMatchInlineSnapshot(`


me="pointer-events-none flex place-items-center gap-2 p-8 lg:pointer-events-auto lg:p-0"
            href="https://vercel.com?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app"
            target="_blank"
            rel="n

     <div className="fixed bottom-0 left-0 flex h-48 w-full items-end justify-center bg-gradient-to-t from-white via-white dark:from-black dark:via-black lg:static lg:h-auto lg:w-auto lg:bg-none">
          <a
            classNa


() => {
  const { next } = nextTestSetup({ files: __dirname, patchFileDelay: 1000 })
  const loggedAfterValueRegexp = /After: (\d\.\d+)/
  let cliOutputLength: number

  const getLoggedAfterValue = () => {
    const match = next.cliOutput
      .slice(cliOutputLength)
      .match(loggedAfterValueRegexp)

    if (!match) {
      throw new Error('No logs from after() found')
    }
    return match[1]
  }

  // Edge runtime is not supported with Cache Components.
  const runtimes = isCacheComponentsEnabled ?

 => {
      const browser = await next.browser(`/${runtime}`)
      const valueBeforePatch = await browser.elementById('value').text()

      await next.patchFile(
        'components/shared-page.tsx',
        (content) => content.replace('foo', 'bar'),

['node'] : ['edge', 'node']

  beforeEach(() => {
    cliOutputLength = next.cliOutput.length
  })

  describe.each(runtimes)('%s runtime', (runtime) => {
    it('should use cached fetch calls for fast refresh requests', async ()


e: 'performance' | 'console'
  name: string
  properties: any
  startTime: number
  endTime: number
}>

declare global {
  interface Window {
    reactServerRequests: {
      /** For tests */
      getSnapshot: () => Array<
        Omit<ReactServerRequests[number], 'startTime' | 'endTime' | 'type'>
      >
      getStoreSnapshot(): ReactServerRequests
      subscribe(callback: () => void): () => void
    }
  }

  interface PerformanceEntry {
    detail?: any
  }
}

let reactServerRequests: ReactServerReques

urn reactServerRequests
      .filter((request) => {
        const isRegisterTrackRequest =
          request.type === 'console' &&
          request.name === undefined &&
          request.startTime === 0.001 &&
          request.endTime === 0.001

ts = []
const listeners = new Set<() => void>()

// The store implementation is just a local debugging aid.
// Assertions should happen on `getSnapshot` not on the UI.
window.reactServerRequests = {
  getSnapshot: () => {
    ret


he default when visiting pages as an ordinary user.
  // true is the default when having Chrome DevTools open.
  // Hardcoded for now since most of the actual behavior is not intended.
  const disableCache = false
  const extraHTTPHeaders = disableCache
    ? { 'Cache-Control': 'no-cache' }
    : undefined

  const { next } = nextTestSetup({
    files: __dirname,
  })

  it('should show setTimeout', async () => {
    const browser = await next.browser('/set-timeout', { extraHTTPHeaders })
    await browser.

   { name: '\u200bsetTimeout', properties: [] },
        { name: '\u200bsetTimeout', properties: [] },
      ])
    )
  })

  it('should show fetch', async () => {
    const browser = await next.browser('/fetch', { extraHTTPHeaders })
    await browser.ele

elementByCss('[data-react-server-requests-done]', {
      state: 'attached',
    })

    const track = await browser.eval('window.reactServerRequests.getSnapshot()')
    expect(track).toEqual(
      expect.arrayContaining([


import { useSyncExternalStore } from 'react'

const reactServerRequestsServerSnapshot: never[] = []
const ServerRequestsStore = {
  subscribe:
    typeof window === 'undefined'
      ? () => () => {}
      : window.reactServerRequests.subscribe,
  getSnapshot:
    typeof window === 'undefined'
      ? () => []
      : window.reactServerRequests.getStoreSnapshot,
  getServerSnapshot: () => reactServerRequestsServerSnapshot,
}

export function ReactServerRequests() {
  const reactServerRequests = useSyncExt

{reactServerRequests.map((request, index) => (

                  {request.type}: {request.name || '<Unnamed>'}

                (

ernalStore(
    ServerRequestsStore.subscribe,
    ServerRequestsStore.getSnapshot,
    ServerRequestsStore.getServerSnapshot
  )

  return (
    <>
      <p>{reactServerRequests.length} Server Request entries</p>
      <ol>


{ ReactNode, Suspense } from 'react'
import { ReactServerRequests } from './ReactServerRequests'
import Link from 'next/link'

export default function Root({ children }: { children: ReactNode }) {
  return (

            <Link href="/">Home</Link>

            <Link href="/fetch">fetch</Link>

            <Link href="/set-timeout">setT

<Link href="/headers">headers</Link>

            <Link href="/cookies">cookies</Link>

            <Link href="/draftMode">draftMode</Link>

imeout</Link>

            <Link href="/params/next">params</Link>

            <Link href="/searchparams?slug=next">searchParams</Link>


ts child dependency update without re-evaluating',
      async () => {
        const browser = await next.browser('/dep-accept')

        // Wait for initial render and hydration (eval time only appears after useEffect)
        await retry(async () => {
          const text = await browser.elementByCss('#dep-value').text()
          expect(text).toBe('initial')
        })
        await retry(async () => {
          const text = await browser.elementByCss('#parent-eval-time').text()
          expect(text).to

al accept call count
        const initialCallCount = await browser
          .elementByCss('#accept-call-count')
          .text()
        expect(initialCallCount).toBe('Accept Calls: 0')

        // Patch the dependency to change its exported value

Match(/Parent Evaluated At: \d+/)
        })

        // Capture the parent evaluation timestamp
        const parentEvalTime = await browser
          .elementByCss('#parent-eval-time')
          .text()

        // Verify initi


import { useEffect, useState, useRef } from 'react'
import { value } from './dep'

// Track when this module was evaluated (should NOT change on dep update)
const evaluatedAt = Date.now()

export default function DepAcceptPage() {
  const [depValue, setDepValue] = useState(value)
  const [acceptCallCount, setAcceptCallCount] = useState(0)
  const [evalTime, setEvalTime] = useState<number | null>(null)
  const mountedRef = useRef(false)

  useEffect(() => {
    mountedRef.current = true
    // Set eval tim

    if (import.meta.turbopackHot) {
      import.meta.turbopackHot.accept('./dep', () => {
        // ESM bindings are automatically re-imported before this callback runs,
        // so `value` already reflects the updated module.
        if (mountedRef.c

e on client only to avoid hydration mismatch
    setEvalTime(evaluatedAt)
    return () => {
      mountedRef.current = false
    }
  }, [])

  useEffect(() => {
    // import.meta.turbopackHot is the ESM equivalent of module.hot


import { useEffect, useState, useRef } from 'react'
import { valueA } from './dep-a'
import { valueB } from './dep-b'

const evaluatedAt = Date.now()

export default function DepAcceptArrayPage() {
  const [depAValue, setDepAValue] = useState(valueA)
  const [depBValue, setDepBValue] = useState(valueB)
  const [acceptCallCount, setAcceptCallCount] = useState(0)
  const [evalTime, setEvalTime] = useState<number | null>(null)
  const mountedRef = useRef(false)

  useEffect(() => {
    mountedRef.current = t

      // ESM bindings are automatically re-imported before this callback runs,
        // so `valueA` and `valueB` already reflect the updated modules.
        if (mountedRef.current) {
          setDepAValue(valueA)
          setDepBValue(valueB)

rue
    setEvalTime(evaluatedAt)
    return () => {
      mountedRef.current = false
    }
  }, [])

  useEffect(() => {
    if (import.meta.turbopackHot) {
      import.meta.turbopackHot.accept(['./dep-a', './dep-b'], () => {


client'

import { useEffect, useState } from 'react'
import { valueA } from './dep-a'
import { valueB } from './dep-b'

// Track when this module was evaluated
const evaluatedAt = Date.now()

export default function DepDeclineArrayPage() {
  const [evalTime, setEvalTime] = useState<number | null>(null)

  useEffect(() => {
    setEvalTime(evaluatedAt)
  }, [])

  useEffect(() => {
    if (import.meta.turbopackHot) {
      // Decline updates for both dependencies — should trigger full reload
      import.met

.decline(['./dep-a', './dep-b'])
    }
  }, [])

  return (

{valueA}

{valueB}

      {evalTime !== null && (

Parent Evaluated At: {evalTime}

      )}


ywright'

export type { Playwright }

if (!process.env.TEST_FILE_PATH) {
  process.env.TEST_FILE_PATH = module.parent!.filename
}

let deviceIP: string
const isBrowserStack = !!process.env.BROWSERSTACK
;(global as any).browserName = process.env.BROWSER_NAME || 'chrome'

if (isBrowserStack) {
  const nets = os.networkInterfaces()
  for (const key of Object.keys(nets)) {
    let done = false

    for (const item of nets[key]!) {
      if (item.family === 'IPv4' && !item.internal) {
        deviceIP = item.add

l(async () => {
    await Promise.all(browserTeardown.map((f) => f())).catch((e) =>
      console.error('browser teardown', e)
    )

    if (browserQuit) {
      await browserQuit()
    }
  })
}

export interface WebdriverOptions {
  permissions?: Permiss

ress
        done = true
        break
      }
    }
    if (done) break
  }
}

let browserTeardown: (() => Promise<void>)[] = []
let browserQuit: (() => Promise<void>) | undefined

if (typeof afterAll === 'function') {
  afterAl


 client. This option is only supported when nested inside an outer `act`
 *   scope. The blocked response will be fulfilled when the outer
 *   scope completes.
 *
 * The list of expected responses does not need to be exhaustive — any
 * responses that don't match will proceed like normal. However, `act` will
 * error if the expected substring is not found in any of the responses, or
 * if the expected responses are received out of order. It will also error
 * if the same expected substring is found in mult

ted, pass "no-requests".
 */
type ActConfig =
  | ExpectedResponseConfig
  | Array<ExpectedResponseConfig>
  | 'block'
  | 'no-requests'
  | null

export function createRouterAct(
  page: Playwright.Page,
  options?: {
    /**
     * Status codes that are

iple responses.
 *
 * If no expected responses are provided, the only expectation is that at
 * least one request is initiated. (This is the same as passing an
 * empty array.)
 *
 * Alternatively, if no network activity is expec


ess.env.TRACE_PLAYWRIGHT

const defaultTimeout = process.env.NEXT_E2E_TEST_TIMEOUT
  ? parseInt(process.env.NEXT_E2E_TEST_TIMEOUT, 10)
  : // In development mode, compilation can take longer due to lower CPU
    // availability in GitHub Actions.
    60 * 1000

// loose global to register teardown functions before quitting the browser instance.
// This is due to `quit` can be called anytime outside of Playwright's lifecycle,
// which can create corrupted state by terminating the context.
// [TODO] global `q

ntext?.close()
  await browser?.close()
  context = undefined
  browser = undefined
}

async function teardown(tearDownFn: () => Promise<void>) {
  pendingTeardown.push(tearDownFn)
  await tearDownFn()
  pendingTeardown.splice(pendingTeardown.indexOf(tearD

uit` might need to be removed, instead should introduce per-instance teardown
const pendingTeardown: Array<() => Promise<void>> = []
export async function quit() {
  await Promise.all(pendingTeardown.map((fn) => fn()))
  await co


  _res: http.ServerResponse
  resolve: (value?: string) => any
  reject: (value: any) => any
}

type TestDataServer = {
  _server: http.Server
  listen: (port: number) => void
  close: () => void
}

// Creates a lightweight HTTP server for use in e2e testing. This simulates the
// data service that would be used in a real Next.js application, whether it's
// direct database access, an ORM, or a higher-level data access layer. The e2e
// test can observe when individual requests are received, and control the

t can respond with any text it wants.
//
// Examples:
//   response.resolve() // Responds with the key itself
//   response.resolve('custom') // Responds with custom text
//   response.reject(new Error('oops!')) // Responds with a 500 error
//
// Based on

// timing of when the data is fulfilled, without needing to mock any lower
// level I/O.
//
// Receives requests of the form: /?key=foo
//
// Responds in plain text. By default, the response is the key itself, but the
// e2e tes


ates static and dynamic content in a response stream
 * by splitting on PPR boundary sentinel markers.
 *
 * This function is used in Partial Prerendering (PPR) tests to analyze the output
 * of Next.js pages and verify that static and dynamic content are properly separated.
 *
 * @param fn - A function that returns a Promise resolving to a readable stream
 *             containing HTML with PPR boundary markers
 * @returns An object containing the separated static and dynamic chunks
 *
 * @example
 * const

// Content after the boundary
 */
export async function splitResponseWithPPRSentinel(
  fn: () => Promise<NodeJS.ReadableStream>
): Promise<[staticPart: string, dynamicPart: string]> {
  const stream = await fn()
  const chunks: string[] = []

  await new

 [staticPart, dynamicPart] = await splitResponseWithPPRSentinel(async () => {
 *   return fetch('/some-ppr-page').then(res => res.body)
 * })
 * console.log(staticPart)  // Content before the boundary
 * console.log(dynamicPart)


tring>
  subDir?: string
  turbo?: boolean
  forcedPort?: string
  serverReadyPattern?: RegExp
  patchFileDelay?: number
  startServerTimeout?: number
  disableAutoSkewProtection?: boolean
}

/**
 * Omit the first argument of a function
 */
type OmitFirstArgument<F> = F extends (
  firstArgument: any,
  ...args: infer P
) => infer R
  ? (...args: P) => R
  : never

// Do not rename or format. sync-react script relies on this line.
// prettier-ignore
const nextjsReactPeerVersion = "19.2.6";

const ROOT_PACKA

ed installCommand?: InstallCommand
  public buildCommand?: string
  public buildArgs?: string[]
  protected startCommand?: string
  protected startArgs?: string[]
  protected dependencies?: PackageJson['dependencies'] = {}
  protected resolutions?: Package

GE_MANAGER: string =
  require('../../../package.json').packageManager

export class NextInstance {
  protected files: ResolvedFileConfig
  protected overrideFiles: ResolvedFileConfig
  protected nextConfig?: NextConfig
  protect