diff --git a/crates/next-api/src/server_actions.rs b/crates/next-api/src/server_actions.rs index cd5a58504393..e7f55f8b119c 100644 --- a/crates/next-api/src/server_actions.rs +++ b/crates/next-api/src/server_actions.rs @@ -634,10 +634,10 @@ async fn module_hash( } else { None }; - let code = chunk_item.code(async_info); + let factory = chunk_item.code(async_info).await?; RcStr::from(deterministic_hash( "", - (ident_str, code.source_code_hash().await?), + (ident_str, factory.code.to_code().source_code_hash().await?), HashAlgorithm::Xxh3Hash128Hex, )) } else { diff --git a/docs/01-app/02-guides/upgrading/codemods.mdx b/docs/01-app/02-guides/upgrading/codemods.mdx index 7bfb3ffcdbaf..4d4740afa2e3 100644 --- a/docs/01-app/02-guides/upgrading/codemods.mdx +++ b/docs/01-app/02-guides/upgrading/codemods.mdx @@ -76,12 +76,13 @@ npx @next/codemod upgrade canary --yes npx @next/codemod@canary cache-components-instant-false ./app ``` -This codemod adds `export const instant = false` to every `{page,layout,default}` file in your app directory that doesn't already export `instant`, so you can enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) and then remove the opt-outs route by route. It skips Client Components (`"use client"`) and files that already declare `instant`. +This codemod adds `export const instant = false` to every `{page,layout,default}` file in your app directory that doesn't already export `instant`, so you can enable [`cacheComponents`](/docs/app/api-reference/config/next-config-js/cacheComponents) and then remove the opt-outs route by route. It skips Client Components (`"use client"`) and files that already declare `instant`. The generated `@next-codemod-ignore` comment marks the intentional opt-out without blocking compilation. > **Good to know**: Pass `./src/app` in a `src/` project. A wrong path reports `0 ok` instead of failing, so check the file count. ```diff filename="app/page.tsx" -+ // TODO: Cache Components adoption. Refactor this route so this opt-out can be removed. ++ // @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking. ++ // Remove this opt-out after verifying the segment passes validation without it. + // See: https://nextjs.org/docs/app/guides/migrating-to-cache-components + export const instant = false + @@ -291,7 +292,9 @@ npx @next/codemod@latest next-async-request-api . ``` This codemod will transform dynamic APIs (`cookies()`, `headers()` and `draftMode()` from `next/headers`) that are now asynchronous to be properly awaited or wrapped with `React.use()` if applicable. -When an automatic migration isn't possible, the codemod will either add a typecast (if a TypeScript file) or a comment to inform the user that it needs to be manually reviewed & updated. +When automatic migration isn't possible, the codemod adds an `@next-codemod-error` comment and may add a temporary `UnsafeUnwrapped*` cast. Complete the migration before removing them. If the suggested change doesn't apply, replace the directive with `@next-codemod-ignore` and explain why. + +See the [Async Request APIs migration guide](/docs/app/guides/upgrading/version-15#async-request-apis-breaking-change) for examples. For example: @@ -323,7 +326,9 @@ import { type UnsafeUnwrappedCookies, type UnsafeUnwrappedHeaders, } from 'next/headers' -const token = (cookies() as unknown as UnsafeUnwrappedCookies).get('token') +const token = + /* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedCookies cast after repairing the migration. */ + (cookies() as unknown as UnsafeUnwrappedCookies).get('token') function useToken() { const token = use(cookies()).get('token') @@ -335,7 +340,10 @@ export default async function Page() { } function getHeader() { - return (headers() as unknown as UnsafeUnwrappedHeaders).get('x-foo') + return ( + /* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */ + (headers() as unknown as UnsafeUnwrappedHeaders).get('x-foo') + ) } ``` diff --git a/lerna.json b/lerna.json index 5c789e98fa56..8a33ac382421 100644 --- a/lerna.json +++ b/lerna.json @@ -15,5 +15,5 @@ "registry": "https://registry.npmjs.org/" } }, - "version": "16.4.0-canary.28" + "version": "16.4.0-canary.29" } \ No newline at end of file diff --git a/packages/create-next-app/package.json b/packages/create-next-app/package.json index 10c361a32366..446678322ef3 100644 --- a/packages/create-next-app/package.json +++ b/packages/create-next-app/package.json @@ -1,6 +1,6 @@ { "name": "create-next-app", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "keywords": [ "react", "next", diff --git a/packages/devlow-bench/package.json b/packages/devlow-bench/package.json index f19244f15e05..a6512c74098e 100644 --- a/packages/devlow-bench/package.json +++ b/packages/devlow-bench/package.json @@ -1,6 +1,6 @@ { "name": "@vercel/devlow-bench", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "description": "Benchmarking tool for the developer workflow", "repository": { "type": "git", diff --git a/packages/eslint-config-next/package.json b/packages/eslint-config-next/package.json index 45be3bf66b61..7159fc02a8ea 100644 --- a/packages/eslint-config-next/package.json +++ b/packages/eslint-config-next/package.json @@ -1,6 +1,6 @@ { "name": "eslint-config-next", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "description": "ESLint configuration used by Next.js.", "license": "MIT", "repository": { @@ -12,7 +12,7 @@ "dist" ], "dependencies": { - "@next/eslint-plugin-next": "16.4.0-canary.28", + "@next/eslint-plugin-next": "16.4.0-canary.29", "eslint-import-resolver-node": "^0.3.6", "eslint-import-resolver-typescript": "^3.5.2", "eslint-plugin-import": "^2.32.0", diff --git a/packages/eslint-plugin-internal/package.json b/packages/eslint-plugin-internal/package.json index 317fb2744403..c9c64325c132 100644 --- a/packages/eslint-plugin-internal/package.json +++ b/packages/eslint-plugin-internal/package.json @@ -1,7 +1,7 @@ { "name": "@next/eslint-plugin-internal", "private": true, - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "description": "ESLint plugin for working on Next.js.", "exports": { ".": "./src/eslint-plugin-internal.js" diff --git a/packages/eslint-plugin-next/package.json b/packages/eslint-plugin-next/package.json index 08b74e20e1d7..0cc8f492c6b0 100644 --- a/packages/eslint-plugin-next/package.json +++ b/packages/eslint-plugin-next/package.json @@ -1,6 +1,6 @@ { "name": "@next/eslint-plugin-next", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "description": "ESLint plugin for Next.js.", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/packages/font/package.json b/packages/font/package.json index 308348cba0cc..c71404deddee 100644 --- a/packages/font/package.json +++ b/packages/font/package.json @@ -1,7 +1,7 @@ { "name": "@next/font", "private": true, - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "repository": { "url": "vercel/next.js", "directory": "packages/font" diff --git a/packages/next-bundle-analyzer/package.json b/packages/next-bundle-analyzer/package.json index 683f32225c08..19204551a132 100644 --- a/packages/next-bundle-analyzer/package.json +++ b/packages/next-bundle-analyzer/package.json @@ -1,6 +1,6 @@ { "name": "@next/bundle-analyzer", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "main": "index.js", "types": "index.d.ts", "license": "MIT", diff --git a/packages/next-codemod/README.md b/packages/next-codemod/README.md index 32f1b96a0fd7..43bb42f98200 100644 --- a/packages/next-codemod/README.md +++ b/packages/next-codemod/README.md @@ -7,3 +7,14 @@ Codemods are transformations that run on your codebase programmatically. This al ## Documentation Visit [nextjs.org/docs/advanced-features/codemods](https://nextjs.org/docs/app/guides/upgrading/codemods) to view the documentation for this package. + +## Skip optional feature adoption + +`upgrade --skip-adoption` skips codemods marked as feature adoption in the +registry while keeping version migrations and normal dependency selection. +Currently this excludes `cache-components-instant-false` and the +`remove-partial-prefetch` cleanup used after adopting partial prefetching. +Both transforms can still be run explicitly. + +Combine it with `--yes` for an unattended version upgrade. Without +`--skip-adoption`, the existing upgrade selections are unchanged. diff --git a/packages/next-codemod/bin/next-codemod.ts b/packages/next-codemod/bin/next-codemod.ts index 367412ee26fe..d0a378f3bbf9 100644 --- a/packages/next-codemod/bin/next-codemod.ts +++ b/packages/next-codemod/bin/next-codemod.ts @@ -70,6 +70,11 @@ program 'Skip every interactive prompt and accept its default. Also auto-enabled when stdin is not a TTY (e.g. running under an agent or in CI).', false ) + .option( + '--skip-adoption', + 'Skip optional feature-adoption codemods while applying version migrations.', + false + ) .action(async (revision, options) => { try { await runUpgrade(revision, options) diff --git a/packages/next-codemod/bin/upgrade.ts b/packages/next-codemod/bin/upgrade.ts index cca79d83bbc0..5818213886b4 100644 --- a/packages/next-codemod/bin/upgrade.ts +++ b/packages/next-codemod/bin/upgrade.ts @@ -113,7 +113,7 @@ function resolveSemanticRevision( export async function runUpgrade( revision: string | undefined, - options: { verbose: boolean; yes?: boolean } + options: { verbose: boolean; yes?: boolean; skipAdoption?: boolean } ): Promise { const { verbose } = options const nonInteractive = options.yes === true || !process.stdin.isTTY @@ -272,7 +272,8 @@ export async function runUpgrade( const codemods = await suggestCodemods( installedNextVersion, targetNextVersion, - nonInteractive + nonInteractive, + options.skipAdoption ) const packageManager: PackageManager = getPkgManager(cwd) @@ -641,7 +642,8 @@ async function suggestTurbopack( async function suggestCodemods( initialNextVersion: string, targetNextVersion: string, - nonInteractive: boolean + nonInteractive: boolean, + skipAdoption = false ): Promise { // example: // codemod version: 15.0.0-canary.45 @@ -670,7 +672,7 @@ async function suggestCodemods( const relevantCodemods = TRANSFORMER_INQUIRER_CHOICES.slice( initialVersionIndex, targetVersionIndex - ) + ).filter((codemod) => !skipAdoption || !codemod.adoption) if (relevantCodemods.length === 0) { return [] diff --git a/packages/next-codemod/lib/utils.ts b/packages/next-codemod/lib/utils.ts index c9cc09539669..c6fa67428dc0 100644 --- a/packages/next-codemod/lib/utils.ts +++ b/packages/next-codemod/lib/utils.ts @@ -1,6 +1,9 @@ import { yellow } from 'picocolors' import isGitClean from 'is-git-clean' +export const NEXT_CODEMOD_ERROR_PREFIX = '@next-codemod-error' +export const NEXT_CODEMOD_IGNORE_ERROR_PREFIX = '@next-codemod-ignore' + export function checkGitStatus(force) { let clean = false let errorMessage = 'Unable to determine if git directory is clean' @@ -148,11 +151,13 @@ export const TRANSFORMER_INQUIRER_CHOICES = [ 'Add `export const instant = false` to App Router pages and layouts to ease Cache Components adoption', value: 'cache-components-instant-false', version: '16.3.0', + adoption: true, }, { title: "Remove `export const prefetch = 'partial'` Route Segment Config from App Router pages and layouts after enabling `partialPrefetching` globally", value: 'remove-partial-prefetch', version: '16.3.0', + adoption: true, }, ] diff --git a/packages/next-codemod/package.json b/packages/next-codemod/package.json index 20cad814c49c..f8b0bbf8d744 100644 --- a/packages/next-codemod/package.json +++ b/packages/next-codemod/package.json @@ -1,6 +1,6 @@ { "name": "@next/codemod", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "license": "MIT", "repository": { "type": "git", diff --git a/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/basic-default.output.tsx b/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/basic-default.output.tsx index babd4c3af036..243ed4f897dd 100644 --- a/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/basic-default.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/basic-default.output.tsx @@ -1,5 +1,6 @@ // @ts-nocheck -// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed. +// @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking. +// Remove this opt-out after verifying the segment passes validation without it. // See: https://nextjs.org/docs/app/guides/migrating-to-cache-components export const instant = false; diff --git a/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/basic-layout.output.tsx b/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/basic-layout.output.tsx index 2057a49ee2d2..5667f0e63ce1 100644 --- a/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/basic-layout.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/basic-layout.output.tsx @@ -1,5 +1,6 @@ // @ts-nocheck -// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed. +// @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking. +// Remove this opt-out after verifying the segment passes validation without it. // See: https://nextjs.org/docs/app/guides/migrating-to-cache-components export const instant = false; diff --git a/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/basic-page.output.tsx b/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/basic-page.output.tsx index ffd6b9312136..a9eb93921070 100644 --- a/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/basic-page.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/basic-page.output.tsx @@ -1,5 +1,6 @@ // @ts-nocheck -// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed. +// @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking. +// Remove this opt-out after verifying the segment passes validation without it. // See: https://nextjs.org/docs/app/guides/migrating-to-cache-components export const instant = false; diff --git a/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/jsdoc-leading.output.tsx b/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/jsdoc-leading.output.tsx index ce9a11815332..d16e5c9496fa 100644 --- a/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/jsdoc-leading.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/jsdoc-leading.output.tsx @@ -3,7 +3,8 @@ * A page with a leading JSDoc banner. * The opt-out must be appended after this block, not inside it. */ -// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed. +// @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking. +// Remove this opt-out after verifying the segment passes validation without it. // See: https://nextjs.org/docs/app/guides/migrating-to-cache-components export const instant = false; diff --git a/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/multiline-imports.output.tsx b/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/multiline-imports.output.tsx index 8ba3d6d1f01d..3fda733800a6 100644 --- a/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/multiline-imports.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/multiline-imports.output.tsx @@ -8,7 +8,8 @@ import { bar, } from './lib' -// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed. +// @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking. +// Remove this opt-out after verifying the segment passes validation without it. // See: https://nextjs.org/docs/app/guides/migrating-to-cache-components export const instant = false; diff --git a/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/with-imports.output.tsx b/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/with-imports.output.tsx index 0ed7138d9db6..4dc0ea4e1462 100644 --- a/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/with-imports.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/cache-components-instant-false/with-imports.output.tsx @@ -2,7 +2,8 @@ import { Suspense } from 'react' import { foo } from './bar' -// TODO: Cache Components adoption. Refactor this route so this opt-out can be removed. +// @next-codemod-ignore Cache Components adoption: this segment temporarily allows blocking. +// Remove this opt-out after verifying the segment passes validation without it. // See: https://nextjs.org/docs/app/guides/migrating-to-cache-components export const instant = false; diff --git a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-05.output.tsx b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-05.output.tsx index 6b0c35247451..bc77314b094a 100644 --- a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-05.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-05.output.tsx @@ -2,7 +2,8 @@ import { use } from "react"; import { draftMode, type UnsafeUnwrappedDraftMode } from 'next/headers'; export function MyComponent2() { - (draftMode() as unknown as UnsafeUnwrappedDraftMode).enable() + (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedDraftMode cast after repairing the migration. */ + draftMode() as unknown as UnsafeUnwrappedDraftMode).enable() } export function useDraftModeEnabled() { diff --git a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-07.output.tsx b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-07.output.tsx index b0d19f30d7a4..823b7a4bf332 100644 --- a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-07.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-07.output.tsx @@ -2,5 +2,6 @@ import { draftMode, type UnsafeUnwrappedDraftMode } from 'next/headers' export function MyComponent2() { - (draftMode() as unknown as UnsafeUnwrappedDraftMode).enable() + (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedDraftMode cast after repairing the migration. */ + draftMode() as unknown as UnsafeUnwrappedDraftMode).enable() } diff --git a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-10.output.tsx b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-10.output.tsx index 7af01fa129a5..50bb93e82946 100644 --- a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-10.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-10.output.tsx @@ -1,13 +1,16 @@ import { headers, type UnsafeUnwrappedHeaders } from 'next/headers'; export function MyComp() { - return (headers() as unknown as UnsafeUnwrappedHeaders); + return (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */ + headers() as unknown as UnsafeUnwrappedHeaders); } export function MyComp2() { - return (headers() as unknown as UnsafeUnwrappedHeaders); + return (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */ + headers() as unknown as UnsafeUnwrappedHeaders); } export function MyComp3() { - return (headers() as unknown as UnsafeUnwrappedHeaders); + return (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */ + headers() as unknown as UnsafeUnwrappedHeaders); } diff --git a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-11.output.tsx b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-11.output.tsx index b317adc58030..99ae03fd2055 100644 --- a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-11.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-11.output.tsx @@ -1,10 +1,12 @@ import { headers, type UnsafeUnwrappedHeaders } from 'next/headers'; export function MyComp() { - void (headers() as unknown as UnsafeUnwrappedHeaders) + void (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */ + headers() as unknown as UnsafeUnwrappedHeaders) } export function generateContentfulMetadata() { - void (headers() as unknown as UnsafeUnwrappedHeaders) + void (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */ + headers() as unknown as UnsafeUnwrappedHeaders) } diff --git a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-19.output.tsx b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-19.output.tsx index 39476c888899..a928aac50bf1 100644 --- a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-19.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-19.output.tsx @@ -8,6 +8,7 @@ export function myFun() { export function myFun2() { return function () { - void (headers() as unknown as UnsafeUnwrappedHeaders) + void (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */ + headers() as unknown as UnsafeUnwrappedHeaders) }; } diff --git a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-25.output.tsx b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-25.output.tsx index bd162864fc3a..47369dbc721d 100644 --- a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-25.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-25.output.tsx @@ -1,6 +1,8 @@ import { cookies, type UnsafeUnwrappedCookies } from 'next/headers'; export function myFunc() { - const c = (cookies() as unknown as UnsafeUnwrappedCookies) - void (cookies() as unknown as UnsafeUnwrappedCookies) + const c = (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedCookies cast after repairing the migration. */ + cookies() as unknown as UnsafeUnwrappedCookies) + void (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedCookies cast after repairing the migration. */ + cookies() as unknown as UnsafeUnwrappedCookies) } diff --git a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-type-cast-01.output.tsx b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-type-cast-01.output.tsx index f950e53e6f96..85c0190e015d 100644 --- a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-type-cast-01.output.tsx +++ b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/async-api-type-cast-01.output.tsx @@ -9,7 +9,8 @@ import { } from 'next/headers'; export function MyDraftComponent() { - if ((draftMode() as unknown as UnsafeUnwrappedDraftMode).isEnabled) { + if ((/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedDraftMode cast after repairing the migration. */ + draftMode() as unknown as UnsafeUnwrappedDraftMode).isEnabled) { return null } @@ -17,12 +18,14 @@ export function MyDraftComponent() { } export function MyCookiesComponent() { - const c = (cookies() as unknown as UnsafeUnwrappedCookies) + const c = (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedCookies cast after repairing the migration. */ + cookies() as unknown as UnsafeUnwrappedCookies) return c.get('name') } export function MyHeadersComponent() { - const h = (headers() as unknown as UnsafeUnwrappedHeaders) + const h = (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedHeaders cast after repairing the migration. */ + headers() as unknown as UnsafeUnwrappedHeaders) return

{h.get('x-foo')}

} diff --git a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/origin-name-01-util.output.ts b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/origin-name-01-util.output.ts index 165d15948a7f..b0a11af52de8 100644 --- a/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/origin-name-01-util.output.ts +++ b/packages/next-codemod/transforms/__testfixtures__/next-async-request-api-dynamic-apis/origin-name-01-util.output.ts @@ -1,6 +1,7 @@ import { cookies, type UnsafeUnwrappedCookies } from 'next/headers'; export default function Foo(): string { - const name = (cookies() as unknown as UnsafeUnwrappedCookies).get('name') + const name = (/* @next-codemod-error Await this API and update its callers; remove the temporary UnsafeUnwrappedCookies cast after repairing the migration. */ + cookies() as unknown as UnsafeUnwrappedCookies).get('name') return name } diff --git a/packages/next-codemod/transforms/__tests__/next-async-request-api-dynamic-apis.test.js b/packages/next-codemod/transforms/__tests__/next-async-request-api-dynamic-apis.test.js index 9892ff2aee20..59c0feb0c4b2 100644 --- a/packages/next-codemod/transforms/__tests__/next-async-request-api-dynamic-apis.test.js +++ b/packages/next-codemod/transforms/__tests__/next-async-request-api-dynamic-apis.test.js @@ -67,3 +67,31 @@ describe('next-async-request-api - dynamic-apis', () => { }) } }) + +describe('unfinished async migration markers', () => { + const transform = require('../next-async-request-api').default + const j = require('jscodeshift').withParser('tsx') + const apply = source => transform({ path: 'lib/viewer.ts', source }, { jscodeshift: j, j }, {}) + + it('marks contextual helper repair and does not duplicate it on a second pass', () => { + const source = "import { cookies } from 'next/headers'; export function readViewer() { return cookies().get('viewer')?.value }" + const once = apply(source) + expect(once).toContain('@next-codemod-error') + expect(once).toContain('UnsafeUnwrappedCookies') + const twice = apply(once) || once + expect((twice.match(/@next-codemod-error/g) || []).length).toBe(1) + expect((twice.match(/as unknown as UnsafeUnwrappedCookies/g) || []).length).toBe(1) + }) + + it('preserves an explicitly documented ignore on a repeated pass', () => { + const source = "import { cookies, type UnsafeUnwrappedCookies } from 'next/headers'; export function readViewer() { return (/* @next-codemod-ignore Verified exception in fixture. */ cookies() as unknown as UnsafeUnwrappedCookies).get('viewer')?.value }" + const output = apply(source) || source + expect(output).toContain('@next-codemod-ignore') + expect(output).not.toContain('@next-codemod-error') + }) + + it('uses the same marker for a dynamic import requiring contextual review', () => { + const output = apply("export async function readViewer() { const { cookies } = await import('next/headers'); return cookies().get('viewer') }") + expect(output).toContain('@next-codemod-error') + }) +}) diff --git a/packages/next-codemod/transforms/cache-components-instant-false.ts b/packages/next-codemod/transforms/cache-components-instant-false.ts index bdb8a351c9d5..f8863808570f 100644 --- a/packages/next-codemod/transforms/cache-components-instant-false.ts +++ b/packages/next-codemod/transforms/cache-components-instant-false.ts @@ -1,5 +1,6 @@ import type { API, FileInfo } from 'jscodeshift' import { createParserFromPath } from '../lib/parser' +import { NEXT_CODEMOD_IGNORE_ERROR_PREFIX } from '../lib/utils' /** * Blanket-inserts `export const instant = false` into every App Router `page`, @@ -104,11 +105,16 @@ export default function transformer(file: FileInfo, _api: API) { return file.source } - // Build `export const instant = false`. The two `//` comments above it - // (TODO + See:) are attached as leading comments on the declaration so + // Build `export const instant = false`. The ignore reason, removal condition, + // and guide link are attached as leading comments on the declaration so // recast prints them right above it. - const todoComment = j.commentLine( - ' TODO: Cache Components adoption. Refactor this route so this opt-out can be removed.', + const ignoreComment = j.commentLine( + ` ${NEXT_CODEMOD_IGNORE_ERROR_PREFIX} Cache Components adoption: this segment temporarily allows blocking.`, + true, + false + ) + const removalComment = j.commentLine( + ' Remove this opt-out after verifying the segment passes validation without it.', true, false ) @@ -122,7 +128,7 @@ export default function transformer(file: FileInfo, _api: API) { j.variableDeclarator(j.identifier('instant'), j.booleanLiteral(false)), ]) ) - instantExport.comments = [todoComment, seeComment] + instantExport.comments = [ignoreComment, removalComment, seeComment] // Insert after the last top-level import, or at the top of the module // if there are no imports. @@ -138,14 +144,19 @@ export default function transformer(file: FileInfo, _api: API) { // No imports. Inserting at index 0 would steal any file-level leading // comments (e.g. `// @ts-nocheck`) from `body[0]` because recast // attributes them to whatever is first. Move those leading comments - // off `body[0]` onto the new export *before* its TODO/See: lines, so + // off `body[0]` onto the new export *before* its adoption comments, so // they print in their original position. const first = body[0] const allComments = (first.comments ?? []) as any[] const firstLeading = allComments.filter((c) => c.leading === true) if (firstLeading.length > 0) { first.comments = allComments.filter((c) => c.leading !== true) - instantExport.comments = [...firstLeading, todoComment, seeComment] + instantExport.comments = [ + ...firstLeading, + ignoreComment, + removalComment, + seeComment, + ] } body.unshift(instantExport) } else { diff --git a/packages/next-codemod/transforms/lib/async-request-api/next-async-dynamic-api.ts b/packages/next-codemod/transforms/lib/async-request-api/next-async-dynamic-api.ts index 5298052066f7..439c0fc97ff9 100644 --- a/packages/next-codemod/transforms/lib/async-request-api/next-async-dynamic-api.ts +++ b/packages/next-codemod/transforms/lib/async-request-api/next-async-dynamic-api.ts @@ -10,14 +10,14 @@ import { wrapParentheseIfNeeded, insertCommentOnce, NEXTJS_ENTRY_FILES, - NEXT_CODEMOD_ERROR_PREFIX, containsReactHooksCallExpressions, isParentUseCallExpression, isReactHookName, } from './utils' import { createParserFromPath } from '../../../lib/parser' +import { NEXT_CODEMOD_ERROR_PREFIX } from '../../../lib/utils' -const DYNAMIC_IMPORT_WARN_COMMENT = ` @next-codemod-error The APIs under 'next/headers' are async now, need to be manually awaited. ` +const DYNAMIC_IMPORT_WARN_COMMENT = ` ${NEXT_CODEMOD_ERROR_PREFIX} The APIs under 'next/headers' are async now, need to be manually awaited. ` function findDynamicImportsAndComment(root: Collection, j: API['j']) { let modified = false @@ -331,6 +331,20 @@ function castTypesOrAddComment( */ const targetType = API_CAST_TYPE_MAP[originRequestApiName] + const repairComment = ` ${NEXT_CODEMOD_ERROR_PREFIX} Await this API and update its callers; remove the temporary ${targetType} cast after repairing the migration. ` + const parentCast = path.parentPath?.node + const outerCast = path.parentPath?.parentPath?.node + if ( + j.TSAsExpression.check(parentCast) && + j.TSAsExpression.check(outerCast) && + j.TSTypeReference.check(outerCast.typeAnnotation) && + j.Identifier.check(outerCast.typeAnnotation.typeName) && + outerCast.typeAnnotation.typeName.name === targetType + ) { + // Re-parsing attaches the leading marker to the outer cast. + return insertCommentOnce(outerCast, j, repairComment) + } + insertCommentOnce(path.node, j, repairComment) const newCastExpression = j.tsAsExpression( j.tsAsExpression(path.node, j.tsUnknownKeyword()), diff --git a/packages/next-codemod/transforms/lib/async-request-api/next-async-dynamic-prop.ts b/packages/next-codemod/transforms/lib/async-request-api/next-async-dynamic-prop.ts index 64a8eb121179..02e69f5040bb 100644 --- a/packages/next-codemod/transforms/lib/async-request-api/next-async-dynamic-prop.ts +++ b/packages/next-codemod/transforms/lib/async-request-api/next-async-dynamic-prop.ts @@ -20,7 +20,6 @@ import { TARGET_ROUTE_EXPORTS, getVariableDeclaratorId, NEXTJS_ENTRY_FILES, - NEXT_CODEMOD_ERROR_PREFIX, findFunctionBody, containsReactHooksCallExpressions, isParentUseCallExpression, @@ -28,6 +27,7 @@ import { findClosetParentFunctionScope, } from './utils' import { createParserFromPath } from '../../../lib/parser' +import { NEXT_CODEMOD_ERROR_PREFIX } from '../../../lib/utils' const PAGE_PROPS = 'props' diff --git a/packages/next-codemod/transforms/lib/async-request-api/utils.ts b/packages/next-codemod/transforms/lib/async-request-api/utils.ts index a4cc0f76ed88..9752fae93fc7 100644 --- a/packages/next-codemod/transforms/lib/async-request-api/utils.ts +++ b/packages/next-codemod/transforms/lib/async-request-api/utils.ts @@ -17,8 +17,10 @@ export type FunctionScope = | FunctionExpression | ArrowFunctionExpression -export const NEXT_CODEMOD_ERROR_PREFIX = '@next-codemod-error' -const NEXT_CODEMOD_IGNORE_ERROR_PREFIX = '@next-codemod-ignore' +import { + NEXT_CODEMOD_ERROR_PREFIX, + NEXT_CODEMOD_IGNORE_ERROR_PREFIX, +} from '../../../lib/utils' export const TARGET_ROUTE_EXPORTS = new Set([ 'GET', diff --git a/packages/next-codemod/transforms/new-link.ts b/packages/next-codemod/transforms/new-link.ts index 3bfe69ae526d..61846969f937 100644 --- a/packages/next-codemod/transforms/new-link.ts +++ b/packages/next-codemod/transforms/new-link.ts @@ -3,7 +3,7 @@ import type { API, Collection, FileInfo, JSXElement } from 'jscodeshift' import { createParserFromPath } from '../lib/parser' -import { NEXT_CODEMOD_ERROR_PREFIX } from './lib/async-request-api/utils' +import { NEXT_CODEMOD_ERROR_PREFIX } from '../lib/utils' export default function transformer(file: FileInfo, _api: API) { const j = createParserFromPath(file.path) diff --git a/packages/next-env/package.json b/packages/next-env/package.json index 38922f79151d..6842c2d461c8 100644 --- a/packages/next-env/package.json +++ b/packages/next-env/package.json @@ -1,6 +1,6 @@ { "name": "@next/env", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "keywords": [ "react", "next", diff --git a/packages/next-mdx/package.json b/packages/next-mdx/package.json index 815ed6aac63b..2bc5d3c85e38 100644 --- a/packages/next-mdx/package.json +++ b/packages/next-mdx/package.json @@ -1,6 +1,6 @@ { "name": "@next/mdx", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "main": "index.js", "license": "MIT", "repository": { diff --git a/packages/next-playwright/package.json b/packages/next-playwright/package.json index 7c0833d61824..a8516a44d679 100644 --- a/packages/next-playwright/package.json +++ b/packages/next-playwright/package.json @@ -1,6 +1,6 @@ { "name": "@next/playwright", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "repository": { "url": "vercel/next.js", "directory": "packages/next-playwright" diff --git a/packages/next-plugin-storybook/package.json b/packages/next-plugin-storybook/package.json index 75b1539cb060..c4971c937ce9 100644 --- a/packages/next-plugin-storybook/package.json +++ b/packages/next-plugin-storybook/package.json @@ -1,6 +1,6 @@ { "name": "@next/plugin-storybook", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "repository": { "url": "vercel/next.js", "directory": "packages/next-plugin-storybook" diff --git a/packages/next-polyfill-module/package.json b/packages/next-polyfill-module/package.json index e07c0ba224f8..2a3530b434c2 100644 --- a/packages/next-polyfill-module/package.json +++ b/packages/next-polyfill-module/package.json @@ -1,6 +1,6 @@ { "name": "@next/polyfill-module", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "description": "A standard library polyfill for ES Modules supporting browsers (Edge 16+, Firefox 60+, Chrome 61+, Safari 10.1+)", "main": "dist/polyfill-module.js", "license": "MIT", diff --git a/packages/next-polyfill-nomodule/package.json b/packages/next-polyfill-nomodule/package.json index b9b1caed8ba4..8bda59cef610 100644 --- a/packages/next-polyfill-nomodule/package.json +++ b/packages/next-polyfill-nomodule/package.json @@ -1,6 +1,6 @@ { "name": "@next/polyfill-nomodule", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "description": "A polyfill for non-dead, nomodule browsers.", "main": "dist/polyfill-nomodule.js", "license": "MIT", diff --git a/packages/next-routing/package.json b/packages/next-routing/package.json index 3668c5dd85c0..91196068bee8 100644 --- a/packages/next-routing/package.json +++ b/packages/next-routing/package.json @@ -1,6 +1,6 @@ { "name": "@next/routing", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "keywords": [ "react", "next", diff --git a/packages/next-rspack/package.json b/packages/next-rspack/package.json index 400cb6cb8019..74d99ac61b80 100644 --- a/packages/next-rspack/package.json +++ b/packages/next-rspack/package.json @@ -1,6 +1,6 @@ { "name": "next-rspack", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "repository": { "url": "vercel/next.js", "directory": "packages/next-rspack" diff --git a/packages/next-swc/package.json b/packages/next-swc/package.json index 30b1bdcab797..00baff0332ca 100644 --- a/packages/next-swc/package.json +++ b/packages/next-swc/package.json @@ -1,6 +1,6 @@ { "name": "@next/swc", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "private": true, "files": [ "native/" diff --git a/packages/next/package.json b/packages/next/package.json index 39a59b33f0b0..85bf8abe6009 100644 --- a/packages/next/package.json +++ b/packages/next/package.json @@ -1,6 +1,6 @@ { "name": "next", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "description": "The React Framework", "main": "./dist/server/next.js", "license": "MIT", @@ -100,7 +100,7 @@ ] }, "dependencies": { - "@next/env": "16.4.0-canary.28", + "@next/env": "16.4.0-canary.29", "@swc/helpers": "0.5.23", "baseline-browser-mapping": "^2.9.19", "caniuse-lite": "^1.0.30001579", @@ -162,13 +162,13 @@ "@jest/transform": "29.5.0", "@jest/types": "29.5.0", "@modelcontextprotocol/sdk": "1.18.1", - "@mswjs/interceptors": "0.42.0", + "@mswjs/interceptors": "0.42.5", "@napi-rs/triples": "1.2.0", - "@next/font": "16.4.0-canary.28", - "@next/polyfill-module": "16.4.0-canary.28", - "@next/polyfill-nomodule": "16.4.0-canary.28", - "@next/react-refresh-utils": "16.4.0-canary.28", - "@next/swc": "16.4.0-canary.28", + "@next/font": "16.4.0-canary.29", + "@next/polyfill-module": "16.4.0-canary.29", + "@next/polyfill-nomodule": "16.4.0-canary.29", + "@next/react-refresh-utils": "16.4.0-canary.29", + "@next/swc": "16.4.0-canary.29", "@opentelemetry/api": "1.6.0", "@playwright/test": "1.61.0", "@rspack/core": "1.6.7", diff --git a/packages/next/src/compiled/@mswjs/interceptors/ClientRequest/index.js b/packages/next/src/compiled/@mswjs/interceptors/ClientRequest/index.js index 9836a5682ba6..e787a8f82952 100644 --- a/packages/next/src/compiled/@mswjs/interceptors/ClientRequest/index.js +++ b/packages/next/src/compiled/@mswjs/interceptors/ClientRequest/index.js @@ -1 +1 @@ -(function(){var e={349:function(e,t,s){if(typeof Promise.withResolvers!=="function"){Promise.withResolvers=s(252).createPromiseWithResolvers}e.exports=s(1)},252:function(e){"use strict";e.exports=require("next/dist/shared/lib/promise-with-resolvers")},1:function(e,t,s){"use strict";s.r(t);s.d(t,{ClientRequestInterceptor:function(){return qe}});var r=class{#e;#t;constructor(){this.#e=[];this.#t=new Map}get[Symbol.iterator](){return this.#e[Symbol.iterator].bind(this.#e)}entries(){return this.#t.entries()}get(e){return this.#t.get(e)||[]}getAll(){return this.#e.map((([,e])=>e))}append(e,t){this.#e.push([e,t]);this.#s(e,(e=>e.push(t)))}prepend(e,t){this.#e.unshift([e,t]);this.#s(e,(e=>e.unshift(t)))}delete(e,t){if(this.size===0)return false;const s=this.#t.get(e);if(!s)return false;const r=s.indexOf(t);if(r===-1)return false;s.splice(r,1);this.#e.splice(this.#e.findIndex((s=>s[0]===e&&s[1]===t)),1);return true}deleteAll(e){if(this.size===0)return;this.#e=this.#e.filter((t=>t[0]!==e));this.#t.delete(e)}get size(){return this.#e.length}clear(){if(this.size===0)return;this.#e.length=0;this.#t.clear()}#s(e,t){t(this.#t.get(e)||this.#t.set(e,[]).get(e))}};const o=Symbol("kDefaultPrevented");const n=Symbol("kPropagationStopped");const i=Symbol("kImmediatePropagationStopped");var a=class extends MessageEvent{#r;[o];[n];[i];constructor(...e){super(e[0],e[1]);this[o]=false}get defaultPrevented(){return this[o]}preventDefault(){super.preventDefault();this[o]=true}stopImmediatePropagation(){super.stopImmediatePropagation();this[i]=true}};var c=class{#o;#n;#i;#a;#c;#l;#u;hooks;constructor(){this.#o=new r;this.#n=new WeakMap;this.#i=new WeakMap;this.#a=new WeakSet;this.#c=new r;this.#l=new WeakMap;this.#u=new WeakMap;this.hooks={on:(e,t,s)=>{if(s?.signal?.aborted)return;if(s?.once){const s=t;const wrapper=(...t)=>{this.#h(e,wrapper);return s(...t)};t=wrapper}this.#c.append(e,t);if(s)this.#l.set(t,s);if(s?.signal){const{signal:r}=s;const onAbort=()=>{this.#h(e,t)};r.addEventListener("abort",onAbort,{once:true});this.#u.set(t,(()=>{r.removeEventListener("abort",onAbort)}))}},removeListener:(e,t)=>{this.#h(e,t)}}}#h(e,t){this.#c.delete(e,t);const s=this.#u.get(t);if(s){s();this.#u.delete(t)}}#d(e,t){const s=this.#o.delete(e,t);const r=this.#i.get(t);if(r){r();this.#i.delete(t)}return s}on(e,t,s){this.#p(e,t,s);return this}once(e,t,s){return this.on(e,t,{...s||{},once:true})}earlyOn(e,t,s){this.#p(e,t,s,"prepend");return this}earlyOnce(e,t,s){return this.earlyOn(e,t,{...s||{},once:true})}emit(e){if(this.#o.size===0)return false;const t=this.listenerCount(e.type)>0;const s=this.#f(e);for(const t of this.#E(e.type)){if(s.event[n]!=null&&s.event[n]!==this){s.revoke();return false}if(s.event[i])break;this.#T(s.event,t)}s.revoke();return t}async emitAsPromise(e){if(this.#o.size===0)return[];const t=[];const s=this.#f(e);for(const r of this.#E(e.type)){if(s.event[n]!=null&&s.event[n]!==this){s.revoke();return[]}if(s.event[i])break;const e=await Promise.resolve(this.#T(s.event,r));if(!this.#R(r))t.push(e)}s.revoke();return Promise.allSettled(t).then((e=>e.map((e=>e.status==="fulfilled"?e.value:e.reason))))}*emitAsGenerator(e){if(this.#o.size===0)return;const t=this.#f(e);for(const s of this.#E(e.type)){if(t.event[n]!=null&&t.event[n]!==this){t.revoke();return}if(t.event[i])break;const e=this.#T(t.event,s);if(!this.#R(s))yield e}t.revoke()}removeListener(e,t){const s=this.#n.get(t);if(!this.#d(e,t))return;for(const r of this.#c.get("removeListener").slice())r(e,t,s)}removeAllListeners(e){if(e==null){for(const[e,t]of this.#o.entries())while(t.length>0)this.removeListener(e,t[0]);for(const[e,t]of[...this.#c])if(!this.#l.get(t)?.persist)this.#h(e,t);return}const t=this.listeners(e);while(t.length>0)this.removeListener(e,t[0])}listeners(e){if(e==null)return this.#o.getAll();return this.#o.get(e)}listenerCount(e){if(e==null)return this.#o.size;return this.listeners(e).length}#p(e,t,s,r="append"){if(s?.signal?.aborted)return;for(const r of this.#c.get("newListener").slice())r(e,t,s);if(e==="*")this.#a.add(t);if(r==="prepend")this.#o.prepend(e,t);else this.#o.append(e,t);if(s){this.#n.set(t,s);if(s.signal){const{signal:r}=s;const onAbort=()=>{this.removeListener(e,t)};r.addEventListener("abort",onAbort,{once:true});this.#i.set(t,(()=>{r.removeEventListener("abort",onAbort)}))}}}#f(e){const{stopPropagation:t}=e;e.stopPropagation=()=>{e[n]=this;t.call(e)};return{event:e,revoke(){e.stopPropagation=t}}}#T(e,t){for(const t of this.#c.get("beforeEmit").slice())if(t(e)===false)return;const s=t.call(this,e);const r=this.#n.get(t);if(r?.once){const s=this.#R(t)?"*":e.type;if(this.#d(s,t))for(const e of this.#c.get("removeListener").slice())e(s,t,r)}return s}*#E(e){const t=[];for(const[s,r]of this.#o)if(s==="*"||s===e)t.push(r);yield*t}#R(e){return this.#a.has(e)}};var l=require("next/dist/compiled/debug");var u=class{constructor(){this.subscriptions=[]}dispose(){let e;while(e=this.subscriptions.pop())e()}};const h=/\d{2}:\d{2}:\d{2}\.\d{3}/;function normalizeNamespace(e){return e.split(":").map((e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-|-$/g,"").toLowerCase())).filter(Boolean).join(":")}function getTimestamp(){return(new Date).toISOString().slice(11,23)}async function readBody(e){if(e.body==null)return null;try{return await e.clone().text()}catch{return null}}function formatHeaders(e){return Array.from(e.entries()).map((([e,t])=>`${e}: ${t}`))}async function formatHttpMessage(e,t){const s=[e,...formatHeaders(t.headers)];const r=await readBody(t);s.push("",r??"");return s.join("\n")}async function formatRequest(e){return formatHttpMessage(`${e.method} ${e.url}`,e)}async function formatResponse(e){const t=e.statusText?` ${e.statusText}`:"";return formatHttpMessage(`HTTP ${e.status}${t}`,e)}function formatLogArguments(e){const t=e[0];if(typeof t==="string"){const s=t.replace(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z /,"");const r=s.match(h);if(!r||r.index===void 0){e[0]=s;return}const o=s.slice(0,r.index).trim();const n=s.slice(r.index+r[0].length).trimStart();e[0]=`${r[0]} ${o} ${n}`}}function useConciseTimestamp(e){e.log=(...e)=>{formatLogArguments(e);l.log(...e)}}function isVerboseLoggingEnabled(){if(typeof process!=="undefined"&&process.env.DEBUG_LEVEL==="verbose")return true;if(typeof document==="undefined")return false;try{return globalThis.localStorage?.getItem("debugLevel")==="verbose"}catch{return false}}function createLogger(e){const t=l(`interceptors:${normalizeNamespace(e)}`);Reflect.set(t,"useColors",true);useConciseTimestamp(t);return{info(e,...s){t(`${getTimestamp()} ${e}`,...s)},verbose(e,...s){if(!isVerboseLoggingEnabled())return;t(`${getTimestamp()} ${e}`,...s)},isEnabled(e){return t.enabled&&(e==="default"||isVerboseLoggingEnabled())}}}const d=globalThis.__MSW_INTERCEPTORS_REGISTRY??=new Map;var p=class extends u{#S;static singleton(e){const t=e.symbol;const s=d.get(t);if(s instanceof e)return s;const r=new e;d.set(t,r);return r}constructor(){super();this.on=(e,t,s)=>this.emitter.on(e,t,s);this.once=(e,t,s)=>this.emitter.once(e,t,s);this.listeners=e=>this.emitter.listeners(e);this.listenerCount=e=>this.emitter.listenerCount(e);this.removeListener=(e,t)=>this.emitter.removeListener(e,t);this.removeAllListeners=e=>{this.logger.info("removeAllListeners %o",{eventType:e??"*"});return this.emitter.removeAllListeners(e)};this.#S=new Set;this.readyState="INACTIVE";this.emitter=new c;this.logger=createLogger(this.#_())}apply(e=this){if(this.#S.has(e))return;if(this.readyState!=="ACTIVE"&&!this.predicate())return;this.#S.add(e);if(this.readyState==="ACTIVE")return;try{this.setup();this.readyState="ACTIVE";this.logger.info("apply")}catch(t){this.dispose(e);throw t}}dispose(e=this){if(!this.#S.delete(e))return;if(this.#S.size>0)return;super.dispose();this.emitter.removeAllListeners();this.readyState="DISPOSED";this.logger.info("disable")}#_(){const e=this.constructor.symbol?.description;if(e)return e.replace(/-interceptor$/,"");return this.constructor.name.replace(/Interceptor$/,"")}};const f=new TextEncoder;function encodeBuffer(e){return f.encode(e)}function decodeBuffer(e,t){return new TextDecoder(t).decode(e)}function toBuffer(e,t){if(Buffer.isBuffer(e))return e;if(e instanceof Uint8Array)return Buffer.from(e.buffer);return Buffer.from(e,t)}var E=/(%?)(%([sdijo]))/g;function serializePositional(e,t){switch(t){case"s":return e;case"d":case"i":return Number(e);case"j":return JSON.stringify(e);case"o":{if(typeof e==="string"){return e}const t=JSON.stringify(e);if(t==="{}"||t==="[]"||/^\[object .+?\]$/.test(t)){return e}return t}}}function format(e,...t){if(t.length===0){return e}let s=0;let r=e.replace(E,((e,r,o,n)=>{const i=t[s];const a=serializePositional(i,n);if(!r){s++;return a}return e}));if(s{if(!e){throw new R(t,...s)}};invariant.as=(e,t,s,...r)=>{if(!t){const t=r.length===0?s:format(s,...r);let o;try{o=Reflect.construct(e,[t])}catch(s){o=e(t)}throw o}};var S=class InterceptorError extends Error{constructor(e){super(e);this.name="InterceptorError";Object.setPrototypeOf(this,InterceptorError.prototype)}};var _=class RequestController{static{this.PENDING=0}static{this.PASSTHROUGH=1}static{this.RESPONSE=2}static{this.ERROR=3}#A;constructor(e,t,s){this.request=e;this.source=t;this.options=s;this.readyState=RequestController.PENDING;this.#A=Promise.withResolvers();this.handled=this.#A.promise}async passthrough(){invariant.as(S,this.readyState===RequestController.PENDING,'Failed to passthrough the "%s %s" request: the request has already been handled',this.request.method,this.request.url);this.readyState=RequestController.PASSTHROUGH;if(this.options)this.options.logger.info("[%s] passthrough",this.options.requestId);await this.source.passthrough();this.#A.resolve()}respondWith(e){invariant.as(S,this.readyState===RequestController.PENDING,'Failed to respond to the "%s %s" request with "%d %s": the request has already been handled (%d)',this.request.method,this.request.url,e.status,e.statusText||"OK",this.readyState);this.readyState=RequestController.RESPONSE;if(this.options?.logger.isEnabled("default")){const{logger:t,requestId:s}=this.options;formatResponse(e).then((e=>{t.info("[%s] mocked %s",s,e)}))}this.#A.resolve();this.source.respondWith(e)}errorWith(e){invariant.as(S,this.readyState===RequestController.PENDING,'Failed to error the "%s %s" request with "%s": the request has already been handled (%d)',this.request.method,this.request.url,e?.toString(),this.readyState);this.readyState=RequestController.ERROR;if(this.options)this.options.logger.info("[%s] error %o",this.options.requestId,e);this.source.errorWith(e);this.#A.resolve()}};function createRequestId(){return Math.random().toString(16).slice(2)}const A=Symbol("kRawHeaders");const g=Symbol("kRestorePatches");function recordRawHeader(e,t,s){ensureRawHeadersSymbol(e,[]);const r=Reflect.get(e,A);if(s==="set"){for(let e=r.length-1;e>=0;e--)if(r[e][0].toLowerCase()===t[0].toLowerCase())r.splice(e,1)}r.push(t)}function ensureRawHeadersSymbol(e,t){if(Reflect.has(e,A))return;defineRawHeadersSymbol(e,t)}function defineRawHeadersSymbol(e,t){Object.defineProperty(e,A,{value:t,enumerable:false,configurable:true})}function recordRawFetchHeaders(){if(Reflect.get(Headers,g))return Reflect.get(Headers,g);const{Headers:e,Request:t,Response:s}=globalThis;const{set:r,append:o,delete:n}=Headers.prototype;Object.defineProperty(Headers,g,{value:()=>{Headers.prototype.set=r;Headers.prototype.append=o;Headers.prototype.delete=n;globalThis.Headers=e;globalThis.Request=t;globalThis.Response=s;Object.setPrototypeOf(m,t);Object.setPrototypeOf(m.prototype,t.prototype);Object.setPrototypeOf(N,s);Object.setPrototypeOf(N.prototype,s.prototype);Reflect.deleteProperty(Headers,g)},enumerable:false,configurable:true});Object.defineProperty(globalThis,"Headers",{enumerable:true,writable:true,value:new Proxy(Headers,{construct(e,t,s){const r=t[0]||[];if(r instanceof Headers&&Reflect.has(r,A)){const t=Reflect.get(r,A).map((e=>[e[0],e[1]]));const o=Reflect.construct(e,[t],s);ensureRawHeadersSymbol(o,[...t]);return o}const o=Reflect.construct(e,t,s);if(!Reflect.has(o,A))ensureRawHeadersSymbol(o,Array.isArray(r)?r:Object.entries(r));return o}})});Headers.prototype.set=new Proxy(Headers.prototype.set,{apply(e,t,s){recordRawHeader(t,[s[0],s[1]],"set");return Reflect.apply(e,t,s)}});Headers.prototype.append=new Proxy(Headers.prototype.append,{apply(e,t,s){recordRawHeader(t,[s[0],s[1]],"append");return Reflect.apply(e,t,s)}});Headers.prototype.delete=new Proxy(Headers.prototype.delete,{apply(e,t,s){const r=Reflect.get(t,A);if(r){for(let e=r.length-1;e>=0;e--)if(r[e][0].toLowerCase()===s[0].toLowerCase())r.splice(e,1)}return Reflect.apply(e,t,s)}});Object.defineProperty(globalThis,"Request",{enumerable:true,writable:true,value:new Proxy(Request,{construct(e,t,s){const r=Reflect.construct(e,t,s);const o=[];if(typeof t[0]==="object"&&t[0].headers!=null)o.push(...inferRawHeaders(t[0].headers));if(typeof t[1]==="object"&&t[1].headers!=null)o.push(...inferRawHeaders(t[1].headers));if(o.length>0)ensureRawHeadersSymbol(r.headers,o);return r}})});Object.defineProperty(globalThis,"Response",{enumerable:true,writable:true,value:new Proxy(Response,{construct(e,t,s){const r=Reflect.construct(e,t,s);if(typeof t[1]==="object"&&t[1].headers!=null)ensureRawHeadersSymbol(r.headers,inferRawHeaders(t[1].headers));return r}})});Object.setPrototypeOf(m,globalThis.Request);Object.setPrototypeOf(m.prototype,globalThis.Request.prototype);Object.setPrototypeOf(N,globalThis.Response);Object.setPrototypeOf(N.prototype,globalThis.Response.prototype);return restoreHeadersPrototype}function restoreHeadersPrototype(){if(!Reflect.get(Headers,g))return;Reflect.get(Headers,g)()}function getRawFetchHeaders(e){if(!Reflect.has(e,A))return Array.from(e.entries());const t=Reflect.get(e,A);return t.length>0?t:Array.from(e.entries())}function inferRawHeaders(e){if(e instanceof Headers)return Reflect.get(e,A)||[];return Reflect.get(new Headers(e),A)}function copyRawHeaders(e,t){const s=[...getRawFetchHeaders(e)];if(s.length===0)return;for(const[e,r]of t)if(s.every((t=>t[0].toLowerCase()!==e.toLowerCase())))s.push([e,r]);defineRawHeadersSymbol(t,s)}function getValueBySymbol(e,t){const s=Object.getOwnPropertySymbols(t).find((t=>t.description===e));if(s)return Reflect.get(t,s)}function isObject(e,t=false){return t?Object.prototype.toString.call(e).startsWith("[object "):Object.prototype.toString.call(e)==="[object Object]"}function isPropertyAccessible(e,t){try{e[t];return true}catch{return false}}function createServerErrorResponse(e){return new Response(JSON.stringify(e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e),{status:500,statusText:"Unhandled Exception",headers:{"Content-Type":"application/json"}})}const O=Symbol("kErrorResponse");function getErrorResponse(e){if(e instanceof Error&&O in e&&isResponseError(e[O]))return e[O]}function isResponseError(e){return e!=null&&e instanceof Response&&isPropertyAccessible(e,"type")&&e.type==="error"}function isResponseLike(e){return isObject(e,true)&&isPropertyAccessible(e,"status")&&isPropertyAccessible(e,"statusText")&&isPropertyAccessible(e,"bodyUsed")}var m=class FetchRequest extends Request{static#g(e,t={},s){return t[s]??(e instanceof Request?e[s]:void 0)}static isConfigurableMethod(e){return e!=="CONNECT"&&e!=="TRACE"&&e!=="TRACK"}static isMethodWithBody(e){return e!=="HEAD"&&e!=="GET"&&FetchRequest.isConfigurableMethod(e)}static isConfigurableMode(e){return e!=="navigate"&&e!=="websocket"&&e!=="webtransport"}constructor(e,t){const s=FetchRequest.#g(e,t,"method")||"GET";const r=FetchRequest.isConfigurableMethod(s)?s:"GET";const o=t!=null&&"body"in t;const n=!FetchRequest.isMethodWithBody(s)?{body:void 0}:o?{body:t.body}:{};const i=FetchRequest.#g(e,t,"mode")??void 0;const a=FetchRequest.isConfigurableMode(i)?i:void 0;super(e,{...t||{},method:r,mode:a,duplex:t?.duplex??(FetchRequest.isMethodWithBody(s)?"half":void 0),...n});if(s!==r)this.#O("method",s);if(s==="CONNECT"){const t=new URL(e instanceof Request?e.url:e);let s;if(t.protocol==="localhost:")s=t.href;else s=t.pathname.replace(/^\/+/,"");Object.defineProperty(this,"url",{get:()=>s,enumerable:true,configurable:true})}if(i!=null&&i!==a)this.#O("mode",i)}#O(e,t){const s=getValueBySymbol("state",this);if(s)Reflect.set(s,e,t);else Object.defineProperty(this,e,{value:t,enumerable:true,configurable:true,writable:false})}};const y=Symbol("kStatus");const C=Symbol("kUrl");var N=class FetchResponse extends Response{static from(e,t){if(e instanceof FetchResponse)return e;if(isResponseError(e))return e;const s=new FetchResponse(e.body,{url:t?.url??e.url,status:t?.status||e.status,statusText:t?.statusText??e.statusText,headers:t?.headers??e.headers});copyRawHeaders(e.headers,s.headers);return s}static{this.STATUS_CODES_WITHOUT_BODY=[101,103,204,205,304]}static{this.STATUS_CODES_WITH_REDIRECT=[301,302,303,307,308]}static isConfigurableStatusCode(e){return e>=200&&e<=599}static isRedirectResponse(e){return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(e)}static isResponseWithBody(e){return!FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(e)}static setStatus(e,t){const s=getValueBySymbol("state",t);if(s)s.status=e;else Object.defineProperty(t,"status",{value:e,enumerable:true,configurable:true,writable:false});Object.defineProperty(t,y,{value:e,enumerable:false})}static setUrl(e,t){if(!e||e==="about:"||!URL.canParse(e))return;const s=getValueBySymbol("state",t);if(s)s.urlList.push(new URL(e));else Object.defineProperty(t,"url",{value:e,enumerable:true,configurable:true,writable:false});Object.defineProperty(t,C,{value:e,enumerable:false})}static parseRawHeaders(e){const t=new Headers;for(let s=0;s{}}if(o.descriptor.configurable)Object.defineProperty(e,t,{value:s(e[t]),enumerable:true,configurable:true});else if(o.descriptor.writable)e[t]=s(e[t]);else throw new Error(`Failed to patch a non-configurable non-writable property "${t.toString()}"`);const restorePatch=()=>{const s=this.#C.get(e);if(!s?.has(t))return;if(o.owner===e)Object.defineProperty(o.owner,t,o.descriptor);else Reflect.deleteProperty(e,t);s.delete(t);if(s.size===0)this.#C.delete(e)};if(r)r.set(t,restorePatch);else this.#C.set(e,new Map([[t,restorePatch]]));return restorePatch}restoreAllPatches(){const e=[];for(const[,t]of this.#C)for(const[,s]of t)try{s()}catch(t){if(t instanceof Error)e.push(t);else throw t}if(e.length>0)throw new AggregateError(e,"FOO!")}};const H=new I;function getDeepPropertyDescriptor(e,t){let s=e;let r;while(s){r=Object.getOwnPropertyDescriptor(s,t);if(r)return{owner:s,descriptor:r};s=Object.getPrototypeOf(s)}}function normalizeNetConnectArgs(e){if(e.length===0)return[{path:""},null];const t=typeof e[1]==="function"?e[1]:e[2]||null;if(typeof e[0]==="string")return[{path:e[0]},t];if(typeof e[0]==="number")return[{port:e[0],path:"",host:typeof e[1]==="string"?e[1]:void 0},t];if(typeof e[0]==="object"){if("port"in e[0])return[{path:"",port:Reflect.get(e[0],"port"),host:Reflect.get(e[0],"host"),auth:Reflect.get(e[0],"auth"),family:Reflect.get(e[0],"family"),hints:Reflect.get(e[0],"hints"),session:Reflect.get(e[0],"session"),localAddress:Reflect.get(e[0],"localAddress"),localPort:Reflect.get(e[0],"localPort"),timeout:Reflect.get(e[0],"timeout"),lookup:Reflect.get(e[0],"lookup"),allowHalfOpen:Reflect.get(e[0],"allowHalfOpen"),noDelay:Reflect.get(e[0],"noDelay"),keepAlive:Reflect.get(e[0],"keepAlive"),keepAliveInitialDelay:Reflect.get(e[0],"keepAliveInitialDelay"),autoSelectFamily:Reflect.get(e[0],"autoSelectFamily"),autoSelectFamilyAttemptTimeout:Reflect.get(e[0],"autoSelectFamilyAttemptTimeout")},t];return[{path:e[0].path||"",family:Reflect.get(e[0],"family"),session:Reflect.get(e[0],"session"),auth:Reflect.get(e[0],"auth"),timeout:Reflect.get(e[0],"timeout"),allowHalfOpen:Reflect.get(e[0],"allowHalfOpen")},t]}throw new Error(`Invalid arguments passed to net.connect: ${e}`)}function writePendingData(e,t,s,r){if(Array.isArray(t)){for(let s=0;se.description==="connect-options"));if(t==null)return;return Reflect.get(e,t)}function getAddressInfoByConnectionOptions(e){if(e==null)return{};const t=e.family===6||k.isIPv6(e.host||"");return{address:t?"::1":"127.0.0.1",port:Number(e.port)||(e.protocol==="https:"?443:80),family:t?"IPv6":"IPv4"}}function getLocalAddressInfoByConnectionOptions(e){if(e==null)return{};const t=e.family===6||k.isIPv6(e.host||"");return{address:e.localAddress||(t?"::1":"127.0.0.1"),port:e.localPort||getEphemeralPort(),family:t?"IPv6":"IPv4"}}function getEphemeralPort(){return 49152+Math.floor(Math.random()*16384)}const D=Symbol("kListenerWrap");const L=Symbol("kRawSocket");const w=Symbol("kPatched");const v=createLogger("socket");function toServerSocket(e){const t=[];let s;let r=false;let o=false;const flushPendingWrites=()=>{if(e.connecting){r=true;if(!o){o=true;e.once("ready",(()=>{o=false;flushPendingWrites()}))}return false}while(t.length>0){const s=t.shift();e._unrefTimer();const o=e.push(toBuffer(s.chunk,s.encoding),s.encoding);s.callback?.();if(!o){r=true;return false}}const n=r;r=false;if(s){const t=s;s=void 0;if(t.chunk!=null)e.push(toBuffer(t.chunk,t.encoding),t.encoding);e.push(null);t.callback?.()}if(n)e.emit("internal:drain");return true};const n=e._read.bind(e);e._read=e=>{n(e);if(t.length>0||s!=null||r)flushPendingWrites()};return new Proxy(e,{get:(e,o,n)=>{const getRealValue=()=>Reflect.get(e,o,n);if(o==="on"||o==="addListener"||o==="once"||o==="prependListener"||o==="prependOnceListener"){const t=getRealValue();return(s,r)=>{if(s==="data"){const listenerWrap=(e,t)=>{r(toBuffer(e,t))};Object.defineProperty(r,D,{enumerable:false,writable:false,value:listenerWrap});Reflect.apply(t,e,["internal:write",listenerWrap]);return e}if(s==="drain"){Reflect.apply(t,e,["internal:drain",r]);return e}return t.call(e,s,r)}}if(o==="off"||o==="removeListener"){const t=getRealValue();return(s,r)=>{if(s==="data"){const s=r[D];if(s)return t.call(e,"internal:write",s)}if(s==="drain")return t.call(e,"internal:drain",r);return t.call(e,s,r)}}if(o==="write")return(e,s,o)=>{if(typeof s==="function"){o=s;s=void 0}t.push({chunk:e,encoding:s,callback:o});if(r)return false;return flushPendingWrites()};if(o==="end")return(...t)=>{const r=t[t.length-1];s={chunk:typeof t[0]==="function"?void 0:t[0],encoding:typeof t[1]==="string"?t[1]:void 0,callback:typeof r==="function"?r:void 0};flushPendingWrites();return e};return getRealValue()}})}var M=class SocketController{static{this.PENDING=0}static{this.CLAIMED=1}static{this.PASSTHROUGH=2}constructor(e){this[L]=e;e[w]=true;this.readyState=SocketController.PENDING}claim(){invariant(this.readyState===SocketController.PENDING,"Failed to claim a socket connection: already handled (%s)",this.readyState);this.readyState=SocketController.CLAIMED}passthrough(){invariant(this.readyState===SocketController.PENDING,"Failed to passthrough a socket connection: already handled (%s)",this.readyState);this.readyState=SocketController.PASSTHROUGH}};var U=class extends M{#N;#b;#k=null;#P=[];#I=false;#H=[];#D=false;#L=false;#w=false;#v=false;constructor(e,t,s){super(e);this.socket=e;this.createConnection=t;this.#N=s;this.socket._read=()=>{this.#k?.resume()};this.#b=this.socket._writeGeneric;this.#P=[];this.socket._writeGeneric=(...e)=>{this.#M(e)};this.socket.connect=new Proxy(this.socket.connect,{apply:(e,t,s)=>{v.verbose("socket.connect() %o",s);this.#N=s[0];if(s[0]!=null&&typeof s[0]==="object"&&(s[0].localAddress!=null||s[0].localPort!=null))s[0]={...s[0],localAddress:void 0,localPort:void 0};return Reflect.apply(e,t,s)}});e.on("free",(()=>{v.verbose("client socket freed!");this.reset()})).on("close",(()=>{v.verbose("client socket closed!");this.#L=true;this.#k?.destroy();this.#k=null;this.#P=[];this.#I=false;this.#H=[]}));this.serverSocket=toServerSocket(this.socket);this.pendingConnection=Promise.withResolvers();this.#U()}reset(){if(this.readyState===M.PENDING)return;this.#U()}#U(){v.verbose("resetting the socket...");this.readyState=M.PENDING;this.pendingConnection=Promise.withResolvers();this.#P=[];this.#v=false;this.socket._pendingData=null;this.socket._pendingEncoding="";const wrapHandle=e=>{this.pendingConnection.promise.then((()=>{v.verbose("connection request resolved!",this.readyState);process.nextTick((()=>{if(this.readyState===M.PENDING&&this.socket.connecting&&this.#P.length===0&&this.socket.listenerCount("connect")>0){v.verbose('assume connect->write socket, calling "connect" listeners...');this.emulateConnect()}}))}));if(e.setTypeOfService)e.setTypeOfService=void 0;e.connect=e.connect6=t=>{v.verbose("handle.connect()");this.pendingConnection.resolve([t,e])};v.verbose("socket handle wrapped! waiting for connection request...")};if(this.socket._handle)wrapHandle(this.socket._handle);else this.socket.prependOnceListener("connectionAttempt",(()=>{wrapHandle(this.socket._handle)}))}#M(e){const t=e[1];v.verbose("socket write (state: %d) %o",this.readyState,e);this.#P.push(e);if(this.readyState===M.PENDING){const e=Array.isArray(this.socket._pendingData)?this.socket._pendingData:[];unwrapPendingData(t,((t,s)=>{e.push({chunk:t,encoding:s})}));this.socket._pendingData=e;if(this.socket.listenerCount("internal:write")===0){v.verbose("no server data listeners, scheduling to the next tick...");process.nextTick((()=>{this.#q(t)}))}else this.#q(t)}else this.#q(t);switch(this.readyState){case M.PENDING:if(!this.#P.includes(e))this.#P.push(e);this.#B(e);return;case M.CLAIMED:this.#F(e);this.#B(e);return;case M.PASSTHROUGH:if(!this.#F(e))return;if(!this.#D&&this.#k){writePendingData(this.#k,t,e[2],e[3]);return}this.#b.apply(this.socket,e)}}#B(e){const t=e[3];if(typeof t==="function"){t();e[3]=void 0}}#F(e){const t=this.#P.indexOf(e);if(t===-1)return false;this.#P.splice(t,1);return true}emulateConnect(){this.#v=true;Reflect.set(this.socket,"connecting",false);for(const e of this.socket.rawListeners("connect"))e.apply(this.socket)}#q=e=>{if(e==null)return;v.verbose("server push %o",e);unwrapPendingData(e,((e,t)=>{v.verbose('server emitting "data" %o',{chunk:e,encoding:t});this.socket.emit("internal:write",e,t)}))};#x=()=>{if(!this.#k)return;if(this.socket.destroyed){this.#k.destroy();return}const e=this.socket._handle;const t=e!=null&&typeof e.hasRef==="function"&&!e.hasRef();this.socket._handle=this.#k._handle;this.#D=true;if(t)this.socket._handle.unref?.();if(e!=null){e.close();e._parent?.close()}Reflect.set(this.socket,"connecting",false);this.socket.remoteAddress;this.socket.emit("connect");this.socket.emit("ready")};#G=(e,t,s,r)=>{this.socket.emit("connectionAttemptFailed",e,t,s,r)};#W=(e,t,s)=>{this.socket.emit("connectionAttemptTimeout",e,t,s)};#j=e=>{v.verbose('real socket "data" event %o',e);this.socket._unrefTimer();if(this.#I){v.verbose("reads are corked, buffering the data...");this.#H.push({type:"data",chunk:e});return}if(!this.socket.push(e)){v.verbose("client socket forbade more pushes, pausing the passthrough socket...");this.#k?.pause()}};#V=e=>{v.verbose('real socket "error" event %o',e);if(this.socket.destroyed){v.verbose("real socket errored but client socket already destroyed, skipping...");return}v.verbose("real socket errored, forwarding %o",e);this.socket.destroy(e);if(this.#D)process.nextTick((()=>this.socket.emit("close",true)))};#K=()=>{this.socket._unrefTimer();if(this.#I){this.#H.push({type:"end"});return}this.#w=true;this.socket.push(null)};#$=e=>{if(this.#D&&this.socket._handle)this.socket._handle.shutdown=()=>1;if(this.#I){this.#H.push({type:"close",hadError:e});return}if(this.#L)return;if(this.socket.destroyed&&!this.#D)return;this.#X(e)};#X(e){if(this.#w&&!this.socket.readableEnded&&!this.socket.destroyed){let t=false;const deliverClose=s=>{if(t)return;t=true;process.nextTick((()=>{if(!this.#L)this.socket.emit("close",s??e)}))};this.socket.once("end",(()=>{deliverClose()}));const s=this.socket._destroy;this.socket._destroy=(e,t)=>{deliverClose(e!=null);return s.call(this.socket,e,t)};return}this.socket.emit("close",e)}#Y=()=>{v.verbose("client socket drained!");this.#k?.resume()};corkReads(){this.#I=true}uncorkReads(){if(!this.#I)return;this.#I=false;for(const e of this.#H.splice(0))switch(e.type){case"data":if(!this.socket.push(e.chunk)){v.verbose("client socket forbade more pushes, pausing the passthrough socket...");this.#k?.pause()}break;case"end":this.#w=true;this.socket.push(null);break;case"close":this.#X(e.hadError);break}}claim(){super.claim();if(this.socket.destroyed){v.verbose("socket already destroyed, skipping claim...");return}if(!this.socket.connecting&&!this.#v){v.verbose("socket already connected, skipping claim...");return}v.verbose("-> claim!");this.socket._handle.getsockname=e=>{Object.assign(e,getLocalAddressInfoByConnectionOptions(this.#N));return 0};this.socket._handle.getpeername=e=>{Object.assign(e,getAddressInfoByConnectionOptions(this.#N));return 0};this.#P=[];this.socket._pendingData=null;this.socket._pendingEncoding="";this.pendingConnection.promise.then((([e,t])=>{v.verbose("connection request resolved, mocking the connection...");if(this.#v)Reflect.set(this.socket,"connecting",true);e.oncomplete(0,t,e,true,true)}))}passthrough(e){super.passthrough();v.verbose("-> passthrough!");const createRealSocket=()=>{const e=this.createConnection();e[w]=true;if(this.socket.timeout!=null)e.setTimeout(this.socket.timeout);return e};const t=this.#k&&!this.#k.destroyed?this.#k:createRealSocket();if(t!==this.#k)this.#k=t;if(this.#P.length===0)v.verbose("passthrough with empty writes buffer (state: %d)",this.readyState);for(let s=0;s{r[1]=e}))}const[,o,n,i]=r;writePendingData(t,o,n,i)}this.#P=[];this.socket._pendingData=null;this.socket._pendingEncoding="";this.socket.address=t.address.bind(t);this.socket.removeListener("drain",this.#Y);this.socket.on("drain",this.#Y);t.removeListener("connect",this.#x).removeListener("connectionAttemptFailed",this.#G).removeListener("connectionAttemptTimeout",this.#W).removeListener("data",this.#j).removeListener("error",this.#V).removeListener("end",this.#K).removeListener("close",this.#$);t.once("connect",this.#x).on("connectionAttemptFailed",this.#G).on("connectionAttemptTimeout",this.#W).on("data",this.#j).on("error",this.#V).on("end",this.#K).on("close",this.#$);return t}};var q=class extends U{#z;constructor(e,t,s){super(e,t,s);this.socket=e;this.createConnection=t;this.#z=s;e.prependListener("secureConnect",(()=>{e.alpnProtocol=e._handle.getALPNNegotiatedProtocol()}))}emulateConnect(){super.emulateConnect();for(const e of this.socket.rawListeners("secureConnect"))e.apply(this.socket)}claim(){if(this.socket.destroyed){super.claim();return}this.socket.prependOnceListener("secureConnect",(()=>{Reflect.set(this.socket,"authorized",false);Reflect.set(this.socket,"authorizationError","MOCKED_CONNECTION_NOT_VERIFIED")}));const e=this.socket._handle;e.start=()=>void 0;e.verifyError=()=>void 0;e.getSession=()=>Buffer.from("mocked session");const t=getTlsConnectOptions(this.socket);if(t)t.checkServerIdentity=()=>{};e.getCipher=()=>({name:"TLS_AES_256_GCM_SHA384",standardName:"TLS_AES_256_GCM_SHA384",version:"TLSv1.3"});e.getEphemeralKeyInfo=()=>({type:"ECDH",name:"X25519",size:253});const s=this.#z?.ALPNProtocols;if(Array.isArray(s)&&s.length>0){const[t]=s;e.getALPNNegotiatedProtocol=()=>typeof t==="string"?t:false}this.socket.once("connect",(()=>{const t="0".repeat(64);const s="0".repeat(96);for(const e of["SERVER_HANDSHAKE_TRAFFIC_SECRET","EXPORTER_SECRET","SERVER_TRAFFIC_SECRET_0","CLIENT_HANDSHAKE_TRAFFIC_SECRET","CLIENT_TRAFFIC_SECRET_0"])this.socket.emit("keylog",Buffer.from(`${e} ${t} ${s}\n`));e.onhandshakedone();e.onnewsession(1,Buffer.from("mocked session"));e.onnewsession(2,Buffer.from("mocked session"))}));super.claim()}passthrough(e){const t=super.passthrough(e);for(const e of this.socket.listeners("connect"))if(e===this.socket._start||"listener"in e&&e.listener===this.socket._start)this.socket.removeListener("connect",e);t.on("secure",(()=>{this.socket.emit("secure")})).on("session",((...e)=>{this.socket.emit("session",...e)})).on("keylog",((...e)=>{this.socket.emit("keylog",...e)})).on("OCSPResponse",((...e)=>{this.socket.emit("OCSPResponse",...e)}));return t}};function normalizeTlsConnectArgs(e){const t=normalizeNetConnectArgs(e);const s=t[0];const r=t[1];if(e[0]!==null&&typeof e[0]==="object")Object.assign(s,e[0]);else if(e[1]!==null&&typeof e[1]==="object")Object.assign(s,e[1]);else if(e[2]!==null&&typeof e[2]==="object")Object.assign(s,e[2]);return r?[s,r]:[s]}var B=class extends a{constructor(e){super(...["connection",{}]);this.socket=e.socket;this.connectionOptions=e.connectionOptions;this.controller=e.controller}};const F=createLogger("socket");const mockLookup=(e,t,s)=>{const r=t.family===6?6:4;const o=r===6?"::1":"127.0.0.1";process.nextTick((()=>{if(t.all){s(null,[{address:o,family:r}]);return}s(null,o,r)}))};var x=class extends p{static{this.symbol=Symbol.for("socket-interceptor")}predicate(){return true}setup(){const e=this;let t=false;this.subscriptions.push(H.applyPatch(k.Socket.prototype,"connect",(s=>function connect(...r){const o=this;if(o[w]||t)return s.apply(o,r);F.verbose("socket.connect() %o",r);const n=Array.isArray(r[0])?r[0]:r;const[i,a]=normalizeNetConnectArgs(n);F.verbose("connection options %o",{transportConnectionOptions:i,connectionCallback:a});let c;let l;if(o instanceof P.TLSSocket){const e=getTlsConnectOptions(o);const[s]=normalizeTlsConnectArgs([{...i,...e}]);l=s;c=new q(o,(()=>{t=true;try{return P.connect(e??s)}finally{t=false}}),s)}else{const e=n.filter((e=>typeof e!=="function"));const t=n[0]!==null&&typeof n[0]==="object"&&!("href"in n[0])?n[0]:{};l=i;c=new U(o,(()=>{const r=new k.Socket(t);Reflect.apply(s,r,e);return r}))}process.nextTick((()=>{if(o.destroyed)return;if(!e.emitter.emit(new B({socket:c.serverSocket,controller:c,connectionOptions:l}))){F.verbose('no "connection" listeners found on the interceptor, passthrough...');c.passthrough();return}F.verbose('emitted "connection" event!')}));F.verbose("connecting the socket...");const u={...i};u.lookup=mockLookup;try{return o.connect(u,a??void 0)}catch(e){o.destroy();throw e}})),this.#Q())}#Q(){if(typeof b.Agent.prototype.addRequest!=="function")return()=>{};return H.applyPatch(b.Agent.prototype,"addRequest",(e=>function(...t){for(const e of Object.values(this.freeSockets)){if(e==null)continue;for(const t of e)if(!t[w])t.destroy()}return e?.apply(this,t)}))}};var G=require("node:async_hooks");var W=require("node:stream");var j=require("node:fs");async function until(e){try{return[null,await e().catch((e=>{throw e}))]}catch(e){return[e,null]}}var V=Object.create;var K=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var X=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf;var z=Object.prototype.hasOwnProperty;var __commonJSMin=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);var __copyProps=(e,t,s,r)=>{if(t&&typeof t==="object"||typeof t==="function")for(var o=X(t),n=0,i=o.length,a;nt[e]).bind(null,a),enumerable:!(r=$(t,a))||r.enumerable})}return e};var __toESM=(e,t,s)=>(s=e!=null?V(Y(e)):{},__copyProps(t||!e||!e.__esModule?K(s,"default",{value:e,enumerable:true}):s,e));const Q=new G.AsyncLocalStorage;function runInRequestContext(e,t){if(Q.getStore())return e();const s={initiator:void 0,logger:t};return Q.run(s,(()=>{const t=e();s.initiator=t;return t}))}const J=createLogger("http-request");function forwardHttpEvents(e){const t=new AbortController;const{source:s,emitter:r,predicate:o,responsePredicate:n}=e;s.on("request",(async e=>{if(o(e.initiator)){J.verbose('forwarding "request" event %o',{requestId:e.requestId});await r.emitAsPromise(e)}}),{signal:t.signal});const responseListener=async e=>{if(o(e.initiator)&&(n==null||n(e))){J.verbose('forwarding "response" event %o',{requestId:e.requestId,responseType:e.responseType});await r.emitAsPromise(e)}};const unhandledExceptionListener=async e=>{if(o(e.initiator)){J.verbose('forwarding "unhandledException" event %o',{requestId:e.requestId});await r.emitAsPromise(e)}};const addResponseListener=()=>{if(!s.listeners("response").includes(responseListener))s.on("response",responseListener,{signal:t.signal})};const addUnhandledExceptionListener=()=>{if(!s.listeners("unhandledException").includes(unhandledExceptionListener))s.on("unhandledException",unhandledExceptionListener,{signal:t.signal})};if(r.listenerCount("response")>0)addResponseListener();if(r.listenerCount("unhandledException")>0)addUnhandledExceptionListener();r.hooks.on("newListener",(e=>{if(e==="response")addResponseListener();if(e==="unhandledException")addUnhandledExceptionListener()}),{signal:t.signal,persist:true});r.hooks.on("removeListener",(e=>{if(e==="response"&&r.listenerCount("response")===0)s.removeListener("response",responseListener);if(e==="unhandledException"&&r.listenerCount("unhandledException")===0)s.removeListener("unhandledException",unhandledExceptionListener)}),{signal:t.signal,persist:true});return()=>{t.abort()}}var Z=class extends a{constructor(e){super(...["request",{}]);this.request=e.request;this.requestId=e.requestId;this.initiator=e.initiator;this.controller=e.controller}};var ee=class extends a{constructor(e){super(...["response",{}]);this.response=e.response;this.responseType=e.responseType;this.request=e.request;this.requestId=e.requestId;this.initiator=e.initiator}};var te=class extends a{constructor(e){super(...["unhandledException",{}]);this.error=e.error;this.request=e.request;this.requestId=e.requestId;this.initiator=e.initiator;this.controller=e.controller}};function connectionOptionsToUrl(e,t){const s=k.isIPv6(e.host||"");const r=t instanceof P.TLSSocket?"https:":getProtocolByConnectionOptions(e);const o=e.host||"localhost";const n=new URL(`${r}//${s?`[${o}]`:o}`);if(e.path)n.pathname=e.path;if(e.port)n.port=e.port.toString();if(e.auth){const[t,s]=e.auth.split(":");n.username=encodeURIComponent(t);n.password=encodeURIComponent(s)}return n}function getProtocolByConnectionOptions(e){if(e.protocol)return e.protocol;if(e.port===443)return"https:";return"http:"}var se=__toESM(__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.SPECIAL_HEADERS=e.MINOR=e.MAJOR=e.QDTEXT=e.CONNECTION_TOKEN_CHARS=e.RELAXED_HEADER_CHARS=e.HEADER_CHARS=e.HTAB_SP_VCHAR_OBS_TEXT=e.SP=e.HTAB=e.TOKEN=e.HEX=e.URL_CHAR=e.USERINFO_CHARS=e.MARK=e.ALPHANUM=e.DIGIT=e.HEX_MAP=e.NUM_MAP=e.ALPHA=e.METHODS=e.METHODS_HTTP=e.METHODS_HTTP2=e.METHODS_HTTP1=e.METHODS_RTSP=e.METHODS_RAOP=e.METHODS_AIRPLAY=e.METHODS_ICECAST=e.METHODS_NON_STANDARD=e.METHODS_CALDAV=e.METHODS_UPNP=e.METHODS_SUBVERSION=e.METHODS_WEBDAV=e.METHODS_BASIC_HTTP=e.METHODS_HTTP1_HEAD=e.HEADER_STATE=e.FINISH=e.STATUSES=e.LENIENT_FLAGS=e.FLAGS=e.TYPE=e.ERROR=void 0;e.ERROR={OK:0,INTERNAL:1,STRICT:2,CR_EXPECTED:25,LF_EXPECTED:3,UNEXPECTED_CONTENT_LENGTH:4,UNEXPECTED_SPACE:30,CLOSED_CONNECTION:5,INVALID_METHOD:6,INVALID_URL:7,INVALID_CONSTANT:8,INVALID_VERSION:9,INVALID_HEADER_TOKEN:10,INVALID_CONTENT_LENGTH:11,INVALID_CHUNK_SIZE:12,INVALID_STATUS:13,INVALID_EOF_STATE:14,INVALID_TRANSFER_ENCODING:15,CB_MESSAGE_BEGIN:16,CB_HEADERS_COMPLETE:17,CB_MESSAGE_COMPLETE:18,CB_CHUNK_HEADER:19,CB_CHUNK_COMPLETE:20,PAUSED:21,PAUSED_UPGRADE:22,PAUSED_H2_UPGRADE:23,USER:24,CB_URL_COMPLETE:26,CB_STATUS_COMPLETE:27,CB_METHOD_COMPLETE:32,CB_VERSION_COMPLETE:33,CB_HEADER_FIELD_COMPLETE:28,CB_HEADER_VALUE_COMPLETE:29,CB_CHUNK_EXTENSION_NAME_COMPLETE:34,CB_CHUNK_EXTENSION_VALUE_COMPLETE:35,CB_RESET:31,CB_PROTOCOL_COMPLETE:38};e.TYPE={BOTH:0,REQUEST:1,RESPONSE:2};e.FLAGS={CONNECTION_KEEP_ALIVE:1,CONNECTION_CLOSE:2,CONNECTION_UPGRADE:4,CHUNKED:8,UPGRADE:16,CONTENT_LENGTH:32,SKIPBODY:64,TRAILING:128,TRANSFER_ENCODING:512};e.LENIENT_FLAGS={HEADERS:1,CHUNKED_LENGTH:2,KEEP_ALIVE:4,TRANSFER_ENCODING:8,VERSION:16,DATA_AFTER_CLOSE:32,OPTIONAL_LF_AFTER_CR:64,OPTIONAL_CRLF_AFTER_CHUNK:128,OPTIONAL_CR_BEFORE_LF:256,SPACES_AFTER_CHUNK_SIZE:512,HEADER_VALUE_RELAXED:1024};e.STATUSES={CONTINUE:100,SWITCHING_PROTOCOLS:101,PROCESSING:102,EARLY_HINTS:103,RESPONSE_IS_STALE:110,REVALIDATION_FAILED:111,DISCONNECTED_OPERATION:112,HEURISTIC_EXPIRATION:113,MISCELLANEOUS_WARNING:199,OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,TRANSFORMATION_APPLIED:214,IM_USED:226,MISCELLANEOUS_PERSISTENT_WARNING:299,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,SWITCH_PROXY:306,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,PAGE_EXPIRED:419,ENHANCE_YOUR_CALM:420,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL:430,REQUEST_HEADER_FIELDS_TOO_LARGE:431,LOGIN_TIMEOUT:440,NO_RESPONSE:444,RETRY_WITH:449,BLOCKED_BY_PARENTAL_CONTROL:450,UNAVAILABLE_FOR_LEGAL_REASONS:451,CLIENT_CLOSED_LOAD_BALANCED_REQUEST:460,INVALID_X_FORWARDED_FOR:463,REQUEST_HEADER_TOO_LARGE:494,SSL_CERTIFICATE_ERROR:495,SSL_CERTIFICATE_REQUIRED:496,HTTP_REQUEST_SENT_TO_HTTPS_PORT:497,INVALID_TOKEN:498,CLIENT_CLOSED_REQUEST:499,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,BANDWIDTH_LIMIT_EXCEEDED:509,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511,WEB_SERVER_UNKNOWN_ERROR:520,WEB_SERVER_IS_DOWN:521,CONNECTION_TIMEOUT:522,ORIGIN_IS_UNREACHABLE:523,TIMEOUT_OCCURED:524,SSL_HANDSHAKE_FAILED:525,INVALID_SSL_CERTIFICATE:526,RAILGUN_ERROR:527,SITE_IS_OVERLOADED:529,SITE_IS_FROZEN:530,IDENTITY_PROVIDER_AUTHENTICATION_ERROR:561,NETWORK_READ_TIMEOUT:598,NETWORK_CONNECT_TIMEOUT:599};e.FINISH={SAFE:0,SAFE_WITH_CB:1,UNSAFE:2};e.HEADER_STATE={GENERAL:0,CONNECTION:1,CONTENT_LENGTH:2,TRANSFER_ENCODING:3,UPGRADE:4,CONNECTION_KEEP_ALIVE:5,CONNECTION_CLOSE:6,CONNECTION_UPGRADE:7,TRANSFER_ENCODING_CHUNKED:8};e.METHODS_HTTP1_HEAD={HEAD:2};e.METHODS_BASIC_HTTP={DELETE:0,GET:1,...e.METHODS_HTTP1_HEAD,POST:3,PUT:4,CONNECT:5,OPTIONS:6,TRACE:7,PATCH:28,LINK:31,UNLINK:32};e.METHODS_WEBDAV={COPY:8,LOCK:9,MKCOL:10,MOVE:11,PROPFIND:12,PROPPATCH:13,SEARCH:14,UNLOCK:15,BIND:16,REBIND:17,UNBIND:18,ACL:19};e.METHODS_SUBVERSION={REPORT:20,MKACTIVITY:21,CHECKOUT:22,MERGE:23};e.METHODS_UPNP={"M-SEARCH":24,NOTIFY:25,SUBSCRIBE:26,UNSUBSCRIBE:27};e.METHODS_CALDAV={MKCALENDAR:30};e.METHODS_NON_STANDARD={PURGE:29,QUERY:46};e.METHODS_ICECAST={SOURCE:33};e.METHODS_AIRPLAY={GET:1,POST:3};e.METHODS_RAOP={FLUSH:45};e.METHODS_RTSP={OPTIONS:e.METHODS_BASIC_HTTP.OPTIONS,DESCRIBE:35,ANNOUNCE:36,SETUP:37,PLAY:38,PAUSE:39,TEARDOWN:40,GET_PARAMETER:41,SET_PARAMETER:42,REDIRECT:43,RECORD:44,...e.METHODS_AIRPLAY,...e.METHODS_RAOP};e.METHODS_HTTP1={...e.METHODS_BASIC_HTTP,...e.METHODS_WEBDAV,...e.METHODS_SUBVERSION,...e.METHODS_UPNP,...e.METHODS_CALDAV,...e.METHODS_NON_STANDARD,...e.METHODS_ICECAST};e.METHODS_HTTP2={PRI:34};e.METHODS_HTTP={...e.METHODS_HTTP1,...e.METHODS_HTTP2};e.METHODS={...e.METHODS_HTTP1,...e.METHODS_HTTP2,...e.METHODS_RTSP};e.ALPHA=["A","a","B","b","C","c","D","d","E","e","F","f","G","g","H","h","I","i","J","j","K","k","L","l","M","m","N","n","O","o","P","p","Q","q","R","r","S","s","T","t","U","u","V","v","W","w","X","x","Y","y","Z","z"];e.NUM_MAP={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9};e.HEX_MAP={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15};e.DIGIT=["0","1","2","3","4","5","6","7","8","9"];e.ALPHANUM=[...e.ALPHA,...e.DIGIT];e.MARK=["-","_",".","!","~","*","'","(",")"];e.USERINFO_CHARS=[...e.ALPHANUM,...e.MARK,"%",";",":","&","=","+","$",","];e.URL_CHAR=["!",'"',"$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","@","[","\\","]","^","_","`","{","|","}","~",...e.ALPHANUM];e.HEX=[...e.DIGIT,"a","b","c","d","e","f","A","B","C","D","E","F"];e.TOKEN=["!","#","$","%","&","'","*","+","-",".","^","_","`","|","~",...e.ALPHANUM];e.HTAB=["\t"];e.SP=[" "];const t=[33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126];const s=[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255];e.HTAB_SP_VCHAR_OBS_TEXT=[...e.HTAB,...e.SP,...t,...s];e.HEADER_CHARS=e.HTAB_SP_VCHAR_OBS_TEXT;e.RELAXED_HEADER_CHARS=[...[1,2,3,4,5,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,127],...e.HEADER_CHARS];e.CONNECTION_TOKEN_CHARS=[...e.HTAB,...e.SP,33,34,35,36,37,38,39,40,41,42,43,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,...s];e.QDTEXT=[...e.HTAB,...e.SP,33,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,...s];e.MAJOR=e.NUM_MAP;e.MINOR=e.MAJOR;e.SPECIAL_HEADERS={connection:e.HEADER_STATE.CONNECTION,"content-length":e.HEADER_STATE.CONTENT_LENGTH,"proxy-connection":e.HEADER_STATE.CONNECTION,"transfer-encoding":e.HEADER_STATE.TRANSFER_ENCODING,upgrade:e.HEADER_STATE.UPGRADE};e.default={ERROR:e.ERROR,TYPE:e.TYPE,FLAGS:e.FLAGS,LENIENT_FLAGS:e.LENIENT_FLAGS,STATUSES:e.STATUSES,FINISH:e.FINISH,HEADER_STATE:e.HEADER_STATE,ALPHA:e.ALPHA,NUM_MAP:e.NUM_MAP,HEX_MAP:e.HEX_MAP,DIGIT:e.DIGIT,ALPHANUM:e.ALPHANUM,MARK:e.MARK,USERINFO_CHARS:e.USERINFO_CHARS,URL_CHAR:e.URL_CHAR,HEX:e.HEX,TOKEN:e.TOKEN,HEADER_CHARS:e.HEADER_CHARS,RELAXED_HEADER_CHARS:e.RELAXED_HEADER_CHARS,CONNECTION_TOKEN_CHARS:e.CONNECTION_TOKEN_CHARS,QDTEXT:e.QDTEXT,HTAB_SP_VCHAR_OBS_TEXT:e.HTAB_SP_VCHAR_OBS_TEXT,MAJOR:e.MAJOR,MINOR:e.MINOR,SPECIAL_HEADERS:e.SPECIAL_HEADERS,METHODS:e.METHODS,METHODS_HTTP:e.METHODS_HTTP,METHODS_HTTP1_HEAD:e.METHODS_HTTP1_HEAD,METHODS_HTTP1:e.METHODS_HTTP1,METHODS_HTTP2:e.METHODS_HTTP2,METHODS_ICECAST:e.METHODS_ICECAST,METHODS_RTSP:e.METHODS_RTSP}}))(),1);const re=se.TYPE.REQUEST;se.TYPE.RESPONSE;const oe=Symbol("kPtr");const ne=Symbol("kUrl");const ie=Symbol("kStatusMessage");const ae=Symbol("kHeadersFields");const ce=Symbol("kHeadersValues");const le=Symbol("kLastHeaderCallback");const ue=Symbol("kCallbacks");const he=Symbol("kType");const de=0;const pe=1;const fe=2;const Ee=new Map;const Te=Object.fromEntries(Object.entries(se.METHODS).map((([e,t])=>[t,e])));function readStringFrom(e,t){return Buffer.from(Ae.buffer,e,t).toString("latin1")}const Re=require("url").pathToFileURL(__filename).href;const Se=new WebAssembly.Module(j.readFileSync(new URL("./llhttp/llhttp.wasm",Re)));const _e=new WebAssembly.Instance(Se,{env:{wasm_on_message_begin(e){const t=Ee.get(e);t[ne]="";t[ie]="";t[ae]=[];t[ce]=[];t[le]=de;return t[ue].onMessageBegin?.()??0},wasm_on_url(e,t,s){Ee.get(e)[ne]=readStringFrom(t,s);return 0},wasm_on_status(e,t,s){Ee.get(e)[ie]=readStringFrom(t,s);return 0},wasm_on_header_field(e,t,s){const r=Ee.get(e);const o=readStringFrom(t,s);const n=r[ae];if(r[le]===pe)n[n.length-1]+=o;else{n.push(o);r[le]=pe}return 0},wasm_on_header_value(e,t,s){const r=Ee.get(e);const o=readStringFrom(t,s);const n=r[ce];if(r[le]===fe)n[n.length-1]+=o;else{n.push(o);r[le]=fe}return 0},wasm_on_headers_complete(e,t,s,r){const o=Ee.get(e);const n=be(e);const i=Ne(e);const a=[];const c=s===1;const l=r===1;for(let e=0;e{const o=(s||e.connectionOptions.method||"GET").toUpperCase();const n=new URL(r||"",e.connectionOptions.url);const i=N.parseRawHeaders([...t]);if(n.username||n.password){if(!i.has("authorization")){const e=Buffer.from(`${n.username}:${n.password}`).toString("base64");i.set("authorization",`Basic ${e}`)}n.username="";n.password=""}this.#Z=new W.Readable({read:()=>{}});const a=new AbortController;const c=new m(n,{method:o,headers:i,credentials:"same-origin",body:W.Readable.toWeb(this.#Z),signal:a.signal});e.onRequest(c,a)},onBody:e=>{invariant(this.#Z,"Failed to write to a request stream: stream does not exist. This is likely an issue with the library. Please report it on GitHub.");this.#Z.push(e)},onMessageComplete:()=>{this.#Z?.push(null)}})}free(){this.destroy();this.#Z?.destroy();this.#Z=void 0}};var we=class extends De{#ee;constructor(e){super(2,{onHeadersComplete:({rawHeaders:t,statusCode:s,statusMessage:r})=>{const o=N.parseRawHeaders([...t]);const n=new N(N.isResponseWithBody(s)?W.Readable.toWeb(this.#ee=new W.Readable({read(){}})):null,{status:s,statusText:r,headers:o});e.onResponse(n)},onBody:e=>{invariant(this.#ee,"Failed to read from a response stream: stream does not exist. This is likely an issue with the library. Please report it on GitHub.");this.#ee.push(e)},onMessageComplete:()=>{this.#ee?.push(null)}})}free(){this.destroy();this.#ee=null}};function isNodeLikeError(e){if(e==null)return false;if(!(e instanceof Error))return false;return"code"in e&&"errno"in e}async function handleRequest(e){if(e.logger?.isEnabled("default"))formatRequest(e.request).then((t=>{e.logger?.info("[%s] %s",e.requestId,t)}));const handleResponse=async t=>{if(t instanceof Error){await e.controller.errorWith(t);return true}if(isResponseError(t)){await e.controller.respondWith(t);return true}if(isResponseLike(t)){await e.controller.respondWith(t);return true}if(isObject(t)){await e.controller.errorWith(t);return true}return false};const handleResponseError=async t=>{if(t instanceof S)throw o;if(isNodeLikeError(t)){await e.controller.errorWith(t);return true}if(t instanceof Response)return await handleResponse(t);return false};const t=Promise.withResolvers();let s;let r=false;const onAbort=()=>{r=true;s=e.request.signal?.reason;t.reject(s)};if(e.request.signal){if(e.request.signal.aborted){await e.controller.errorWith(e.request.signal.reason);return}e.request.signal.addEventListener("abort",onAbort,{once:true})}const[o]=await until((async()=>{const s=new Z({initiator:e.initiator,requestId:e.requestId,request:e.request,controller:e.controller});const r=e.emitter.emitAsPromise(s);await Promise.race([t.promise,r,e.controller.handled]);if(s.request!==e.request)e.request=s.request}));e.request.signal?.removeEventListener("abort",onAbort);if(r){await e.controller.errorWith(s);return}if(o){if(await handleResponseError(o))return;if(e.emitter.listenerCount("unhandledException")>0){const t=new _(e.request,{passthrough(){},async respondWith(e){await handleResponse(e)},async errorWith(t){await e.controller.errorWith(t)}});await e.emitter.emitAsPromise(new te({initiator:e.initiator,error:o,request:e.request,requestId:e.requestId,controller:t}));if(t.readyState!==_.PENDING)return}await e.controller.respondWith(createServerErrorResponse(o));return}if(e.controller.readyState===_.PENDING)return await e.controller.passthrough();return e.controller.handled}const ve=createLogger("http-request");var Me=class extends p{static{this.symbol=Symbol.for("node-http-request-source")}predicate(){return true}setup(){const e=p.singleton(x);e.apply(this);this.subscriptions.push((()=>{e.dispose(this)}));this.subscriptions.push(recordRawFetchHeaders());const t=new AbortController;this.subscriptions.push((()=>t.abort()));e.on("connection",(({connectionOptions:e,socket:t,controller:s})=>{let r;let o;let n;let i;const a=Q.getStore();const c=s[L];const l=c._destroy.bind(c);c._destroy=(e,t)=>{i?.();l(e,t)};t.on("data",(c=>{if(r===false)return;if(n&&o){o.free();o=void 0;r=void 0;s.reset()}if(o){o.execute(toBuffer(c));return}const l=c.toString();const u=l.split(" ")[0]||"";if(!b.METHODS.includes(u.toUpperCase())){r=false;return}r=true;const h=n??connectionOptionsToUrl(e,t);ve.verbose("handling http message %o",{httpMessage:l,httpMethod:u,baseUrl:h});const d=Q.getStore()??a;const p=d?.initiator||t;o=new Le({connectionOptions:{method:u,url:h},onRequest:async(e,r)=>{const o=d?.transformRequest?.(e)??e;if(s["readyState"]!==M.PENDING)s.reset();const a=createRequestId();const c=d?.logger??ve;ve.verbose("received a parsed HTTP request %o",{method:o.method,url:o.url});const l=new _(o,{respondWith:async e=>{ve.verbose("respondWith() %o",{status:e.status,statusText:e.statusText,hasBody:e.body!=null});if(t.destroyed)return;s.claim();const r=N.from(e,{url:o.url});if(o.method==="CONNECT"&&r.ok)n=new URL(`http://${o.url}`);const i=isResponseError(r)?null:r.clone();const respond=()=>this.respondWith({socket:s[L],request:u.request,response:r});if(i)await this.emitter.emitAsPromise(new ee({initiator:p,requestId:a,request:u.request,response:i,responseType:"mock"}));if(t.connecting)t.once("connect",respond);else await respond()},errorWith:e=>{if(e instanceof Error)t.destroy(e)},passthrough:()=>{const e=s.passthrough(this.#te(u.request));if(this.emitter.listenerCount("response")>0){ve.verbose('found "response" listener, corking socket reads');s.corkReads();const t=new we({onResponse:async e=>{ve.verbose("HTTP response parser parsed: %d %s",e.status,e.statusText);if(isResponseError(e)){ve.verbose("response is an error response, uncorking socket reads...");s.uncorkReads();return}N.setUrl(o.url,e);try{ve.verbose('emitting "response" event');await this.emitter.emitAsPromise(new ee({initiator:p,requestId:a,request:u.request,response:e,responseType:"original"}))}finally{ve.verbose("uncorking socket reads");s.uncorkReads();if(e.status<200&&e.status!==101)s.corkReads()}}});e.on("data",(e=>t.execute(e))).on("close",(()=>t.free()))}}},{logger:c,requestId:a});invariant(s["readyState"]===M.PENDING,"CANNOT HANDLE ALREADY HANDLED REQUEST",o.method,o.url,s["readyState"]);const u={initiator:p,requestId:a,request:o,controller:l,emitter:this.emitter,logger:c};i=()=>{if(l.readyState===_.PENDING)r.abort()};try{await handleRequest(u)}finally{i=void 0}}});o.execute(toBuffer(c))}));t.on("close",(()=>o?.free()))}),{signal:t.signal})}async respondWith(e){const{socket:t,request:s,response:r}=e;if(t.destroyed)return;if(isResponseError(r)){t.destroy(Object.defineProperty(new TypeError("Network error"),O,{value:r,enumerable:false}));return}invariant(!t.connecting,'Failed to mock a response for "%s %s": socket has not connected',s.method,s.url);const o=new b.IncomingMessage(t);o.method=s.method;const n=new b.ServerResponse(o);const i=new k.Socket;i._writeGeneric=(e,s,r,o)=>{unwrapPendingData(s,((e,s)=>{t.push(toBuffer(e),s)}));o?.()};i._destroy=(e,s)=>{if(e)t.destroy();s(null)};i.on("drain",(()=>n.emit("drain")));n.assignSocket(i);n.removeHeader("connection");n.removeHeader("date");const a=getRawFetchHeaders(r.headers);n.writeHead(r.status,r.statusText||b.STATUS_CODES[r.status],a);t._destroy=function(e,t){if(e)queueMicrotask((()=>this.emit("error",e)));t(null);process.nextTick((()=>this.emit("close",e!=null)))};if(r.body){const e=r.body.getReader();try{while(true){const{done:t,value:s}=await e.read();if(t){n.end();break}if(!n.write(s))await new Promise((e=>{n.once("drain",e)}))}}catch{await new Promise((e=>process.nextTick(e)));t.destroy();return}}else n.end();const c=s.method==="HEAD"||r.headers.has("content-length")||r.headers.has("transfer-encoding")||!N.isResponseWithBody(r.status);if(s.method!=="CONNECT"&&!c){await new Promise((e=>process.nextTick(e)));t.push(null)}}#te(e){const transformRequestMessage=(t,s)=>{if(s==="buffer")return t;const r=t.toString(s).split("\r\n");const o=r.findIndex((e=>e===""));const n=r.slice(1,o);const i=n.map((e=>{const t=e.indexOf(": ");return[e.slice(0,t),e.slice(t+2)]}));const a=getRawFetchHeaders(e.headers);if(i.length===a.length&&i.every(((e,t)=>{const s=a[t];return e[0]===s[0]&&e[1]===s[1]})))return t;const c=N.parseRawHeaders(n.flatMap((e=>e.split(": "))));const l=new Set;for(const[t]of a){const s=t.toLowerCase();if(l.has(s))continue;l.add(s);const r=e.headers.get(t);if(r===null)continue;c.set(t,r)}l.clear();const u=Array.from(c).map((([e,t])=>`${e}: ${t}`)).join("\r\n");r.splice(1,o-1,u);return r.join("\r\n")};return(e,t,s)=>{if(Array.isArray(e))e[0].chunk=transformRequestMessage(e[0].chunk,e[0].encoding);else e=transformRequestMessage(e,t);s(e)}}};var Ue=require("node:https");var qe=class extends p{static{this.symbol=Symbol.for("client-request-interceptor")}predicate(){return true}setup(){const e=p.singleton(Me);const t=this.logger;e.apply(this);this.subscriptions.push((()=>{e.dispose(this)}));this.subscriptions.push(forwardHttpEvents({source:e,emitter:this.emitter,predicate:e=>e instanceof b.ClientRequest}));this.subscriptions.push(H.applyPatch(b,"ClientRequest",(e=>new Proxy(e,{construct(e,s,r){return runInRequestContext((()=>Reflect.construct(e,s,r)),t)}}))),H.applyPatch(b,"get",(e=>function mockHttpGet(...s){return runInRequestContext((()=>e(...s)),t)})),H.applyPatch(b,"request",(e=>function mockHttpRequest(...s){return runInRequestContext((()=>e(...s)),t)})),H.applyPatch(Ue,"get",(e=>function mockHttpsGet(...s){return runInRequestContext((()=>e(...s)),t)})),H.applyPatch(Ue,"request",(e=>function mockHttpsRequest(...s){return runInRequestContext((()=>e(...s)),t)})))}}}};var t={};function __nccwpck_require__(s){var r=t[s];if(r!==undefined){return r.exports}var o=t[s]={exports:{}};var n=true;try{e[s](o,o.exports,__nccwpck_require__);n=false}finally{if(n)delete t[s]}return o.exports}!function(){__nccwpck_require__.d=function(e,t){for(var s in t){if(__nccwpck_require__.o(t,s)&&!__nccwpck_require__.o(e,s)){Object.defineProperty(e,s,{enumerable:true,get:t[s]})}}}}();!function(){__nccwpck_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}}();!function(){__nccwpck_require__.r=function(e){if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}Object.defineProperty(e,"__esModule",{value:true})}}();if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var s=__nccwpck_require__(349);module.exports=s})(); \ No newline at end of file +(function(){var e={349:function(e,t,s){if(typeof Promise.withResolvers!=="function"){Promise.withResolvers=s(252).createPromiseWithResolvers}e.exports=s(871)},252:function(e){"use strict";e.exports=require("next/dist/shared/lib/promise-with-resolvers")},871:function(e,t,s){"use strict";s.r(t);s.d(t,{ClientRequestInterceptor:function(){return qe}});var r=class{#e;#t;constructor(){this.#e=[];this.#t=new Map}get[Symbol.iterator](){return this.#e[Symbol.iterator].bind(this.#e)}entries(){return this.#t.entries()}get(e){return this.#t.get(e)||[]}getAll(){return this.#e.map((([,e])=>e))}append(e,t){this.#e.push([e,t]);this.#s(e,(e=>e.push(t)))}prepend(e,t){this.#e.unshift([e,t]);this.#s(e,(e=>e.unshift(t)))}delete(e,t){if(this.size===0)return false;const s=this.#t.get(e);if(!s)return false;const r=s.indexOf(t);if(r===-1)return false;s.splice(r,1);this.#e.splice(this.#e.findIndex((s=>s[0]===e&&s[1]===t)),1);return true}deleteAll(e){if(this.size===0)return;this.#e=this.#e.filter((t=>t[0]!==e));this.#t.delete(e)}get size(){return this.#e.length}clear(){if(this.size===0)return;this.#e.length=0;this.#t.clear()}#s(e,t){t(this.#t.get(e)||this.#t.set(e,[]).get(e))}};const o=Symbol("kDefaultPrevented");const n=Symbol("kPropagationStopped");const i=Symbol("kImmediatePropagationStopped");var a=class extends MessageEvent{#r;[o];[n];[i];constructor(...e){super(e[0],e[1]);this[o]=false}get defaultPrevented(){return this[o]}preventDefault(){super.preventDefault();this[o]=true}stopImmediatePropagation(){super.stopImmediatePropagation();this[i]=true}};var c=class{#o;#n;#i;#a;#c;#l;#u;hooks;constructor(){this.#o=new r;this.#n=new WeakMap;this.#i=new WeakMap;this.#a=new WeakSet;this.#c=new r;this.#l=new WeakMap;this.#u=new WeakMap;this.hooks={on:(e,t,s)=>{if(s?.signal?.aborted)return;if(s?.once){const s=t;const wrapper=(...t)=>{this.#h(e,wrapper);return s(...t)};t=wrapper}this.#c.append(e,t);if(s)this.#l.set(t,s);if(s?.signal){const{signal:r}=s;const onAbort=()=>{this.#h(e,t)};r.addEventListener("abort",onAbort,{once:true});this.#u.set(t,(()=>{r.removeEventListener("abort",onAbort)}))}},removeListener:(e,t)=>{this.#h(e,t)}}}#h(e,t){this.#c.delete(e,t);const s=this.#u.get(t);if(s){s();this.#u.delete(t)}}#d(e,t){const s=this.#o.delete(e,t);const r=this.#i.get(t);if(r){r();this.#i.delete(t)}return s}on(e,t,s){this.#p(e,t,s);return this}once(e,t,s){return this.on(e,t,{...s||{},once:true})}earlyOn(e,t,s){this.#p(e,t,s,"prepend");return this}earlyOnce(e,t,s){return this.earlyOn(e,t,{...s||{},once:true})}emit(e){if(this.#o.size===0)return false;const t=this.listenerCount(e.type)>0;const s=this.#f(e);for(const t of this.#E(e.type)){if(s.event[n]!=null&&s.event[n]!==this){s.revoke();return false}if(s.event[i])break;this.#R(s.event,t)}s.revoke();return t}async emitAsPromise(e){if(this.#o.size===0)return[];const t=[];const s=this.#f(e);for(const r of this.#E(e.type)){if(s.event[n]!=null&&s.event[n]!==this){s.revoke();return[]}if(s.event[i])break;const e=await Promise.resolve(this.#R(s.event,r));if(!this.#S(r))t.push(e)}s.revoke();return Promise.allSettled(t).then((e=>e.map((e=>e.status==="fulfilled"?e.value:e.reason))))}*emitAsGenerator(e){if(this.#o.size===0)return;const t=this.#f(e);for(const s of this.#E(e.type)){if(t.event[n]!=null&&t.event[n]!==this){t.revoke();return}if(t.event[i])break;const e=this.#R(t.event,s);if(!this.#S(s))yield e}t.revoke()}removeListener(e,t){const s=this.#n.get(t);if(!this.#d(e,t))return;for(const r of this.#c.get("removeListener").slice())r(e,t,s)}removeAllListeners(e){if(e==null){for(const[e,t]of this.#o.entries())while(t.length>0)this.removeListener(e,t[0]);for(const[e,t]of[...this.#c])if(!this.#l.get(t)?.persist)this.#h(e,t);return}const t=this.listeners(e);while(t.length>0)this.removeListener(e,t[0])}listeners(e){if(e==null)return this.#o.getAll();return this.#o.get(e)}listenerCount(e){if(e==null)return this.#o.size;return this.listeners(e).length}#p(e,t,s,r="append"){if(s?.signal?.aborted)return;for(const r of this.#c.get("newListener").slice())r(e,t,s);if(e==="*")this.#a.add(t);if(r==="prepend")this.#o.prepend(e,t);else this.#o.append(e,t);if(s){this.#n.set(t,s);if(s.signal){const{signal:r}=s;const onAbort=()=>{this.removeListener(e,t)};r.addEventListener("abort",onAbort,{once:true});this.#i.set(t,(()=>{r.removeEventListener("abort",onAbort)}))}}}#f(e){const{stopPropagation:t}=e;e.stopPropagation=()=>{e[n]=this;t.call(e)};return{event:e,revoke(){e.stopPropagation=t}}}#R(e,t){for(const t of this.#c.get("beforeEmit").slice())if(t(e)===false)return;const s=t.call(this,e);const r=this.#n.get(t);if(r?.once){const s=this.#S(t)?"*":e.type;if(this.#d(s,t))for(const e of this.#c.get("removeListener").slice())e(s,t,r)}return s}*#E(e){const t=[];for(const[s,r]of this.#o)if(s==="*"||s===e)t.push(r);yield*t}#S(e){return this.#a.has(e)}};var l=require("next/dist/compiled/debug");var u=class{constructor(){this.subscriptions=[]}dispose(){let e;while(e=this.subscriptions.pop())e()}};const h=/\d{2}:\d{2}:\d{2}\.\d{3}/;function normalizeNamespace(e){return e.split(":").map((e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-|-$/g,"").toLowerCase())).filter(Boolean).join(":")}function getTimestamp(){return(new Date).toISOString().slice(11,23)}async function readBody(e){if(e.body==null)return null;try{return await e.clone().text()}catch{return null}}function formatHeaders(e){return Array.from(e.entries()).map((([e,t])=>`${e}: ${t}`))}async function formatHttpMessage(e,t){const s=[e,...formatHeaders(t.headers)];const r=await readBody(t);s.push("",r??"");return s.join("\n")}async function formatRequest(e){return formatHttpMessage(`${e.method} ${e.url}`,e)}async function formatResponse(e){const t=e.statusText?` ${e.statusText}`:"";return formatHttpMessage(`HTTP ${e.status}${t}`,e)}function formatLogArguments(e){const t=e[0];if(typeof t==="string"){const s=t.replace(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z /,"");const r=s.match(h);if(!r||r.index===void 0){e[0]=s;return}const o=s.slice(0,r.index).trim();const n=s.slice(r.index+r[0].length).trimStart();e[0]=`${r[0]} ${o} ${n}`}}function useConciseTimestamp(e){e.log=(...e)=>{formatLogArguments(e);l.log(...e)}}function isVerboseLoggingEnabled(){if(typeof process!=="undefined"&&process.env.DEBUG_LEVEL==="verbose")return true;if(typeof document==="undefined")return false;try{return globalThis.localStorage?.getItem("debugLevel")==="verbose"}catch{return false}}function createLogger(e){const t=l(`interceptors:${normalizeNamespace(e)}`);Reflect.set(t,"useColors",true);useConciseTimestamp(t);return{info(e,...s){t(`${getTimestamp()} ${e}`,...s)},verbose(e,...s){if(!isVerboseLoggingEnabled())return;t(`${getTimestamp()} ${e}`,...s)},isEnabled(e){return t.enabled&&(e==="default"||isVerboseLoggingEnabled())}}}const d=globalThis.__MSW_INTERCEPTORS_REGISTRY??=new Map;var p=class extends u{#T;static singleton(e){const t=e.symbol;const s=d.get(t);if(s instanceof e)return s;const r=new e;d.set(t,r);return r}constructor(){super();this.on=(e,t,s)=>this.emitter.on(e,t,s);this.once=(e,t,s)=>this.emitter.once(e,t,s);this.listeners=e=>this.emitter.listeners(e);this.listenerCount=e=>this.emitter.listenerCount(e);this.removeListener=(e,t)=>this.emitter.removeListener(e,t);this.removeAllListeners=e=>{this.logger.info("removeAllListeners %o",{eventType:e??"*"});return this.emitter.removeAllListeners(e)};this.#T=new Set;this.readyState="INACTIVE";this.emitter=new c;this.logger=createLogger(this.#_())}apply(e=this){if(this.#T.has(e))return;if(this.readyState!=="ACTIVE"&&!this.predicate())return;this.#T.add(e);if(this.readyState==="ACTIVE")return;try{this.setup();this.readyState="ACTIVE";this.logger.info("apply")}catch(t){this.dispose(e);throw t}}dispose(e=this){if(!this.#T.delete(e))return;if(this.#T.size>0)return;super.dispose();this.emitter.removeAllListeners();this.readyState="DISPOSED";this.logger.info("disable")}#_(){const e=this.constructor.symbol?.description;if(e)return e.replace(/-interceptor$/,"");return this.constructor.name.replace(/Interceptor$/,"")}};var f=/(%?)(%([sdijo]))/g;function serializePositional(e,t){switch(t){case"s":return e;case"d":case"i":return Number(e);case"j":return JSON.stringify(e);case"o":{if(typeof e==="string"){return e}const t=JSON.stringify(e);if(t==="{}"||t==="[]"||/^\[object .+?\]$/.test(t)){return e}return t}}}function format(e,...t){if(t.length===0){return e}let s=0;let r=e.replace(f,((e,r,o,n)=>{const i=t[s];const a=serializePositional(i,n);if(!r){s++;return a}return e}));if(s{if(!e){throw new R(t,...s)}};invariant.as=(e,t,s,...r)=>{if(!t){const t=r.length===0?s:format(s,...r);let o;try{o=Reflect.construct(e,[t])}catch(s){o=e(t)}throw o}};var S=class InterceptorError extends Error{constructor(e){super(e);this.name="InterceptorError";Object.setPrototypeOf(this,InterceptorError.prototype)}};var T=class RequestController{static{this.PENDING=0}static{this.PASSTHROUGH=1}static{this.RESPONSE=2}static{this.ERROR=3}#g;constructor(e,t,s){this.request=e;this.source=t;this.options=s;this.readyState=RequestController.PENDING;this.#g=Promise.withResolvers();this.handled=this.#g.promise}async passthrough(){invariant.as(S,this.readyState===RequestController.PENDING,'Failed to passthrough the "%s %s" request: the request has already been handled',this.request.method,this.request.url);this.readyState=RequestController.PASSTHROUGH;if(this.options)this.options.logger.info("[%s] passthrough",this.options.requestId);await this.source.passthrough();this.#g.resolve()}respondWith(e){invariant.as(S,this.readyState===RequestController.PENDING,'Failed to respond to the "%s %s" request with "%d %s": the request has already been handled (%d)',this.request.method,this.request.url,e.status,e.statusText||"OK",this.readyState);this.readyState=RequestController.RESPONSE;if(this.options?.logger.isEnabled("default")){const{logger:t,requestId:s}=this.options;formatResponse(e).then((e=>{t.info("[%s] mocked %s",s,e)}))}this.#g.resolve();this.source.respondWith(e)}errorWith(e){invariant.as(S,this.readyState===RequestController.PENDING,'Failed to error the "%s %s" request with "%s": the request has already been handled (%d)',this.request.method,this.request.url,e?.toString(),this.readyState);this.readyState=RequestController.ERROR;if(this.options)this.options.logger.info("[%s] error %o",this.options.requestId,e);this.source.errorWith(e);this.#g.resolve()}};const _=Symbol("kRawHeaders");const g=Symbol("kRestorePatches");function recordRawHeader(e,t,s){ensureRawHeadersSymbol(e,[]);const r=Reflect.get(e,_);if(s==="set"){for(let e=r.length-1;e>=0;e--)if(r[e][0].toLowerCase()===t[0].toLowerCase())r.splice(e,1)}r.push(t)}function ensureRawHeadersSymbol(e,t){if(Reflect.has(e,_))return;defineRawHeadersSymbol(e,t)}function defineRawHeadersSymbol(e,t){Object.defineProperty(e,_,{value:t,enumerable:false,configurable:true})}function recordRawFetchHeaders(){if(Reflect.get(Headers,g))return Reflect.get(Headers,g);const{Headers:e,Request:t,Response:s}=globalThis;const{set:r,append:o,delete:n}=Headers.prototype;Object.defineProperty(Headers,g,{value:()=>{Headers.prototype.set=r;Headers.prototype.append=o;Headers.prototype.delete=n;globalThis.Headers=e;globalThis.Request=t;globalThis.Response=s;Object.setPrototypeOf(A,t);Object.setPrototypeOf(A.prototype,t.prototype);Object.setPrototypeOf(C,s);Object.setPrototypeOf(C.prototype,s.prototype);Reflect.deleteProperty(Headers,g)},enumerable:false,configurable:true});Object.defineProperty(globalThis,"Headers",{enumerable:true,writable:true,value:new Proxy(Headers,{construct(e,t,s){const r=t[0]||[];if(r instanceof Headers&&Reflect.has(r,_)){const t=Reflect.get(r,_).map((e=>[e[0],e[1]]));const o=Reflect.construct(e,[t],s);ensureRawHeadersSymbol(o,[...t]);return o}const o=Reflect.construct(e,t,s);if(!Reflect.has(o,_))ensureRawHeadersSymbol(o,Array.isArray(r)?r:Object.entries(r));return o}})});Headers.prototype.set=new Proxy(Headers.prototype.set,{apply(e,t,s){recordRawHeader(t,[s[0],s[1]],"set");return Reflect.apply(e,t,s)}});Headers.prototype.append=new Proxy(Headers.prototype.append,{apply(e,t,s){recordRawHeader(t,[s[0],s[1]],"append");return Reflect.apply(e,t,s)}});Headers.prototype.delete=new Proxy(Headers.prototype.delete,{apply(e,t,s){const r=Reflect.get(t,_);if(r){for(let e=r.length-1;e>=0;e--)if(r[e][0].toLowerCase()===s[0].toLowerCase())r.splice(e,1)}return Reflect.apply(e,t,s)}});Object.defineProperty(globalThis,"Request",{enumerable:true,writable:true,value:new Proxy(Request,{construct(e,t,s){const r=Reflect.construct(e,t,s);const o=[];if(typeof t[0]==="object"&&t[0].headers!=null)o.push(...inferRawHeaders(t[0].headers));if(typeof t[1]==="object"&&t[1].headers!=null)o.push(...inferRawHeaders(t[1].headers));if(o.length>0)ensureRawHeadersSymbol(r.headers,o);return r}})});Object.defineProperty(globalThis,"Response",{enumerable:true,writable:true,value:new Proxy(Response,{construct(e,t,s){const r=Reflect.construct(e,t,s);if(typeof t[1]==="object"&&t[1].headers!=null)ensureRawHeadersSymbol(r.headers,inferRawHeaders(t[1].headers));return r}})});Object.setPrototypeOf(A,globalThis.Request);Object.setPrototypeOf(A.prototype,globalThis.Request.prototype);Object.setPrototypeOf(C,globalThis.Response);Object.setPrototypeOf(C.prototype,globalThis.Response.prototype);return restoreHeadersPrototype}function restoreHeadersPrototype(){if(!Reflect.get(Headers,g))return;Reflect.get(Headers,g)()}function getRawFetchHeaders(e){if(!Reflect.has(e,_))return Array.from(e.entries());const t=Reflect.get(e,_);return t.length>0?t:Array.from(e.entries())}function inferRawHeaders(e){if(e instanceof Headers)return Reflect.get(e,_)||[];return Reflect.get(new Headers(e),_)}function copyRawHeaders(e,t){const s=[...getRawFetchHeaders(e)];if(s.length===0)return;for(const[e,r]of t)if(s.every((t=>t[0].toLowerCase()!==e.toLowerCase())))s.push([e,r]);defineRawHeadersSymbol(t,s)}function getValueBySymbol(e,t){const s=Object.getOwnPropertySymbols(t).find((t=>t.description===e));if(s)return Reflect.get(t,s)}function isObject(e,t=false){return t?Object.prototype.toString.call(e).startsWith("[object "):Object.prototype.toString.call(e)==="[object Object]"}function isPropertyAccessible(e,t){try{e[t];return true}catch{return false}}function createServerErrorResponse(e){return new Response(JSON.stringify(e instanceof Error?{name:e.name,message:e.message,stack:e.stack}:e),{status:500,statusText:"Unhandled Exception",headers:{"Content-Type":"application/json"}})}const O=Symbol("kErrorResponse");function getErrorResponse(e){if(e instanceof Error&&O in e&&isResponseError(e[O]))return e[O]}function isResponseError(e){return e!=null&&e instanceof Response&&isPropertyAccessible(e,"type")&&e.type==="error"}function isResponseLike(e){return isObject(e,true)&&isPropertyAccessible(e,"status")&&isPropertyAccessible(e,"statusText")&&isPropertyAccessible(e,"bodyUsed")}var A=class FetchRequest extends Request{static#O(e,t={},s){return t[s]??(e instanceof Request?e[s]:void 0)}static isConfigurableMethod(e){return e!=="CONNECT"&&e!=="TRACE"&&e!=="TRACK"}static isMethodWithBody(e){return e!=="HEAD"&&e!=="GET"&&FetchRequest.isConfigurableMethod(e)}static isConfigurableMode(e){return e!=="navigate"&&e!=="websocket"&&e!=="webtransport"}constructor(e,t){const s=FetchRequest.#O(e,t,"method")||"GET";const r=FetchRequest.isConfigurableMethod(s)?s:"GET";const o=t!=null&&"body"in t;const n=!FetchRequest.isMethodWithBody(s)?{body:void 0}:o?{body:t.body}:{};const i=FetchRequest.#O(e,t,"mode")??void 0;const a=FetchRequest.isConfigurableMode(i)?i:void 0;super(e,{...t||{},method:r,mode:a,duplex:t?.duplex??(FetchRequest.isMethodWithBody(s)?"half":void 0),...n});if(s!==r)this.#A("method",s);if(s==="CONNECT"){const t=new URL(e instanceof Request?e.url:e);let s;if(t.protocol==="localhost:")s=t.href;else s=t.pathname.replace(/^\/+/,"");Object.defineProperty(this,"url",{get:()=>s,enumerable:true,configurable:true})}if(i!=null&&i!==a)this.#A("mode",i)}#A(e,t){const s=getValueBySymbol("state",this);if(s)Reflect.set(s,e,t);else Object.defineProperty(this,e,{value:t,enumerable:true,configurable:true,writable:false})}};const m=Symbol("kStatus");const y=Symbol("kUrl");var C=class FetchResponse extends Response{static from(e,t){if(e instanceof FetchResponse)return e;if(isResponseError(e))return e;const s=new FetchResponse(e.body,{url:t?.url??e.url,status:t?.status||e.status,statusText:t?.statusText??e.statusText,headers:t?.headers??e.headers});copyRawHeaders(e.headers,s.headers);return s}static{this.STATUS_CODES_WITHOUT_BODY=[101,103,204,205,304]}static{this.STATUS_CODES_WITH_REDIRECT=[301,302,303,307,308]}static isConfigurableStatusCode(e){return e>=200&&e<=599}static isRedirectResponse(e){return FetchResponse.STATUS_CODES_WITH_REDIRECT.includes(e)}static isResponseWithBody(e){return!FetchResponse.STATUS_CODES_WITHOUT_BODY.includes(e)}static setStatus(e,t){const s=getValueBySymbol("state",t);if(s)s.status=e;else Object.defineProperty(t,"status",{value:e,enumerable:true,configurable:true,writable:false});Object.defineProperty(t,m,{value:e,enumerable:false})}static setUrl(e,t){if(!e||e==="about:"||!URL.canParse(e))return;const s=getValueBySymbol("state",t);if(s)s.urlList.push(new URL(e));else Object.defineProperty(t,"url",{value:e,enumerable:true,configurable:true,writable:false});Object.defineProperty(t,y,{value:e,enumerable:false})}static parseRawHeaders(e){const t=new Headers;for(let s=0;s{}}if(o.descriptor.configurable)Object.defineProperty(e,t,{value:s(e[t]),enumerable:true,configurable:true});else if(o.descriptor.writable)e[t]=s(e[t]);else throw new Error(`Failed to patch a non-configurable non-writable property "${t.toString()}"`);const restorePatch=()=>{const s=this.#C.get(e);if(!s?.has(t))return;if(o.owner===e)Object.defineProperty(o.owner,t,o.descriptor);else Reflect.deleteProperty(e,t);s.delete(t);if(s.size===0)this.#C.delete(e)};if(r)r.set(t,restorePatch);else this.#C.set(e,new Map([[t,restorePatch]]));return restorePatch}restoreAllPatches(){const e=[];for(const[,t]of this.#C)for(const[,s]of t)try{s()}catch(t){if(t instanceof Error)e.push(t);else throw t}if(e.length>0)throw new AggregateError(e,"FOO!")}};const P=new k;function getDeepPropertyDescriptor(e,t){let s=e;let r;while(s){r=Object.getOwnPropertyDescriptor(s,t);if(r)return{owner:s,descriptor:r};s=Object.getPrototypeOf(s)}}var b=require("node:http");var I=require("node:async_hooks");var H=require("node:net");var L=require("node:tls");function normalizeNetConnectArgs(e){if(e.length===0)return[{path:""},null];const t=typeof e[1]==="function"?e[1]:e[2]||null;if(typeof e[0]==="string")return[{path:e[0]},t];if(typeof e[0]==="number")return[{port:e[0],path:"",host:typeof e[1]==="string"?e[1]:void 0},t];if(typeof e[0]==="object"){if("port"in e[0])return[{path:"",port:Reflect.get(e[0],"port"),host:Reflect.get(e[0],"host"),auth:Reflect.get(e[0],"auth"),family:Reflect.get(e[0],"family"),hints:Reflect.get(e[0],"hints"),session:Reflect.get(e[0],"session"),localAddress:Reflect.get(e[0],"localAddress"),localPort:Reflect.get(e[0],"localPort"),timeout:Reflect.get(e[0],"timeout"),lookup:Reflect.get(e[0],"lookup"),allowHalfOpen:Reflect.get(e[0],"allowHalfOpen"),noDelay:Reflect.get(e[0],"noDelay"),keepAlive:Reflect.get(e[0],"keepAlive"),keepAliveInitialDelay:Reflect.get(e[0],"keepAliveInitialDelay"),autoSelectFamily:Reflect.get(e[0],"autoSelectFamily"),autoSelectFamilyAttemptTimeout:Reflect.get(e[0],"autoSelectFamilyAttemptTimeout")},t];return[{path:e[0].path||"",family:Reflect.get(e[0],"family"),session:Reflect.get(e[0],"session"),auth:Reflect.get(e[0],"auth"),timeout:Reflect.get(e[0],"timeout"),allowHalfOpen:Reflect.get(e[0],"allowHalfOpen")},t]}throw new Error(`Invalid arguments passed to net.connect: ${e}`)}function writePendingData(e,t,s,r){if(Array.isArray(t)){for(let s=0;se.description==="connect-options"));if(t==null)return;return Reflect.get(e,t)}function getAddressInfoByConnectionOptions(e){if(e==null)return{};const t=e.family===6||H.isIPv6(e.host||"");return{address:t?"::1":"127.0.0.1",port:Number(e.port)||(e.protocol==="https:"?443:80),family:t?"IPv6":"IPv4"}}function getLocalAddressInfoByConnectionOptions(e){if(e==null)return{};const t=e.family===6||H.isIPv6(e.host||"");return{address:e.localAddress||(t?"::1":"127.0.0.1"),port:e.localPort||getEphemeralPort(),family:t?"IPv6":"IPv4"}}function getEphemeralPort(){return 49152+Math.floor(Math.random()*16384)}const D=Symbol("kListenerWrap");const w=Symbol("kRawSocket");const v=Symbol("kPatched");const M=createLogger("socket");function toServerSocket(e){const t=[];let s;let r=false;let o=false;const flushPendingWrites=()=>{if(e.connecting){r=true;if(!o){o=true;e.once("ready",(()=>{o=false;flushPendingWrites()}))}return false}while(t.length>0){const s=t.shift();e._unrefTimer();const o=e.push(toBuffer(s.chunk,s.encoding),s.encoding);s.callback?.();if(!o){r=true;return false}}const n=r;r=false;if(s){const t=s;s=void 0;if(t.chunk!=null)e.push(toBuffer(t.chunk,t.encoding),t.encoding);e.push(null);t.callback?.()}if(n)e.emit("internal:drain");return true};const n=e._read.bind(e);e._read=e=>{n(e);if(t.length>0||s!=null||r)flushPendingWrites()};return new Proxy(e,{get:(e,o,n)=>{const getRealValue=()=>Reflect.get(e,o,n);if(o==="on"||o==="addListener"||o==="once"||o==="prependListener"||o==="prependOnceListener"){const t=getRealValue();return(s,r)=>{if(s==="data"){const listenerWrap=(e,t)=>{r(toBuffer(e,t))};Object.defineProperty(r,D,{enumerable:false,writable:false,value:listenerWrap});Reflect.apply(t,e,["internal:write",listenerWrap]);return e}if(s==="drain"){Reflect.apply(t,e,["internal:drain",r]);return e}return t.call(e,s,r)}}if(o==="off"||o==="removeListener"){const t=getRealValue();return(s,r)=>{if(s==="data"){const s=r[D];if(s)return t.call(e,"internal:write",s)}if(s==="drain")return t.call(e,"internal:drain",r);return t.call(e,s,r)}}if(o==="write")return(e,s,o)=>{if(typeof s==="function"){o=s;s=void 0}t.push({chunk:e,encoding:s,callback:o});if(r)return false;return flushPendingWrites()};if(o==="end")return(...t)=>{const r=t[t.length-1];s={chunk:typeof t[0]==="function"?void 0:t[0],encoding:typeof t[1]==="string"?t[1]:void 0,callback:typeof r==="function"?r:void 0};flushPendingWrites();return e};return getRealValue()}})}var U=class SocketController{static{this.PENDING=0}static{this.CLAIMED=1}static{this.PASSTHROUGH=2}#N=0;constructor(e){this[w]=e;e[v]=true;this.readyState=SocketController.PENDING}claim(){invariant(this.readyState===SocketController.PENDING,"Failed to claim a socket connection: already handled (%s)",this.readyState);this.readyState=SocketController.CLAIMED}passthrough(){invariant(this.readyState===SocketController.PENDING,"Failed to passthrough a socket connection: already handled (%s)",this.readyState);this.readyState=SocketController.PASSTHROUGH}awaitVerdicts(e){this.#N=e;if(this.#N===0)this.passthrough()}decline(){if(this.readyState!==SocketController.PENDING)return;this.#N-=1;if(this.#N<=0)process.nextTick((()=>{if(this.readyState===SocketController.PENDING&&!this[w].destroyed)this.passthrough()}))}};var q=class extends U{#k;#P;#b;#I=null;#H=[];#L=false;#D=[];#w=false;#v=false;#M=false;#U=false;#q=false;constructor(e,t,s){super(e);this.socket=e;this.createConnection=t;this.#k=s;this.socket._read=()=>{this.#I?.resume()};this.#b=this.socket._writeGeneric;this.#H=[];this.socket._writeGeneric=(...e)=>{this.#B(e)};this.socket.connect=new Proxy(this.socket.connect,{apply:(e,t,s)=>{M.verbose("socket.connect() %o",s);this.#k=s[0];if(s[0]!=null&&typeof s[0]==="object"&&(s[0].localAddress!=null||s[0].localPort!=null))s[0]={...s[0],localAddress:void 0,localPort:void 0};return Reflect.apply(e,t,s)}});e.on("free",(()=>{M.verbose("client socket freed!");this.reset()})).on("close",(()=>{M.verbose("client socket closed!");this.#M=true;this.#I?.destroy();this.#I=null;this.#H=[];this.#L=false;this.#D=[]}));this.serverSocket=toServerSocket(this.socket);this.pendingConnection=Promise.withResolvers();this.#F()}reset(e){if(e!=null){this.#P=e;this.#k=e;if(this.#I){this.removePassthroughSocketListeners?.();this.#I.destroy();this.#I=null;this.#w=false}}if(this.readyState===U.PENDING)return;this.#F()}scheduleReset(){this.#v=true}#F(){M.verbose("resetting the socket...");this.#v=false;this.readyState=U.PENDING;this.pendingConnection=Promise.withResolvers();this.#H=[];this.#q=false;this.socket._pendingData=null;this.socket._pendingEncoding="";const wrapHandle=e=>{this.pendingConnection.promise.then((()=>{M.verbose("connection request resolved!",this.readyState);process.nextTick((()=>{if(this.readyState===U.PENDING&&this.socket.connecting&&this.#H.length===0&&this.socket.listenerCount("connect")>0){M.verbose('assume connect->write socket, calling "connect" listeners...');this.emulateConnect()}}))}));if(e.setTypeOfService)e.setTypeOfService=void 0;e.connect=e.connect6=t=>{M.verbose("handle.connect()");this.pendingConnection.resolve([t,e])};M.verbose("socket handle wrapped! waiting for connection request...")};if(this.socket._handle)wrapHandle(this.socket._handle);else this.socket.prependOnceListener("connectionAttempt",(()=>{wrapHandle(this.socket._handle)}))}#B(e){const t=e[1];M.verbose("socket write (state: %d) %o",this.readyState,e);if(this.#v)this.reset();this.#H.push(e);if(this.readyState===U.PENDING){const e=Array.isArray(this.socket._pendingData)?this.socket._pendingData:[];unwrapPendingData(t,((t,s)=>{e.push({chunk:t,encoding:s})}));this.socket._pendingData=e;if(this.socket.listenerCount("internal:write")===0){M.verbose("no server data listeners, scheduling to the next tick...");process.nextTick((()=>{this.#x(t)}))}else this.#x(t)}else this.#x(t);switch(this.readyState){case U.PENDING:if(!this.#H.includes(e))this.#H.push(e);this.#G(e);return;case U.CLAIMED:this.#W(e);this.#G(e);return;case U.PASSTHROUGH:if(!this.#W(e))return;if(!this.#w&&this.#I){writePendingData(this.#I,t,e[2],e[3]);return}this.#b.apply(this.socket,e)}}#G(e){const t=e[3];if(typeof t==="function"){t();e[3]=void 0}}#W(e){const t=this.#H.indexOf(e);if(t===-1)return false;this.#H.splice(t,1);return true}emulateConnect(){this.#q=true;Reflect.set(this.socket,"connecting",false);for(const e of this.socket.rawListeners("connect"))e.apply(this.socket)}#x=e=>{if(e==null)return;M.verbose("server push %o",e);unwrapPendingData(e,((e,t)=>{M.verbose('server emitting "data" %o',{chunk:e,encoding:t});this.socket.emit("internal:write",e,t)}))};#j=()=>{if(!this.#I)return;if(this.socket.destroyed){this.#I.destroy();return}const e=this.socket._handle;const t=e!=null&&typeof e.hasRef==="function"&&!e.hasRef();this.socket._handle=this.#I._handle;this.#w=true;if(t)this.socket._handle.unref?.();if(e!=null){e.close();e._parent?.close()}Reflect.set(this.socket,"connecting",false);this.socket.remoteAddress;this.socket.emit("connect");this.socket.emit("ready")};#V=(e,t,s,r)=>{this.socket.emit("connectionAttemptFailed",e,t,s,r)};#K=(e,t,s)=>{this.socket.emit("connectionAttemptTimeout",e,t,s)};#X=e=>{M.verbose('real socket "data" event %o',e);this.socket._unrefTimer();if(this.#L){M.verbose("reads are corked, buffering the data...");this.#D.push({type:"data",chunk:e});return}if(!this.socket.push(e)){M.verbose("client socket forbade more pushes, pausing the passthrough socket...");this.#I?.pause()}};#$=e=>{M.verbose('real socket "error" event %o',e);if(this.socket.destroyed){M.verbose("real socket errored but client socket already destroyed, skipping...");return}M.verbose("real socket errored, forwarding %o",e);this.socket.destroy(e);if(this.#w)process.nextTick((()=>this.socket.emit("close",true)))};#Y=()=>{this.socket._unrefTimer();if(this.#L){this.#D.push({type:"end"});return}this.#U=true;this.socket.push(null)};#z=e=>{if(this.#w&&this.socket._handle)this.socket._handle.shutdown=()=>1;if(this.#L){this.#D.push({type:"close",hadError:e});return}if(this.#M)return;if(this.socket.destroyed&&!this.#w)return;this.#Q(e)};#Q(e){if(this.#M)return;if(this.#U&&!this.socket.readableEnded&&!this.socket.destroyed){let t=false;const deliverClose=s=>{if(t)return;t=true;process.nextTick((()=>{this.#Q(s??e)}))};this.socket.once("end",(()=>{deliverClose()}));const s=this.socket._destroy;this.socket._destroy=(e,t)=>{deliverClose(e!=null);return s.call(this.socket,e,t)};return}this.socket.destroy();if(this.#w)this.socket.emit("close",e)}#J=()=>{M.verbose("client socket drained!");this.#I?.resume()};#Z=()=>{if(!this.#w)this.#I?.end()};corkReads(){this.#L=true}uncorkReads(){if(!this.#L)return;this.#L=false;for(const e of this.#D.splice(0))switch(e.type){case"data":if(!this.socket.push(e.chunk)){M.verbose("client socket forbade more pushes, pausing the passthrough socket...");this.#I?.pause()}break;case"end":this.#U=true;this.socket.push(null);break;case"close":this.#Q(e.hadError);break}}claim(){super.claim();if(this.socket.destroyed){M.verbose("socket already destroyed, skipping claim...");return}if(!this.socket.connecting&&!this.#q){M.verbose("socket already connected, skipping claim...");return}M.verbose("-> claim!");this.socket._handle.getsockname=e=>{Object.assign(e,getLocalAddressInfoByConnectionOptions(this.#k));return 0};this.socket._handle.getpeername=e=>{Object.assign(e,getAddressInfoByConnectionOptions(this.#k));return 0};this.#H=[];this.socket._pendingData=null;this.socket._pendingEncoding="";this.pendingConnection.promise.then((([e,t])=>{M.verbose("connection request resolved, mocking the connection...");if(this.#q)Reflect.set(this.socket,"connecting",true);e.oncomplete(0,t,e,true,true)}))}passthrough(e){super.passthrough();M.verbose("-> passthrough!");const createRealSocket=()=>{const e=this.#P?this.#ee(this.#P):this.createConnection();e[v]=true;e.allowHalfOpen=true;if(this.socket.timeout!=null)e.setTimeout(this.socket.timeout);return e};const t=this.#I&&!this.#I.destroyed?this.#I:createRealSocket();const s=t!==this.#I;this.#I=t;if(this.#H.length===0)M.verbose("passthrough with empty writes buffer (state: %d)",this.readyState);for(let s=0;s{r[1]=e}))}const[,o,n,i]=r;writePendingData(t,o,n,i)}this.#H=[];this.socket._pendingData=null;this.socket._pendingEncoding="";this.socket.address=t.address.bind(t);this.socket.removeListener("drain",this.#J);this.socket.on("drain",this.#J);if(s){this.removePassthroughSocketListeners=this.addPassthroughSocketListeners(t);t.once("close",this.removePassthroughSocketListeners)}if(!this.#w)if(this.socket.writableFinished)this.#Z();else{this.socket.removeListener("finish",this.#Z);this.socket.once("finish",this.#Z)}return t}addPassthroughSocketListeners(e){e.once("connect",this.#j).on("connectionAttemptFailed",this.#V).on("connectionAttemptTimeout",this.#K).on("data",this.#X).on("error",this.#$).on("end",this.#Y).on("close",this.#z);return()=>{e.removeListener("connect",this.#j).removeListener("connectionAttemptFailed",this.#V).removeListener("connectionAttemptTimeout",this.#K).removeListener("data",this.#X).removeListener("error",this.#$).removeListener("end",this.#Y).removeListener("close",this.#z)}}#ee(e){const t=new H.Socket;t[v]=true;return t.connect(e)}};var B=class extends q{#te;constructor(e,t,s){super(e,t,s);this.socket=e;this.createConnection=t;this.#te=s;e.prependListener("secureConnect",(()=>{e.alpnProtocol=e._handle.getALPNNegotiatedProtocol()}))}emulateConnect(){if(this.#te){const e=this.socket._handle.getALPNNegotiatedProtocol();this.#te.ALPNProtocols=e?[e]:[]}super.emulateConnect();for(const e of this.socket.rawListeners("secureConnect"))e.apply(this.socket)}claim(){if(this.socket.destroyed){super.claim();return}this.socket.prependOnceListener("secureConnect",(()=>{Reflect.set(this.socket,"authorized",false);Reflect.set(this.socket,"authorizationError","MOCKED_CONNECTION_NOT_VERIFIED")}));const e=this.socket._handle;e.start=()=>void 0;e.verifyError=()=>void 0;e.getSession=()=>Buffer.from("mocked session");const t=getTlsConnectOptions(this.socket);if(t)t.checkServerIdentity=()=>{};e.getCipher=()=>({name:"TLS_AES_256_GCM_SHA384",standardName:"TLS_AES_256_GCM_SHA384",version:"TLSv1.3"});e.getEphemeralKeyInfo=()=>({type:"ECDH",name:"X25519",size:253});const s=this.#te?.ALPNProtocols;if(Array.isArray(s)&&s.length>0){const[t]=s;e.getALPNNegotiatedProtocol=()=>typeof t==="string"?t:false}this.socket.once("connect",(()=>{const t="0".repeat(64);const s="0".repeat(96);for(const e of["SERVER_HANDSHAKE_TRAFFIC_SECRET","EXPORTER_SECRET","SERVER_TRAFFIC_SECRET_0","CLIENT_HANDSHAKE_TRAFFIC_SECRET","CLIENT_TRAFFIC_SECRET_0"])this.socket.emit("keylog",Buffer.from(`${e} ${t} ${s}\n`));e.onhandshakedone();e.onnewsession(1,Buffer.from("mocked session"));e.onnewsession(2,Buffer.from("mocked session"))}));super.claim()}passthrough(e){const t=super.passthrough(e);for(const e of this.socket.listeners("connect"))if(e===this.socket._start||"listener"in e&&e.listener===this.socket._start)this.socket.removeListener("connect",e);return t}#se=()=>{this.socket.emit("secure")};#re=e=>{this.socket.emit("session",e)};#oe=e=>{this.socket.emit("keylog",e)};#ne=e=>{this.socket.emit("OCSPResponse",e)};addPassthroughSocketListeners(e){const t=super.addPassthroughSocketListeners(e);e.on("secure",this.#se).on("session",this.#re).on("keylog",this.#oe).on("OCSPResponse",this.#ne);return()=>{t();e.removeListener("secure",this.#se).removeListener("session",this.#re).removeListener("keylog",this.#oe).removeListener("OCSPResponse",this.#ne)}}};function normalizeTlsConnectArgs(e){const t=normalizeNetConnectArgs(e);const s=t[0];const r=t[1];if(e[0]!==null&&typeof e[0]==="object")Object.assign(s,e[0]);else if(e[1]!==null&&typeof e[1]==="object")Object.assign(s,e[1]);else if(e[2]!==null&&typeof e[2]==="object")Object.assign(s,e[2]);return r?[s,r]:[s]}globalThis.__MSW_INTERNAL_CONNECTION_CONTEXT??=(()=>{const e=new I.AsyncLocalStorage;return{run(t){return e.run({consumed:false},t)},consume(){const t=e.getStore();if(!t||t.consumed)return false;t.consumed=true;return true}}})();var F=class extends a{constructor(e){super(...["connection",{}]);this.socket=e.socket;this.connectionOptions=e.connectionOptions;this.controller=e.controller}};const x=createLogger("socket");const mockLookup=(e,t,s)=>{const r=t.family===6?6:4;const o=r===6?"::1":"127.0.0.1";process.nextTick((()=>{if(t.all){s(null,[{address:o,family:r}]);return}s(null,o,r)}))};var G=class extends p{static{this.symbol=Symbol.for("socket-interceptor")}predicate(){return true}setup(){const e=this;let t=false;this.subscriptions.push(P.applyPatch(H.Socket.prototype,"connect",(s=>function connect(...r){const o=this;if(o[v]||t)return s.apply(o,r);if(globalThis.__MSW_INTERNAL_CONNECTION_CONTEXT?.consume()){o[v]=true;return s.apply(o,r)}x.verbose("socket.connect() %o",r);const n=Array.isArray(r[0])?r[0]:r;const[i,a]=normalizeNetConnectArgs(n);x.verbose("connection options %o",{transportConnectionOptions:i,connectionCallback:a});let c;let l;if(o instanceof L.TLSSocket){const e=getTlsConnectOptions(o);const[s]=normalizeTlsConnectArgs([{...i,...e}]);l=s;c=new B(o,(()=>{t=true;try{return L.connect(s)}finally{t=false}}),s)}else{const e=n.filter((e=>typeof e!=="function"));const t=n[0]!==null&&typeof n[0]==="object"&&!("href"in n[0])?n[0]:{};l=i;c=new q(o,(()=>{const r=new H.Socket(t);Reflect.apply(s,r,e);return r}))}process.nextTick((()=>{if(o.destroyed)return;c.awaitVerdicts(e.listenerCount("connection"));e.emitter.emit(new F({socket:c.serverSocket,controller:c,connectionOptions:l}));x.verbose('emitted "connection" event!')}));x.verbose("connecting the socket...");const u={...i};u.lookup=mockLookup;try{return o.connect(u,a??void 0)}catch(e){o.destroy();throw e}})),this.#ie())}#ie(){if(typeof b.Agent.prototype.addRequest!=="function")return()=>{};return P.applyPatch(b.Agent.prototype,"addRequest",(e=>function(...t){for(const e of Object.values(this.freeSockets)){if(e==null)continue;for(const t of e)if(!t[v])t.destroy()}return e?.apply(this,t)}))}};var W=require("node:stream");var j=require("node:fs");async function until(e){try{return[null,await e().catch((e=>{throw e}))]}catch(e){return[e,null]}}var V=Object.create;var K=Object.defineProperty;var X=Object.getOwnPropertyDescriptor;var $=Object.getOwnPropertyNames;var Y=Object.getPrototypeOf;var z=Object.prototype.hasOwnProperty;var __commonJSMin=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports);var __copyProps=(e,t,s,r)=>{if(t&&typeof t==="object"||typeof t==="function")for(var o=$(t),n=0,i=o.length,a;nt[e]).bind(null,a),enumerable:!(r=X(t,a))||r.enumerable})}return e};var __toESM=(e,t,s)=>(s=e!=null?V(Y(e)):{},__copyProps(t||!e||!e.__esModule?K(s,"default",{value:e,enumerable:true}):s,e));const Q=new I.AsyncLocalStorage;function runInRequestContext(e,t){if(Q.getStore())return e();const s={initiator:void 0,logger:t};return Q.run(s,(()=>{const t=e();s.initiator=t;return t}))}const J=createLogger("http-request");function forwardHttpEvents(e){const t=new AbortController;const{source:s,emitter:r,predicate:o,responsePredicate:n}=e;s.on("request",(async e=>{if(o(e.initiator)){J.verbose('forwarding "request" event %o',{requestId:e.requestId});await r.emitAsPromise(e)}}),{signal:t.signal});const responseListener=async e=>{if(o(e.initiator)&&(n==null||n(e))){J.verbose('forwarding "response" event %o',{requestId:e.requestId,responseType:e.responseType});await r.emitAsPromise(e)}};const unhandledExceptionListener=async e=>{if(o(e.initiator)){J.verbose('forwarding "unhandledException" event %o',{requestId:e.requestId});await r.emitAsPromise(e)}};const addResponseListener=()=>{if(!s.listeners("response").includes(responseListener))s.on("response",responseListener,{signal:t.signal})};const addUnhandledExceptionListener=()=>{if(!s.listeners("unhandledException").includes(unhandledExceptionListener))s.on("unhandledException",unhandledExceptionListener,{signal:t.signal})};if(r.listenerCount("response")>0)addResponseListener();if(r.listenerCount("unhandledException")>0)addUnhandledExceptionListener();r.hooks.on("newListener",(e=>{if(e==="response")addResponseListener();if(e==="unhandledException")addUnhandledExceptionListener()}),{signal:t.signal,persist:true});r.hooks.on("removeListener",(e=>{if(e==="response"&&r.listenerCount("response")===0)s.removeListener("response",responseListener);if(e==="unhandledException"&&r.listenerCount("unhandledException")===0)s.removeListener("unhandledException",unhandledExceptionListener)}),{signal:t.signal,persist:true});return()=>{t.abort()}}var Z=class extends a{constructor(e){super(...["request",{}]);this.request=e.request;this.requestId=e.requestId;this.initiator=e.initiator;this.controller=e.controller}};var ee=class extends a{constructor(e){super(...["response",{}]);this.response=e.response;this.responseType=e.responseType;this.request=e.request;this.requestId=e.requestId;this.initiator=e.initiator}};var te=class extends a{constructor(e){super(...["unhandledException",{}]);this.error=e.error;this.request=e.request;this.requestId=e.requestId;this.initiator=e.initiator;this.controller=e.controller}};function connectionOptionsToUrl(e,t){const s=H.isIPv6(e.host||"");const r=t instanceof L.TLSSocket?"https:":getProtocolByConnectionOptions(e);const o=e.host||"localhost";const n=new URL(`${r}//${s?`[${o}]`:o}`);if(e.path)n.pathname=e.path;if(e.port)n.port=e.port.toString();if(e.auth){const[t,s]=e.auth.split(":");n.username=encodeURIComponent(t);n.password=encodeURIComponent(s)}return n}function getProtocolByConnectionOptions(e){if(e.protocol)return e.protocol;if(e.port===443)return"https:";return"http:"}var se=__toESM(__commonJSMin((e=>{Object.defineProperty(e,"__esModule",{value:true});e.SPECIAL_HEADERS=e.MINOR=e.MAJOR=e.QDTEXT=e.CONNECTION_TOKEN_CHARS=e.RELAXED_HEADER_CHARS=e.HEADER_CHARS=e.HTAB_SP_VCHAR_OBS_TEXT=e.SP=e.HTAB=e.TOKEN=e.HEX=e.URL_CHAR=e.USERINFO_CHARS=e.MARK=e.ALPHANUM=e.DIGIT=e.HEX_MAP=e.NUM_MAP=e.ALPHA=e.METHODS=e.METHODS_HTTP=e.METHODS_HTTP2=e.METHODS_HTTP1=e.METHODS_RTSP=e.METHODS_RAOP=e.METHODS_AIRPLAY=e.METHODS_ICECAST=e.METHODS_NON_STANDARD=e.METHODS_CALDAV=e.METHODS_UPNP=e.METHODS_SUBVERSION=e.METHODS_WEBDAV=e.METHODS_BASIC_HTTP=e.METHODS_HTTP1_HEAD=e.HEADER_STATE=e.FINISH=e.STATUSES=e.LENIENT_FLAGS=e.FLAGS=e.TYPE=e.ERROR=void 0;e.ERROR={OK:0,INTERNAL:1,STRICT:2,CR_EXPECTED:25,LF_EXPECTED:3,UNEXPECTED_CONTENT_LENGTH:4,UNEXPECTED_SPACE:30,CLOSED_CONNECTION:5,INVALID_METHOD:6,INVALID_URL:7,INVALID_CONSTANT:8,INVALID_VERSION:9,INVALID_HEADER_TOKEN:10,INVALID_CONTENT_LENGTH:11,INVALID_CHUNK_SIZE:12,INVALID_STATUS:13,INVALID_EOF_STATE:14,INVALID_TRANSFER_ENCODING:15,CB_MESSAGE_BEGIN:16,CB_HEADERS_COMPLETE:17,CB_MESSAGE_COMPLETE:18,CB_CHUNK_HEADER:19,CB_CHUNK_COMPLETE:20,PAUSED:21,PAUSED_UPGRADE:22,PAUSED_H2_UPGRADE:23,USER:24,CB_URL_COMPLETE:26,CB_STATUS_COMPLETE:27,CB_METHOD_COMPLETE:32,CB_VERSION_COMPLETE:33,CB_HEADER_FIELD_COMPLETE:28,CB_HEADER_VALUE_COMPLETE:29,CB_CHUNK_EXTENSION_NAME_COMPLETE:34,CB_CHUNK_EXTENSION_VALUE_COMPLETE:35,CB_RESET:31,CB_PROTOCOL_COMPLETE:38};e.TYPE={BOTH:0,REQUEST:1,RESPONSE:2};e.FLAGS={CONNECTION_KEEP_ALIVE:1,CONNECTION_CLOSE:2,CONNECTION_UPGRADE:4,CHUNKED:8,UPGRADE:16,CONTENT_LENGTH:32,SKIPBODY:64,TRAILING:128,TRANSFER_ENCODING:512};e.LENIENT_FLAGS={HEADERS:1,CHUNKED_LENGTH:2,KEEP_ALIVE:4,TRANSFER_ENCODING:8,VERSION:16,DATA_AFTER_CLOSE:32,OPTIONAL_LF_AFTER_CR:64,OPTIONAL_CRLF_AFTER_CHUNK:128,OPTIONAL_CR_BEFORE_LF:256,SPACES_AFTER_CHUNK_SIZE:512,HEADER_VALUE_RELAXED:1024};e.STATUSES={CONTINUE:100,SWITCHING_PROTOCOLS:101,PROCESSING:102,EARLY_HINTS:103,RESPONSE_IS_STALE:110,REVALIDATION_FAILED:111,DISCONNECTED_OPERATION:112,HEURISTIC_EXPIRATION:113,MISCELLANEOUS_WARNING:199,OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,ALREADY_REPORTED:208,TRANSFORMATION_APPLIED:214,IM_USED:226,MISCELLANEOUS_PERSISTENT_WARNING:299,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,SWITCH_PROXY:306,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,PAGE_EXPIRED:419,ENHANCE_YOUR_CALM:420,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL:430,REQUEST_HEADER_FIELDS_TOO_LARGE:431,LOGIN_TIMEOUT:440,NO_RESPONSE:444,RETRY_WITH:449,BLOCKED_BY_PARENTAL_CONTROL:450,UNAVAILABLE_FOR_LEGAL_REASONS:451,CLIENT_CLOSED_LOAD_BALANCED_REQUEST:460,INVALID_X_FORWARDED_FOR:463,REQUEST_HEADER_TOO_LARGE:494,SSL_CERTIFICATE_ERROR:495,SSL_CERTIFICATE_REQUIRED:496,HTTP_REQUEST_SENT_TO_HTTPS_PORT:497,INVALID_TOKEN:498,CLIENT_CLOSED_REQUEST:499,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,BANDWIDTH_LIMIT_EXCEEDED:509,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511,WEB_SERVER_UNKNOWN_ERROR:520,WEB_SERVER_IS_DOWN:521,CONNECTION_TIMEOUT:522,ORIGIN_IS_UNREACHABLE:523,TIMEOUT_OCCURED:524,SSL_HANDSHAKE_FAILED:525,INVALID_SSL_CERTIFICATE:526,RAILGUN_ERROR:527,SITE_IS_OVERLOADED:529,SITE_IS_FROZEN:530,IDENTITY_PROVIDER_AUTHENTICATION_ERROR:561,NETWORK_READ_TIMEOUT:598,NETWORK_CONNECT_TIMEOUT:599};e.FINISH={SAFE:0,SAFE_WITH_CB:1,UNSAFE:2};e.HEADER_STATE={GENERAL:0,CONNECTION:1,CONTENT_LENGTH:2,TRANSFER_ENCODING:3,UPGRADE:4,CONNECTION_KEEP_ALIVE:5,CONNECTION_CLOSE:6,CONNECTION_UPGRADE:7,TRANSFER_ENCODING_CHUNKED:8};e.METHODS_HTTP1_HEAD={HEAD:2};e.METHODS_BASIC_HTTP={DELETE:0,GET:1,...e.METHODS_HTTP1_HEAD,POST:3,PUT:4,CONNECT:5,OPTIONS:6,TRACE:7,PATCH:28,LINK:31,UNLINK:32};e.METHODS_WEBDAV={COPY:8,LOCK:9,MKCOL:10,MOVE:11,PROPFIND:12,PROPPATCH:13,SEARCH:14,UNLOCK:15,BIND:16,REBIND:17,UNBIND:18,ACL:19};e.METHODS_SUBVERSION={REPORT:20,MKACTIVITY:21,CHECKOUT:22,MERGE:23};e.METHODS_UPNP={"M-SEARCH":24,NOTIFY:25,SUBSCRIBE:26,UNSUBSCRIBE:27};e.METHODS_CALDAV={MKCALENDAR:30};e.METHODS_NON_STANDARD={PURGE:29,QUERY:46};e.METHODS_ICECAST={SOURCE:33};e.METHODS_AIRPLAY={GET:1,POST:3};e.METHODS_RAOP={FLUSH:45};e.METHODS_RTSP={OPTIONS:e.METHODS_BASIC_HTTP.OPTIONS,DESCRIBE:35,ANNOUNCE:36,SETUP:37,PLAY:38,PAUSE:39,TEARDOWN:40,GET_PARAMETER:41,SET_PARAMETER:42,REDIRECT:43,RECORD:44,...e.METHODS_AIRPLAY,...e.METHODS_RAOP};e.METHODS_HTTP1={...e.METHODS_BASIC_HTTP,...e.METHODS_WEBDAV,...e.METHODS_SUBVERSION,...e.METHODS_UPNP,...e.METHODS_CALDAV,...e.METHODS_NON_STANDARD,...e.METHODS_ICECAST};e.METHODS_HTTP2={PRI:34};e.METHODS_HTTP={...e.METHODS_HTTP1,...e.METHODS_HTTP2};e.METHODS={...e.METHODS_HTTP1,...e.METHODS_HTTP2,...e.METHODS_RTSP};e.ALPHA=["A","a","B","b","C","c","D","d","E","e","F","f","G","g","H","h","I","i","J","j","K","k","L","l","M","m","N","n","O","o","P","p","Q","q","R","r","S","s","T","t","U","u","V","v","W","w","X","x","Y","y","Z","z"];e.NUM_MAP={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9};e.HEX_MAP={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15};e.DIGIT=["0","1","2","3","4","5","6","7","8","9"];e.ALPHANUM=[...e.ALPHA,...e.DIGIT];e.MARK=["-","_",".","!","~","*","'","(",")"];e.USERINFO_CHARS=[...e.ALPHANUM,...e.MARK,"%",";",":","&","=","+","$",","];e.URL_CHAR=["!",'"',"$","%","&","'","(",")","*","+",",","-",".","/",":",";","<","=",">","@","[","\\","]","^","_","`","{","|","}","~",...e.ALPHANUM];e.HEX=[...e.DIGIT,"a","b","c","d","e","f","A","B","C","D","E","F"];e.TOKEN=["!","#","$","%","&","'","*","+","-",".","^","_","`","|","~",...e.ALPHANUM];e.HTAB=["\t"];e.SP=[" "];const t=[33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126];const s=[128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255];e.HTAB_SP_VCHAR_OBS_TEXT=[...e.HTAB,...e.SP,...t,...s];e.HEADER_CHARS=e.HTAB_SP_VCHAR_OBS_TEXT;e.RELAXED_HEADER_CHARS=[...[1,2,3,4,5,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,127],...e.HEADER_CHARS];e.CONNECTION_TOKEN_CHARS=[...e.HTAB,...e.SP,33,34,35,36,37,38,39,40,41,42,43,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,...s];e.QDTEXT=[...e.HTAB,...e.SP,33,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,...s];e.MAJOR=e.NUM_MAP;e.MINOR=e.MAJOR;e.SPECIAL_HEADERS={connection:e.HEADER_STATE.CONNECTION,"content-length":e.HEADER_STATE.CONTENT_LENGTH,"proxy-connection":e.HEADER_STATE.CONNECTION,"transfer-encoding":e.HEADER_STATE.TRANSFER_ENCODING,upgrade:e.HEADER_STATE.UPGRADE};e.default={ERROR:e.ERROR,TYPE:e.TYPE,FLAGS:e.FLAGS,LENIENT_FLAGS:e.LENIENT_FLAGS,STATUSES:e.STATUSES,FINISH:e.FINISH,HEADER_STATE:e.HEADER_STATE,ALPHA:e.ALPHA,NUM_MAP:e.NUM_MAP,HEX_MAP:e.HEX_MAP,DIGIT:e.DIGIT,ALPHANUM:e.ALPHANUM,MARK:e.MARK,USERINFO_CHARS:e.USERINFO_CHARS,URL_CHAR:e.URL_CHAR,HEX:e.HEX,TOKEN:e.TOKEN,HEADER_CHARS:e.HEADER_CHARS,RELAXED_HEADER_CHARS:e.RELAXED_HEADER_CHARS,CONNECTION_TOKEN_CHARS:e.CONNECTION_TOKEN_CHARS,QDTEXT:e.QDTEXT,HTAB_SP_VCHAR_OBS_TEXT:e.HTAB_SP_VCHAR_OBS_TEXT,MAJOR:e.MAJOR,MINOR:e.MINOR,SPECIAL_HEADERS:e.SPECIAL_HEADERS,METHODS:e.METHODS,METHODS_HTTP:e.METHODS_HTTP,METHODS_HTTP1_HEAD:e.METHODS_HTTP1_HEAD,METHODS_HTTP1:e.METHODS_HTTP1,METHODS_HTTP2:e.METHODS_HTTP2,METHODS_ICECAST:e.METHODS_ICECAST,METHODS_RTSP:e.METHODS_RTSP}}))(),1);const re=se.TYPE.REQUEST;se.TYPE.RESPONSE;const oe=Symbol("kPtr");const ne=Symbol("kUrl");const ie=Symbol("kStatusMessage");const ae=Symbol("kHeadersFields");const ce=Symbol("kHeadersValues");const le=Symbol("kLastHeaderCallback");const ue=Symbol("kCallbacks");const he=Symbol("kType");const de=0;const pe=1;const fe=2;const Ee=new Map;const Re=Object.fromEntries(Object.entries(se.METHODS).map((([e,t])=>[t,e])));function readStringFrom(e,t){return Buffer.from(ge.buffer,e,t).toString("latin1")}const Se=require("url").pathToFileURL(__filename).href;const Te=new WebAssembly.Module(j.readFileSync(new URL("./llhttp/llhttp.wasm",Se)));const _e=new WebAssembly.Instance(Te,{env:{wasm_on_message_begin(e){const t=Ee.get(e);t[ne]="";t[ie]="";t[ae]=[];t[ce]=[];t[le]=de;return t[ue].onMessageBegin?.()??0},wasm_on_url(e,t,s){Ee.get(e)[ne]=readStringFrom(t,s);return 0},wasm_on_status(e,t,s){Ee.get(e)[ie]=readStringFrom(t,s);return 0},wasm_on_header_field(e,t,s){const r=Ee.get(e);const o=readStringFrom(t,s);const n=r[ae];if(r[le]===pe)n[n.length-1]+=o;else{n.push(o);r[le]=pe}return 0},wasm_on_header_value(e,t,s){const r=Ee.get(e);const o=readStringFrom(t,s);const n=r[ce];if(r[le]===fe)n[n.length-1]+=o;else{n.push(o);r[le]=fe}return 0},wasm_on_headers_complete(e,t,s,r){const o=Ee.get(e);const n=ke(e);const i=Ne(e);const a=[];const c=s===1;const l=r===1;for(let e=0;e{this.#le=o;const n=(s||e.connectionOptions.method||"GET").toUpperCase();const i=new URL(r||"",e.connectionOptions.url);const a=C.parseRawHeaders([...t]);if(i.username||i.password){if(!a.has("authorization")){const e=Buffer.from(`${i.username}:${i.password}`).toString("base64");a.set("authorization",`Basic ${e}`)}i.username="";i.password=""}this.#ce=new W.Readable({read:()=>{}});const c=new AbortController;const l=new A(i,{method:n,headers:a,credentials:"same-origin",body:W.Readable.toWeb(this.#ce),signal:c.signal});e.onRequest(l,c)},onBody:e=>{invariant(this.#ce,"Failed to write to a request stream: stream does not exist. This is likely an issue with the library. Please report it on GitHub.");this.#ce.push(e)},onMessageComplete:()=>{this.#ce?.push(null);this.#ce=void 0;if(!this.#le)e.onMessageComplete?.()}})}free(e){this.destroy();this.#ce?.destroy(e);this.#ce=void 0}};var we=class extends Le{#ue;#m=0;constructor(e){super(2,{onError:e.onError,onHeadersComplete:({rawHeaders:t,statusCode:s,statusMessage:r})=>{this.#m=s;const o=C.parseRawHeaders([...t]);const n=new C(C.isResponseWithBody(s)?W.Readable.toWeb(this.#ue=new W.Readable({read(){}})):null,{status:s,statusText:r,headers:o});e.onResponse(n)},onBody:e=>{invariant(this.#ue,"Failed to read from a response stream: stream does not exist. This is likely an issue with the library. Please report it on GitHub.");this.#ue.push(e)},onMessageComplete:()=>{this.#ue?.push(null);this.#ue=null;e.onMessageComplete?.(this.#m)}})}free(e){this.destroy();if(e)this.#ue?.destroy(e);this.#ue=null}};function isNodeLikeError(e){if(e==null)return false;if(!(e instanceof Error))return false;return"code"in e&&"errno"in e}async function handleRequest(e){if(e.logger?.isEnabled("default"))formatRequest(e.request).then((t=>{e.logger?.info("[%s] %s",e.requestId,t)}));const handleResponse=async t=>{if(t instanceof Error){await e.controller.errorWith(t);return true}if(isResponseError(t)){await e.controller.respondWith(t);return true}if(isResponseLike(t)){await e.controller.respondWith(t);return true}if(isObject(t)){await e.controller.errorWith(t);return true}return false};const handleResponseError=async t=>{if(t instanceof S)throw o;if(isNodeLikeError(t)){await e.controller.errorWith(t);return true}if(t instanceof Response)return await handleResponse(t);return false};const t=Promise.withResolvers();let s;let r=false;const onAbort=()=>{r=true;s=e.request.signal?.reason;t.reject(s)};if(e.request.signal){if(e.request.signal.aborted){await e.controller.errorWith(e.request.signal.reason);return}e.request.signal.addEventListener("abort",onAbort,{once:true})}const[o]=await until((async()=>{const s=new Z({initiator:e.initiator,requestId:e.requestId,request:e.request,controller:e.controller});const r=e.emitter.emitAsPromise(s);await Promise.race([t.promise,r,e.controller.handled]);if(s.request!==e.request)e.request=s.request}));e.request.signal?.removeEventListener("abort",onAbort);if(r){await e.controller.errorWith(s);return}if(o){if(await handleResponseError(o))return;if(e.emitter.listenerCount("unhandledException")>0){const t=new T(e.request,{passthrough(){},async respondWith(e){await handleResponse(e)},async errorWith(t){await e.controller.errorWith(t)}});await e.emitter.emitAsPromise(new te({initiator:e.initiator,error:o,request:e.request,requestId:e.requestId,controller:t}));if(t.readyState!==T.PENDING)return}await e.controller.respondWith(createServerErrorResponse(o));return}if(e.controller.readyState===T.PENDING)return await e.controller.passthrough();return e.controller.handled}function cloneResponse(e){const t=C.clone(e);if(!e.body||!t.body)return[e,t];const s=wrapResponse(t);return[wrapResponse(e,s.cancel).response,s.response]}function wrapResponse(e,t){const s=e.body;const r=s.getReader();const cancel=e=>s.locked?r.cancel(e):s.cancel(e);const o=new C(new ReadableStream({async pull(e){try{const{done:t,value:s}=await r.read();if(t){e.close();r.releaseLock();return}e.enqueue(s)}catch(t){e.error(t);r.releaseLock()}},async cancel(e){try{const s=cancel(e);if(t)await Promise.all([s,t(e)]);else s.catch((()=>{}))}finally{r.releaseLock()}}},{highWaterMark:0}),e);copyRawHeaders(e.headers,o.headers);Object.defineProperties(o,{type:{value:e.type},redirected:{value:e.redirected}});return{response:o,cancel:cancel}}const ve=createLogger("http-request");var Me=class extends p{static{this.symbol=Symbol.for("node-http-request-source")}predicate(){return true}setup(){const e=p.singleton(G);e.apply(this);this.subscriptions.push((()=>{e.dispose(this)}));this.subscriptions.push(recordRawFetchHeaders());const t=new AbortController;this.subscriptions.push((()=>t.abort()));e.on("connection",(({connectionOptions:e,socket:t,controller:s})=>{let r;let o;let n;let i;let a;const stopParsingRequests=e=>{ve.verbose("stopping HTTP request parsing: %o",e);r=false;if(a?.readyState===T.PENDING)a.passthrough();else s.decline();o?.free(e)};const c=Q.getStore();const l=s[w];const u=l._destroy.bind(l);l._destroy=(e,t)=>{i?.();u(e,t)};const addRequestDataListener=()=>{const executeRequestParser=(e,s)=>{if(e.execute(s)!==null){t.removeListener("data",onRequestData);e.free();o=void 0}};const onRequestData=l=>{if(r===false){s.decline();return}if(n&&!o){r=void 0;s.reset({host:n.hostname,port:Number(n.port)||80,path:null})}if(o){executeRequestParser(o,toBuffer(l));return}const u=l.toString();const h=u.split(" ")[0]||"";if(!b.METHODS.includes(h.toUpperCase())){r=false;s.decline();return}r=true;const d=n??connectionOptionsToUrl(e,t);ve.verbose("handling http message %o",{httpMessage:u,httpMethod:h,baseUrl:d});const p=Q.getStore()??c;const f=p?.initiator||t;o=new De({onError:stopParsingRequests,connectionOptions:{method:h,url:d},onMessageComplete:()=>{s.scheduleReset()},onRequest:async(e,o)=>{const c=p?.transformRequest?.(e)??e;if(s["readyState"]!==U.PENDING)s.reset();const l=createRequestId();const u=p?.logger??ve;ve.verbose("received a parsed HTTP request %o",{method:c.method,url:c.url});const h=new T(c,{respondWith:async e=>{ve.verbose("respondWith() %o",{status:e.status,statusText:e.statusText,hasBody:e.body!=null});if(t.destroyed)return;s.claim();const r=C.from(e,{url:c.url});const[o,i]=!isResponseError(r)&&this.emitter.listenerCount("response")>0?cloneResponse(r):[r,null];if(c.method==="CONNECT"&&o.ok){n=new URL(`http://${c.url}`);addRequestDataListener()}const respond=()=>this.respondWith({socket:s[w],request:d.request,response:o});if(i)await this.emitter.emitAsPromise(new ee({initiator:f,requestId:l,request:d.request,response:i,responseType:"mock"}));if(t.connecting)t.once("connect",respond);else await respond()},errorWith:e=>{if(e instanceof Error)t.destroy(e)},passthrough:()=>{const e=s.passthrough(r===false?void 0:this.#he(d.request));if(r===false)return;if(this.emitter.listenerCount("response")>0){ve.verbose('found "response" listener, corking socket reads');s.corkReads();let t=false;let r=false;let o=false;const n=new we({onError:e=>{disposeResponseParser(e);s.uncorkReads()},onMessageComplete:e=>{r=e>=200||e===101},onResponse:async e=>{o=e.status>=200||e.status===101;ve.verbose("HTTP response parser parsed: %d %s",e.status,e.statusText);if(isResponseError(e)){ve.verbose("response is an error response, uncorking socket reads...");s.uncorkReads();return}C.setUrl(c.url,e);try{ve.verbose('emitting "response" event');await this.emitter.emitAsPromise(new ee({initiator:f,requestId:l,request:d.request,response:e,responseType:"original"}))}finally{ve.verbose("uncorking socket reads");s.uncorkReads();if(!t&&e.status<200&&e.status!==101)s.corkReads()}}});const onResponseData=e=>{n.execute(e);if(r)disposeResponseParser()};const onResponseEnd=()=>{disposeResponseParser();if(!o)s.uncorkReads()};const disposeResponseParser=s=>{t=true;e.removeListener("data",onResponseData);e.removeListener("end",onResponseEnd);e.removeListener("close",onResponseEnd);n.free(s)};e.on("data",onResponseData).once("end",onResponseEnd).once("close",onResponseEnd)}}},{logger:u,requestId:l});invariant(s["readyState"]===U.PENDING,"CANNOT HANDLE ALREADY HANDLED REQUEST",c.method,c.url,s["readyState"]);const d={initiator:f,requestId:l,request:c,controller:h,emitter:this.emitter,logger:u};i=()=>{if(h.readyState===T.PENDING)o.abort()};a=h;try{await handleRequest(d)}finally{a=void 0;i=void 0}}});executeRequestParser(o,toBuffer(l))};t.on("data",onRequestData)};addRequestDataListener();t.on("close",(()=>o?.free()))}),{signal:t.signal})}async respondWith(e){const{socket:t,request:s,response:r}=e;if(t.destroyed)return;if(isResponseError(r)){t.destroy(Object.defineProperty(new TypeError("Network error"),O,{value:r,enumerable:false}));return}invariant(!t.connecting,'Failed to mock a response for "%s %s": socket has not connected',s.method,s.url);const o=new b.IncomingMessage(t);o.method=s.method;const n=new b.ServerResponse(o);const i=new H.Socket;i._writeGeneric=(e,s,r,o)=>{unwrapPendingData(s,((e,s)=>{t.push(toBuffer(e),s)}));o?.()};i._destroy=(e,s)=>{if(e)t.destroy();s(null)};i.on("drain",(()=>n.emit("drain")));n.assignSocket(i);n.removeHeader("connection");n.removeHeader("date");const a=getRawFetchHeaders(r.headers);n.writeHead(r.status,r.statusText||b.STATUS_CODES[r.status],a);t._destroy=function(e,t){if(e)queueMicrotask((()=>this.emit("error",e)));t(null);process.nextTick((()=>this.emit("close",e!=null)))};if(r.body){const e=r.body.getReader();try{while(true){const{done:t,value:s}=await e.read();if(t){n.end();break}if(!n.write(s))await new Promise((e=>{n.once("drain",e)}))}}catch{await new Promise((e=>process.nextTick(e)));t.destroy();return}}else n.end();const c=s.method==="HEAD"||r.headers.has("content-length")||r.headers.has("transfer-encoding")||!C.isResponseWithBody(r.status);if(s.method==="CONNECT"&&!r.ok||s.method!=="CONNECT"&&!c){await new Promise((e=>process.nextTick(e)));t.push(null)}}#he(e){const transformRequestMessage=(t,s)=>{if(s==="buffer")return t;const r=t.toString(s).split("\r\n");const o=r.findIndex((e=>e===""));const n=r.slice(1,o);const i=n.map((e=>{const t=e.indexOf(": ");return[e.slice(0,t),e.slice(t+2)]}));const a=getRawFetchHeaders(e.headers);if(i.length===a.length&&i.every(((e,t)=>{const s=a[t];return e[0]===s[0]&&e[1]===s[1]})))return t;const c=C.parseRawHeaders(n.flatMap((e=>e.split(": "))));const l=new Set;for(const[t]of a){const s=t.toLowerCase();if(l.has(s))continue;l.add(s);const r=e.headers.get(t);if(r===null)continue;c.set(t,r)}l.clear();const u=Array.from(c).map((([e,t])=>`${e}: ${t}`)).join("\r\n");r.splice(1,o-1,u);return r.join("\r\n")};return(e,t,s)=>{if(Array.isArray(e))e[0].chunk=transformRequestMessage(e[0].chunk,e[0].encoding);else e=transformRequestMessage(e,t);s(e)}}};var Ue=require("node:https");var qe=class extends p{static{this.symbol=Symbol.for("client-request-interceptor")}predicate(){return true}setup(){const e=p.singleton(Me);const t=this.logger;e.apply(this);this.subscriptions.push((()=>{e.dispose(this)}));this.subscriptions.push(forwardHttpEvents({source:e,emitter:this.emitter,predicate:e=>e instanceof b.ClientRequest}));this.subscriptions.push(P.applyPatch(b,"ClientRequest",(e=>new Proxy(e,{construct(e,s,r){return runInRequestContext((()=>Reflect.construct(e,s,r)),t)}}))),P.applyPatch(b,"get",(e=>function mockHttpGet(...s){return runInRequestContext((()=>e(...s)),t)})),P.applyPatch(b,"request",(e=>function mockHttpRequest(...s){return runInRequestContext((()=>e(...s)),t)})),P.applyPatch(Ue,"get",(e=>function mockHttpsGet(...s){return runInRequestContext((()=>e(...s)),t)})),P.applyPatch(Ue,"request",(e=>function mockHttpsRequest(...s){return runInRequestContext((()=>e(...s)),t)})))}}}};var t={};function __nccwpck_require__(s){var r=t[s];if(r!==undefined){return r.exports}var o=t[s]={exports:{}};var n=true;try{e[s](o,o.exports,__nccwpck_require__);n=false}finally{if(n)delete t[s]}return o.exports}!function(){__nccwpck_require__.d=function(e,t){for(var s in t){if(__nccwpck_require__.o(t,s)&&!__nccwpck_require__.o(e,s)){Object.defineProperty(e,s,{enumerable:true,get:t[s]})}}}}();!function(){__nccwpck_require__.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}}();!function(){__nccwpck_require__.r=function(e){if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})}Object.defineProperty(e,"__esModule",{value:true})}}();if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var s=__nccwpck_require__(349);module.exports=s})(); \ No newline at end of file diff --git a/packages/next/src/server/use-cache/use-cache-wrapper.ts b/packages/next/src/server/use-cache/use-cache-wrapper.ts index 4af9bfe939f4..918f9558393b 100644 --- a/packages/next/src/server/use-cache/use-cache-wrapper.ts +++ b/packages/next/src/server/use-cache/use-cache-wrapper.ts @@ -2122,20 +2122,19 @@ export async function cache( const temporaryReferences = createClientTemporaryReferenceSet() - // The base serialized cache key doesn't include the cookies or headers that - // private caches are allowed to read. In production this is because private - // cache entries aren't stored in a cache handler, only in the Resume Data - // Cache (RDC): private caches are only used during dynamic requests and - // runtime prefetches; for dynamic requests the RDC is immutable and excludes - // private caches, and for runtime prefetches it's mutable but lives only as - // long as the request. In development private caches are persisted across - // requests, so `cacheHandlerKeyBase` (below) additionally scopes the handler - // key by the request's cookies and headers. - const cacheKeyParts: CacheKeyParts = [ - id, - args, - await computeCacheKeyImplementationPart(workStore, workUnitStore, id), - ] + // The base serialized cache key doesn't include runtime env var state or the + // cookies and headers that private caches are allowed to read. Env var state + // only scopes the cache handler because the RDC must reuse entries across + // rendering phases. In production private cache entries aren't stored in a + // cache handler, only in the Resume Data Cache (RDC): private caches are only + // used during dynamic requests and runtime prefetches; for dynamic requests + // the RDC is immutable and excludes private caches, and for runtime prefetches + // it's mutable but lives only as long as the request. In development private + // caches are persisted across requests, so `cacheHandlerKeyBase` (below) + // additionally scopes the handler key by the request's cookies and headers. + const { implementationPart, runtimeEnvVarStateHash } = + await computeCacheKeyImplementationPart(workStore, workUnitStore, id) + const cacheKeyParts: CacheKeyParts = [id, args, implementationPart] const encodeCacheKeyParts = () => encodeReply(cacheKeyParts, { @@ -2270,19 +2269,19 @@ export async function cache( // The coarse cache-handler key. With no root params read, it locates the // entry directly; otherwise it locates a redirect entry from which the - // specific key (this key + root params, computed below) is derived. For - // private caches in development (persisted in the built-in in-memory handler) - // it's additionally scoped by the request's cookies and headers, so entries - // for requests with different request data don't collide; keys derived from - // it inherit that scoping. + // specific key (this key + root params, computed below) is derived. It's + // scoped by runtime env var state and, for private caches in development + // (persisted in the built-in in-memory handler), the request's cookies and + // headers. Keys derived from it inherit that scoping. const cacheHandlerKeyBase = - process.env.__NEXT_DEV_SERVER && cacheContext.kind === 'private' - ? serializedCacheKey + - computePrivateCacheKeyRequestSuffix( + serializedCacheKey + + (runtimeEnvVarStateHash ?? '') + + (process.env.__NEXT_DEV_SERVER && cacheContext.kind === 'private' + ? computePrivateCacheKeyRequestSuffix( cacheContext.outerWorkUnitStore.cookies, cacheContext.outerWorkUnitStore.headers ) - : serializedCacheKey + : '') // If we already know which root params this function reads, include them in // the cache handler key for a direct hit (skipping the redirect entry). // rootParams is undefined when nested inside unstable_cache. @@ -3672,8 +3671,12 @@ export async function cache( } /** - * This returns a cache key that has to cover everything that can affect the result of the cached - * function (apart from the arguments). So + * This returns cache key parts that cover everything that can affect the result of the cached + * function (apart from the arguments). The implementation part is used by both the RDC and cache + * handler, while the runtime env var state hash is only used by the cache handler. The RDC is + * per-page and must reuse entries across rendering phases even if an env var changes between them. + * + * The parts cover: * - codeHash: the code itself that generates the return value * - Notably, this excludes the following modules. Those are included via the Next.js version anyway: * - react, react-dom, private-next-rsc-server-reference, private-next-rsc-cache-wrapper @@ -3688,7 +3691,10 @@ async function computeCacheKeyImplementationPart( workStore: WorkStore, workUnitStore: WorkUnitStore, id: string -): Promise { +): Promise<{ + implementationPart: unknown + runtimeEnvVarStateHash: string | undefined +}> { let durability = workStore.durableUseCacheEntries ? getServerActionsManifest().node[id].workers?.[ normalizeWorkerPageName(workStore.page) @@ -3715,8 +3721,12 @@ async function computeCacheKeyImplementationPart( ) .digest('hex') - // When more accurate analysis information is available, use codeHash + runtime env vars - return [durability.codeHash, nextVersion, runtimeEnvVarStateHash] + // The env var state is added to the cache handler key separately so it + // doesn't affect RDC lookups between rendering phases. + return { + implementationPart: [durability.codeHash, nextVersion], + runtimeEnvVarStateHash, + } } else { // Because the Action ID is not yet unique per implementation of that Action we can't // safely reuse the results across builds yet. In the meantime we add the buildId to the @@ -3732,7 +3742,12 @@ async function computeCacheKeyImplementationPart( const hmrRefreshHash = getHmrRefreshHash(workUnitStore) // otherwise fall back to buildId and/or the HMR hash. - return hmrRefreshHash ? [buildId, hmrRefreshHash] : [buildId] + return { + implementationPart: hmrRefreshHash + ? [buildId, hmrRefreshHash] + : [buildId], + runtimeEnvVarStateHash: undefined, + } } } diff --git a/packages/react-refresh-utils/package.json b/packages/react-refresh-utils/package.json index 438155695762..6b5c5acfb7ac 100644 --- a/packages/react-refresh-utils/package.json +++ b/packages/react-refresh-utils/package.json @@ -1,6 +1,6 @@ { "name": "@next/react-refresh-utils", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "description": "An experimental package providing utilities for React Refresh.", "repository": { "url": "vercel/next.js", diff --git a/packages/third-parties/package.json b/packages/third-parties/package.json index d0ac385361e6..0248038d48ce 100644 --- a/packages/third-parties/package.json +++ b/packages/third-parties/package.json @@ -1,6 +1,6 @@ { "name": "@next/third-parties", - "version": "16.4.0-canary.28", + "version": "16.4.0-canary.29", "repository": { "url": "vercel/next.js", "directory": "packages/third-parties" @@ -26,7 +26,7 @@ "third-party-capital": "1.0.20" }, "devDependencies": { - "next": "16.4.0-canary.28", + "next": "16.4.0-canary.29", "outdent": "0.8.0", "prettier": "2.5.1", "typescript": "6.0.2" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index be27e4c0863e..0994b0272205 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1012,7 +1012,7 @@ importers: packages/eslint-config-next: dependencies: '@next/eslint-plugin-next': - specifier: 16.4.0-canary.28 + specifier: 16.4.0-canary.29 version: link:../eslint-plugin-next eslint: specifier: '>=9.0.0' @@ -1095,7 +1095,7 @@ importers: packages/next: dependencies: '@next/env': - specifier: 16.4.0-canary.28 + specifier: 16.4.0-canary.29 version: link:../next-env '@swc/helpers': specifier: 0.5.23 @@ -1210,25 +1210,25 @@ importers: specifier: 1.18.1 version: 1.18.1(patch_hash=680fe4edb7abd1de29d08cdf217a22506e815a8cc1c2282201d5d47aa3e5da12) '@mswjs/interceptors': - specifier: 0.42.0 - version: 0.42.0 + specifier: 0.42.5 + version: 0.42.5 '@napi-rs/triples': specifier: 1.2.0 version: 1.2.0 '@next/font': - specifier: 16.4.0-canary.28 + specifier: 16.4.0-canary.29 version: link:../font '@next/polyfill-module': - specifier: 16.4.0-canary.28 + specifier: 16.4.0-canary.29 version: link:../next-polyfill-module '@next/polyfill-nomodule': - specifier: 16.4.0-canary.28 + specifier: 16.4.0-canary.29 version: link:../next-polyfill-nomodule '@next/react-refresh-utils': - specifier: 16.4.0-canary.28 + specifier: 16.4.0-canary.29 version: link:../react-refresh-utils '@next/swc': - specifier: 16.4.0-canary.28 + specifier: 16.4.0-canary.29 version: link:../next-swc '@opentelemetry/api': specifier: 1.6.0 @@ -1971,7 +1971,7 @@ importers: version: 1.0.20 devDependencies: next: - specifier: 16.4.0-canary.28 + specifier: 16.4.0-canary.29 version: link:../next outdent: specifier: 0.8.0 @@ -4588,8 +4588,8 @@ packages: resolution: {integrity: sha512-3rDakgJZ77+RiQUuSK69t1F0m8BQKA8Vh5DCS5V0DWvNY67zob2JhhQrhCO0AKLGINTRSFd1tBaHcJTkhefoSw==} engines: {node: '>=18'} - '@mswjs/interceptors@0.42.0': - resolution: {integrity: sha512-HFjFa93wzY++HEC50SpTRMGCAlzA2y71a0H2io3vysc/QYQ0PJVrJuo3CXKcVPe5mOxT7FMwKBNuCouAoIeLxQ==} + '@mswjs/interceptors@0.42.5': + resolution: {integrity: sha512-mrHZiA/nh6OV5punS+GKzG9iZoryKRIg0DhIeu1v1OlOUAJDQ4+d4GWtMSXa/L88NBmn+j0eqQgyygNOn2dCoQ==} engines: {node: '>=22'} '@napi-rs/cli@3.7.2': @@ -21831,7 +21831,7 @@ snapshots: outvariant: 1.4.2 strict-event-emitter: 0.5.1 - '@mswjs/interceptors@0.42.0': + '@mswjs/interceptors@0.42.5': dependencies: '@open-draft/until': 3.0.1 '@types/debug': 4.1.13 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 33e83211d500..418af8a7364b 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -36,7 +36,7 @@ ignoredBuiltDependencies: blockExoticSubdeps: true minimumReleaseAge: 2880 # 48 hrs minimumReleaseAgeExclude: - - '@mswjs/interceptors@0.42.0' + - '@mswjs/interceptors@0.42.5' - '@next/*' - '@turbo/*' - '@types/react@19.2.18' diff --git a/test/e2e/opentelemetry/instrumentation/collector.ts b/test/e2e/opentelemetry/instrumentation/collector.ts index 9c03d03c7783..8caa8adc4e22 100644 --- a/test/e2e/opentelemetry/instrumentation/collector.ts +++ b/test/e2e/opentelemetry/instrumentation/collector.ts @@ -40,6 +40,9 @@ export async function connectCollector({ return true }) spans.push(...filteredSpans) + // Exporters can leave pooled sockets idle between tests. Close each + // response so a server keep-alive timeout cannot drop a later export. + res.setHeader('Connection', 'close') res.statusCode = 202 res.end() }) diff --git a/test/e2e/opentelemetry/instrumentation/opentelemetry.test.ts b/test/e2e/opentelemetry/instrumentation/opentelemetry.test.ts index f391ef6236ac..cd9981977216 100644 --- a/test/e2e/opentelemetry/instrumentation/opentelemetry.test.ts +++ b/test/e2e/opentelemetry/instrumentation/opentelemetry.test.ts @@ -137,6 +137,16 @@ describe.each( await expectAppRouteTrace('/api/app/param/data') }) + it('closes collector connections after each export', async () => { + const response = await fetch(`http://localhost:${COLLECTOR_PORT}`, { + method: 'POST', + body: '[]', + }) + + expect(response.status).toBe(202) + expect(response.headers.get('connection')).toBe('close') + }) + // Edge runtime is currently not implemented in custom-entrypoint-server.ts const itEdge = useDirectEntrypointHandler ? it.skip : it diff --git a/test/production/app-dir/use-cache-cross-deployment/app/env-mutation/[slug]/mutate-env.tsx b/test/production/app-dir/use-cache-cross-deployment/app/env-mutation/[slug]/mutate-env.tsx new file mode 100644 index 000000000000..224f87bb36c6 --- /dev/null +++ b/test/production/app-dir/use-cache-cross-deployment/app/env-mutation/[slug]/mutate-env.tsx @@ -0,0 +1,4 @@ +export function MutateEnv() { + process.env.MUTATED_DURING_CACHE_GENERATION = '1' + return null +} diff --git a/test/production/app-dir/use-cache-cross-deployment/app/env-mutation/[slug]/page.tsx b/test/production/app-dir/use-cache-cross-deployment/app/env-mutation/[slug]/page.tsx new file mode 100644 index 000000000000..1a023dddd559 --- /dev/null +++ b/test/production/app-dir/use-cache-cross-deployment/app/env-mutation/[slug]/page.tsx @@ -0,0 +1,45 @@ +import { cacheLife } from 'next/cache' +import { Suspense } from 'react' +import { cookies } from 'next/headers' +import { MutateEnv } from './mutate-env' + +export const prefetch = 'partial' + +async function CachedValue({ slug }: { slug: string }) { + 'use cache' + cacheLife('days') + + const value = process.env.MUTATED_DURING_CACHE_GENERATION ?? 'unset' + + return ( + <> +

{`${slug}:${value}`}

+ + + ) +} + +async function Content({ slug }: { slug: string }) { + if (slug === 'known') { + await cookies() + } + + return +} + +export default async function Page({ + params, +}: { + params: Promise<{ slug: string }> +}) { + const { slug } = await params + return ( + + + + ) +} + +export function generateStaticParams() { + return [{ slug: 'known' }] +} diff --git a/test/production/app-dir/use-cache-cross-deployment/use-cache-cross-deployment.test.ts b/test/production/app-dir/use-cache-cross-deployment/use-cache-cross-deployment.test.ts index 7a85a690e727..3cb6ffe59f70 100644 --- a/test/production/app-dir/use-cache-cross-deployment/use-cache-cross-deployment.test.ts +++ b/test/production/app-dir/use-cache-cross-deployment/use-cache-cross-deployment.test.ts @@ -220,6 +220,38 @@ describe.each(['NEXT_DEPLOYMENT_ID', 'BUILD_ID', 'default'])( await next.deleteFile('handler-remote-data.json') }) + it('should not miss when an env var changes during cache generation', async () => { + // Regression test for mutating env vars which changes the cache key mid-rendering and breaks + // the multi-phase rendering process (be it within the next build prerendering, or in the + // resume case at runtime). + // RDC stores cache entries, and we should use those entries regardless of whether env vars + // changed in the meantime (among other things, to prevent tearing). + // + // Error: Route "foo": Unexpected cache miss after cache warming phase during prerendering. + // This is likely caused by non-deterministic arguments that differ between the cache warming + // phase and the final prerender phase (e.g. unstable array order). Ensure that arguments + // passed to cached functions are deterministic. + // + // Error: Route "foo": Next.js encountered uncached or runtime data during prerendering. + await next.stop() + delete next.env.MUTATED_DURING_CACHE_GENERATION + + try { + await next.start() + const output = next.getCliOutputFromHere() + const browser = await next.browser('/env-mutation/test') + + expect(output()).not.toContain('Error') + expect(output()).not.toContain( + 'Unexpected cache miss after cache warming phase during prerendering' + ) + expect(await browser.elementById('data').text()).toBe('test:unset') + } finally { + await next.stop() + delete next.env.MUTATED_DURING_CACHE_GENERATION + } + }) + it('should not recompute when nothing changes', async () => { const key1 = await execute(next, 'NEXT_DEPLOYMENT_ID', 'dpl-id-1') const key2 = await execute(next, 'NEXT_DEPLOYMENT_ID', 'dpl-id-2') diff --git a/turbopack/crates/turbo-rcstr/src/dynamic.rs b/turbopack/crates/turbo-rcstr/src/dynamic.rs index 93bc7a7a07bc..81de8a7838c9 100644 --- a/turbopack/crates/turbo-rcstr/src/dynamic.rs +++ b/turbopack/crates/turbo-rcstr/src/dynamic.rs @@ -1,4 +1,4 @@ -use std::{num::NonZeroU8, ptr::NonNull}; +use std::{borrow::Cow, num::NonZeroU8, ptr::NonNull}; use triomphe::Arc; @@ -47,9 +47,11 @@ pub unsafe fn restore_arc(v: TaggedValue) -> Arc { /// This can create any kind of [Atom], although this lives in the `dynamic` /// module. -pub(crate) fn new_atom + Into>(text: T) -> RcStr { - let text = text.as_ref(); - if is_atom_inlineable(text) { +/// +/// Takes a [`Cow`] rather than a `&str` so that an already-owned string can be moved into the atom +/// instead of being copied into a new allocation. +pub(crate) fn new_atom(text: Cow<'_, str>) -> RcStr { + if is_atom_inlineable(&text) { let len = text.len(); // INLINE_TAG ensures this is never zero let tag = INLINE_TAG_INIT | ((len as u8) << LEN_OFFSET); @@ -64,7 +66,8 @@ pub(crate) fn new_atom + Into>(text: T) -> RcStr { let prehashed = DynamicPrehashedString { // NOTE: This will capture as a Box which will essentially - // `shrink_to_fit` the bytes. + // `shrink_to_fit` the bytes. `Box`'s own `From>` impl already moves an + // owned string's buffer in rather than copying it. value: text.into(), hash, }; diff --git a/turbopack/crates/turbo-rcstr/src/lib.rs b/turbopack/crates/turbo-rcstr/src/lib.rs index 4deda1869c2d..7fd8ae6a878f 100644 --- a/turbopack/crates/turbo-rcstr/src/lib.rs +++ b/turbopack/crates/turbo-rcstr/src/lib.rs @@ -718,6 +718,37 @@ mod tests { use super::*; + /// An `RcStr` built from an owned string takes over its buffer instead of copying it. Only a + /// non-inline string can show this: an inline atom stores its bytes in the tagged value, so it + /// has no buffer to take over. + #[test] + fn from_owned_cow_takes_over_the_buffer() { + let mut string = "a string far too long to be stored inline".to_string(); + // So that `String::into_boxed_str` has no reason to reallocate. + string.shrink_to_fit(); + let ptr = string.as_ptr(); + + let rc_str = RcStr::from(Cow::Owned(string)); + + assert!( + rc_str.tag() == DYNAMIC_TAG, + "the test string must not be inlineable" + ); + assert_eq!( + rc_str.as_str().as_ptr(), + ptr, + "the owned buffer should have been taken over, not copied" + ); + } + + /// There is no buffer to take over here, so this only pins the contents. + #[test] + fn from_borrowed_cow_copies() { + let string = "a string far too long to be stored inline"; + let rc_str = RcStr::from(Cow::Borrowed(string)); + assert_eq!(rc_str.as_str(), string); + } + #[test] fn test_refcount() { fn refcount(str: &RcStr) -> usize { diff --git a/turbopack/crates/turbo-tasks-fs/src/path.rs b/turbopack/crates/turbo-tasks-fs/src/path.rs index 8b28719bb47c..8f76e0efec1c 100644 --- a/turbopack/crates/turbo-tasks-fs/src/path.rs +++ b/turbopack/crates/turbo-tasks-fs/src/path.rs @@ -131,10 +131,7 @@ impl FileSystemPath { return None; } - Some(match get_relative_request_to(&self.path, &other.path) { - Cow::Borrowed(path) => path.into(), - Cow::Owned(path) => path.into(), - }) + Some(get_relative_request_to(&self.path, &other.path).into()) } /// Returns the final component of the FileSystemPath, or an empty string @@ -794,63 +791,11 @@ mod tests { use super::*; use crate::VirtualFileSystem; - /// Builds two paths on the same filesystem and returns them. - fn paths_on_one_fs( - fs: ResolvedVc>, - from: &str, - target: &str, - ) -> (FileSystemPath, FileSystemPath) { - ( - FileSystemPath::new_normalized_unchecked(fs, from.into()), - FileSystemPath::new_normalized_unchecked(fs, target.into()), - ) - } - - #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn test_get_relative_path_to() { - let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new( - BackendOptions::default(), - noop_backing_storage(), - )); - tt.run_once(async move { - let fs = Vc::upcast::>(VirtualFileSystem::new()) - .to_resolved() - .await?; - - for (from, target, expected) in [ - ("a/b/c", "a/b/c", "."), - ("a/c/d", "a/b/c", "../../b/c"), - ("", "a/b/c", "a/b/c"), - ("a/b", "a/b/c", "c"), - ("a/b/c", "", "../../.."), - ("a/b/c", "c/b/a", "../../../c/b/a"), - ] { - let (from_path, target_path) = paths_on_one_fs(fs, from, target); - assert_eq!( - from_path.get_relative_path_to(&target_path).as_deref(), - Some(expected), - "{from:?} -> {target:?}" - ); - } - - // A path on another filesystem is not reachable relatively. - let (from_path, _) = paths_on_one_fs(fs, "a/b", "a/b/c"); - let other_fs = Vc::upcast::>(VirtualFileSystem::new()) - .to_resolved() - .await?; - let on_other_fs = FileSystemPath::new_normalized_unchecked(other_fs, rcstr!("a/b/c")); - assert_eq!(from_path.get_relative_path_to(&on_other_fs), None); - - anyhow::Ok(()) - }) - .await - .unwrap(); - } - - /// The cases this covers are the ones `get_relative_path_to` was asserted against before it - /// stopped prefixing `./`, so they pin that the request form still produces them. + /// `turbo-unix-path` covers how the relative path itself is computed, so this only pins what + /// this layer adds: that each method reaches for the form it names, and that neither crosses + /// between filesystems. #[tokio::test(flavor = "multi_thread", worker_threads = 2)] - async fn test_get_relative_request_to() { + async fn get_relative_to() { let tt = turbo_tasks::TurboTasks::new(TurboTasksBackend::new( BackendOptions::default(), noop_backing_storage(), @@ -859,30 +804,21 @@ mod tests { let fs = Vc::upcast::>(VirtualFileSystem::new()) .to_resolved() .await?; + let dir = FileSystemPath::new_normalized_unchecked(fs, rcstr!("a/b")); + let file = FileSystemPath::new_normalized_unchecked(fs, rcstr!("a/b/c.js")); - for (from, target, expected) in [ - ("a/b/c", "a/b/c", "."), - ("a/c/d", "a/b/c", "../../b/c"), - ("", "a/b/c", "./a/b/c"), - ("a/b", "a/b/c", "./c"), - ("a/b/c", "", "../../.."), - ("a/b/c", "c/b/a", "../../../c/b/a"), - ] { - let (from_path, target_path) = paths_on_one_fs(fs, from, target); - assert_eq!( - from_path.get_relative_request_to(&target_path).as_deref(), - Some(expected), - "{from:?} -> {target:?}" - ); - } + assert_eq!(dir.get_relative_path_to(&file).as_deref(), Some("c.js")); + assert_eq!( + dir.get_relative_request_to(&file).as_deref(), + Some("./c.js") + ); - // A path on another filesystem is not reachable relatively. - let (from_path, _) = paths_on_one_fs(fs, "a/b", "a/b/c"); let other_fs = Vc::upcast::>(VirtualFileSystem::new()) .to_resolved() .await?; - let on_other_fs = FileSystemPath::new_normalized_unchecked(other_fs, rcstr!("a/b/c")); - assert_eq!(from_path.get_relative_request_to(&on_other_fs), None); + let elsewhere = FileSystemPath::new_normalized_unchecked(other_fs, rcstr!("a/b/c.js")); + assert_eq!(dir.get_relative_path_to(&elsewhere), None); + assert_eq!(dir.get_relative_request_to(&elsewhere), None); anyhow::Ok(()) }) diff --git a/turbopack/crates/turbopack-browser/src/ecmascript/content.rs b/turbopack/crates/turbopack-browser/src/ecmascript/content.rs index 95fc436a1457..53104a180f50 100644 --- a/turbopack/crates/turbopack-browser/src/ecmascript/content.rs +++ b/turbopack/crates/turbopack-browser/src/ecmascript/content.rs @@ -14,7 +14,10 @@ use turbopack_core::{ version::{MergeableVersionedContent, Version, VersionedContent, VersionedContentMerger}, }; use turbopack_ecmascript::{ - chunk::{EcmascriptChunkContent, EcmascriptChunkContentEntries}, + chunk::{ + EcmascriptChunkContent, EcmascriptChunkContentEntries, strict_chunk_wrapper, + strict_factory_mode, write_module_factories, + }, hmr::{ EcmascriptHmrChunkContent, merger::EcmascriptChunkContentMerger, version::EcmascriptChunkVersion, @@ -85,6 +88,22 @@ impl EcmascriptBrowserChunkContent { *this.chunking_context.debug_ids_enabled().await?, ); + let supports_arrow_functions = *this + .chunking_context + .environment() + .runtime_versions() + .supports_arrow_functions() + .await?; + let content = this.content.await?; + let chunk_items = content.chunk_item_code_module_ids_and_paths().await?; + let strict_factory_mode = strict_factory_mode(&chunk_items, supports_arrow_functions); + + let strict_chunk_wrapper = + strict_chunk_wrapper(strict_factory_mode, supports_arrow_functions); + if let Some((prefix, _)) = strict_chunk_wrapper { + code += prefix; + } + // When a chunk is executed, it will either register itself with the current // instance of the runtime, or it will push itself onto the list of pending // chunks (using the configured chunk loading global variable). @@ -100,26 +119,18 @@ impl EcmascriptBrowserChunkContent { r#"(globalThis[{chunk_loading_global}] || (globalThis[{chunk_loading_global}] = [])).push([{script_or_path},"#, chunk_loading_global = StringifyJs(&chunk_loading_global), )?; + write_module_factories( + &mut code, + &chunk_items, + strict_factory_mode, + supports_arrow_functions, + )?; + write!(code, "\n]);")?; - let content = this.content.await?; - let mut chunk_items = content.chunk_item_code_module_ids_and_paths().await?; - // Sort items by their module path so that similar modules stay - // together so that the chunks gzips better. - chunk_items.sort_by(|a, b| { - a.first() - .map(|(id, _, path)| (path, id)) - .cmp(&b.first().map(|(id, _, path)| (path, id))) - }); - for item in &chunk_items { - for (id, item_code, _) in &**item { - write!(code, "\n{}, ", StringifyJs(id))?; - code.push_code(item_code); - write!(code, ",")?; - } + if let Some((_, suffix)) = strict_chunk_wrapper { + code += suffix; } - write!(code, "\n]);")?; - let mut code = code.build(); if let MinifyType::Minify { mangle } = *this.chunking_context.minify_type().await? { diff --git a/turbopack/crates/turbopack-ecmascript-runtime/js/src/shared/runtime/runtime-types.d.ts b/turbopack/crates/turbopack-ecmascript-runtime/js/src/shared/runtime/runtime-types.d.ts index ad44d98ebcf7..7fd9bda5343b 100644 --- a/turbopack/crates/turbopack-ecmascript-runtime/js/src/shared/runtime/runtime-types.d.ts +++ b/turbopack/crates/turbopack-ecmascript-runtime/js/src/shared/runtime/runtime-types.d.ts @@ -88,11 +88,15 @@ type ModuleCache = Record // TODO properly type values here type ModuleFactories = Map /** - * This is an alternating, non-empty arrow of module factory functions and module ids + * This is an alternating, non-empty array of module factory functions and module ids * `[id1, id2..., factory1, id3, factory2, id4, id5, factory3]` - * There can be multiple ids to support scope hoisted merged modules + * There can be multiple ids to support scope hoisted merged modules. + * The strict mode module factories of a chunk can be prepended as a nested array, + * which the chunk creates inside a `"use strict"` IIFE. */ -type CompressedModuleFactories = Array +type CompressedModuleFactories = Array< + ModuleId | Function | Array +> type RelativeURL = (inputUrl: string) => void type ResolvePathFromModule = (moduleId: string) => string diff --git a/turbopack/crates/turbopack-ecmascript-runtime/js/src/shared/runtime/runtime-utils.ts b/turbopack/crates/turbopack-ecmascript-runtime/js/src/shared/runtime/runtime-utils.ts index da41ee1b66e9..ddd1a7389b97 100644 --- a/turbopack/crates/turbopack-ecmascript-runtime/js/src/shared/runtime/runtime-utils.ts +++ b/turbopack/crates/turbopack-ecmascript-runtime/js/src/shared/runtime/runtime-utils.ts @@ -578,12 +578,9 @@ function getChunkPath(chunkData: ChunkData): ChunkPath { return typeof chunkData === 'string' ? chunkData : chunkData.path } -// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map. -// The CompressedModuleFactories format is -// - 1 or more module ids -// - a module factory function -// So walking this is a little complex but the flat structure is also fast to -// traverse, we can use `typeof` operators to distinguish the two cases. +// Load the CompressedModuleFactories of a chunk into the `moduleFactories` Map. +// The flat format alternates one or more module IDs with their factory function. +// Strict factories can be prepended as a nested array. function installCompressedModuleFactories( chunkModules: CompressedModuleFactories, offset: number, @@ -591,6 +588,16 @@ function installCompressedModuleFactories( newModuleId?: (id: ModuleId) => void ) { let i = offset + const strictFactories = chunkModules[i] + if (Array.isArray(strictFactories)) { + installCompressedModuleFactories( + strictFactories, + 0, + moduleFactories, + newModuleId + ) + i++ + } while (i < chunkModules.length) { let end = i + 1 // Find our factory function @@ -634,7 +641,7 @@ function installCompressedModuleFactories( newModuleId?.(id) } } - i = end + 1 // end is pointing at the last factory advance to the next id or the end of the array. + i = end + 1 } } diff --git a/turbopack/crates/turbopack-ecmascript/src/chunk/code_module_ids_and_paths.rs b/turbopack/crates/turbopack-ecmascript/src/chunk/code_module_ids_and_paths.rs index 7dececa5fa93..87203039de0a 100644 --- a/turbopack/crates/turbopack-ecmascript/src/chunk/code_module_ids_and_paths.rs +++ b/turbopack/crates/turbopack-ecmascript/src/chunk/code_module_ids_and_paths.rs @@ -2,7 +2,10 @@ use anyhow::Result; use rustc_hash::FxHashMap; use smallvec::{SmallVec, smallvec}; use turbo_rcstr::RcStr; -use turbo_tasks::{ReadRef, TryJoinIterExt, ValueToString, Vc}; +use turbo_tasks::{ + NonLocalValue, ReadRef, TryJoinIterExt, ValueToString, Vc, debug::ValueDebugFormat, + trace::TraceRawVcs, +}; use turbopack_core::{ chunk::{ChunkItem, ChunkItemExt, ModuleId}, code_builder::Code, @@ -13,8 +16,31 @@ use crate::chunk::{ EcmascriptChunkItemWithAsyncInfo, }; +async fn code_module_id_and_path( + item: &EcmascriptChunkItemWithAsyncInfo, +) -> Result { + let factory = item + .chunk_item + .code(item.async_info.map(|info| *info)) + .await?; + Ok(CodeModuleIdAndPath { + id: item.chunk_item.id().await?, + code: factory.code.to_code().await?, + path: item.chunk_item.asset_ident().to_string().owned().await?, + strict: factory.strict, + }) +} + +#[derive(Clone, PartialEq, Eq, TraceRawVcs, ValueDebugFormat, NonLocalValue)] +pub struct CodeModuleIdAndPath { + pub id: ModuleId, + pub code: ReadRef, + pub path: RcStr, + pub strict: bool, +} + #[turbo_tasks::value(transparent, serialization = "skip")] -pub struct CodeModuleIdsAndPaths(SmallVec<[(ModuleId, ReadRef, RcStr); 1]>); +pub struct CodeModuleIdsAndPaths(SmallVec<[CodeModuleIdAndPath; 1]>); #[turbo_tasks::value(transparent, serialization = "skip")] pub struct BatchGroupCodeModuleIdsAndPaths( @@ -48,29 +74,14 @@ pub async fn item_code_module_ids_and_paths( item: EcmascriptChunkItemOrBatchWithAsyncInfo, ) -> Result> { Ok(Vc::cell(match item { - EcmascriptChunkItemOrBatchWithAsyncInfo::ChunkItem(EcmascriptChunkItemWithAsyncInfo { - chunk_item, - async_info, - .. - }) => { - let id = chunk_item.id().await?; - let code = chunk_item.code(async_info.map(|info| *info)); - let path = chunk_item.asset_ident().to_string().owned().await?; - smallvec![(id, code.await?, path)] + EcmascriptChunkItemOrBatchWithAsyncInfo::ChunkItem(item) => { + smallvec![code_module_id_and_path(&item).await?] } EcmascriptChunkItemOrBatchWithAsyncInfo::Batch(batch) => batch .await? .chunk_items .iter() - .map(async |item| { - Ok(( - item.chunk_item.id().await?, - item.chunk_item - .code(item.async_info.map(|info| *info)) - .await?, - item.chunk_item.asset_ident().to_string().owned().await?, - )) - }) + .map(code_module_id_and_path) .try_join() .await? .into(), diff --git a/turbopack/crates/turbopack-ecmascript/src/chunk/content.rs b/turbopack/crates/turbopack-ecmascript/src/chunk/content.rs index a36221777890..ba816613f606 100644 --- a/turbopack/crates/turbopack-ecmascript/src/chunk/content.rs +++ b/turbopack/crates/turbopack-ecmascript/src/chunk/content.rs @@ -2,11 +2,11 @@ use std::future::IntoFuture; use anyhow::Result; use either::Either; -use turbo_tasks::{ReadRef, ResolvedVc, TryJoinIterExt, Vc}; +use turbo_tasks::{ResolvedVc, TryJoinIterExt, Vc}; use turbopack_core::chunk::{ChunkItem, ChunkItems, batch_info}; use crate::chunk::{ - CodeModuleIdsAndPaths, + CodeModuleIdAndPath, batch::{EcmascriptChunkItemBatchGroup, EcmascriptChunkItemOrBatchWithAsyncInfo}, batch_group_code_module_ids_and_paths, item_code_module_ids_and_paths, }; @@ -49,15 +49,21 @@ impl EcmascriptChunkContent { } impl EcmascriptChunkContent { - pub async fn chunk_item_code_module_ids_and_paths( - &self, - ) -> Result>> { - batch_info( + pub async fn chunk_item_code_module_ids_and_paths(&self) -> Result> { + let chunk_item_groups = batch_info( &self.batch_groups, &self.chunk_items, |batch| batch_group_code_module_ids_and_paths(batch).into_future(), |item| item_code_module_ids_and_paths(item.clone()).into_future(), ) - .await + .await?; + let mut chunk_items = chunk_item_groups + .iter() + .flat_map(|items| items.iter().cloned()) + .collect::>(); + // Sort all items by their module path so that similar modules stay + // together and the chunks gzip better. + chunk_items.sort_by(|a, b| (&a.path, &a.id).cmp(&(&b.path, &b.id))); + Ok(chunk_items) } } diff --git a/turbopack/crates/turbopack-ecmascript/src/chunk/content_entry.rs b/turbopack/crates/turbopack-ecmascript/src/chunk/content_entry.rs index 3abe23600eef..c42bcaaf64ff 100644 --- a/turbopack/crates/turbopack-ecmascript/src/chunk/content_entry.rs +++ b/turbopack/crates/turbopack-ecmascript/src/chunk/content_entry.rs @@ -29,7 +29,8 @@ impl EcmascriptChunkContentEntry { chunk_item: ResolvedVc>, async_module_info: Option>, ) -> Result { - let code = chunk_item.code(async_module_info).to_resolved().await?; + let factory = chunk_item.code(async_module_info).await?; + let code = factory.code.to_code().to_resolved().await?; Ok(EcmascriptChunkContentEntry { code, hash: code.source_code_hash().to_resolved().await?, diff --git a/turbopack/crates/turbopack-ecmascript/src/chunk/factory_group.rs b/turbopack/crates/turbopack-ecmascript/src/chunk/factory_group.rs new file mode 100644 index 000000000000..612b1680cae4 --- /dev/null +++ b/turbopack/crates/turbopack-ecmascript/src/chunk/factory_group.rs @@ -0,0 +1,172 @@ +use std::io::Write; + +use anyhow::Result; +use turbopack_core::code_builder::CodeBuilder; + +use crate::{chunk::CodeModuleIdAndPath, utils::StringifyJs}; + +const MIXED_ARROW_PREFIX: &str = "\n(()=>{\"use strict\";return["; +const MIXED_FUNCTION_PREFIX: &str = "\n(function(){\"use strict\";return["; +const MIXED_SUFFIX: &str = "\n]})(),"; +const ALL_STRICT_ARROW_PREFIX: &str = "(()=>{\"use strict\";"; +const ALL_STRICT_FUNCTION_PREFIX: &str = "(function(){\"use strict\";"; +const ALL_STRICT_SUFFIX: &str = "})()"; + +/// Minimum number of strict factories that makes hoisting the directive worth its wrapper. +/// Derived from the minified wrapper sizes and pinned by `strict_thresholds_match_wrapper_sizes`. +/// The mixed wrappers differ in length but land on the same minimum; the all-strict ones do not, +/// which is why arrow support still selects between two constants here. +const MIXED_STRICT_THRESHOLD: usize = 3; +const ALL_STRICT_ARROW_THRESHOLD: usize = 2; +const ALL_STRICT_FUNCTION_THRESHOLD: usize = 3; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum StrictFactoryMode { + Flat, + Mixed, + AllStrict, +} + +/// Selects the smallest expected minified representation for this chunk's mix of module factories. +pub fn strict_factory_mode( + chunk_items: &[CodeModuleIdAndPath], + supports_arrow_functions: bool, +) -> StrictFactoryMode { + let mut strict = 0; + let mut non_strict = 0; + for item in chunk_items { + if item.strict { + strict += 1; + } else { + non_strict += 1; + } + } + if strict == 0 { + return StrictFactoryMode::Flat; + } + + let mode = if non_strict == 0 { + StrictFactoryMode::AllStrict + } else { + StrictFactoryMode::Mixed + }; + let threshold = match (mode, supports_arrow_functions) { + (StrictFactoryMode::Mixed, _) => MIXED_STRICT_THRESHOLD, + (StrictFactoryMode::AllStrict, true) => ALL_STRICT_ARROW_THRESHOLD, + (StrictFactoryMode::AllStrict, false) => ALL_STRICT_FUNCTION_THRESHOLD, + (StrictFactoryMode::Flat, _) => unreachable!(), + }; + if strict >= threshold { + mode + } else { + StrictFactoryMode::Flat + } +} + +/// Code written around the whole chunk in the all-strict case. +pub fn strict_chunk_wrapper( + mode: StrictFactoryMode, + supports_arrow_functions: bool, +) -> Option<(&'static str, &'static str)> { + (mode == StrictFactoryMode::AllStrict).then(|| { + ( + all_strict_prefix(supports_arrow_functions), + ALL_STRICT_SUFFIX, + ) + }) +} + +const fn mixed_prefix(supports_arrow_functions: bool) -> &'static str { + if supports_arrow_functions { + MIXED_ARROW_PREFIX + } else { + MIXED_FUNCTION_PREFIX + } +} + +const fn all_strict_prefix(supports_arrow_functions: bool) -> &'static str { + if supports_arrow_functions { + ALL_STRICT_ARROW_PREFIX + } else { + ALL_STRICT_FUNCTION_PREFIX + } +} + +/// Writes flat factories, with a strict IIFE prepended to the non-strict factories in mixed chunks. +pub fn write_module_factories( + code: &mut CodeBuilder, + chunk_items: &[CodeModuleIdAndPath], + mode: StrictFactoryMode, + supports_arrow_functions: bool, +) -> Result<()> { + if mode == StrictFactoryMode::Mixed { + *code += mixed_prefix(supports_arrow_functions); + write_factories(code, chunk_items, |strict| strict)?; + *code += MIXED_SUFFIX; + write_factories(code, chunk_items, |strict| !strict)?; + } else { + write_factories(code, chunk_items, |_| true)?; + } + Ok(()) +} + +fn write_factories( + code: &mut CodeBuilder, + chunk_items: &[CodeModuleIdAndPath], + include: impl Fn(bool) -> bool, +) -> Result<()> { + for item in chunk_items { + if include(item.strict) { + write!(code, "\n{}, ", StringifyJs(&item.id))?; + code.push_code(&item.code); + write!(code, ",")?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Minified length of the `"use strict";` directive that + /// `EcmascriptChunkItemContent::module_factory` writes into every strict factory, and that + /// the minimizer removes again inside a strict wrapper. The trailing newlines the factory + /// writes do not survive minification, so they are not counted. Kept here because only these + /// assertions need it. + const STRICT_MODE_DIRECTIVE_LEN: usize = "\"use strict\";".len(); + + fn minified_len(wrapper: &str) -> usize { + // Formatting whitespace is only added at line boundaries. Trim each line rather than all + // whitespace so the space inside the `"use strict"` string literal is preserved. + wrapper.lines().map(str::trim).map(str::len).sum() + } + + /// `threshold` must be the smallest factory count worth grouping: one below it the directives + /// do not outweigh the wrapper, at the threshold they do. + fn assert_threshold(threshold: usize, wrapper: &str) { + let wrapper_len = minified_len(wrapper); + assert!((threshold - 1) * STRICT_MODE_DIRECTIVE_LEN <= wrapper_len); + assert!(threshold * STRICT_MODE_DIRECTIVE_LEN > wrapper_len); + } + + #[test] + fn strict_thresholds_match_wrapper_sizes() { + assert_threshold( + MIXED_STRICT_THRESHOLD, + &format!("{MIXED_ARROW_PREFIX}{MIXED_SUFFIX}"), + ); + assert_threshold( + MIXED_STRICT_THRESHOLD, + &format!("{MIXED_FUNCTION_PREFIX}{MIXED_SUFFIX}"), + ); + assert_threshold( + ALL_STRICT_ARROW_THRESHOLD, + &format!("{ALL_STRICT_ARROW_PREFIX}{ALL_STRICT_SUFFIX}"), + ); + assert_threshold( + ALL_STRICT_FUNCTION_THRESHOLD, + &format!("{ALL_STRICT_FUNCTION_PREFIX}{ALL_STRICT_SUFFIX}"), + ); + } +} diff --git a/turbopack/crates/turbopack-ecmascript/src/chunk/item.rs b/turbopack/crates/turbopack-ecmascript/src/chunk/item.rs index 8ad26c5bb3cd..f5585ffbff36 100644 --- a/turbopack/crates/turbopack-ecmascript/src/chunk/item.rs +++ b/turbopack/crates/turbopack-ecmascript/src/chunk/item.rs @@ -6,7 +6,8 @@ use bincode::{Decode, Encode}; use smallvec::SmallVec; use turbo_rcstr::{RcStr, rcstr}; use turbo_tasks::{ - NonLocalValue, PrettyPrintError, ResolvedVc, Upcast, ValueToString, Vc, trace::TraceRawVcs, + NonLocalValue, PrettyPrintError, ReadRef, ResolvedVc, Upcast, ValueToString, Vc, + trace::TraceRawVcs, }; use turbo_tasks_fs::{FileSystemPath, rope::Rope}; use turbopack_core::{ @@ -14,7 +15,7 @@ use turbopack_core::{ AsyncModuleInfo, ChunkItem, ChunkItemWithAsyncModuleInfo, ChunkType, ChunkingContext, ChunkingContextExt, ModuleId, SourceMapSourceType, }, - code_builder::{Code, CodeBuilder, PersistedCode}, + code_builder::{CodeBuilder, PersistedCode}, ident::AssetIdent, issue::{IssueExt, IssueSeverity, StyledString, code_gen::CodeGenerationIssue}, module::Module, @@ -256,9 +257,18 @@ pub trait EcmascriptChunkItem: ChunkItem + OutputAssetsReference { ) -> Result>; } +#[turbo_tasks::value] +pub struct EcmascriptChunkItemCode { + pub code: ResolvedVc, + pub strict: bool, +} + pub trait EcmascriptChunkItemExt { - /// Generates the module factory for this chunk item. - fn code(self: Vc, async_module_info: Option>) -> Vc; + /// Generates the module factory and returns whether it must run in strict mode. + fn code( + self: Vc, + async_module_info: Option>, + ) -> Vc; } impl EcmascriptChunkItemExt for T @@ -266,9 +276,11 @@ where T: Upcast>, { /// Generates the module factory for this chunk item. - fn code(self: Vc, async_module_info: Option>) -> Vc { + fn code( + self: Vc, + async_module_info: Option>, + ) -> Vc { module_factory_with_code_generation_issue(Vc::upcast_non_strict(self), async_module_info) - .to_code() } } @@ -276,21 +288,25 @@ where async fn module_factory_with_code_generation_issue( chunk_item: Vc>, async_module_info: Option>, -) -> Result> { +) -> Result> { async fn get_content( chunk_item: Vc>, async_module_info: Option>, - ) -> Result> { - let chunk_item_ref = chunk_item.into_trait_ref().await?; - let content = chunk_item_ref + ) -> Result> { + chunk_item + .into_trait_ref() + .await? .content_with_async_module_info(async_module_info, false) .await? - .await?; - content.module_factory().await + .await } - let content = get_content(chunk_item, async_module_info).await; - Ok(match content { - Ok(factory) => *factory, + + let (code, strict) = match get_content(chunk_item, async_module_info).await { + Ok(content) => (content.module_factory().await, content.options.strict), + Err(error) => (Err(error), false), + }; + let code = match code { + Ok(factory) => factory, Err(error) => { let id = chunk_item.asset_ident().to_string().await; let id = id.as_ref().map_or_else(|_| "unknown", |id| &**id); @@ -315,9 +331,10 @@ async fn module_factory_with_code_generation_issue( code += "(() => {{\n\n"; writeln!(code, "throw new Error({error});", error = js_error_message)?; code += "\n}})"; - *code.build().cell_persisted() + code.build().cell_persisted() } - }) + }; + Ok(EcmascriptChunkItemCode { code, strict }.cell()) } /// Generic chunk item that wraps any EcmascriptChunkPlaceable module. diff --git a/turbopack/crates/turbopack-ecmascript/src/chunk/mod.rs b/turbopack/crates/turbopack-ecmascript/src/chunk/mod.rs index c229066fda26..7be9a73a2c29 100644 --- a/turbopack/crates/turbopack-ecmascript/src/chunk/mod.rs +++ b/turbopack/crates/turbopack-ecmascript/src/chunk/mod.rs @@ -4,6 +4,7 @@ pub(crate) mod code_module_ids_and_paths; pub(crate) mod content; pub(crate) mod content_entry; pub(crate) mod data; +pub(crate) mod factory_group; pub(crate) mod item; pub(crate) mod placeable; @@ -31,15 +32,19 @@ pub use self::{ }, chunk_type::EcmascriptChunkType, code_module_ids_and_paths::{ - BatchGroupCodeModuleIdsAndPaths, CodeModuleIdsAndPaths, + BatchGroupCodeModuleIdsAndPaths, CodeModuleIdAndPath, CodeModuleIdsAndPaths, batch_group_code_module_ids_and_paths, item_code_module_ids_and_paths, }, content::EcmascriptChunkContent, content_entry::{EcmascriptChunkContentEntries, EcmascriptChunkContentEntry}, data::EcmascriptChunkData, + factory_group::{ + StrictFactoryMode, strict_chunk_wrapper, strict_factory_mode, write_module_factories, + }, item::{ - EcmascriptChunkItem, EcmascriptChunkItemContent, EcmascriptChunkItemExt, - EcmascriptChunkItemOptions, EcmascriptChunkItemWithAsyncInfo, ecmascript_chunk_item, + EcmascriptChunkItem, EcmascriptChunkItemCode, EcmascriptChunkItemContent, + EcmascriptChunkItemExt, EcmascriptChunkItemOptions, EcmascriptChunkItemWithAsyncInfo, + ecmascript_chunk_item, }, placeable::{CjsStaticExports, EcmascriptChunkPlaceable, EcmascriptExports}, }; diff --git a/turbopack/crates/turbopack-nodejs/src/ecmascript/node/content.rs b/turbopack/crates/turbopack-nodejs/src/ecmascript/node/content.rs index 063f802e7bda..4f068626a33d 100644 --- a/turbopack/crates/turbopack-nodejs/src/ecmascript/node/content.rs +++ b/turbopack/crates/turbopack-nodejs/src/ecmascript/node/content.rs @@ -10,13 +10,15 @@ use turbopack_core::{ version::{MergeableVersionedContent, Version, VersionedContent, VersionedContentMerger}, }; use turbopack_ecmascript::{ - chunk::{EcmascriptChunkContent, EcmascriptChunkContentEntries}, + chunk::{ + EcmascriptChunkContent, EcmascriptChunkContentEntries, strict_chunk_wrapper, + strict_factory_mode, write_module_factories, + }, hmr::{ EcmascriptHmrChunkContent, merger::EcmascriptChunkContentMerger, version::EcmascriptChunkVersion, }, minify::minify, - utils::StringifyJs, }; use super::chunk::EcmascriptBuildNodeChunk; @@ -60,25 +62,32 @@ impl EcmascriptNodeChunkContent { .await?; let mut code = CodeBuilder::new(true, *self.chunking_context.debug_ids_enabled().await?); - - write!(code, "module.exports = [")?; - + let supports_arrow_functions = *self + .chunking_context + .environment() + .runtime_versions() + .supports_arrow_functions() + .await?; let content = self.content.await?; - let mut chunk_items = content.chunk_item_code_module_ids_and_paths().await?; - chunk_items.sort_by(|a, b| { - a.first() - .map(|(id, _, path)| (path, id)) - .cmp(&b.first().map(|(id, _, path)| (path, id))) - }); - for item in &chunk_items { - for (id, item_code, _) in &**item { - write!(code, "\n{}, ", StringifyJs(id))?; - code.push_code(item_code); - write!(code, ",")?; - } - } + let chunk_items = content.chunk_item_code_module_ids_and_paths().await?; + let strict_factory_mode = strict_factory_mode(&chunk_items, supports_arrow_functions); + let strict_chunk_wrapper = + strict_chunk_wrapper(strict_factory_mode, supports_arrow_functions); + if let Some((prefix, _)) = strict_chunk_wrapper { + code += prefix; + } + write!(code, "module.exports = [")?; + write_module_factories( + &mut code, + &chunk_items, + strict_factory_mode, + supports_arrow_functions, + )?; write!(code, "\n];")?; + if let Some((_, suffix)) = strict_chunk_wrapper { + code += suffix; + } let mut code = code.build(); diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/dynamic-import/output/1jsg_tests_snapshot_basic-tree-shake_dynamic-import_input_lib_1b34ju5a6z6v3.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/dynamic-import/output/1jsg_tests_snapshot_basic-tree-shake_dynamic-import_input_lib_1b34ju5a6z6v3.js index ff91a8209f3d..e71e71fa0373 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/dynamic-import/output/1jsg_tests_snapshot_basic-tree-shake_dynamic-import_input_lib_1b34ju5a6z6v3.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/dynamic-import/output/1jsg_tests_snapshot_basic-tree-shake_dynamic-import_input_lib_1b34ju5a6z6v3.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_dynamic-import_input_lib_1b34ju5a6z6v3.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_dynamic-import_input_lib_1b34ju5a6z6v3.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/dynamic-import/input/lib.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -180,6 +180,6 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ; ; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_basic-tree-shake_dynamic-import_input_lib_1b34ju5a6z6v3.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/export-named/output/1jsg_tests_snapshot_basic-tree-shake_export-named_input_0xj7cshvyczs_._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/export-named/output/1jsg_tests_snapshot_basic-tree-shake_export-named_input_0xj7cshvyczs_._.js index cc56eb63656b..5c32ec148bb3 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/export-named/output/1jsg_tests_snapshot_basic-tree-shake_export-named_input_0xj7cshvyczs_._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/export-named/output/1jsg_tests_snapshot_basic-tree-shake_export-named_input_0xj7cshvyczs_._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_export-named_input_0xj7cshvyczs_._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_export-named_input_0xj7cshvyczs_._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/export-named/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -92,6 +92,6 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ; ; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_basic-tree-shake_export-named_input_0xj7cshvyczs_._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/export-namespace/output/1jsg_tests_snapshot_basic-tree-shake_export-namespace_input_1mqgz2-3_b4v8._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/export-namespace/output/1jsg_tests_snapshot_basic-tree-shake_export-namespace_input_1mqgz2-3_b4v8._.js index 19b09f16be00..e79a6670f5e3 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/export-namespace/output/1jsg_tests_snapshot_basic-tree-shake_export-namespace_input_1mqgz2-3_b4v8._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/export-namespace/output/1jsg_tests_snapshot_basic-tree-shake_export-namespace_input_1mqgz2-3_b4v8._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_export-namespace_input_1mqgz2-3_b4v8._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_export-namespace_input_1mqgz2-3_b4v8._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/export-namespace/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -187,6 +187,6 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ; ; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_basic-tree-shake_export-namespace_input_1mqgz2-3_b4v8._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-named-all/output/1jsg_tests_snapshot_basic-tree-shake_import-named-all_input_1orhvu2sihqe-._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-named-all/output/1jsg_tests_snapshot_basic-tree-shake_import-named-all_input_1orhvu2sihqe-._.js index cef624f4916c..1ca05111b11c 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-named-all/output/1jsg_tests_snapshot_basic-tree-shake_import-named-all_input_1orhvu2sihqe-._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-named-all/output/1jsg_tests_snapshot_basic-tree-shake_import-named-all_input_1orhvu2sihqe-._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_import-named-all_input_1orhvu2sihqe-._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_import-named-all_input_1orhvu2sihqe-._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-named-all/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -75,6 +75,6 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ; ; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_basic-tree-shake_import-named-all_input_1orhvu2sihqe-._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-named/output/1jsg_tests_snapshot_basic-tree-shake_import-named_input_1j9uhcyhqdoze._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-named/output/1jsg_tests_snapshot_basic-tree-shake_import-named_input_1j9uhcyhqdoze._.js index 01a3353f88c5..f1d7357f0a22 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-named/output/1jsg_tests_snapshot_basic-tree-shake_import-named_input_1j9uhcyhqdoze._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-named/output/1jsg_tests_snapshot_basic-tree-shake_import-named_input_1j9uhcyhqdoze._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_import-named_input_1j9uhcyhqdoze._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_import-named_input_1j9uhcyhqdoze._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-named/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -75,6 +75,6 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ; ; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_basic-tree-shake_import-named_input_1j9uhcyhqdoze._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-namespace/output/1jsg_tests_snapshot_basic-tree-shake_import-namespace_input_1ippwh3yc_l3v._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-namespace/output/1jsg_tests_snapshot_basic-tree-shake_import-namespace_input_1ippwh3yc_l3v._.js index c961f16a2299..34ae25dce464 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-namespace/output/1jsg_tests_snapshot_basic-tree-shake_import-namespace_input_1ippwh3yc_l3v._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-namespace/output/1jsg_tests_snapshot_basic-tree-shake_import-namespace_input_1ippwh3yc_l3v._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_import-namespace_input_1ippwh3yc_l3v._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_import-namespace_input_1ippwh3yc_l3v._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-namespace/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -171,6 +171,6 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ; ; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_basic-tree-shake_import-namespace_input_1ippwh3yc_l3v._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-side-effect/output/1jsg_tests_snapshot_basic-tree-shake_import-side-effect_input_1_hdh9its1vdz._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-side-effect/output/1jsg_tests_snapshot_basic-tree-shake_import-side-effect_input_1_hdh9its1vdz._.js index e1a674eed97a..f979e4d5d29e 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-side-effect/output/1jsg_tests_snapshot_basic-tree-shake_import-side-effect_input_1_hdh9its1vdz._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-side-effect/output/1jsg_tests_snapshot_basic-tree-shake_import-side-effect_input_1_hdh9its1vdz._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_import-side-effect_input_1_hdh9its1vdz._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_import-side-effect_input_1_hdh9its1vdz._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/import-side-effect/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -51,6 +51,6 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ; __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2d$tree$2d$shake$2f$import$2d$side$2d$effect$2f$input$2f$lib$2e$js__$5b$test$5d$__$28$ecmascript$29$__$3c$internal__part__0$3e$__["a"] += '!'; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_basic-tree-shake_import-side-effect_input_1_hdh9its1vdz._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/output/1jsg_tests_snapshot_basic-tree-shake_require-side-effect_input_0fs4qhn32cnvu._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/output/1jsg_tests_snapshot_basic-tree-shake_require-side-effect_input_0fs4qhn32cnvu._.js index 3de73b86d67a..ec09065d3887 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/output/1jsg_tests_snapshot_basic-tree-shake_require-side-effect_input_0fs4qhn32cnvu._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/output/1jsg_tests_snapshot_basic-tree-shake_require-side-effect_input_0fs4qhn32cnvu._.js @@ -1,8 +1,5 @@ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_require-side-effect_input_0fs4qhn32cnvu._.js", -"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { - -const { cat } = __turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js [test] (ecmascript)"); -}), +(()=>{"use strict";return[ "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -184,6 +181,11 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ; ; }), +]})(), +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { + +const { cat } = __turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js [test] (ecmascript)"); +}), ]); //# sourceMappingURL=1jsg_tests_snapshot_basic-tree-shake_require-side-effect_input_0fs4qhn32cnvu._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/output/1jsg_tests_snapshot_basic-tree-shake_require-side-effect_input_0fs4qhn32cnvu._.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/output/1jsg_tests_snapshot_basic-tree-shake_require-side-effect_input_0fs4qhn32cnvu._.js.map index 53593d7c0707..94e8bdd3d3cb 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/output/1jsg_tests_snapshot_basic-tree-shake_require-side-effect_input_0fs4qhn32cnvu._.js.map +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/output/1jsg_tests_snapshot_basic-tree-shake_require-side-effect_input_0fs4qhn32cnvu._.js.map @@ -2,16 +2,16 @@ "version": 3, "sources": [], "sections": [ - {"offset": {"line": 3, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/index.js"],"sourcesContent":["const { cat } = require('./lib')\n"],"names":["cat"],"mappings":"AAAA,MAAM,EAAEA,GAAG,EAAE"}}, - {"offset": {"line": 8, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":""}}, - {"offset": {"line": 26, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":""}}, - {"offset": {"line": 48, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":["dog"],"mappings":";;;;;AAAA,IAAIA,MAAM"}}, - {"offset": {"line": 59, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":[],"mappings":";;;AAEA,+PAAG,IAAI;AAQP,+PAAG,IAAI"}}, - {"offset": {"line": 68, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":["console","log"],"mappings":";;;;;;;AAIAA,QAAQC,GAAG,CAAC,+PAAG;AAQfD,QAAQC,GAAG,CAAC,+PAAG;AAQfD,QAAQC,GAAG,CAAC,+PAAG"}}, - {"offset": {"line": 83, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":["getDog","setDog","newDog","dogRef","initial","get","set"],"mappings":";;;;;;;;;;;;;;;;;AAMA,SAASA;IACP,OAAO,+PAAG;AACZ;AAMA,SAASC,OAAOC,MAAM;IACpB,+PAAG,GAAGA;AACR;AAMO,MAAMC,SAAS;IACpBC,SAAS,+PAAG;IACZC,KAAKL;IACLM,KAAKL;AACP"}}, - {"offset": {"line": 119, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":[],"mappings":";;;;;AAkBA,+PAAG,IAAI"}}, - {"offset": {"line": 129, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":["cat"],"mappings":";;;;;AA4BO,IAAIA,MAAM"}}, - {"offset": {"line": 140, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":["initialCat"],"mappings":";;;;;;;;;AA8BO,MAAMA,aAAa,+PAAG"}}, - {"offset": {"line": 156, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":["getChimera"],"mappings":";;;;;;;;;;;;;AAgCO,SAASA;IACd,OAAO,+PAAG,GAAG,+PAAG;AAClB"}}, - {"offset": {"line": 178, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":""}}] + {"offset": {"line": 5, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":""}}, + {"offset": {"line": 23, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":""}}, + {"offset": {"line": 45, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":["dog"],"mappings":";;;;;AAAA,IAAIA,MAAM"}}, + {"offset": {"line": 56, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":[],"mappings":";;;AAEA,+PAAG,IAAI;AAQP,+PAAG,IAAI"}}, + {"offset": {"line": 65, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":["console","log"],"mappings":";;;;;;;AAIAA,QAAQC,GAAG,CAAC,+PAAG;AAQfD,QAAQC,GAAG,CAAC,+PAAG;AAQfD,QAAQC,GAAG,CAAC,+PAAG"}}, + {"offset": {"line": 80, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":["getDog","setDog","newDog","dogRef","initial","get","set"],"mappings":";;;;;;;;;;;;;;;;;AAMA,SAASA;IACP,OAAO,+PAAG;AACZ;AAMA,SAASC,OAAOC,MAAM;IACpB,+PAAG,GAAGA;AACR;AAMO,MAAMC,SAAS;IACpBC,SAAS,+PAAG;IACZC,KAAKL;IACLM,KAAKL;AACP"}}, + {"offset": {"line": 116, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":[],"mappings":";;;;;AAkBA,+PAAG,IAAI"}}, + {"offset": {"line": 126, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":["cat"],"mappings":";;;;;AA4BO,IAAIA,MAAM"}}, + {"offset": {"line": 137, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":["initialCat"],"mappings":";;;;;;;;;AA8BO,MAAMA,aAAa,+PAAG"}}, + {"offset": {"line": 153, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/lib.js"],"sourcesContent":["let dog = 'dog'\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction getDog() {\n return dog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nfunction setDog(newDog) {\n dog = newDog\n}\n\ndog += '!'\n\nconsole.log(dog)\n\nexport const dogRef = {\n initial: dog,\n get: getDog,\n set: setDog,\n}\n\nexport let cat = 'cat'\n\nexport const initialCat = cat\n\nexport function getChimera() {\n return cat + dog\n}\n"],"names":["getChimera"],"mappings":";;;;;;;;;;;;;AAgCO,SAASA;IACd,OAAO,+PAAG,GAAG,+PAAG;AAClB"}}, + {"offset": {"line": 175, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":""}}, + {"offset": {"line": 186, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/require-side-effect/input/index.js"],"sourcesContent":["const { cat } = require('./lib')\n"],"names":["cat"],"mappings":"AAAA,MAAM,EAAEA,GAAG,EAAE"}}] } \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/tree-shake-test-1/output/1jsg_tests_snapshot_basic-tree-shake_tree-shake-test-1_input_index_07jttq51-r0-b.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/tree-shake-test-1/output/1jsg_tests_snapshot_basic-tree-shake_tree-shake-test-1_input_index_07jttq51-r0-b.js index 1a7d7e262ea8..28b46e0d583d 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/tree-shake-test-1/output/1jsg_tests_snapshot_basic-tree-shake_tree-shake-test-1_input_index_07jttq51-r0-b.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/tree-shake-test-1/output/1jsg_tests_snapshot_basic-tree-shake_tree-shake-test-1_input_index_07jttq51-r0-b.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_tree-shake-test-1_input_index_07jttq51-r0-b.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic-tree-shake_tree-shake-test-1_input_index_07jttq51-r0-b.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic-tree-shake/tree-shake-test-1/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -180,6 +180,6 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ; ; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_basic-tree-shake_tree-shake-test-1_input_index_07jttq51-r0-b.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/async_chunk/output/1do3_crates_turbopack-tests_tests_snapshot_basic_async_chunk_input_1lkohl-aes1w9._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/async_chunk/output/1do3_crates_turbopack-tests_tests_snapshot_basic_async_chunk_input_1lkohl-aes1w9._.js index 169ceef8335e..0bbbf1b51f55 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic/async_chunk/output/1do3_crates_turbopack-tests_tests_snapshot_basic_async_chunk_input_1lkohl-aes1w9._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/async_chunk/output/1do3_crates_turbopack-tests_tests_snapshot_basic_async_chunk_input_1lkohl-aes1w9._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_async_chunk_input_1lkohl-aes1w9._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_async_chunk_input_1lkohl-aes1w9._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/async_chunk/input/import.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -23,6 +23,6 @@ function foo(value) { console.assert(value); } }), -]); +]);})() //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_basic_async_chunk_input_1lkohl-aes1w9._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/async_chunk_build/output/0_9x_turbopack-tests_tests_snapshot_basic_async_chunk_build_input_0aldykipaj64f._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/async_chunk_build/output/0_9x_turbopack-tests_tests_snapshot_basic_async_chunk_build_input_0aldykipaj64f._.js index a43b7875186b..82ca52e51235 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic/async_chunk_build/output/0_9x_turbopack-tests_tests_snapshot_basic_async_chunk_build_input_0aldykipaj64f._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/async_chunk_build/output/0_9x_turbopack-tests_tests_snapshot_basic_async_chunk_build_input_0aldykipaj64f._.js @@ -1,4 +1,4 @@ -module.exports = [ +(()=>{"use strict";module.exports = [ "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/async_chunk_build/input/import.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -23,6 +23,6 @@ function foo(value) { console.assert(value); } }), -]; +];})() //# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_basic_async_chunk_build_input_0aldykipaj64f._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/chunked/output/1do3_crates_turbopack-tests_tests_snapshot_basic_chunked_input_1_yzgm1kllkx5._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/chunked/output/1do3_crates_turbopack-tests_tests_snapshot_basic_chunked_input_1_yzgm1kllkx5._.js index 8be3d678cff1..487bde69bc49 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic/chunked/output/1do3_crates_turbopack-tests_tests_snapshot_basic_chunked_input_1_yzgm1kllkx5._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/chunked/output/1do3_crates_turbopack-tests_tests_snapshot_basic_chunked_input_1_yzgm1kllkx5._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_chunked_input_1_yzgm1kllkx5._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_chunked_input_1_yzgm1kllkx5._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/chunked/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -18,6 +18,6 @@ function foo(value) { console.assert(value); } }), -]); +]);})() //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_basic_chunked_input_1_yzgm1kllkx5._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/export-default/output/1do3_crates_turbopack-tests_tests_snapshot_basic_export-default_input_1k9-ja77l7ynd._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/export-default/output/1do3_crates_turbopack-tests_tests_snapshot_basic_export-default_input_1k9-ja77l7ynd._.js index f70fd4688c33..5f84eb8a11eb 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic/export-default/output/1do3_crates_turbopack-tests_tests_snapshot_basic_export-default_input_1k9-ja77l7ynd._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/export-default/output/1do3_crates_turbopack-tests_tests_snapshot_basic_export-default_input_1k9-ja77l7ynd._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_export-default_input_1k9-ja77l7ynd._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_export-default_input_1k9-ja77l7ynd._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/export-default/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -19,6 +19,6 @@ __turbopack_context__.s([ __TURBOPACK__default__export__ ]); }), -]); +]);})() //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_basic_export-default_input_1k9-ja77l7ynd._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/shebang/output/1do3_crates_turbopack-tests_tests_snapshot_basic_shebang_input_02e38zhtmusm6._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/shebang/output/1do3_crates_turbopack-tests_tests_snapshot_basic_shebang_input_02e38zhtmusm6._.js index 4297bcd714e9..2284f0a4af30 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic/shebang/output/1do3_crates_turbopack-tests_tests_snapshot_basic_shebang_input_02e38zhtmusm6._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/shebang/output/1do3_crates_turbopack-tests_tests_snapshot_basic_shebang_input_02e38zhtmusm6._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_shebang_input_02e38zhtmusm6._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_shebang_input_02e38zhtmusm6._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/shebang/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -18,6 +18,6 @@ function foo(value) { console.assert(value); } }), -]); +]);})() //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_basic_shebang_input_02e38zhtmusm6._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/top-level-await/output/1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_0zs_dr_r82cwm._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/top-level-await/output/1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_0zs_dr_r82cwm._.js index e678d043819a..207d8b4e2ff8 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic/top-level-await/output/1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_0zs_dr_r82cwm._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/top-level-await/output/1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_0zs_dr_r82cwm._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_0zs_dr_r82cwm._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_0zs_dr_r82cwm._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/top-level-await/input/UserAPI.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -49,6 +49,6 @@ const close = ()=>{ }; __turbopack_async_result__(); } catch(e) { __turbopack_async_result__(e); } }, true);}), -]); +]);})() //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_0zs_dr_r82cwm._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/top-level-await/output/1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_1ih204k-kik67._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/top-level-await/output/1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_1ih204k-kik67._.js index 54f64d9b5364..853aa529a2b7 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic/top-level-await/output/1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_1ih204k-kik67._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/top-level-await/output/1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_1ih204k-kik67._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_1ih204k-kik67._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_1ih204k-kik67._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/top-level-await/input/Actions.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -34,6 +34,6 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo console.log('created user John'); })(); }), -]); +]);})() //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_basic_top-level-await_input_1ih204k-kik67._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict-a.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict-a.js new file mode 100644 index 000000000000..41715495f45f --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict-a.js @@ -0,0 +1 @@ +export const a = 1 diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict-b.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict-b.js new file mode 100644 index 000000000000..2e9a7c1c293e --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict-b.js @@ -0,0 +1 @@ +export const b = 2 diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict.js new file mode 100644 index 000000000000..99f649690c4f --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict.js @@ -0,0 +1,4 @@ +import { a } from './all-strict-a' +import { b } from './all-strict-b' + +export const value = a + b diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/below-threshold.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/below-threshold.js new file mode 100644 index 000000000000..3aee44a1eb39 --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/below-threshold.js @@ -0,0 +1 @@ +export const value = 2 diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/index.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/index.js index ff1fe73ae2b9..750d99f9df02 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/index.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/index.js @@ -1,4 +1,15 @@ 'use strict' -console.log('this is CJS') -module.exports = 1234 +const strictA = require('./strict-a') +const strictB = require('./strict-b').default +const sloppy = require('./non-strict') + +import('./below-threshold').then(({ value }) => { + console.log('below threshold', value) +}) +import('./all-strict').then(({ value }) => { + console.log('all strict', value) +}) + +console.log('this is CJS', strictA, strictB, sloppy) +module.exports = strictA + strictB + sloppy diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/non-strict.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/non-strict.js new file mode 100644 index 000000000000..916bbf382326 --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/non-strict.js @@ -0,0 +1,3 @@ +module.exports = (function () { + return this === globalThis ? 34 : 0 +})() diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/strict-a.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/strict-a.js new file mode 100644 index 000000000000..599fe94db7c6 --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/strict-a.js @@ -0,0 +1,3 @@ +'use strict' + +module.exports = 1000 diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/strict-b.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/strict-b.js new file mode 100644 index 000000000000..f02c66655596 --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/strict-b.js @@ -0,0 +1 @@ +export default 200 diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0nlvx9556vyf1.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0nlvx9556vyf1.js deleted file mode 100644 index 5c32047506a0..000000000000 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0nlvx9556vyf1.js +++ /dev/null @@ -1,10 +0,0 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0nlvx9556vyf1.js", -"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { -"use strict"; - -console.log('this is CJS'); -module.exports = 1234; -}), -]); - -//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0nlvx9556vyf1.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0nlvx9556vyf1.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0nlvx9556vyf1.js.map deleted file mode 100644 index 099ea083cceb..000000000000 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0nlvx9556vyf1.js.map +++ /dev/null @@ -1,6 +0,0 @@ -{ - "version": 3, - "sources": [], - "sections": [ - {"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/index.js"],"sourcesContent":["'use strict'\n\nconsole.log('this is CJS')\nmodule.exports = 1234\n"],"names":["console","log","module","exports"],"mappings":"AAEAA,QAAQC,GAAG,CAAC;AACZC,OAAOC,OAAO,GAAG"}}] -} \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_06b3uhycu7sip.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0r4xda1wnxaqk.js.map similarity index 100% rename from turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_06b3uhycu7sip.js.map rename to turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0r4xda1wnxaqk.js.map diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0rv8_turbopack-tests_tests_snapshot_basic_use-strict_input_index_06b3uhycu7sip.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0rv8_turbopack-tests_tests_snapshot_basic_use-strict_input_index_06b3uhycu7sip.js deleted file mode 100644 index a3916c755aee..000000000000 --- a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0rv8_turbopack-tests_tests_snapshot_basic_use-strict_input_index_06b3uhycu7sip.js +++ /dev/null @@ -1,5 +0,0 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ - "output/0rv8_turbopack-tests_tests_snapshot_basic_use-strict_input_index_06b3uhycu7sip.js", - {"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0nlvx9556vyf1.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/index.js [test] (ecmascript)"]} -]); -// Dummy runtime \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0rv8_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0r4xda1wnxaqk.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0rv8_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0r4xda1wnxaqk.js new file mode 100644 index 000000000000..d85518b06021 --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/0rv8_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0r4xda1wnxaqk.js @@ -0,0 +1,5 @@ +(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ + "output/0rv8_turbopack-tests_tests_snapshot_basic_use-strict_input_index_0r4xda1wnxaqk.js", + {"otherChunks":["output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_0czj5szeqd2rf._.js","output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1wmp5yoyw-hht._.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/index.js [test] (ecmascript)"]} +]); +// Dummy runtime \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_0czj5szeqd2rf._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_0czj5szeqd2rf._.js new file mode 100644 index 000000000000..3d46eee35bdd --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_0czj5szeqd2rf._.js @@ -0,0 +1,22 @@ +(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_0czj5szeqd2rf._.js", +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict.js [test] (ecmascript, async loader)", ((__turbopack_context__) => { + +__turbopack_context__.v((parentImport) => { + return Promise.all([ + "output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1fuq2pc5luz9r._.js" +].map((chunk) => __turbopack_context__.l(chunk))).then(() => { + return parentImport("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict.js [test] (ecmascript)"); + }); +}); +}), +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/below-threshold.js [test] (ecmascript, async loader)", ((__turbopack_context__) => { + +__turbopack_context__.v((parentImport) => { + return Promise.all([ + "output/1jsg_tests_snapshot_basic_use-strict_input_below-threshold_1my1mnvsmmqb0.js" +].map((chunk) => __turbopack_context__.l(chunk))).then(() => { + return parentImport("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/below-threshold.js [test] (ecmascript)"); + }); +}); +}), +]); \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_0czj5szeqd2rf._.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_0czj5szeqd2rf._.js.map new file mode 100644 index 000000000000..c15d7ec00382 --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_0czj5szeqd2rf._.js.map @@ -0,0 +1,5 @@ +{ + "version": 3, + "sources": [], + "sections": [] +} \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1fuq2pc5luz9r._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1fuq2pc5luz9r._.js new file mode 100644 index 000000000000..016f920965c0 --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1fuq2pc5luz9r._.js @@ -0,0 +1,35 @@ +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1fuq2pc5luz9r._.js", +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict-a.js [test] (ecmascript)", ((__turbopack_context__) => { +"use strict"; + +__turbopack_context__.s([ + "a", + ()=>a +]); +const a = 1; +}), +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict-b.js [test] (ecmascript)", ((__turbopack_context__) => { +"use strict"; + +__turbopack_context__.s([ + "b", + ()=>b +]); +const b = 2; +}), +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict.js [test] (ecmascript)", ((__turbopack_context__) => { +"use strict"; + +__turbopack_context__.s([ + "value", + ()=>value +]); +var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$use$2d$strict$2f$input$2f$all$2d$strict$2d$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict-a.js [test] (ecmascript)"); +var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$use$2d$strict$2f$input$2f$all$2d$strict$2d$b$2e$js__$5b$test$5d$__$28$ecmascript$29$__ = __turbopack_context__.i("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict-b.js [test] (ecmascript)"); +; +; +const value = __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$use$2d$strict$2f$input$2f$all$2d$strict$2d$a$2e$js__$5b$test$5d$__$28$ecmascript$29$__["a"] + __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$basic$2f$use$2d$strict$2f$input$2f$all$2d$strict$2d$b$2e$js__$5b$test$5d$__$28$ecmascript$29$__["b"]; +}), +]);})() + +//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1fuq2pc5luz9r._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1fuq2pc5luz9r._.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1fuq2pc5luz9r._.js.map new file mode 100644 index 000000000000..406799b6fa9c --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1fuq2pc5luz9r._.js.map @@ -0,0 +1,8 @@ +{ + "version": 3, + "sources": [], + "sections": [ + {"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict-a.js"],"sourcesContent":["export const a = 1\n"],"names":["a"],"mappings":";;;;AAAO,MAAMA,IAAI"}}, + {"offset": {"line": 13, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict-b.js"],"sourcesContent":["export const b = 2\n"],"names":["b"],"mappings":";;;;AAAO,MAAMA,IAAI"}}, + {"offset": {"line": 22, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict.js"],"sourcesContent":["import { a } from './all-strict-a'\nimport { b } from './all-strict-b'\n\nexport const value = a + b\n"],"names":["value"],"mappings":";;;;AAAA;AACA;;;AAEO,MAAMA,QAAQ,sNAAC,GAAG,sNAAC"}}] +} \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1wmp5yoyw-hht._.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1wmp5yoyw-hht._.js new file mode 100644 index 000000000000..b2f09e1085b7 --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1wmp5yoyw-hht._.js @@ -0,0 +1,41 @@ +(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1wmp5yoyw-hht._.js", +(()=>{"use strict";return[ +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/index.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { +"use strict"; + +const strictA = __turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/strict-a.js [test] (ecmascript)"); +const strictB = __turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/strict-b.js [test] (ecmascript)").default; +const sloppy = __turbopack_context__.r("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/non-strict.js [test] (ecmascript)"); +__turbopack_context__.A("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/below-threshold.js [test] (ecmascript, async loader)").then(({ value })=>{ + console.log('below threshold', value); +}); +__turbopack_context__.A("[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/all-strict.js [test] (ecmascript, async loader)").then(({ value })=>{ + console.log('all strict', value); +}); +console.log('this is CJS', strictA, strictB, sloppy); +module.exports = strictA + strictB + sloppy; +}), +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/strict-a.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { +"use strict"; + +module.exports = 1000; +}), +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/strict-b.js [test] (ecmascript)", ((__turbopack_context__) => { +"use strict"; + +__turbopack_context__.s([ + "default", + ()=>__TURBOPACK__default__export__ +]); +const __TURBOPACK__default__export__ = 200; +}), +]})(), +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/non-strict.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { + +module.exports = function() { + return this === globalThis ? 34 : 0; +}(); +}), +]); + +//# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1wmp5yoyw-hht._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1wmp5yoyw-hht._.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1wmp5yoyw-hht._.js.map new file mode 100644 index 000000000000..4502eb46c08b --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1do3_crates_turbopack-tests_tests_snapshot_basic_use-strict_input_1wmp5yoyw-hht._.js.map @@ -0,0 +1,9 @@ +{ + "version": 3, + "sources": [], + "sections": [ + {"offset": {"line": 5, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/index.js"],"sourcesContent":["'use strict'\n\nconst strictA = require('./strict-a')\nconst strictB = require('./strict-b').default\nconst sloppy = require('./non-strict')\n\nimport('./below-threshold').then(({ value }) => {\n console.log('below threshold', value)\n})\nimport('./all-strict').then(({ value }) => {\n console.log('all strict', value)\n})\n\nconsole.log('this is CJS', strictA, strictB, sloppy)\nmodule.exports = strictA + strictB + sloppy\n"],"names":["strictA","strictB","default","sloppy","then","value","console","log","module","exports"],"mappings":"AAEA,MAAMA;AACN,MAAMC,UAAU,4IAAsBC,OAAO;AAC7C,MAAMC;AAEN,iKAA4BC,IAAI,CAAC,CAAC,EAAEC,KAAK,EAAE;IACzCC,QAAQC,GAAG,CAAC,mBAAmBF;AACjC;AACA,4JAAuBD,IAAI,CAAC,CAAC,EAAEC,KAAK,EAAE;IACpCC,QAAQC,GAAG,CAAC,cAAcF;AAC5B;AAEAC,QAAQC,GAAG,CAAC,eAAeP,SAASC,SAASE;AAC7CK,OAAOC,OAAO,GAAGT,UAAUC,UAAUE"}}, + {"offset": {"line": 20, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/strict-a.js"],"sourcesContent":["'use strict'\n\nmodule.exports = 1000\n"],"names":["module","exports"],"mappings":"AAEAA,OAAOC,OAAO,GAAG"}}, + {"offset": {"line": 25, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/strict-b.js"],"sourcesContent":["export default 200\n"],"names":[],"mappings":";;;;uCAAe"}}, + {"offset": {"line": 34, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/non-strict.js"],"sourcesContent":["module.exports = (function () {\n return this === globalThis ? 34 : 0\n})()\n"],"names":["module","exports","globalThis"],"mappings":"AAAAA,OAAOC,OAAO,GAAG,AAAC;IAChB,OAAO,IAAI,KAAKC,aAAa,KAAK;AACpC"}}] +} \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1jsg_tests_snapshot_basic_use-strict_input_below-threshold_1my1mnvsmmqb0.js b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1jsg_tests_snapshot_basic_use-strict_input_below-threshold_1my1mnvsmmqb0.js new file mode 100644 index 000000000000..8f1aeb5a9e7a --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1jsg_tests_snapshot_basic_use-strict_input_below-threshold_1my1mnvsmmqb0.js @@ -0,0 +1,13 @@ +(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_basic_use-strict_input_below-threshold_1my1mnvsmmqb0.js", +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/below-threshold.js [test] (ecmascript)", ((__turbopack_context__) => { +"use strict"; + +__turbopack_context__.s([ + "value", + ()=>value +]); +const value = 2; +}), +]); + +//# sourceMappingURL=1jsg_tests_snapshot_basic_use-strict_input_below-threshold_1my1mnvsmmqb0.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1jsg_tests_snapshot_basic_use-strict_input_below-threshold_1my1mnvsmmqb0.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1jsg_tests_snapshot_basic_use-strict_input_below-threshold_1my1mnvsmmqb0.js.map new file mode 100644 index 000000000000..787f51fd7237 --- /dev/null +++ b/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/output/1jsg_tests_snapshot_basic_use-strict_input_below-threshold_1my1mnvsmmqb0.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": [], + "sections": [ + {"offset": {"line": 4, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/basic/use-strict/input/below-threshold.js"],"sourcesContent":["export const value = 2\n"],"names":["value"],"mappings":";;;;AAAO,MAAMA,QAAQ"}}] +} \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-attribute/output/1jsg_tests_snapshot_comptime_cross-module-attribute_input_0scutbfo13k0p._.js b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-attribute/output/1jsg_tests_snapshot_comptime_cross-module-attribute_input_0scutbfo13k0p._.js index 105354316776..312adf4a89d5 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-attribute/output/1jsg_tests_snapshot_comptime_cross-module-attribute_input_0scutbfo13k0p._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-attribute/output/1jsg_tests_snapshot_comptime_cross-module-attribute_input_0scutbfo13k0p._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_comptime_cross-module-attribute_input_0scutbfo13k0p._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_comptime_cross-module-attribute_input_0scutbfo13k0p._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-attribute/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -57,6 +57,6 @@ __turbopack_context__.s([ const lower = 'lowercase'; const UPPER = 'UPPER'; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_comptime_cross-module-attribute_input_0scutbfo13k0p._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-barrel/output/0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-barrel_input_0pg1--73_0gbu._.js b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-barrel/output/0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-barrel_input_0pg1--73_0gbu._.js index 351f523f15f3..d285fa720f31 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-barrel/output/0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-barrel_input_0pg1--73_0gbu._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-barrel/output/0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-barrel_input_0pg1--73_0gbu._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-barrel_input_0pg1--73_0gbu._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-barrel_input_0pg1--73_0gbu._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-barrel/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -28,6 +28,6 @@ function foo() { return 123; } }), -]); +]);})() //# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-barrel_input_0pg1--73_0gbu._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-cycle-constant/output/1jsg_tests_snapshot_comptime_cross-module-cycle-constant_input_13shj11lx78r9._.js b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-cycle-constant/output/1jsg_tests_snapshot_comptime_cross-module-cycle-constant_input_13shj11lx78r9._.js index 3aa7ed7ecf3f..6b5aa9a3d4e1 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-cycle-constant/output/1jsg_tests_snapshot_comptime_cross-module-cycle-constant_input_13shj11lx78r9._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-cycle-constant/output/1jsg_tests_snapshot_comptime_cross-module-cycle-constant_input_13shj11lx78r9._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_comptime_cross-module-cycle-constant_input_13shj11lx78r9._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_comptime_cross-module-cycle-constant_input_13shj11lx78r9._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-cycle-constant/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -29,6 +29,6 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ; const TWO = '2' + __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbopack$2d$tests$2f$tests$2f$snapshot$2f$comptime$2f$cross$2d$module$2d$cycle$2d$constant$2f$input$2f$multiple$2d$1$2e$js__$5b$test$5d$__$28$ecmascript$29$__["ONE"]; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_comptime_cross-module-cycle-constant_input_13shj11lx78r9._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-cycle-dynamic/output/1jsg_tests_snapshot_comptime_cross-module-cycle-dynamic_input_0y6rllfq_jecq._.js b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-cycle-dynamic/output/1jsg_tests_snapshot_comptime_cross-module-cycle-dynamic_input_0y6rllfq_jecq._.js index 37b80337ac93..dfd74b0ef09f 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-cycle-dynamic/output/1jsg_tests_snapshot_comptime_cross-module-cycle-dynamic_input_0y6rllfq_jecq._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-cycle-dynamic/output/1jsg_tests_snapshot_comptime_cross-module-cycle-dynamic_input_0y6rllfq_jecq._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_comptime_cross-module-cycle-dynamic_input_0y6rllfq_jecq._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_comptime_cross-module-cycle-dynamic_input_0y6rllfq_jecq._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-cycle-dynamic/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -54,6 +54,6 @@ function foo1(left, right) { } ; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_comptime_cross-module-cycle-dynamic_input_0y6rllfq_jecq._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-imported/output/1jsg_tests_snapshot_comptime_cross-module-imported_input_1h-za4-_ttkv-._.js b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-imported/output/1jsg_tests_snapshot_comptime_cross-module-imported_input_1h-za4-_ttkv-._.js index 4a5a5d6eec00..78f9bdf02719 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-imported/output/1jsg_tests_snapshot_comptime_cross-module-imported_input_1h-za4-_ttkv-._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-imported/output/1jsg_tests_snapshot_comptime_cross-module-imported_input_1h-za4-_ttkv-._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_comptime_cross-module-imported_input_1h-za4-_ttkv-._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_comptime_cross-module-imported_input_1h-za4-_ttkv-._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-imported/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -45,6 +45,6 @@ __turbopack_context__.s([ const REEXPORTED = 'reexported'; const IMPORTED_EXPORTED = 'imported exported'; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_comptime_cross-module-imported_input_1h-za4-_ttkv-._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-long-literals/output/1jsg_tests_snapshot_comptime_cross-module-long-literals_input_1dlt5gz60hx2n._.js b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-long-literals/output/1jsg_tests_snapshot_comptime_cross-module-long-literals_input_1dlt5gz60hx2n._.js index efc453e5f2d4..424367ebeabe 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-long-literals/output/1jsg_tests_snapshot_comptime_cross-module-long-literals_input_1dlt5gz60hx2n._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-long-literals/output/1jsg_tests_snapshot_comptime_cross-module-long-literals_input_1dlt5gz60hx2n._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_comptime_cross-module-long-literals_input_1dlt5gz60hx2n._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1jsg_tests_snapshot_comptime_cross-module-long-literals_input_1dlt5gz60hx2n._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-long-literals/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -52,6 +52,6 @@ const REGEX = /ab/i; const NAN = NaN; const INFINITY = Infinity; }), -]); +]);})() //# sourceMappingURL=1jsg_tests_snapshot_comptime_cross-module-long-literals_input_1dlt5gz60hx2n._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-strict/output/0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-strict_input_0lz7wh6sby-77._.js b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-strict/output/0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-strict_input_0lz7wh6sby-77._.js index 1f752879bc36..1a3ce7bbc2c4 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-strict/output/0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-strict_input_0lz7wh6sby-77._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-strict/output/0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-strict_input_0lz7wh6sby-77._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-strict_input_0lz7wh6sby-77._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-strict_input_0lz7wh6sby-77._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/cross-module-strict/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -51,6 +51,6 @@ const LONG_NUMBER = 21345672345678345678901234567890; const LONG_BIG_NUMBER = 21345672345678345678901234567890n; const LONG_REGEX = /abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0123456789/i; }), -]); +]);})() //# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_comptime_cross-module-strict_input_0lz7wh6sby-77._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/early-return/output/1do3_crates_turbopack-tests_tests_snapshot_comptime_early-return_input_00p0fdz0d5nhi._.js b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/early-return/output/1do3_crates_turbopack-tests_tests_snapshot_comptime_early-return_input_00p0fdz0d5nhi._.js index 1240e19e97d9..3024ea10f23c 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/early-return/output/1do3_crates_turbopack-tests_tests_snapshot_comptime_early-return_input_00p0fdz0d5nhi._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/early-return/output/1do3_crates_turbopack-tests_tests_snapshot_comptime_early-return_input_00p0fdz0d5nhi._.js @@ -1,4 +1,4 @@ -(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_comptime_early-return_input_00p0fdz0d5nhi._.js", +(()=>{"use strict";(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_comptime_early-return_input_00p0fdz0d5nhi._.js", "[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/early-return/input/index.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -226,6 +226,6 @@ z1(); return; z2(); }), -]); +]);})() //# sourceMappingURL=1do3_crates_turbopack-tests_tests_snapshot_comptime_early-return_input_00p0fdz0d5nhi._.js.map \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/output/1do3_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_1y4b353ijz1yk._.js b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/output/1do3_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_1y4b353ijz1yk._.js index bf598a8e6dda..682647ba4b7d 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/output/1do3_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_1y4b353ijz1yk._.js +++ b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/output/1do3_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_1y4b353ijz1yk._.js @@ -1,29 +1,5 @@ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push(["output/1do3_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_1y4b353ijz1yk._.js", -"[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/cjs.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { - -var __TURBOPACK__import$2e$meta__ = { - get url () { - return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/cjs.js"); - }, - env: { - DEV: true, - PROD: false, - MODE: "development", - BASE_URL: "/", - SSR: false - } -}; -console.log('typeof require', ("TURBOPACK compile-time value", "function")); -console.log('typeof import.meta', ("TURBOPACK compile-time value", "object")); -// CJS, should be `object` -console.log('typeof module', ("TURBOPACK compile-time value", "object")); -console.log('typeof exports', ("TURBOPACK compile-time value", "object")); -// CJS, should be real require -console.log(/*TURBOPACK member replacement*/ __turbopack_context__.t); -}), -"[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/dep.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { - -}), +(()=>{"use strict";return[ "[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-automatic.js [test] (ecmascript)", ((__turbopack_context__) => { "use strict"; @@ -84,6 +60,32 @@ var __TURBOPACK__imported__module__$5b$project$5d2f$turbopack$2f$crates$2f$turbo ; ; ; +}), +]})(), +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/cjs.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { + +var __TURBOPACK__import$2e$meta__ = { + get url () { + return __turbopack_context__.F("turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/cjs.js"); + }, + env: { + DEV: true, + PROD: false, + MODE: "development", + BASE_URL: "/", + SSR: false + } +}; +console.log('typeof require', ("TURBOPACK compile-time value", "function")); +console.log('typeof import.meta', ("TURBOPACK compile-time value", "object")); +// CJS, should be `object` +console.log('typeof module', ("TURBOPACK compile-time value", "object")); +console.log('typeof exports', ("TURBOPACK compile-time value", "object")); +// CJS, should be real require +console.log(/*TURBOPACK member replacement*/ __turbopack_context__.t); +}), +"[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/dep.js [test] (ecmascript)", ((__turbopack_context__, module, exports) => { + }), ]); diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/output/1do3_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_1y4b353ijz1yk._.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/output/1do3_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_1y4b353ijz1yk._.js.map index 227b5e663a42..5e5d8604722c 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/output/1do3_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_1y4b353ijz1yk._.js.map +++ b/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/output/1do3_crates_turbopack-tests_tests_snapshot_comptime_typeof_input_1y4b353ijz1yk._.js.map @@ -2,9 +2,9 @@ "version": 3, "sources": [], "sections": [ - {"offset": {"line": 3, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/cjs.js"],"sourcesContent":["console.log('typeof require', typeof require)\nconsole.log('typeof import.meta', typeof import.meta)\n// CJS, should be `object`\nconsole.log('typeof module', typeof module)\nconsole.log('typeof exports', typeof exports)\n\n// CJS, should be real require\nconsole.log(require)\n"],"names":["console","log"],"mappings":";;;;;;;;;;;;AAAAA,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZ,0BAA0B;AAC1BD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AAEZ,8BAA8B;AAC9BD,QAAQC,GAAG"}}, - {"offset": {"line": 25, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":""}}, - {"offset": {"line": 29, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-automatic.js"],"sourcesContent":["import './dep.js'\n\nconsole.log('typeof require', typeof require)\nconsole.log('typeof import.meta', typeof import.meta)\n// ESM, should be `undefined`\nconsole.log('typeof module', typeof module)\nconsole.log('typeof exports', typeof exports)\n\n// ESM, should be require stub\nconsole.log(require)\n"],"names":["console","log"],"mappings":";AAAA;;;;;;;;;;;;;;AAEAA,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZ,6BAA6B;AAC7BD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AAEZ,8BAA8B;AAC9BD,QAAQC,GAAG"}}, - {"offset": {"line": 55, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-specified.mjs"],"sourcesContent":["console.log('typeof require', typeof require)\nconsole.log('typeof import.meta', typeof import.meta)\n// ESM, should be `undefined`\nconsole.log('typeof module', typeof module)\nconsole.log('typeof exports', typeof exports)\n\n// ESM, should be require stub\nconsole.log(require)\n"],"names":["console","log"],"mappings":";;;;;;;;;;;;;AAAAA,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZ,6BAA6B;AAC7BD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AAEZ,8BAA8B;AAC9BD,QAAQC,GAAG"}}, - {"offset": {"line": 79, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/index.js"],"sourcesContent":["import './cjs.js'\nimport './esm-automatic.js'\nimport './esm-specified.mjs'\n"],"names":[],"mappings":";AAAA;AACA;AACA"}}] + {"offset": {"line": 5, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-automatic.js"],"sourcesContent":["import './dep.js'\n\nconsole.log('typeof require', typeof require)\nconsole.log('typeof import.meta', typeof import.meta)\n// ESM, should be `undefined`\nconsole.log('typeof module', typeof module)\nconsole.log('typeof exports', typeof exports)\n\n// ESM, should be require stub\nconsole.log(require)\n"],"names":["console","log"],"mappings":";AAAA;;;;;;;;;;;;;;AAEAA,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZ,6BAA6B;AAC7BD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AAEZ,8BAA8B;AAC9BD,QAAQC,GAAG"}}, + {"offset": {"line": 31, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/esm-specified.mjs"],"sourcesContent":["console.log('typeof require', typeof require)\nconsole.log('typeof import.meta', typeof import.meta)\n// ESM, should be `undefined`\nconsole.log('typeof module', typeof module)\nconsole.log('typeof exports', typeof exports)\n\n// ESM, should be require stub\nconsole.log(require)\n"],"names":["console","log"],"mappings":";;;;;;;;;;;;;AAAAA,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZ,6BAA6B;AAC7BD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AAEZ,8BAA8B;AAC9BD,QAAQC,GAAG"}}, + {"offset": {"line": 55, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/index.js"],"sourcesContent":["import './cjs.js'\nimport './esm-automatic.js'\nimport './esm-specified.mjs'\n"],"names":[],"mappings":";AAAA;AACA;AACA"}}, + {"offset": {"line": 66, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/comptime/typeof/input/cjs.js"],"sourcesContent":["console.log('typeof require', typeof require)\nconsole.log('typeof import.meta', typeof import.meta)\n// CJS, should be `object`\nconsole.log('typeof module', typeof module)\nconsole.log('typeof exports', typeof exports)\n\n// CJS, should be real require\nconsole.log(require)\n"],"names":["console","log"],"mappings":";;;;;;;;;;;;AAAAA,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AACZ,0BAA0B;AAC1BD,QAAQC,GAAG,CAAC;AACZD,QAAQC,GAAG,CAAC;AAEZ,8BAA8B;AAC9BD,QAAQC,GAAG"}}, + {"offset": {"line": 88, "column": 0}, "map": {"version":3,"sources":[],"names":[],"mappings":""}}] } \ No newline at end of file diff --git a/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/output/0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map b/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/output/0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map index 3430c53be6f0..58a97bfc130e 100644 --- a/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/output/0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map +++ b/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/output/0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map @@ -1,13 +1,13 @@ { "version": 3, "sources": [], - "debugId": "37ea5bcf-f259-1cd1-a144-361dcb52f06f", + "debugId": "77867742-97a1-7739-5b4e-e0fc46a40a42", "sections": [ - {"offset": {"line": 26, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/runtime/runtime-utils.ts"],"sourcesContent":["/**\n * This file contains runtime types and functions that are shared between all\n * TurboPack ECMAScript runtimes.\n *\n * It will be prepended to the runtime code of each runtime.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\ntype EsmNamespaceObject = Record\n\n/**\n * Describes why a module was instantiated.\n * Shared between browser and Node.js runtimes.\n */\nenum SourceType {\n /**\n * The module was instantiated because it was included in an evaluated chunk's\n * runtime.\n * SourceData is a ChunkPath.\n */\n Runtime = 0,\n /**\n * The module was instantiated because a parent module imported it.\n * SourceData is a ModuleId.\n */\n Parent = 1,\n /**\n * The module was instantiated because it was included in a chunk's hot module\n * update.\n * SourceData is an array of ModuleIds or undefined.\n */\n Update = 2,\n}\n\ntype SourceData = ChunkPath | ModuleId | ModuleId[] | undefined\n\n// @ts-ignore Defined in `dev-base.ts`\ndeclare function getOrInstantiateModuleFromParent(\n id: ModuleId,\n sourceModule: M\n): M\n\n/**\n * Flag indicating which module object type to create when a module is merged. Set to `true`\n * by each runtime that uses ModuleWithDirection (browser dev-base.ts, nodejs dev-base.ts,\n * nodejs build-base.ts). Browser production (build-base.ts) leaves it as `false` since it\n * uses plain Module objects.\n */\nlet createModuleWithDirectionFlag = false\n\nconst REEXPORTED_OBJECTS = new WeakMap()\n\n/**\n * Constructs the `__turbopack_context__` object for a module.\n */\nfunction Context(\n this: TurbopackBaseContext,\n module: Module,\n exports: Exports\n) {\n this.m = module\n // We need to store this here instead of accessing it from the module object to:\n // 1. Make it available to factories directly, since we rewrite `this` to\n // `__turbopack_context__.e` in CJS modules.\n // 2. Support async modules which rewrite `module.exports` to a promise, so we\n // can still access the original exports object from functions like\n // `esmExport`\n // Ideally we could find a new approach for async modules and drop this property altogether.\n this.e = exports\n}\nconst contextPrototype = Context.prototype as TurbopackBaseContext\n\ntype ModuleContextMap = Record\n\ninterface ModuleContextEntry {\n id: () => ModuleId\n module: () => any\n}\n\ninterface ModuleContext {\n // require call\n (moduleId: string): Exports | EsmNamespaceObject\n\n // async import call\n import(moduleId: string): Promise\n\n keys(): ModuleId[]\n\n resolve(moduleId: string): ModuleId\n}\n\ntype GetOrInstantiateModuleFromParent = (\n moduleId: M['id'],\n parentModule: M\n) => M\n\ndeclare function getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module\n\nconst hasOwnProperty = Object.prototype.hasOwnProperty\nconst toStringTag = typeof Symbol !== 'undefined' && Symbol.toStringTag\n\nfunction defineProp(\n obj: any,\n name: PropertyKey,\n options: PropertyDescriptor & ThisType\n) {\n if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options)\n}\n\nfunction getOverwrittenModule(\n moduleCache: ModuleCache,\n id: ModuleId\n): Module {\n let module = moduleCache[id]\n if (!module) {\n if (createModuleWithDirectionFlag) {\n // set in development modes for hmr support\n module = createModuleWithDirection(id)\n } else {\n module = createModuleObject(id)\n }\n moduleCache[id] = module\n }\n return module\n}\n\n/**\n * Creates the module object. Only done here to ensure all module objects have the same shape.\n */\nfunction createModuleObject(id: ModuleId): Module {\n return {\n exports: {},\n error: undefined,\n id,\n namespaceObject: undefined,\n }\n}\n\nfunction createModuleWithDirection(id: ModuleId): ModuleWithDirection {\n return {\n exports: {},\n error: undefined,\n id,\n namespaceObject: undefined,\n parents: [],\n children: [],\n }\n}\n\ntype BindingTag = 0\nconst BindingTag_Value = 0 as BindingTag\n\n// an arbitrary sequence of bindings as\n// - a prop name\n// - BindingTag_Value, a value to be bound directly, or\n// - 1 or 2 functions to bind as getters and sdetters\ntype EsmBindings = Array<\n string | BindingTag | (() => unknown) | ((v: unknown) => void) | unknown\n>\n\n/**\n * Adds the getters to the exports object.\n */\nfunction esm(exports: Exports, bindings: EsmBindings, dynamic?: boolean) {\n defineProp(exports, '__esModule', { value: true })\n if (toStringTag) defineProp(exports, toStringTag, { value: 'Module' })\n let i = 0\n while (i < bindings.length) {\n const propName = bindings[i++] as string\n const tagOrFunction = bindings[i++]\n if (typeof tagOrFunction === 'number') {\n if (tagOrFunction === BindingTag_Value) {\n defineProp(exports, propName, {\n value: bindings[i++],\n enumerable: true,\n writable: false,\n })\n } else {\n throw new Error(`unexpected tag: ${tagOrFunction}`)\n }\n } else {\n const getterFn = tagOrFunction as () => unknown\n if (typeof bindings[i] === 'function') {\n const setterFn = bindings[i++] as (v: unknown) => void\n defineProp(exports, propName, {\n get: getterFn,\n set: setterFn,\n enumerable: true,\n })\n } else {\n defineProp(exports, propName, {\n get: getterFn,\n enumerable: true,\n })\n }\n }\n }\n // The properties defined above are already non-configurable and\n // non-writable, so the namespace's existing exports are effectively\n // immutable. Sealing additionally makes the object non-extensible, matching\n // real ESM-namespace semantics. Modules with dynamic re-exports\n // (`export *` from a CommonJS module) must stay extensible so the dynamic\n // export proxy can surface keys discovered at runtime, so skip the seal for\n // them.\n if (!dynamic) Object.seal(exports)\n}\n\n/**\n * Makes the module an ESM with exports\n */\nfunction esmExport(\n this: TurbopackBaseContext,\n bindings: EsmBindings,\n id: ModuleId | undefined,\n dynamic?: boolean\n) {\n let module: Module\n let exports: Module['exports']\n if (id != null) {\n module = getOverwrittenModule(this.c, id)\n exports = module.exports\n } else {\n module = this.m\n exports = this.e\n }\n module.namespaceObject = exports\n esm(exports, bindings, dynamic)\n}\ncontextPrototype.s = esmExport\n\ntype ReexportedObjects = Record[]\nfunction ensureDynamicExports(\n module: Module,\n exports: Exports\n): ReexportedObjects {\n let reexportedObjects: ReexportedObjects | undefined =\n REEXPORTED_OBJECTS.get(module)\n\n if (!reexportedObjects) {\n REEXPORTED_OBJECTS.set(module, (reexportedObjects = []))\n // Returns the re-exported object that provides `prop` as an own property,\n // or `undefined` if none does. The traps share this logic so they always\n // agree on which keys are synthesized from `reexportedObjects`. `default`\n // is never re-exported by `export *`, so it is never synthesized.\n const reexportOwning = (prop: PropertyKey) => {\n if (prop !== 'default') {\n for (const obj of reexportedObjects!) {\n if (hasOwnProperty.call(obj, prop)) return obj\n }\n }\n return undefined\n }\n // Modules with dynamic re-exports are not sealed by `esm()`, so the\n // target beneath the namespace stays extensible. That is what lets the\n // `ownKeys` and `getOwnPropertyDescriptor` traps legally report keys that\n // exist on `reexportedObjects` but not on the target itself.\n module.exports = module.namespaceObject = new Proxy(exports, {\n get(target, prop) {\n if (\n hasOwnProperty.call(target, prop) ||\n prop === 'default' ||\n prop === '__esModule'\n ) {\n return Reflect.get(target, prop)\n }\n const obj = reexportOwning(prop)\n return obj && Reflect.get(obj, prop)\n },\n // The namespace is read-only, like a real esm namespace object. The\n // re-exported modules can still mutate their own exports (exposed live\n // via `get`), but mutating the namespace itself is rejected. Refusing\n // here, rather than forwarding to the extensible target, also prevents an\n // assignment/definition from shadowing a dynamic re-export. It also\n // prevents delete from removing a static export.\n set() {\n return false\n },\n defineProperty() {\n return false\n },\n deleteProperty() {\n return false\n },\n // The `has` trap ensures that `'exportName' in starImports` will reflect\n // the truth of whether a key is exported.\n has(target, prop) {\n if (Reflect.has(target, prop)) return true\n if (prop === 'default' || prop === '__esModule') return false\n return reexportOwning(prop) !== undefined\n },\n // ownKeys and getOwnPropertyDescriptor together make the keys enumerable.\n // If a value is returned from `ownKeys` but its property descriptor is\n // not enumerable, it will not be visible to iterator methods.\n // Collectively, they allow code like the following:\n //\n // ```\n // // module.js re-exports dynamic CJS exports\n // export * from './legacyModule.cjs'\n //\n // // from another JS file, reference the re-exported dynamic values\n // import * as Namespace from './module.js'\n // Object.keys(Namespace)\n // ```\n ownKeys(target) {\n const keys = Reflect.ownKeys(target)\n for (const obj of reexportedObjects!) {\n for (const key of Reflect.ownKeys(obj)) {\n if (key !== 'default' && !keys.includes(key)) keys.push(key)\n }\n }\n return keys\n },\n getOwnPropertyDescriptor(target, prop) {\n const own = Reflect.getOwnPropertyDescriptor(target, prop)\n if (own || prop === 'default' || prop === '__esModule') return own\n const obj = reexportOwning(prop)\n if (obj) {\n // Synthetic keys don't exist on the target, so they MUST be\n // reported as configurable. However the set/delete traps above will\n // prevent them from actually being changed\n return {\n enumerable: true,\n configurable: true,\n get: () => Reflect.get(obj, prop),\n }\n }\n return undefined\n },\n })\n }\n return reexportedObjects\n}\n\n/**\n * Dynamically exports properties from an object\n */\nfunction dynamicExport(\n this: TurbopackBaseContext,\n object: Record,\n id: ModuleId | undefined\n) {\n let module: Module\n let exports: Exports\n if (id != null) {\n module = getOverwrittenModule(this.c, id)\n exports = module.exports\n } else {\n module = this.m\n exports = this.e\n }\n const reexportedObjects = ensureDynamicExports(module, exports)\n\n if (typeof object === 'object' && object !== null) {\n reexportedObjects.push(object)\n }\n}\ncontextPrototype.j = dynamicExport\n\nfunction exportValue(\n this: TurbopackBaseContext,\n value: any,\n id: ModuleId | undefined\n) {\n let module: Module\n if (id != null) {\n module = getOverwrittenModule(this.c, id)\n } else {\n module = this.m\n }\n module.exports = value\n}\ncontextPrototype.v = exportValue\n\nfunction exportNamespace(\n this: TurbopackBaseContext,\n namespace: any,\n id: ModuleId | undefined\n) {\n let module: Module\n if (id != null) {\n module = getOverwrittenModule(this.c, id)\n } else {\n module = this.m\n }\n module.exports = module.namespaceObject = namespace\n}\ncontextPrototype.n = exportNamespace\n\nfunction createGetter(obj: Record, key: string | symbol) {\n return () => obj[key]\n}\n\n/**\n * @returns prototype of the object\n */\nconst getProto: (obj: any) => any = Object.getPrototypeOf\n ? (obj) => Object.getPrototypeOf(obj)\n : (obj) => obj.__proto__\n\n/** Prototypes that are not expanded for exports */\nconst LEAF_PROTOTYPES = [null, getProto({}), getProto([]), getProto(getProto)]\n\n/**\n * @param raw\n * @param ns\n * @param allowExportDefault\n * * `false`: will have the raw module as default export\n * * `true`: will have the default property as default export\n */\nfunction interopEsm(\n raw: Exports,\n ns: EsmNamespaceObject,\n allowExportDefault?: boolean\n) {\n const bindings: EsmBindings = []\n let defaultLocation = -1\n for (\n let current = raw;\n (typeof current === 'object' || typeof current === 'function') &&\n !LEAF_PROTOTYPES.includes(current);\n current = getProto(current)\n ) {\n for (const key of Object.getOwnPropertyNames(current)) {\n bindings.push(key, createGetter(raw, key))\n if (defaultLocation === -1 && key === 'default') {\n defaultLocation = bindings.length - 1\n }\n }\n }\n\n // this is not really correct\n // we should set the `default` getter if the imported module is a `.cjs file`\n if (!(allowExportDefault && defaultLocation >= 0)) {\n // Replace the binding with one for the namespace itself in order to preserve iteration order.\n if (defaultLocation >= 0) {\n // Replace the getter with the value\n bindings.splice(defaultLocation, 1, BindingTag_Value, raw)\n } else {\n bindings.push('default', BindingTag_Value, raw)\n }\n }\n\n esm(ns, bindings)\n return ns\n}\n\nfunction createNS(raw: Module['exports']): EsmNamespaceObject {\n if (typeof raw === 'function') {\n return function (this: any, ...args: any[]) {\n return raw.apply(this, args)\n }\n } else {\n return Object.create(null)\n }\n}\n\nfunction esmImport(\n this: TurbopackBaseContext,\n id: ModuleId\n): Exclude {\n const module = getOrInstantiateModuleFromParent(id, this.m)\n\n // any ES module has to have `module.namespaceObject` defined.\n if (module.namespaceObject) return module.namespaceObject\n\n // only ESM can be an async module, so we don't need to worry about exports being a promise here.\n const raw = module.exports\n return (module.namespaceObject = interopEsm(\n raw,\n createNS(raw),\n raw && (raw as any).__esModule\n ))\n}\ncontextPrototype.i = esmImport\n\nfunction asyncLoader(\n this: TurbopackBaseContext,\n moduleId: ModuleId\n): Promise {\n const loader = this.r(moduleId) as (\n importFunction: EsmImport\n ) => Promise\n return loader(esmImport.bind(this))\n}\ncontextPrototype.A = asyncLoader\n\n// Add a simple runtime require so that environments without one can still pass\n// `typeof require` CommonJS checks so that exports are correctly registered.\nconst runtimeRequire =\n // @ts-ignore\n typeof require === 'function'\n ? // @ts-ignore\n require\n : function require() {\n throw new Error('Unexpected use of runtime require')\n }\ncontextPrototype.t = runtimeRequire\n\nfunction commonJsRequire(\n this: TurbopackBaseContext,\n id: ModuleId\n): Exports {\n return getOrInstantiateModuleFromParent(id, this.m).exports\n}\ncontextPrototype.r = commonJsRequire\n\n/**\n * Remove fragments and query parameters since they are never part of the context map keys\n *\n * This matches how we parse patterns at resolving time. Arguably we should only do this for\n * strings passed to `import` but the resolve does it for `import` and `require` and so we do\n * here as well.\n */\nfunction parseRequest(request: string): string {\n // Per the URI spec fragments can contain `?` characters, so we should trim it off first\n // https://datatracker.ietf.org/doc/html/rfc3986#section-3.5\n const hashIndex = request.indexOf('#')\n if (hashIndex !== -1) {\n request = request.substring(0, hashIndex)\n }\n\n const queryIndex = request.indexOf('?')\n if (queryIndex !== -1) {\n request = request.substring(0, queryIndex)\n }\n\n return request\n}\n/**\n * `require.context` and require/import expression runtime.\n */\nfunction moduleContext(map: ModuleContextMap): ModuleContext {\n function moduleContext(id: string): Exports {\n id = parseRequest(id)\n if (hasOwnProperty.call(map, id)) {\n return map[id].module()\n }\n\n const e = new Error(`Cannot find module '${id}'`)\n ;(e as any).code = 'MODULE_NOT_FOUND'\n throw e\n }\n\n moduleContext.keys = (): string[] => {\n return Object.keys(map)\n }\n\n moduleContext.resolve = (id: string): ModuleId => {\n id = parseRequest(id)\n if (hasOwnProperty.call(map, id)) {\n return map[id].id()\n }\n\n const e = new Error(`Cannot find module '${id}'`)\n ;(e as any).code = 'MODULE_NOT_FOUND'\n throw e\n }\n\n moduleContext.import = async (id: string) => {\n return await (moduleContext(id) as Promise)\n }\n\n return moduleContext\n}\ncontextPrototype.f = moduleContext\n\n/**\n * Returns the path of a chunk defined by its data.\n */\nfunction getChunkPath(chunkData: ChunkData): ChunkPath {\n return typeof chunkData === 'string' ? chunkData : chunkData.path\n}\n\n// Load the CompressedmoduleFactories of a chunk into the `moduleFactories` Map.\n// The CompressedModuleFactories format is\n// - 1 or more module ids\n// - a module factory function\n// So walking this is a little complex but the flat structure is also fast to\n// traverse, we can use `typeof` operators to distinguish the two cases.\nfunction installCompressedModuleFactories(\n chunkModules: CompressedModuleFactories,\n offset: number,\n moduleFactories: ModuleFactories,\n newModuleId?: (id: ModuleId) => void\n) {\n let i = offset\n while (i < chunkModules.length) {\n let end = i + 1\n // Find our factory function\n while (\n end < chunkModules.length &&\n typeof chunkModules[end] !== 'function'\n ) {\n end++\n }\n if (end === chunkModules.length) {\n throw new Error('malformed chunk format, expected a factory function')\n }\n\n // Install the factory for each module ID that doesn't already have one.\n // When some IDs in this group already have a factory, reuse that existing\n // group factory for the missing IDs to keep all IDs in the group consistent.\n // Otherwise, install the factory from this chunk.\n const moduleFactoryFn = chunkModules[end] as Function\n let existingGroupFactory: Function | undefined = undefined\n for (let j = i; j < end; j++) {\n const id = chunkModules[j] as ModuleId\n const existingFactory = moduleFactories.get(id)\n if (existingFactory) {\n existingGroupFactory = existingFactory\n break\n }\n }\n const factoryToInstall = existingGroupFactory ?? moduleFactoryFn\n\n let didInstallFactory = false\n for (let j = i; j < end; j++) {\n const id = chunkModules[j] as ModuleId\n if (!moduleFactories.has(id)) {\n if (!didInstallFactory) {\n if (factoryToInstall === moduleFactoryFn) {\n applyModuleFactoryName(moduleFactoryFn)\n }\n didInstallFactory = true\n }\n moduleFactories.set(id, factoryToInstall)\n newModuleId?.(id)\n }\n }\n i = end + 1 // end is pointing at the last factory advance to the next id or the end of the array.\n }\n}\n\n/**\n * A pseudo \"fake\" URL object to resolve to its relative path.\n *\n * When UrlRewriteBehavior is set to relative, calls to the `new URL()` will construct url without base using this\n * runtime function to generate context-agnostic urls between different rendering context, i.e ssr / client to avoid\n * hydration mismatch.\n *\n * This is based on webpack's existing implementation:\n * https://github.com/webpack/webpack/blob/87660921808566ef3b8796f8df61bd79fc026108/lib/runtime/RelativeUrlRuntimeModule.js\n */\nconst relativeURL = function relativeURL(this: any, inputUrl: string) {\n const realUrl = new URL(inputUrl, 'x:/')\n const values: Record = {}\n for (const key in realUrl) values[key] = (realUrl as any)[key]\n values.href = inputUrl\n values.pathname = inputUrl.replace(/[?#].*/, '')\n values.origin = values.protocol = ''\n values.toString = values.toJSON = (..._args: Array) => inputUrl\n for (const key in values)\n Object.defineProperty(this, key, {\n enumerable: true,\n configurable: true,\n value: values[key],\n })\n}\nrelativeURL.prototype = URL.prototype\ncontextPrototype.U = relativeURL\n\n/**\n * Utility function to ensure all variants of an enum are handled.\n */\nfunction invariant(never: never, computeMessage: (arg: any) => string): never {\n throw new Error(`Invariant: ${computeMessage(never)}`)\n}\n\n/**\n * Constructs an error message for when a module factory is not available.\n */\nfunction factoryNotAvailableMessage(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): string {\n let instantiationReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n instantiationReason = `as a runtime entry of chunk ${sourceData}`\n break\n case SourceType.Parent:\n instantiationReason = `because it was required from module ${sourceData}`\n break\n case SourceType.Update:\n instantiationReason = 'because of an HMR update'\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n return `Module ${moduleId} was instantiated ${instantiationReason}, but the module factory is not available.`\n}\n\n/**\n * A stub function to make `require` available but non-functional in ESM.\n */\nfunction requireStub(_moduleId: ModuleId): never {\n throw new Error('dynamic usage of require is not supported')\n}\ncontextPrototype.z = requireStub\n\n// Make `globalThis` available to the module in a way that cannot be shadowed by a local variable.\ncontextPrototype.g = globalThis\n\ntype ContextConstructor = {\n new (module: Module, exports: Exports): TurbopackBaseContext\n}\n\nfunction applyModuleFactoryName(factory: Function) {\n // Give the module factory a nice name to improve stack traces.\n Object.defineProperty(factory, 'name', {\n value: 'module evaluation',\n })\n}\n"],"names":["SourceType","createModuleWithDirectionFlag","REEXPORTED_OBJECTS","WeakMap","Context","module","exports","m","e","contextPrototype","prototype","hasOwnProperty","Object","toStringTag","Symbol","defineProp","obj","name","options","call","defineProperty","getOverwrittenModule","moduleCache","id","createModuleWithDirection","createModuleObject","error","undefined","namespaceObject","parents","children","BindingTag_Value","esm","bindings","dynamic","value","i","length","propName","tagOrFunction","enumerable","writable","Error","getterFn","setterFn","get","set","seal","esmExport","c","s","ensureDynamicExports","reexportedObjects","reexportOwning","prop","Proxy","target","Reflect","deleteProperty","has","ownKeys","keys","key","includes","push","getOwnPropertyDescriptor","own","configurable","dynamicExport","object","j","exportValue","v","exportNamespace","namespace","n","createGetter","getProto","getPrototypeOf","__proto__","LEAF_PROTOTYPES","interopEsm","raw","ns","allowExportDefault","defaultLocation","current","getOwnPropertyNames","splice","createNS","args","apply","create","esmImport","getOrInstantiateModuleFromParent","__esModule","asyncLoader","moduleId","loader","r","bind","A","runtimeRequire","require","require1","t","commonJsRequire","parseRequest","request","hashIndex","indexOf","substring","queryIndex","moduleContext","map","code","resolve","import","f","getChunkPath","chunkData","path","installCompressedModuleFactories","chunkModules","offset","moduleFactories","newModuleId","end","moduleFactoryFn","existingGroupFactory","existingFactory","factoryToInstall","didInstallFactory","applyModuleFactoryName","relativeURL","inputUrl","realUrl","URL","values","href","pathname","replace","origin","protocol","toString","toJSON","_args","U","invariant","never","computeMessage","factoryNotAvailableMessage","sourceType","sourceData","instantiationReason","requireStub","_moduleId","z","g","globalThis","factory"],"mappings":"AAAA;;;;;CAKC,GAED,oDAAoD,GAEpD,6CAA6C;AAC7C,0CAA0C;AAI1C;;;CAGC,GACD,IAAA,AAAKA,oCAAAA;IACH;;;;GAIC,sCACS;IACV;;;GAGC,qCACQ;IACT;;;;GAIC,qCACQ;WAjBNA;EAAAA;AA4BL;;;;;CAKC,GACD,IAAIC,gCAAgC;AAEpC,MAAMC,qBAAqB,IAAIC;AAE/B;;CAEC,GACD,SAASC,QAEPC,MAAc,EACdC,OAAgB;IAEhB,IAAI,CAACC,CAAC,GAAGF;IACT,gFAAgF;IAChF,yEAAyE;IACzE,+CAA+C;IAC/C,8EAA8E;IAC9E,sEAAsE;IACtE,iBAAiB;IACjB,4FAA4F;IAC5F,IAAI,CAACG,CAAC,GAAGF;AACX;AACA,MAAMG,mBAAmBL,QAAQM,SAAS;AA+B1C,MAAMC,iBAAiBC,OAAOF,SAAS,CAACC,cAAc;AACtD,MAAME,cAAc,OAAOC,WAAW,eAAeA,OAAOD,WAAW;AAEvE,SAASE,WACPC,GAAQ,EACRC,IAAiB,EACjBC,OAA2C;IAE3C,IAAI,CAACP,eAAeQ,IAAI,CAACH,KAAKC,OAAOL,OAAOQ,cAAc,CAACJ,KAAKC,MAAMC;AACxE;AAEA,SAASG,qBACPC,WAAgC,EAChCC,EAAY;IAEZ,IAAIlB,SAASiB,WAAW,CAACC,GAAG;IAC5B,IAAI,CAAClB,QAAQ;QACX,IAAIJ,+BAA+B;YACjC,2CAA2C;YAC3CI,SAASmB,0BAA0BD;QACrC,OAAO;YACLlB,SAASoB,mBAAmBF;QAC9B;QACAD,WAAW,CAACC,GAAG,GAAGlB;IACpB;IACA,OAAOA;AACT;AAEA;;CAEC,GACD,SAASoB,mBAAmBF,EAAY;IACtC,OAAO;QACLjB,SAAS,CAAC;QACVoB,OAAOC;QACPJ;QACAK,iBAAiBD;IACnB;AACF;AAEA,SAASH,0BAA0BD,EAAY;IAC7C,OAAO;QACLjB,SAAS,CAAC;QACVoB,OAAOC;QACPJ;QACAK,iBAAiBD;QACjBE,SAAS,EAAE;QACXC,UAAU,EAAE;IACd;AACF;AAGA,MAAMC,mBAAmB;AAUzB;;CAEC,GACD,SAASC,IAAI1B,OAAgB,EAAE2B,QAAqB,EAAEC,OAAiB;IACrEnB,WAAWT,SAAS,cAAc;QAAE6B,OAAO;IAAK;IAChD,IAAItB,aAAaE,WAAWT,SAASO,aAAa;QAAEsB,OAAO;IAAS;IACpE,IAAIC,IAAI;IACR,MAAOA,IAAIH,SAASI,MAAM,CAAE;QAC1B,MAAMC,WAAWL,QAAQ,CAACG,IAAI;QAC9B,MAAMG,gBAAgBN,QAAQ,CAACG,IAAI;QACnC,IAAI,OAAOG,kBAAkB,UAAU;YACrC,IAAIA,kBAAkBR,kBAAkB;gBACtChB,WAAWT,SAASgC,UAAU;oBAC5BH,OAAOF,QAAQ,CAACG,IAAI;oBACpBI,YAAY;oBACZC,UAAU;gBACZ;YACF,OAAO;gBACL,MAAM,IAAIC,MAAM,CAAC,gBAAgB,EAAEH,eAAe;YACpD;QACF,OAAO;YACL,MAAMI,WAAWJ;YACjB,IAAI,OAAON,QAAQ,CAACG,EAAE,KAAK,YAAY;gBACrC,MAAMQ,WAAWX,QAAQ,CAACG,IAAI;gBAC9BrB,WAAWT,SAASgC,UAAU;oBAC5BO,KAAKF;oBACLG,KAAKF;oBACLJ,YAAY;gBACd;YACF,OAAO;gBACLzB,WAAWT,SAASgC,UAAU;oBAC5BO,KAAKF;oBACLH,YAAY;gBACd;YACF;QACF;IACF;IACA,gEAAgE;IAChE,oEAAoE;IACpE,4EAA4E;IAC5E,gEAAgE;IAChE,0EAA0E;IAC1E,4EAA4E;IAC5E,QAAQ;IACR,IAAI,CAACN,SAAStB,OAAOmC,IAAI,CAACzC;AAC5B;AAEA;;CAEC,GACD,SAAS0C,UAEPf,QAAqB,EACrBV,EAAwB,EACxBW,OAAiB;IAEjB,IAAI7B;IACJ,IAAIC;IACJ,IAAIiB,MAAM,MAAM;QACdlB,SAASgB,qBAAqB,IAAI,CAAC4B,CAAC,EAAE1B;QACtCjB,UAAUD,OAAOC,OAAO;IAC1B,OAAO;QACLD,SAAS,IAAI,CAACE,CAAC;QACfD,UAAU,IAAI,CAACE,CAAC;IAClB;IACAH,OAAOuB,eAAe,GAAGtB;IACzB0B,IAAI1B,SAAS2B,UAAUC;AACzB;AACAzB,iBAAiByC,CAAC,GAAGF;AAGrB,SAASG,qBACP9C,MAAc,EACdC,OAAgB;IAEhB,IAAI8C,oBACFlD,mBAAmB2C,GAAG,CAACxC;IAEzB,IAAI,CAAC+C,mBAAmB;QACtBlD,mBAAmB4C,GAAG,CAACzC,QAAS+C,oBAAoB,EAAE;QACtD,0EAA0E;QAC1E,yEAAyE;QACzE,0EAA0E;QAC1E,kEAAkE;QAClE,MAAMC,iBAAiB,CAACC;YACtB,IAAIA,SAAS,WAAW;gBACtB,KAAK,MAAMtC,OAAOoC,kBAAoB;oBACpC,IAAIzC,eAAeQ,IAAI,CAACH,KAAKsC,OAAO,OAAOtC;gBAC7C;YACF;YACA,OAAOW;QACT;QACA,oEAAoE;QACpE,uEAAuE;QACvE,0EAA0E;QAC1E,6DAA6D;QAC7DtB,OAAOC,OAAO,GAAGD,OAAOuB,eAAe,GAAG,IAAI2B,MAAMjD,SAAS;YAC3DuC,KAAIW,MAAM,EAAEF,IAAI;gBACd,IACE3C,eAAeQ,IAAI,CAACqC,QAAQF,SAC5BA,SAAS,aACTA,SAAS,cACT;oBACA,OAAOG,QAAQZ,GAAG,CAACW,QAAQF;gBAC7B;gBACA,MAAMtC,MAAMqC,eAAeC;gBAC3B,OAAOtC,OAAOyC,QAAQZ,GAAG,CAAC7B,KAAKsC;YACjC;YACA,oEAAoE;YACpE,uEAAuE;YACvE,sEAAsE;YACtE,0EAA0E;YAC1E,oEAAoE;YACpE,iDAAiD;YACjDR;gBACE,OAAO;YACT;YACA1B;gBACE,OAAO;YACT;YACAsC;gBACE,OAAO;YACT;YACA,yEAAyE;YACzE,0CAA0C;YAC1CC,KAAIH,MAAM,EAAEF,IAAI;gBACd,IAAIG,QAAQE,GAAG,CAACH,QAAQF,OAAO,OAAO;gBACtC,IAAIA,SAAS,aAAaA,SAAS,cAAc,OAAO;gBACxD,OAAOD,eAAeC,UAAU3B;YAClC;YACA,0EAA0E;YAC1E,uEAAuE;YACvE,8DAA8D;YAC9D,oDAAoD;YACpD,EAAE;YACF,MAAM;YACN,8CAA8C;YAC9C,qCAAqC;YACrC,EAAE;YACF,oEAAoE;YACpE,2CAA2C;YAC3C,yBAAyB;YACzB,MAAM;YACNiC,SAAQJ,MAAM;gBACZ,MAAMK,OAAOJ,QAAQG,OAAO,CAACJ;gBAC7B,KAAK,MAAMxC,OAAOoC,kBAAoB;oBACpC,KAAK,MAAMU,OAAOL,QAAQG,OAAO,CAAC5C,KAAM;wBACtC,IAAI8C,QAAQ,aAAa,CAACD,KAAKE,QAAQ,CAACD,MAAMD,KAAKG,IAAI,CAACF;oBAC1D;gBACF;gBACA,OAAOD;YACT;YACAI,0BAAyBT,MAAM,EAAEF,IAAI;gBACnC,MAAMY,MAAMT,QAAQQ,wBAAwB,CAACT,QAAQF;gBACrD,IAAIY,OAAOZ,SAAS,aAAaA,SAAS,cAAc,OAAOY;gBAC/D,MAAMlD,MAAMqC,eAAeC;gBAC3B,IAAItC,KAAK;oBACP,4DAA4D;oBAC5D,oEAAoE;oBACpE,2CAA2C;oBAC3C,OAAO;wBACLwB,YAAY;wBACZ2B,cAAc;wBACdtB,KAAK,IAAMY,QAAQZ,GAAG,CAAC7B,KAAKsC;oBAC9B;gBACF;gBACA,OAAO3B;YACT;QACF;IACF;IACA,OAAOyB;AACT;AAEA;;CAEC,GACD,SAASgB,cAEPC,MAA2B,EAC3B9C,EAAwB;IAExB,IAAIlB;IACJ,IAAIC;IACJ,IAAIiB,MAAM,MAAM;QACdlB,SAASgB,qBAAqB,IAAI,CAAC4B,CAAC,EAAE1B;QACtCjB,UAAUD,OAAOC,OAAO;IAC1B,OAAO;QACLD,SAAS,IAAI,CAACE,CAAC;QACfD,UAAU,IAAI,CAACE,CAAC;IAClB;IACA,MAAM4C,oBAAoBD,qBAAqB9C,QAAQC;IAEvD,IAAI,OAAO+D,WAAW,YAAYA,WAAW,MAAM;QACjDjB,kBAAkBY,IAAI,CAACK;IACzB;AACF;AACA5D,iBAAiB6D,CAAC,GAAGF;AAErB,SAASG,YAEPpC,KAAU,EACVZ,EAAwB;IAExB,IAAIlB;IACJ,IAAIkB,MAAM,MAAM;QACdlB,SAASgB,qBAAqB,IAAI,CAAC4B,CAAC,EAAE1B;IACxC,OAAO;QACLlB,SAAS,IAAI,CAACE,CAAC;IACjB;IACAF,OAAOC,OAAO,GAAG6B;AACnB;AACA1B,iBAAiB+D,CAAC,GAAGD;AAErB,SAASE,gBAEPC,SAAc,EACdnD,EAAwB;IAExB,IAAIlB;IACJ,IAAIkB,MAAM,MAAM;QACdlB,SAASgB,qBAAqB,IAAI,CAAC4B,CAAC,EAAE1B;IACxC,OAAO;QACLlB,SAAS,IAAI,CAACE,CAAC;IACjB;IACAF,OAAOC,OAAO,GAAGD,OAAOuB,eAAe,GAAG8C;AAC5C;AACAjE,iBAAiBkE,CAAC,GAAGF;AAErB,SAASG,aAAa5D,GAAiC,EAAE8C,GAAoB;IAC3E,OAAO,IAAM9C,GAAG,CAAC8C,IAAI;AACvB;AAEA;;CAEC,GACD,MAAMe,WAA8BjE,OAAOkE,cAAc,GACrD,CAAC9D,MAAQJ,OAAOkE,cAAc,CAAC9D,OAC/B,CAACA,MAAQA,IAAI+D,SAAS;AAE1B,iDAAiD,GACjD,MAAMC,kBAAkB;IAAC;IAAMH,SAAS,CAAC;IAAIA,SAAS,EAAE;IAAGA,SAASA;CAAU;AAE9E;;;;;;CAMC,GACD,SAASI,WACPC,GAAY,EACZC,EAAsB,EACtBC,kBAA4B;IAE5B,MAAMnD,WAAwB,EAAE;IAChC,IAAIoD,kBAAkB,CAAC;IACvB,IACE,IAAIC,UAAUJ,KACd,CAAC,OAAOI,YAAY,YAAY,OAAOA,YAAY,UAAU,KAC7D,CAACN,gBAAgBjB,QAAQ,CAACuB,UAC1BA,UAAUT,SAASS,SACnB;QACA,KAAK,MAAMxB,OAAOlD,OAAO2E,mBAAmB,CAACD,SAAU;YACrDrD,SAAS+B,IAAI,CAACF,KAAKc,aAAaM,KAAKpB;YACrC,IAAIuB,oBAAoB,CAAC,KAAKvB,QAAQ,WAAW;gBAC/CuB,kBAAkBpD,SAASI,MAAM,GAAG;YACtC;QACF;IACF;IAEA,6BAA6B;IAC7B,6EAA6E;IAC7E,IAAI,CAAC,CAAC+C,sBAAsBC,mBAAmB,CAAC,GAAG;QACjD,8FAA8F;QAC9F,IAAIA,mBAAmB,GAAG;YACxB,oCAAoC;YACpCpD,SAASuD,MAAM,CAACH,iBAAiB,GAAGtD,kBAAkBmD;QACxD,OAAO;YACLjD,SAAS+B,IAAI,CAAC,WAAWjC,kBAAkBmD;QAC7C;IACF;IAEAlD,IAAImD,IAAIlD;IACR,OAAOkD;AACT;AAEA,SAASM,SAASP,GAAsB;IACtC,IAAI,OAAOA,QAAQ,YAAY;QAC7B,OAAO,SAAqB,GAAGQ,IAAW;YACxC,OAAOR,IAAIS,KAAK,CAAC,IAAI,EAAED;QACzB;IACF,OAAO;QACL,OAAO9E,OAAOgF,MAAM,CAAC;IACvB;AACF;AAEA,SAASC,UAEPtE,EAAY;IAEZ,MAAMlB,SAASyF,iCAAiCvE,IAAI,IAAI,CAAChB,CAAC;IAE1D,8DAA8D;IAC9D,IAAIF,OAAOuB,eAAe,EAAE,OAAOvB,OAAOuB,eAAe;IAEzD,iGAAiG;IACjG,MAAMsD,MAAM7E,OAAOC,OAAO;IAC1B,OAAQD,OAAOuB,eAAe,GAAGqD,WAC/BC,KACAO,SAASP,MACTA,OAAO,AAACA,IAAYa,UAAU;AAElC;AACAtF,iBAAiB2B,CAAC,GAAGyD;AAErB,SAASG,YAEPC,QAAkB;IAElB,MAAMC,SAAS,IAAI,CAACC,CAAC,CAACF;IAGtB,OAAOC,OAAOL,UAAUO,IAAI,CAAC,IAAI;AACnC;AACA3F,iBAAiB4F,CAAC,GAAGL;AAErB,+EAA+E;AAC/E,6EAA6E;AAC7E,MAAMM,iBACJ,aAAa;AACb,OAAOC,YAAY,aAEfA,UACA,SAASC;IACP,MAAM,IAAI9D,MAAM;AAClB;AACNjC,iBAAiBgG,CAAC,GAAGH;AAErB,SAASI,gBAEPnF,EAAY;IAEZ,OAAOuE,iCAAiCvE,IAAI,IAAI,CAAChB,CAAC,EAAED,OAAO;AAC7D;AACAG,iBAAiB0F,CAAC,GAAGO;AAErB;;;;;;CAMC,GACD,SAASC,aAAaC,OAAe;IACnC,wFAAwF;IACxF,4DAA4D;IAC5D,MAAMC,YAAYD,QAAQE,OAAO,CAAC;IAClC,IAAID,cAAc,CAAC,GAAG;QACpBD,UAAUA,QAAQG,SAAS,CAAC,GAAGF;IACjC;IAEA,MAAMG,aAAaJ,QAAQE,OAAO,CAAC;IACnC,IAAIE,eAAe,CAAC,GAAG;QACrBJ,UAAUA,QAAQG,SAAS,CAAC,GAAGC;IACjC;IAEA,OAAOJ;AACT;AACA;;CAEC,GACD,SAASK,cAAcC,GAAqB;IAC1C,SAASD,cAAc1F,EAAU;QAC/BA,KAAKoF,aAAapF;QAClB,IAAIZ,eAAeQ,IAAI,CAAC+F,KAAK3F,KAAK;YAChC,OAAO2F,GAAG,CAAC3F,GAAG,CAAClB,MAAM;QACvB;QAEA,MAAMG,IAAI,IAAIkC,MAAM,CAAC,oBAAoB,EAAEnB,GAAG,CAAC,CAAC;QAC9Cf,EAAU2G,IAAI,GAAG;QACnB,MAAM3G;IACR;IAEAyG,cAAcpD,IAAI,GAAG;QACnB,OAAOjD,OAAOiD,IAAI,CAACqD;IACrB;IAEAD,cAAcG,OAAO,GAAG,CAAC7F;QACvBA,KAAKoF,aAAapF;QAClB,IAAIZ,eAAeQ,IAAI,CAAC+F,KAAK3F,KAAK;YAChC,OAAO2F,GAAG,CAAC3F,GAAG,CAACA,EAAE;QACnB;QAEA,MAAMf,IAAI,IAAIkC,MAAM,CAAC,oBAAoB,EAAEnB,GAAG,CAAC,CAAC;QAC9Cf,EAAU2G,IAAI,GAAG;QACnB,MAAM3G;IACR;IAEAyG,cAAcI,MAAM,GAAG,OAAO9F;QAC5B,OAAO,MAAO0F,cAAc1F;IAC9B;IAEA,OAAO0F;AACT;AACAxG,iBAAiB6G,CAAC,GAAGL;AAErB;;CAEC,GACD,SAASM,aAAaC,SAAoB;IACxC,OAAO,OAAOA,cAAc,WAAWA,YAAYA,UAAUC,IAAI;AACnE;AAEA,gFAAgF;AAChF,0CAA0C;AAC1C,yBAAyB;AACzB,8BAA8B;AAC9B,6EAA6E;AAC7E,wEAAwE;AACxE,SAASC,iCACPC,YAAuC,EACvCC,MAAc,EACdC,eAAgC,EAChCC,WAAoC;IAEpC,IAAI1F,IAAIwF;IACR,MAAOxF,IAAIuF,aAAatF,MAAM,CAAE;QAC9B,IAAI0F,MAAM3F,IAAI;QACd,4BAA4B;QAC5B,MACE2F,MAAMJ,aAAatF,MAAM,IACzB,OAAOsF,YAAY,CAACI,IAAI,KAAK,WAC7B;YACAA;QACF;QACA,IAAIA,QAAQJ,aAAatF,MAAM,EAAE;YAC/B,MAAM,IAAIK,MAAM;QAClB;QAEA,wEAAwE;QACxE,0EAA0E;QAC1E,6EAA6E;QAC7E,kDAAkD;QAClD,MAAMsF,kBAAkBL,YAAY,CAACI,IAAI;QACzC,IAAIE,uBAA6CtG;QACjD,IAAK,IAAI2C,IAAIlC,GAAGkC,IAAIyD,KAAKzD,IAAK;YAC5B,MAAM/C,KAAKoG,YAAY,CAACrD,EAAE;YAC1B,MAAM4D,kBAAkBL,gBAAgBhF,GAAG,CAACtB;YAC5C,IAAI2G,iBAAiB;gBACnBD,uBAAuBC;gBACvB;YACF;QACF;QACA,MAAMC,mBAAmBF,wBAAwBD;QAEjD,IAAII,oBAAoB;QACxB,IAAK,IAAI9D,IAAIlC,GAAGkC,IAAIyD,KAAKzD,IAAK;YAC5B,MAAM/C,KAAKoG,YAAY,CAACrD,EAAE;YAC1B,IAAI,CAACuD,gBAAgBlE,GAAG,CAACpC,KAAK;gBAC5B,IAAI,CAAC6G,mBAAmB;oBACtB,IAAID,qBAAqBH,iBAAiB;wBACxCK,uBAAuBL;oBACzB;oBACAI,oBAAoB;gBACtB;gBACAP,gBAAgB/E,GAAG,CAACvB,IAAI4G;gBACxBL,cAAcvG;YAChB;QACF;QACAa,IAAI2F,MAAM,GAAE,sFAAsF;IACpG;AACF;AAEA;;;;;;;;;CASC,GACD,MAAMO,cAAc,SAASA,YAAuBC,QAAgB;IAClE,MAAMC,UAAU,IAAIC,IAAIF,UAAU;IAClC,MAAMG,SAA8B,CAAC;IACrC,IAAK,MAAM5E,OAAO0E,QAASE,MAAM,CAAC5E,IAAI,GAAG,AAAC0E,OAAe,CAAC1E,IAAI;IAC9D4E,OAAOC,IAAI,GAAGJ;IACdG,OAAOE,QAAQ,GAAGL,SAASM,OAAO,CAAC,UAAU;IAC7CH,OAAOI,MAAM,GAAGJ,OAAOK,QAAQ,GAAG;IAClCL,OAAOM,QAAQ,GAAGN,OAAOO,MAAM,GAAG,CAAC,GAAGC,QAAsBX;IAC5D,IAAK,MAAMzE,OAAO4E,OAChB9H,OAAOQ,cAAc,CAAC,IAAI,EAAE0C,KAAK;QAC/BtB,YAAY;QACZ2B,cAAc;QACdhC,OAAOuG,MAAM,CAAC5E,IAAI;IACpB;AACJ;AACAwE,YAAY5H,SAAS,GAAG+H,IAAI/H,SAAS;AACrCD,iBAAiB0I,CAAC,GAAGb;AAErB;;CAEC,GACD,SAASc,UAAUC,KAAY,EAAEC,cAAoC;IACnE,MAAM,IAAI5G,MAAM,CAAC,WAAW,EAAE4G,eAAeD,QAAQ;AACvD;AAEA;;CAEC,GACD,SAASE,2BACPtD,QAAkB,EAClBuD,UAAsB,EACtBC,UAAsB;IAEtB,IAAIC;IACJ,OAAQF;QACN,KArpBQ;YAspBNE,sBAAsB,CAAC,4BAA4B,EAAED,YAAY;YACjE;QACF,KAnpBO;YAopBLC,sBAAsB,CAAC,oCAAoC,EAAED,YAAY;YACzE;QACF,KAhpBO;YAipBLC,sBAAsB;YACtB;QACF;YACEN,UACEI,YACA,CAACA,aAAe,CAAC,qBAAqB,EAAEA,YAAY;IAE1D;IACA,OAAO,CAAC,OAAO,EAAEvD,SAAS,kBAAkB,EAAEyD,oBAAoB,0CAA0C,CAAC;AAC/G;AAEA;;CAEC,GACD,SAASC,YAAYC,SAAmB;IACtC,MAAM,IAAIlH,MAAM;AAClB;AACAjC,iBAAiBoJ,CAAC,GAAGF;AAErB,kGAAkG;AAClGlJ,iBAAiBqJ,CAAC,GAAGC;AAMrB,SAAS1B,uBAAuB2B,OAAiB;IAC/C,+DAA+D;IAC/DpJ,OAAOQ,cAAc,CAAC4I,SAAS,QAAQ;QACrC7H,OAAO;IACT;AACF","ignoreList":[0]}}, - {"offset": {"line": 551, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/runtime/async-module.ts"],"sourcesContent":["/// \n/// \n\n/**\n * Top-level-await / async-module machinery. This is only included in the runtime\n * when the module graph actually contains an async module (a module with\n * top-level await, or one that transitively depends on one). When no async\n * module is present, the chunk items never reference `__turbopack_context__.a`,\n * so this whole file can be omitted.\n *\n * everything below is adapted from webpack\n * https://github.com/webpack/webpack/blob/6be4065ade1e252c1d8dcba4af0f43e32af1bdc1/lib/runtime/AsyncModuleRuntimeModule.js#L13\n */\n\nconst turbopackQueues = Symbol('turbopack queues')\nconst turbopackExports = Symbol('turbopack exports')\nconst turbopackError = Symbol('turbopack error')\n\nconst enum QueueStatus {\n Unknown = -1,\n Unresolved = 0,\n Resolved = 1,\n}\n\ntype AsyncQueueFn = (() => void) & { queueCount: number }\ntype AsyncQueue = AsyncQueueFn[] & {\n status: QueueStatus\n}\n\ntype Dep = Exports | AsyncModulePromise | Promise\n\ntype AsyncModuleExt = {\n [turbopackQueues]: (fn: (queue: AsyncQueue) => void) => void\n [turbopackExports]: Exports\n [turbopackError]?: any\n}\n\ntype AsyncModulePromise = Promise & AsyncModuleExt\n\nfunction isPromise(maybePromise: any): maybePromise is Promise {\n return (\n maybePromise != null &&\n typeof maybePromise === 'object' &&\n 'then' in maybePromise &&\n typeof maybePromise.then === 'function'\n )\n}\n\nfunction isAsyncModuleExt(obj: T): obj is AsyncModuleExt & T {\n return turbopackQueues in obj\n}\n\nfunction createPromise() {\n let resolve: (value: T | PromiseLike) => void\n let reject: (reason?: any) => void\n\n const promise = new Promise((res, rej) => {\n reject = rej\n resolve = res\n })\n\n return {\n promise,\n resolve: resolve!,\n reject: reject!,\n }\n}\n\nfunction resolveQueue(queue?: AsyncQueue) {\n if (queue && queue.status !== QueueStatus.Resolved) {\n queue.status = QueueStatus.Resolved\n queue.forEach((fn) => fn.queueCount--)\n queue.forEach((fn) => (fn.queueCount-- ? fn.queueCount++ : fn()))\n }\n}\n\nfunction wrapDeps(deps: Dep[]): AsyncModuleExt[] {\n return deps.map((dep): AsyncModuleExt => {\n if (dep !== null && typeof dep === 'object') {\n if (isAsyncModuleExt(dep)) return dep\n if (isPromise(dep)) {\n const queue: AsyncQueue = Object.assign([], {\n status: QueueStatus.Unresolved,\n })\n\n const obj: AsyncModuleExt = {\n [turbopackExports]: {},\n [turbopackQueues]: (fn: (queue: AsyncQueue) => void) => fn(queue),\n }\n\n dep.then(\n (res) => {\n obj[turbopackExports] = res\n resolveQueue(queue)\n },\n (err) => {\n obj[turbopackError] = err\n resolveQueue(queue)\n }\n )\n\n return obj\n }\n }\n\n return {\n [turbopackExports]: dep,\n [turbopackQueues]: () => {},\n }\n })\n}\n\nfunction asyncModule(\n this: TurbopackBaseContext,\n body: (\n handleAsyncDependencies: (\n deps: Dep[]\n ) => Exports[] | Promise<() => Exports[]>,\n asyncResult: (err?: any) => void\n ) => void,\n hasAwait: boolean\n) {\n const module = this.m\n const queue: AsyncQueue | undefined = hasAwait\n ? Object.assign([], { status: QueueStatus.Unknown })\n : undefined\n\n const depQueues: Set = new Set()\n\n const { resolve, reject, promise: rawPromise } = createPromise()\n\n const promise: AsyncModulePromise = Object.assign(rawPromise, {\n [turbopackExports]: module.exports,\n [turbopackQueues]: (fn) => {\n queue && fn(queue)\n depQueues.forEach(fn)\n promise['catch'](() => {})\n },\n } satisfies AsyncModuleExt)\n\n const attributes: PropertyDescriptor = {\n get(): any {\n return promise\n },\n set(v: any) {\n // Calling `esmExport` leads to this.\n if (v !== promise) {\n promise[turbopackExports] = v\n }\n },\n }\n\n Object.defineProperty(module, 'exports', attributes)\n Object.defineProperty(module, 'namespaceObject', attributes)\n\n function handleAsyncDependencies(deps: Dep[]) {\n const currentDeps = wrapDeps(deps)\n\n const getResult = () =>\n currentDeps.map((d) => {\n if (d[turbopackError]) throw d[turbopackError]\n return d[turbopackExports]\n })\n\n const { promise, resolve } = createPromise<() => Exports[]>()\n\n const fn: AsyncQueueFn = Object.assign(() => resolve(getResult), {\n queueCount: 0,\n })\n\n function fnQueue(q: AsyncQueue) {\n if (q !== queue && !depQueues.has(q)) {\n depQueues.add(q)\n if (q && q.status === QueueStatus.Unresolved) {\n fn.queueCount++\n q.push(fn)\n }\n }\n }\n\n currentDeps.map((dep) => dep[turbopackQueues](fnQueue))\n\n return fn.queueCount ? promise : getResult()\n }\n\n function asyncResult(err?: any) {\n if (err) {\n reject((promise[turbopackError] = err))\n } else {\n resolve(promise[turbopackExports])\n }\n\n resolveQueue(queue)\n }\n\n body(handleAsyncDependencies, asyncResult)\n\n if (queue && queue.status === QueueStatus.Unknown) {\n queue.status = QueueStatus.Unresolved\n }\n}\ncontextPrototype.a = asyncModule\n"],"names":["turbopackQueues","Symbol","turbopackExports","turbopackError","isPromise","maybePromise","then","isAsyncModuleExt","obj","createPromise","resolve","reject","promise","Promise","res","rej","resolveQueue","queue","status","forEach","fn","queueCount","wrapDeps","deps","map","dep","Object","assign","err","asyncModule","body","hasAwait","module","m","undefined","depQueues","Set","rawPromise","exports","attributes","get","set","v","defineProperty","handleAsyncDependencies","currentDeps","getResult","d","fnQueue","q","has","add","push","asyncResult","contextPrototype","a"],"mappings":"AAAA,6CAA6C;AAC7C,2CAA2C;AAE3C;;;;;;;;;CASC,GAED,MAAMA,kBAAkBC,OAAO;AAC/B,MAAMC,mBAAmBD,OAAO;AAChC,MAAME,iBAAiBF,OAAO;AAuB9B,SAASG,UAAmBC,YAAiB;IAC3C,OACEA,gBAAgB,QAChB,OAAOA,iBAAiB,YACxB,UAAUA,gBACV,OAAOA,aAAaC,IAAI,KAAK;AAEjC;AAEA,SAASC,iBAA+BC,GAAM;IAC5C,OAAOR,mBAAmBQ;AAC5B;AAEA,SAASC;IACP,IAAIC;IACJ,IAAIC;IAEJ,MAAMC,UAAU,IAAIC,QAAW,CAACC,KAAKC;QACnCJ,SAASI;QACTL,UAAUI;IACZ;IAEA,OAAO;QACLF;QACAF,SAASA;QACTC,QAAQA;IACV;AACF;AAEA,SAASK,aAAaC,KAAkB;IACtC,IAAIA,SAASA,MAAMC,MAAM,KAhDd,GAgDyC;QAClDD,MAAMC,MAAM,GAjDH;QAkDTD,MAAME,OAAO,CAAC,CAACC,KAAOA,GAAGC,UAAU;QACnCJ,MAAME,OAAO,CAAC,CAACC,KAAQA,GAAGC,UAAU,KAAKD,GAAGC,UAAU,KAAKD;IAC7D;AACF;AAEA,SAASE,SAASC,IAAW;IAC3B,OAAOA,KAAKC,GAAG,CAAC,CAACC;QACf,IAAIA,QAAQ,QAAQ,OAAOA,QAAQ,UAAU;YAC3C,IAAIlB,iBAAiBkB,MAAM,OAAOA;YAClC,IAAIrB,UAAUqB,MAAM;gBAClB,MAAMR,QAAoBS,OAAOC,MAAM,CAAC,EAAE,EAAE;oBAC1CT,QA9DK;gBA+DP;gBAEA,MAAMV,MAAsB;oBAC1B,CAACN,iBAAiB,EAAE,CAAC;oBACrB,CAACF,gBAAgB,EAAE,CAACoB,KAAoCA,GAAGH;gBAC7D;gBAEAQ,IAAInB,IAAI,CACN,CAACQ;oBACCN,GAAG,CAACN,iBAAiB,GAAGY;oBACxBE,aAAaC;gBACf,GACA,CAACW;oBACCpB,GAAG,CAACL,eAAe,GAAGyB;oBACtBZ,aAAaC;gBACf;gBAGF,OAAOT;YACT;QACF;QAEA,OAAO;YACL,CAACN,iBAAiB,EAAEuB;YACpB,CAACzB,gBAAgB,EAAE,KAAO;QAC5B;IACF;AACF;AAEA,SAAS6B,YAEPC,IAKS,EACTC,QAAiB;IAEjB,MAAMC,SAAS,IAAI,CAACC,CAAC;IACrB,MAAMhB,QAAgCc,WAClCL,OAAOC,MAAM,CAAC,EAAE,EAAE;QAAET,MAAM;IAAsB,KAChDgB;IAEJ,MAAMC,YAA6B,IAAIC;IAEvC,MAAM,EAAE1B,OAAO,EAAEC,MAAM,EAAEC,SAASyB,UAAU,EAAE,GAAG5B;IAEjD,MAAMG,UAA8Bc,OAAOC,MAAM,CAACU,YAAY;QAC5D,CAACnC,iBAAiB,EAAE8B,OAAOM,OAAO;QAClC,CAACtC,gBAAgB,EAAE,CAACoB;YAClBH,SAASG,GAAGH;YACZkB,UAAUhB,OAAO,CAACC;YAClBR,OAAO,CAAC,QAAQ,CAAC,KAAO;QAC1B;IACF;IAEA,MAAM2B,aAAiC;QACrCC;YACE,OAAO5B;QACT;QACA6B,KAAIC,CAAM;YACR,qCAAqC;YACrC,IAAIA,MAAM9B,SAAS;gBACjBA,OAAO,CAACV,iBAAiB,GAAGwC;YAC9B;QACF;IACF;IAEAhB,OAAOiB,cAAc,CAACX,QAAQ,WAAWO;IACzCb,OAAOiB,cAAc,CAACX,QAAQ,mBAAmBO;IAEjD,SAASK,wBAAwBrB,IAAW;QAC1C,MAAMsB,cAAcvB,SAASC;QAE7B,MAAMuB,YAAY,IAChBD,YAAYrB,GAAG,CAAC,CAACuB;gBACf,IAAIA,CAAC,CAAC5C,eAAe,EAAE,MAAM4C,CAAC,CAAC5C,eAAe;gBAC9C,OAAO4C,CAAC,CAAC7C,iBAAiB;YAC5B;QAEF,MAAM,EAAEU,OAAO,EAAEF,OAAO,EAAE,GAAGD;QAE7B,MAAMW,KAAmBM,OAAOC,MAAM,CAAC,IAAMjB,QAAQoC,YAAY;YAC/DzB,YAAY;QACd;QAEA,SAAS2B,QAAQC,CAAa;YAC5B,IAAIA,MAAMhC,SAAS,CAACkB,UAAUe,GAAG,CAACD,IAAI;gBACpCd,UAAUgB,GAAG,CAACF;gBACd,IAAIA,KAAKA,EAAE/B,MAAM,KAzJV,GAyJuC;oBAC5CE,GAAGC,UAAU;oBACb4B,EAAEG,IAAI,CAAChC;gBACT;YACF;QACF;QAEAyB,YAAYrB,GAAG,CAAC,CAACC,MAAQA,GAAG,CAACzB,gBAAgB,CAACgD;QAE9C,OAAO5B,GAAGC,UAAU,GAAGT,UAAUkC;IACnC;IAEA,SAASO,YAAYzB,GAAS;QAC5B,IAAIA,KAAK;YACPjB,OAAQC,OAAO,CAACT,eAAe,GAAGyB;QACpC,OAAO;YACLlB,QAAQE,OAAO,CAACV,iBAAiB;QACnC;QAEAc,aAAaC;IACf;IAEAa,KAAKc,yBAAyBS;IAE9B,IAAIpC,SAASA,MAAMC,MAAM,SAA0B;QACjDD,MAAMC,MAAM,GAlLD;IAmLb;AACF;AACAoC,iBAAiBC,CAAC,GAAG1B","ignoreList":[0]}}, - {"offset": {"line": 683, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/browser/runtime/base/runtime-base.ts"],"sourcesContent":["/**\n * This file contains runtime types and functions that are shared between all\n * Turbopack *browser* ECMAScript runtimes.\n *\n * It will be appended to the runtime code of each runtime right after the\n * shared runtime utils.\n */\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// \n/// \n\n// Used in WebWorkers to tell the runtime about the chunk suffix\ndeclare var TURBOPACK_ASSET_SUFFIX: string\n// Used in WebWorkers to tell the runtime about the current chunk url since it\n// can't be detected via `document.currentScript`. Note it's stored in reversed\n// order to use `push` and `pop`\ndeclare var TURBOPACK_NEXT_CHUNK_URLS: ChunkUrl[] | undefined\n// Used in WebWorkers to override the regular chunk base path with the base\n// used for the worker entrypoint and its initial chunks.\ndeclare var TURBOPACK_CHUNK_BASE_PATH: string | undefined\n\n// Injected by rust code\ndeclare var CHUNK_BASE_PATH: string\ndeclare var ASSET_SUFFIX: string\ndeclare var CROSS_ORIGIN: 'anonymous' | 'use-credentials' | null\ndeclare var CHUNK_LOAD_RETRY_MAX_ATTEMPTS: number\ndeclare var CHUNK_LOAD_RETRY_BASE_DELAY_MS: number\ndeclare var CHUNK_LOAD_RETRY_MAX_JITTER_MS: number\ndeclare const SUPPORT_COMPONENT_CHUNKS: boolean\n\ninterface TurbopackBrowserBaseContext extends TurbopackBaseContext {\n R: ResolvePathFromModule\n}\n\nconst browserContextPrototype =\n Context.prototype as TurbopackBrowserBaseContext\n\nconst RUNTIME_CHUNK_BASE_PATH =\n typeof TURBOPACK_CHUNK_BASE_PATH === 'string'\n ? TURBOPACK_CHUNK_BASE_PATH\n : CHUNK_BASE_PATH\n\n// Provided by build or dev base\ndeclare function instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module\n\ntype RuntimeParams = {\n otherChunks: ChunkData[]\n runtimeModuleIds: ModuleId[]\n}\n\ntype ChunkRegistrationChunk =\n | ChunkPath\n | { getAttribute: (name: string) => string | null }\n | undefined\n\ntype ChunkRegistration = [\n chunkPath: ChunkRegistrationChunk,\n ...([RuntimeParams] | CompressedModuleFactories),\n]\n\ntype ChunkList = {\n script: ChunkRegistrationChunk\n chunks: ChunkData[]\n source: 'entry' | 'dynamic'\n}\n\ninterface RuntimeBackend {\n /**\n * Registers a chunk. `chunk` is `undefined` for an inlined entry-only registration\n * (no source chunk): the params' other chunks are loaded and its runtime modules run\n * with no self chunk identity.\n */\n registerChunk: (\n chunk: ChunkPath | ChunkScript | undefined,\n params?: RuntimeParams\n ) => void\n /**\n * Returns the same Promise for the same chunk URL.\n */\n loadChunkCached: (sourceType: SourceType, chunkUrl: ChunkUrl) => Promise\n}\n\ninterface DevRuntimeBackend {\n reloadChunk?: (chunkUrl: ChunkUrl) => Promise\n unloadChunk?: (chunkUrl: ChunkUrl) => void\n restart: () => void\n}\n\nconst moduleFactories: ModuleFactories = new Map()\ncontextPrototype.M = moduleFactories\n\nconst availableModules: Map | true> = new Map()\n\nconst availableModuleChunks: Map | true> = new Map()\n\n// Registry mapping a merged chunk's path to its constituent component chunk paths.\nconst chunkComponents: Map = new Map()\n\n// Registry mapping a component chunk's path to its size in bytes, used by the\n// split-vs-whole cost heuristic.\nconst componentChunkSizes: Map = new Map()\n\nfunction registerComponentChunkSizes(\n componentChunks: ChunkPath[],\n sizes: number[]\n): void {\n for (let i = 0; i < componentChunks.length; i++) {\n const size = sizes[i]\n if (size !== undefined) {\n componentChunkSizes.set(componentChunks[i], size)\n }\n }\n}\n\ntype ChunkUrlOrMerged = ChunkUrl | [ChunkUrl, ChunkPath[], number[]]\n\n// Memoizes the composite promise returned for a merged chunk loaded by URL, keyed by URL.\nconst splitChunkPromises: Map> = new Map()\n\nfunction loadChunk(\n this: TurbopackBrowserBaseContext,\n chunkData: ChunkData\n): Promise {\n return loadChunkInternal(SourceType.Parent, this.m.id, chunkData)\n}\nbrowserContextPrototype.l = loadChunk\n\n// `chunkPath` is the source chunk; it is `undefined` for entry-only registrations,\n// which have no self chunk.\nfunction loadInitialChunk(\n chunkPath: ChunkPath | undefined,\n chunkData: ChunkData\n) {\n return loadChunkInternal(SourceType.Runtime, chunkPath, chunkData)\n}\n\nasync function loadChunkInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkData: ChunkData\n): Promise {\n if (typeof chunkData === 'string') {\n return loadChunkPath(sourceType, sourceData, chunkData)\n }\n\n const includedList = chunkData.included || []\n const modulesPromises = includedList.map((included) => {\n if (moduleFactories.has(included)) return true\n return availableModules.get(included)\n })\n if (modulesPromises.length > 0 && modulesPromises.every((p) => p)) {\n // When all included items are already loaded or loading, we can skip loading ourselves\n await Promise.all(modulesPromises)\n return\n }\n\n let promise: Promise\n if (SUPPORT_COMPONENT_CHUNKS) {\n const componentChunks = chunkData.moduleChunks || []\n // We already have this chunk's component list inline (chunkData.moduleChunks) and split on it\n // here, so the whole-chunk fallback uses loadChunkByUrlWhole to skip loadChunkByUrlInternal's\n // chunkComponents-registry lookup, which would just repeat the same split decision.\n promise = loadComponentChunksOrWhole(\n sourceType,\n sourceData,\n componentChunks,\n getChunkRelativeUrl(chunkData.path)\n )\n } else {\n promise = loadChunkByUrlWhole(\n sourceType,\n sourceData,\n getChunkRelativeUrl(chunkData.path)\n )\n }\n\n for (const included of includedList) {\n if (!availableModules.has(included)) {\n // 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.\n // In production it's even more rare, because the chunk optimization tries to deduplicate modules anyway.\n availableModules.set(included, promise)\n }\n }\n\n await promise\n}\n\n/**\n * Approximate cost of an extra HTTP request, expressed in emitted (minified, uncompressed) chunk\n * bytes, used to decide whether splitting a merged chunk into individually-cached component\n * chunks is worthwhile.\n */\nconst REQUEST_COST_BYTES = 20_000\n\n/**\n * Decides whether to load a merged chunk's component chunks individually instead of the whole\n * merged chunk, weighing the bytes saved (the available components we avoid re-downloading)\n * against the extra network requests splitting incurs.\n *\n * Splitting issues one request per unavailable component vs. a single request for the merged\n * chunk, so it adds `unavailableCount - 1` extra requests. When at most one component needs the\n * network, splitting never costs more requests than the merged load (and transfers fewer bytes),\n * so it always wins. Otherwise it's only worth it when the available bytes exceed the extra\n * request cost.\n */\nfunction shouldLoadComponentChunks(\n availableBytes: number,\n unavailableCount: number\n): boolean {\n if (unavailableCount <= 1) {\n return true\n }\n return availableBytes > REQUEST_COST_BYTES * (unavailableCount - 1)\n}\n\n/**\n * Loads a chunk's component chunks individually when enough of them are already available\n * in memory (avoiding re-downloading the ones we have, per `shouldLoadComponentChunks`),\n * otherwise loads the whole chunk from `chunkUrl` and records its component chunks as available.\n */\nfunction loadComponentChunksOrWhole(\n sourceType: SourceType,\n sourceData: SourceData,\n componentChunks: ChunkPath[],\n chunkUrl: ChunkUrl\n): Promise {\n const componentChunkPromises: Array | true> = []\n let availableBytes = 0\n let unavailableCount = 0\n for (const componentChunk of componentChunks) {\n const available = availableModuleChunks.get(componentChunk)\n if (available) {\n componentChunkPromises.push(available)\n availableBytes += componentChunkSizes.get(componentChunk) ?? 0\n } else {\n unavailableCount++\n }\n }\n\n if (\n componentChunkPromises.length > 0 &&\n shouldLoadComponentChunks(availableBytes, unavailableCount)\n ) {\n // Enough component chunks are already loaded or loading that splitting saves more\n // bytes than the extra requests cost.\n for (const componentChunk of componentChunks) {\n if (!availableModuleChunks.has(componentChunk)) {\n const promise = loadChunkPath(sourceType, sourceData, componentChunk)\n availableModuleChunks.set(componentChunk, promise)\n componentChunkPromises.push(promise)\n }\n }\n return Promise.all(componentChunkPromises)\n }\n\n // Not enough is available in memory for splitting to pay off. Load the\n // whole chunk in a single request and record its component chunks as available.\n const promise = loadChunkByUrlWhole(sourceType, sourceData, chunkUrl)\n for (const componentChunk of componentChunks) {\n if (!availableModuleChunks.has(componentChunk)) {\n availableModuleChunks.set(componentChunk, promise)\n }\n }\n return promise\n}\n\nconst loadedChunk = Promise.resolve(undefined)\nconst instrumentedBackendLoadChunks = new WeakMap<\n Promise,\n Promise | typeof loadedChunk\n>()\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrl(\n this: TurbopackBrowserBaseContext,\n chunkEntry: ChunkUrlOrMerged\n) {\n return loadChunkByUrlInternal(SourceType.Parent, this.m.id, chunkEntry)\n}\nbrowserContextPrototype.L = loadChunkByUrl\n\n// Do not make this async. React relies on referential equality of the returned Promise.\nfunction loadChunkByUrlInternal(\n sourceType: SourceType,\n sourceData: SourceData,\n chunkEntry: ChunkUrlOrMerged\n): Promise {\n if (SUPPORT_COMPONENT_CHUNKS) {\n // A merged chunk arrives as a `[url, componentChunkPaths, componentChunkSizes]` array. Register\n // the components so a by-URL load of this merged chunk — now or from a later navigation — can\n // be split, and so `registerChunk` can mark them available when the whole chunk loads.\n let chunkUrl: ChunkUrl\n let components: ChunkPath[] | undefined\n if (typeof chunkEntry === 'string') {\n chunkUrl = chunkEntry\n } else {\n let componentSizes: number[]\n ;[chunkUrl, components, componentSizes] = chunkEntry\n registerComponentChunkSizes(components, componentSizes)\n }\n const chunkPath = chunkUrlToPath(chunkUrl)\n if (components !== undefined) {\n chunkComponents.set(chunkPath, components)\n } else {\n // A plain URL may still be a merged chunk we already registered from its array.\n components = chunkComponents.get(chunkPath)\n }\n\n // If we have component chunks for this merged chunk, load only the ones we don't already have\n // instead of the whole merged chunk.\n if (components !== undefined) {\n let promise = splitChunkPromises.get(chunkUrl)\n if (promise === undefined) {\n promise = loadComponentChunksOrWhole(\n sourceType,\n sourceData,\n components,\n chunkUrl\n )\n splitChunkPromises.set(chunkUrl, promise)\n }\n return promise\n }\n\n // This is a non-merged chunk. If its modules were already loaded — e.g. this chunk is a\n // component of a merged chunk fetched on a previous navigation — reuse that load instead of\n // re-downloading.\n const existing = availableModuleChunks.get(chunkPath)\n if (existing !== undefined) {\n return existing === true ? loadedChunk : existing\n }\n const promise = loadChunkByUrlWhole(sourceType, sourceData, chunkUrl)\n availableModuleChunks.set(chunkPath, promise)\n return promise\n }\n\n // Component chunks are disabled, so the chunking context never emits merged arrays and every\n // entry is a plain chunk URL. Load it whole; the backend dedupes repeated URLs.\n return loadChunkByUrlWhole(sourceType, sourceData, chunkEntry as ChunkUrl)\n}\n\n// Convert a chunk URL back to its ChunkPath (strip base path, query/hash, decode), to\n// match the keys stored in `chunkComponents`.\nfunction chunkUrlToPath(chunkUrl: ChunkUrl): ChunkPath {\n const src = decodeURIComponent(chunkUrl.replace(/[?#].*$/, ''))\n return (\n src.startsWith(RUNTIME_CHUNK_BASE_PATH)\n ? src.slice(RUNTIME_CHUNK_BASE_PATH.length)\n : src\n ) as ChunkPath\n}\n\n/**\n * When a merged chunk finishes registering (e.g. an initial-load `