code
stringlengths 28
313k
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
74
| language
stringclasses 1
value | repo
stringlengths 5
60
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
digest(s) {
return import_enc_hex.default.stringify((0, import_sha1.default)(s));
}
|
Compute the sha1 hash of the script and return its hex representation.
|
digest
|
javascript
|
vercel/next.js
|
.github/actions/upload-turboyet-data/dist/index.js
|
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
|
MIT
|
constructor(client, opts) {
this.client = client;
this.opts = opts;
this.enableTelemetry = opts?.enableTelemetry ?? true;
if (opts?.readYourWrites === false) {
this.client.readYourWrites = false;
}
this.enableAutoPipelining = opts?.enableAutoPipelining ?? true;
}
|
Create a new redis client
@example
```typescript
const redis = new Redis({
url: "<UPSTASH_REDIS_REST_URL>",
token: "<UPSTASH_REDIS_REST_TOKEN>",
});
```
|
constructor
|
javascript
|
vercel/next.js
|
.github/actions/upload-turboyet-data/dist/index.js
|
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
|
MIT
|
createScript(script) {
return new Script(this, script);
}
|
Technically this is not private, we can hide it from intellisense by doing this
|
createScript
|
javascript
|
vercel/next.js
|
.github/actions/upload-turboyet-data/dist/index.js
|
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
|
MIT
|
constructor(configOrRequester) {
if ("request" in configOrRequester) {
super(configOrRequester);
return;
}
if (!configOrRequester.url) {
console.warn(
`[Upstash Redis] The 'url' property is missing or undefined in your Redis config.`
);
} else if (configOrRequester.url.startsWith(" ") || configOrRequester.url.endsWith(" ") || /\r|\n/.test(configOrRequester.url)) {
console.warn(
"[Upstash Redis] The redis url contains whitespace or newline, which can cause errors!"
);
}
if (!configOrRequester.token) {
console.warn(
`[Upstash Redis] The 'token' property is missing or undefined in your Redis config.`
);
} else if (configOrRequester.token.startsWith(" ") || configOrRequester.token.endsWith(" ") || /\r|\n/.test(configOrRequester.token)) {
console.warn(
"[Upstash Redis] The redis token contains whitespace or newline, which can cause errors!"
);
}
const client = new HttpClient({
baseUrl: configOrRequester.url,
retry: configOrRequester.retry,
headers: { authorization: `Bearer ${configOrRequester.token}` },
agent: configOrRequester.agent,
responseEncoding: configOrRequester.responseEncoding,
cache: configOrRequester.cache ?? "no-store",
signal: configOrRequester.signal,
keepAlive: configOrRequester.keepAlive,
readYourWrites: configOrRequester.readYourWrites
});
super(client, {
automaticDeserialization: configOrRequester.automaticDeserialization,
enableTelemetry: !process.env.UPSTASH_DISABLE_TELEMETRY,
latencyLogging: configOrRequester.latencyLogging,
enableAutoPipelining: configOrRequester.enableAutoPipelining
});
this.addTelemetry({
runtime: (
// @ts-expect-error to silence compiler
typeof EdgeRuntime === "string" ? "edge-light" : `node@${process.version}`
),
platform: process.env.VERCEL ? "vercel" : process.env.AWS_REGION ? "aws" : "unknown",
sdk: `@upstash/redis@${VERSION}`
});
if (this.enableAutoPipelining) {
return this.autoPipeline();
}
}
|
Create a new redis client by providing a custom `Requester` implementation
@example
```ts
import { UpstashRequest, Requester, UpstashResponse, Redis } from "@upstash/redis"
const requester: Requester = {
request: <TResult>(req: UpstashRequest): Promise<UpstashResponse<TResult>> => {
// ...
}
}
const redis = new Redis(requester)
```
|
constructor
|
javascript
|
vercel/next.js
|
.github/actions/upload-turboyet-data/dist/index.js
|
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
|
MIT
|
static fromEnv(config) {
if (process.env === void 0) {
throw new TypeError(
'[Upstash Redis] Unable to get environment variables, `process.env` is undefined. If you are deploying to cloudflare, please import from "@upstash/redis/cloudflare" instead'
);
}
const url = process.env.UPSTASH_REDIS_REST_URL || process.env.KV_REST_API_URL;
if (!url) {
console.warn("[Upstash Redis] Unable to find environment variable: `UPSTASH_REDIS_REST_URL`");
}
const token = process.env.UPSTASH_REDIS_REST_TOKEN || process.env.KV_REST_API_TOKEN;
if (!token) {
console.warn(
"[Upstash Redis] Unable to find environment variable: `UPSTASH_REDIS_REST_TOKEN`"
);
}
return new _Redis({ ...config, url, token });
}
|
Create a new Upstash Redis instance from environment variables.
Use this to automatically load connection secrets from your environment
variables. For instance when using the Vercel integration.
This tries to load `UPSTASH_REDIS_REST_URL` and `UPSTASH_REDIS_REST_TOKEN` from
your environment using `process.env`.
|
fromEnv
|
javascript
|
vercel/next.js
|
.github/actions/upload-turboyet-data/dist/index.js
|
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
|
MIT
|
async *scanIterator(options) {
let cursor = "0";
let keys;
do {
[cursor, keys] = await this.scan(cursor, options);
for (const key of keys) {
yield key;
}
} while (cursor !== "0");
}
|
Same as `scan` but returns an AsyncIterator to allow iteration via `for await`.
|
scanIterator
|
javascript
|
vercel/next.js
|
.github/actions/upload-turboyet-data/dist/index.js
|
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
|
MIT
|
async *hscanIterator(key, options) {
let cursor = "0";
let items;
do {
[cursor, items] = await this.hscan(key, cursor, options);
for (const item of items) {
yield item;
}
} while (cursor !== "0");
}
|
Same as `hscan` but returns an AsyncIterator to allow iteration via `for await`.
|
hscanIterator
|
javascript
|
vercel/next.js
|
.github/actions/upload-turboyet-data/dist/index.js
|
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
|
MIT
|
async *sscanIterator(key, options) {
let cursor = "0";
let items;
do {
[cursor, items] = await this.sscan(key, cursor, options);
for (const item of items) {
yield item;
}
} while (cursor !== "0");
}
|
Same as `sscan` but returns an AsyncIterator to allow iteration via `for await`.
|
sscanIterator
|
javascript
|
vercel/next.js
|
.github/actions/upload-turboyet-data/dist/index.js
|
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
|
MIT
|
async *zscanIterator(key, options) {
let cursor = "0";
let items;
do {
[cursor, items] = await this.zscan(key, cursor, options);
for (const item of items) {
yield item;
}
} while (cursor !== "0");
}
|
Same as `zscan` but returns an AsyncIterator to allow iteration via `for await`.
|
zscanIterator
|
javascript
|
vercel/next.js
|
.github/actions/upload-turboyet-data/dist/index.js
|
https://github.com/vercel/next.js/blob/master/.github/actions/upload-turboyet-data/dist/index.js
|
MIT
|
TinaProvider = ({ children }) => {
return <TinaCMS {...tinaConfig}>{children}</TinaCMS>;
}
|
@private Do not import this directly, please import the dynamic provider instead
|
TinaProvider
|
javascript
|
vercel/next.js
|
examples/cms-tina/.tina/components/TinaProvider.js
|
https://github.com/vercel/next.js/blob/master/examples/cms-tina/.tina/components/TinaProvider.js
|
MIT
|
async function createCouchbaseCluster() {
if (cached.conn) {
return cached.conn;
}
cached.conn = await couchbase.connect(
"couchbase://" +
COUCHBASE_ENDPOINT +
(IS_CLOUD_INSTANCE === "true"
? "?ssl=no_verify&console_log_level=5"
: ""),
{
username: COUCHBASE_USER,
password: COUCHBASE_PASSWORD,
},
);
return cached.conn;
}
|
Global is used here to maintain a cached connection across hot reloads
in development. This prevents connections growing exponentially
during API Route usage.
|
createCouchbaseCluster
|
javascript
|
vercel/next.js
|
examples/with-couchbase/util/couchbase.js
|
https://github.com/vercel/next.js/blob/master/examples/with-couchbase/util/couchbase.js
|
MIT
|
function getKnex() {
if (!cached.instance) cached.instance = knex(config);
return cached.instance;
}
|
Global is used here to ensure the connection
is cached across hot-reloads in development
see https://github.com/vercel/next.js/discussions/12229#discussioncomment-83372
|
getKnex
|
javascript
|
vercel/next.js
|
examples/with-knex/knex/index.js
|
https://github.com/vercel/next.js/blob/master/examples/with-knex/knex/index.js
|
MIT
|
function MyApp({ Component, pageProps }) {
return (
/* Here we call NextSeo and pass our default configuration to it */
<>
<DefaultSeo {...SEO} />
<Component {...pageProps} />
</>
);
}
|
Using a custom _app.js with next-seo you can set default SEO
that will apply to every page. Full info on how the default works
can be found here: https://github.com/garmeeh/next-seo#default-seo-configuration
|
MyApp
|
javascript
|
vercel/next.js
|
examples/with-next-seo/pages/_app.js
|
https://github.com/vercel/next.js/blob/master/examples/with-next-seo/pages/_app.js
|
MIT
|
async function createUser({ username, password }) {
// Here you should create the user and save the salt and hashed password (some dbs may have
// authentication methods that will do it for you so you don't have to worry about it):
const salt = crypto.randomBytes(16).toString("hex");
const hash = crypto
.pbkdf2Sync(password, salt, 1000, 64, "sha512")
.toString("hex");
const user = {
id: crypto.randomUUID(),
createdAt: Date.now(),
username,
hash,
salt,
};
// This is an in memory store for users, there is no data persistence without a proper DB
users.push(user);
return { username, createdAt: Date.now() };
}
|
User methods. The example doesn't contain a DB, but for real applications you must use a
db here, such as MongoDB, Fauna, SQL, etc.
|
createUser
|
javascript
|
vercel/next.js
|
examples/with-passport/lib/user.js
|
https://github.com/vercel/next.js/blob/master/examples/with-passport/lib/user.js
|
MIT
|
create(context) {
function checkRequireCall(node) {
// Check if this is a require() call
if (
node.type !== 'CallExpression' ||
node.callee.type !== 'Identifier' ||
node.callee.name !== 'require' ||
node.arguments.length !== 1 ||
node.arguments[0].type !== 'Literal'
) {
return
}
const requireSource = node.arguments[0].value
const parent = node.parent
// json is fine because we have resolveJsonModule disabled in our TS project
if (requireSource.endsWith('.json')) {
return
}
// Check if the require is wrapped in a TypeScript assertion
if (parent && parent.type === 'TSAsExpression') {
const typeAnnotation = parent.typeAnnotation
// Check if it's a typeof import() expression
if (
typeAnnotation.type === 'TSTypeQuery' &&
typeAnnotation.exprName.type === 'TSImportType'
) {
const importType = typeAnnotation.exprName
// Check if the import source matches the require source
if (
importType.argument &&
importType.argument.type === 'TSLiteralType' &&
importType.argument.literal.type === 'Literal'
) {
const importSource = importType.argument.literal.value
if (requireSource !== importSource) {
context.report({
node,
messageId: 'mismatchedSource',
data: {
requireSource,
importSource,
},
fix(fixer) {
// importSource as source of truth since that's what's typechecked
// and will be changed by automated refactors.
const newCast = `(require('${importSource}') as typeof import('${importSource}'))`
return fixer.replaceText(parent, newCast)
},
})
}
}
} else {
// Has assertion but not the correct type
context.report({
node: parent,
messageId: 'missingCast',
fix(fixer) {
const newCast = `(require('${requireSource}') as typeof import('${requireSource}'))`
return fixer.replaceText(parent, newCast)
},
})
}
} else {
// No TypeScript assertion at all
context.report({
node,
messageId: 'missingCast',
fix(fixer) {
const newCast = `(require('${requireSource}') as typeof import('${requireSource}'))`
return fixer.replaceText(node, newCast)
},
})
}
}
return {
CallExpression: checkRequireCall,
}
}
|
ESLint rule: typechecked-require
Ensures every require(source) call is cast to typeof import(source)
Source: https://v0.dev/chat/eslint-cast-imports-CDvQ3iWC1Mo
|
create
|
javascript
|
vercel/next.js
|
packages/eslint-plugin-internal/src/eslint-typechecked-require.js
|
https://github.com/vercel/next.js/blob/master/packages/eslint-plugin-internal/src/eslint-typechecked-require.js
|
MIT
|
externalHandler = ({ context, request, getResolve }, callback) => {
;(async () => {
if (
request.match(
/next[/\\]dist[/\\]compiled[/\\](babel|webpack|source-map|semver|jest-worker|stacktrace-parser|@ampproject\/toolbox-optimizer)/
)
) {
callback(null, 'commonjs ' + request)
return
}
if (request.match(/(server\/image-optimizer|experimental\/testmode)/)) {
callback(null, 'commonjs ' + request)
return
}
if (request.endsWith('.external')) {
const resolve = getResolve()
const resolved = await resolve(context, request)
const relative = path.relative(
path.join(__dirname, '..'),
resolved.replace('esm' + path.sep, '')
)
callback(null, `commonjs ${relative}`)
} else {
const regexMatch = Object.keys(externalsRegexMap).find((regex) =>
new RegExp(regex).test(request)
)
if (regexMatch) {
return callback(null, 'commonjs ' + externalsRegexMap[regexMatch])
}
callback()
}
})()
}
|
@param {Object} options
@param {boolean} options.dev
@param {boolean} options.turbo
@param {keyof typeof bundleTypes} options.bundleType
@param {boolean} options.experimental
@param {Partial<webpack.Configuration>} options.rest
@returns {webpack.Configuration}
|
externalHandler
|
javascript
|
vercel/next.js
|
packages/next/next-runtime.webpack-config.js
|
https://github.com/vercel/next.js/blob/master/packages/next/next-runtime.webpack-config.js
|
MIT
|
async function server(task, opts) {
await task
.source('src/server/**/!(*.test).+(js|ts|tsx)')
.swc('server', { dev: opts.dev })
.target('dist/server')
}
|
/!(*.test).+(js|ts|tsx|json)')
.swc('server', { dev: opts.dev })
.target('dist/lib')
}
export async function lib_esm(task, opts) {
await task
.source('src/lib/*
|
server
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
async function api_esm(task, opts) {
await task
.source('src/api/**/*.+(js|mts|ts|tsx)')
.swc('server', { dev: opts.dev, esm: true })
.target('dist/api')
.target('dist/esm/api')
}
|
/!(*.test).+(js|ts|tsx)')
.swc('server', { dev: opts.dev })
.target('dist/server')
}
export async function server_esm(task, opts) {
await task
.source('src/server/*
|
api_esm
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
async function next_devtools_entrypoint(task, opts) {
await task
.source('src/next-devtools/dev-overlay.shim.ts')
.swc('client', { dev: opts.dev, interopClientDefaultExport: true })
.target('dist/next-devtools')
}
|
/!(*.test|*.stories).+(js|ts|tsx|woff2)')
.swc('client', { dev: opts.dev, interopClientDefaultExport: true })
.target('dist/client')
}
export async function client_esm(task, opts) {
await task
.source('src/client/*
|
next_devtools_entrypoint
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
async function next_devtools_shared(task, opts) {
await task
.source(
'src/next-devtools/shared/**/!(*.test|*.stories).+(js|ts|tsx|woff2)'
)
.swc('client', { dev: opts.dev, interopClientDefaultExport: true })
.target('dist/next-devtools/shared')
}
|
/!(*.test|*.stories).+(js|ts|tsx|woff2)'
)
.swc('client', { dev: opts.dev, interopClientDefaultExport: true })
.target('dist/next-devtools/server')
}
export async function next_devtools_server_esm(task, opts) {
await task
.source(
'src/next-devtools/server/*
|
next_devtools_shared
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
async function next_devtools_userspace(task, opts) {
await task
.source(
'src/next-devtools/userspace/**/!(*.test|*.stories).+(js|ts|tsx|woff2)'
)
.swc('client', { dev: opts.dev, interopClientDefaultExport: true })
.target('dist/next-devtools/userspace')
}
|
/!(*.test|*.stories).+(js|ts|tsx|woff2)'
)
.swc('client', { dev: opts.dev, interopClientDefaultExport: true })
.target('dist/next-devtools/shared')
}
export async function next_devtools_shared_esm(task, opts) {
await task
.source(
'src/next-devtools/shared/*
|
next_devtools_userspace
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
async function nextbuildstatic(task, opts) {
await task
.source('src/export/**/!(*.test).+(js|ts|tsx)')
.swc('server', { dev: opts.dev })
.target('dist/export')
}
|
/!(*.test|*.stories).+(js|ts|tsx|woff2)'
)
.swc('client', { dev: opts.dev, interopClientDefaultExport: true })
.target('dist/next-devtools/userspace')
}
export async function next_devtools_userspace_esm(task, opts) {
await task
.source(
'src/next-devtools/userspace/*
|
nextbuildstatic
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
async function pages_app(task, opts) {
await task
.source('src/pages/_app.tsx')
.swc('client', {
dev: opts.dev,
interopClientDefaultExport: true,
})
.target('dist/pages')
}
|
/!(*.test).+(js|ts|tsx)')
.swc('server', { dev: opts.dev })
.target('dist/export')
}
// export is a reserved keyword for functions
export async function nextbuildstatic_esm(task, opts) {
await task
.source('src/export/*
|
pages_app
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
async function diagnostics(task, opts) {
await task
.source('src/diagnostics/**/*.+(js|ts|tsx)')
.swc('server', { dev: opts.dev })
.target('dist/diagnostics')
}
|
/*.+(js|ts|tsx)')
.swc('server', { dev: opts.dev })
.target('dist/telemetry')
}
export async function trace(task, opts) {
await task
.source('src/trace/*
|
diagnostics
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
async function shared_esm(task, opts) {
await task
.source('src/shared/**/*.+(js|ts|tsx)', {
ignore: [
'src/shared/**/{amp,config,constants,dynamic,app-dynamic,head,runtime-config}.+(js|ts|tsx)',
'**/*.test.d.ts',
'**/*.test.+(js|ts|tsx)',
],
})
.swc('client', { dev: opts.dev, esm: true })
.target('dist/esm/shared')
}
|
/{amp,config,constants,dynamic,app-dynamic,head,runtime-config}.+(js|ts|tsx)',
'*
|
shared_esm
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
async function shared_re_exported(task, opts) {
await task
.source(
'src/shared/**/{amp,config,constants,dynamic,app-dynamic,head,runtime-config}.+(js|ts|tsx)',
{
ignore: ['**/*.test.d.ts', '**/*.test.+(js|ts|tsx)'],
}
)
.swc('client', { dev: opts.dev, interopClientDefaultExport: true })
.target('dist/shared')
}
|
/*.+(js|ts|tsx)', {
ignore: [
'src/shared/*
|
shared_re_exported
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
async function shared_re_exported_esm(task, opts) {
await task
.source(
'src/shared/**/{amp,config,constants,app-dynamic,dynamic,head}.+(js|ts|tsx)',
{
ignore: ['**/*.test.d.ts', '**/*.test.+(js|ts|tsx)'],
}
)
.swc('client', {
dev: opts.dev,
esm: true,
})
.target('dist/esm/shared')
}
|
/{amp,config,constants,dynamic,app-dynamic,head,runtime-config}.+(js|ts|tsx)',
{
ignore: ['*
|
shared_re_exported_esm
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
async function server_wasm(task, opts) {
await task.source('src/server/**/*.+(wasm)').target('dist/server')
}
|
/{amp,config,constants,app-dynamic,dynamic,head}.+(js|ts|tsx)',
{
ignore: ['*
|
server_wasm
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
async function experimental_testmode(task, opts) {
await task
.source('src/experimental/testmode/**/!(*.test).+(js|ts|tsx)')
.swc('server', {
dev: opts.dev,
})
.target('dist/experimental/testmode')
}
|
/*.+(wasm)').target('dist/server')
}
export async function experimental_testing(task, opts) {
await task
.source('src/experimental/testing/*
|
experimental_testmode
|
javascript
|
vercel/next.js
|
packages/next/taskfile.js
|
https://github.com/vercel/next.js/blob/master/packages/next/taskfile.js
|
MIT
|
function pluginCreator() {
return {
postcssPlugin: 'postcss-plugin-stub',
prepare() {
return {}
},
}
}
|
This file creates a stub postcss plugin
It will be pre-compiled into "src/compiled/postcss-plugin-stub-for-cssnano-simple",
which "postcss-svgo" will be aliased to when creating "cssnano-preset-simple"
|
pluginCreator
|
javascript
|
vercel/next.js
|
packages/next/src/bundles/postcss-plugin-stub/index.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/bundles/postcss-plugin-stub/index.js
|
MIT
|
get size() {
return this._parsed.size;
}
|
The amount of cookies received from the client
|
size
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/cookies/index.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/cookies/index.js
|
MIT
|
delete(names) {
const map = this._parsed;
const result = !Array.isArray(names) ? map.delete(names) : names.map((name) => map.delete(name));
this._headers.set(
"cookie",
Array.from(map).map(([_, value]) => stringifyCookie(value)).join("; ")
);
return result;
}
|
Delete the cookies matching the passed name or names in the request.
|
delete
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/cookies/index.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/cookies/index.js
|
MIT
|
clear() {
this.delete(Array.from(this._parsed.keys()));
return this;
}
|
Delete all the cookies in the cookies in the request.
|
clear
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/cookies/index.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/cookies/index.js
|
MIT
|
toString() {
return [...this._parsed.values()].map((v) => `${v.name}=${encodeURIComponent(v.value)}`).join("; ");
}
|
Format the cookies in the request as a string for logging
|
toString
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/cookies/index.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/cookies/index.js
|
MIT
|
get(...args) {
const key = typeof args[0] === "string" ? args[0] : args[0].name;
return this._parsed.get(key);
}
|
{@link https://wicg.github.io/cookie-store/#CookieStore-get CookieStore#get} without the Promise.
|
get
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/cookies/index.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/cookies/index.js
|
MIT
|
getAll(...args) {
var _a;
const all = Array.from(this._parsed.values());
if (!args.length) {
return all;
}
const key = typeof args[0] === "string" ? args[0] : (_a = args[0]) == null ? void 0 : _a.name;
return all.filter((c) => c.name === key);
}
|
{@link https://wicg.github.io/cookie-store/#CookieStore-getAll CookieStore#getAll} without the Promise.
|
getAll
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/cookies/index.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/cookies/index.js
|
MIT
|
set(...args) {
const [name, value, cookie] = args.length === 1 ? [args[0].name, args[0].value, args[0]] : args;
const map = this._parsed;
map.set(name, normalizeCookie({ name, value, ...cookie }));
replace(map, this._headers);
return this;
}
|
{@link https://wicg.github.io/cookie-store/#CookieStore-set CookieStore#set} without the Promise.
|
set
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/cookies/index.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/cookies/index.js
|
MIT
|
delete(...args) {
const [name, options] = typeof args[0] === "string" ? [args[0]] : [args[0].name, args[0]];
return this.set({ ...options, name, value: "", expires: /* @__PURE__ */ new Date(0) });
}
|
{@link https://wicg.github.io/cookie-store/#CookieStore-delete CookieStore#delete} without the Promise.
|
delete
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/cookies/index.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/cookies/index.js
|
MIT
|
add(key, value) {
const length = key.length;
if (length === 0) {
throw new TypeError("Unreachable");
}
let index = 0;
let node = this;
while (true) {
const code = key.charCodeAt(index);
if (code > 127) {
throw new TypeError("key must be ascii string");
}
if (node.code === code) {
if (length === ++index) {
node.value = value;
break;
} else if (node.middle !== null) {
node = node.middle;
} else {
node.middle = new _TstNode(key, value, index);
break;
}
} else if (node.code < code) {
if (node.left !== null) {
node = node.left;
} else {
node.left = new _TstNode(key, value, index);
break;
}
} else if (node.right !== null) {
node = node.right;
} else {
node.right = new _TstNode(key, value, index);
break;
}
}
}
|
@param {string} key
@param {any} value
|
add
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
MIT
|
constructor(maxCachedSessions) {
this._maxCachedSessions = maxCachedSessions;
this._sessionCache = /* @__PURE__ */ new Map();
this._sessionRegistry = new global.FinalizationRegistry((key) => {
if (this._sessionCache.size < this._maxCachedSessions) {
return;
}
const ref = this._sessionCache.get(key);
if (ref !== void 0 && ref.deref() === void 0) {
this._sessionCache.delete(key);
}
});
}
|
Exporting for testing purposes only.
Marking as deprecated to discourage any use outside of testing.
@deprecated
|
constructor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
MIT
|
dispatch(opts, handler) {
const headers = buildHeaders(opts.headers);
throwIfProxyAuthIsSent(headers);
if (headers && !("host" in headers) && !("Host" in headers)) {
const { host } = new URL2(opts.origin);
headers.host = host;
}
return this[kAgent].dispatch(
{
...opts,
headers
},
handler
);
}
|
@param {import('../types/proxy-agent').ProxyAgent.Options | string | URL} opts
@returns {URL}
|
dispatch
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
MIT
|
append(name, value, isLowerCase) {
this[kHeadersSortedMap] = null;
const lowercaseName = isLowerCase ? name : name.toLowerCase();
const exists = this[kHeadersMap].get(lowercaseName);
if (exists) {
const delimiter = lowercaseName === "cookie" ? "; " : ", ";
this[kHeadersMap].set(lowercaseName, {
name: exists.name,
value: `${exists.value}${delimiter}${value}`
});
} else {
this[kHeadersMap].set(lowercaseName, { name, value });
}
if (lowercaseName === "set-cookie") {
(this.cookies ??= []).push(value);
}
}
|
@see https://fetch.spec.whatwg.org/#concept-header-list-append
@param {string} name
@param {string} value
@param {boolean} isLowerCase
|
append
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
MIT
|
readAsArrayBuffer(blob) {
webidl.brandCheck(this, _FileReader);
webidl.argumentLengthCheck(arguments, 1, "FileReader.readAsArrayBuffer");
blob = webidl.converters.Blob(blob, { strict: false });
readOperation(this, blob, "ArrayBuffer");
}
|
@see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
@param {import('buffer').Blob} blob
|
readAsArrayBuffer
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
MIT
|
get result() {
webidl.brandCheck(this, _FileReader);
return this[kResult];
}
|
@see https://w3c.github.io/FileAPI/#dom-filereader-result
|
result
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
MIT
|
constructor(options = {}) {
options.readableObjectMode = true;
super(options);
this.state = options.eventSourceSettings || {};
if (options.push) {
this.push = options.push;
}
}
|
@param {object} options
@param {eventSourceSettings} options.eventSourceSettings
@param {Function} [options.push]
|
constructor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
MIT
|
parseLine(line, event) {
if (line.length === 0) {
return;
}
const colonPosition = line.indexOf(COLON);
if (colonPosition === 0) {
return;
}
let field = "";
let value = "";
if (colonPosition !== -1) {
field = line.subarray(0, colonPosition).toString("utf8");
let valueStart = colonPosition + 1;
if (line[valueStart] === SPACE) {
++valueStart;
}
value = line.subarray(valueStart).toString("utf8");
} else {
field = line.toString("utf8");
value = "";
}
switch (field) {
case "data":
if (event[field] === void 0) {
event[field] = value;
} else {
event[field] += `
${value}`;
}
break;
case "retry":
if (isASCIINumber(value)) {
event[field] = value;
}
break;
case "id":
if (isValidLastEventId(value)) {
event[field] = value;
}
break;
case "event":
if (value.length > 0) {
event[field] = value;
}
break;
}
}
|
@param {Buffer} line
@param {EventStreamEvent} event
|
parseLine
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
MIT
|
constructor(url, eventSourceInitDict = {}) {
super();
__privateAdd(this, _connect);
/**
* @see https://html.spec.whatwg.org/multipage/server-sent-events.html#sse-processing-model
* @returns {Promise<void>}
*/
__privateAdd(this, _reconnect);
__privateAdd(this, _events, {
open: null,
error: null,
message: null
});
__privateAdd(this, _url, null);
__privateAdd(this, _withCredentials, false);
__privateAdd(this, _readyState, CONNECTING);
__privateAdd(this, _request, null);
__privateAdd(this, _controller, null);
__privateAdd(this, _dispatcher, void 0);
/**
* @type {import('./eventsource-stream').eventSourceSettings}
*/
__privateAdd(this, _state, void 0);
webidl.util.markAsUncloneable(this);
const prefix = "EventSource constructor";
webidl.argumentLengthCheck(arguments, 1, prefix);
if (!experimentalWarned) {
experimentalWarned = true;
define_process_default.emitWarning("EventSource is experimental, expect them to change at any time.", {
code: "UNDICI-ES"
});
}
url = webidl.converters.USVString(url, prefix, "url");
eventSourceInitDict = webidl.converters.EventSourceInitDict(eventSourceInitDict, prefix, "eventSourceInitDict");
__privateSet(this, _dispatcher, eventSourceInitDict.dispatcher);
__privateSet(this, _state, {
lastEventId: "",
reconnectionTime: defaultReconnectionTime
});
const settings = environmentSettingsObject;
let urlRecord;
try {
urlRecord = new URL(url, settings.settingsObject.baseUrl);
__privateGet(this, _state).origin = urlRecord.origin;
} catch (e) {
throw new DOMException(e, "SyntaxError");
}
__privateSet(this, _url, urlRecord.href);
let corsAttributeState = ANONYMOUS;
if (eventSourceInitDict.withCredentials) {
corsAttributeState = USE_CREDENTIALS;
__privateSet(this, _withCredentials, true);
}
const initRequest = {
redirect: "follow",
keepalive: true,
// @see https://html.spec.whatwg.org/multipage/urls-and-fetching.html#cors-settings-attributes
mode: "cors",
credentials: corsAttributeState === "anonymous" ? "same-origin" : "omit",
referrer: "no-referrer"
};
initRequest.client = environmentSettingsObject.settingsObject;
initRequest.headersList = [["accept", { name: "accept", value: "text/event-stream" }]];
initRequest.cache = "no-store";
initRequest.initiator = "other";
initRequest.urlList = [new URL(__privateGet(this, _url))];
__privateSet(this, _request, makeRequest(initRequest));
__privateMethod(this, _connect, connect_fn).call(this);
}
|
Creates a new EventSource object.
@param {string} url
@param {EventSourceInit} [eventSourceInitDict]
@see https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
|
constructor
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
MIT
|
get readyState() {
return __privateGet(this, _readyState);
}
|
Returns the state of this EventSource object's connection. It can have the
values described below.
@returns {0|1|2}
@readonly
|
readyState
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/@edge-runtime/primitives/fetch.js
|
MIT
|
function createSafeHandler(cb) {
return input => {
const type = getURLType(input);
const base = buildSafeBase(input);
const url = new URL(input, base);
cb(url);
const result = url.toString();
if (type === "absolute") {
return result;
} else if (type === "scheme-relative") {
return result.slice(PROTOCOL.length);
} else if (type === "path-absolute") {
return result.slice(PROTOCOL_AND_HOST.length);
}
// This assumes that the callback will only change
// the path, search and hash values.
return computeRelativeURL(base, result);
};
}
|
Make it easy to create small utilities that tweak a URL's path.
|
createSafeHandler
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function computeRelativeURL(rootURL, targetURL) {
if (typeof rootURL === "string") rootURL = new URL(rootURL);
if (typeof targetURL === "string") targetURL = new URL(targetURL);
const targetParts = targetURL.pathname.split("/");
const rootParts = rootURL.pathname.split("/");
// If we've got a URL path ending with a "/", we remove it since we'd
// otherwise be relative to the wrong location.
if (rootParts.length > 0 && !rootParts[rootParts.length - 1]) {
rootParts.pop();
}
while (
targetParts.length > 0 &&
rootParts.length > 0 &&
targetParts[0] === rootParts[0]
) {
targetParts.shift();
rootParts.shift();
}
const relativePath = rootParts
.map(() => "..")
.concat(targetParts)
.join("/");
return relativePath + targetURL.search + targetURL.hash;
}
|
Given two URLs that are assumed to be on the same
protocol/host/user/password build a relative URL from the
path, params, and hash values.
@param rootURL The root URL that the target will be relative to.
@param targetURL The target that the relative URL points to.
@return A rootURL-relative, normalized URL value.
|
computeRelativeURL
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function join(aRoot, aPath) {
const pathType = getURLType(aPath);
const rootType = getURLType(aRoot);
aRoot = ensureDirectory(aRoot);
if (pathType === "absolute") {
return withBase(aPath, undefined);
}
if (rootType === "absolute") {
return withBase(aPath, aRoot);
}
if (pathType === "scheme-relative") {
return normalize(aPath);
}
if (rootType === "scheme-relative") {
return withBase(aPath, withBase(aRoot, PROTOCOL_AND_HOST)).slice(PROTOCOL.length);
}
if (pathType === "path-absolute") {
return normalize(aPath);
}
if (rootType === "path-absolute") {
return withBase(aPath, withBase(aRoot, PROTOCOL_AND_HOST)).slice(PROTOCOL_AND_HOST.length);
}
const base = buildSafeBase(aPath + aRoot);
const newPath = withBase(aPath, withBase(aRoot, base));
return computeRelativeURL(base, newPath);
}
|
Joins two paths/URLs.
All returned URLs will be normalized.
@param aRoot The root path or URL. Assumed to reference a directory.
@param aPath The path or URL to be joined with the root.
@return A joined and normalized URL value.
|
join
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
function relative(rootURL, targetURL) {
const result = relativeIfPossible(rootURL, targetURL);
return typeof result === "string" ? result : normalize(targetURL);
}
|
Make a path relative to a URL or another path. If returning a
relative URL is not possible, the original target will be returned.
All returned URLs will be normalized.
@param aRoot The root path or URL.
@param aPath The path or URL to be made relative to aRoot.
@return A rootURL-relative (if possible), normalized URL value.
|
relative
|
javascript
|
vercel/next.js
|
packages/next/src/compiled/source-map08/source-map.js
|
https://github.com/vercel/next.js/blob/master/packages/next/src/compiled/source-map08/source-map.js
|
MIT
|
constructor(options = {}) {
this.options = {
shouldIgnorePath: options.shouldIgnorePath ?? defaultShouldIgnorePath,
isSourceMapAsset: options.isSourceMapAsset ?? defaultIsSourceMapAsset,
}
}
|
This plugin adds a field to source maps that identifies which sources are
vendored or runtime-injected (aka third-party) sources. These are consumed by
Chrome DevTools to automatically ignore-list sources.
|
constructor
|
javascript
|
vercel/next.js
|
packages/next/webpack-plugins/devtools-ignore-list-plugin.js
|
https://github.com/vercel/next.js/blob/master/packages/next/webpack-plugins/devtools-ignore-list-plugin.js
|
MIT
|
function loader(value, bindings, callback) {
const defaults = this.sourceMap ? { SourceMapGenerator } : {}
const options = this.getOptions()
const config = { ...defaults, ...options }
const hash = getOptionsHash(options)
const compiler = this._compiler || marker
let map = cache.get(compiler)
if (!map) {
map = new Map()
cache.set(compiler, map)
}
let process = map.get(hash)
if (!process) {
process = createFormatAwareProcessors(
bindings,
coereceMdxTransformOptions(config)
).compile
map.set(hash, process)
}
process({ value, path: this.resourcePath }).then(
(code) => {
// TODO: no sourcemap
callback(null, code, null)
},
(error) => {
const fpath = path.relative(this.context, this.resourcePath)
error.message = `${fpath}:${error.name}: ${error.message}`
callback(error)
}
)
}
|
A webpack loader for mdx-rs. This is largely based on existing @mdx-js/loader,
replaces internal compilation logic to use mdx-rs instead.
|
loader
|
javascript
|
vercel/next.js
|
packages/next-mdx/mdx-rs-loader.js
|
https://github.com/vercel/next.js/blob/master/packages/next-mdx/mdx-rs-loader.js
|
MIT
|
async function getSchedulerVersion(reactVersion) {
const url = `https://registry.npmjs.org/react-dom/${reactVersion}`
const response = await fetch(url, {
headers: {
Accept: 'application/json',
},
})
if (!response.ok) {
throw new Error(
`${url}: ${response.status} ${response.statusText}\n${await response.text()}`
)
}
const manifest = await response.json()
return manifest.dependencies['scheduler']
}
|
Set to `null` to automatically sync the React version of Pages Router with App Router React version.
Set to a specific version to override the Pages Router React version e.g. `^19.0.0`.
"Active" just refers to our current development practice. While we do support
React 18 in pages router, we don't focus our development process on it considering
it does not receive new features.
@type {string | null}
|
getSchedulerVersion
|
javascript
|
vercel/next.js
|
scripts/sync-react.js
|
https://github.com/vercel/next.js/blob/master/scripts/sync-react.js
|
MIT
|
formatUnion = (values) =>
values.map((value) => `"${value}"`).join('|')
|
This is an autogenerated file by scripts/update-google-fonts.js
|
formatUnion
|
javascript
|
vercel/next.js
|
scripts/update-google-fonts.js
|
https://github.com/vercel/next.js/blob/master/scripts/update-google-fonts.js
|
MIT
|
function exec(title, file, args) {
logCommand(title, `${file} ${args.join(' ')}`)
return execa(file, args, {
stderr: 'inherit',
})
}
|
@param title {string}
@param file {string}
@param args {readonly string[]}
@returns {execa.ExecaChildProcess}
|
exec
|
javascript
|
vercel/next.js
|
test/update-bundler-manifest.js
|
https://github.com/vercel/next.js/blob/master/test/update-bundler-manifest.js
|
MIT
|
function logCommand(title, command) {
let message = `\n${bold().underline(title)}\n`
if (command) {
message += `> ${bold(command)}\n`
}
console.log(message)
}
|
@param {string} title
@param {string} [command]
|
logCommand
|
javascript
|
vercel/next.js
|
test/update-bundler-manifest.js
|
https://github.com/vercel/next.js/blob/master/test/update-bundler-manifest.js
|
MIT
|
function accountForOverhead(megaBytes) {
// We are sending {megaBytes} - 5% to account for encoding overhead
return Math.floor(1024 * 1024 * megaBytes * 0.95)
}
|
This function accounts for the overhead of encoding the data to be sent
over the network via a multipart request.
@param {number} megaBytes
@returns {number}
|
accountForOverhead
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/actions/account-for-overhead.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/actions/account-for-overhead.js
|
MIT
|
async function middleware(request) {
if (request.nextUrl.pathname === '/searchparams-normalization-bug') {
const headers = new Headers(request.headers)
headers.set('test', request.nextUrl.searchParams.get('val') || '')
const response = NextResponse.next({
request: {
headers,
},
})
return response
}
if (request.nextUrl.pathname === '/exists-but-not-routed') {
return NextResponse.rewrite(new URL('/dashboard', request.url))
}
if (request.nextUrl.pathname === '/middleware-to-dashboard') {
return NextResponse.rewrite(new URL('/dashboard', request.url))
}
// In dev this route will fail to bootstrap because webpack uses eval which is dissallowed by
// this policy. In production this route will work
if (request.nextUrl.pathname === '/bootstrap/with-nonce') {
const nonce = crypto.randomUUID()
return NextResponse.next({
headers: {
'Content-Security-Policy': `script-src 'nonce-${nonce}' 'strict-dynamic';`,
},
})
}
if (request.nextUrl.pathname.startsWith('/internal/test')) {
const method = request.nextUrl.pathname.endsWith('rewrite')
? 'rewrite'
: 'redirect'
const internal = ['RSC', 'Next-Router-State-Tree']
if (internal.some((name) => request.headers.has(name.toLowerCase()))) {
return NextResponse[method](new URL('/internal/failure', request.url))
}
return NextResponse[method](new URL('/internal/success', request.url))
}
if (request.nextUrl.pathname === '/search-params-prop-middleware-rewrite') {
return NextResponse.rewrite(
new URL(
'/search-params-prop?first=value&second=other%20value&third',
request.url
)
)
}
if (
request.nextUrl.pathname === '/search-params-prop-server-middleware-rewrite'
) {
return NextResponse.rewrite(
new URL(
'/search-params-prop/server?first=value&second=other%20value&third',
request.url
)
)
}
if (request.nextUrl.pathname === '/script-nonce') {
const nonce = crypto.randomUUID()
return NextResponse.next({
headers: {
'content-security-policy': `script-src 'nonce-${nonce}' 'strict-dynamic';`,
},
})
}
if (request.nextUrl.pathname === '/script-nonce/with-next-font') {
const nonce = crypto.randomUUID()
return NextResponse.next({
headers: {
'content-security-policy': `script-src 'nonce-${nonce}' 'strict-dynamic';`,
},
})
}
}
|
@param {import('next/server').NextRequest} request
@returns {Promise<NextResponse | undefined>}
|
middleware
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/app/middleware.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/app/middleware.js
|
MIT
|
async function middleware(request) {
const headersFromRequest = new Headers(request.headers)
// It should be able to import and use `headers` inside middleware
const headersFromNext = await nextHeaders()
headersFromRequest.set('x-from-middleware', 'hello-from-middleware')
// make sure headers() from `next/headers` is behaving properly
if (
headersFromRequest.get('x-from-client') &&
headersFromNext.get('x-from-client') !==
headersFromRequest.get('x-from-client')
) {
throw new Error('Expected headers from client to match')
}
if (request.nextUrl.searchParams.get('draft')) {
;(await draftMode()).enable()
}
const removeHeaders = request.nextUrl.searchParams.get('remove-headers')
if (removeHeaders) {
for (const key of removeHeaders.split(',')) {
headersFromRequest.delete(key)
}
}
const updateHeader = request.nextUrl.searchParams.get('update-headers')
if (updateHeader) {
for (const kv of updateHeader.split(',')) {
const [key, value] = kv.split('=')
headersFromRequest.set(key, value)
}
}
if (request.nextUrl.pathname.includes('/rewrite-to-app')) {
request.nextUrl.pathname = '/headers'
return NextResponse.rewrite(request.nextUrl)
}
if (request.nextUrl.pathname === '/rsc-cookies') {
const res = NextResponse.next()
res.cookies.set('rsc-cookie-value-1', `${Math.random()}`)
res.cookies.set('rsc-cookie-value-2', `${Math.random()}`)
return res
}
if (request.nextUrl.pathname === '/rsc-cookies/cookie-options') {
const res = NextResponse.next()
res.cookies.set('rsc-secure-cookie', `${Math.random()}`, {
secure: true,
httpOnly: true,
})
return res
}
if (request.nextUrl.pathname === '/rsc-cookies-delete') {
const res = NextResponse.next()
res.cookies.delete('rsc-cookie-value-1')
return res
}
if (request.nextUrl.pathname === '/preloads') {
const res = NextResponse.next({
headers: {
link: '<https://example.com/page>; rel="alternate"; hreflang="en"',
},
})
return res
}
return NextResponse.next({
request: {
headers: headersFromRequest,
},
})
}
|
@param {import('next/server').NextRequest} request
|
middleware
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/app-middleware/middleware.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/app-middleware/middleware.js
|
MIT
|
function middleware(request) {
if (
request.nextUrl.pathname ===
'/hooks/use-selected-layout-segment/rewritten-middleware'
) {
return NextResponse.rewrite(
new URL(
'/hooks/use-selected-layout-segment/first/slug3/second/catch/all',
request.url
)
)
}
}
|
@param {import('next/server').NextRequest} request
@returns {NextResponse | undefined}
|
middleware
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/hooks/middleware.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/hooks/middleware.js
|
MIT
|
get() {
return {
waitUntil(/** @type {Promise<any>} */ promise) {
cliLog('waitUntil from "@next/request-context" was called')
promise.catch((err) => {
console.error(err)
})
},
}
}
|
@type {import('next/dist/server/after/builtin-request-context').BuiltinRequestContext}
|
get
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/next-after-app/utils/provided-request-context.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/next-after-app/utils/provided-request-context.js
|
MIT
|
async get(cacheKey, softTags) {
console.log('ModernCustomCacheHandler::get', cacheKey, softTags)
return defaultCacheHandler.get(cacheKey, softTags)
}
|
@type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2}
|
get
|
javascript
|
vercel/next.js
|
test/e2e/app-dir/use-cache-custom-handler/handler.js
|
https://github.com/vercel/next.js/blob/master/test/e2e/app-dir/use-cache-custom-handler/handler.js
|
MIT
|
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
|
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'
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
|
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
|
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
|
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
|
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 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 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 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 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
|
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
|
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 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 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
|
async function loadChunk(source, chunkData) {
if (typeof chunkData === 'string') {
return loadChunkPath(source, chunkData);
}
const includedList = chunkData.included || [];
const modulesPromises = includedList.map((included)=>{
if (moduleFactories[included]) return true;
return availableModules.get(included);
});
if (modulesPromises.length > 0 && modulesPromises.every((p)=>p)) {
// When all included items are already loaded or loading, we can skip loading ourselves
return Promise.all(modulesPromises);
}
const includedModuleChunksList = chunkData.moduleChunks || [];
const moduleChunksPromises = includedModuleChunksList.map((included)=>{
// TODO(alexkirsz) Do we need this check?
// if (moduleFactories[included]) return true;
return availableModuleChunks.get(included);
}).filter((p)=>p);
let promise;
if (moduleChunksPromises.length > 0) {
// Some module chunks are already loaded or loading.
if (moduleChunksPromises.length === includedModuleChunksList.length) {
// When all included module chunks are already loaded or loading, we can skip loading ourselves
return Promise.all(moduleChunksPromises);
}
const moduleChunksToLoad = new Set();
for (const moduleChunk of includedModuleChunksList){
if (!availableModuleChunks.has(moduleChunk)) {
moduleChunksToLoad.add(moduleChunk);
}
}
for (const moduleChunkToLoad of moduleChunksToLoad){
const promise = loadChunkPath(source, moduleChunkToLoad);
availableModuleChunks.set(moduleChunkToLoad, promise);
moduleChunksPromises.push(promise);
}
promise = Promise.all(moduleChunksPromises);
} else {
promise = loadChunkPath(source, chunkData.path);
// Mark all included module chunks as loading if they are not already loaded or loading.
for (const includedModuleChunk of includedModuleChunksList){
if (!availableModuleChunks.has(includedModuleChunk)) {
availableModuleChunks.set(includedModuleChunk, promise);
}
}
}
for (const included of includedList){
if (!availableModules.has(included)) {
// It might be better to race old and new promises, but it's rare that the new promise will be faster than a request started earlier.
// In production it's even more rare, because the chunk optimization tries to deduplicate modules anyway.
availableModules.set(included, promise);
}
}
return promise;
}
|
Map from a chunk path to the chunk lists it belongs to.
|
loadChunk
|
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 createResolvePathFromModule(resolver) {
return function resolvePathFromModule(moduleId) {
const exported = resolver(moduleId);
return exported?.default ?? exported;
};
}
|
Returns an absolute url to an asset.
|
createResolvePathFromModule
|
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 resolveAbsolutePath(modulePath) {
return `/ROOT/${modulePath ?? ''}`;
}
|
no-op for browser
@param modulePath
|
resolveAbsolutePath
|
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 getWorkerBlobURL(chunks) {
// It is important to reverse the array so when bootstrapping we can infer what chunk is being
// evaluated by poping urls off of this array. See `getPathFromScript`
let bootstrap = `self.TURBOPACK_WORKER_LOCATION = ${JSON.stringify(location.origin)};
self.TURBOPACK_NEXT_CHUNK_URLS = ${JSON.stringify(chunks.reverse().map(getChunkRelativeUrl), null, 2)};
importScripts(...self.TURBOPACK_NEXT_CHUNK_URLS.map(c => self.TURBOPACK_WORKER_LOCATION + c).reverse());`;
let blob = new Blob([
bootstrap
], {
type: 'text/javascript'
});
return URL.createObjectURL(blob);
}
|
Returns a blob URL for the worker.
@param chunks list of chunks to load
|
getWorkerBlobURL
|
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 getFirstModuleChunk(moduleId) {
const moduleChunkPaths = moduleChunksMap.get(moduleId);
if (moduleChunkPaths == null) {
return null;
}
return moduleChunkPaths.values().next().value;
}
|
Returns the first chunk that included a module.
This is used by the Node.js backend, hence why it's marked as unused in this
file.
|
getFirstModuleChunk
|
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 getChunkRelativeUrl(chunkPath) {
return `${CHUNK_BASE_PATH}${chunkPath.split('/').map((p)=>encodeURIComponent(p)).join('/')}${CHUNK_SUFFIX_PATH}`;
}
|
Returns the URL relative to the origin where a chunk can be fetched from.
|
getChunkRelativeUrl
|
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 registerChunk([chunkScript, chunkModules, runtimeParams]) {
const chunkPath = getPathFromScript(chunkScript);
for (const [moduleId, moduleFactory] of Object.entries(chunkModules)){
if (!moduleFactories[moduleId]) {
moduleFactories[moduleId] = moduleFactory;
}
addModuleToChunk(moduleId, chunkPath);
}
return BACKEND.registerChunk(chunkPath, runtimeParams);
}
|
Marks a chunk list as a runtime chunk list. There can be more than one
runtime chunk list. For instance, integration tests can have multiple chunk
groups loaded at runtime, each with its own chunk list.
|
registerChunk
|
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 isCss(chunkUrl) {
return regexCssUrl.test(chunkUrl);
}
|
Checks if a given path/URL ends with .css, optionally followed by ?query or #fragment.
|
isCss
|
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
|
constructor(message, dependencyChain){
super(message);
this.dependencyChain = dependencyChain;
}
|
This file contains runtime types and functions that are shared between all
Turbopack *development* ECMAScript runtimes.
It will be appended to the runtime code of each runtime right after the
shared runtime utils.
|
constructor
|
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.