code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
async get(cacheKey, softTags) {
console.log(
'LegacyCustomCacheHandler::get',
cacheKey,
JSON.stringify(softTags)
)
return defaultCacheHandler.get(cacheKey, softTags)
} | @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler} | get | javascript | vercel/next.js | test/e2e/app-dir/use-cache-custom-handler/legacy-handler.js | https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/use-cache-custom-handler/legacy-handler.js | MIT |
async set(cacheKey, pendingEntry) {
console.log('LegacyCustomCacheHandler::set', cacheKey)
return defaultCacheHandler.set(cacheKey, pendingEntry)
} | @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler} | set | javascript | vercel/next.js | test/e2e/app-dir/use-cache-custom-handler/legacy-handler.js | https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/use-cache-custom-handler/legacy-handler.js | MIT |
async expireTags(...tags) {
console.log('LegacyCustomCacheHandler::expireTags', JSON.stringify(tags))
return defaultCacheHandler.expireTags(...tags)
} | @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler} | expireTags | javascript | vercel/next.js | test/e2e/app-dir/use-cache-custom-handler/legacy-handler.js | https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/use-cache-custom-handler/legacy-handler.js | MIT |
async receiveExpiredTags(...tags) {
console.log(
'LegacyCustomCacheHandler::receiveExpiredTags',
JSON.stringify(tags)
)
} | @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler} | receiveExpiredTags | javascript | vercel/next.js | test/e2e/app-dir/use-cache-custom-handler/legacy-handler.js | https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/use-cache-custom-handler/legacy-handler.js | MIT |
async function middleware(request) {
const headers = new Headers(request.headers)
headers.set('x-from-middleware', 'hello-from-middleware')
const removeHeaders = request.nextUrl.searchParams.get('remove-headers')
if (removeHeaders) {
for (const key of removeHeaders.split(',')) {
headers.delete(key)
}
}
const updateHeader = request.nextUrl.searchParams.get('update-headers')
if (updateHeader) {
for (const kv of updateHeader.split(',')) {
const [key, value] = kv.split('=')
headers.set(key, value)
}
}
return NextResponse.next({
request: {
headers,
},
})
} | @param {import('next/server').NextRequest} request | middleware | javascript | vercel/next.js | test/e2e/middleware-request-header-overrides/app/middleware.js | https://github.com/vercel/next.js/blob/master/test/e2e/middleware-request-header-overrides/app/middleware.js | MIT |
async function middleware(request) {
const url = request.nextUrl
if (url.pathname.includes('article')) {
return NextResponse.next()
}
// this is needed for tests to get the BUILD_ID
if (url.pathname.startsWith('/_next/static/__BUILD_ID')) {
return NextResponse.next()
}
if (url.pathname.includes('/to/some/404/path')) {
return NextResponse.next({
'x-matched-path': '/404',
})
}
if (url.pathname.includes('/middleware-external-rewrite-body')) {
return NextResponse.rewrite(
'https://next-data-api-endpoint.vercel.app/api/echo-body'
)
}
if (url.pathname.includes('/rewrite-to-static')) {
request.nextUrl.pathname = '/static-ssg/post-1'
return NextResponse.rewrite(request.nextUrl)
}
if (url.pathname.includes('/fallback-true-blog/rewritten')) {
request.nextUrl.pathname = '/about'
return NextResponse.rewrite(request.nextUrl)
}
if (url.pathname.startsWith('/about') && url.searchParams.has('override')) {
const isExternal = url.searchParams.get('override') === 'external'
return NextResponse.rewrite(
isExternal
? 'https://example.vercel.sh'
: new URL('/ab-test/a', request.url)
)
}
if (url.pathname === '/rewrite-to-beforefiles-rewrite') {
url.pathname = '/beforefiles-rewrite'
return NextResponse.rewrite(url)
}
if (url.pathname === '/rewrite-to-afterfiles-rewrite') {
url.pathname = '/afterfiles-rewrite'
return NextResponse.rewrite(url)
}
if (url.pathname.startsWith('/to-blog')) {
const slug = url.pathname.split('/').pop()
url.pathname = `/fallback-true-blog/${slug}`
return NextResponse.rewrite(url)
}
if (url.pathname === '/rewrite-to-ab-test') {
let bucket = request.cookies.get('bucket')
if (!bucket) {
bucket = Math.random() >= 0.5 ? 'a' : 'b'
url.pathname = `/ab-test/${bucket}`
const response = NextResponse.rewrite(url)
response.cookies.set('bucket', bucket, { maxAge: 10 })
return response
}
url.pathname = `/${bucket}`
return NextResponse.rewrite(url)
}
if (url.pathname === '/rewrite-me-to-about') {
url.pathname = '/about'
return NextResponse.rewrite(url, {
headers: { 'x-rewrite-target': String(url) },
})
}
if (url.pathname === '/rewrite-me-with-a-colon') {
url.pathname = '/with:colon'
return NextResponse.rewrite(url)
}
if (url.pathname === '/colon:here') {
url.pathname = '/no-colon-here'
return NextResponse.rewrite(url)
}
if (url.pathname === '/rewrite-me-to-vercel') {
return NextResponse.rewrite('https://example.vercel.sh')
}
if (url.pathname === '/clear-query-params') {
const allowedKeys = ['allowed']
for (const key of [...url.searchParams.keys()]) {
if (!allowedKeys.includes(key)) {
url.searchParams.delete(key)
}
}
return NextResponse.rewrite(url)
}
if (url.pathname === '/dynamic-no-cache/1') {
const rewriteUrl =
request.headers.get('purpose') === 'prefetch'
? '/dynamic-no-cache/1'
: '/dynamic-no-cache/2'
url.pathname = rewriteUrl
return NextResponse.rewrite(url, {
headers: { 'x-middleware-cache': 'no-cache' },
})
}
if (
url.pathname === '/rewrite-me-without-hard-navigation' ||
url.searchParams.get('path') === 'rewrite-me-without-hard-navigation'
) {
url.searchParams.set('middleware', 'foo')
url.pathname = request.cookies.has('about-bypass')
? '/about-bypass'
: '/about'
return NextResponse.rewrite(url, {
headers: { 'x-middleware-cache': 'no-cache' },
})
}
if (url.pathname.endsWith('/dynamic-replace')) {
url.pathname = '/dynamic-fallback/catch-all'
return NextResponse.rewrite(url)
}
if (url.pathname.startsWith('/country')) {
const locale = url.searchParams.get('my-locale')
if (locale) {
url.locale = locale
}
const country = url.searchParams.get('country') || 'us'
if (!PUBLIC_FILE.test(url.pathname) && !url.pathname.includes('/api/')) {
url.pathname = `/country/${country}`
return NextResponse.rewrite(url)
}
}
if (url.pathname.startsWith('/i18n')) {
url.searchParams.set('locale', url.locale)
return NextResponse.rewrite(url)
}
return NextResponse.rewrite(request.nextUrl)
} | @param {import('next/server').NextRequest} request | middleware | javascript | vercel/next.js | test/e2e/middleware-rewrites/app/middleware.js | https://github.com/vercel/next.js/blob/master/test/e2e/middleware-rewrites/app/middleware.js | MIT |
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { hasDynamic } from 'lib'
// populated with tests
export default async function () {
await hasDynamic()
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '**/node_modules/lib/**'
}
`)
context.lib.write(`
export async function hasDynamic() {
eval('100')
}
`)
} | '
}
`)
await waitFor(500)
})
it('warns in dev for allowed code', async () => {
context.app = await launchApp(context.appDir, context.appPort, appOption)
const res = await fetchViaHTTP(context.appPort, middlewareUrl)
await waitFor(500)
expect(res.status).toBe(200)
await retry(async () => {
expect(context.logs.output).toContain(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime`
)
})
})
it('warns in dev for unallowed code', async () => {
context.app = await launchApp(context.appDir, context.appPort, appOption)
const res = await fetchViaHTTP(context.appPort, routeUrl)
expect(res.status).toBe(200)
await retry(async () => {
expect(context.logs.output).toContain(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime`
)
})
})
;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode',
() => {
it('fails to build because of unallowed code', async () => {
const output = await nextBuild(context.appDir, undefined, {
stdout: true,
stderr: true,
env: process.env.IS_TURBOPACK_TEST
? {}
: { NEXT_TELEMETRY_DEBUG: 1 },
})
expect(output.code).toBe(1)
if (!process.env.IS_TURBOPACK_TEST) {
expect(output.stderr).toContain(`./pages/api/route.js`)
}
expect(output.stderr).toContain(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime`
)
if (!process.env.IS_TURBOPACK_TEST) {
expect(output.stderr).toContain(`Used by default`)
expect(output.stderr).toContain(TELEMETRY_EVENT_NAME)
}
})
}
)
})
describe.each([
{
title: 'Edge API',
url: routeUrl,
init() {
context.api.write(`
export default async function handler(request) {
eval('100')
return Response.json({ result: true })
}
export const config = {
runtime: 'edge',
unstable_allowDynamic: '**'
}
`)
},
},
{
title: 'Middleware',
url: middlewareUrl,
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
export default () => {
eval('100')
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '**'
}
`)
},
},
{
title: 'Edge API using lib',
url: routeUrl,
init() {
context.api.write(`
import { hasDynamic } from 'lib'
export default async function handler(request) {
await hasDynamic()
return Response.json({ result: true })
}
export const config = {
runtime: 'edge',
unstable_allowDynamic: '* | init | javascript | vercel/next.js | test/integration/edge-runtime-configurable-guards/test/index.test.js | https://github.com/vercel/next.js/blob/master/test/integration/edge-runtime-configurable-guards/test/index.test.js | MIT |
init() {
context.api.write(`
export default async function handler(request) {
if ((() => false)()) {
eval('100')
}
return Response.json({ result: true })
}
export const config = {
runtime: 'edge',
unstable_allowDynamic: '**'
}
`)
} | '
}
`)
context.lib.write(`
export async function hasDynamic() {
eval('100')
}
`)
},
},
{
title: 'Middleware using lib',
url: middlewareUrl,
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { hasDynamic } from 'lib'
// populated with tests
export default async function () {
await hasDynamic()
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '* | init | javascript | vercel/next.js | test/integration/edge-runtime-configurable-guards/test/index.test.js | https://github.com/vercel/next.js/blob/master/test/integration/edge-runtime-configurable-guards/test/index.test.js | MIT |
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
// populated with tests
export default () => {
if ((() => false)()) {
eval('100')
}
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '**'
}
`)
} | '
}
`)
context.lib.write(`
export async function hasDynamic() {
eval('100')
}
`)
},
},
{
title: 'Middleware using lib',
url: middlewareUrl,
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { hasDynamic } from 'lib'
// populated with tests
export default async function () {
await hasDynamic()
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '* | init | javascript | vercel/next.js | test/integration/edge-runtime-configurable-guards/test/index.test.js | https://github.com/vercel/next.js/blob/master/test/integration/edge-runtime-configurable-guards/test/index.test.js | MIT |
init() {
context.api.write(`
import { hasUnusedDynamic } from 'lib'
export default async function handler(request) {
await hasUnusedDynamic()
return Response.json({ result: true })
}
export const config = {
runtime: 'edge',
unstable_allowDynamic: '**/node_modules/lib/**'
}
`)
context.lib.write(`
export async function hasUnusedDynamic() {
if ((() => false)()) {
eval('100')
}
}
`)
} | '
}
`)
context.lib.write(`
export async function hasDynamic() {
eval('100')
}
`)
},
},
{
title: 'Middleware using lib',
url: middlewareUrl,
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { hasDynamic } from 'lib'
// populated with tests
export default async function () {
await hasDynamic()
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '* | init | javascript | vercel/next.js | test/integration/edge-runtime-configurable-guards/test/index.test.js | https://github.com/vercel/next.js/blob/master/test/integration/edge-runtime-configurable-guards/test/index.test.js | MIT |
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { hasUnusedDynamic } from 'lib'
// populated with tests
export default async function () {
await hasUnusedDynamic()
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '**/node_modules/lib/**'
}
`)
context.lib.write(`
export async function hasUnusedDynamic() {
if ((() => false)()) {
eval('100')
}
}
`)
} | '
}
`)
context.lib.write(`
export async function hasDynamic() {
eval('100')
}
`)
},
// TODO: Re-enable when Turbopack applies the middleware dynamic code
// evaluation transforms also to code in node_modules.
skip: Boolean(process.env.IS_TURBOPACK_TEST),
},
])('$title with allowed, used dynamic code', ({ init, url, skip }) => {
beforeEach(() => init())
;(skip ? it.skip : it)('still warns in dev at runtime', async () => {
context.app = await launchApp(context.appDir, context.appPort, appOption)
const res = await fetchViaHTTP(context.appPort, url)
await waitFor(500)
// eslint-disable-next-line jest/no-standalone-expect
expect(res.status).toBe(200)
// eslint-disable-next-line jest/no-standalone-expect
expect(context.logs.output).toContain(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime`
)
})
})
describe.each([
{
title: 'Edge API',
url: routeUrl,
init() {
context.api.write(`
export default async function handler(request) {
if ((() => false)()) {
eval('100')
}
return Response.json({ result: true })
}
export const config = {
runtime: 'edge',
unstable_allowDynamic: '**'
}
`)
},
},
{
title: 'Middleware',
url: middlewareUrl,
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
// populated with tests
export default () => {
if ((() => false)()) {
eval('100')
}
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '**'
}
`)
},
},
{
title: 'Edge API using lib',
url: routeUrl,
init() {
context.api.write(`
import { hasUnusedDynamic } from 'lib'
export default async function handler(request) {
await hasUnusedDynamic()
return Response.json({ result: true })
}
export const config = {
runtime: 'edge',
unstable_allowDynamic: '* | init | javascript | vercel/next.js | test/integration/edge-runtime-configurable-guards/test/index.test.js | https://github.com/vercel/next.js/blob/master/test/integration/edge-runtime-configurable-guards/test/index.test.js | MIT |
init() {
context.api.write(`
import { hasDynamic } from 'lib'
export default async function handler(request) {
await hasDynamic()
return Response.json({ result: true })
}
export const config = {
runtime: 'edge',
unstable_allowDynamic: '/pages/**'
}
`)
context.lib.write(`
export async function hasDynamic() {
eval('100')
}
`)
} | '
}
`)
context.lib.write(`
export async function hasUnusedDynamic() {
if ((() => false)()) {
eval('100')
}
}
`)
},
},
{
title: 'Middleware using lib',
url: middlewareUrl,
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { hasUnusedDynamic } from 'lib'
// populated with tests
export default async function () {
await hasUnusedDynamic()
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '* | init | javascript | vercel/next.js | test/integration/edge-runtime-configurable-guards/test/index.test.js | https://github.com/vercel/next.js/blob/master/test/integration/edge-runtime-configurable-guards/test/index.test.js | MIT |
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { hasDynamic } from 'lib'
export default async function () {
await hasDynamic()
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '/pages/**'
}
`)
context.lib.write(`
export async function hasDynamic() {
eval('100')
}
`)
} | '
}
`)
context.lib.write(`
export async function hasUnusedDynamic() {
if ((() => false)()) {
eval('100')
}
}
`)
},
},
{
title: 'Middleware using lib',
url: middlewareUrl,
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { hasUnusedDynamic } from 'lib'
// populated with tests
export default async function () {
await hasUnusedDynamic()
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '* | init | javascript | vercel/next.js | test/integration/edge-runtime-configurable-guards/test/index.test.js | https://github.com/vercel/next.js/blob/master/test/integration/edge-runtime-configurable-guards/test/index.test.js | MIT |
init() {
context.api.write(`
export default async function handler(request) {
return Response.json({ result: (() => {}) instanceof Function })
}
export const config = { runtime: 'edge' }
`)
} | '
}
`)
context.lib.write(`
export async function hasUnusedDynamic() {
if ((() => false)()) {
eval('100')
}
}
`)
},
},
{
title: 'Middleware using lib',
url: middlewareUrl,
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { hasUnusedDynamic } from 'lib'
// populated with tests
export default async function () {
await hasUnusedDynamic()
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '* | init | javascript | vercel/next.js | test/integration/edge-runtime-configurable-guards/test/index.test.js | https://github.com/vercel/next.js/blob/master/test/integration/edge-runtime-configurable-guards/test/index.test.js | MIT |
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { returnTrue } from 'lib'
export default async function () {
(() => {}) instanceof Function
return NextResponse.next()
}
`)
} | '
}
`)
context.lib.write(`
export async function hasUnusedDynamic() {
if ((() => false)()) {
eval('100')
}
}
`)
},
},
{
title: 'Middleware using lib',
url: middlewareUrl,
init() {
context.middleware.write(`
import { NextResponse } from 'next/server'
import { hasUnusedDynamic } from 'lib'
// populated with tests
export default async function () {
await hasUnusedDynamic()
return NextResponse.next()
}
export const config = {
unstable_allowDynamic: '* | init | javascript | vercel/next.js | test/integration/edge-runtime-configurable-guards/test/index.test.js | https://github.com/vercel/next.js/blob/master/test/integration/edge-runtime-configurable-guards/test/index.test.js | MIT |
function getAmpValidatorInstance(
/** @type {string | undefined} */ validatorPath
) {
let promise = instancePromises.get(validatorPath)
if (!promise) {
// NOTE: if `validatorPath` is undefined, `AmpHtmlValidator` will load the code from its default URL
promise = AmpHtmlValidator.getInstance(validatorPath)
instancePromises.set(validatorPath, promise)
}
return promise
} | This is a workaround for issues with concurrent `AmpHtmlValidator.getInstance()` calls,
duplicated from 'packages/next/src/export/helpers/get-amp-html-validator.ts'.
see original code for explanation.
@returns {Promise<Validator>} | getAmpValidatorInstance | javascript | vercel/next.js | test/lib/amp-test-utils.js | https://github.com/vercel/next.js/blob/master/test/lib/amp-test-utils.js | MIT |
function getBundledAmpValidatorFilepath() {
return require.resolve(
'next/dist/compiled/amphtml-validator/validator_wasm.js'
)
} | Use the same validator that we use for builds.
This avoids trying to load one from the network, which can cause random test flakiness.
(duplicated from 'packages/next/src/export/helpers/get-amp-html-validator.ts') | getBundledAmpValidatorFilepath | javascript | vercel/next.js | test/lib/amp-test-utils.js | https://github.com/vercel/next.js/blob/master/test/lib/amp-test-utils.js | MIT |
async function createNextInstall({
parentSpan,
dependencies = {},
resolutions = null,
installCommand = null,
packageJson = {},
dirSuffix = '',
keepRepoDir = false,
beforeInstall,
}) {
const tmpDir = await fs.realpath(process.env.NEXT_TEST_DIR || os.tmpdir())
return await parentSpan
.traceChild('createNextInstall')
.traceAsyncFn(async (rootSpan) => {
const origRepoDir = path.join(__dirname, '../../')
const installDir = path.join(
tmpDir,
`next-install-${randomBytes(32).toString('hex')}${dirSuffix}`
)
let tmpRepoDir
require('console').log('Creating next instance in:')
require('console').log(installDir)
const pkgPathsEnv = process.env.NEXT_TEST_PKG_PATHS
let pkgPaths
if (pkgPathsEnv) {
pkgPaths = new Map(JSON.parse(pkgPathsEnv))
require('console').log('using provided pkg paths')
} else {
tmpRepoDir = path.join(
tmpDir,
`next-repo-${randomBytes(32).toString('hex')}${dirSuffix}`
)
require('console').log('Creating temp repo dir', tmpRepoDir)
for (const item of ['package.json', 'packages']) {
await rootSpan
.traceChild(`copy ${item} to temp dir`)
.traceAsyncFn(() =>
fs.copy(
path.join(origRepoDir, item),
path.join(tmpRepoDir, item),
{
filter: (item) => {
return (
!item.includes('node_modules') &&
!item.includes('pnpm-lock.yaml') &&
!item.includes('.DS_Store') &&
// Exclude Rust compilation files
!/packages[\\/]next-swc/.test(item)
)
},
}
)
)
}
const nativePath = path.join(origRepoDir, 'packages/next-swc/native')
const hasNativeBinary = fs.existsSync(nativePath)
? fs.readdirSync(nativePath).some((item) => item.endsWith('.node'))
: false
if (hasNativeBinary) {
process.env.NEXT_TEST_NATIVE_DIR = nativePath
} else {
const swcDirectory = fs
.readdirSync(path.join(origRepoDir, 'node_modules/@next'))
.find((directory) => directory.startsWith('swc-'))
process.env.NEXT_TEST_NATIVE_DIR = path.join(
origRepoDir,
'node_modules/@next',
swcDirectory
)
}
// log for clarity of which version we're using
require('console').log({
swcDirectory: process.env.NEXT_TEST_NATIVE_DIR,
})
pkgPaths = await rootSpan
.traceChild('linkPackages')
.traceAsyncFn((span) =>
linkPackages({
repoDir: tmpRepoDir,
parentSpan: span,
})
)
}
const combinedDependencies = {
next: pkgPaths.get('next'),
...Object.keys(dependencies).reduce((prev, pkg) => {
const pkgPath = pkgPaths.get(pkg)
prev[pkg] = pkgPath || dependencies[pkg]
return prev
}, {}),
}
if (useRspack) {
combinedDependencies['next-rspack'] = pkgPaths.get('next-rspack')
}
const scripts = {
debug: `NEXT_PRIVATE_SKIP_CANARY_CHECK=1 NEXT_TELEMETRY_DISABLED=1 NEXT_TEST_NATIVE_DIR=${process.env.NEXT_TEST_NATIVE_DIR} node --inspect --trace-deprecation --enable-source-maps node_modules/next/dist/bin/next`,
'debug-brk': `NEXT_PRIVATE_SKIP_CANARY_CHECK=1 NEXT_TELEMETRY_DISABLED=1 NEXT_TEST_NATIVE_DIR=${process.env.NEXT_TEST_NATIVE_DIR} node --inspect-brk --trace-deprecation --enable-source-maps node_modules/next/dist/bin/next`,
...packageJson.scripts,
}
await fs.ensureDir(installDir)
await fs.writeFile(
path.join(installDir, 'package.json'),
JSON.stringify(
{
...packageJson,
scripts,
dependencies: combinedDependencies,
private: true,
// Add resolutions if provided.
...(resolutions ? { resolutions } : {}),
},
null,
2
)
)
if (beforeInstall !== undefined) {
await rootSpan
.traceChild('beforeInstall')
.traceAsyncFn(async (span) => {
await beforeInstall(span, installDir)
})
}
if (installCommand) {
const installString =
typeof installCommand === 'function'
? installCommand({
dependencies: combinedDependencies,
resolutions,
})
: installCommand
console.log('running install command', installString)
rootSpan.traceChild('run custom install').traceFn(() => {
childProcess.execSync(installString, {
cwd: installDir,
stdio: ['ignore', 'inherit', 'inherit'],
})
})
} else {
await rootSpan
.traceChild('run generic install command', combinedDependencies)
.traceAsyncFn(() => installDependencies(installDir, tmpDir))
}
if (useRspack) {
// This is what the next-rspack plugin does.
// TODO: Load the plugin properly during test
process.env.NEXT_RSPACK = 'true'
process.env.RSPACK_CONFIG_VALIDATE = 'loose-silent'
}
return {
installDir,
pkgPaths,
tmpRepoDir,
}
})
} | @param {object} param0
@param {import('@next/telemetry').Span} param0.parentSpan
@param {object} [param0.dependencies]
@param {object | null} [param0.resolutions]
@param { ((ctx: { dependencies: { [key: string]: string } }) => string) | string | null} [param0.installCommand]
@param {object} [param0.packageJson]
@param {string} [param0.dirSuffix]
@param {boolean} [param0.keepRepoDir]
@param {(span: import('@next/telemetry').Span, installDir: string) => Promise<void>} param0.beforeInstall
@returns {Promise<{installDir: string, pkgPaths: Map<string, string>, tmpRepoDir: string | undefined}>} | createNextInstall | javascript | vercel/next.js | test/lib/create-next-install.js | https://github.com/vercel/next.js/blob/master/test/lib/create-next-install.js | MIT |
async get(cacheKey) {
return defaultCacheHandler.get(cacheKey)
} | @type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2} | get | javascript | vercel/next.js | test/production/custom-server/cache-handler.js | https://github.com/vercel/next.js/blob/master/test/production/custom-server/cache-handler.js | MIT |
async set(cacheKey, pendingEntry) {
const requestId = requestIdStorage.getStore()
console.log('set cache', cacheKey, 'requestId:', requestId)
return defaultCacheHandler.set(cacheKey, pendingEntry)
} | @type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2} | set | javascript | vercel/next.js | test/production/custom-server/cache-handler.js | https://github.com/vercel/next.js/blob/master/test/production/custom-server/cache-handler.js | MIT |
async refreshTags() {
return defaultCacheHandler.refreshTags()
} | @type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2} | refreshTags | javascript | vercel/next.js | test/production/custom-server/cache-handler.js | https://github.com/vercel/next.js/blob/master/test/production/custom-server/cache-handler.js | MIT |
async getExpiration(...tags) {
return defaultCacheHandler.getExpiration(...tags)
} | @type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2} | getExpiration | javascript | vercel/next.js | test/production/custom-server/cache-handler.js | https://github.com/vercel/next.js/blob/master/test/production/custom-server/cache-handler.js | MIT |
async expireTags(...tags) {
return defaultCacheHandler.expireTags(...tags)
} | @type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2} | expireTags | javascript | vercel/next.js | test/production/custom-server/cache-handler.js | https://github.com/vercel/next.js/blob/master/test/production/custom-server/cache-handler.js | MIT |
function Home() {
const helloWorld = useMemo(()=>new HelloWorld(), []);
return /*#__PURE__*/ _jsx("button", {
onClick: ()=>helloWorld.hi(),
children: "Click me"
});
} | Add your relevant code here for the issue to reproduce | Home | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/analyzer/graph/issue-75938/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/analyzer/graph/issue-75938/input.js | MIT |
hi() {
this.#wrap(()=>{
alert(fooBar());
});
} | Add your relevant code here for the issue to reproduce | hi | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/analyzer/graph/issue-75938/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/analyzer/graph/issue-75938/input.js | MIT |
set (carrier, key, value) {
carrier.push({
key,
value
});
} | we use this map to propagate attributes from nested spans to the top span | set | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
getTracerInstance() {
return trace.getTracer('next.js', '0.0.1');
} | Returns an instance to the trace with configured name.
Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
This should be lazily evaluated. | getTracerInstance | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
getContext() {
return context;
} | Returns an instance to the trace with configured name.
Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
This should be lazily evaluated. | getContext | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
getTracePropagationData() {
const activeContext = context.active();
const entries = [];
propagation.inject(activeContext, entries, clientTraceDataSetter);
return entries;
} | Returns an instance to the trace with configured name.
Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
This should be lazily evaluated. | getTracePropagationData | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
getActiveScopeSpan() {
return trace.getSpan(context == null ? void 0 : context.active());
} | Returns an instance to the trace with configured name.
Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
This should be lazily evaluated. | getActiveScopeSpan | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
withPropagatedContext(carrier, fn, getter) {
const activeContext = context.active();
if (trace.getSpanContext(activeContext)) {
// Active span is already set, too late to propagate.
return fn();
}
const remoteContext = propagation.extract(activeContext, carrier, getter);
return context.with(remoteContext, fn);
} | Returns an instance to the trace with configured name.
Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
This should be lazily evaluated. | withPropagatedContext | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
trace(...args) {
var _trace_getSpanContext;
const [type, fnOrOptions, fnOrEmpty] = args;
// coerce options form overload
const { fn, options } = typeof fnOrOptions === 'function' ? {
fn: fnOrOptions,
options: {}
} : {
fn: fnOrEmpty,
options: {
...fnOrOptions
}
};
const spanName = options.spanName ?? type;
if (!NextVanillaSpanAllowlist.includes(type) && process.env.NEXT_OTEL_VERBOSE !== '1' || options.hideSpan) {
return fn();
}
// Trying to get active scoped span to assign parent. If option specifies parent span manually, will try to use it.
let spanContext = this.getSpanContext((options == null ? void 0 : options.parentSpan) ?? this.getActiveScopeSpan());
let isRootSpan = false;
if (!spanContext) {
spanContext = (context == null ? void 0 : context.active()) ?? ROOT_CONTEXT;
isRootSpan = true;
} else if ((_trace_getSpanContext = trace.getSpanContext(spanContext)) == null ? void 0 : _trace_getSpanContext.isRemote) {
isRootSpan = true;
}
const spanId = getSpanId();
options.attributes = {
'next.span_name': spanName,
'next.span_type': type,
...options.attributes
};
return context.with(spanContext.setValue(rootSpanIdKey, spanId), ()=>this.getTracerInstance().startActiveSpan(spanName, options, (span)=>{
const startTime = 'performance' in globalThis && 'measure' in performance ? globalThis.performance.now() : undefined;
const onCleanup = ()=>{
rootSpanAttributesStore.delete(spanId);
if (startTime && process.env.NEXT_OTEL_PERFORMANCE_PREFIX && LogSpanAllowList.includes(type || '')) {
performance.measure(`${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-${(type.split('.').pop() || '').replace(/[A-Z]/g, (match)=>'-' + match.toLowerCase())}`, {
start: startTime,
end: performance.now()
});
}
};
if (isRootSpan) {
rootSpanAttributesStore.set(spanId, new Map(Object.entries(options.attributes ?? {})));
}
try {
if (fn.length > 1) {
return fn(span, (err)=>closeSpanWithError(span, err));
}
const result = fn(span);
if (isPromise(result)) {
// If there's error make sure it throws
return result.then((res)=>{
span.end();
// Need to pass down the promise result,
// it could be react stream response with error { error, stream }
return res;
}).catch((err)=>{
closeSpanWithError(span, err);
throw err;
}).finally(onCleanup);
} else {
span.end();
onCleanup();
}
return result;
} catch (err) {
closeSpanWithError(span, err);
onCleanup();
throw err;
}
}));
} | Returns an instance to the trace with configured name.
Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
This should be lazily evaluated. | trace | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
onCleanup = ()=>{
rootSpanAttributesStore.delete(spanId);
if (startTime && process.env.NEXT_OTEL_PERFORMANCE_PREFIX && LogSpanAllowList.includes(type || '')) {
performance.measure(`${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-${(type.split('.').pop() || '').replace(/[A-Z]/g, (match)=>'-' + match.toLowerCase())}`, {
start: startTime,
end: performance.now()
});
}
} | Returns an instance to the trace with configured name.
Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
This should be lazily evaluated. | onCleanup | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
onCleanup = ()=>{
rootSpanAttributesStore.delete(spanId);
if (startTime && process.env.NEXT_OTEL_PERFORMANCE_PREFIX && LogSpanAllowList.includes(type || '')) {
performance.measure(`${process.env.NEXT_OTEL_PERFORMANCE_PREFIX}:next-${(type.split('.').pop() || '').replace(/[A-Z]/g, (match)=>'-' + match.toLowerCase())}`, {
start: startTime,
end: performance.now()
});
}
} | Returns an instance to the trace with configured name.
Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
This should be lazily evaluated. | onCleanup | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
wrap(...args) {
const tracer = this;
const [name, options, fn] = args.length === 3 ? args : [
args[0],
{},
args[1]
];
if (!NextVanillaSpanAllowlist.includes(name) && process.env.NEXT_OTEL_VERBOSE !== '1') {
return fn;
}
return function() {
let optionsObj = options;
if (typeof optionsObj === 'function' && typeof fn === 'function') {
optionsObj = optionsObj.apply(this, arguments);
}
const lastArgId = arguments.length - 1;
const cb = arguments[lastArgId];
if (typeof cb === 'function') {
const scopeBoundCb = tracer.getContext().bind(context.active(), cb);
return tracer.trace(name, optionsObj, (_span, done)=>{
arguments[lastArgId] = function(err) {
done == null ? void 0 : done(err);
return scopeBoundCb.apply(this, arguments);
};
return fn.apply(this, arguments);
});
} else {
return tracer.trace(name, optionsObj, ()=>fn.apply(this, arguments));
}
};
} | Returns an instance to the trace with configured name.
Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
This should be lazily evaluated. | wrap | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
startSpan(...args) {
const [type, options] = args;
const spanContext = this.getSpanContext((options == null ? void 0 : options.parentSpan) ?? this.getActiveScopeSpan());
return this.getTracerInstance().startSpan(type, options, spanContext);
} | Returns an instance to the trace with configured name.
Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
This should be lazily evaluated. | startSpan | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
getSpanContext(parentSpan) {
const spanContext = parentSpan ? trace.setSpan(context.active(), parentSpan) : undefined;
return spanContext;
} | Returns an instance to the trace with configured name.
Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
This should be lazily evaluated. | getSpanContext | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
getRootSpanAttributes() {
const spanId = context.active().getValue(rootSpanIdKey);
return rootSpanAttributesStore.get(spanId);
} | Returns an instance to the trace with configured name.
Since wrap / trace can be defined in any place prior to actual trace subscriber initialization,
This should be lazily evaluated. | getRootSpanAttributes | javascript | vercel/next.js | turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-ecmascript/tests/tree-shaker/analyzer/nextjs-tracer/input.js | MIT |
function defineProp(obj, name, options) {
if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options);
} | This file contains runtime types and functions that are shared between all
TurboPack ECMAScript runtimes.
It will be prepended to the runtime code of each runtime. | defineProp | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function esm(exports, getters) {
defineProp(exports, '__esModule', {
value: true
});
if (toStringTag) defineProp(exports, toStringTag, {
value: 'Module'
});
for(const key in getters){
const item = getters[key];
if (Array.isArray(item)) {
defineProp(exports, key, {
get: item[0],
set: item[1],
enumerable: true
});
} else {
defineProp(exports, key, {
get: item,
enumerable: true
});
}
}
Object.seal(exports);
} | Adds the getters to the exports object. | esm | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function esmExport(module, exports, getters) {
module.namespaceObject = module.exports;
esm(exports, getters);
} | Makes the module an ESM with exports | esmExport | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function ensureDynamicExports(module, exports) {
let reexportedObjects = module[REEXPORTED_OBJECTS];
if (!reexportedObjects) {
reexportedObjects = module[REEXPORTED_OBJECTS] = [];
module.exports = module.namespaceObject = new Proxy(exports, {
get (target, prop) {
if (hasOwnProperty.call(target, prop) || prop === 'default' || prop === '__esModule') {
return Reflect.get(target, prop);
}
for (const obj of reexportedObjects){
const value = Reflect.get(obj, prop);
if (value !== undefined) return value;
}
return undefined;
},
ownKeys (target) {
const keys = Reflect.ownKeys(target);
for (const obj of reexportedObjects){
for (const key of Reflect.ownKeys(obj)){
if (key !== 'default' && !keys.includes(key)) keys.push(key);
}
}
return keys;
}
});
}
} | Makes the module an ESM with exports | ensureDynamicExports | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
get (target, prop) {
if (hasOwnProperty.call(target, prop) || prop === 'default' || prop === '__esModule') {
return Reflect.get(target, prop);
}
for (const obj of reexportedObjects){
const value = Reflect.get(obj, prop);
if (value !== undefined) return value;
}
return undefined;
} | Makes the module an ESM with exports | get | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
ownKeys (target) {
const keys = Reflect.ownKeys(target);
for (const obj of reexportedObjects){
for (const key of Reflect.ownKeys(obj)){
if (key !== 'default' && !keys.includes(key)) keys.push(key);
}
}
return keys;
} | Makes the module an ESM with exports | ownKeys | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function dynamicExport(module, exports, object) {
ensureDynamicExports(module, exports);
if (typeof object === 'object' && object !== null) {
module[REEXPORTED_OBJECTS].push(object);
}
} | Dynamically exports properties from an object | dynamicExport | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function exportValue(module, value) {
module.exports = value;
} | Dynamically exports properties from an object | exportValue | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function exportNamespace(module, namespace) {
module.exports = module.namespaceObject = namespace;
} | Dynamically exports properties from an object | exportNamespace | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function createGetter(obj, key) {
return ()=>obj[key];
} | Dynamically exports properties from an object | createGetter | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function interopEsm(raw, ns, allowExportDefault) {
const getters = Object.create(null);
for(let current = raw; (typeof current === 'object' || typeof current === 'function') && !LEAF_PROTOTYPES.includes(current); current = getProto(current)){
for (const key of Object.getOwnPropertyNames(current)){
getters[key] = createGetter(raw, key);
}
}
// this is not really correct
// we should set the `default` getter if the imported module is a `.cjs file`
if (!(allowExportDefault && 'default' in getters)) {
getters['default'] = ()=>raw;
}
esm(ns, getters);
return ns;
} | @param raw
@param ns
@param allowExportDefault
* `false`: will have the raw module as default export
* `true`: will have the default property as default export | interopEsm | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function createNS(raw) {
if (typeof raw === 'function') {
return function(...args) {
return raw.apply(this, args);
};
} else {
return Object.create(null);
}
} | @param raw
@param ns
@param allowExportDefault
* `false`: will have the raw module as default export
* `true`: will have the default property as default export | createNS | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function esmImport(sourceModule, id) {
const module = getOrInstantiateModuleFromParent(id, sourceModule);
if (module.error) throw module.error;
// any ES module has to have `module.namespaceObject` defined.
if (module.namespaceObject) return module.namespaceObject;
// only ESM can be an async module, so we don't need to worry about exports being a promise here.
const raw = module.exports;
return module.namespaceObject = interopEsm(raw, createNS(raw), raw && raw.__esModule);
} | @param raw
@param ns
@param allowExportDefault
* `false`: will have the raw module as default export
* `true`: will have the default property as default export | esmImport | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function commonJsRequire(sourceModule, id) {
const module = getOrInstantiateModuleFromParent(id, sourceModule);
if (module.error) throw module.error;
return module.exports;
} | @param raw
@param ns
@param allowExportDefault
* `false`: will have the raw module as default export
* `true`: will have the default property as default export | commonJsRequire | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function moduleContext(map) {
function moduleContext(id) {
if (hasOwnProperty.call(map, id)) {
return map[id].module();
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
}
moduleContext.keys = ()=>{
return Object.keys(map);
};
moduleContext.resolve = (id)=>{
if (hasOwnProperty.call(map, id)) {
return map[id].id();
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
};
moduleContext.import = async (id)=>{
return await moduleContext(id);
};
return moduleContext;
} | `require.context` and require/import expression runtime. | moduleContext | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function moduleContext(id) {
if (hasOwnProperty.call(map, id)) {
return map[id].module();
}
const e = new Error(`Cannot find module '${id}'`);
e.code = 'MODULE_NOT_FOUND';
throw e;
} | `require.context` and require/import expression runtime. | moduleContext | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function getChunkPath(chunkData) {
return typeof chunkData === 'string' ? chunkData : chunkData.path;
} | Returns the path of a chunk defined by its data. | getChunkPath | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function isPromise(maybePromise) {
return maybePromise != null && typeof maybePromise === 'object' && 'then' in maybePromise && typeof maybePromise.then === 'function';
} | Returns the path of a chunk defined by its data. | isPromise | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function isAsyncModuleExt(obj) {
return turbopackQueues in obj;
} | Returns the path of a chunk defined by its data. | isAsyncModuleExt | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function createPromise() {
let resolve;
let reject;
const promise = new Promise((res, rej)=>{
reject = rej;
resolve = res;
});
return {
promise,
resolve: resolve,
reject: reject
};
} | Returns the path of a chunk defined by its data. | createPromise | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function resolveQueue(queue) {
if (queue && queue.status !== 1) {
queue.status = 1;
queue.forEach((fn)=>fn.queueCount--);
queue.forEach((fn)=>fn.queueCount-- ? fn.queueCount++ : fn());
}
} | Returns the path of a chunk defined by its data. | resolveQueue | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function wrapDeps(deps) {
return deps.map((dep)=>{
if (dep !== null && typeof dep === 'object') {
if (isAsyncModuleExt(dep)) return dep;
if (isPromise(dep)) {
const queue = Object.assign([], {
status: 0
});
const obj = {
[turbopackExports]: {},
[turbopackQueues]: (fn)=>fn(queue)
};
dep.then((res)=>{
obj[turbopackExports] = res;
resolveQueue(queue);
}, (err)=>{
obj[turbopackError] = err;
resolveQueue(queue);
});
return obj;
}
}
return {
[turbopackExports]: dep,
[turbopackQueues]: ()=>{}
};
});
} | Returns the path of a chunk defined by its data. | wrapDeps | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function asyncModule(module, body, hasAwait) {
const queue = hasAwait ? Object.assign([], {
status: -1
}) : undefined;
const depQueues = new Set();
const { resolve, reject, promise: rawPromise } = createPromise();
const promise = Object.assign(rawPromise, {
[turbopackExports]: module.exports,
[turbopackQueues]: (fn)=>{
queue && fn(queue);
depQueues.forEach(fn);
promise['catch'](()=>{});
}
});
const attributes = {
get () {
return promise;
},
set (v) {
// Calling `esmExport` leads to this.
if (v !== promise) {
promise[turbopackExports] = v;
}
}
};
Object.defineProperty(module, 'exports', attributes);
Object.defineProperty(module, 'namespaceObject', attributes);
function handleAsyncDependencies(deps) {
const currentDeps = wrapDeps(deps);
const getResult = ()=>currentDeps.map((d)=>{
if (d[turbopackError]) throw d[turbopackError];
return d[turbopackExports];
});
const { promise, resolve } = createPromise();
const fn = Object.assign(()=>resolve(getResult), {
queueCount: 0
});
function fnQueue(q) {
if (q !== queue && !depQueues.has(q)) {
depQueues.add(q);
if (q && q.status === 0) {
fn.queueCount++;
q.push(fn);
}
}
}
currentDeps.map((dep)=>dep[turbopackQueues](fnQueue));
return fn.queueCount ? promise : getResult();
}
function asyncResult(err) {
if (err) {
reject(promise[turbopackError] = err);
} else {
resolve(promise[turbopackExports]);
}
resolveQueue(queue);
}
body(handleAsyncDependencies, asyncResult);
if (queue && queue.status === -1) {
queue.status = 0;
}
} | Returns the path of a chunk defined by its data. | asyncModule | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
get () {
return promise;
} | Returns the path of a chunk defined by its data. | get | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
set (v) {
// Calling `esmExport` leads to this.
if (v !== promise) {
promise[turbopackExports] = v;
}
} | Returns the path of a chunk defined by its data. | set | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function handleAsyncDependencies(deps) {
const currentDeps = wrapDeps(deps);
const getResult = ()=>currentDeps.map((d)=>{
if (d[turbopackError]) throw d[turbopackError];
return d[turbopackExports];
});
const { promise, resolve } = createPromise();
const fn = Object.assign(()=>resolve(getResult), {
queueCount: 0
});
function fnQueue(q) {
if (q !== queue && !depQueues.has(q)) {
depQueues.add(q);
if (q && q.status === 0) {
fn.queueCount++;
q.push(fn);
}
}
}
currentDeps.map((dep)=>dep[turbopackQueues](fnQueue));
return fn.queueCount ? promise : getResult();
} | Returns the path of a chunk defined by its data. | handleAsyncDependencies | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
getResult = ()=>currentDeps.map((d)=>{
if (d[turbopackError]) throw d[turbopackError];
return d[turbopackExports];
}) | Returns the path of a chunk defined by its data. | getResult | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
getResult = ()=>currentDeps.map((d)=>{
if (d[turbopackError]) throw d[turbopackError];
return d[turbopackExports];
}) | Returns the path of a chunk defined by its data. | getResult | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function fnQueue(q) {
if (q !== queue && !depQueues.has(q)) {
depQueues.add(q);
if (q && q.status === 0) {
fn.queueCount++;
q.push(fn);
}
}
} | Returns the path of a chunk defined by its data. | fnQueue | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function asyncResult(err) {
if (err) {
reject(promise[turbopackError] = err);
} else {
resolve(promise[turbopackExports]);
}
resolveQueue(queue);
} | Returns the path of a chunk defined by its data. | asyncResult | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
} | A pseudo "fake" URL object to resolve to its relative path.
When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
hydration mismatch.
This is based on webpack's existing implementation:
https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js | relativeURL | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
relativeURL = function relativeURL(inputUrl) {
const realUrl = new URL(inputUrl, 'x:/');
const values = {};
for(const key in realUrl)values[key] = realUrl[key];
values.href = inputUrl;
values.pathname = inputUrl.replace(/[?#].*/, '');
values.origin = values.protocol = '';
values.toString = values.toJSON = (..._args)=>inputUrl;
for(const key in values)Object.defineProperty(this, key, {
enumerable: true,
configurable: true,
value: values[key]
});
} | A pseudo "fake" URL object to resolve to its relative path.
When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this
runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid
hydration mismatch.
This is based on webpack's existing implementation:
https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js | relativeURL | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
} | Utility function to ensure all variants of an enum are handled. | invariant | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function requireStub(_moduleId) {
throw new Error('dynamic usage of require is not supported');
} | A stub function to make `require` available but non-functional in ESM. | requireStub | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
async function externalImport(id) {
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.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.default && 'default' in raw.default) {
return interopEsm(raw.default, createNS(raw), true);
}
return raw;
} | A stub function to make `require` available but non-functional in ESM. | externalImport | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function externalRequire(id, thunk, esm = false) {
let raw;
try {
raw = thunk();
} 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.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 (!esm || raw.__esModule) {
return raw;
}
return interopEsm(raw, createNS(raw), true);
} | A stub function to make `require` available but non-functional in ESM. | externalRequire | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function resolveAbsolutePath(modulePath) {
if (modulePath) {
return path.join(ABSOLUTE_ROOT, modulePath);
}
return ABSOLUTE_ROOT;
} | Returns an absolute path to the given module path.
Module path should be relative, either path to 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. | resolveAbsolutePath | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function readWebAssemblyAsResponse(path) {
const { createReadStream } = require('fs');
const { Readable } = require('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': 'application/wasm'
}
});
} | Returns an absolute path to the given module path.
Module path should be relative, either path to 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. | readWebAssemblyAsResponse | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
async function compileWebAssemblyFromPath(path) {
const response = readWebAssemblyAsResponse(path);
return await WebAssembly.compileStreaming(response);
} | Returns an absolute path to the given module path.
Module path should be relative, either path to 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. | compileWebAssemblyFromPath | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
async function instantiateWebAssemblyFromPath(path, importsObj) {
const response = readWebAssemblyAsResponse(path);
const { instance } = await WebAssembly.instantiateStreaming(response, importsObj);
return instance.exports;
} | Returns an absolute path to the given module path.
Module path should be relative, either path to 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. | instantiateWebAssemblyFromPath | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function stringifySourceInfo(source) {
switch(source.type){
case 0:
return `runtime for chunk ${source.chunkPath}`;
case 1:
return `parent module ${source.parentId}`;
default:
invariant(source, (source)=>`Unknown source type: ${source?.type}`);
}
} | The module was instantiated because a parent module imported it. | stringifySourceInfo | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function createResolvePathFromModule(resolver) {
return function resolvePathFromModule(moduleId) {
const exported = resolver(moduleId);
const exportedPath = exported?.default ?? exported;
if (typeof exportedPath !== 'string') {
return exported;
}
const strippedAssetPrefix = exportedPath.slice(ASSET_PREFIX.length);
const resolved = path.resolve(RUNTIME_ROOT, strippedAssetPrefix);
return url.pathToFileURL(resolved).href;
};
} | Returns an absolute path to the given module's id. | createResolvePathFromModule | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function loadChunk(chunkData, source) {
if (typeof chunkData === 'string') {
return loadChunkPath(chunkData, source);
} else {
return loadChunkPath(chunkData.path, source);
}
} | Returns an absolute path to the given module's id. | loadChunk | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function loadChunkPath(chunkPath, source) {
if (!isJs(chunkPath)) {
// We only support loading JS chunks in Node.js.
// This branch can be hit when trying to load a CSS chunk.
return;
}
if (loadedChunks.has(chunkPath)) {
return;
}
try {
const resolved = path.resolve(RUNTIME_ROOT, chunkPath);
const chunkModules = require(resolved);
for (const [moduleId, moduleFactory] of Object.entries(chunkModules)){
if (!moduleFactories[moduleId]) {
moduleFactories[moduleId] = moduleFactory;
}
}
loadedChunks.add(chunkPath);
} catch (e) {
let errorMessage = `Failed to load chunk ${chunkPath}`;
if (source) {
errorMessage += ` from ${stringifySourceInfo(source)}`;
}
throw new Error(errorMessage, {
cause: e
});
}
} | Returns an absolute path to the given module's id. | loadChunkPath | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
async function loadChunkAsync(source, chunkData) {
const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path;
if (!isJs(chunkPath)) {
// We only support loading JS chunks in Node.js.
// This branch can be hit when trying to load a CSS chunk.
return;
}
if (loadedChunks.has(chunkPath)) {
return;
}
const resolved = path.resolve(RUNTIME_ROOT, chunkPath);
try {
const contents = await fs.readFile(resolved, 'utf-8');
const localRequire = (id)=>{
let resolvedId = require.resolve(id, {
paths: [
path.dirname(resolved)
]
});
return require(resolvedId);
};
const module1 = {
exports: {}
};
(0, eval)('(function(module, exports, require, __dirname, __filename) {' + contents + '\n})' + '\n//# sourceURL=' + url.pathToFileURL(resolved))(module1, module1.exports, localRequire, path.dirname(resolved), resolved);
const chunkModules = module1.exports;
for (const [moduleId, moduleFactory] of Object.entries(chunkModules)){
if (!moduleFactories[moduleId]) {
moduleFactories[moduleId] = moduleFactory;
}
}
loadedChunks.add(chunkPath);
} catch (e) {
let errorMessage = `Failed to load chunk ${chunkPath}`;
if (source) {
errorMessage += ` from ${stringifySourceInfo(source)}`;
}
throw new Error(errorMessage, {
cause: e
});
}
} | Returns an absolute path to the given module's id. | loadChunkAsync | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
localRequire = (id)=>{
let resolvedId = require.resolve(id, {
paths: [
path.dirname(resolved)
]
});
return require(resolvedId);
} | Returns an absolute path to the given module's id. | localRequire | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
localRequire = (id)=>{
let resolvedId = require.resolve(id, {
paths: [
path.dirname(resolved)
]
});
return require(resolvedId);
} | Returns an absolute path to the given module's id. | localRequire | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
async function loadChunkAsyncByUrl(source, chunkUrl) {
const path1 = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT));
return loadChunkAsync(source, path1);
} | Returns an absolute path to the given module's id. | loadChunkAsyncByUrl | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function loadWebAssembly(chunkPath, _edgeModule, imports) {
const resolved = path.resolve(RUNTIME_ROOT, chunkPath);
return instantiateWebAssemblyFromPath(resolved, imports);
} | Returns an absolute path to the given module's id. | loadWebAssembly | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function loadWebAssemblyModule(chunkPath, _edgeModule) {
const resolved = path.resolve(RUNTIME_ROOT, chunkPath);
return compileWebAssemblyFromPath(resolved);
} | Returns an absolute path to the given module's id. | loadWebAssemblyModule | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function getWorkerBlobURL(_chunks) {
throw new Error('Worker blobs are not implemented yet for Node.js');
} | Returns an absolute path to the given module's id. | getWorkerBlobURL | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function instantiateModule(id, source) {
const moduleFactory = moduleFactories[id];
if (typeof moduleFactory !== 'function') {
// This can happen if modules incorrectly handle HMR disposes/updates,
// e.g. when they keep a `setTimeout` around which still executes old code
// and contains e.g. a `require("something")` call.
let instantiationReason;
switch(source.type){
case 0:
instantiationReason = `as a runtime entry of chunk ${source.chunkPath}`;
break;
case 1:
instantiationReason = `because it was required from module ${source.parentId}`;
break;
default:
invariant(source, (source)=>`Unknown source type: ${source?.type}`);
}
throw new Error(`Module ${id} was instantiated ${instantiationReason}, but the module factory is not available. It might have been deleted in an HMR update.`);
}
let parents;
switch(source.type){
case 0:
parents = [];
break;
case 1:
// No need to add this module as a child of the parent module here, this
// has already been taken care of in `getOrInstantiateModuleFromParent`.
parents = [
source.parentId
];
break;
default:
invariant(source, (source)=>`Unknown source type: ${source?.type}`);
}
const module1 = {
exports: {},
error: undefined,
loaded: false,
id,
namespaceObject: undefined
};
moduleCache[id] = module1;
// NOTE(alexkirsz) This can fail when the module encounters a runtime error.
try {
const r = commonJsRequire.bind(null, module1);
moduleFactory.call(module1.exports, {
a: asyncModule.bind(null, module1),
e: module1.exports,
r,
t: runtimeRequire,
x: externalRequire,
y: externalImport,
f: moduleContext,
i: esmImport.bind(null, module1),
s: esmExport.bind(null, module1, module1.exports),
j: dynamicExport.bind(null, module1, module1.exports),
v: exportValue.bind(null, module1),
n: exportNamespace.bind(null, module1),
m: module1,
c: moduleCache,
M: moduleFactories,
l: loadChunkAsync.bind(null, {
type: 1,
parentId: id
}),
L: loadChunkAsyncByUrl.bind(null, {
type: 1,
parentId: id
}),
w: loadWebAssembly,
u: loadWebAssemblyModule,
P: resolveAbsolutePath,
U: relativeURL,
R: createResolvePathFromModule(r),
b: getWorkerBlobURL,
z: requireStub
});
} catch (error) {
module1.error = error;
throw error;
}
module1.loaded = true;
if (module1.namespaceObject && module1.exports !== module1.namespaceObject) {
// in case of a circular dependency: cjs1 -> esm2 -> cjs1
interopEsm(module1.exports, module1.namespaceObject);
}
return module1;
} | Returns an absolute path to the given module's id. | instantiateModule | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function getOrInstantiateModuleFromParent(id, sourceModule) {
const module1 = moduleCache[id];
if (module1) {
return module1;
}
return instantiateModule(id, {
type: 1,
parentId: sourceModule.id
});
} | Retrieves a module from the cache, or instantiate it if it is not cached. | getOrInstantiateModuleFromParent | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function getOrInstantiateRuntimeModule(moduleId, chunkPath) {
const module1 = moduleCache[moduleId];
if (module1) {
if (module1.error) {
throw module1.error;
}
return module1;
}
return instantiateRuntimeModule(moduleId, chunkPath);
} | Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached. | getOrInstantiateRuntimeModule | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function isJs(chunkUrlOrPath) {
return regexJsUrl.test(chunkUrlOrPath);
} | Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment. | isJs | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_build_runtime/output/[turbopack]_runtime.js | MIT |
function defineProp(obj, name, options) {
if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options);
} | This file contains runtime types and functions that are shared between all
TurboPack ECMAScript runtimes.
It will be prepended to the runtime code of each runtime. | defineProp | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | MIT |
function esm(exports, getters) {
defineProp(exports, '__esModule', {
value: true
});
if (toStringTag) defineProp(exports, toStringTag, {
value: 'Module'
});
for(const key in getters){
const item = getters[key];
if (Array.isArray(item)) {
defineProp(exports, key, {
get: item[0],
set: item[1],
enumerable: true
});
} else {
defineProp(exports, key, {
get: item,
enumerable: true
});
}
}
Object.seal(exports);
} | Adds the getters to the exports object. | esm | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | MIT |
function esmExport(module, exports, getters) {
module.namespaceObject = module.exports;
esm(exports, getters);
} | Makes the module an ESM with exports | esmExport | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | MIT |
function ensureDynamicExports(module, exports) {
let reexportedObjects = module[REEXPORTED_OBJECTS];
if (!reexportedObjects) {
reexportedObjects = module[REEXPORTED_OBJECTS] = [];
module.exports = module.namespaceObject = new Proxy(exports, {
get (target, prop) {
if (hasOwnProperty.call(target, prop) || prop === 'default' || prop === '__esModule') {
return Reflect.get(target, prop);
}
for (const obj of reexportedObjects){
const value = Reflect.get(obj, prop);
if (value !== undefined) return value;
}
return undefined;
},
ownKeys (target) {
const keys = Reflect.ownKeys(target);
for (const obj of reexportedObjects){
for (const key of Reflect.ownKeys(obj)){
if (key !== 'default' && !keys.includes(key)) keys.push(key);
}
}
return keys;
}
});
}
} | Makes the module an ESM with exports | ensureDynamicExports | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | MIT |
get (target, prop) {
if (hasOwnProperty.call(target, prop) || prop === 'default' || prop === '__esModule') {
return Reflect.get(target, prop);
}
for (const obj of reexportedObjects){
const value = Reflect.get(obj, prop);
if (value !== undefined) return value;
}
return undefined;
} | Makes the module an ESM with exports | get | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | MIT |
ownKeys (target) {
const keys = Reflect.ownKeys(target);
for (const obj of reexportedObjects){
for (const key of Reflect.ownKeys(obj)){
if (key !== 'default' && !keys.includes(key)) keys.push(key);
}
}
return keys;
} | Makes the module an ESM with exports | ownKeys | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | MIT |
function dynamicExport(module, exports, object) {
ensureDynamicExports(module, exports);
if (typeof object === 'object' && object !== null) {
module[REEXPORTED_OBJECTS].push(object);
}
} | Dynamically exports properties from an object | dynamicExport | javascript | vercel/next.js | turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | https://github.com/vercel/next.js/blob/master/turbopack/crates/turbopack-tests/tests/snapshot/runtime/default_dev_runtime/output/b1abf_turbopack-tests_tests_snapshot_runtime_default_dev_runtime_input_index_75df6705.js | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.