[{{mminutes}}:{{sseconds}}] X
Пользователь приглашает вас присоединиться к открытой игре игре с друзьями .
TypeScript
(0)       Используют 8 человек

Комментарии

pepepe 20 августа 2024
Длинные строки (да еще из такого проекта) это конечно полный треш
Написать тут
Описание:
Длинные строки из репозитория next.js https://github.com/vercel/next.js/
Автор:
trolle
Создан:
1 марта 2023 в 16:08 (текущая версия от 4 марта 2023 в 10:25)
Публичный:
Нет
Тип словаря:
Фразы
В этом режиме перемешиваться будут не слова, а целые фразы, разделенные переносом строки.
Содержание:
1 const response = await fetchViaHTTP(next.url, `/_next/data/${next.buildId}/with-middleware.json`, undefined, { headers: { 'x-nextjs-data': '1' } });
2 const response = await fetchViaHTTP(next.url, `/_next/data/${next.buildId}/another-middleware.json`, undefined, { headers: { 'x-nextjs-data': '1' } });
3 const response = await fetchViaHTTP(next.url, `/_next/data/${next.buildId}/index.json`, undefined, { headers: { 'x-nextjs-data': '1' } });
4 return matchers && matchers.some((m) => m.regexp.includes('with-middleware')) && matchers.some((m) => m.regexp.includes('another-middleware')) ? 'success' : 'failed';
5 const response = await fetchViaHTTP(next.url, `/_next/data/${next.buildId}/middleware/works.json`, undefined, { headers: { 'x-nextjs-data': '1' } });
6 describe.each([{ title: '' }, { title: ' and trailingSlash', trailingSlash: true }])('using a single matcher with i18n$title', ({ trailingSlash }) => {
7 const res1 = await fetchViaHTTP(next.url, `/_next/data/${next.buildId}/en.json`, undefined, { headers: { 'x-nextjs-data': '1' } });
8 describe.each([{ title: '' }, { title: ' and trailingSlash', trailingSlash: true }])('using a single matcher with i18n and basePath$title', ({ trailingSlash }) => {
9 const res1 = await fetchViaHTTP(next.url, `/root/_next/data/${next.buildId}/en.json`, undefined, { headers: { 'x-nextjs-data': '1' } });
10 const res2 = await fetchViaHTTP(next.url, `/root/_next/data/${next.buildId}/es.json`, undefined, { headers: { 'x-nextjs-data': '1' } });
11 for (const [asPath, pathname, query] of [['/'], ['/another'], ['/dynamic/first', '/dynamic/[slug]', { slug: 'first' }], ['/dynamic/second', '/dynamic/[slug]', { slug: 'second' }]]) {
12 tests: [/webpack-runtime\.js/, /node_modules\/react\/index\.js/, /node_modules\/react\/package\.json/, /node_modules\/react\/cjs\/react\.production\.min\.js/],
13 const chunks = (await fs.readdir(path.join(next.testDir, '.next', 'static', 'chunks'))).filter((f) => f.endsWith('.js'));
14 expect(await browser.elementByCss('#root > .segments').text()).toMatchInlineSnapshot(`"[\\"segment-name\\",\\"value1\\",\\"segment-name2\\",\\"value2\\",\\"value3/value4\\"]"`);
15 expect(await browser.elementByCss('#before-static > .segments').text()).toMatchInlineSnapshot(`"[\\"segment-name2\\",\\"value2\\",\\"value3/value4\\"]"`);
16 expect(await browser.elementByCss('#before-param > .segments').text()).toMatchInlineSnapshot(`"[\\"value2\\",\\"value3/value4\\"]"`);
17 expect(await browser.elementByCss('#root > .segments').text()).toMatchInlineSnapshot(`"[\\"segment-name\\",\\"param1\\",\\"different-segment\\"]"`);
18 expect(await browser.elementByCss('#root > .segments').text()).toMatchInlineSnapshot(`"[\\"segment-name\\",\\"param1\\",\\"segment-name2\\",\\"different-value\\",\\"value3/value4\\"]"`);
19 expect(await browser.elementByCss('#before-param > .segments').text()).toMatchInlineSnapshot(`"[\\"different-value\\",\\"value3/value4\\"]"`);
20 expect(await browser.elementByCss('#root > .segments').text()).toMatchInlineSnapshot(`"[\\"segment-name\\",\\"param1\\",\\"segment-name2\\",\\"value2\\",\\"different/random/paths\\"]"`);
21 expect(await browser.eval(`[...document.styleSheets].some(({ rules }) => [...rules].some(rule => rule.selectorText.includes('this_should_not_be_included')))`)).toBe(false);
22 expect(await browser.eval(`[...document.styleSheets].some(({ rules }) => [...rules].some(rule => rule.selectorText.includes('this_should_not_be_included_in_inner_path')))`)).toBe(false);
23 path | outerLayout | innerLayout
24 ${'/hooks/use-selected-layout-segment/first'} | ${['first']} | ${[]}
25 ${'/hooks/use-selected-layout-segment/first/slug1'} | ${['first', 'slug1']} | ${['slug1']}
26 ${'/hooks/use-selected-layout-segment/first/slug2/second'} | ${['first', 'slug2', '(group)', 'second']} | ${['slug2', '(group)', 'second']}
27 ${'/hooks/use-selected-layout-segment/first/slug2/second/a/b'} | ${['first', 'slug2', '(group)', 'second', 'a/b']} | ${['slug2', '(group)', 'second', 'a/b']}
28 ${'/hooks/use-selected-layout-segment/rewritten'} | ${['first', 'slug3', '(group)', 'second', 'catch/all']} | ${['slug3', '(group)', 'second', 'catch/all']}
29 ${'/hooks/use-selected-layout-segment/rewritten-middleware'} | ${['first', 'slug3', '(group)', 'second', 'catch/all']} | ${['slug3', '(group)', 'second', 'catch/all']}
30 path | outerLayout | innerLayout
31 ${'/hooks/use-selected-layout-segment/first'} | ${'first'} | ${null}
32 ${'/hooks/use-selected-layout-segment/first/slug1'} | ${'first'} | ${'slug1'}
33 async function checkMeta(browser: BrowserInterface, name: string, content: string | string[], property: string = 'property', tag: string = 'meta', field: string = 'content') {
34 const values = await browser.eval(`[...document.querySelectorAll('${tag}[${property}="${name}"]')].map((el) => el.getAttribute("${field}"))`);
35 const checkLink = (browser: BrowserInterface, rel: string, content: string | string[]) => checkMeta(browser, rel, content, 'rel', 'link', 'href');
36 expect($('[property="og:image"]').attr('content')).toMatch( /https:\/\/example.com\/_next\/opengraph-image.\w+.png/);
37 expect($('[name="twitter:image"]').attr('content')).toMatch( /https:\/\/example.com\/_next\/twitter-image.\w+.png/);
38 expect(await queryMetaProps(browser, 'link', 'href="/apple-icon-x3.png"', ['sizes', 'type'])).toEqual({ sizes: '180x180', type: 'image/png' });
39 expect(await browser.eval(`window.getComputedStyle(document.querySelector('p')).fontFamily`)).toMatch(/^__myFont_.{6}, __myFont_Fallback_.{6}$/);
40 expect(await browser.elementByCss('[href="/intercepting-parallel-modal/photos/1"]').click().waitForElementByCss('#photo-modal-1').text()).toBe('Photo MODAL 1');
41 it.each([['page'], ['layout'], ['component']])('should add preconnect when preloading is disabled in %s', async (type: string) => {
42 expect(await browser.elementByCss(`a[href="/nested-navigation/${category.toLowerCase()}"]`).click().waitForElementByCss(`#all-${category.toLowerCase()}`).text()).toBe(`All ${category}`);
43 await browser.elementByCss(`a[href="/nested-navigation/${category.toLowerCase()}/${subcategory.toLowerCase()}"]`).click().waitForElementByCss(`#${subcategory.toLowerCase()}`).text(),
44 it.each([{ pathname: '/redirect-1' }, { pathname: '/redirect-2' }, { pathname: '/blog/old-post' }, { pathname: '/redirect-3/some' }, { pathname: '/redirect-4' }])(
45 expect(res.headers.get('vary')).toBe(isNextDeploy ? 'RSC, Next-Router-State-Tree, Next-Router-Prefetch' : 'RSC, Next-Router-State-Tree, Next-Router-Prefetch, Accept-Encoding');
46 await next.patchFile(filePath, origContent.replace("// 'use client'", "'use client'").replace('hello dashboard/page!', 'hello dashboard/page in client component!'));
47 await next.patchFile(filePath, origContent.replace("// 'use client'", "'use client'").replace('hello dashboard/page!', 'hello dashboard/page in client component2!'));
48 expect(await browser.waitForElementByCss('body').elementByCss('h2').text()).toBe('Application error: a client-side exception has occurred (see the browser console for more information).');
49 expect(await browser.elementByCss('#link-to-info-123').click().waitForElementByCss('#message').text()).toBe(`hello from app/dashboard/deployments/info/[id]. ID is: 123`);
50 expect(headTags.find((el) => el.attribs.src === '/hello3.js' && el.attribs['data-slug'] === 'post-1')).toBeTruthy();
51 export function cookieWithRequestMeta(meta: Record<string, any>, { cookie = '', ...headers }: Record<string, string> = {}): Record<string, string> {
52 export const helloHandler = async (request: NextRequest, { params }: { params?: Record<string, string | string[]> }): Promise<Response> => {
53 it.each(['/static/first/data.json', '/static/second/data.json', '/static/three/data.json'])('responds correctly on %s', async (path) => {
54 it.each(['/revalidate-1/first/data.json', '/revalidate-1/second/data.json', '/revalidate-1/three/data.json'])('revalidates correctly on %s', async (path) => {
55 describe.each(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])('made via a %s request', (method) => {
56 it.each([['get'], ['head'], ['options'], ['post'], ['put'], ['delete'], ['patch']])('should print an error when using lowercase %p in dev', async (method: string) => {
57 expect(next.cliOutput).toMatch(/Detected lowercase method '.+' in '.+\/route\.ts'\. Export the uppercase '.+' method name to fix this error\./);
58 dataRouteRegex: normalizeRegEx('^\\/static\\-to\\-dynamic\\-error\\-forced\\/([^\\/]+?)\\.rsc$'),
59 routeRegex: normalizeRegEx('^\\/static\\-to\\-dynamic\\-error\\-forced\\/([^\\/]+?)(?:\\/)?$'),
60 it.each(['/hello', '/en/hello', '/nl-NL/hello', '/nl-NL/about'])('should match', async (path) => {
61 it.each(['/invalid/hello', '/hello/invalid', '/about', '/en/about'])('should not match', async (path) => {
62 itif(!isModeDeploy).each(['hello', 'en_hello', 'nl-NL_hello', 'nl-NL_about'])('should match has query on client routing', async (id) => {
63 const res = await fetchViaHTTP(next.url, `/_next/data/${next.buildId}/es/about.json`, { override: 'internal' }, { redirect: 'manual', headers: { 'x-nextjs-data': '1' } });
64 await check(() => browser.eval('next.router.query.hello === "world" ? "success" : JSON.stringify(next.router.query)'), 'success');
65 return didReq || requests.some((req) => new URL(req, 'http://n').pathname.endsWith('/to-ssg.json')) ? 'found' : JSON.stringify(requests);
66 const dataRes = await fetchViaHTTP(next.url, `/_next/data/${next.buildId}${i18n ? '/en' : ''}/ssr-page.json`, undefined, { headers: { 'x-nextjs-data': '1' } });
67 expect(requests.filter((req) => req.includes('_next/data'))).toEqual([`${next.url}/_next/data/${next.buildId}${i18n ? '/en' : ''}/sha.json?hello=goodbye`]);
68 expect(hrefs.map((href) => new URL(href).pathname.replace(/\/_next\/data\/[^/]+/, ''))).toEqual([`${basePath}/gsp.json`, `${basePath}/index.json`, `${basePath}/index/index.json`]);
69 const res = await fetchViaHTTP(next.url, `/_next/data/${next.buildId}/es/old-home.json`, { override: 'internal' }, { redirect: 'manual', headers: { 'x-nextjs-data': '1' } });
70 const res = await fetchViaHTTP(next.url, `/_next/data/${next.buildId}/es/old-home.json`, { override: 'external' }, { redirect: 'manual', headers: { 'x-nextjs-data': '1' } });
71 expect(next.cliOutput).toContain("Invalid href '/hello//world' passed to next/router in page: '/my/path/[name]'. Repeated forward-slashes (//) or backslashes \\ are not valid in the href.");
72 const emitPopsStateEvent = (browser: BrowserInterface, state: HistoryState) => browser.eval(`window.dispatchEvent(new PopStateEvent("popstate", { state: ${JSON.stringify(state)} }))`);
73 expect(await browser.eval('getComputedStyle(document.querySelector("#app-open-sans")).fontFamily')).toMatch(/^__Open_Sans_.{6}, __Open_Sans_Fallback_.{6}$/);
74 expect(await browser.eval('getComputedStyle(document.querySelector("#with-fonts-open-sans")).fontFamily')).toMatch(/^__Open_Sans_.{6}, __Open_Sans_Fallback_.{6}$/);
75 expect(await browser.eval('getComputedStyle(document.querySelector("#comp-with-fonts-inter")).fontFamily')).toMatch(/^__Inter_.{6}, __Inter_Fallback_.{6}$/);
76 expect(await browser.eval('getComputedStyle(document.querySelector("#comp-with-fonts-roboto")).fontFamily')).toMatch(/^__Roboto_.{6}, __Roboto_Fallback_.{6}$/);
77 expect(await browser.eval('getComputedStyle(document.querySelector("#with-fallback-fonts-classname")).fontFamily')).toMatch(/^__Open_Sans_.{6}, system-ui, Arial$/);
78 expect(await browser.eval('getComputedStyle(document.querySelector("#with-fallback-fonts-style")).fontFamily')).toMatch(/^__Open_Sans_.{6}, system-ui, Arial$/);
79 expect(await browser.eval('getComputedStyle(document.querySelector("#with-fallback-fonts-variable")).fontFamily')).toMatch(/^__Open_Sans_.{6}, system-ui, Arial$/);
80 const dataRes = await fetchViaHTTP(next.url, `/_next/data/${next.buildId}/ssr-page.json`, undefined, { headers: { 'x-nextjs-data': '1' } });
81 expect(requests.filter((req) => req.includes('_next/data'))).toEqual([`${next.url}/ next/data/${next.buildId}/sha.json?hello=goodbye`]);
82 expect(configScript.replace(/(?: *[ ])+ */g, '')).toEqual('partytown = {lib: "/_next/static/~partytown/"};');
83 next = await createNextApp(`<Script id="inline-script" strategy="worker" dangerouslySetInnerHTML={{__html: "document.getElementById('text').textContent += 'abcd'"}}/>`);
84 expect(configScript.replace(/(?: *[ ])+ */g, '')).toEqual('partytown = {lib: "/_next/static/~partytown/",debug: true};');
85 const toBuild = ['/', '/another', '/something', '/normal', '/blog/post-1', '/blog/post-1/comment-1', '/catchall/first'];
86 expect(hrefs.map((href) => new URL(href).pathname.replace(/^\/_next\/data\/[^/]+/, ''))).toContainEqual('/lang/en/about.json');
87 await check(() => next.cliOutput, /Warning: data for page "\/large-page-data" is 256 kB which exceeds the threshold of 128 kB, this amount of data can reduce performance/);
88 await check(() => next.cliOutput, /Warning: data for page "\/large-page-data-ssr" is 256 kB which exceeds the threshold of 128 kB, this amount of data can reduce performance/);
89 await next.patchFile(indexPage, origContent.replace('// throw new', 'throw new').replace('{/* <div', '<div').replace('</div> */}', '</div>'));
90 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/api\\-docs\\/(.+?)\\.json$`),
91 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/blocking\\-fallback\\/([^\\/]+?)\\.json$`),
92 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/blocking\\-fallback\\-once\\/([^\\/]+?)\\.json$`),
93 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/blocking\\-fallback\\-some\\/([^\\/]+?)\\.json$`),
94 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/blog\\/([^\\/]+?)\\.json$`),
95 namedDataRouteRegex: `^/_next/data/${escapeRegex(next.buildId)}/blog/(?<post>[^/]+?)/(?<comment>[^/]+?)\\.json$`,
96 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/blog\\/([^\\/]+?)\\/([^\\/]+?)\\.json$`),
97 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/catchall\\-explicit\\/(.+?)\\.json$`),
98 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/catchall\\-optional(?:\\/(.+?))?\\.json$`),
99 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/dynamic\\/([^\\/]+?)\\.json$`),
100 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/fallback\\-only\\/([^\\/]+?)\\.json$`),
101 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/lang\\/([^\\/]+?)\\/about\\.json$`),
102 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/non\\-json\\/([^\\/]+?)\\.json$`),
103 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/non\\-json\\-blocking\\/([^\\/]+?)\\.json$`),
104 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(next.buildId)}\\/user\\/([^\\/]+?)\\/profile\\.json$`),
105 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\-once\\/([^\\/]+?)\\.json$`),
106 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\-some\\/([^\\/]+?)\\.json$`),
107 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapedBuildId}\\/blocking\\-fallback\\/([^\\/]+?)\\.json$`),
108 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapedBuildId}\\/blog\\/([^\\/]+?)\\.json$`),
109 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapedBuildId}\\/blog\\/([^\\/]+?)\\/([^\\/]+?)\\.json$`),
110 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapedBuildId}\\/dynamic\\/([^\\/]+?)\\.json$`),
111 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapedBuildId}\\/fallback\\-only\\/([^\\/]+?)\\.json$`),
112 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapedBuildId}\\/lang\\/([^\\/]+?)\\/about\\.json$`),
113 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapedBuildId}\\/non\\-json\\-blocking\\/([^\\/]+?)\\.json$`),
114 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapedBuildId}\\/non\\-json\\/([^\\/]+?)\\.json$`),
115 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapedBuildId}\\/user\\/([^\\/]+?)\\/profile\\.json$`),
116 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapedBuildId}\\/catchall\\-optional(?:\\/(.+?))?\\.json$`),
117 previewCookie += `${isBypass ? '__prerender_bypass' : '__next_preview_data'}=${c[isBypass ? '__prerender_bypass' : '__next_preview_data']}`;
118 tests: [/webpack-runtime\.js/, /node_modules\/react\/index\.js/, /node_modules\/react\/package\.json/, /node_modules\/react\/cjs\/react\.production\.min\.js/, /node_modules\/next/],
119 await check(() => (next.cliOutput.match(/throwing error for \/blocking-fallback\/test-errors-1/).length === 1 ? 'success' : next.cliOutput), 'success');
120 await check(() => (next.cliOutput.match(/throwing error for \/blocking-fallback\/test-errors-2/).length === 1 ? 'success' : next.cliOutput), 'success');
121 return redirect.statusCode === 308 && (redirect.destination === '/:path+' || redirect.destination === '/:path+/');
122 let res = await fetchViaHTTP(next.url, `/_next/data/${next.buildId}/middleware-rewrite-with-slash.json`, undefined, { redirect: 'manual', headers: { 'x-nextjs-data': '1' } });
123 res = await fetchViaHTTP(next.url, `/_next/data/${next.buildId}/middleware-rewrite-without-slash.json`, undefined, { redirect: 'manual', headers: { 'x-nextjs-data': '1' } });
124 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/blog\\/([^\\/]+?)\\.json$`),
125 namedDataRouteRegex: `^/_next/data/${escapeRegex(buildId)}/blog/(?<post>[^/]+?)/(?<comment>[^/]+?)\\.json$`,
126 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/blog\\/([^\\/]+?)\\/([^\\/]+?)\\.json$`),
127 dataRouteRegex: `^\\/_next\\/data\\/${escapeRegex(buildId)}\\/not\\-found\\/([^\\/]+?)\\.json$`,
128 dataRouteRegex: normalizeRegEx(`^\\/_next\\/data\\/${escapeRegex(buildId)}\\/user\\/([^\\/]+?)\\/profile\\.json$`),
129 const toBuild = ['/', '/another', '/something', '/normal', '/blog/post-1', '/blog/post-1/comment-1'];
130 const [three, four] = await Promise.all([fetchWithDuration(ctx.appPort, '/_next/image', query, opts), fetchWithDuration(ctx.appPort, '/_next/image', query, opts)]);
131 const xCache = [res1, res2, res3].map((r) => r.headers.get('X-Nextjs-Cache')).sort((a, b) => b.localeCompare(a));
132 expect(stderr).toContain('The value at .images.remotePatterns[0] has an unexpected property, foo, which is not in the list of allowed properties (hostname, pathname, port, protocol).');
133 it.each(undefinedProperties.map((api) => ({ api })))('does not throw on using $api', async ({ api }) => {
134 it.each(['Buffer', ...undefinedProperties].map((api) => ({ api })))('does not warn on using $api', ({ api }) => {
135 expect(await browser.elementById('img1').getAttribute('srcset')).toBe(`/_next/image`);
136 expect(await browser.elementById('img3').getAttribute('srcset')).toBe(`/_next/image`);
137 expect(await img.getAttribute('style')).toBe('position:absolute;height:100%;width:100%;left:0;top:0;right:0;bottom:0;object-fit:cover;object-position:10% 10%;color:transparent');
138 expect(await getRedboxHeader(browser)).toContain('Invalid src prop (https://google.com/test.png) on `next/image`, hostname "google.com" is not configured under images in your `next.config.js`');
139 expect(await browser.eval(`document.getElementById("fill-image-1").getAttribute('style')`)).toBe('position:absolute;height:100%;width:100%;left:0;top:0;right:0;bottom:0;color:transparent');
140 expect(warnings).toContain('Image with src "/wide.png" has "fill" and parent element with invalid "position". Provided "static" should be one of absolute,fixed,relative.');
141 expect(warnings).toContain('Image with src "/wide.png" has "fill" and a height value of 0. This is likely because the parent element of the image has not been styled to have a set height.');
142 outputs: ['The value at .images.loader must be one of', 'The value at .rewrites must be a function that returns a Promise', 'The value at .swcMinify must be a boolean but it was a string'],
143 expect(await browser.elementById('basic-image').getAttribute('srcset')).toBe('https://customresolver.com/foo.jpg?w~~480,q~~60 1x, https://customresolver.com/foo.jpg?w~~1024,q~~60 2x');
144 expect(warnings).toMatch(/Image with src (.*)jpg(.*) may not render properly with a parent using position:"static". Consider changing the parent style to position:"relative"/gm);
145 expect([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a].every((b, i) => buffer[i] === b)).toBeTrue();
146 [projectName, '--ts', '--eslint', '--no-src-dir', '--no-experimental-app', `--import-alias=@/*`],
147 [projectName, '--ts', '--eslint', '--src-dir', '--no-experimental-app', `--import-alias=@/*`],
148 [projectName, '--js', '--eslint', '--no-src-dir', '--no-experimental-app', `--import-alias=@/*`],
149 [projectName, '--js', '--eslint', '--src-dir', '--no-experimental-app', `--import-alias=@/*`],
150 [projectName, '--ts', '--experimental-app', '--eslint', '--no-src-dir', `--import-alias=@/*`],
151 [projectName, '--js', '--experimental-app', '--eslint', '--no-src-dir', `--import-alias=@/*`],
152 [projectName, '--js', '--experimental-app', '--eslint', '--src-dir', '--import-alias=@/*'],
153 const res = await run([projectName, '--js', '--eslint', '--no-src-dir', '--no-experimental-app', `--import-alias=@/*`], {
154 const res = await run([projectName, '--js', '--eslint', '--no-src-dir', '--no-experimental-app', `--import-alias=@/*`], { cwd });
155 const res = await run([projectName, '--js', '--eslint', '--example', `${exampleRepo}/${examplePath}`], {
156 const res = await run([projectName, '--js', '--eslint', '--example', 'https://github.com/vercel/nextjs-portfolio-starter/'], {
157 const res = await run([projectName, '--js', '--eslint', '--example', exampleRepo, '--example-path', examplePath], {
158 const res = await run([projectName, '--js', '--eslint', '--example', `${exampleRepo}/${examplePath}`, '--example-path', examplePath], {
159 const res = await run([projectName, '--js', '--eslint', '--example', '__internal-testing-retry', '--import-alias=@/*'], {
160 const res = await run([projectName, '--js', '--eslint', '--example', 'default', '--import-alias=@/*'], {
161 const res = await run([projectName, '--js', '--eslint', '--example', '--no-src-dir', '--no-experimental-app', `--import-alias=@/*`], {
162 const res = await run(['.', '--js', '--eslint', '--no-src-dir', '--no-experimental-app', `--import-alias=@/*`], {
163 const res = await run(['--js', '--eslint', '--no-src-dir', '--no-experimental-app', `--import-alias=@/*`], {
164 const res = await run([projectName, '--js', '--eslint', '--use-npm', '--no-src-dir', '--no-experimental-app', `--import-alias=@/*`], {
165 const res = await run([projectName, '--js', '--eslint', '--use-npm', '--example', `${exampleRepo}/${examplePath}`], { cwd });
166 const res = await run([projectName, '--js', '--eslint', '--use-pnpm', '--no-src-dir', '--no-experimental-app', `--import-alias=@/*`], {
167 const res = await run([projectName, '--js', '--eslint', '--use-pnpm', '--example', `${exampleRepo}/${examplePath}`], { cwd });
168 const res = await run([projectName, '--js', '--eslint', '--example', `${exampleRepo}/${examplePath}`], { cwd, env: { ...process.env, npm_config_user_agent: 'npm' } });
169 const res = await run([projectName, '--js', '--eslint', '--example', `${exampleRepo}/${examplePath}`], { cwd, env: { ...process.env, npm_config_user_agent: 'yarn' } });
170 const res = await run([projectName, '--js', '--eslint', '--example', `${exampleRepo}/${examplePath}`], { cwd, env: { ...process.env, npm_config_user_agent: 'pnpm' } });
171 export const mapSrcFiles = (files: string[], srcDir?: boolean) => files.map((file) => (srcDir && SRC_DIR_NAMES.some((name) => file.startsWith(name)) ? path.join('src', file) : file));
172 require('console').error(`missing expected file ${file}`, glob.sync('**/*', { cwd, ignore: '**/node_modules/**' }), files);
173 require('console').error(`unexpected file present ${file}`, glob.sync('**/*', { cwd, ignore: '**/node_modules/**' }), files);
174 await fs.writeFile(testServer, (await fs.readFile(testServer, 'utf8')).replace('console.error(err)', `console.error('top-level', err)`).replace('conf:', 'minimalMode: true,conf:'));
175 for (const path of ['/', '/dynamic/another/', '/dynamic/another', '/fallback/first/', '/fallback/first', '/fallback/another/', '/fallback/another']) {
176 await fs.writeFile(testServer, (await fs.readFile(testServer, 'utf8')).replace('console.error(err)', `console.error('top-level', err)`).replace('conf:', `minimalMode: ${minimalMode},conf:`));
177 await browser.eval('next.router.prefetch("/blog/first", undefined, { unstable_skipClientCache: true }).finally(() => { window.prefetchDone = "yes" })');
178 await browser.eval('next.router.push("/blog/first", undefined, { unstable_skipClientCache: true }).finally(() => { window.prefetchDone = "yes" })');
179 return cacheKeys.some((url) => url.includes('/blog/first')) && cacheKeys.some((url) => url.includes('/blog/second')) ? 'success' : JSON.stringify(requests, null, 2);
180 text: 'query pagesQuery { viewer { user { id name } id } } ',
181 await next.patchFile(indexPage, `import {secondData} from "@lib/second-data" ${indexContent.replace('</p>', `</p><p id="second-data">{JSON.stringify(secondData)}</p>`)}`);
182 expect(await getRedboxHeader(browser)).toMatch(`Objects are not valid as a React child (found: [object RegExp]). If you meant to render a collection of children, use an array instead.`);
183 browserLogs.some(({ message }) => message.includes("Fast Refresh will perform a full reload when you edit a file that's imported by modules outside of the React rendering tree.")),
184 const editedContent = originalContent.replace('<a className="text-blue-600" href="https://nextjs.org" id="test-link">', '<a className="text-red-600" href="https://nextjs.org" id="test-link">');
185 ])('basic next/dynamic usage, basePath: %p with %p compiler', (basePath: string, testCase: 'swc' | 'babel' | 'document.getInitialProps') => {
186 You're importing a component that needs next/headers. That only works in a Server Component which is not supported in the pages/ directory. Read more: https://beta.nextjs.org/docs/rendering/server-and-client-components
187 You're importing a component that needs server-only. That only works in a Server Component which is not supported in the pages/ directory. Read more: https://beta.nextjs.org/docs/rendering/server-and-client-components
188 expect(await session.evaluate(() => (document.querySelector('body > nextjs-portal').shadowRoot.querySelector('#nextjs__container_errors_desc a:nth-of-type(1)') as any).href)).toMatchSnapshot();
189 expect(await session.evaluate(() => (document.querySelector('body > nextjs-portal').shadowRoot.querySelector('#nextjs__container_errors_desc a:nth-of-type(2)') as any).href)).toMatchSnapshot();
190 expect(await session.evaluate(() => (document.querySelector('body > nextjs-portal').shadowRoot.querySelector('#nextjs__container_errors_desc a:nth-of-type(1)') as any).href)).toMatch(
191 expect(await session.getRedboxDescription()).toMatchInlineSnapshot(`"Error: Failed prop type: The prop \`href\` expects a \`string\` or \`object\` in <Link>, but got \`undefined\` instead."`);
192 expect(await session.evaluate(() => (window as any).log)).toEqual(['init LeafV1', 'init MiddleAV1', 'init MiddleBV1', 'init MiddleCV1', 'init RootV1']);
193 await session.write('./foo.js', `;(typeof global !== 'undefined' ? global : window).log.push('init FooV1'); import './bar'; export default function Foo() {};`);
194 await session.write('./bar.js', `;(typeof global !== 'undefined' ? global : window).log.push('init BarV1'); export default function Bar() {};`);
195 await session.patch('index.js', `;(typeof global !== 'undefined' ? global : window).log = []; require('./foo'); export default () => null;`);
196 didFullRefresh = didFullRefresh || !(await session.patch('./bar.js', `window.log.push('init BarV1.1'); export default function Bar() {};`));
197 didFullRefresh = didFullRefresh || !(await session.patch('./bar.js', `window.log.push('init BarV2'); export default function Bar() {};`));
198 didFullRefresh = didFullRefresh || !(await session.patch('./bar.js', `window.log.push('init BarV3'); export default function Bar() {};`));
199 You're importing a component that needs useState. It only works in a Client Component but none of its parents are marked with \\"use client\\", so they're Server Components by default.
200 expect(await session.getRedboxDescription()).toMatchInlineSnapshot(`"Error: Page with \`dynamic = \\"error\\"\` couldn't be rendered statically because it used \`cookies\`"`);
201 The error was caused by using 'styled-jsx' in 'app/comp2.js'. It only works in a Client Component but none of its parents are marked with \\"use client\\", so they're Server Components by default.
202 await session.patch('index.js', file.replace('//', "if (typeof window !== 'undefined') throw new Error('Component error')"));
203 test.each([['server'], ['client']])('%s component can recover from error thrown in the module', async (type: string) => {
204 ws.on('close', () => page.evaluate(`console.log('closed websocket ${ws.url()}')`).catch(() => {}));
205 this._buildId = (await fs.readFile(path.join(this.testDir, this.nextConfig?.distDir || '.next', 'BUILD_ID'), 'utf8').catch(() => '')).trim();
206 const deployRes = await execa('vercel', ['deploy', '--build-env', 'NEXT_PRIVATE_TEST_MODE=1', '--build-env', 'NEXT_TELEMETRY_DISABLED=1', ...additionalEnv, '--force', ...vercelFlags], {
207 type OmitFirstArgument<F> = F extends (firstArgument: any, ...args: infer P) => infer R ? (...args: P) => R : never;
208 const tmpDir = skipIsolatedNext ? path.join(__dirname, '../../tmp') : process.env.NEXT_TEST_DIR || (await fs.realpath(os.tmpdir()));
209 this.basePath = content.match(/['"`]?basePath['"`]?:.*?['"`](.*?)['"`]/)?.[1] || '';
210 path.join(__dirname, '../../traces', `${path.relative(path.join(__dirname, '../../'), process.env.TEST_FILE_PATH).replace(/\//g, '-')}`, `next-trace`),
211 expect(() => m(p, new URL('https://example.com'))).toThrow('Pattern should define hostname but found {"protocol":"https"}');
212 it('should handle amp as the middle parameter', () => check('/some/path?page=10&amp=1&last=here', '/some/path?page=10&last=here'));
213 response.cookies.set('foo', 'bar', { path: '/test' }).set('fooz', 'barz', { path: '/test2' });
214 expect(Object.fromEntries(response.headers.entries())['set-cookie']).toBe('foo=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT, fooz=barz; Path=/');
215 expect(Object.fromEntries(response.headers.entries())['set-cookie']).toBe('foo=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT, fooz=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT');
216 expect(() => getSortedRoutes(['/', '/blog', '/blog/[id]', '/blog/[id]/comments/[cid]', '/blog/[cid]'])).toThrowError(/different slug names/);
217 expect(() => getSortedRoutes(['/', '/blog', '/blog/[id]/comments/[id]', '/blog/[id]'])).toThrowError(/the same slug name/);
218 expect(() => getSortedRoutes(['/blog/[id]', '/blog/[id]/[...id]'])).toThrowError(/the same slug name/);
219 expect(() => getSortedRoutes(['/blog/[...id]/[...id2]'])).toThrowErrorMatchingInlineSnapshot(`"Catch-all must be the last part of the URL."`);
220 expect(() => getSortedRoutes(['/blog/[...id]/abc'])).toThrowErrorMatchingInlineSnapshot(`"Catch-all must be the last part of the URL."`);
221 expect(() => getSortedRoutes(['/blog/[....id]/abc'])).toThrowErrorMatchingInlineSnapshot(`"Segment names may not start with erroneous periods ('.id')."`);
222 expect(() => getSortedRoutes(['/blog/[..id]/abc'])).toThrowErrorMatchingInlineSnapshot(`"Segment names may not start with erroneous periods ('..id')."`);
223 expect(() => getSortedRoutes(['/blog/[[...id]'])).toThrowErrorMatchingInlineSnapshot(`"Segment names may not start or end with extra brackets ('[...id')."`);
224 expect(() => getSortedRoutes(['/blog/[[[...id]]'])).toThrowErrorMatchingInlineSnapshot(`"Segment names may not start or end with extra brackets ('[...id')."`);
225 expect(() => getSortedRoutes(['/blog/[...id]]'])).toThrowErrorMatchingInlineSnapshot(`"Segment names may not start or end with extra brackets ('id]')."`);
226 expect(() => getSortedRoutes(['/blog/[[...id]]]'])).toThrowErrorMatchingInlineSnapshot(`"Segment names may not start or end with extra brackets ('id]')."`);
227 expect(() => getSortedRoutes(['/blog/[[[...id]]]'])).toThrowErrorMatchingInlineSnapshot(`"Segment names may not start or end with extra brackets ('[...id]')."`);
228 expect(() => getSortedRoutes(['/[[blog]]'])).toThrowErrorMatchingInlineSnapshot(`"Optional route parameters are not yet supported (\\"[[blog]]\\")."`);
229 expect(() => getSortedRoutes(['/abc/[[blog]]'])).toThrowErrorMatchingInlineSnapshot(`"Optional route parameters are not yet supported (\\"[[blog]]\\")."`);
230 expect(() => getSortedRoutes(['/abc/[[blog]]/def'])).toThrowErrorMatchingInlineSnapshot(`"Optional route parameters are not yet supported (\\"[[blog]]\\")."`);
231 expect(() => getSortedRoutes(['/blog/[helloworld]', '/blog/[helloworld]/[hello-world]'])).toThrowError(/differ only by non-word/);
232 const [, react, reactNamespace] = output.match(/(([a-z0-9_]+)(\[[^\]]*?\]|\.[a-z0-9_]+)*?)\.Fragment/i);
233 expect(output).toMatchInlineSnapshot(`"var React=require('react');var __jsx=React.createElement;module.exports=function(){return __jsx(\\"div\\",null,\\"test2\\");};"`);
234 expect(output).toMatchInlineSnapshot(`"import{jsx as _jsx}from\\"react/jsx-runtime\\";var a=function a(){return/*#__PURE__*/_jsx(\\"a\\",{href:\\"/\\",children:\\"home\\"});};"`);
235 expect(output).toMatchInlineSnapshot(`"import React from\\"react\\";var __jsx=React.createElement;var a=function a(){return __jsx(\\"a\\",{href:\\"/\\"},\\"home\\");};"`);
236 Reason: Props must be returned as a plain object from test: \`{ props: { ... } }\` (received: \`[object Null]\`)."
237 Reason: Props must be returned as a plain object from test: \`{ props: { ... } }\` (received: \`[object Undefined]\`)."
238 Reason: Props must be returned as a plain object from test: \`{ props: { ... } }\` (received: \`[object Array]\`)."
239 Reason: Props must be returned as a plain object from test: \`{ props: { ... } }\` (received: \`[object Function]\`)."
240 expect(() => isSerializableProps('/', 'test', { k: { a: [1, { n: new Date() }] } })).toThrowErrorMatchingInlineSnapshot(`
241 expect(() => isSerializableProps('/', 'test', { k: { a: [1, { n: class A {} }] } })).toThrowErrorMatchingInlineSnapshot(`
242 expect(() => isSerializableProps('/', 'test', { k: { a: [function () {}] } })).toThrowErrorMatchingInlineSnapshot(`
243 expect(output).toMatchInlineSnapshot(`"export var __N_SSG=true;export{foo,bar as baz}from'.';export default function Test(){return __jsx(\\"div\\",null);}"`);
244 expect(output).toMatchInlineSnapshot(`"export var __N_SSG=true;export function Noop(){}export default function Test(){return __jsx(\\"div\\",null);}"`);
245 expect(output).toMatchInlineSnapshot(`"export var __N_SSG=true;export const foo=2;export default function Test(){return __jsx(\\"div\\",null);}"`);
246 expect(output).toMatchInlineSnapshot(`"const a=2;export var __N_SSG=true;export default function Test(){return __jsx(\\"div\\",null);}"`);
247 expect(output).toMatchInlineSnapshot(`"export var __N_SSG=true;export class MyClass{}export default function Test(){return __jsx(\\"div\\",null);}"`);
248 expect(output).toMatchInlineSnapshot(`"export var __N_SSG=true;export default class Test extends React.Component{render(){return __jsx(\\"div\\",null);}}"`);
249 expect(output).toMatchInlineSnapshot(`"class Test extends React.Component{render(){return __jsx(\\"div\\",null);}}export var __N_SSG=true;export default Test;"`);
250 expect(output).toMatchInlineSnapshot(`"function El(){return __jsx(\\"div\\",null);}export var __N_SSG=true;export{El as default};"`);
251 expect(output).toMatchInlineSnapshot(`"function El(){return __jsx(\\"div\\",null);}const a=5;export var __N_SSG=true;export{El as default,a};"`);
252 expect(output).toMatchInlineSnapshot(`"class El extends React.Component{render(){return __jsx(\\"div\\",null);}}const a=5;export var __N_SSG=true;export{El as default,a};"`);
253 expect(output).toMatchInlineSnapshot(`"import other from'other';const{a,cat:bar}=other;export var __N_SSG=true;export default function Home(){return __jsx(\\"div\\",null);}"`);
254 expect(output).toMatchInlineSnapshot(`"import other from'other';const[foo]=other;export var __N_SSG=true;export default function Home(){return __jsx(\\"div\\",null);}"`);
255 expect(spy).toHaveBeenCalledWith(expect.stringContaining('warn'), '`relay` has been moved out of `experimental` and into `compiler.relay`. Please update your next.config.js file accordingly.');
256 ['Source_Sans_Pro', { weight: '900', display: 'auto' }, 'https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@900&display=auto'],
257 ['Source_Sans_Pro', { weight: '200', style: 'italic' }, 'https://fonts.googleapis.com/css2?family=Source+Sans+Pro:ital,wght@1,200&display=swap'],
258 ['Roboto_Flex', { display: 'fallback', weight: 'variable', axes: ['opsz'] }, 'https://fonts.googleapis.com/css2?family=Roboto+Flex:opsz,wght@8..144,100..1000&display=fallback'],
259 ['Albert_Sans', { weight: 'variable', style: 'italic' }, 'https://fonts.googleapis.com/css2?family=Albert+Sans:ital,wght@1,100..900&display=swap'],
260 ['Roboto', { weight: ['500', '300', '400'], style: ['normal', 'italic'] }, 'https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap'],
261 ['Roboto Mono', { style: ['italic', 'normal'] }, 'https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@0,100..700;1,100..700&display=swap'],
262 ['Poppins', { weight: ['900', '400', '100'] }, 'https://fonts.googleapis.com/css2?family=Poppins:wght@100;400;900&display=swap'],
263 ['Nabla', { axes: ['EDPT', 'EHLT'] }, 'https://fonts.googleapis.com/css2?family=Nabla:EDPT,EHLT@0..200,0..24&display=swap'],
264 Available weights: \`100\`, \`200\`, \`300\`, \`400\`, \`500\`, \`600\`, \`700\`, \`800\`, \`900\`, \`variable\`"
265 Available axes: \`GRAD\`, \`XTRA\`, \`YOPQ\`, \`YTAS\`, \`YTDE\`, \`YTFI\`, \`YTLC\`, \`YTUC\`, \`opsz\`, \`slnt\`, \`wdth\`"
266 ).rejects.toThrowErrorMatchingInlineSnapshot(`"Unexpected \`variable\` in weight array for font \`Inter\`. You only need \`variable\`, it includes all available weights."`);
267 Available subsets: \`cyrillic\`, \`cyrillic-ext\`, \`greek\`, \`greek-ext\`, \`latin\`, \`latin-ext\`, \`vietnamese\`"
268 unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
269 var _i = arr == null ? null : typeof Symbol !== \\"undefined\\" && arr[Symbol.iterator] || arr[\\"@@iterator\\"];
270 throw new TypeError(\\"Invalid attempt to destructure non-iterable instance.\\\\\\\ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.\\");
271 if (n === \\"Arguments\\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
272 if (typeof Symbol !== \\"undefined\\" && iter[Symbol.iterator] != null || iter[\\"@@iterator\\"] != null) return Array.from(iter);
273 use: ['hehe', 'haha', 'rawr', expect.stringMatching(/react-refresh-utils[\\/]dist[\\/]loader\.js/), 'rr', 'lol', 'bla'],
274 expect(getOxfordCommaList(['1', '2', '3', '4', '5'])).toMatchInlineSnapshot(`"1, 2, 3, 4, and 5"`);
275 message: '`next/script` should not be used in `next/head` component. Move `<Script />` outside of `<Head>` instead. See: https://nextjs.org/docs/messages/no-script-component-in-head',
276 assert.equal(report.message, 'Do not use an `<a>` element to navigate to `/`. Use `<Link />` from `next/link` instead. See: https://nextjs.org/docs/messages/no-html-link-for-pages');
277 assert.equal(report.message, 'Do not use an `<a>` element to navigate to `/list/foo/bar/`. Use `<Link />` from `next/link` instead. See: https://nextjs.org/docs/messages/no-html-link-for-pages');
278 message: '`<Document />` from `next/document` should not be imported outside of `pages/_document.js`. See: https://nextjs.org/docs/messages/no-document-import-in-page',
279 message: 'Custom fonts not added in `pages/_document.js` will only load for a single page. This is discouraged. See: https://nextjs.org/docs/messages/no-page-custom-font',
280 message: 'Using `<link />` outside of `<Head>` will disable automatic font optimization. This is discouraged. See: https://nextjs.org/docs/messages/no-page-custom-font',
281 message: '`next/head` should not be imported in `pages/_document.js`. Use `<Head />` from `next/document` instead. See: https://nextjs.org/docs/messages/no-head-import-in-document',
282 message: '`next/head` should not be imported in `pages/_document.page.tsx`. Use `<Head />` from `next/document` instead. See: https://nextjs.org/docs/messages/no-head-import-in-document',
283 message: '`next/head` should not be imported in `pages/_document/index.js`. Use `<Head />` from `next/document` instead. See: https://nextjs.org/docs/messages/no-head-import-in-document',
284 message: '`next/head` should not be imported in `pages/_document/index.tsx`. Use `<Head />` from `next/document` instead. See: https://nextjs.org/docs/messages/no-head-import-in-document',
285 message: 'Do not use `<head>` element. Use `<Head />` from `next/head` instead. See: https://nextjs.org/docs/messages/no-head-element',
286 source: ' mutation UpdateName($name: String!) { updateName(name: $name) { id name status } } ',
287 ): typeof documents[' mutation UpdateName($name: String!) { updateName(name: $name) { id name status } } '];
288 source: ' query Viewer { viewer { id name status } } ',
289 ): typeof documents[' query Viewer { viewer { id name status } } '];
290 source: ' query GetAllPosts($first: Int!) { postCollection(first: $first) { edges { node { id title slug } } } } ',
291 ): typeof documents[' query GetAllPosts($first: Int!) { postCollection(first: $first) { edges { node { id title slug } } } } '];
292 source: ' query GetPostBySlug($slug: String!) { post(by: { slug: $slug }) { id title slug } } ',
293 ): typeof documents[' query GetPostBySlug($slug: String!) { post(by: { slug: $slug }) { id title slug } } '];
294 message: `Invalid page. '${slug}' was not found in the sitemap. Are you trying to preview a Dynamic Page Item? If so, ensure you have your List Preview Page, Item Preview Page, and Item Preview Query String Parameter set (contentid) .`,
295 function useMqtt({ uri, options = {}, topicHandlers = [{ topic: '', handler: ({ topic, payload, packet }) => {} }], onConnectedHandler = (client) => {} }: useMqttProps) {
296 const re = /^(([()[\]\\.,;:\s@"]+(\.[()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
297 const features = (await redis.hvals('features')).map((entry) => JSON.parse(entry)).sort((a, b) => b.score - a.score);
298 export const pathToSearchState = (path: string) => (path.includes('?') ? qs.parse(path.substring(path.indexOf('?') + 1)) : {});
299 const fetchedResults = await cloudinary.v2.search.expression(`folder:${process.env.CLOUDINARY_FOLDER}/*`).sort_by('public_id', 'desc').max_results(400).execute();
300 const response = await fetch(`https://res.cloudinary.com/${process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME}/image/upload/f_jpg,w_8,q_70/${image.public_id}.${image.format}`);
301 const pathnameIsMissingLocale = i18n.locales.every((locale) => !pathname.startsWith(`/${locale}/`) && pathname !== `/${locale}`);
302 const formatValues = (values: string[]) => values.map((val) => `\`${val}\``).join(', ');
303 let { weight, style, preload = true, display = 'swap', axes, fallback, adjustFontFallback = true, variable, subsets: callSubsets } = data[0] || ({} as any);
304 weight: '400' | '500' | '600' | '700' | '800' | Array<'400' | '500' | '600' | '700' | '800'>;
305 weight?: '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | 'variable' | Array<'100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'>;
306 weight?: '300' | '400' | '500' | '600' | '700' | 'variable' | Array<'300' | '400' | '500' | '600' | '700'>;
307 weight?: '400' | '500' | '600' | '700' | '800' | '900' | 'variable' | Array<'400' | '500' | '600' | '700' | '800' | '900'>;
308 subsets?: Array<'cyrillic' | 'cyrillic-ext' | 'greek' | 'greek-ext' | 'latin' | 'latin-ext' | 'vietnamese'>;
309 weight: '400' | '500' | '700' | '800' | '900' | Array<'400' | '500' | '700' | '800' | '900'>;
310 weight: '100' | '300' | '400' | '500' | '700' | '800' | '900' | Array<'100' | '300' | '400' | '500' | '700' | '800' | '900'>;
311 weight?: '400' | '500' | '600' | '700' | '800' | 'variable' | Array<'400' | '500' | '600' | '700' | '800'>;
312 weight?: '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | 'variable' | Array<'100' | '200' | '300' | '400' | '500' | '600' | '700' | '800'>;
313 weight?: '100' | '200' | '300' | '400' | '500' | '600' | '700' | 'variable' | Array<'100' | '200' | '300' | '400' | '500' | '600' | '700'>;
314 weight?: '400' | '500' | '600' | '700' | 'variable' | Array<'400' | '500' | '600' | '700'>;
315 subsets?: Array<'greek' | 'greek-ext' | 'latin' | 'latin-ext' | 'malayalam' | 'tamil' | 'vietnamese'>;
316 weight: '100' | '200' | '300' | '400' | '500' | '700' | '800' | '900' | Array<'100' | '200' | '300' | '400' | '500' | '700' | '800' | '900'>;
317 subsets?: Array<'cyrillic' | 'cyrillic-ext' | 'greek' | 'greek-ext' | 'hebrew' | 'latin' | 'latin-ext' | 'vietnamese'>;
318 weight: '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | Array<'200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'>;
319 weight?: '200' | '300' | '400' | '500' | '600' | '700' | '800' | 'variable' | Array<'200' | '300' | '400' | '500' | '600' | '700' | '800'>;
320 weight: '200' | '300' | '400' | '500' | '600' | '700' | Array<'200' | '300' | '400' | '500' | '600' | '700'>;
321 weight: '300' | '400' | '500' | '600' | '700' | Array<'300' | '400' | '500' | '600' | '700'>;
322 weight: '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | Array<'100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'>;
323 weight: '100' | '300' | '400' | '700' | '900' | Array<'100' | '300' | '400' | '700' | '900'>;
324 weight: '200' | '300' | '400' | '700' | '800' | Array<'200' | '300' | '400' | '700' | '800'>;
325 weight: '200' | '300' | '400' | '600' | '700' | '800' | '900' | Array<'200' | '300' | '400' | '600' | '700' | '800' | '900'>;
326 weight: '100' | '200' | '300' | '400' | '600' | '700' | '800' | '900' | Array<'100' | '200' | '300' | '400' | '600' | '700' | '800' | '900'>;
327 subsets?: Array<'cyrillic' | 'cyrillic-ext' | 'greek' | 'hebrew' | 'latin' | 'latin-ext' | 'vietnamese'>;
328 weight?: '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | '1000' | 'variable' | Array<'200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | '1000'>;
329 weight: '100' | '300' | '400' | '700' | '800' | Array<'100' | '300' | '400' | '700' | '800'>;
330 weight?: '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | 'variable' | Array<'200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'>;
331 weight: '300' | '400' | '500' | '600' | '700' | '800' | '900' | Array<'300' | '400' | '500' | '600' | '700' | '800' | '900'>;
332 weight?: '300' | '400' | '500' | '600' | '700' | '800' | 'variable' | Array<'300' | '400' | '500' | '600' | '700' | '800'>;
333 weight?: '300' | '400' | '500' | '600' | '700' | '800' | '900' | 'variable' | Array<'300' | '400' | '500' | '600' | '700' | '800' | '900'>;
334 weight?: '1' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | 'variable' | Array<'1' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900'>;
335 weight: '100' | '200' | '300' | '400' | '500' | '600' | '700' | Array<'100' | '200' | '300' | '400' | '500' | '600' | '700'>;
336 subsets?: Array<'cyrillic' | 'cyrillic-ext' | 'greek' | 'greek-ext' | 'kayah-li' | 'latin' | 'latin-ext' | 'vietnamese'>;
337 weight: '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | Array<'100' | '200' | '300' | '400' | '500' | '600' | '700' | '800'>;
338 weight: '300' | '400' | '600' | '700' | '800' | Array<'300' | '400' | '600' | '700' | '800'>;
339 weight: '200' | '300' | '400' | '600' | '700' | Array<'200' | '300' | '400' | '600' | '700'>;
340 weight: '200' | '300' | '400' | '500' | '600' | '700' | '800' | Array<'200' | '300' | '400' | '500' | '600' | '700' | '800'>;
341 weight: '100' | '200' | '300' | '400' | '500' | '600' | '700' | '900' | Array<'100' | '200' | '300' | '400' | '500' | '600' | '700' | '900'>;
342 weight: '200' | '300' | '400' | '500' | '600' | '700' | '900' | Array<'200' | '300' | '400' | '500' | '600' | '700' | '900'>;
343 subsets?: Array<'cyrillic' | 'cyrillic-ext' | 'devanagari' | 'greek' | 'greek-ext' | 'latin' | 'latin-ext' | 'vietnamese'>;
344 weight: '100' | '300' | '400' | '500' | '700' | '900' | Array<'100' | '300' | '400' | '500' | '700' | '900'>;
345 subsets?: Array<'cyrillic' | 'cyrillic-ext' | 'greek' | 'latin' | 'latin-ext' | 'tamil' | 'vietnamese'>;
346 weight?: '200' | '300' | '400' | '500' | '600' | '700' | 'variable' | Array<'200' | '300' | '400' | '500' | '600' | '700'>;
347 weight?: '300' | '400' | '500' | '600' | '700' | '800' | '900' | '1000' | 'variable' | Array<'300' | '400' | '500' | '600' | '700' | '800' | '900' | '1000'>;
348 weight?: '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | '1000' | 'variable' | Array<'100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | '1000'>;
349 axes?: ('GRAD' | 'XTRA' | 'YOPQ' | 'YTAS' | 'YTDE' | 'YTFI' | 'YTLC' | 'YTUC' | 'opsz' | 'slnt' | 'wdth')[];
350 weight: '400' | '500' | '600' | '700' | '800' | '900' | Array<'400' | '500' | '600' | '700' | '800' | '900'>;
351 | Array<'1' | '100' | '200' | '300' | '400' | '500' | '600' | '700' | '800' | '900' | '1000'>;
352 weight: '300' | '400' | '500' | '700' | '800' | Array<'300' | '400' | '500' | '700' | '800'>;
353 weight: '200' | '300' | '400' | '600' | '700' | '900' | Array<'200' | '300' | '400' | '600' | '700' | '900'>;
354 weight: '200' | '300' | '400' | '500' | '700' | '800' | '900' | Array<'200' | '300' | '400' | '500' | '700' | '800' | '900'>;
355 weight: '200' | '300' | '400' | '500' | '700' | '800' | Array<'200' | '300' | '400' | '500' | '700' | '800'>;
356 weight: '300' | '400' | '500' | '700' | '900' | Array<'300' | '400' | '500' | '700' | '900'>;
357 weight: '400' | '500' | '600' | '700' | '900' | Array<'400' | '500' | '600' | '700' | '900'>;
358 let { src, display = 'swap', weight, style, fallback, preload = true, variable, adjustFontFallback, declarations } = fontData || ({} as any);
359 element.innerHTML = '<map name="image-map-tabindex-test">' + '<area shape="rect" coords="63,19,144,45"></map>' + '<img usemap="#image-map-tabindex-test" tabindex="-1" alt="" src="' + gif + '">';
360 element.innerHTML = '<map name="image-map-area-href-test">' + '<area shape="rect" coords="63,19,144,45"></map>' + '<img usemap="#image-map-area-href-test" alt="" src="' + gif + '">';
361 element.innerHTML = '<map name="broken-image-map-test"><area href="#void" shape="rect" coords="63,19,144,45"></map>' + '<img usemap="#broken-image-map-test" alt="" src="' + invalidGif + '">';
362 return (_document.activeElement === focusable && 'focusable') || (_document.activeElement === tabbable && 'tabbable') || '';
363 return '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' + element + '</svg>';
364 element.innerHTML = generate(['<g id="ally-test-target"><a xlink:href="#void"><text>link</text></a></g>', '<use xlink:href="#ally-test-target" x="0" y="0" tabindex="-1" />'].join(''));
365 if (nodeName === 'input' || nodeName === 'select' || nodeName === 'button' || nodeName === 'textarea') {
366 if (!supports$2.focusBrokenImageMap && (!img.complete || !img.naturalHeight || img.offsetWidth <= 0 || img.offsetHeight <= 0)) {
367 var isFixedBlink = (platform.name === 'Chrome' && platform.majorVersion >= 54) || (platform.name === 'Opera' && platform.majorVersion >= 41);
368 (nodeName === 'input' && element.type === 'text') || element.type === 'password' || nodeName === 'select' || nodeName === 'textarea' || element.hasAttribute('contenteditable');
369 p = child_process.spawn('osascript', ['-e', `tell application "Terminal" to do script "${shellQuote.quote([editor, ...args])}"`], { stdio: 'ignore' });
370 if (!((frame.file?.startsWith('webpack-internal:///') || frame.file?.startsWith('file://')) && Boolean(parseInt(frame.lineNumber?.toString() ?? '', 10)))) {
371 const modulePath = frame.file.replace(/^(webpack-internal:\/\/\/|file:\/\/)(\(.*\)\/)?/, '');
372 const indexTransformRes = await runJscodeshift(indexTransformPath, { ...this.jscodeShiftFlags, silent: true, verbose: 0 }, [path.join(this.appDir, 'src', this.indexPage)]);
373 if (element.tagName === 'title' || (element.tagName === 'meta' && element.attribs.name === 'viewport')) {
374 serializedAttrs += ` dangerouslySetInnerHTML={{ __html: \`${gatherTextChildren(element.children).replace(/`/g, '\\`')}\` }}`;
375 serializedHeadTags.push(hasChildren ? `<${element.tagName}${serializedAttrs}>${gatherTextChildren(element.children)}</${element.tagName}>` : `<${element.tagName}${serializedAttrs} />`);
376 .filter((el) => el.value.openingElement.name && el.value.openingElement.name.type === 'JSXIdentifier' && el.value.openingElement.name.name === tagName)
377 if (images.type === 'ObjectProperty' && images.key.type === 'Identifier' && images.key.name === 'images' && images.value.type === 'ObjectExpression' && images.value.properties) {
378 if (p.type === 'ObjectProperty' && p.key.type === 'Identifier' && p.key.name === 'loader' && 'value' in p.value) {
379 if (p.value.value === 'imgix' || p.value.value === 'cloudinary' || p.value.value === 'akamai') {
380 if (p.type === 'ObjectProperty' && p.key.type === 'Identifier' && p.key.name === 'path' && 'value' in p.value) {
381 const isConfig = parsed.base === 'next.config.js' || parsed.base === 'next.config.ts' || parsed.base === 'next.config.mjs' || parsed.base === 'next.config.cjs';
382 const val = value.replace(/[-_\s.]+(.)?/g, (_match, chr) => (chr ? chr.toUpperCase() : ''));
383 if (defaultReactDomImport && node.callee.type === 'MemberExpression' && (node.callee.object as any).name === defaultReactDomImport && (node.callee.property as any).name === 'render') {
384 export function execOnce<TArgs extends any[], TResult extends unknown>(fn: (...args: TArgs) => TResult): (...args: TArgs) => TResult {
385 message: `\`next/head\` should not be imported in \`pages${document}\`. Use <Head /> from \`next/document\` instead. See: ${url}`,
386 message: `No duplicate polyfills from Polyfill.io are allowed. ${unwantedFeatures.join(', ')} ${unwantedFeatures.length > 1 ? 'are' : 'is'} already shipped with Next.js. See: ${url}`,
387 (child) => child.openingElement && child.openingElement.name && child.openingElement.name.type === 'JSXIdentifier' && child.openingElement.name.name === 'title',
388 message: `Do not use <title> element with <Head /> component from \`next/document\`. Titles should defined at the page-level using <Head /> from \`next/head\` instead. See: ${url}`,
389 attributes.find((attr) => attr.name.name === 'href' && attr.value.type === 'Literal' && !/^https?/.test(attr.value.value))
390 const isInAppDir = () => (paths.includes(`app${path.sep}`) || paths.includes(`app${path.posix.sep}`)) && !paths.includes(`pages${path.sep}`) && !paths.includes(`pages${path.posix.sep}`);
391 message: `Do not use <head> element. Use <Head /> from \`next/head\` instead. See: ${url}`,
392 if (node.declaration.type === 'ClassDeclaration' && node.declaration.superClass && 'name' in node.declaration.superClass && node.declaration.superClass.name === documentImportName) {
393 return ancestor.type === exportDeclarationType && 'superClass' in ancestor && ancestor.superClass && 'name' in ancestor.superClass && ancestor.superClass.name === documentImportName;
394 message: `<Document /> from \`next/document\` should not be imported outside of \`pages/_document.js\`. See: ${url}`,
395 message: `Using <img> could result in slower LCP and higher bandwidth. Use <Image /> from \`next/image\` instead to utilize Image Optimization. See: ${url}`,
396 console.warn(`Pages directory cannot be found at ${pagesDirs.join(' or ')}. ` + 'If using a custom path, please configure with the `no-html-link-for-pages` rule in your eslint config file.');
397 const pagesDirs = (customPagesDirectory ? [customPagesDirectory] : rootDirs.map((dir) => [path.join(dir, 'pages'), path.join(dir, 'src', 'pages')])).flat();
398 message: `Do not use an <a> element to navigate to \`${hrefPath}\`. Use <Link /> from \`next/link\` instead. See: ${url}`,
399 (ancestorNode) => ancestorNode.type === 'ClassDeclaration' && ancestorNode.superClass && 'name' in ancestorNode.superClass && ancestorNode.superClass.name === documentImportName,
400 if (!(name.startsWith('_document') || (dir === '/_document' && name === 'index'))) {
401 if (node.name.name === 'style' && node.attributes.find((attr) => attr.type === 'JSXAttribute' && attr.name.name === 'jsx')) {
402 message: `\`next/script\` should not be used in \`next/head\` component. Move <Script /> outside of <Head> instead. See: ${url}`,
403 validate: (value) => (/.+\/\*/.test(value) ? true : 'Import alias must follow the pattern <prefix>/*'),
404 const updateMessage = packageManager === 'yarn' ? 'yarn global add create-next-app' : packageManager === 'pnpm' ? 'pnpm add -g create-next-app' : 'npm i -g create-next-app';
405 console.log(chalk.yellow.bold('A new version of `create-next-app` is available!') + ' ' + 'You can update by running: ' + chalk.cyan(updateMessage) + ' ');
406 (await fs.promises.readFile(tsconfigFile, 'utf8')).replace(`"@/*": ["./*"]`, srcDir ? `"@/*": ["./src/*"]` : `"@/*": ["./*"]`).replace(`"@/*":`, `"${importAlias}":`),
407 await fs.promises.writeFile(filePath, (await fs.promises.readFile(filePath, 'utf8')).replace(`@/`, `${importAlias.replace(/\*/g, '')}`));
408 const indexPageFile = path.join('src', template === 'app' ? 'app' : 'pages', `${template === 'app' ? 'page' : 'index'}.${mode === 'ts' ? 'tsx' : 'js'}`);
409 (await fs.promises.readFile(indexPageFile, 'utf8')).replace(template === 'app' ? 'app/page' : 'pages/index', template === 'app' ? 'src/app/page' : 'src/pages/index'),
410 const dependencies = ['react', 'react-dom', `next${process.env.NEXT_PRIVATE_TEST_VERSION ? `@${process.env.NEXT_PRIVATE_TEST_VERSION}` : ''}`];
411 const branch = examplePath ? `${_branch}/${file.join('/')}`.replace(new RegExp(`/${filePath}|/$`), '') : _branch;
412 filter: (p) => p.startsWith(`${name}-${branch.replace(/\//g, '-')}${filePath ? `/${filePath}/` : '/'}`),
413 return typeof err === 'object' && err !== null && typeof (err as { message?: unknown }).message === 'string';
414 type ModuleHotStatus = 'idle' | 'check' | 'prepare' | 'ready' | 'dispose' | 'apply' | 'abort' | 'fail';
415 export type FileSizeSuffix = `${'k' | 'K' | 'm' | 'M' | 'g' | 'G' | 't' | 'T' | 'p' | 'P'}${'b' | 'B'}`;
416 export type GetStaticPropsResult<Props> = { props: Props; revalidate?: number | boolean } | { redirect: Redirect; revalidate?: number | boolean } | { notFound: true; revalidate?: number | boolean };
417 export type GetStaticProps<Props extends { [key: string]: any } = { [key: string]: any }, Params extends ParsedUrlQuery = ParsedUrlQuery, Preview extends PreviewData = PreviewData> = (
418 export type GetServerSideProps<Props extends { [key: string]: any } = { [key: string]: any }, Params extends ParsedUrlQuery = ParsedUrlQuery, Preview extends PreviewData = PreviewData> = (
419 getRandomValues<T extends Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | null>(array: T): T;
420 [K in keyof T]: T[K] extends string ? never : T[K] extends Handler ? ReturnType<T[K]> : T[K] extends [Handler] ? Array<ReturnType<T[K][0]>> : never;
421 expect(getWordsAndWhitespaces(text)).toEqual([' ', 'hello', ' ', 'world', ' ', 'https://nextjs.org/', ' ', 'https://nextjs.org/']);
422 const modulePath = webpackFile?.replace(/^(webpack-internal:\/\/\/|file:\/\/)(\(.*\)\/)?/, '');
423 return typeof error?.digest === 'string' && error.digest.startsWith(REDIRECT_ERROR_CODE + ';') && error.digest.length > REDIRECT_ERROR_CODE.length + 1;
424 return mod.indexOf(`pages${curPage.startsWith('/') ? curPage : `/${curPage}`}`) !== -1 || mod.indexOf(`pages${curPage.startsWith('/') ? curPage : `/${curPage}`}`.replace(/\//g, '\\')) !== -1;
425 const pathname = (Router.pathname === '/404' || Router.pathname === '/_error') && notFoundSrcPage ? notFoundSrcPage : Router.pathname;
426 const stackTrace = err && ((err.stack && err.stack.split(' ').slice(0, 5).join(' ')) || err.message || err + '');
427 ? (importTraceNote || ' Import trace for requested module:') + filteredModuleTrace.map((trace: any) => ` ${trace.moduleName}`).join('')
428 message = message.replace(/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?) /g, `${friendlySyntaxErrorLabel} $3 ($1:$2) `);
429 message = message.replace(/^.*export '(.+?)' was not found in '(.+?)'.*$/gm, `Attempted import error: '$1' is not exported from '$2'.`);
430 message = message.replace(/^.*export 'default' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, `Attempted import error: '$2' does not contain a default export (imported as '$1').`);
431 message = message.replace(/^.*export '(.+?)' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, `Attempted import error: '$1' is not exported from '$3' (imported as '$2').`);
432 lines = [lines[0], lines[1].replace('Error: ', '').replace('Module not found: Cannot find file:', 'Cannot find file:'), ...lines.slice(2)];
433 message = message.replace(/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*( |$)/gm, ''); // at ... ...:x:y
434 lines = (lines as string[]).filter((line, index, arr) => index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim());
435 const isHydrateError = args.some((arg) => typeof arg === 'string' && arg.match(/(hydration|content does not match|did not match)/i));
436 return locale && (pathLower.startsWith(`/${localeLower}/`) || pathLower === `/${localeLower}`) ? `${pathname.length === locale.length + 1 ? `/` : ``}${path.slice(locale.length + 1)}` : path;
437 speed: 'connection' in navigator && (navigator as any)['connection'] && 'effectiveType' in (navigator as any)['connection'] ? ((navigator as any)['connection']['effectiveType'] as string) : '',
438 if (type === 'script' && (attr === 'async' || attr === 'defer' || attr === 'noModule')) {
439 const feComponentTransfer = blurDataURL.startsWith('data:image/jpeg') ? `%3CfeComponentTransfer%3E%3CfeFuncA type='discrete' tableValues='1 1'/%3E%3C/feComponentTransfer%3E%` : '';
440 return `%3Csvg xmlns='http%3A//www.w3.org/2000/svg' viewBox='0 0 ${svgWidth} ${svgHeight}'%3E%3Cfilter id='b' color-interpolation-filters='sRGB'%3E%3CfeGaussianBlur stdDeviation='${std}'/%3E${feComponentTransfer}%3C/filter%3E%3Cimage preserveAspectRatio='none' filter='url(%23b)' x='0' y='0' height='100%25' width='100%25' href='${blurDataURL}'/%3E%3C/svg%3E`;
441 return `%3Csvg xmlns='http%3A//www.w3.org/2000/svg'%3E%3Cimage style='filter:blur(20px)' preserveAspectRatio='${preserveAspectRatio}' x='0' y='0' height='100%25' width='100%25' href='${blurDataURL}'/%3E%3C/svg%3E`;
442 return segment.replace(new RegExp(`([/#?]${escapeEncoded ? '|%(2f|23|3f)' : ''})`, 'gi'), (char: string) => encodeURIComponent(char));
443 params[slugName] = ~m.indexOf('/') ? m.split('/').map((entry) => decode(entry)) : g.repeat ? [decode(m)] : decode(m);
444 pathname = addPathSuffix(addPathPrefix(pathname, `/_next/data/${info.buildId}`), info.pathname === '/' ? 'index.json' : '.json');
445 if (locale && locale !== defaultLocale && (ignorePrefix || (!pathHasPrefix(path.toLowerCase(), `/${locale.toLowerCase()}`) && !pathHasPrefix(path.toLowerCase(), '/api')))) {
446 const routes = childrenPaths.map((c) => this.children.get(c)!._smoosh(`${prefix}${c}/`)).reduce((prev, curr) => [...prev, ...curr], []);
447 throw new Error(`You cannot define a route with the same specificity as a optional catch-all route ("${r}" and "${r}[[...${this.optionalRestSlugName}]]").`);
448 routes.push(...this.children.get('[[...]]')!._smoosh(`${prefix}[[...${this.optionalRestSlugName}]]/`));
449 throw new Error(`You cannot use both an required and optional catch-all route at the same level ("[...${this.restSlugName}]" and "${urlPaths[0]}" ).`);
450 throw new Error(`You cannot use both an optional and required catch-all route at the same level ("[[...${this.optionalRestSlugName}]]" and "${urlPaths[0]}").`);
451 const path = route === '/' ? '/index' : /^\/index(\/|$)/.test(route) ? `/index${route}` : `${route}`;
452 if (typeof param === 'string' || (typeof param === 'number' && !isNaN(param)) || typeof param === 'boolean') {
453 export function matchHas(req: BaseNextRequest | IncomingMessage, query: Params, has: RouteHas[] = [], missing: RouteHas[] = []): false | Params {
454 throw new Error(`To use a multi-match in the destination you must add \`*\` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match`);
455 const resolvedBase = base ? new URL(base, globalBase) : url.startsWith('.') ? new URL(typeof window === 'undefined' ? 'http://n' : window.location.href) : globalBase;
456 return repeat ? (optional ? `(?:/(?<${cleanedKey}>.+?))?` : `/(?<${cleanedKey}>.+?)`) : `/(?<${cleanedKey}>[^/]+?)`;
457 export const urlObjectKeys = ['auth', 'hash', 'host', 'hostname', 'href', 'path', 'pathname', 'port', 'protocol', 'query', 'search', 'slashes'];
458 console.error(`Invalid href '${urlAsString}' passed to next/router in page: '${router.pathname}'. Repeated forward-slashes (//) or backslashes \\ are not valid in the href.`);
459 export type HistoryState = null | { __NA: true; __N?: false } | { __N: false; __NA?: false } | ({ __NA?: false; __N: true; key: string } & NextHistoryState);
460 if (matchedPath && !rewriteTarget && !matchedPath.includes('__next_data_catchall') && !matchedPath.includes('/_error') && !matchedPath.includes('/404')) {
461 export type NextRouter = BaseRouter & Pick<Router, 'push' | 'replace' | 'reload' | 'back' | 'forward' | 'prefetch' | 'beforePopState' | 'events' | 'isFallback' | 'isReady' | 'isPreview'>;
462 headers: Object.assign({} as HeadersInit, isPrefetch ? { purpose: 'prefetch' } : {}, isPrefetch && hasMiddleware ? { 'x-middleware-prefetch': '1' } : {}),
463 if (!persistCache || process.env.NODE_ENV !== 'production' || data.response.headers.get('x-middleware-cache') === 'no-cache') {
464 throw new Error(`Invalid href: "${url}" and as: "${as}", received relative href and external as` + ` See more info: https://nextjs.org/docs/messages/invalid-relative-url-external-as`);
465 ? `The provided \`href\` (${url}) value is missing query values (${missingParams.join(', ')}) to be interpolated properly. `
466 if (isQueryUpdating && this.pathname === '/_error' && self.__NEXT_DATA__.props?.pageProps?.statusCode === 500 && routeInfo.props?.pageProps) {
467 if (this.pathname === '/_error' && self.__NEXT_DATA__.props?.pageProps?.statusCode === 500 && routeInfo.props?.pageProps) {
468 const rewritesResult = resolveRewrites(addBasePath(addLocale(asPath, this.locale), true), pages, rewrites, parsed.query, (p: string) => resolveDynamicRoute(p, pages), this.locales);
469 export async function loadGetInitialProps<C extends BaseContext, IP = {}, P = {}>(App: NextComponentType<C, IP, P>, ctx: C): Promise<IP> {
470 export const ST = SP && (['mark', 'measure', 'getEntriesByName'] as const).every((method) => typeof performance[method] === 'function');
471 5_016_456_510_113_118_655_434_598_811_035_278_955_030_765_345_404_790_744_303_017_523_831_112_055_108_147_451_509_157_692_220_295_382_716_162_651_878_526_895_249_385_292_291_816_524_375_083_746_691_371_804_094_271_873_160_484_737_966_720_260_389_217_684_476_157_468_082_573,
472 9_659_303_129_496_669_498_009_435_400_716_310_466_090_418_745_672_637_896_108_374_329_434_462_657_994_582_932_197_716_438_449_813_051_892_206_539_805_784_495_328_239_340_083_876_191_928_701_583_869_517_785,
473 14_197_795_064_947_621_068_722_070_641_403_218_320_880_622_795_441_933_960_878_474_914_617_582_723_252_296_732_303_717_722_150_864_096_521_202_355_549_365_628_174_669_108_571_814_760_471_015_076_148_029_755_969_804_077_320_157_692_458_563_003_215_304_957_150_157_403_644_460_363_550_505_412_711_285_966_361_610_267_868_082_893_823_963_790_439_336_411_086_884_584_107_735_010_676_915,
474 if (hostname === domainHostname || detectedLocale === item.defaultLocale.toLowerCase() || item.locales?.some((locale) => locale.toLowerCase() === detectedLocale)) {
475 const normalized = ensureLeadingSlash(/^\/index(\/|$)/.test(page) && !isDynamicRoute(page) ? `/index${page}` : page === '/' ? '/index' : page);
476 return _page.startsWith('/index/') && !isDynamicRoute(_page) ? _page.slice(6) : _page !== '/index' ? _page : '/';
477 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
478 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
479 export function getHostname(parsed: { hostname?: string | null }, headers?: { [key: string]: string | string[] | undefined }) {
480 throw new Error(`Failed to parse src "${src}" on \`next/image\`, protocol-relative URL (//) must be changed to an absolute URL (http:// or https://)`);
481 throw new Error(`Failed to parse src "${src}" on \`next/image\`, if using relative image it must start with a leading slash "/" or be an absolute URL (http:// or https://)`);
482 return build(dir, args['--profile'], args['--debug'] || process.env.NEXT_DEBUG_BUILD, !args['--no-lint'], args['--no-mangling'], args['--experimental-app-only']).catch((err) => {
483 if (isError(err) && (err.code === 'INVALID_RESOLVE_ALIAS' || err.code === 'WEBPACK_ERRORS' || err.code === 'BUILD_OPTIMIZATION_FAILED' || err.code === 'EDGE_RUNTIME_UNSUPPORTED_API')) {
484 const { getPackageVersion, getDependencies } = (await Promise.resolve(require('../lib/get-package-version'))) as typeof import('../lib/get-package-version');
485 const [sassVersion, nodeSassVersion] = await Promise.all([getPackageVersion({ cwd: dir, name: 'sass' }), getPackageVersion({ cwd: dir, name: 'node-sass' })]);
486 if (dependencies['@next/font'] || (devDependencies['@next/font'] && devDependencies['@next/font'] !== 'workspace:*')) {
487 let thankYouMsg = `Thank you for trying Next.js v13 with Turbopack! As a reminder, Turbopack is currently in alpha and not yet ready for production. We appreciate your ongoing support as we work to make it ready for everyone. `;
488 unsupportedParts += ` - Babel detected (${chalk.cyan(babelrc)}) ${chalk.dim(`Babel is not yet supported. To use Turbopack at the moment, you'll need to remove your usage of Babel.`)}`;
489 .join('')} To use Turbopack, remove the following configuration options: ${nonSupportedConfig.map((name) => ` - ${chalk.red(name)} `)}`,
490 ${chalk.bold.cyan(`${pkgManager === 'npm' ? 'npx create-next-app' : `${pkgManager} create next-app`} --example with-turbopack with-turbopack-app`)} cd with-turbopack-app ${pkgManager} run dev
491 const debugPortStr = process.execArgv.find((localArg) => localArg.startsWith('--inspect') || localArg.startsWith('--inspect-brk'))?.split('=')[1];
492 warn(`the --inspect${isDebuggingWithBrk ? '-brk' : ''} option was detected, the Next.js server should be inspected at port ${debugPort + 1}.`);
493 extensions: args['--ext'] ?? ['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx'],
494 -d, --dir Array Include directory, or directories, to run ESLint - default: 'pages', 'components', and 'lib'
495 --ext [String] Specify JavaScript file extensions - default: .js, .mjs, .cjs, .jsx, .ts, .mts, .cts, .tsx
496 --strict Creates an .eslintrc.json file using the Next.js strict configuration (only possible if no .eslintrc.json file is present)
497 const path = (parentPath ? parentPath + '/' : '') + (parallelRouteKey !== 'children' && !segment.startsWith('@') ? parallelRouteKey + '/' : '') + (segment === '' ? 'page' : segment);
498 async ensurePage({ page, clientOnly, appPaths = null, match }: { page: string; clientOnly: boolean; appPaths?: ReadonlyArray<string> | null; match?: RouteMatch }): Promise<void> {
499 staleness: 'fresh' | 'stale-patch' | 'stale-minor' | 'stale-major' | 'stale-prerelease' | 'newer-than-npm' | 'unknown';
500 .filter((line: string) => !/next[\\/]dist[\\/]compiled/.test(line) && !/node_modules[\\/]/.test(line) && !/node:internal[\\/]/.test(line))
501 import { PHASE_DEVELOPMENT_SERVER, CLIENT_STATIC_FILES_PATH, DEV_CLIENT_PAGES_MANIFEST, DEV_MIDDLEWARE_MANIFEST, COMPILER_NAMES, PAGES_MANIFEST, APP_PATHS_MANIFEST } from '../../shared/lib/constants';
502 const envFiles = ['.env.development.local', '.env.local', '.env.development', '.env'].map((file) => pathJoin(this.dir, file));
503 Log.error(`Conflicting app and page file${numConflicting === 1 ? ' was' : 's were'} found, please remove the conflicting files to continue:`);
504 async runEdgeFunction(params: { req: BaseNextRequest; res: BaseNextResponse; query: ParsedUrlQuery; params: Params | undefined; page: string; appPaths: string[] | null; isAppPath: boolean }) {
505 const frame = frames.find(({ file }) => !file?.startsWith('eval') && !file?.includes('web/adapter') && !file?.includes('sandbox/context') && !file?.includes('<anonymous>'))!;
506 Log[type === 'warning' ? 'warn' : 'error'](`${file} (${lineNumber}:${column}) @ ${methodName}`);
507 export async function renderScriptError(res: ServerResponse, error: Error, { verbose = true } = {}): Promise<{ finished: true | undefined }> {
508 .traceAsyncFn(() => Promise.all([findPageFile(this.pagesDir!, '/_app', pageExtensions, false), findPageFile(this.pagesDir!, '/_document', pageExtensions, false)]));
509 public async ensurePage({ page, clientOnly, appPaths, match }: { page: string; clientOnly: boolean; appPaths?: string[] | null; match?: RouteMatch }): Promise<void> {
510 [DocumentMod, AppMod] = await Promise.all([Promise.resolve().then(() => requirePage('/_document', distDir, false)), Promise.resolve().then(() => requirePage('/_app', distDir, false))]);
511 const keysToInclude: (keyof NextQueryMetadata)[] = ['__nextDefaultLocale', '__nextFallback', '__nextLocale', '__nextSsgPath', '_nextBubbleNoFallback', '__nextDataReq'];
512 controller.enqueue(encodeText(`<script>self.__next_root_layout_missing_tags_error=${JSON.stringify({ missingTags, assetPrefix: assetPrefix ?? '', tree: getTree() })}</script>`));
513 if (!('isNextDevCommand' in options) && process.env.NODE_ENV && !['production', 'development', 'test'].includes(process.env.NODE_ENV)) {
514 const { dir = '.', quiet = false, conf, dev = false, minimalMode = false, customServer = true, hostname, port } = options;
515 val = [...(middlewareValue || []), ...(typeof val === 'string' ? [val] : Array.isArray(val) ? val : [])];
516 parsedUrl.pathname = `${this.nextConfig.basePath || ''}${matchedPath === '/' && this.nextConfig.basePath ? '' : matchedPath}`;
517 if ((err && typeof err === 'object' && err.code === 'ERR_INVALID_URL') || err instanceof DecodeError || err instanceof NormalizeError) {
518 console.warn(`Cannot render page with path "${pathname}", did you mean "/${pathname}"?. See more info here: https://nextjs.org/docs/messages/render-no-starting-slash`);
519 if (!internalRender && !this.minimalMode && !query.__nextDataReq && (req.url?.match(/^\/_next\//) || (this.hasStaticDir && req.url!.match(/^\/static\//)))) {
520 let isDataReq = !!(query.__nextDataReq || (req.headers['x-nextjs-data'] && (this.serverOptions as any).webServerConfig)) && (isSSG || hasServerProps);
521 if (!is404Page && !is500Page && pathname !== '/_error' && req.method !== 'HEAD' && req.method !== 'GET' && (typeof components.Component === 'string' || isSSG)) {
522 : `${locale ? `/${locale}` : ''}${(pathname === '/' || resolvedUrlPathname === '/') && locale ? '' : resolvedUrlPathname}${query.amp ? '.amp' : ''}`;
523 ssgCacheKey = `${locale ? `/${locale}` : ''}${pathname}${query.amp ? '.amp' : ''}`;
524 throw new Error('invariant: Expected pageData to be a string for app data request but received ' + typeof cachedData.pageData + '. This is a bug in Next.js.');
525 if (this.router.catchAllMiddleware[0] && !!ctx.req.headers['x-nextjs-data'] && (!res.statusCode || res.statusCode === 200 || res.statusCode === 404)) {
526 public async renderError(err: Error | null, req: BaseNextRequest, res: BaseNextResponse, pathname: string, query: NextParsedUrlQuery = {}, setHeaders = true): Promise<void> {
527 private async renderErrorImpl(err: Error | null, req: BaseNextRequest, res: BaseNextResponse, pathname: string, query: NextParsedUrlQuery = {}, setHeaders = true): Promise<void> {
528 if (process.env.NODE_ENV !== 'production' && !using404Page && (await this.hasPage('/_error')) && !(await this.hasPage('/404'))) {
529 if ([0x52, 0x49, 0x46, 0x46, 0, 0, 0, 0, 0x57, 0x45, 0x42, 0x50].every((b, i) => !b || buffer[i] === b)) {
530 if ([0, 0, 0, 0, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66].every((b, i) => !b || buffer[i] === b)) {
531 const { deviceSizes = [], imageSizes = [], domains = [], minimumCacheTTL = 60, formats = ['image/webp'] } = imageData;
532 const { resBuffers, req: mockReq, res: mockRes, streamPromise: isStreamFinished } = mockRequest(href, _req.headers, _req.method || 'GET', _req.connection);
533 res.setHeader('Cache-Control', isStatic ? 'public, max-age=315360000, immutable' : `public, max-age=${isDev ? 0 : maxAge}, must-revalidate`);
534 !this.minimalMode && fs.existsSync(join(this.distDir, 'static')) ? recursiveReadDirSync(join(this.distDir, 'static')).map((f) => join('.', relative(this.dir, this.distDir), 'static', f)) : [];
535 paths.unshift(...paths.map((path) => `/${query.__nextLocale}${path === '/' ? '' : path}`));
536 public async renderErrorToHTML(err: Error | null, req: BaseNextRequest | IncomingMessage, res: BaseNextResponse | ServerResponse, pathname: string, query?: ParsedUrlQuery): Promise<string | null> {
537 protected generateRewrites({ restrictedRedirectPaths }: { restrictedRedirectPaths: string[] }): { beforeFiles: Route[]; afterFiles: Route[]; fallback: Route[] } {
538 url = `${getRequestMeta(params.request, '_protocol')}://${this.hostname}:${this.port}${locale ? `/${locale}` : ''}${params.parsed.pathname}${query ? `?${query}` : ''}`;
539 if (!result.response.headers.has('x-middleware-rewrite') && !result.response.headers.has('x-middleware-next') && !result.response.headers.has('Location')) {
540 const agent = ({ protocol }: any) => (protocol === 'http:' ? (global as any).__NEXT_HTTP_AGENT : (global as any).__NEXT_HTTPS_AGENT);
541 appDirRegExp = new RegExp('^' + (projectDir + '(/src)?/app').replace(/[\\/]/g, '[\\/]'));
542 const insertText = e.kind === ts.ScriptElementKind.memberVariableElement && /^[a-zA-Z0-9_]+$/.test(e.name) ? e.name + ': ' : e.name;
543 (ts.isNumericLiteral((value as any).operand.kind) || (ts.isIdentifier((value as any).operand.kind) && (value as any).operand.kind.getText() === 'Infinity'))) ||
544 export type PayloadOptions = { private: true } | { private: boolean; stateful: true } | { private: boolean; stateful: false; revalidate: number | false };
545 res.setHeader('Content-Type', resultContentType ? resultContentType : type === 'rsc' ? RSC_CONTENT_TYPE_HEADER : type === 'json' ? 'application/json' : 'text/html; charset=utf-8');
546 read: jest.fn(() => [...extensions.map((ext) => `${dir}/some/route.${ext}`), ...extensions.map((ext) => `${dir}/api/other.${ext}`), ...files]),
547 read: jest.fn(() => [...extensions.map((ext) => `${dir}/some/page.${ext}`), ...extensions.map((ext) => `${dir}/api/other.${ext}`), ...files]),
548 read: jest.fn(() => [...extensions.map((ext) => `${dir}/api/other/page.${ext}`), ...files]),
549 const results = await Promise.all([cached.read('<root>/pages'), cached.read('<root>/pages'), cached.read('<root>/app'), cached.read('<root>/app')]);
550 read: jest.fn(() => [...extensions.map((ext) => `${dir}/some/other/page.${ext}`), ...extensions.map((ext) => `${dir}/some/other/route.${ext}`), `${dir}/some/api/route.ts`, ...files]),
551 const body: BodyInit | null | undefined = req.method !== 'GET' && req.method !== 'HEAD' && req.body ? req.body : null;
552 Log.error(`Detected lowercase method '${invalidMethodName}' in '${resolvedPagePath}'. Export the uppercase '${invalidMethodName.toUpperCase()}' method name to fix this error.`);
553 throw new Error('NextResponse.next() was used in a app route handler, this is not supported. See here for more info: https://nextjs.org/docs/messages/next-response-next-in-app-route-handler');
554 Log.warn(`Duplicate page detected. ${matchers.map((matcher) => chalk.cyan(path.relative(this.dir, matcher.definition.filename))).join(' and ')} resolve to ${chalk.cyan(pathname)}`);
555 result = result.replace('</head>', `<style data-href="${url}"${nonceStr}${dataAttr}>${fontContent}</style></head>`);
556 const escapedUrl = url.replace(/&/g, '&amp;').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
557 export function getCustomRoute(params: { rule: Rewrite | Redirect | Header; type: RouteType; restrictedRedirectPaths: string[] }): (Route & Rewrite) | (Route & Header) | (Route & Rewrite) {
558 regexModifier: !(rule as any).internal ? (regex: string) => modifyRouteRegex(regex, type === 'redirect' ? restrictedRedirectPaths : undefined) : undefined,
559 const flush = typeof (res as any).flush === 'function' ? () => (res as any).flush() : () => {};
560 ...pick(input, ['method', 'body', 'cache', 'credentials', 'integrity', 'keepalive', 'mode', 'redirect', 'referrer', 'referrerPolicy', 'signal']),
561 throw new Error(`URL is malformed "${String(url)}". Please use only absolute URLs - https://nextjs.org/docs/messages/middleware-relative-urls`, { cause: error });
562 const REGEX_LOCALHOST_HOSTNAME = /(?!^https?:\/\/)(127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}|::1|localhost)/;
563 logLevel?: 'bug' | 'fatal' | 'error' | 'warning' | 'hint' | 'note' | 'suggestions' | 'info';
564 const key = Object.entries(supportedFormats).find(([, { detectors }]) => detectors.some((detector) => detector.exec(firstChunkString)))?.[0] as EncoderKey | undefined;
565 type ResizeOpts = { image: ImageData } & ({ width: number; height?: never } | { height: number; width?: never } | { height: number; width: number });
566 } & ({ width: number; height?: never } | { height: number; width?: never } | { width: number; height: number });
567 const requestInputFields = ['cache', 'credentials', 'headers', 'integrity', 'keepalive', 'method', 'mode', 'redirect', 'referrer', 'referrerPolicy', 'signal', 'window', 'duplex'];
568 const { encode } = require('../../shared/lib/bloom-filter/base64-arraybuffer') as typeof import('../../shared/lib/bloom-filter/base64-arraybuffer');
569 const { decode } = require('../../shared/lib/bloom-filter/base64-arraybuffer') as typeof import('../../shared/lib/bloom-filter/base64-arraybuffer');
570 warn(`Duplicate page detected. ${chalk.cyan(join('pages', existingPath))} and ${chalk.cyan(join('pages', others[0]))} both resolve to ${chalk.cyan(normalizedPagePath)}.`);
571 return new RegExp(`(^page|[\\\\/]page|^route|[\\\\/]route)\\.(?:${pageExtensions.join('|')})$`).test(filePath);
572 trace<T>(name: SpanNames, options: TracerSpanOptions, fn: (span: Span, done?: (error?: Error) => any) => Promise<T>): Promise<T>;
573 wrap<T = (...args: Array<any>) => any>(name: SpanNames, options: (...args: any[]) => TracerSpanOptions, fn: T): T;
574 public trace<T>(name: SpanNames, fn: (span: Span, done?: (error?: Error) => any) => Promise<T>): Promise<T>;
575 public trace<T>(name: SpanNames, options: TracerSpanOptions, fn: (span: Span, done?: (error?: Error) => any) => Promise<T>): Promise<T>;
576 public trace<T>(name: SpanNames, options: TracerSpanOptions, fn: (span: Span, done?: (error?: Error) => any) => T): T;
577 public wrap<T = (...args: Array<any>) => any>(name: SpanNames, options: (...args: any[]) => TracerSpanOptions, fn: T): T;
578 type SpanNames = `${BaseServerSpan}` | `${LoadComponentsSpan}` | `${NextServerSpan}` | `${StartServerSpan}` | `${NextNodeServerSpan}` | `${RenderSpan}` | `${RouterSpan}` | `${AppRenderSpan}`;
579 this.cacheEndpoint = `https://${ctx._requestHeaders['x-vercel-sc-host']}${ctx._requestHeaders['x-vercel-sc-basepath'] || ''}`;
580 lastModified: cacheState === 'stale' ? Date.now() + CACHE_ONE_YEAR : Date.now() - parseInt(age || '0', 10) * 1000,
581 const { getPathMatch } = require('../../shared/lib/router/utils/path-match') as typeof import('../../shared/lib/router/utils/path-match');
582 const { default: loadCustomRoutes } = require('../../lib/load-custom-routes') as typeof import('../../lib/load-custom-routes');
583 route.type === 'rewrite' || route.type === 'redirect' || route.type === 'header' || route.name === 'catchall route' || route.name === 'middleware catchall' || route.name?.includes('check');
584 Log.warn(`\`${oldKey}\` has been moved out of \`experimental\`` + (newKey.includes('.') ? ` and into \`${newKey}\`` : '') + `. Please update your ${configFileName} file accordingly.`);
585 throw new Error(`Specified pageExtensions is not an array of strings, found "${ext}" of type "${typeof ext}". Please update this config or remove it.`);
586 if ((images.loader !== 'default' && images.path[images.path.length - 1] !== '/') || result.trailingSlash) {
587 console.warn(`Both ${item.domain} and ${domainItem.domain} configured the locale (${locale}) but only one can. Remove it from one i18n.domains config to continue`);
588 .join(' ')} domains value must follow format { domain: 'example.fr', defaultLocale: 'fr', locales: ['fr'] }. See more info here: https://nextjs.org/docs/messages/invalid-i18n-config`,
589 throw new Error(`The "target" property is no longer supported in ${configFileName}. ` + 'See more info here https://nextjs.org/docs/messages/deprecated-target-config');
590 const nonJsPath = findUp.sync([`${configBaseName}.jsx`, `${configBaseName}.ts`, `${configBaseName}.tsx`, `${configBaseName}.json`], { cwd: dir });
591 const allowedRevalidateHeaderKeys = [...(context.allowedRevalidateHeaderKeys || []), ...(context.trustHostHeader ? ['cookie', 'x-vercel-protection-bypass'] : [])];
592 console.warn(`API response for ${req.url} exceeds ${bytes.format(maxContentLength)}. API Routes are meant to respond quickly. https://nextjs.org/docs/messages/api-routes-response-size-limit`);
593 throw new Error(`Invalid redirect arguments. Please use a single argument URL, e.g. res.redirect('/destination') or use a status code and URL, e.g. res.redirect(307, '/destination').`);
594 console.warn(`The module '${dependency}' was not found. Next.js requires that you include it in 'dependencies' of your 'package.json'. To add it, run 'npm install ${dependency}'`);
595 if (args['--inspect']) throw new Error(`--inspect flag is deprecated. Use env variable NODE_OPTIONS instead: NODE_OPTIONS='--inspect' next ${command}`);
596 const shouldWarnCommands = process.env.NODE_ENV === 'development' ? ['start', 'build'] : process.env.NODE_ENV === 'production' ? ['dev'] : [];
597 const reportToLocalHost = (name: string, duration: number, timestamp: number, id: number, parentId?: number, attrs?: Object, startTime?: number) => {
598 const result = webpackCloseSpan.traceChild('webpack-generate-error-stats').traceFn(() => generateStats({ errors: [], warnings: [], stats }, stats));
599 modules: (clientWasLoading ? client.modules : 0) + (serverWasLoading ? server.modules : 0) + (edgeServerWasLoading ? edgeServer?.modules || 0 : 0),
600 const warnings = [...(client.warnings || []), ...(server.warnings || []), ...(edgeServer.warnings || [])].concat(formatAmpMessages(amp) || []);
601 if (([...new Set([...Object.keys(lastStore), ...Object.keys(nextStore)])] as Array<keyof OutputState>).every((key) => Object.is(lastStore[key], nextStore[key]))) {
602 console.log(`AMP bind syntax [${prop}]='' is not supported in JSX, use 'data-amp-bind-${prop}' instead. https://nextjs.org/docs/messages/amp-bind-jsx-alt`);
603 warn(`Duplicate page detected. ${chalk.cyan(join('pages', previousPages[pageKey]))} and ${chalk.cyan(join('pages', pagePath))} both resolve to ${chalk.cyan(pageKey)}.`);
604 result[pageKey] = normalizePathSep(join(pagesType === 'pages' ? PAGES_DIR_ALIAS : pagesType === 'app' ? APP_DIR_ALIAS : ROOT_DIR_ALIAS, pagePath));
605 if (params.page === '/_app' || params.page === '/_error' || params.page === '/404' || params.page === '/500') {
606 const getEntryHandler = (mappings: Record<string, string>, pagesType: 'app' | 'pages' | 'root') => async (page: string) => {
607 const serverBundlePath = pagesType === 'pages' ? posix.join('pages', bundleFile) : pagesType === 'app' ? posix.join('app', bundleFile) : bundleFile.slice(1);
608 const isAppLayer = hasAppDir && (name === CLIENT_STATIC_FILES_RUNTIME_MAIN_APP || name === APP_CLIENT_INTERNALS || name.startsWith('app/'));
609 export async function generateBuildId(generate: () => string | null | Promise<string | null>, fallback: () => string): Promise<string> {
610 export default function createSpinner(text: string | { prefixText: string }, options: ora.Options = {}, logFn: (...data: any[]) => void = console.log) {
611 [...new Set<string>([...files.pages.each.keys(), ...(files.app?.each.keys() ?? [])])].map(async (f) => {
612 .filter((e) => !(e === '/_document' || e === '/_error' || (!hasCustomApp && e === '/_app')))
613 messages.push([routerType === 'app' ? 'Route (app)' : 'Route (pages)', 'Size', 'First Load JS'].map((entry) => chalk.underline(entry)) as [string, string, string]);
614 const totalDuration = (pageInfo?.pageDuration || 0) + (pageInfo?.ssgPageDurations?.reduce((a, b) => a + (b || 0), 0) || 0);
615 const uniqueCssFiles = buildManifest.pages[item]?.filter((file) => file.endsWith('.css') && stats.router[routerType]?.unique.files.includes(file)) || [];
616 messages.push([`${contSymbol} ${innerSymbol} ${getCleanName(file)}`, typeof size === 'number' ? prettyBytes(size) : '', '']);
617 messages.push([` ${innerSymbol} ${cleanName}`, typeof size === 'number' ? prettyBytes(size) : '', '']);
618 usedSymbols.has('ISR') && ['', '(ISR)', `incremental static regeneration (uses revalidate in ${chalk.cyan('getStaticProps')})`],
619 const printRoutes = (routes: Redirect[] | Rewrite[] | Header[], type: 'Redirects' | 'Rewrites' | 'Headers') => {
620 const expectedReturnVal = `Expected: { paths: [], fallback: boolean } ` + `See here for more info: https://nextjs.org/docs/messages/invalid-getstaticpaths-value`;
621 throw new Error(`Invalid \`paths\` value returned from getStaticPaths in ${page}. ` + `\`paths\` must be an array of strings or objects of shape { params: [key: string]: string }`);
622 if (optional && params.hasOwnProperty(validParamKey) && (paramValue === null || paramValue === undefined || (paramValue as any) === false)) {
623 throw new Error(`A required parameter (${validParamKey}) was not provided as ${repeat ? 'an array' : 'a string'} in ${appDir ? 'generateStaticParams' : 'getStaticPaths'} for ${page}`);
624 .replace(replaced, repeat ? (paramValue as string[]).map((segment) => escapePathDelimiters(segment, true)).join('/') : escapePathDelimiters(paramValue as string, true))
625 encodedBuiltPage = encodedBuiltPage.replace(replaced, repeat ? (paramValue as string[]).map(encodeURIComponent).join('/') : encodeURIComponent(paramValue as string)).replace(/(?!^)\/$/, '');
626 prerenderPaths.add(`${curLocale ? `/${curLocale}` : ''}${curLocale && builtPage === '/' ? '' : builtPage}`);
627 encodedPrerenderPaths.add(`${curLocale ? `/${curLocale}` : ''}${curLocale && encodedBuiltPage === '/' ? '' : encodedBuiltPage}`);
628 segmentPath: `/${parentSegments.join('/')}${segment[0] && parentSegments.length > 0 ? '/' : ''}${segment[0]}`,
629 throw new Error(`getStaticPaths can only be used with dynamic pages, not '${page}'.` + ` Learn more: https://nextjs.org/docs/routing/dynamic-routes`);
630 throw new Error(`getStaticPaths is required for dynamic SSG pages and is missing for '${page}'.` + ` Read more: https://nextjs.org/docs/messages/invalid-getstaticpaths-value`);
631 conflictingPathsOutput += `path: "${pathItem.path}"${isDynamic ? ` from page: "${pathItem.page}" ` : ' '}`;
632 files.push(path.join(folder, `${INSTRUMENTATION_HOOK_FILENAME}.${extension}`), path.join(folder, `src`, `${INSTRUMENTATION_HOOK_FILENAME}.${extension}`));
633 if (node.type === 'ExportDeclaration' && node.declaration?.type === 'FunctionDeclaration' && ['getStaticProps', 'getServerSideProps'].includes(node.declaration.identifier?.value)) {
634 const values = node.specifiers.map((specifier: any) => specifier.type === 'ExportSpecifier' && specifier.orig?.type === 'Identifier' && specifier.orig?.value);
635 source = `/:nextData(_next/data/[^/]{1,})?${source}${isRoot ? `(${nextConfig.i18n ? '|\\.json|' : ''}/?index|/?index\\.json)?` : '(.json)?'}`;
636 Log.warn(apiRoute ? `${apiRoute} provided runtime 'experimental-edge'. It can be updated to 'edge' instead.` : `You are using an experimental edge runtime, the API might change.`);
637 export async function getPageStaticInfo(params: { nextConfig: Partial<NextConfig>; pageFilePath: string; isDev?: boolean; page?: string; pageType?: 'pages' | 'app' }): Promise<PageStaticInfo> {
638 !appDirOnly && pagesDir ? await nextBuildSpan.traceChild('collect-pages').traceAsyncFn(() => recursiveReadDir(pagesDir, new RegExp(`\\.(?:${config.pageExtensions.join('|')})$`))) : [];
639 appPaths = await nextBuildSpan.traceChild('collect-app-paths').traceAsyncFn(() => recursiveReadDir(appDir, new RegExp(`^(page|route)\\.(?:${config.pageExtensions.join('|')})$`)));
640 Log.error(`Conflicting app and page file${numConflictingAppPaths === 1 ? ' was' : 's were'} found, please remove the conflicting files to continue:`);
641 ...(config.experimental.sri ? [path.join(SERVER_DIRECTORY, SUBRESOURCE_INTEGRITY_MANIFEST + '.js'), path.join(SERVER_DIRECTORY, SUBRESOURCE_INTEGRITY_MANIFEST + '.json')] : []),
642 ...(hasInstrumentationHook ? [path.join(SERVER_DIRECTORY, `${INSTRUMENTATION_HOOK_FILENAME}.js`), path.join(SERVER_DIRECTORY, `edge-${INSTRUMENTATION_HOOK_FILENAME}.js`)] : []),
643 .filter((f) => !f.includes('/node_modules/') && f.startsWith(turbotraceContextAppDir) && !entriesToTrace.includes(f) && !depModSet.has(f));
644 } else if (isDynamic && !hasGenerateStaticParams && (appConfig.dynamic === 'error' || appConfig.dynamic === 'force-static')) {
645 chalk.yellow(`You have opted-out of Automatic Static Optimization due to \`getInitialProps\` in \`pages/_app\`. This does not opt-out pages with \`getStaticProps\``),
646 const lockFiles: string[] = (await Promise.all(['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'].map((file) => findUp(file, { cwd: dir })))).filter(Boolean) as any; // TypeScript doesn't like this filter
647 for (const page of [...staticPages, ...ssgPages, ...(useStatic404 ? ['/404'] : []), ...(useDefaultStatic500 ? ['/500'] : [])]) {
648 dataRouteRegex: isRouteHandler ? null : normalizeRouteRegex(getNamedRouteRegex(dataRoute.replace(/\.rsc$/, '')).re.source.replace(/\(\?:\\\/\)\?\$$/, '\\.rsc$')),
649 const moveExportedPage = async (originPage: string, page: string, file: string, isSsg: boolean, ext: 'html' | 'json', additionalSsgFile = false) => {
650 dataRouteRegex: normalizeRouteRegex(getNamedRouteRegex(dataRoute.replace(/\.json$/, '')).re.source.replace(/\(\?:\\\/\)\?\$$/, '\\.json$')),
651 console.log(chalk.bold.green('Next.js Analytics') + ' is enabled for this production build. ' + "You'll receive a Real Experience Score computed by all of your visitors.");
652 t.program([t.variableDeclaration('const', [t.variableDeclarator(t.identifier(STRING_LITERAL_DROP_BUNDLE), t.stringLiteral(`${STRING_LITERAL_DROP_BUNDLE} ${Date.now()}`))])], []),
653 t.stringLiteral((state.file.opts.caller?.pagesDir ? relativePath(state.file.opts.caller.pagesDir, state.file.opts.filename) : state.file.opts.filename) + ' -> '),
654 const libs = state.opts.lib && (state.opts.lib === true ? ['react', 'preact/hooks'] : [].concat(state.opts.lib));
655 const nextDistPath = /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/;
656 const reactRefreshItem = hasReactRefresh ? createConfigItem([require('next/dist/compiled/react-refresh/babel'), { skipEnvCheck: true }], { type: 'plugin' }) : null;
657 const disallowExportAllItem = !isServer && isPageFile ? createConfigItem([require('../plugins/next-page-disallow-re-export-all-exports')], { type: 'plugin' }) : null;
658 const flags = 0 | (isServer ? 0b0001 : 0) | (isPageFile ? 0b0010 : 0) | (isNextDist ? 0b0100 : 0) | (hasModuleExports ? 0b1000 : 0);
659 const isBabelLoader = api.caller((caller: any) => !!caller && (caller.name === 'babel-loader' || caller.name === 'next-babel-turbo-loader'));
660 const useJsxRuntime = options['preset-react']?.runtime === 'automatic' || (Boolean(api.caller((caller: any) => !!caller && caller.hasJsxRuntime)) && options['preset-react']?.runtime !== 'classic');
661 if ((isServer || isTest) && (!presetEnvConfig.targets || !(typeof presetEnvConfig.targets === 'object' && 'node' in presetEnvConfig.targets))) {
662 [isTest && options['styled-jsx'] && options['styled-jsx']['babel-test'] ? require('styled-jsx/babel-test') : require('styled-jsx/babel'), styledJsxOptions(options['styled-jsx'])],
663 return `Images ${chalk.bold('cannot')} be imported within ${chalk.cyan('pages/_document.js')}. Please move image imports that need to be displayed on every page into ${chalk.cyan(
664 return `Global CSS ${chalk.bold('cannot')} be imported from within ${chalk.bold('node_modules')}. Read more: https://nextjs.org/docs/messages/css-npm`;
665 return `CSS Modules ${chalk.bold('cannot')} be imported from within ${chalk.bold('node_modules')}. Read more: https://nextjs.org/docs/messages/css-modules-npm`;
666 return `CSS ${chalk.bold('cannot')} be imported within ${chalk.cyan('pages/_document.js')}. Please move global styles to ${chalk.cyan('pages/_app.js')}.`;
667 const googleLoaderOptions = ctx.experimental?.fontLoaders?.find((loaderConfig) => loaderConfig.loader === '@next/font/google' || loaderConfig.loader === 'next/font/google')?.options ?? {};
668 use: [require.resolve('../../../loaders/next-flight-css-loader'), ...getCssModuleLoader({ ...ctx, isAppDir: true }, lazyPostCSSInitializer)],
669 use: [require.resolve('../../../loaders/next-flight-css-loader'), ...getCssModuleLoader({ ...ctx, isAppDir: true }, lazyPostCSSInitializer, sassPreprocessors)],
670 use: [require.resolve('../../../loaders/next-flight-css-loader'), ...getGlobalCssLoader({ ...ctx, isAppDir: true }, lazyPostCSSInitializer)],
671 use: [require.resolve('../../../loaders/next-flight-css-loader'), ...getGlobalCssLoader({ ...ctx, isAppDir: true }, lazyPostCSSInitializer, sassPreprocessors)],
672 exclude: [/\.(js|mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/, /\.webpack\[[^\]]+\]$/],
673 return `${chalk.red.bold('Error')}: Your PostCSS configuration for '${pluginName}' cannot have ${chalk.bold('null')} configuration. To disable '${pluginName}', pass ${chalk.bold(
674 const ignoredRegex = /(?:^|[\\/])(postcss-modules-values|postcss-modules-scope|postcss-modules-extract-imports|postcss-modules-local-by-default|postcss-modules)(?:[\\/]|$)/i;
675 throw new Error(`Your custom PostCSS configuration may not export a function. Please export a plain object instead. ` + 'Read more: https://nextjs.org/docs/messages/postcss-function');
676 console.warn(`${chalk.yellow.bold('Warning')}: Your PostCSS configuration defines a field which is not supported (\`${invalidKey}\`). ` + `Please remove this configuration value.`);
677 if (typeof pluginName === 'string' && (typeof pluginConfig === 'boolean' || typeof pluginConfig === 'object' || typeof pluginConfig === 'string')) {
678 console.error(`${chalk.red.bold('Error')}: An unknown PostCSS plugin was provided (${plugin}). ` + 'Read more: https://nextjs.org/docs/messages/postcss-shape');
679 files.push(...entryFiles.filter((file) => !file.endsWith('.hot-update.js')).map((file) => 'server/' + file));
680 ((memberExpression.property?.type === 'Literal' && memberExpression.property.value === 'env') || (memberExpression.property?.type === 'Identifier' && memberExpression.property.name === 'env'))
681 const pageFilePath = await new Promise((resolve) => resolver.resolve({}, '/', absolutePagePath, {}, (err, path) => resolve(err || path)));
682 const hasOGImageGeneration = resource && /[\\/]node_modules[\\/]@vercel[\\/]og[\\/]dist[\\/]index.js$/.test(resource);
683 export async function handleWebpackExternalForEdgeRuntime({ request, context, contextInfo, getResolve }: { request: string; context: string; contextInfo: any; getResolve: () => any }) {
684 const files = entrypoint.getFiles().filter((file: string) => !file.includes('webpack-runtime') && !file.includes('webpack-api-runtime') && file.endsWith('.js'));
685 fetchCache?: 'auto' | 'force-no-store' | 'only-no-store' | 'default-no-store' | 'default-cache' | 'only-cache' | 'force-cache'
686 checkFields<Diff<${options.type === 'page' ? 'PageProps' : 'LayoutProps'}, FirstArg<MaybeField<TEntry, 'generateMetadata'>>, 'generateMetadata'>>()
687 checkFields<Diff<{ __tag__: 'generateStaticParams', __return_type__: any[] | Promise<any[]> }, { __tag__: 'generateStaticParams', __return_type__: ReturnType<MaybeField<TEntry, 'generateStaticParams'>> }>>()
688 type Diff<Base, T extends Base, Message extends string = ''> = 0 extends (1 & T) ? {} : OmitWithTag<T, keyof Base, Message>
689 type FirstArg<T extends Function> = T extends (...args: [infer T, any]) => any ? unknown extends T ? any : T : never
690 type SecondArg<T extends Function> = T extends (...args: [any, infer T]) => any ? unknown extends T ? any : T : never
691 type Negative<T extends Numeric> = T extends Zero ? never : \`\${T}\` extends \`-\${string}\` ? T : never
692 const relativeImportPath = path.join(distDirRelative, path.relative(typePath, ''), relativePathToRoot.replace(/\.(js|jsx|ts|tsx|mjs)$/, '')).replace(/\\/g, '/');
693 return new Error(`${file} from Terser ${error.message} [${file}:${error.line},${error.col}]${error.stack ? ` ${error.stack.split(' ').slice(1).join(' ')}` : ''}`);
694 ...(terserOptions.format ? { format: { beautify: false, ...terserOptions.format } } : { output: { beautify: false, ...terserOptions.output } }),
695 const regexScssError = /SassError: (.+) \s+on line (\d+) [\s\S]*?>> (.+) \s*(-+)\^$/m;
696 if (!((err.name === 'CssSyntaxError' || err.name === 'SyntaxError') && (err as any).stack === false && !(err instanceof SyntaxError))) {
697 return new SimpleWebpackError(`${chalk.cyan(fileName)}:${chalk.yellow(lineNumber.toString())}:${chalk.yellow(column.toString())}`, chalk.red.bold('Syntax error').concat(`: ${reason}`));
698 if (!(typeof input === 'object' && (input?.name === 'ModuleBuildError' || input?.name === 'ModuleNotFoundError') && Boolean(input.module) && isError(input.error))) {
699 invalidImportMessage += ` The error was caused by using 'styled-jsx' in '${importTrace[0]}'. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.`;
700 err.message + invalidImportMessage + (importTrace.length > 0 ? ` Import trace for requested module: ${importTrace.map((mod) => ' ' + mod).join(' ')}` : ''),
701 formattedMessage = message.replace(NEXT_RSC_ERR_INVALID_API, ` "$1" is not supported in app/. Read more: https://beta.nextjs.org/docs/data-fetching/fundamentals `);
702 if (input.name !== 'ModuleNotFoundError' && !(input.name === 'ModuleBuildError' && /Error: Can't resolve '.+' in /.test(input.message))) {
703 const errorMessage = input.error.message.replace(/ in '.*?'/, '').replace(/Can't resolve '(.*)'/, `Can't resolve '${chalk.green('$1')}'`);
704 .filter((name) => name && !/next-(app|middleware|client-pages|flight-(client|server|client-entry))-loader\.js/.test(name) && !/css-loader.+\.js/.test(name));
705 let message = chalk.red.bold('Module not found') + `: ${errorMessage}` + ' ' + frame + (frame !== '' ? ' ' : '') + ' https://nextjs.org/docs/messages/module-not-found ' + importTrace();
706 .replace(new RegExp(`[^\\S\\r\ ]*\\(${lineNumber}:${column}\\)[^\\S\\r\ ]*`), '');
707 return new SimpleWebpackError(`${chalk.cyan(fileName)}:${chalk.yellow(lineNumber.toString())}:${chalk.yellow(column.toString())}`, chalk.red.bold('Syntax error').concat(`: ${message}`));
708 if ((file.endsWith('.js') || file.endsWith('.css')) && file.match(/^static\/(chunks|css)\//)) {
709 this.traceHookPair('webpack-compilation-chunk-graph', compilation.hooks.beforeChunks, compilation.hooks.afterChunks, { parentSpan: () => spans.get(compilation) || spans.get(compiler)! });
710 this.traceHookPair('webpack-compilation-optimize', compilation.hooks.optimize, compilation.hooks.reviveModules, { parentSpan: () => spans.get(compilation) || spans.get(compiler)! });
711 this.traceHookPair('webpack-compilation-hash', compilation.hooks.beforeHash, compilation.hooks.afterHash, { parentSpan: () => spans.get(compilation) || spans.get(compiler)! });
712 if (!props.rel || props.rel !== 'stylesheet' || !props.href || !OPTIMIZED_FONT_PROVIDERS.some(({ url }) => props.href.startsWith(url))) {
713 fontLoaderTargets.some((fontLoaderTarget) => (typeof fontLoaderTarget === 'string' ? mod.userRequest?.startsWith(`${fontLoaderTarget}?`) : fontLoaderTarget.test(mod.userRequest))),
714 const fontFiles: string[] = entrypoint.chunks.flatMap((chunk: any) => [...chunk.auxiliaryFiles]).filter((file: string) => /\.(woff|woff2|eot|ttf|otf)$/.test(file));
715 (dev ? mod.loaders.some((item) => item.loader.includes('next-style-loader/index.js')) : mod.loaders.some((item) => item.loader.includes('mini-css-extract-plugin/loader.js'))));
716 return requiredChunk.id + ':' + (requiredChunk.name || requiredChunk.id) + (dev ? '' : '-' + requiredChunk.hash);
717 manifest[resource.replace(/[\\/]next[\\/]dist[\\/]/, '/next/dist/esm/'.replace(/\//g, path.sep))] = moduleExports;
718 function forEachBail<TEntry>(array: TEntry[], iterator: (entry: TEntry, entryCallback: (err?: any, result?: any) => void) => void, callback: (err?: any, result?: any) => void): void {
719 resolver.getHook('described-resolve').tapAsync('JsConfigPathsPlugin', (request: any, resolveContext: any, callback: (err?: any, result?: any) => void) => {
720 resolver.doResolve(target, obj, `Aliased with tsconfig.json or jsconfig.json ${matchedPatternText} to ${candidate}`, resolveContext, (resolverErr: any, resolverResult: any) => {
721 const bundlePath = normalizePathSep(relativeRequest.replace(/\.[^.\\/]+$/, '').replace(/^src[\\/]/, ''));
722 modules: this.isEdgeServer ? clientImports.map((importPath) => importPath.replace(/[\\/]next[\\/]dist[\\/]esm[\\/]/, '/next/dist/'.replace(/\//g, path.sep))) : clientImports,
723 const NOT_TRACEABLE = ['.wasm', '.png', '.jpg', '.jpeg', '.gif', '.webp', '.avif', '.ico', '.bmp', '.svg'];
724 files: [...new Set([...entryFiles, ...allEntryFiles, ...(this.entryTraces.get(entrypoint.name) || [])])].map((file) => {
725 if (isError(e) && (e.code === 'EINVAL' || e.code === 'ENOENT' || e.code === 'UNKNOWN')) {
726 if (name[0] === '@' && segments.length > 1) return segments.length > 1 ? segments.slice(0, 2).join('/') : null;
727 requestPath = (resContext.descriptionFileRoot + request.slice(getPkgName(request)?.length || 0) + nodePath.sep + 'package.json').replace(/\\/g, '/').replace(/\0/g, '');
728 const doResolve = async (request: string, parent: string, job: import('@vercel/nft/out/node-file-trace').Job, isEsmRequested: boolean): Promise<string> => {
729 export function traverseModules(compilation: webpack.Compilation, callback: (mod: any, chunk: webpack.Chunk, chunkGroup: typeof compilation.chunkGroups[0], modId: string | number) => any) {
730 const css = remove ? '' : obj.media ? '@media ' + obj.media + ' {' + obj.css + '}' : obj.css;
731 const insert = typeof options.insert === 'undefined' ? '"head"' : typeof options.insert === 'string' ? JSON.stringify(options.insert) : options.insert.toString();
732 .map((request) => (regexCSS.test(request) ? `(() => import(/* webpackMode: "lazy" */ ${JSON.stringify(request)}))` : `import(/* webpackMode: "eager" */ ${JSON.stringify(request)})`))
733 warnOnce(`Warning: You're using \`next/head\` inside the \`app\` directory, please migrate to the Metadata API. See https://beta.nextjs.org/docs/api-reference/metadata for more details.`);
734 throw new Error(`Cannot render a Client Context Provider on the Server. ` + `Instead, you can export a Client Component wrapper ` + `that itself renders a Client Context Provider.`);
735 throw new Error(`Cannot access ${expression} on the server. ` + 'You cannot dot into a client module from a server component. ' + 'You can only pass the imported name through.');
736 resolve: (src: string) => promisify(this.resolve)(path.dirname(path.join(this.rootContext, relativeFilePathFromRoot)), src.startsWith('.') ? src : `./${src}`),
737 localeDomainRedirect = `http${matchedDomain.http ? '' : 's'}://${matchedDomain.domain}/${localeToCheck === matchedDomain.defaultLocale ? '' : localeToCheck}`;
738 export const unstable_getStaticParams = compMod['unstable_getStaticParam' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticParam' + 's'])
739 export const unstable_getStaticProps = compMod['unstable_getStaticProp' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticProp' + 's'])
740 export const unstable_getStaticPaths = compMod['unstable_getStaticPath' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getStaticPath' + 's'])
741 export const unstable_getServerProps = compMod['unstable_getServerProp' + 's'] || compMod.then && compMod.then(mod => mod['unstable_getServerProp' + 's'])
742 export let config = compMod['confi' + 'g'] || (compMod.then && compMod.then(mod => mod['confi' + 'g'])) || {}
743 Object.assign({}, getStaticProps ? { ...(parsedUrl.query.amp ? { amp: '1' } : {}) } : parsedUrl.query, nowParams ? nowParams : params, _params, isFallback ? { __nextFallback: 'true' } : {}),
744 const EXCLUDED_PATHS = /[\\/](cache[\\/][^\\/]+\.zip[\\/]node_modules|__virtual__)[\\/]/g;
745 return names.map((name) => ` '${generateActionId(path, name)}': () => import(/* webpackMode: "eager" */ ${JSON.stringify(path)}).then(mod => mod[${JSON.stringify(name)}]),`).join(' ');
746 return `'${file}': [() => import(/* webpackMode: "eager" */ ${JSON.stringify(filePath)}), ${JSON.stringify(filePath)}],`;
747 Log.error(`${chalk.bold(pagePath.replace(`${APP_DIR_ALIAS}/`, ''))} doesn't have a root layout. To fix this error, make sure every page has a root layout.`);
748 .concat((typeof exception === 'string' && exception) || (exception instanceof Error && [exception.message, (exception as any).stack.split(' ')[1].trim()]) || [])
749 throw new Error('source-map information is not available at url() declaration ' + (ORPHAN_CR_REGEX.test(sourceContent) ? '(found orphan CR, try removeCR option)' : '(no orphan CR found)'));
750 const URL_STATEMENT_REGEX = /(url\s*\()\s*(?:(['"])((?:(?!\2).)*)(\2)|([^'"](?:(?!\)).)*[^'"]))\s*(\))/g;
751 return !!uri && typeof options.root === 'string' && loaderUtils.isUrlRequest(uri, options.root) && (/^\//.test(uri) || path.isAbsolute(uri));
752 return (relative[0] === '..' ? absolute.split(path.sep) : ['.'].concat(relative).filter(Boolean)).join('/');
753 const pageModPath = `${appDirLoader}${stringifiedPagePath.substring(1, stringifiedPagePath.length - 1)}${isAppDir ? '?__edge_ssr_entry__' : ''}`;
754 if (paramsNodes.length === 0 || (paramsNodes[0].type !== 'string' && paramsNodes[0].type !== 'function')) {
755 const unescapeRegExp = new RegExp(`\\\\([\\da-f]{1,6}${whitespace}?|(${whitespace})|.)`, 'ig');
756 code += `import ${options.modules.exportOnlyLocals ? '' : `${importName}, `}* as ${importName}_NAMED___ from ${url}; `;
757 ? `___CSS_LOADER_EXPORT___.push([module.id, ${JSON.stringify(`@import url(${url});`)}${media ? `, ${JSON.stringify(media)}` : ''}]); `
758 : `___CSS_LOADER_EXPORT___.i(${item.importName}${media ? `, ${JSON.stringify(media)}` : dedupe ? ', ""' : ''}${dedupe ? ', true' : ''}); `;
759 options.modules.namedExport ? `" + ${importName}_NAMED___[${JSON.stringify(camelCase(localName))}] + "` : `" + ${importName}.locals[${JSON.stringify(localName)}] + "`,
760 const getUrlOptions = [...(hash ? [`hash: ${JSON.stringify(hash)}`] : []), ...(needQuotes ? 'needQuotes: true' : [])];
761 code += options.modules.namedExport ? localsCode : `${options.esModule ? 'export default' : 'module.exports ='} { ${localsCode} }; `;
762 return input.replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toLocaleUpperCase(options.locale)).replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, (m) => m.toLocaleUpperCase(options.locale));
763 module.exports = global.process?.env && typeof global.process?.env === 'object' ? global.process : require('../../compiled/process');
764 ...(transpiled ? [`/node_modules/(?!.pnpm)(?!(${transpiled})/)`, `/node_modules/.pnpm/(?!(${transpiled.replace(/\//g, '\\+')})@)`] : ['/node_modules/']),
765 const BABEL_CONFIG_FILES = ['.babelrc', '.babelrc.json', '.babelrc.js', '.babelrc.mjs', '.babelrc.cjs', 'babel.config.js', 'babel.config.json', 'babel.config.mjs', 'babel.config.cjs'];
766 const nodePathList = (process.env.NODE_PATH || '').split(process.platform === 'win32' ? ';' : ':').filter((p) => !!p);
767 console.warn(\`An environment variable (\${prop}) that was not provided in the environment was accessed. See more info here: https://nextjs.org/docs/messages/missing-env-value\`)
768 [CLIENT_STATIC_FILES_RUNTIME_AMP]: `./` + path.relative(dir, path.join(NEXT_PROJECT_ROOT_DIST_CLIENT, 'dev', 'amp-dev')).replace(/\\/g, '/'),
769 [CLIENT_STATIC_FILES_RUNTIME_MAIN]: `./` + path.relative(dir, path.join(NEXT_PROJECT_ROOT_DIST_CLIENT, dev ? `next-dev.js` : 'next.js')).replace(/\\/g, '/'),
770 : [`./` + path.relative(dir, path.join(NEXT_PROJECT_ROOT_DIST_CLIENT, 'app-next.js')).replace(/\\/g, '/')],
771 extensions: isNodeServer ? ['.js', '.mjs', '.tsx', '.ts', '.jsx', '.json', '.wasm'] : ['.mjs', '.js', '.tsx', '.ts', '.jsx', '.json', '.wasm'],
772 const optOutBundlingPackageRegex = new RegExp(`[/\\\\]node_modules[/\\\\](${optOutBundlingPackages.map((p) => p.replace(/\//g, '[/\\\\]')).join('|')})[/\\\\]`);
773 const isNextExternal = /next[/\\]dist[/\\](esm[\\/])?(shared|server)[/\\](?!lib[/\\](router[/\\]router|dynamic|app-dynamic|lazy-dynamic|head[^-]))/.test(localRes);
774 if (/next[/\\]dist[/\\](esm[\\/])?shared[/\\](?!lib[/\\]router[/\\]router)/.test(res) || /next[/\\]dist[/\\]compiled[/\\].*\.[mc]?js$/.test(res)) {
775 ) => (resolveContext: string, resolveRequest: string, callback: (err?: Error, result?: string, resolveData?: { descriptionFileData?: { type?: any } }) => void) => void;
776 : `static/chunks/${isDevFallback ? 'fallback/' : ''}[name]${dev ? '' : appDir ? '-[chunkhash]' : '-[contenthash]'}.js`,
777 chunkFilename: isNodeServer || isEdgeServer ? '[name].js' : `static/chunks/${isDevFallback ? 'fallback/' : ''}${dev ? '[name]' : '[name].[contenthash]'}.js`,
778 webpack5Config.module.unsafeCache = (module) => !/[\\/]pages[\\/][^\\/]+(?:$|\?|#)/.test(module.resource);
779 webpack5Config.snapshot.managedPaths = [/^(.+?(?:[\\/]\.yarn[\\/]unplugged[\\/][^\\/]+)?[\\/]node_modules[\\/])/];
780 webpack5Config.snapshot.immutablePaths = [/^(.+?[\\/]cache[\\/][^\\/]+\.zip[\\/]node_modules[\\/])/];
781 const hasCustomSvg = rules.some((rule) => rule && typeof rule === 'object' && rule.loader !== 'next-image-loader' && 'test' in rule && rule.test instanceof RegExp && rule.test.test('.svg'));
782 const nextImageRule = rules.find((rule) => rule && typeof rule === 'object' && rule.loader === 'next-image-loader');
783 console.warn(` @zeit/next-typescript is no longer needed since Next.js has built-in support for TypeScript now. Please remove it from your ${config.configFileName} and your .babelrc `);
784 const plugins = (nextConfig?.experimental?.swcPlugins ?? []).filter(Array.isArray).map(([name, options]: any) => [require.resolve(name), options]);
785 events.forEach(({ eventName, payload }) => console.error(`[telemetry] ` + JSON.stringify({ eventName, payload }, null, 2)));
786 const REGEXP_DIRECTORY_DUNDER = /[\\/]__[^\\/]+(?<![\\/]__(?:tests|mocks))__[\\/]/i;
787 export function eventBuildCompleted(pagePaths: string[], event: Omit<EventBuildCompleted, 'totalPageCount' | 'hasDunderPages' | 'hasTestPages'>): { eventName: string; payload: EventBuildCompleted } {
788 export function eventBuildOptimize(pagePaths: string[], event: Omit<EventBuildOptimized, 'totalPageCount' | 'hasDunderPages' | 'hasTestPages'>): { eventName: string; payload: EventBuildOptimized } {
789 const isForTooling = res.options?.presets?.every((e: any) => e?.file?.request === 'next/babel') && res.options?.plugins?.length === 0;
790 return findUp([`.${key}rc.json`, `${key}.config.json`, `.${key}rc.js`, `${key}.config.js`, `${key}.config.cjs`], {
791 export const PUBLIC_DIR_MIDDLEWARE_CONFLICT = `You can not have a '_next' folder inside of your public folder. This conflicts with the internal '/_next' route. https://nextjs.org/docs/messages/public-next-folder-conflict`;
792 export const GSSP_COMPONENT_MEMBER_ERROR = `can not be attached to a page's component and must be exported from the page. See more info here: https://nextjs.org/docs/messages/gssp-component-member`;
793 export const NON_STANDARD_NODE_ENV = `You are using a non-standard "NODE_ENV" value in your environment. This creates inconsistencies in the project and is strongly advised against. Read more: https://nextjs.org/docs/messages/non-standard-node-env`;
794 export const SSG_FALLBACK_EXPORT_ERROR = `Pages with \`fallback\` enabled in \`getStaticPaths\` can not be exported. See more info here: https://nextjs.org/docs/messages/ssg-fallback-true-export`;
795 export type ReferrerEnum = 'no-referrer' | 'origin' | 'no-referrer-when-downgrade' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin';
796 [[{ openGraph: { type: 'article', images: 'https://test1.com' } }], { openGraph: { images: [{ url: 'https://test1.com' }] } }],
797 [[{ openGraph: { type: 'book', images: 'https://test2.com' } }], { openGraph: { images: [{ url: 'https://test2.com' }] } }],
798 [[{ openGraph: { type: 'video.movie', images: 'https://test6.com' } }], { openGraph: { images: [{ url: 'https://test6.com' }] } }],
799 expect(resolveTitle({ default: 'title', template: '%s | absolute' }, 'dash %s')).toEqual({ absolute: 'dash title', template: '%s | absolute' });
800 expect(resolveTitle({ default: '', template: '%s | absolute' }, 'fake template')).toEqual({ absolute: 'fake template', template: '%s | absolute' });
801 const startupImages = appWebApp.startupImage ? resolveAsArrayOrUndefined(appWebApp.startupImage)?.map((item) => (typeof item === 'string' ? { url: item } : item)) : null;
802 function resolveUrlValuesOfObject(obj: Record<string, string | URL | null> | null | undefined, metadataBase: ResolvedMetadata['metadataBase']): null | Record<string, string | URL | null> {
803 regex = regex.replace(/\^/, `^(?!${restrictedPaths.map((path) => path.replace(/\//g, '\\/')).join('|')})`);
804 path ? `Error serializing \`${path}\` returned from \`${method}\` in "${page}". Reason: ${message}` : `Error serializing props returned from \`${method}\` in "${page}". Reason: ${message}`,
805 throw new SerializableError(page, method, '', `Props must be returned as a plain object from ${method}: \`{ props: { ... } }\` (received: \`${getObjectClassLabel(input)}\`).`);
806 throw new SerializableError(page, method, path, `Circular references cannot be expressed in JSON (references: \`${visited.get(value) || '(self)'}\`).`);
807 throw new FatalError(chalk.red.bold('Could not parse', chalk.cyan('tsconfig.json') + '.' + ' Please make sure it contains syntactically correct JSON.') + reason);
808 export async function runTypeCheck(ts: typeof import('typescript'), baseDir: string, distDir: string, tsConfigPath: string, cacheDir?: string, isAppDirEnabled?: boolean): Promise<TypeCheckResult> {
809 const regexIgnoredFile = /[\\/]__(?:tests|mocks)__[\\/]|(?<=[\\/.])(?:spec|test)\.[^\\/]+$/;
810 const firstError = allDiagnostics.find((d) => d.category === DiagnosticCategory.Error && Boolean(d.file)) ?? allDiagnostics.find((d) => d.category === DiagnosticCategory.Error);
811 const allErrors = allDiagnostics.filter((d) => d.category === DiagnosticCategory.Error).map((d) => '[Test Mode] ' + getFormattedDiagnostic(ts, baseDir, distDir, d, isAppDirEnabled));
812 console.error(' ===== TS errors ===== ' + allErrors.join(' ') + ' ===== TS errors ===== ');
813 const warnings = allDiagnostics.filter((d) => d.category === DiagnosticCategory.Warning).map((d) => getFormattedDiagnostic(ts, baseDir, distDir, d, isAppDirEnabled));
814 Log.info(`VS Code settings.json has been ${configExists ? 'updated' : 'created'} for Next.js' automatic app types, this file can be added to .gitignore if desired`);
815 directives.push('', '// NOTE: This file should not be edited', '// see https://nextjs.org/docs/basic-features/typescript for more information.');
816 chalk.bold('If you are not trying to use TypeScript, please remove the ' + chalk.cyan('tsconfig.json') + ' file from your package root (and any TypeScript files in your pages directory).');
817 const match = message.match(/Type '"(.+)"' is not assignable to type 'RouteImpl<.+> \| UrlObject'\./) || message.match(/Type '"(.+)"' is not assignable to type 'UrlObject \| RouteImpl<.+>'\./);
818 if (typeof relatedMessage === 'string' && relatedMessage.match(/The expected type comes from property 'href' which is declared here on type 'IntrinsicAttributes & /)) {
819 return `Invalid \`href\` property of \`Link\`: the route does not exist. If it is intentional, please type it explicitly with \`as Route\`.`;
820 message.match(/Type '"(.+)"' is not assignable to type 'RouteImpl<.+> \| UrlObject'\. Did you mean '"(.+)"'?/) ||
821 message.match(/Type '"(.+)"' is not assignable to type 'UrlObject \| RouteImpl<.+>'\. Did you mean '"(.+)"'?/);
822 return `"${chalk.bold(href)}" is not an existing route. Did you mean "${chalk.bold(suggestion)}" instead? If it is intentional, please type it explicitly with \`as Route\`.`;
823 main += `Expected "${chalk.bold(types[2].replace('"__invalid_negative_number__"', 'number (>= 0)'))}", got "${chalk.bold(types[1])}".`;
824 const main = `${type} "${chalk.bold(relativeSourceFilepath)}" has an invalid "${chalk.bold(invalidExportFnArg[2])}" export: Type "${chalk.bold(invalidExportFnArg[1])}" is not valid.`;
825 const invalidExportFnReturn = messageText.match(/Type '{ __tag__: "(.+)"; __return_type__: (.+); }' does not satisfy/);
826 let main = `${type} "${chalk.bold(relativeSourceFilepath)}" has an invalid export: "${chalk.bold(invalidExportFnReturn[2])}" is not a valid ${invalidExportFnReturn[1]} return type:`;
827 const main = `${type} "${chalk.bold(relativeSourceFilepath)}" contains an invalid type "${chalk.bold(invalid[1])}" as ${invalid[2]}.`;
828 message = chalk.cyan(fileName) + ':' + chalk.yellow(line.toString()) + ':' + chalk.yellow(character.toString()) + ' ' + message;
829 if (!('parsedValues' in check ? check.parsedValues?.includes(ev) : 'parsedValue' in check ? check.parsedValue === ev : check.value === ev)) {
830 userTsConfig.include = isAppDirEnabled ? ['next-env.d.ts', nextAppTypes, '**/*.ts', '**/*.tsx'] : ['next-env.d.ts', '**/*.ts', '**/*.tsx'];
831 chalk.cyan('include') + ' was set to ' + chalk.bold(isAppDirEnabled ? `['next-env.d.ts', '${nextAppTypes}', '**/*.ts', '**/*.tsx']` : `['next-env.d.ts', '**/*.ts', '**/*.tsx']`),
832 console.log(chalk.green(`We detected TypeScript in your project and reconfigured your ${chalk.bold('tsconfig.json')} file for you. Strict-mode is set to ${chalk.bold('false')} by default.`) + ' ');
833 console.log(`The following suggested values were added to your ${chalk.cyan('tsconfig.json')}. These values ${chalk.bold('can be changed')} to fit your project's needs: `);
834 return items.map((v, index, { length }) => (index > 0 ? (index === length - 1 ? (length > 2 ? ', and ' : ' and ') : ', ') : '') + v).join('');
835 (packageManager === 'yarn' ? 'yarn add --dev' : packageManager === 'pnpm' ? 'pnpm install --save-dev' : 'npm install --save-dev') + ' eslint',
836 return `${chalk.red('error')} - Your project has an older version of ESLint installed${eslintVersion ? ' (' + eslintVersion + ')' : ''}. Please upgrade to ESLint version 7 or above`;
837 if (!options.baseConfig!.rules?.[rule] && !options.baseConfig!.rules?.[rule.replace('@next/next', '@next/babel-plugin-next')]) {
838 nextEslintPluginIsEnabled && deps.resolved.has('eslint-config-next') ? require(path.join(path.dirname(deps.resolved.get('eslint-config-next')!), 'package.json')).version : null,
839 const { lintDuringBuild = false, eslintOptions = null, reportErrorsOnly = false, maxWarnings = -1, formatter = null, outputFile = null, strict = false } = opts;
840 (await findUp(['.eslintrc.js', '.eslintrc.cjs', '.eslintrc.yaml', '.eslintrc.yml', '.eslintrc.json', '.eslintrc'], {
841 const { config: selectedConfig } = strict ? ESLINT_PROMPT_VALUES.find((opt: { title: string }) => opt.title === 'Strict')! : await cliPrompt();
842 const output = format ? format(resultsWithMessages) : resultsWithMessages.map(({ messages, filePath }) => formatMessage(baseDir, messages, filePath)).join(' ');
843 resultsWithMessages.length > 0 ? output + ` ${chalk.cyan('info')} - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules` : '',
844 if (content === '' || content === '{}' || content === '---' || content === 'module.exports = {}') {
845 chalk.bold('If you are not trying to use TypeScript, please remove the ' + chalk.cyan('tsconfig.json') + ' file from your package root (and any TypeScript files in your pages directory).') +
846 export function withPromiseCache<K, V>(cache: Cache<K, Promise<V>>, fn: (value: K) => Promise<V>): (value: K) => Promise<V>;
847 export function withPromiseCache<T extends any[], K, V>(cache: Cache<K, Promise<V>>, fn: (...values: T) => Promise<V>, getKey: (...values: T) => K): (...values: T) => Promise<V>;
848 export function withPromiseCache<T extends any[], K, V>(cache: Cache<K, Promise<V>>, fn: (...values: T) => Promise<V>, getKey?: (...values: T) => K): (...values: T) => Promise<V> {
849 if ((code === 'EBUSY' || code === 'ENOTEMPTY' || code === 'EPERM' || code === 'EMFILE') && t < 3) {
850 export function withCoalescedInvoke<F extends (...args: any) => any>(func: F): (key: string, args: Parameters<F>) => Promise<CoalescedInvoke<UnwrapPromise<ReturnType<F>>>> {
851 chalk.green(` Your page ${chalk.bold(`app/${normalizedPagePath}`)} did not have a root layout. We created ${chalk.bold(`app${rootLayoutPath.replace(appDir, '')}`)} for you.`) + ' ',
852 This might be caused by a React Class Component being rendered in a Server Component, React Class Components only works in Client Components. Read more: https://nextjs.org/docs/messages/class-component-in-server-component"
853 console.error(`Error: ${type}s must return an array, received ${typeof routes}. ` + `See here for more info: https://nextjs.org/docs/messages/routes-must-be-array`);
854 console.error(`The route ${JSON.stringify(route)} is not a valid object with \`source\`${type !== 'middleware' ? ` and \`${type === 'header' ? 'headers' : 'destination'}\`` : ''}`);
855 if (type === 'rewrite' && (route as Rewrite).basePath === false && !((route as Rewrite).destination.startsWith('http://') || (route as Rewrite).destination.startsWith('https://'))) {
856 } rewrites urls outside of the basePath. Please use a destination that starts with \`http://\` or \`https://\` https://nextjs.org/docs/messages/invalid-external-rewrite`,
857 } else if (type === 'rewrite' && !_route.destination.match(/^(\/|https:\/\/|http:\/\/)/)) {
858 invalidParts.push(`\`destination\` has segments not in \`source\` or \`has\` (${[...invalidDestSegments].join(', ')})`);
859 invalidKeys.length ? (hasInvalidParts ? ',' : '') + ` invalid field${invalidKeys.length === 1 ? '' : 's'}: ` + invalidKeys.join(',') : ''
860 source: `${srcBasePath}/${item.locale}${r.source === '/' && !config.trailingSlash ? '' : r.source}`,
861 r.source = `/:nextInternalLocale(${config.i18n.locales.map((locale: string) => escapeStringRegexp(locale)).join('|')})${r.source === '/' && !config.trailingSlash ? '' : r.source}`;
862 if (!Array.isArray(_rewrites) && typeof _rewrites === 'object' && Object.keys(_rewrites).every((key) => key === 'beforeFiles' || key === 'afterFiles' || key === 'fallback')) {
863 frames: ['[ ]', '[= ]', '[== ]', '[=== ]', '[ ===]', '[ ==]', '[ =]', '[ ]', '[ =]', '[ ==]', '[ ===]', '[====]', '[=== ]', '[== ]', '[= ]'],
864 await nextExportSpan.traceChild('copy-next-static-directory').traceAsyncFn(() => recursiveCopy(join(distDir, CLIENT_STATIC_FILES_PATH), join(outDir, '_next', CLIENT_STATIC_FILES_PATH)));
865 const htmlDest = join(outDir, `${route}${subFolders && route !== '/index' ? `${sep}index` : ''}.html`);
866 throw new Error(`The provided export path '${updatedPath}' doesn't match the '${page}' page. Read more: https://nextjs.org/docs/messages/export-path-mismatch`);
867 if ([`/${statusCode}`, `/${statusCode}.html`, `/${statusCode}/index.html`].some((p) => p === updatedPath || `/${locale}${p}` === updatedPath)) {
868 if (locale && buildExport && renderOpts.domainLocales && renderOpts.domainLocales.some((dl) => dl.defaultLocale === locale || dl.locales?.includes(locale || ''))) {
869 const isBuiltinPaths = ['/500', '/404'].some((p) => p === path || p === path + '.html');
870 const isDynamicUsageError = (err: any) => err.digest === DYNAMIC_ERROR_CODE || isNotFoundError(err) || err.digest === NEXT_DYNAMIC_NO_SSR_CODE || isRedirectError(err);
871 const { AppRouteRouteHandler } = require('../server/future/route-handlers/app-route-route-handler') as typeof import('../server/future/route-handlers/app-route-route-handler');
872 console.error(` Error occurred prerendering page "${path}". Read more: https://nextjs.org/docs/messages/prerender-error ` + (isError(error) && error.stack ? error.stack : error));
873 expect(requests.filter((req) => req.includes('_next/data'))).toEqual([`${next.url}/ next/data/${next.buildId}/sha.json?hello=goodbye`]);
874 ${} ${} ${} ${} ${} ${} ${} ${} ${} ${} ${} ${} ${} ${} ${} ${} ${} ${} ${} ${}
875 <WithNav><App /></WithNav> <WithNav><App /></WithNav> <WithNav><App /></WithNav> <WithNav><App /></WithNav> <WithNav><App /></WithNav>
876 for (c.width = i = W = 250; i -= 2;) for (j = 1; j < W; x.fillRect(i, j++ - h, 2, h + 1)) x.fillStyle = R(h = ((d = W / j * 35) * S(A = i / W + t / 2) & d * C(A) + t * 80 + t & 36) * 180 / d, d / 2, d)
877 for (i = 2e3; i--; x.fillStyle = `hsl(${1e3 * T(t + C(t - i / 77) * 3 | S(t + i / 77) * 3)},70%,50%)`) x.fillRect(1, i - S(t + C(t + i / 99)) * 50, 2, 1); x.drawImage(c, 2, 0)
878 for (c.width = i = W = 220; i -= 2;) for (j = 9; j < W; x.fillRect(i, j++ - h, 2, 9 / d)) x.fillStyle = R(h = ((d = W * 9 / j) * S(A = i / W + S(t)) + t & d * C(A) + t * 9 & 11) * 9 / d)
879 for (c.width = w = 170, Y = j = 9; j--;) for (i = 1e3, x.fillStyle = R(a = j * j * 5, a - a % 99, a / 2); i--; x.fillRect(i, Y - j * 9 + 99, 1, w)) Y += C(j * (t * (9 - j) ** 3 + i | 0) ** 3) - Y / w
880 for (L = i = 26e3; i--; x.fillStyle = R(3 * Z * Z, x.fillRect(X, Y - 9 + L, 9, 9), Z ** 3)) for (g = 215, Z = m = 6; m--;) Z += C(d = Math.hypot((X = i % g * 9) - C(m + t / 9) * L, Y = i / g * 9 - L) / g)
881 for (L = i = 3e4; i--; x.fillStyle = R(Z ** 33, x.fillRect(X, Y - 9, 9, 20), Y / 9)) for (g = 214, Z = m = 7; m--;) Z += C(d = Math.hypot((X = i % g * 9) - C(m + t / 14) * L, (Y = i / g * 9) - L) / g)
882 const b = 500; x.fillRect(c.width / 2 - b / 2 * t, c.height / 2 - b / 2 * t, b * t, b * t)
883 for (i = 2e3; i--; x.fillStyle = `hsl(${i * T(t * i / 9 + C(z * t) * 4 & S(z ^ t) * 9)},99%,39%,.1)`) x.fillRect(1, i - S(t + C(z = t + i / 59)) * i / 9, 8.2, 1); x.drawImage(c, 9, C(t))
884 var lib = require("./jsfuck.js");
885 for (var i = 0; i < lines.length; i++) if (lines[i] !== '') this.push(lines[i] + ' ');
886 [17, 42, 89, 3092, 400, 584, 434, 457].map((number) => ("$" + number));
887 unmappped = unmappped.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
888 if (/^\d$/.test(input)) { output += "+[]"; }
889 return '\\u' + ('0000' + cc16).substring(cc16.length);
890 "$" "$" "$" "$" "$" "$" "$" "$" "$" "$" "$" "$" "$" "$" "$" "$" "$" "$" "$" "$"
891 '$', '$', '$', '$', '$', '$', '$', '$', '$', '$', '$', '$', '$', '$', '$', '$', '$', '$', '$', '$'
892 $('.table') $('.table') $('.table') $('.table') $('.table') $('.table') $('.table') $('.table') $('.table') $('.table') $('.table') $('.table')
893 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z' 'z'
894 2/1000 = 0.002, 2/1000 = 0.002, 2/1000 = 0.002, 2/1000 = 0.002, 2/1000 = 0.002, 2/1000 = 0.002, 2/1000 = 0.002
895 test@gmail.com test@gmail.com test@gmail.com test@gmail.com test@gmail.com test@gmail.com test@gmail.com
896 &#38; &#38; &#38; &#38; &#38; &#38; &#38; &#38; &#38; &#38; &#38; &#38; &#38; &#38; &#38;
897 /(?<=(\$|\^))\d+/; /(?<=(\$|\^))\d+/; /(?<=(\$|\^))\d+/; /(?<=(\$|\^))\d+/; /(?<=(\$|\^))\d+/;
898 \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$ \$
899 \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^ \^
900 x | 2; x | 2; x | 2; x | 2; x | 2; x | 2; x | 2; x | 2; x | 2; x | 2; x | 2; x | 2; x | 2; x | 2; x | 2; x | 2;
901 :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j :j
902 :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f :f
903 \\ \| \/ \\ \| \/ \\ \| \/ \\ \| \/ \\ \| \/ \\ \| \/ \\ \| \/ \\ \| \/ \\ \| \/
904 (x*y) (x*y) (x*y) (x*y) (x*y) (x*y) (x*y) (x*y) (x*y) (x*y) (x*y) (x*y) (x*y)
905 (() => {return $("div",null);}); (() => {return $("div",null);}); (() => {return $("div",null);}); (() => {return $("div",null);});

Связаться
Выделить
Выделите фрагменты страницы, относящиеся к вашему сообщению
Скрыть сведения
Скрыть всю личную информацию
Отмена