From 51f8f19959aac1c74294ea208feb0d2447cda63d Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Fri, 24 Feb 2023 07:49:08 +0000
Subject: [PATCH 01/37] =?UTF-8?q?fix=20=C2=B7=20it=20can=20access=20websit?=
=?UTF-8?q?e=20without=20index=20in=20dev=20environment=20and=20production?=
=?UTF-8?q?=20environment?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.changeset/small-knives-sparkle.md | 5 +++++
packages/astro/src/core/build/common.ts | 6 +++++-
packages/astro/src/core/routing/params.ts | 3 ++-
3 files changed, 12 insertions(+), 2 deletions(-)
create mode 100644 .changeset/small-knives-sparkle.md
diff --git a/.changeset/small-knives-sparkle.md b/.changeset/small-knives-sparkle.md
new file mode 100644
index 000000000000..9dc0f3d75fde
--- /dev/null
+++ b/.changeset/small-knives-sparkle.md
@@ -0,0 +1,5 @@
+---
+'astro': major
+---
+
+· it can access website without 'index'
diff --git a/packages/astro/src/core/build/common.ts b/packages/astro/src/core/build/common.ts
index 74be830f0356..5f65a6dd038c 100644
--- a/packages/astro/src/core/build/common.ts
+++ b/packages/astro/src/core/build/common.ts
@@ -5,6 +5,7 @@ import { appendForwardSlash } from '../../core/path.js';
const STATUS_CODE_PAGES = new Set(['/404', '/500']);
const FALLBACK_OUT_DIR_NAME = './.astro/';
+const PAGEHOMENAME = 'index';
function getOutRoot(astroConfig: AstroConfig): URL {
if (astroConfig.output === 'static') {
@@ -29,7 +30,10 @@ export function getOutFolder(
switch (astroConfig.build.format) {
case 'directory': {
if (STATUS_CODE_PAGES.has(pathname)) {
- return new URL('.' + appendForwardSlash(npath.dirname(pathname)), outRoot);
+ if(pathname.endsWith(PAGEHOMENAME)){
+ new URL('.' + appendForwardSlash(npath.dirname(pathname.slice(0, -PAGEHOMENAME.length))), outRoot);;
+ }
+ return new URL('.' + appendForwardSlash(npath.dirname(pathname)), outRoot);;
}
return new URL('.' + appendForwardSlash(pathname), outRoot);
}
diff --git a/packages/astro/src/core/routing/params.ts b/packages/astro/src/core/routing/params.ts
index 6a822861fecf..86d25278a09a 100644
--- a/packages/astro/src/core/routing/params.ts
+++ b/packages/astro/src/core/routing/params.ts
@@ -11,7 +11,8 @@ export function getParams(array: string[]) {
const params: Params = {};
array.forEach((key, i) => {
if (key.startsWith('...')) {
- params[key.slice(3)] = match[i + 1] ? decodeURIComponent(match[i + 1]) : undefined;
+ // default to 'index' if the param is empty in the dev environment
+ params[key.slice(3)] = match[i + 1] ? decodeURIComponent(match[i + 1]) : 'index';
} else {
params[key] = decodeURIComponent(match[i + 1]);
}
From b1e081bff052a123f3138ec7bbce69d7a8e1c6b9 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Fri, 24 Feb 2023 09:41:06 +0000
Subject: [PATCH 02/37] pass test
---
packages/astro/src/core/routing/params.ts | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/packages/astro/src/core/routing/params.ts b/packages/astro/src/core/routing/params.ts
index 86d25278a09a..a5e5722b33c8 100644
--- a/packages/astro/src/core/routing/params.ts
+++ b/packages/astro/src/core/routing/params.ts
@@ -11,8 +11,7 @@ export function getParams(array: string[]) {
const params: Params = {};
array.forEach((key, i) => {
if (key.startsWith('...')) {
- // default to 'index' if the param is empty in the dev environment
- params[key.slice(3)] = match[i + 1] ? decodeURIComponent(match[i + 1]) : 'index';
+ params[key.slice(3)] = match[i + 1] ? decodeURIComponent(match[i + 1]) : undefined;
} else {
params[key] = decodeURIComponent(match[i + 1]);
}
@@ -33,7 +32,8 @@ export function stringifyParams(params: GetStaticPathsItem['params'], routeCompo
const validatedParams = Object.entries(params).reduce((acc, next) => {
validateGetStaticPathsParameter(next, routeComponent);
const [key, value] = next;
- acc[key] = value?.toString();
+ // default to 'index' if the param is empty in the dev environment
+ acc[key] = !value ? 'index' : value?.toString();
return acc;
}, {} as Params);
From d155a24096e3adbab1b60b4638ed7e47c478aa8a Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Tue, 28 Feb 2023 08:57:42 +0000
Subject: [PATCH 03/37] add test
---
packages/astro/package.json | 2 ++
packages/astro/src/core/build/common.ts | 11 ++++++----
.../src/pages/slug-index/[...slug].astro | 22 +++++++++++++++++++
packages/astro/test/routing-priority.test.js | 8 ++++++-
4 files changed, 38 insertions(+), 5 deletions(-)
create mode 100644 packages/astro/test/fixtures/routing-priority/src/pages/slug-index/[...slug].astro
diff --git a/packages/astro/package.json b/packages/astro/package.json
index 339bd8d5d2eb..8bd3a47c51d2 100644
--- a/packages/astro/package.json
+++ b/packages/astro/package.json
@@ -92,6 +92,8 @@
"postbuild": "astro-scripts copy \"src/**/*.astro\"",
"benchmark": "node test/benchmark/dev.bench.js && node test/benchmark/build.bench.js",
"test:unit": "mocha --exit --timeout 30000 ./test/units/**/*.test.js",
+ "test:1": "mocha --exit --timeout 30000 ./test/routing-priority.test.js",
+
"test:unit:match": "mocha --exit --timeout 30000 ./test/units/**/*.test.js -g",
"test": "pnpm run test:unit && mocha --exit --timeout 20000 --ignore **/lit-element.test.js && mocha --timeout 20000 **/lit-element.test.js",
"test:match": "mocha --timeout 20000 -g",
diff --git a/packages/astro/src/core/build/common.ts b/packages/astro/src/core/build/common.ts
index 5f65a6dd038c..e1e63f146d7c 100644
--- a/packages/astro/src/core/build/common.ts
+++ b/packages/astro/src/core/build/common.ts
@@ -29,11 +29,14 @@ export function getOutFolder(
case 'page':
switch (astroConfig.build.format) {
case 'directory': {
+ if (pathname.endsWith(PAGEHOMENAME)) {
+ return new URL(
+ '.' + appendForwardSlash(npath.dirname(pathname.slice(0, -PAGEHOMENAME.length + 1))),
+ outRoot
+ );
+ }
if (STATUS_CODE_PAGES.has(pathname)) {
- if(pathname.endsWith(PAGEHOMENAME)){
- new URL('.' + appendForwardSlash(npath.dirname(pathname.slice(0, -PAGEHOMENAME.length))), outRoot);;
- }
- return new URL('.' + appendForwardSlash(npath.dirname(pathname)), outRoot);;
+ return new URL('.' + appendForwardSlash(npath.dirname(pathname)), outRoot);
}
return new URL('.' + appendForwardSlash(pathname), outRoot);
}
diff --git a/packages/astro/test/fixtures/routing-priority/src/pages/slug-index/[...slug].astro b/packages/astro/test/fixtures/routing-priority/src/pages/slug-index/[...slug].astro
new file mode 100644
index 000000000000..0bfcf4b3d3ff
--- /dev/null
+++ b/packages/astro/test/fixtures/routing-priority/src/pages/slug-index/[...slug].astro
@@ -0,0 +1,22 @@
+---
+export function getStaticPaths() {
+ return [{
+ params: { slug: "index" },
+ }, {
+ params: { slug: 'potato' },
+ }]
+}
+const { slug } = Astro.params
+---
+
+
+
+
+
+ {slug}
+
+
+ slug-index/[...slug].astro
+ slug: {slug || 'index'}
+
+
diff --git a/packages/astro/test/routing-priority.test.js b/packages/astro/test/routing-priority.test.js
index 586978d4f4cd..e7c4f0612c1b 100644
--- a/packages/astro/test/routing-priority.test.js
+++ b/packages/astro/test/routing-priority.test.js
@@ -95,6 +95,12 @@ const routes = [
h1: '[id].astro',
p: 'injected-2',
},
+ {
+ description: 'matches /slug-index to slug-index/[...slug].astro',
+ url: '/slug-index',
+ h1: 'slug-index/[...slug].astro',
+ p: 'slug: index',
+ },
{
description: 'matches /empty-slug to empty-slug/[...slug].astro',
url: '/empty-slug',
@@ -143,7 +149,7 @@ describe('Routing priority', () => {
it(description, async () => {
const htmlFile = isEndpoint ? url : `${appendForwardSlash(url)}index.html`;
-
+ debugger
if (fourOhFour) {
expect(fixture.pathExists(htmlFile)).to.be.false;
return;
From bd2c39c47f71de8e57834865e0636370091fbb10 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Tue, 28 Feb 2023 08:59:04 +0000
Subject: [PATCH 04/37] delete redundent code
---
packages/astro/package.json | 4 +---
.../astro/test/fixtures/unused-slot/src/components/Card.astro | 1 -
packages/astro/test/routing-priority.test.js | 3 +--
3 files changed, 2 insertions(+), 6 deletions(-)
diff --git a/packages/astro/package.json b/packages/astro/package.json
index 8bd3a47c51d2..44da301e6919 100644
--- a/packages/astro/package.json
+++ b/packages/astro/package.json
@@ -91,9 +91,7 @@
"dev": "astro-scripts dev --prebuild \"src/runtime/server/astro-island.ts\" --prebuild \"src/runtime/client/{idle,load,media,only,visible}.ts\" \"src/**/*.ts\"",
"postbuild": "astro-scripts copy \"src/**/*.astro\"",
"benchmark": "node test/benchmark/dev.bench.js && node test/benchmark/build.bench.js",
- "test:unit": "mocha --exit --timeout 30000 ./test/units/**/*.test.js",
- "test:1": "mocha --exit --timeout 30000 ./test/routing-priority.test.js",
-
+ "test:unit": "mocha --exit --timeout 30000 ./test/units/**/*.test.js",
"test:unit:match": "mocha --exit --timeout 30000 ./test/units/**/*.test.js -g",
"test": "pnpm run test:unit && mocha --exit --timeout 20000 --ignore **/lit-element.test.js && mocha --timeout 20000 **/lit-element.test.js",
"test:match": "mocha --timeout 20000 -g",
diff --git a/packages/astro/test/fixtures/unused-slot/src/components/Card.astro b/packages/astro/test/fixtures/unused-slot/src/components/Card.astro
index 61fafb04c01e..c77e31672f4c 100644
--- a/packages/astro/test/fixtures/unused-slot/src/components/Card.astro
+++ b/packages/astro/test/fixtures/unused-slot/src/components/Card.astro
@@ -5,7 +5,6 @@ export interface Props {
href: string,
}
const {href, title, body} = Astro.props;
-debugger;
---
diff --git a/packages/astro/test/routing-priority.test.js b/packages/astro/test/routing-priority.test.js
index e7c4f0612c1b..fafe9906ba15 100644
--- a/packages/astro/test/routing-priority.test.js
+++ b/packages/astro/test/routing-priority.test.js
@@ -148,8 +148,7 @@ describe('Routing priority', () => {
const isEndpoint = htmlMatch && !h1 && !p;
it(description, async () => {
- const htmlFile = isEndpoint ? url : `${appendForwardSlash(url)}index.html`;
- debugger
+ const htmlFile = isEndpoint ? url : `${appendForwardSlash(url)}index.html`
if (fourOhFour) {
expect(fixture.pathExists(htmlFile)).to.be.false;
return;
From 832925a55f2cd5016220ccdb1f50e27d16759b94 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Tue, 28 Feb 2023 09:00:25 +0000
Subject: [PATCH 05/37] delete blank
---
packages/astro/package.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/astro/package.json b/packages/astro/package.json
index 44da301e6919..339bd8d5d2eb 100644
--- a/packages/astro/package.json
+++ b/packages/astro/package.json
@@ -91,7 +91,7 @@
"dev": "astro-scripts dev --prebuild \"src/runtime/server/astro-island.ts\" --prebuild \"src/runtime/client/{idle,load,media,only,visible}.ts\" \"src/**/*.ts\"",
"postbuild": "astro-scripts copy \"src/**/*.astro\"",
"benchmark": "node test/benchmark/dev.bench.js && node test/benchmark/build.bench.js",
- "test:unit": "mocha --exit --timeout 30000 ./test/units/**/*.test.js",
+ "test:unit": "mocha --exit --timeout 30000 ./test/units/**/*.test.js",
"test:unit:match": "mocha --exit --timeout 30000 ./test/units/**/*.test.js -g",
"test": "pnpm run test:unit && mocha --exit --timeout 20000 --ignore **/lit-element.test.js && mocha --timeout 20000 **/lit-element.test.js",
"test:match": "mocha --timeout 20000 -g",
From e2180276333249d73f2e2ed81bdf2cce3ab30141 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Tue, 28 Feb 2023 09:47:49 +0000
Subject: [PATCH 06/37] better detect file
---
packages/astro/src/core/build/common.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/astro/src/core/build/common.ts b/packages/astro/src/core/build/common.ts
index e1e63f146d7c..2369bb3a6b63 100644
--- a/packages/astro/src/core/build/common.ts
+++ b/packages/astro/src/core/build/common.ts
@@ -29,7 +29,7 @@ export function getOutFolder(
case 'page':
switch (astroConfig.build.format) {
case 'directory': {
- if (pathname.endsWith(PAGEHOMENAME)) {
+ if (npath.basename(pathname) === PAGEHOMENAME) {
return new URL(
'.' + appendForwardSlash(npath.dirname(pathname.slice(0, -PAGEHOMENAME.length + 1))),
outRoot
From de2fe25ec7cbfb48ee53144812ce8ad816f5468f Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Wed, 1 Mar 2023 01:51:54 +0000
Subject: [PATCH 07/37] fix warn message
---
packages/astro/src/core/routing/validation.ts | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/packages/astro/src/core/routing/validation.ts b/packages/astro/src/core/routing/validation.ts
index 047a5b8923ef..151b3792fe13 100644
--- a/packages/astro/src/core/routing/validation.ts
+++ b/packages/astro/src/core/routing/validation.ts
@@ -83,12 +83,13 @@ export function validateGetStaticPathsResult(
}
// TODO: Replace those with errors? They technically don't crash the build, but users might miss the warning. - erika, 2022-11-07
+ // Deleting the undefined judgment is for users who have used undefined before 2023-3-1
for (const [key, val] of Object.entries(pathObject.params)) {
- if (!(typeof val === 'undefined' || typeof val === 'string' || typeof val === 'number')) {
+ if (!(typeof val === 'string' || typeof val === 'number')) {
warn(
logging,
'getStaticPaths',
- `invalid path param: ${key}. A string, number or undefined value was expected, but got \`${JSON.stringify(
+ `invalid path param: ${key}. A string, number value was expected, but got \`${JSON.stringify(
val
)}\`.`
);
From 5bd09e9cf370ec0df62c2a45003d924342fba650 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Wed, 1 Mar 2023 02:15:17 +0000
Subject: [PATCH 08/37] add test about endpoints
---
packages/astro/package.json | 1 +
.../src/pages/api/example/[...slug].ts | 17 +++++++++++++++++
packages/astro/test/routing-priority.test.js | 10 ++++++++++
3 files changed, 28 insertions(+)
create mode 100644 packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
diff --git a/packages/astro/package.json b/packages/astro/package.json
index 339bd8d5d2eb..6b1969dd2919 100644
--- a/packages/astro/package.json
+++ b/packages/astro/package.json
@@ -92,6 +92,7 @@
"postbuild": "astro-scripts copy \"src/**/*.astro\"",
"benchmark": "node test/benchmark/dev.bench.js && node test/benchmark/build.bench.js",
"test:unit": "mocha --exit --timeout 30000 ./test/units/**/*.test.js",
+ "test:1": "mocha --exit --timeout 30000 ./test/routing-priority.test.js",
"test:unit:match": "mocha --exit --timeout 30000 ./test/units/**/*.test.js -g",
"test": "pnpm run test:unit && mocha --exit --timeout 20000 --ignore **/lit-element.test.js && mocha --timeout 20000 **/lit-element.test.js",
"test:match": "mocha --timeout 20000 -g",
diff --git a/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts b/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
new file mode 100644
index 000000000000..8c569bfe094c
--- /dev/null
+++ b/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
@@ -0,0 +1,17 @@
+import type { APIRoute } from "astro";
+
+const slugs = ["one", 'index'];
+
+export const prerender = true;
+
+export const get: APIRoute = ({ params }) => {
+ return {
+ body: JSON.stringify({
+ slug: params.slug || "index",
+ }),
+ };
+};
+
+export function getStaticPaths() {
+ return slugs.map((u) => ({ params: { slug: u } }));
+}
diff --git a/packages/astro/test/routing-priority.test.js b/packages/astro/test/routing-priority.test.js
index fafe9906ba15..6c4222c303cc 100644
--- a/packages/astro/test/routing-priority.test.js
+++ b/packages/astro/test/routing-priority.test.js
@@ -117,6 +117,16 @@ const routes = [
url: '/api/catch/a.json',
htmlMatch: JSON.stringify({ path: 'a' }),
},
+ {
+ description: 'matches /api/example/index',
+ url: '/api/example/index',
+ htmlMatch: JSON.stringify({slug:"index" }),
+ },
+ {
+ description: 'matches /api/example/one',
+ url: '/api/example/one',
+ htmlMatch: JSON.stringify({slug:"one" }),
+ },
{
description: 'matches /api/catch/b/c.json to api/catch/[...slug].json.ts',
url: '/api/catch/b/c.json',
From b9b943ec5c4c971c50a3977c41f47df22a76c388 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Thu, 2 Mar 2023 01:43:21 +0000
Subject: [PATCH 09/37] code come back
---
packages/astro/package.json | 1 -
packages/astro/src/core/build/common.ts | 7 -------
packages/astro/src/core/routing/params.ts | 3 +--
packages/astro/src/core/routing/validation.ts | 5 ++---
4 files changed, 3 insertions(+), 13 deletions(-)
diff --git a/packages/astro/package.json b/packages/astro/package.json
index 6b1969dd2919..339bd8d5d2eb 100644
--- a/packages/astro/package.json
+++ b/packages/astro/package.json
@@ -92,7 +92,6 @@
"postbuild": "astro-scripts copy \"src/**/*.astro\"",
"benchmark": "node test/benchmark/dev.bench.js && node test/benchmark/build.bench.js",
"test:unit": "mocha --exit --timeout 30000 ./test/units/**/*.test.js",
- "test:1": "mocha --exit --timeout 30000 ./test/routing-priority.test.js",
"test:unit:match": "mocha --exit --timeout 30000 ./test/units/**/*.test.js -g",
"test": "pnpm run test:unit && mocha --exit --timeout 20000 --ignore **/lit-element.test.js && mocha --timeout 20000 **/lit-element.test.js",
"test:match": "mocha --timeout 20000 -g",
diff --git a/packages/astro/src/core/build/common.ts b/packages/astro/src/core/build/common.ts
index 2369bb3a6b63..74be830f0356 100644
--- a/packages/astro/src/core/build/common.ts
+++ b/packages/astro/src/core/build/common.ts
@@ -5,7 +5,6 @@ import { appendForwardSlash } from '../../core/path.js';
const STATUS_CODE_PAGES = new Set(['/404', '/500']);
const FALLBACK_OUT_DIR_NAME = './.astro/';
-const PAGEHOMENAME = 'index';
function getOutRoot(astroConfig: AstroConfig): URL {
if (astroConfig.output === 'static') {
@@ -29,12 +28,6 @@ export function getOutFolder(
case 'page':
switch (astroConfig.build.format) {
case 'directory': {
- if (npath.basename(pathname) === PAGEHOMENAME) {
- return new URL(
- '.' + appendForwardSlash(npath.dirname(pathname.slice(0, -PAGEHOMENAME.length + 1))),
- outRoot
- );
- }
if (STATUS_CODE_PAGES.has(pathname)) {
return new URL('.' + appendForwardSlash(npath.dirname(pathname)), outRoot);
}
diff --git a/packages/astro/src/core/routing/params.ts b/packages/astro/src/core/routing/params.ts
index a5e5722b33c8..6a822861fecf 100644
--- a/packages/astro/src/core/routing/params.ts
+++ b/packages/astro/src/core/routing/params.ts
@@ -32,8 +32,7 @@ export function stringifyParams(params: GetStaticPathsItem['params'], routeCompo
const validatedParams = Object.entries(params).reduce((acc, next) => {
validateGetStaticPathsParameter(next, routeComponent);
const [key, value] = next;
- // default to 'index' if the param is empty in the dev environment
- acc[key] = !value ? 'index' : value?.toString();
+ acc[key] = value?.toString();
return acc;
}, {} as Params);
diff --git a/packages/astro/src/core/routing/validation.ts b/packages/astro/src/core/routing/validation.ts
index 151b3792fe13..047a5b8923ef 100644
--- a/packages/astro/src/core/routing/validation.ts
+++ b/packages/astro/src/core/routing/validation.ts
@@ -83,13 +83,12 @@ export function validateGetStaticPathsResult(
}
// TODO: Replace those with errors? They technically don't crash the build, but users might miss the warning. - erika, 2022-11-07
- // Deleting the undefined judgment is for users who have used undefined before 2023-3-1
for (const [key, val] of Object.entries(pathObject.params)) {
- if (!(typeof val === 'string' || typeof val === 'number')) {
+ if (!(typeof val === 'undefined' || typeof val === 'string' || typeof val === 'number')) {
warn(
logging,
'getStaticPaths',
- `invalid path param: ${key}. A string, number value was expected, but got \`${JSON.stringify(
+ `invalid path param: ${key}. A string, number or undefined value was expected, but got \`${JSON.stringify(
val
)}\`.`
);
From 4c9e5df9c2df1c2aff0124965a3e7ed610acf1e8 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Thu, 2 Mar 2023 03:08:18 +0000
Subject: [PATCH 10/37] throw an error with endpoints
---
packages/astro/src/core/errors/errors-data.ts | 25 +++++++++++++++++++
packages/astro/src/core/render/route-cache.ts | 8 +++++-
packages/astro/src/core/routing/validation.ts | 18 +++++++++++++
.../src/pages/api/example/[...slug].ts | 2 +-
.../src/pages/slug-index/[...slug].astro | 22 ----------------
packages/astro/test/routing-priority.test.js | 6 -----
6 files changed, 51 insertions(+), 30 deletions(-)
delete mode 100644 packages/astro/test/fixtures/routing-priority/src/pages/slug-index/[...slug].astro
diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts
index c10748b23bcb..7ffa3d75d739 100644
--- a/packages/astro/src/core/errors/errors-data.ts
+++ b/packages/astro/src/core/errors/errors-data.ts
@@ -454,6 +454,31 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
`[paginate()] page number param \`${paramName}\` not found in your filepath.`,
hint: 'Rename your file to `[page].astro` or `[...page].astro`.',
},
+ /**
+ * @docs
+ * @see
+ * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths)
+ * - [`params`](https://docs.astro.build/en/reference/api-reference/#params)
+ * @description
+ * endpoints `getStaticPaths`'s return value must be an array of objects that can't include `undefined` .
+ *
+ * ```ts title="api/[...slug].ts"
+ * export async function getStaticPaths() {
+ * return [ // <-- Array
+ * { params: { slug: undefined } } error here,
+ * { params: { slug: "about" } }
+ * ];
+ *}
+ * ```
+ */
+ InvalidGetEndpointsPathParam: {
+ title: 'invalid path param when the endponits',
+ code: 3022,
+ message: (paramkey, paramVal) =>
+ `invalid path param: ${paramkey} path. A string, number value was expected, got \`${paramVal}\``,
+ hint: 'See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.',
+ },
+
// No headings here, that way Vite errors are merged with Astro ones in the docs, which makes more sense to users.
// Vite Errors - 4xxx
/**
diff --git a/packages/astro/src/core/render/route-cache.ts b/packages/astro/src/core/render/route-cache.ts
index e6ef87107dfc..4e65b394e3b6 100644
--- a/packages/astro/src/core/render/route-cache.ts
+++ b/packages/astro/src/core/render/route-cache.ts
@@ -11,7 +11,7 @@ import { AstroError, AstroErrorData } from '../errors/index.js';
import { debug, LogOptions, warn } from '../logger/core.js';
import { stringifyParams } from '../routing/params.js';
-import { validateDynamicRouteModule, validateGetStaticPathsResult } from '../routing/validation.js';
+import { validateDynamicRouteModule, validateGetStaticPathsResult, validateUndefineWhenEndpoints } from '../routing/validation.js';
import { generatePaginateFunction } from './paginate.js';
interface CallGetStaticPathsOptions {
@@ -49,6 +49,12 @@ export async function callGetStaticPaths({
},
});
+ // fix bug: https://github.com/withastro/astro/pull/6353
+ // [...slug].astro (with undefined) and index.astro has conflict behavior
+ if(route.type === 'endpoint'){
+ validateUndefineWhenEndpoints(staticPaths, route)
+ }
+
// Flatten the array before validating the content, otherwise users using `.map` will run into errors
if (Array.isArray(staticPaths)) {
staticPaths = staticPaths.flat();
diff --git a/packages/astro/src/core/routing/validation.ts b/packages/astro/src/core/routing/validation.ts
index 047a5b8923ef..b967899bf996 100644
--- a/packages/astro/src/core/routing/validation.ts
+++ b/packages/astro/src/core/routing/validation.ts
@@ -103,3 +103,21 @@ export function validateGetStaticPathsResult(
}
});
}
+
+// fix bug: https://github.com/withastro/astro/pull/6353
+// [...slug].astro (with undefined) and index.astro has conflict behavior
+export function validateUndefineWhenEndpoints(result: GetStaticPathsResult, route: RouteData) {
+ result.forEach((pathObject) => {
+ for (const [key, val] of Object.entries(pathObject.params)) {
+ if (typeof val === 'undefined') {
+ throw new AstroError({
+ ...AstroErrorData.InvalidGetEndpointsPathParam,
+ message: AstroErrorData.InvalidGetEndpointsPathParam.message(key, typeof val),
+ location: {
+ file: route.component,
+ },
+ });
+ }
+ }
+ });
+}
diff --git a/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts b/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
index 8c569bfe094c..f797b37e05c9 100644
--- a/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
+++ b/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
@@ -1,6 +1,6 @@
import type { APIRoute } from "astro";
-const slugs = ["one", 'index'];
+const slugs = ["one", "index"];
export const prerender = true;
diff --git a/packages/astro/test/fixtures/routing-priority/src/pages/slug-index/[...slug].astro b/packages/astro/test/fixtures/routing-priority/src/pages/slug-index/[...slug].astro
deleted file mode 100644
index 0bfcf4b3d3ff..000000000000
--- a/packages/astro/test/fixtures/routing-priority/src/pages/slug-index/[...slug].astro
+++ /dev/null
@@ -1,22 +0,0 @@
----
-export function getStaticPaths() {
- return [{
- params: { slug: "index" },
- }, {
- params: { slug: 'potato' },
- }]
-}
-const { slug } = Astro.params
----
-
-
-
-
-
- {slug}
-
-
- slug-index/[...slug].astro
- slug: {slug || 'index'}
-
-
diff --git a/packages/astro/test/routing-priority.test.js b/packages/astro/test/routing-priority.test.js
index 6c4222c303cc..3a256256ae5c 100644
--- a/packages/astro/test/routing-priority.test.js
+++ b/packages/astro/test/routing-priority.test.js
@@ -95,12 +95,6 @@ const routes = [
h1: '[id].astro',
p: 'injected-2',
},
- {
- description: 'matches /slug-index to slug-index/[...slug].astro',
- url: '/slug-index',
- h1: 'slug-index/[...slug].astro',
- p: 'slug: index',
- },
{
description: 'matches /empty-slug to empty-slug/[...slug].astro',
url: '/empty-slug',
From 850aee93f31a401ecff4e76003ee5ee044ba098d Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Thu, 2 Mar 2023 08:39:57 +0000
Subject: [PATCH 11/37] fix wouldnt create file when miss json
---
.../astro/src/core/routing/manifest/create.ts | 16 +++++++++++++++-
packages/astro/test/routing-priority.test.js | 4 ++--
2 files changed, 17 insertions(+), 3 deletions(-)
diff --git a/packages/astro/src/core/routing/manifest/create.ts b/packages/astro/src/core/routing/manifest/create.ts
index 8c7514969e02..8223744025b3 100644
--- a/packages/astro/src/core/routing/manifest/create.ts
+++ b/packages/astro/src/core/routing/manifest/create.ts
@@ -203,6 +203,12 @@ function injectedRouteToItem(
};
}
+// https://github.com/withastro/astro/pull/6353
+// Suggesting for don't create a file when endpoint mode.
+function vaildateEndpointExtention(segments: RoutePart[][]) {
+ return segments.some((item) => item.some((v) => v.content === '.json'));
+}
+
export interface CreateRouteManifestParams {
/** Astro Settings object */
settings: AstroSettings;
@@ -226,7 +232,8 @@ export function createRouteManifest(
]);
const validEndpointExtensions: Set = new Set(['.js', '.ts']);
const localFs = fsMod ?? nodeFs;
-
+ // https://github.com/withastro/astro/pull/6353
+ // Suggesting for don't create a file when endpoint mode.
function walk(
fs: typeof nodeFs,
dir: string,
@@ -323,6 +330,13 @@ export function createRouteManifest(
.map(([{ dynamic, content }]) => (dynamic ? `[${content}]` : content))
.join('/')}`.toLowerCase();
+ // https://github.com/withastro/astro/pull/6353
+ // Suggesting for don't create a file when endpoint mode.
+ if (!vaildateEndpointExtention(segments) && !item.isPage) {
+ warn(logging, 'endpoint', `Please write the correct name, your ${item.file} file name is missing in ‘json’`)
+ return;
+ }
+
routes.push({
route,
type: item.isPage ? 'page' : 'endpoint',
diff --git a/packages/astro/test/routing-priority.test.js b/packages/astro/test/routing-priority.test.js
index 3a256256ae5c..51723a25f08c 100644
--- a/packages/astro/test/routing-priority.test.js
+++ b/packages/astro/test/routing-priority.test.js
@@ -114,12 +114,12 @@ const routes = [
{
description: 'matches /api/example/index',
url: '/api/example/index',
- htmlMatch: JSON.stringify({slug:"index" }),
+ fourOhFour: true
},
{
description: 'matches /api/example/one',
url: '/api/example/one',
- htmlMatch: JSON.stringify({slug:"one" }),
+ fourOhFour: true
},
{
description: 'matches /api/catch/b/c.json to api/catch/[...slug].json.ts',
From 893dc1effd2fa1b2f4f94b48ec7145a0d013c95f Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Thu, 2 Mar 2023 09:28:12 +0000
Subject: [PATCH 12/37] fix focused on ts
---
packages/astro/src/core/routing/manifest/create.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/astro/src/core/routing/manifest/create.ts b/packages/astro/src/core/routing/manifest/create.ts
index 8223744025b3..a4d086981ded 100644
--- a/packages/astro/src/core/routing/manifest/create.ts
+++ b/packages/astro/src/core/routing/manifest/create.ts
@@ -332,7 +332,7 @@ export function createRouteManifest(
// https://github.com/withastro/astro/pull/6353
// Suggesting for don't create a file when endpoint mode.
- if (!vaildateEndpointExtention(segments) && !item.isPage) {
+ if (!vaildateEndpointExtention(segments) && !item.isPage && validEndpointExtensions.has(item.ext)) {
warn(logging, 'endpoint', `Please write the correct name, your ${item.file} file name is missing in ‘json’`)
return;
}
From 61f408a4106e42640b95d63be7edc7a29fb9896e Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Thu, 2 Mar 2023 10:50:07 +0000
Subject: [PATCH 13/37] After testing, the *.ts files under the endpoint cannot
be ignored
---
packages/astro/src/core/render/core.ts | 13 +++++++++++++
packages/astro/src/core/render/route-cache.ts | 8 +-------
.../astro/src/core/routing/manifest/create.ts | 16 +---------------
packages/astro/src/core/routing/validation.ts | 18 ------------------
.../src/pages/api/example/[...slug].ts | 17 -----------------
packages/astro/test/routing-priority.test.js | 13 ++-----------
6 files changed, 17 insertions(+), 68 deletions(-)
delete mode 100644 packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index 862ada7c8b9b..a9eb08f0d676 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -35,6 +35,19 @@ export async function getParamsAndProps(
const paramsMatch = route.pattern.exec(pathname);
if (paramsMatch) {
params = getParams(route.params)(paramsMatch);
+ const [key, val] = Object.entries(params);
+
+ // fix bug: https://github.com/withastro/astro/pull/6353
+ // [...slug].astro (with undefined) and index.astro has conflict behavior
+ if (route.type === 'endpoint' && typeof val === 'undefined') {
+ throw new AstroError({
+ ...AstroErrorData.InvalidGetEndpointsPathParam,
+ message: AstroErrorData.InvalidGetEndpointsPathParam.message(key, typeof val),
+ location: {
+ file: route.component,
+ },
+ });
+ }
}
}
let routeCacheEntry = routeCache.get(route);
diff --git a/packages/astro/src/core/render/route-cache.ts b/packages/astro/src/core/render/route-cache.ts
index 4e65b394e3b6..e6ef87107dfc 100644
--- a/packages/astro/src/core/render/route-cache.ts
+++ b/packages/astro/src/core/render/route-cache.ts
@@ -11,7 +11,7 @@ import { AstroError, AstroErrorData } from '../errors/index.js';
import { debug, LogOptions, warn } from '../logger/core.js';
import { stringifyParams } from '../routing/params.js';
-import { validateDynamicRouteModule, validateGetStaticPathsResult, validateUndefineWhenEndpoints } from '../routing/validation.js';
+import { validateDynamicRouteModule, validateGetStaticPathsResult } from '../routing/validation.js';
import { generatePaginateFunction } from './paginate.js';
interface CallGetStaticPathsOptions {
@@ -49,12 +49,6 @@ export async function callGetStaticPaths({
},
});
- // fix bug: https://github.com/withastro/astro/pull/6353
- // [...slug].astro (with undefined) and index.astro has conflict behavior
- if(route.type === 'endpoint'){
- validateUndefineWhenEndpoints(staticPaths, route)
- }
-
// Flatten the array before validating the content, otherwise users using `.map` will run into errors
if (Array.isArray(staticPaths)) {
staticPaths = staticPaths.flat();
diff --git a/packages/astro/src/core/routing/manifest/create.ts b/packages/astro/src/core/routing/manifest/create.ts
index a4d086981ded..8c7514969e02 100644
--- a/packages/astro/src/core/routing/manifest/create.ts
+++ b/packages/astro/src/core/routing/manifest/create.ts
@@ -203,12 +203,6 @@ function injectedRouteToItem(
};
}
-// https://github.com/withastro/astro/pull/6353
-// Suggesting for don't create a file when endpoint mode.
-function vaildateEndpointExtention(segments: RoutePart[][]) {
- return segments.some((item) => item.some((v) => v.content === '.json'));
-}
-
export interface CreateRouteManifestParams {
/** Astro Settings object */
settings: AstroSettings;
@@ -232,8 +226,7 @@ export function createRouteManifest(
]);
const validEndpointExtensions: Set = new Set(['.js', '.ts']);
const localFs = fsMod ?? nodeFs;
- // https://github.com/withastro/astro/pull/6353
- // Suggesting for don't create a file when endpoint mode.
+
function walk(
fs: typeof nodeFs,
dir: string,
@@ -330,13 +323,6 @@ export function createRouteManifest(
.map(([{ dynamic, content }]) => (dynamic ? `[${content}]` : content))
.join('/')}`.toLowerCase();
- // https://github.com/withastro/astro/pull/6353
- // Suggesting for don't create a file when endpoint mode.
- if (!vaildateEndpointExtention(segments) && !item.isPage && validEndpointExtensions.has(item.ext)) {
- warn(logging, 'endpoint', `Please write the correct name, your ${item.file} file name is missing in ‘json’`)
- return;
- }
-
routes.push({
route,
type: item.isPage ? 'page' : 'endpoint',
diff --git a/packages/astro/src/core/routing/validation.ts b/packages/astro/src/core/routing/validation.ts
index b967899bf996..047a5b8923ef 100644
--- a/packages/astro/src/core/routing/validation.ts
+++ b/packages/astro/src/core/routing/validation.ts
@@ -103,21 +103,3 @@ export function validateGetStaticPathsResult(
}
});
}
-
-// fix bug: https://github.com/withastro/astro/pull/6353
-// [...slug].astro (with undefined) and index.astro has conflict behavior
-export function validateUndefineWhenEndpoints(result: GetStaticPathsResult, route: RouteData) {
- result.forEach((pathObject) => {
- for (const [key, val] of Object.entries(pathObject.params)) {
- if (typeof val === 'undefined') {
- throw new AstroError({
- ...AstroErrorData.InvalidGetEndpointsPathParam,
- message: AstroErrorData.InvalidGetEndpointsPathParam.message(key, typeof val),
- location: {
- file: route.component,
- },
- });
- }
- }
- });
-}
diff --git a/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts b/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
deleted file mode 100644
index f797b37e05c9..000000000000
--- a/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import type { APIRoute } from "astro";
-
-const slugs = ["one", "index"];
-
-export const prerender = true;
-
-export const get: APIRoute = ({ params }) => {
- return {
- body: JSON.stringify({
- slug: params.slug || "index",
- }),
- };
-};
-
-export function getStaticPaths() {
- return slugs.map((u) => ({ params: { slug: u } }));
-}
diff --git a/packages/astro/test/routing-priority.test.js b/packages/astro/test/routing-priority.test.js
index 51723a25f08c..586978d4f4cd 100644
--- a/packages/astro/test/routing-priority.test.js
+++ b/packages/astro/test/routing-priority.test.js
@@ -111,16 +111,6 @@ const routes = [
url: '/api/catch/a.json',
htmlMatch: JSON.stringify({ path: 'a' }),
},
- {
- description: 'matches /api/example/index',
- url: '/api/example/index',
- fourOhFour: true
- },
- {
- description: 'matches /api/example/one',
- url: '/api/example/one',
- fourOhFour: true
- },
{
description: 'matches /api/catch/b/c.json to api/catch/[...slug].json.ts',
url: '/api/catch/b/c.json',
@@ -152,7 +142,8 @@ describe('Routing priority', () => {
const isEndpoint = htmlMatch && !h1 && !p;
it(description, async () => {
- const htmlFile = isEndpoint ? url : `${appendForwardSlash(url)}index.html`
+ const htmlFile = isEndpoint ? url : `${appendForwardSlash(url)}index.html`;
+
if (fourOhFour) {
expect(fixture.pathExists(htmlFile)).to.be.false;
return;
From f6452f12305ecd778881d984b2e36ba61cec5cd6 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Thu, 2 Mar 2023 11:14:40 +0000
Subject: [PATCH 14/37] fix object bug
---
packages/astro/src/core/render/core.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index a9eb08f0d676..948d227f5127 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -35,7 +35,7 @@ export async function getParamsAndProps(
const paramsMatch = route.pattern.exec(pathname);
if (paramsMatch) {
params = getParams(route.params)(paramsMatch);
- const [key, val] = Object.entries(params);
+ const [[key, val]] = Object.entries(params);
// fix bug: https://github.com/withastro/astro/pull/6353
// [...slug].astro (with undefined) and index.astro has conflict behavior
From d2ee4bb2e46df91571bcc8649c0941b4f204921f Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Fri, 3 Mar 2023 07:10:40 +0000
Subject: [PATCH 15/37] add special a test
---
packages/astro/src/core/render/core.ts | 2 +-
.../test/astro-conflict-behavior.test.js | 54 +++++++++++++++++++
.../astro-conflict-behavior/astro.config.mjs | 11 ++++
.../astro-conflict-behavior/package.json | 9 ++++
.../src/pages/index.astro | 12 +++++
.../src/pages/index/[...slug].astro | 13 +++++
6 files changed, 100 insertions(+), 1 deletion(-)
create mode 100644 packages/astro/test/astro-conflict-behavior.test.js
create mode 100644 packages/astro/test/fixtures/astro-conflict-behavior/astro.config.mjs
create mode 100644 packages/astro/test/fixtures/astro-conflict-behavior/package.json
create mode 100644 packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index.astro
create mode 100644 packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index/[...slug].astro
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index 948d227f5127..e1e209990ad7 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -39,7 +39,7 @@ export async function getParamsAndProps(
// fix bug: https://github.com/withastro/astro/pull/6353
// [...slug].astro (with undefined) and index.astro has conflict behavior
- if (route.type === 'endpoint' && typeof val === 'undefined') {
+ if ((route.type === 'endpoint' || mod.prerender) && typeof val === 'undefined') {
throw new AstroError({
...AstroErrorData.InvalidGetEndpointsPathParam,
message: AstroErrorData.InvalidGetEndpointsPathParam.message(key, typeof val),
diff --git a/packages/astro/test/astro-conflict-behavior.test.js b/packages/astro/test/astro-conflict-behavior.test.js
new file mode 100644
index 000000000000..d61e8841fe2f
--- /dev/null
+++ b/packages/astro/test/astro-conflict-behavior.test.js
@@ -0,0 +1,54 @@
+import { expect } from 'chai';
+import { loadFixture } from './test-utils.js';
+import { load as cheerioLoad } from 'cheerio';
+
+
+describe('astro-conflict-behavior', () => {
+ describe('build', () => {
+ let fixture;
+ let errorMsg
+
+ before(async () => {
+
+ fixture = await loadFixture({
+ root: './fixtures/astro-conflict-behavior/',
+ });
+ try {
+ await fixture.build();
+ } catch (error) {
+ errorMsg = error
+ }
+
+ });
+ it('skiping generate an file when set up undefined in getStaticPaths when pro the environment', async () => {
+ const html = await fixture.pathExists('/index');
+ expect(html).to.be.false;
+ expect(errorMsg.errorCode).to.equal(3022)
+ });
+ });
+
+ describe('dev', () => {
+ let fixture;
+ let devServer;
+ before(async () => {
+
+ fixture = await loadFixture({
+ root: './fixtures/astro-conflict-behavior/',
+ });
+
+ devServer = await fixture.startDevServer();
+ });
+
+ after(async () => {
+ await devServer.stop();
+ });
+ it('skiping generate an file when set up undefined in getStaticPaths when dev the environmen', async () => {
+ const html = await fixture
+ .fetch('/index')
+ .then((res) => res.text());
+ const $ = cheerioLoad(html);
+ expect($('title').text()).to.equal('InvalidGetEndpointsPathParam');
+ });
+
+ });
+});
diff --git a/packages/astro/test/fixtures/astro-conflict-behavior/astro.config.mjs b/packages/astro/test/fixtures/astro-conflict-behavior/astro.config.mjs
new file mode 100644
index 000000000000..7126fddda8c5
--- /dev/null
+++ b/packages/astro/test/fixtures/astro-conflict-behavior/astro.config.mjs
@@ -0,0 +1,11 @@
+import { defineConfig } from 'astro/config';
+import node from "@astrojs/node";
+
+// https://astro.build/config
+export default defineConfig({
+ output: "server",
+ adapter: node({mode:'standalone'}),
+ build: {
+ format: 'file'
+ }
+});
diff --git a/packages/astro/test/fixtures/astro-conflict-behavior/package.json b/packages/astro/test/fixtures/astro-conflict-behavior/package.json
new file mode 100644
index 000000000000..e3e770ba6191
--- /dev/null
+++ b/packages/astro/test/fixtures/astro-conflict-behavior/package.json
@@ -0,0 +1,9 @@
+{
+ "name": "@test/astro-conflict-behavior",
+ "version": "0.0.0",
+ "private": true,
+ "dependencies": {
+ "@astrojs/node": "workspace:*",
+ "astro": "workspace:*"
+ }
+}
diff --git a/packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index.astro b/packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index.astro
new file mode 100644
index 000000000000..5c0680950036
--- /dev/null
+++ b/packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index.astro
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+ Document
+
+
+ test
+
+
diff --git a/packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index/[...slug].astro b/packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index/[...slug].astro
new file mode 100644
index 000000000000..f5416480dddd
--- /dev/null
+++ b/packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index/[...slug].astro
@@ -0,0 +1,13 @@
+---
+export const prerender = true;
+
+export function getStaticPaths() {
+ const slugs = ["one", undefined];
+
+ return slugs.map((u) => ({ params: { slug: u } }));
+}
+
+const { slug } = Astro.params;
+---
+
+{slug || "index"}
From c342a1458b3de60cdab9a389f8676b844a4ec6b3 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Fri, 3 Mar 2023 07:11:14 +0000
Subject: [PATCH 16/37] add special a test
---
pnpm-lock.yaml | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b548db06ac2d..2ebe09bed34a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1283,6 +1283,14 @@ importers:
dependencies:
astro: link:../../..
+ packages/astro/test/fixtures/astro-conflict-behavior:
+ specifiers:
+ '@astrojs/node': workspace:*
+ astro: workspace:*
+ dependencies:
+ '@astrojs/node': link:../../../../integrations/node
+ astro: link:../../..
+
packages/astro/test/fixtures/astro-cookies:
specifiers:
astro: workspace:*
From f99a6fc7000bb9da5e25daf46462295697aa1353 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Fri, 3 Mar 2023 07:49:01 +0000
Subject: [PATCH 17/37] optimize tips
---
packages/astro/src/core/errors/errors-data.ts | 2 +-
packages/astro/src/core/render/core.ts | 4 +++-
2 files changed, 4 insertions(+), 2 deletions(-)
diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts
index 7ffa3d75d739..d8611b7c4c26 100644
--- a/packages/astro/src/core/errors/errors-data.ts
+++ b/packages/astro/src/core/errors/errors-data.ts
@@ -472,7 +472,7 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
* ```
*/
InvalidGetEndpointsPathParam: {
- title: 'invalid path param when the endponits',
+ title: 'There can not use \'undefined\' in the getStaticPaths when the endpoint' ,
code: 3022,
message: (paramkey, paramVal) =>
`invalid path param: ${paramkey} path. A string, number value was expected, got \`${paramVal}\``,
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index e1e209990ad7..0e75ebacf897 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -39,7 +39,9 @@ export async function getParamsAndProps(
// fix bug: https://github.com/withastro/astro/pull/6353
// [...slug].astro (with undefined) and index.astro has conflict behavior
- if ((route.type === 'endpoint' || mod.prerender) && typeof val === 'undefined') {
+ // The [...slug].astro under the folder 'index' has set 'undefine' in getStaticPaths that
+ // it will replace the index.html outside when the build and format is file.
+ if ((route.type === 'endpoint' || route.route.endsWith('/index')) && typeof val === 'undefined') {
throw new AstroError({
...AstroErrorData.InvalidGetEndpointsPathParam,
message: AstroErrorData.InvalidGetEndpointsPathParam.message(key, typeof val),
From f4ce63977b24a93797609c552235ab6d0b2059d5 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Fri, 3 Mar 2023 08:21:54 +0000
Subject: [PATCH 18/37] fix error test
---
packages/astro/src/core/render/core.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index 0e75ebacf897..84566794c53d 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -41,7 +41,7 @@ export async function getParamsAndProps(
// [...slug].astro (with undefined) and index.astro has conflict behavior
// The [...slug].astro under the folder 'index' has set 'undefine' in getStaticPaths that
// it will replace the index.html outside when the build and format is file.
- if ((route.type === 'endpoint' || route.route.endsWith('/index')) && typeof val === 'undefined') {
+ if ((route.type === 'endpoint' || route.route.startsWith('/index')) && typeof val === 'undefined') {
throw new AstroError({
...AstroErrorData.InvalidGetEndpointsPathParam,
message: AstroErrorData.InvalidGetEndpointsPathParam.message(key, typeof val),
From 0d6522f3f9363dd07258127ba7468d3505543eb0 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Tue, 7 Mar 2023 01:58:30 +0000
Subject: [PATCH 19/37] tweak the condition in core file and delete test
---
packages/astro/src/core/render/core.ts | 14 ++---
.../test/astro-conflict-behavior.test.js | 54 -------------------
.../astro-conflict-behavior/astro.config.mjs | 11 ----
.../astro-conflict-behavior/package.json | 9 ----
.../src/pages/index.astro | 12 -----
.../src/pages/index/[...slug].astro | 13 -----
pnpm-lock.yaml | 8 ---
7 files changed, 3 insertions(+), 118 deletions(-)
delete mode 100644 packages/astro/test/astro-conflict-behavior.test.js
delete mode 100644 packages/astro/test/fixtures/astro-conflict-behavior/astro.config.mjs
delete mode 100644 packages/astro/test/fixtures/astro-conflict-behavior/package.json
delete mode 100644 packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index.astro
delete mode 100644 packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index/[...slug].astro
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index 84566794c53d..9c583897e9e8 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -1,5 +1,5 @@
import type { ComponentInstance, Params, Props, RouteData } from '../../@types/astro';
-import type { LogOptions } from '../logger/core.js';
+import { LogOptions, warn } from '../logger/core.js';
import type { RenderContext } from './context.js';
import type { Environment } from './environment.js';
@@ -35,20 +35,12 @@ export async function getParamsAndProps(
const paramsMatch = route.pattern.exec(pathname);
if (paramsMatch) {
params = getParams(route.params)(paramsMatch);
- const [[key, val]] = Object.entries(params);
-
// fix bug: https://github.com/withastro/astro/pull/6353
// [...slug].astro (with undefined) and index.astro has conflict behavior
// The [...slug].astro under the folder 'index' has set 'undefine' in getStaticPaths that
// it will replace the index.html outside when the build and format is file.
- if ((route.type === 'endpoint' || route.route.startsWith('/index')) && typeof val === 'undefined') {
- throw new AstroError({
- ...AstroErrorData.InvalidGetEndpointsPathParam,
- message: AstroErrorData.InvalidGetEndpointsPathParam.message(key, typeof val),
- location: {
- file: route.component,
- },
- });
+ if ((route.type === 'endpoint'||route.component.endsWith('astro')) && !mod.getStaticPaths) {
+ warn(logging, 'getStaticPaths', 'Under dynamic routing, please pay attention to the use of \'undefine\'')
}
}
}
diff --git a/packages/astro/test/astro-conflict-behavior.test.js b/packages/astro/test/astro-conflict-behavior.test.js
deleted file mode 100644
index d61e8841fe2f..000000000000
--- a/packages/astro/test/astro-conflict-behavior.test.js
+++ /dev/null
@@ -1,54 +0,0 @@
-import { expect } from 'chai';
-import { loadFixture } from './test-utils.js';
-import { load as cheerioLoad } from 'cheerio';
-
-
-describe('astro-conflict-behavior', () => {
- describe('build', () => {
- let fixture;
- let errorMsg
-
- before(async () => {
-
- fixture = await loadFixture({
- root: './fixtures/astro-conflict-behavior/',
- });
- try {
- await fixture.build();
- } catch (error) {
- errorMsg = error
- }
-
- });
- it('skiping generate an file when set up undefined in getStaticPaths when pro the environment', async () => {
- const html = await fixture.pathExists('/index');
- expect(html).to.be.false;
- expect(errorMsg.errorCode).to.equal(3022)
- });
- });
-
- describe('dev', () => {
- let fixture;
- let devServer;
- before(async () => {
-
- fixture = await loadFixture({
- root: './fixtures/astro-conflict-behavior/',
- });
-
- devServer = await fixture.startDevServer();
- });
-
- after(async () => {
- await devServer.stop();
- });
- it('skiping generate an file when set up undefined in getStaticPaths when dev the environmen', async () => {
- const html = await fixture
- .fetch('/index')
- .then((res) => res.text());
- const $ = cheerioLoad(html);
- expect($('title').text()).to.equal('InvalidGetEndpointsPathParam');
- });
-
- });
-});
diff --git a/packages/astro/test/fixtures/astro-conflict-behavior/astro.config.mjs b/packages/astro/test/fixtures/astro-conflict-behavior/astro.config.mjs
deleted file mode 100644
index 7126fddda8c5..000000000000
--- a/packages/astro/test/fixtures/astro-conflict-behavior/astro.config.mjs
+++ /dev/null
@@ -1,11 +0,0 @@
-import { defineConfig } from 'astro/config';
-import node from "@astrojs/node";
-
-// https://astro.build/config
-export default defineConfig({
- output: "server",
- adapter: node({mode:'standalone'}),
- build: {
- format: 'file'
- }
-});
diff --git a/packages/astro/test/fixtures/astro-conflict-behavior/package.json b/packages/astro/test/fixtures/astro-conflict-behavior/package.json
deleted file mode 100644
index e3e770ba6191..000000000000
--- a/packages/astro/test/fixtures/astro-conflict-behavior/package.json
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "name": "@test/astro-conflict-behavior",
- "version": "0.0.0",
- "private": true,
- "dependencies": {
- "@astrojs/node": "workspace:*",
- "astro": "workspace:*"
- }
-}
diff --git a/packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index.astro b/packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index.astro
deleted file mode 100644
index 5c0680950036..000000000000
--- a/packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index.astro
+++ /dev/null
@@ -1,12 +0,0 @@
-
-
-
-
-
-
- Document
-
-
- test
-
-
diff --git a/packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index/[...slug].astro b/packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index/[...slug].astro
deleted file mode 100644
index f5416480dddd..000000000000
--- a/packages/astro/test/fixtures/astro-conflict-behavior/src/pages/index/[...slug].astro
+++ /dev/null
@@ -1,13 +0,0 @@
----
-export const prerender = true;
-
-export function getStaticPaths() {
- const slugs = ["one", undefined];
-
- return slugs.map((u) => ({ params: { slug: u } }));
-}
-
-const { slug } = Astro.params;
----
-
-{slug || "index"}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index f4e00efd27a9..9f21215fb06e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1279,14 +1279,6 @@ importers:
dependencies:
astro: link:../../..
- packages/astro/test/fixtures/astro-conflict-behavior:
- specifiers:
- '@astrojs/node': workspace:*
- astro: workspace:*
- dependencies:
- '@astrojs/node': link:../../../../integrations/node
- astro: link:../../..
-
packages/astro/test/fixtures/astro-cookies:
specifiers:
astro: workspace:*
From 72b20a93ff4722b9f57bc6ec1084a54f56c8e38d Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Tue, 7 Mar 2023 02:56:37 +0000
Subject: [PATCH 20/37] add test
---
packages/astro/src/core/render/core.ts | 28 +++++++++++++++++--
packages/astro/src/core/util.ts | 8 ++++++
.../src/pages/api/example/[...slug].ts | 17 +++++++++++
packages/astro/test/routing-priority.test.js | 5 ++++
4 files changed, 55 insertions(+), 3 deletions(-)
create mode 100644 packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index 9c583897e9e8..2baae3039948 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -9,6 +9,7 @@ import { AstroError, AstroErrorData } from '../errors/index.js';
import { getParams } from '../routing/params.js';
import { createResult } from './result.js';
import { callGetStaticPaths, findPathItemByKey, RouteCache } from './route-cache.js';
+import { validateEndpointFileExt } from '../util';
interface GetParamsAndPropsOptions {
mod: ComponentInstance;
@@ -35,13 +36,34 @@ export async function getParamsAndProps(
const paramsMatch = route.pattern.exec(pathname);
if (paramsMatch) {
params = getParams(route.params)(paramsMatch);
+ const [[key, val]] = Object.entries(params)
+ // fix bug: https://github.com/withastro/astro/pull/6353
+ // Verifying the name is legal or is not
+ // if it's only `*.js` and `*.ts` when it's the endpoint, and it has undefined in the `getStaticPaths` returned value.
+ if(!validateEndpointFileExt(route.component) && mod.getStaticPaths && typeof val === 'undefined' ){
+ throw new AstroError({
+ ...AstroErrorData.InvalidGetEndpointsPathParam,
+ message: AstroErrorData.InvalidGetEndpointsPathParam.message(key, typeof val),
+ location: {
+ file: route.component,
+ },
+ });
+ }
// fix bug: https://github.com/withastro/astro/pull/6353
// [...slug].astro (with undefined) and index.astro has conflict behavior
- // The [...slug].astro under the folder 'index' has set 'undefine' in getStaticPaths that
+ // The [...slug].astro under the folder 'index' has set 'undefine' in getStaticPaths that
// it will replace the index.html outside when the build and format is file.
- if ((route.type === 'endpoint'||route.component.endsWith('astro')) && !mod.getStaticPaths) {
- warn(logging, 'getStaticPaths', 'Under dynamic routing, please pay attention to the use of \'undefine\'')
+ if (
+ (route.type === 'endpoint' || route.component.endsWith('astro')) &&
+ mod.getStaticPaths
+ ) {
+ warn(
+ logging,
+ 'getStaticPaths',
+ "Under dynamic routing, please pay attention to the use of 'undefine'"
+ );
}
+
}
}
let routeCacheEntry = routeCache.get(route);
diff --git a/packages/astro/src/core/util.ts b/packages/astro/src/core/util.ts
index a7152e41a242..a8aee33b26e6 100644
--- a/packages/astro/src/core/util.ts
+++ b/packages/astro/src/core/util.ts
@@ -203,3 +203,11 @@ export function resolvePath(specifier: string, importer: string) {
return specifier;
}
}
+
+/**
+ * Verify that the endpoint is a legal name when it has getStaticPaths
+ * *.js or *.js aren't legal when getStaticPaths will return undefine
+ */
+export function validateEndpointFileExt(pathname: string){
+ return (path.basename(pathname) === 'js' || path.basename(pathname) === 'ts') && pathname.includes('json')
+}
diff --git a/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts b/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
new file mode 100644
index 000000000000..34a6cb311da1
--- /dev/null
+++ b/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
@@ -0,0 +1,17 @@
+import type { APIRoute } from "astro";
+
+const slugs = ["one", undefined];
+
+export const prerender = true;
+
+export const get: APIRoute = ({ params }) => {
+ return {
+ body: JSON.stringify({
+ slug: params.slug || "index",
+ }),
+ };
+};
+
+export function getStaticPaths() {
+ return slugs.map((u) => ({ params: { slug: u } }));
+}
diff --git a/packages/astro/test/routing-priority.test.js b/packages/astro/test/routing-priority.test.js
index 586978d4f4cd..25accfbc885d 100644
--- a/packages/astro/test/routing-priority.test.js
+++ b/packages/astro/test/routing-priority.test.js
@@ -111,6 +111,11 @@ const routes = [
url: '/api/catch/a.json',
htmlMatch: JSON.stringify({ path: 'a' }),
},
+ {
+ description: 'matches /api/expamle to api/example/[...slug].ts',
+ url: '/api/example/',
+ fourOhFour: true,
+ },
{
description: 'matches /api/catch/b/c.json to api/catch/[...slug].json.ts',
url: '/api/catch/b/c.json',
From 190d9370bf098b202263c6d9df43b1db965ea0d1 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Tue, 7 Mar 2023 04:27:03 +0000
Subject: [PATCH 21/37] fix bug and test unit
---
packages/astro/src/core/errors/errors-data.ts | 8 ++---
packages/astro/src/core/render/core.ts | 29 +++++++++++--------
packages/astro/src/core/util.ts | 8 ++---
3 files changed, 25 insertions(+), 20 deletions(-)
diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts
index 817ea72bbef4..97d4b6e5d043 100644
--- a/packages/astro/src/core/errors/errors-data.ts
+++ b/packages/astro/src/core/errors/errors-data.ts
@@ -471,11 +471,11 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
*}
* ```
*/
- InvalidGetEndpointsPathParam: {
- title: 'There can not use \'undefined\' in the getStaticPaths when the endpoint' ,
+ InvalidExtension: {
+ title: 'invalid extension' ,
code: 3022,
- message: (paramkey, paramVal) =>
- `invalid path param: ${paramkey} path. A string, number value was expected, got \`${paramVal}\``,
+ message: () =>
+ `Your extension is wrong, please enter the correct extension, like \'*.json.ts\' or \'*.json.js\'`,
hint: 'See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.',
},
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index 2baae3039948..db88866415d6 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -9,7 +9,7 @@ import { AstroError, AstroErrorData } from '../errors/index.js';
import { getParams } from '../routing/params.js';
import { createResult } from './result.js';
import { callGetStaticPaths, findPathItemByKey, RouteCache } from './route-cache.js';
-import { validateEndpointFileExt } from '../util';
+import { validateEndpointFileExt } from '../util.js';
interface GetParamsAndPropsOptions {
mod: ComponentInstance;
@@ -36,18 +36,24 @@ export async function getParamsAndProps(
const paramsMatch = route.pattern.exec(pathname);
if (paramsMatch) {
params = getParams(route.params)(paramsMatch);
- const [[key, val]] = Object.entries(params)
+ const [[key, val]] = Object.entries(params);
// fix bug: https://github.com/withastro/astro/pull/6353
- // Verifying the name is legal or is not
+ // Verifying the name is legal or is not
// if it's only `*.js` and `*.ts` when it's the endpoint, and it has undefined in the `getStaticPaths` returned value.
- if(!validateEndpointFileExt(route.component) && mod.getStaticPaths && typeof val === 'undefined' ){
- throw new AstroError({
- ...AstroErrorData.InvalidGetEndpointsPathParam,
- message: AstroErrorData.InvalidGetEndpointsPathParam.message(key, typeof val),
- location: {
- file: route.component,
- },
- });
+ if (validateEndpointFileExt(route.component)) {
+ if (
+ mod.getStaticPaths &&
+ typeof val === 'undefined' &&
+ !route.component.includes('json')
+ ) {
+ throw new AstroError({
+ ...AstroErrorData.InvalidExtension,
+ message: AstroErrorData.InvalidExtension.message(),
+ location: {
+ file: route.component,
+ },
+ });
+ }
}
// fix bug: https://github.com/withastro/astro/pull/6353
// [...slug].astro (with undefined) and index.astro has conflict behavior
@@ -63,7 +69,6 @@ export async function getParamsAndProps(
"Under dynamic routing, please pay attention to the use of 'undefine'"
);
}
-
}
}
let routeCacheEntry = routeCache.get(route);
diff --git a/packages/astro/src/core/util.ts b/packages/astro/src/core/util.ts
index a8aee33b26e6..b16269db8ac5 100644
--- a/packages/astro/src/core/util.ts
+++ b/packages/astro/src/core/util.ts
@@ -205,9 +205,9 @@ export function resolvePath(specifier: string, importer: string) {
}
/**
- * Verify that the endpoint is a legal name when it has getStaticPaths
- * *.js or *.js aren't legal when getStaticPaths will return undefine
+ * Verify that the endpoint is a legal name when it has getStaticPaths
+ *
*/
-export function validateEndpointFileExt(pathname: string){
- return (path.basename(pathname) === 'js' || path.basename(pathname) === 'ts') && pathname.includes('json')
+export function validateEndpointFileExt(pathname: string) {
+ return pathname.endsWith('js') || pathname.endsWith('ts');
}
From bae3955b10c9fd6d5ee71ba7747f0c92c39f2d69 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Tue, 7 Mar 2023 05:40:05 +0000
Subject: [PATCH 22/37] fix: done all featrue about getstaticPath
---
.../invail-extension/astro.config.mjs | 7 +++
.../fixtures/invail-extension/package.json | 8 +++
.../src/pages/api/catch}/[...slug].ts | 0
packages/astro/test/invail-extension.test.js | 52 +++++++++++++++++++
packages/astro/test/routing-priority.test.js | 5 --
pnpm-lock.yaml | 6 +++
6 files changed, 73 insertions(+), 5 deletions(-)
create mode 100644 packages/astro/test/fixtures/invail-extension/astro.config.mjs
create mode 100644 packages/astro/test/fixtures/invail-extension/package.json
rename packages/astro/test/fixtures/{routing-priority/src/pages/api/example => invail-extension/src/pages/api/catch}/[...slug].ts (100%)
create mode 100644 packages/astro/test/invail-extension.test.js
diff --git a/packages/astro/test/fixtures/invail-extension/astro.config.mjs b/packages/astro/test/fixtures/invail-extension/astro.config.mjs
new file mode 100644
index 000000000000..0c1afccded1f
--- /dev/null
+++ b/packages/astro/test/fixtures/invail-extension/astro.config.mjs
@@ -0,0 +1,7 @@
+import { defineConfig } from 'astro/config';
+
+
+// https://astro.build/config
+export default defineConfig({
+
+});
diff --git a/packages/astro/test/fixtures/invail-extension/package.json b/packages/astro/test/fixtures/invail-extension/package.json
new file mode 100644
index 000000000000..8a0872b3d3f7
--- /dev/null
+++ b/packages/astro/test/fixtures/invail-extension/package.json
@@ -0,0 +1,8 @@
+{
+ "name": "@test/invail-extension",
+ "version": "0.0.0",
+ "private": true,
+ "dependencies": {
+ "astro": "workspace:*"
+ }
+}
diff --git a/packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts b/packages/astro/test/fixtures/invail-extension/src/pages/api/catch/[...slug].ts
similarity index 100%
rename from packages/astro/test/fixtures/routing-priority/src/pages/api/example/[...slug].ts
rename to packages/astro/test/fixtures/invail-extension/src/pages/api/catch/[...slug].ts
diff --git a/packages/astro/test/invail-extension.test.js b/packages/astro/test/invail-extension.test.js
new file mode 100644
index 000000000000..84039437d5a1
--- /dev/null
+++ b/packages/astro/test/invail-extension.test.js
@@ -0,0 +1,52 @@
+import { expect } from 'chai';
+import { load as cheerioLoad } from 'cheerio';
+import { loadFixture } from './test-utils.js';
+
+describe('throw out an error when it isnt right file name', () => {
+ describe('throw out an error when it isnt right file name in the build', () => {
+ let fixture;
+ let errorMsg;
+ before(async () => {
+ fixture = await loadFixture({
+ root: './fixtures/invail-extension/',
+ });
+ try {
+ await fixture.build();
+ } catch (error) {
+ errorMsg = error
+ }
+
+ });
+
+ it("build", async () => {
+ expect(errorMsg.errorCode).to.eq(3022)
+ });
+ });
+
+ describe('throw out an error when it isnt right file name in the dev ', () => {
+ let fixture;
+ let devServer;
+
+ before(async () => {
+ fixture = await loadFixture({
+ root: './fixtures/invail-extension/',
+ });
+
+ devServer = await fixture.startDevServer();
+ });
+
+ after(async () => {
+ await devServer.stop();
+ });
+
+ it("dev", async () => {
+ const html = await fixture.fetch('/api/catch').then((res) => res.text());
+ const $ = cheerioLoad(html);
+
+ expect($('title').text()).to.equal('InvalidExtension');
+ const htmlone = await fixture.fetch('/api/catch/one').then((res) => res.text());
+ const $one = cheerioLoad(htmlone);
+ expect($one('h1').text()).to.equal('');
+ });
+ });
+});
diff --git a/packages/astro/test/routing-priority.test.js b/packages/astro/test/routing-priority.test.js
index 25accfbc885d..586978d4f4cd 100644
--- a/packages/astro/test/routing-priority.test.js
+++ b/packages/astro/test/routing-priority.test.js
@@ -111,11 +111,6 @@ const routes = [
url: '/api/catch/a.json',
htmlMatch: JSON.stringify({ path: 'a' }),
},
- {
- description: 'matches /api/expamle to api/example/[...slug].ts',
- url: '/api/example/',
- fourOhFour: true,
- },
{
description: 'matches /api/catch/b/c.json to api/catch/[...slug].json.ts',
url: '/api/catch/b/c.json',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e5385ccf3ef9..1b824edba23b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1971,6 +1971,12 @@ importers:
dependencies:
astro: link:../../..
+ packages/astro/test/fixtures/invail-extension:
+ specifiers:
+ astro: workspace:*
+ dependencies:
+ astro: link:../../..
+
packages/astro/test/fixtures/jsx:
specifiers:
'@astrojs/preact': workspace:*
From 566a5bc13e2a7b0dd670e448954310c66185e924 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Tue, 7 Mar 2023 08:29:48 +0000
Subject: [PATCH 23/37] fix: test bug
---
packages/astro/src/core/render/core.ts | 2 +-
packages/astro/src/core/render/util.ts | 7 +++++++
packages/astro/src/core/util.ts | 8 --------
3 files changed, 8 insertions(+), 9 deletions(-)
create mode 100644 packages/astro/src/core/render/util.ts
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index db88866415d6..32f8bada04cf 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -9,7 +9,7 @@ import { AstroError, AstroErrorData } from '../errors/index.js';
import { getParams } from '../routing/params.js';
import { createResult } from './result.js';
import { callGetStaticPaths, findPathItemByKey, RouteCache } from './route-cache.js';
-import { validateEndpointFileExt } from '../util.js';
+import { validateEndpointFileExt } from './util.js';
interface GetParamsAndPropsOptions {
mod: ComponentInstance;
diff --git a/packages/astro/src/core/render/util.ts b/packages/astro/src/core/render/util.ts
new file mode 100644
index 000000000000..17acf2a667eb
--- /dev/null
+++ b/packages/astro/src/core/render/util.ts
@@ -0,0 +1,7 @@
+/**
+ * Verify that the endpoint is a legal name when it has getStaticPaths
+ *
+ */
+export function validateEndpointFileExt(pathname: string) {
+ return pathname.endsWith('js') || pathname.endsWith('ts');
+}
diff --git a/packages/astro/src/core/util.ts b/packages/astro/src/core/util.ts
index b16269db8ac5..a7152e41a242 100644
--- a/packages/astro/src/core/util.ts
+++ b/packages/astro/src/core/util.ts
@@ -203,11 +203,3 @@ export function resolvePath(specifier: string, importer: string) {
return specifier;
}
}
-
-/**
- * Verify that the endpoint is a legal name when it has getStaticPaths
- *
- */
-export function validateEndpointFileExt(pathname: string) {
- return pathname.endsWith('js') || pathname.endsWith('ts');
-}
From d08349141b67220ad351ce842a28437ee69db344 Mon Sep 17 00:00:00 2001
From: bluwy
Date: Tue, 7 Mar 2023 17:28:17 +0800
Subject: [PATCH 24/37] Improve endpoint static check
---
.changeset/small-knives-sparkle.md | 4 +--
packages/astro/src/core/render/core.ts | 36 +++++++++-----------------
packages/astro/src/core/render/util.ts | 7 -----
3 files changed, 14 insertions(+), 33 deletions(-)
delete mode 100644 packages/astro/src/core/render/util.ts
diff --git a/.changeset/small-knives-sparkle.md b/.changeset/small-knives-sparkle.md
index 9dc0f3d75fde..03596b9edb30 100644
--- a/.changeset/small-knives-sparkle.md
+++ b/.changeset/small-knives-sparkle.md
@@ -1,5 +1,5 @@
---
-'astro': major
+'astro': minor
---
-· it can access website without 'index'
+Throw better error when a dynamic endpoint without additional extensions is prerendered with `undefined` params. For example, `src/pages/blog/[slug].js` and `src/pages/blog/[...slug].js` can't have a `getStaticPaths` function that returns `undefined` for `slug`, Astro would generate both a `/blog` file and `/blog` directory (for thruthy slugs), causing a build error. To fix this, you can add an extension like `[...slug].json.js` to generate `/blog.json` instead.
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index 32f8bada04cf..f255f3f2de19 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -1,5 +1,5 @@
import type { ComponentInstance, Params, Props, RouteData } from '../../@types/astro';
-import { LogOptions, warn } from '../logger/core.js';
+import type { LogOptions } from '../logger/core.js';
import type { RenderContext } from './context.js';
import type { Environment } from './environment.js';
@@ -9,7 +9,6 @@ import { AstroError, AstroErrorData } from '../errors/index.js';
import { getParams } from '../routing/params.js';
import { createResult } from './result.js';
import { callGetStaticPaths, findPathItemByKey, RouteCache } from './route-cache.js';
-import { validateEndpointFileExt } from './util.js';
interface GetParamsAndPropsOptions {
mod: ComponentInstance;
@@ -36,15 +35,18 @@ export async function getParamsAndProps(
const paramsMatch = route.pattern.exec(pathname);
if (paramsMatch) {
params = getParams(route.params)(paramsMatch);
- const [[key, val]] = Object.entries(params);
- // fix bug: https://github.com/withastro/astro/pull/6353
- // Verifying the name is legal or is not
- // if it's only `*.js` and `*.ts` when it's the endpoint, and it has undefined in the `getStaticPaths` returned value.
- if (validateEndpointFileExt(route.component)) {
+
+ // If we have an endpoint at `src/pages/api/[slug].ts` that's prerendered, and the `slug`
+ // is `undefined`, throw an error as we can't generate the `/api` file and `/api` directory
+ // at the same time. Using something like `[slug].json.ts` instead will work.
+ if (route.type === 'endpoint' && mod.getStaticPaths) {
+ const lastSegment = route.segments[route.segments.length - 1];
+ // Check last segment is solely `[slug]` or `[...slug]` case (dynamic). Make sure it's not
+ // `foo[slug].js` by checking segment length === 1. Also check here if the params are undefined.
if (
- mod.getStaticPaths &&
- typeof val === 'undefined' &&
- !route.component.includes('json')
+ lastSegment.length === 1 &&
+ lastSegment[0].dynamic &&
+ Object.values(params).some((v) => v === undefined)
) {
throw new AstroError({
...AstroErrorData.InvalidExtension,
@@ -55,20 +57,6 @@ export async function getParamsAndProps(
});
}
}
- // fix bug: https://github.com/withastro/astro/pull/6353
- // [...slug].astro (with undefined) and index.astro has conflict behavior
- // The [...slug].astro under the folder 'index' has set 'undefine' in getStaticPaths that
- // it will replace the index.html outside when the build and format is file.
- if (
- (route.type === 'endpoint' || route.component.endsWith('astro')) &&
- mod.getStaticPaths
- ) {
- warn(
- logging,
- 'getStaticPaths',
- "Under dynamic routing, please pay attention to the use of 'undefine'"
- );
- }
}
}
let routeCacheEntry = routeCache.get(route);
diff --git a/packages/astro/src/core/render/util.ts b/packages/astro/src/core/render/util.ts
deleted file mode 100644
index 17acf2a667eb..000000000000
--- a/packages/astro/src/core/render/util.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-/**
- * Verify that the endpoint is a legal name when it has getStaticPaths
- *
- */
-export function validateEndpointFileExt(pathname: string) {
- return pathname.endsWith('js') || pathname.endsWith('ts');
-}
From 06b481f07dd74b9c7e286005962a77f7e318639b Mon Sep 17 00:00:00 2001
From: bluwy
Date: Tue, 7 Mar 2023 17:53:30 +0800
Subject: [PATCH 25/37] Update error message
---
packages/astro/src/core/errors/errors-data.ts | 35 +++++++++++--------
packages/astro/src/core/render/core.ts | 5 +--
2 files changed, 24 insertions(+), 16 deletions(-)
diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts
index 97d4b6e5d043..d6499d574b22 100644
--- a/packages/astro/src/core/errors/errors-data.ts
+++ b/packages/astro/src/core/errors/errors-data.ts
@@ -454,29 +454,36 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
`[paginate()] page number param \`${paramName}\` not found in your filepath.`,
hint: 'Rename your file to `[page].astro` or `[...page].astro`.',
},
- /**
+ /**
* @docs
* @see
* - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths)
* - [`params`](https://docs.astro.build/en/reference/api-reference/#params)
* @description
- * endpoints `getStaticPaths`'s return value must be an array of objects that can't include `undefined` .
+ * A dynamic endpoint with `getStaticPaths()` should not return `params` with `undefined` as prerendering
+ * the endpoint would cause path collisions. For example:
*
- * ```ts title="api/[...slug].ts"
- * export async function getStaticPaths() {
- * return [ // <-- Array
- * { params: { slug: undefined } } error here,
- * { params: { slug: "about" } }
- * ];
- *}
+ * ```ts title="pages/api/[...slug].ts"
+ * export function getStaticPaths() {
+ * return [
+ * { params: { slug: undefined },
+ * { params: { slug: "about" } }
+ * ];
+ * }
* ```
+ *
+ * When prerendering this endpoint, Astro will generate both the `/api` file and `/api/about` file. As `/api`
+ * is both a file and directory in the filesystem, it will cause a path collision when building.
*/
- InvalidExtension: {
- title: 'invalid extension' ,
+ PrerenderDynamicEndpointPathCollide: {
+ title: 'Prerendered dynamic endpoint has path collision.',
code: 3022,
- message: () =>
- `Your extension is wrong, please enter the correct extension, like \'*.json.ts\' or \'*.json.js\'`,
- hint: 'See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.',
+ message: (pathname: string) =>
+ `Could not render \`${pathname}\` with an \`undefined\` param as the generated path will collide during prerendering. ` +
+ `Prevent passing \`undefined\` as \`params\` for the endpoint's \`getStaticPaths()\` function, ` +
+ `or add an additional extension to the endpoint's filename.`,
+ hint: (filename: string) =>
+ `Rename \`${filename}\` to \`${filename.replace(/\.(js|ts)/, (m) => `.json` + m)}\``,
},
// No headings here, that way Vite errors are merged with Astro ones in the docs, which makes more sense to users.
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index f255f3f2de19..b513fbafe182 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -49,8 +49,9 @@ export async function getParamsAndProps(
Object.values(params).some((v) => v === undefined)
) {
throw new AstroError({
- ...AstroErrorData.InvalidExtension,
- message: AstroErrorData.InvalidExtension.message(),
+ ...AstroErrorData.PrerenderDynamicEndpointPathCollide,
+ message: AstroErrorData.PrerenderDynamicEndpointPathCollide.message(route.route),
+ hint: AstroErrorData.PrerenderDynamicEndpointPathCollide.hint(route.component),
location: {
file: route.component,
},
From c41c8db60bb2770a6123dc7cc221c42281a6031c Mon Sep 17 00:00:00 2001
From: bluwy
Date: Tue, 7 Mar 2023 18:00:16 +0800
Subject: [PATCH 26/37] Rename test file
---
.../astro/test/dynamic-endpoint-collision.js | 53 +++++++++++++++++++
.../astro.config.mjs | 0
.../package.json | 2 +-
.../src/pages/api/catch/[...slug].ts | 2 -
packages/astro/test/invail-extension.test.js | 52 ------------------
5 files changed, 54 insertions(+), 55 deletions(-)
create mode 100644 packages/astro/test/dynamic-endpoint-collision.js
rename packages/astro/test/fixtures/{invail-extension => dynamic-endpoint-collision}/astro.config.mjs (100%)
rename packages/astro/test/fixtures/{invail-extension => dynamic-endpoint-collision}/package.json (67%)
rename packages/astro/test/fixtures/{invail-extension => dynamic-endpoint-collision}/src/pages/api/catch/[...slug].ts (90%)
delete mode 100644 packages/astro/test/invail-extension.test.js
diff --git a/packages/astro/test/dynamic-endpoint-collision.js b/packages/astro/test/dynamic-endpoint-collision.js
new file mode 100644
index 000000000000..2d947e1e6fac
--- /dev/null
+++ b/packages/astro/test/dynamic-endpoint-collision.js
@@ -0,0 +1,53 @@
+import { expect } from 'chai';
+import { load as cheerioLoad } from 'cheerio';
+import { loadFixture } from './test-utils.js';
+
+describe('Dynamic endpoint collision', () => {
+ describe('build', () => {
+ let fixture;
+ let errorMsg;
+ before(async () => {
+ fixture = await loadFixture({
+ root: './fixtures/dynamic-endpoint-collision/',
+ });
+ try {
+ await fixture.build();
+ } catch (error) {
+ errorMsg = error;
+ }
+ });
+
+ it('throw error when dynamic endpoint has path collision', async () => {
+ expect(errorMsg.errorCode).to.eq(3022);
+ });
+ });
+
+ describe('throw out an error when it isnt right file name in the dev ', () => {
+ let fixture;
+ let devServer;
+
+ before(async () => {
+ fixture = await loadFixture({
+ root: './fixtures/dynamic-endpoint-collision/',
+ });
+
+ devServer = await fixture.startDevServer();
+ });
+
+ after(async () => {
+ await devServer.stop();
+ });
+
+ it('throw error when dynamic endpoint has path collision', async () => {
+ const html = await fixture.fetch('/api/catch').then((res) => res.text());
+ const $ = cheerioLoad(html);
+ expect($('title').text()).to.equal('PrerenderDynamicEndpointPathCollide');
+ });
+
+ it("don't throw error when dynamic endpoint doesn't load the colliding path", async () => {
+ const html = await fixture.fetch('/api/catch/one').then((res) => res.text());
+ const $ = cheerioLoad(html);
+ expect($('pre').text()).to.equal('{"slug":"one"}');
+ });
+ });
+});
diff --git a/packages/astro/test/fixtures/invail-extension/astro.config.mjs b/packages/astro/test/fixtures/dynamic-endpoint-collision/astro.config.mjs
similarity index 100%
rename from packages/astro/test/fixtures/invail-extension/astro.config.mjs
rename to packages/astro/test/fixtures/dynamic-endpoint-collision/astro.config.mjs
diff --git a/packages/astro/test/fixtures/invail-extension/package.json b/packages/astro/test/fixtures/dynamic-endpoint-collision/package.json
similarity index 67%
rename from packages/astro/test/fixtures/invail-extension/package.json
rename to packages/astro/test/fixtures/dynamic-endpoint-collision/package.json
index 8a0872b3d3f7..7a40aff87376 100644
--- a/packages/astro/test/fixtures/invail-extension/package.json
+++ b/packages/astro/test/fixtures/dynamic-endpoint-collision/package.json
@@ -1,5 +1,5 @@
{
- "name": "@test/invail-extension",
+ "name": "@test/dynamic-endpoint-collision",
"version": "0.0.0",
"private": true,
"dependencies": {
diff --git a/packages/astro/test/fixtures/invail-extension/src/pages/api/catch/[...slug].ts b/packages/astro/test/fixtures/dynamic-endpoint-collision/src/pages/api/catch/[...slug].ts
similarity index 90%
rename from packages/astro/test/fixtures/invail-extension/src/pages/api/catch/[...slug].ts
rename to packages/astro/test/fixtures/dynamic-endpoint-collision/src/pages/api/catch/[...slug].ts
index 34a6cb311da1..8f64c2401ffa 100644
--- a/packages/astro/test/fixtures/invail-extension/src/pages/api/catch/[...slug].ts
+++ b/packages/astro/test/fixtures/dynamic-endpoint-collision/src/pages/api/catch/[...slug].ts
@@ -2,8 +2,6 @@ import type { APIRoute } from "astro";
const slugs = ["one", undefined];
-export const prerender = true;
-
export const get: APIRoute = ({ params }) => {
return {
body: JSON.stringify({
diff --git a/packages/astro/test/invail-extension.test.js b/packages/astro/test/invail-extension.test.js
deleted file mode 100644
index 84039437d5a1..000000000000
--- a/packages/astro/test/invail-extension.test.js
+++ /dev/null
@@ -1,52 +0,0 @@
-import { expect } from 'chai';
-import { load as cheerioLoad } from 'cheerio';
-import { loadFixture } from './test-utils.js';
-
-describe('throw out an error when it isnt right file name', () => {
- describe('throw out an error when it isnt right file name in the build', () => {
- let fixture;
- let errorMsg;
- before(async () => {
- fixture = await loadFixture({
- root: './fixtures/invail-extension/',
- });
- try {
- await fixture.build();
- } catch (error) {
- errorMsg = error
- }
-
- });
-
- it("build", async () => {
- expect(errorMsg.errorCode).to.eq(3022)
- });
- });
-
- describe('throw out an error when it isnt right file name in the dev ', () => {
- let fixture;
- let devServer;
-
- before(async () => {
- fixture = await loadFixture({
- root: './fixtures/invail-extension/',
- });
-
- devServer = await fixture.startDevServer();
- });
-
- after(async () => {
- await devServer.stop();
- });
-
- it("dev", async () => {
- const html = await fixture.fetch('/api/catch').then((res) => res.text());
- const $ = cheerioLoad(html);
-
- expect($('title').text()).to.equal('InvalidExtension');
- const htmlone = await fixture.fetch('/api/catch/one').then((res) => res.text());
- const $one = cheerioLoad(htmlone);
- expect($one('h1').text()).to.equal('');
- });
- });
-});
From 87d5d09a9f440dde376cbe4fe390b228dc6eaf1d Mon Sep 17 00:00:00 2001
From: bluwy
Date: Tue, 7 Mar 2023 18:01:09 +0800
Subject: [PATCH 27/37] Update lockfile
---
pnpm-lock.yaml | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0997757b8237..ccb2b4c04e41 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1835,6 +1835,12 @@ importers:
dependencies:
astro: link:../../..
+ packages/astro/test/fixtures/dynamic-endpoint-collision:
+ specifiers:
+ astro: workspace:*
+ dependencies:
+ astro: link:../../..
+
packages/astro/test/fixtures/dynamic-route-build-file:
specifiers:
astro: workspace:*
@@ -1979,12 +1985,6 @@ importers:
dependencies:
astro: link:../../..
- packages/astro/test/fixtures/invail-extension:
- specifiers:
- astro: workspace:*
- dependencies:
- astro: link:../../..
-
packages/astro/test/fixtures/jsx:
specifiers:
'@astrojs/preact': workspace:*
From 5d7a5183a797f3c7bfa291358e14d0232d74be7f Mon Sep 17 00:00:00 2001
From: bluwy
Date: Tue, 7 Mar 2023 18:02:53 +0800
Subject: [PATCH 28/37] Fix test
---
packages/astro/test/dynamic-endpoint-collision.js | 7 +++----
1 file changed, 3 insertions(+), 4 deletions(-)
diff --git a/packages/astro/test/dynamic-endpoint-collision.js b/packages/astro/test/dynamic-endpoint-collision.js
index 2d947e1e6fac..4ce97df7e11e 100644
--- a/packages/astro/test/dynamic-endpoint-collision.js
+++ b/packages/astro/test/dynamic-endpoint-collision.js
@@ -22,7 +22,7 @@ describe('Dynamic endpoint collision', () => {
});
});
- describe('throw out an error when it isnt right file name in the dev ', () => {
+ describe('dev', () => {
let fixture;
let devServer;
@@ -45,9 +45,8 @@ describe('Dynamic endpoint collision', () => {
});
it("don't throw error when dynamic endpoint doesn't load the colliding path", async () => {
- const html = await fixture.fetch('/api/catch/one').then((res) => res.text());
- const $ = cheerioLoad(html);
- expect($('pre').text()).to.equal('{"slug":"one"}');
+ const res = await fixture.fetch('/api/catch/one').then((res) => res.text());
+ expect(res).to.equal('{"slug":"one"}');
});
});
});
From d5a8ad03cf6d67a2cef7abb4d18a68065372b05f Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Wed, 8 Mar 2023 01:44:16 +0000
Subject: [PATCH 29/37] fix eslint error
---
packages/astro/test/dynamic-endpoint-collision.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/astro/test/dynamic-endpoint-collision.js b/packages/astro/test/dynamic-endpoint-collision.js
index 4ce97df7e11e..6b96f3e52b97 100644
--- a/packages/astro/test/dynamic-endpoint-collision.js
+++ b/packages/astro/test/dynamic-endpoint-collision.js
@@ -45,7 +45,7 @@ describe('Dynamic endpoint collision', () => {
});
it("don't throw error when dynamic endpoint doesn't load the colliding path", async () => {
- const res = await fixture.fetch('/api/catch/one').then((res) => res.text());
+ const res = await fixture.fetch('/api/catch/one').then((r) => r.text());
expect(res).to.equal('{"slug":"one"}');
});
});
From c6d82dd19c33bbb6e431cd503a4c482c792c8fc9 Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Wed, 8 Mar 2023 09:59:19 +0000
Subject: [PATCH 30/37] fix:The name of the code was incorrect and reducing
judgement condition in order optimize code structure
---
packages/astro/src/core/errors/errors-data.ts | 46 +++++++++----------
packages/astro/src/core/render/core.ts | 6 +--
2 files changed, 24 insertions(+), 28 deletions(-)
diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts
index 3724277aa623..bf24da34c6cc 100644
--- a/packages/astro/src/core/errors/errors-data.ts
+++ b/packages/astro/src/core/errors/errors-data.ts
@@ -454,6 +454,27 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
`[paginate()] page number param \`${paramName}\` not found in your filepath.`,
hint: 'Rename your file to `[page].astro` or `[...page].astro`.',
},
+
+ ImageMissingAlt: {
+ title: 'Missing alt property',
+ code: 3022,
+ message: 'The alt property is required.',
+ hint: "The `alt` property is important for the purpose of accessibility, without it users using screen readers or other assistive technologies won't be able to understand what your image is supposed to represent. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-alt for more information.",
+ },
+ InvalidImageService: {
+ title: 'Error while loading image service',
+ code: 3023,
+ message:
+ 'There was an error loading the configured image service. Please see the stack trace for more information',
+ },
+ MissingImageDimension: {
+ title: 'Missing image dimensions',
+ code: 3024,
+ message: (missingDimension: 'width' | 'height' | 'both') =>
+ `For remote images, ${
+ missingDimension === 'both' ? 'width and height are' : `${missingDimension} is`
+ } required.`,
+ },
/**
* @docs
* @see
@@ -475,9 +496,9 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
* When prerendering this endpoint, Astro will generate both the `/api` file and `/api/about` file. As `/api`
* is both a file and directory in the filesystem, it will cause a path collision when building.
*/
- PrerenderDynamicEndpointPathCollide: {
+ PrerenderDynamicEndpointPathCollide: {
title: 'Prerendered dynamic endpoint has path collision.',
- code: 3022,
+ code: 3025,
message: (pathname: string) =>
`Could not render \`${pathname}\` with an \`undefined\` param as the generated path will collide during prerendering. ` +
`Prevent passing \`undefined\` as \`params\` for the endpoint's \`getStaticPaths()\` function, ` +
@@ -485,27 +506,6 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
hint: (filename: string) =>
`Rename \`${filename}\` to \`${filename.replace(/\.(js|ts)/, (m) => `.json` + m)}\``,
},
-
- ImageMissingAlt: {
- title: 'Missing alt property',
- code: 3022,
- message: 'The alt property is required.',
- hint: "The `alt` property is important for the purpose of accessibility, without it users using screen readers or other assistive technologies won't be able to understand what your image is supposed to represent. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-alt for more information.",
- },
- InvalidImageService: {
- title: 'Error while loading image service',
- code: 3023,
- message:
- 'There was an error loading the configured image service. Please see the stack trace for more information',
- },
- MissingImageDimension: {
- title: 'Missing image dimensions',
- code: 3024,
- message: (missingDimension: 'width' | 'height' | 'both') =>
- `For remote images, ${
- missingDimension === 'both' ? 'width and height are' : `${missingDimension} is`
- } required.`,
- },
// No headings here, that way Vite errors are merged with Astro ones in the docs, which makes more sense to users.
// Vite Errors - 4xxx
/**
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index b513fbafe182..4906ffda42d4 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -43,11 +43,7 @@ export async function getParamsAndProps(
const lastSegment = route.segments[route.segments.length - 1];
// Check last segment is solely `[slug]` or `[...slug]` case (dynamic). Make sure it's not
// `foo[slug].js` by checking segment length === 1. Also check here if the params are undefined.
- if (
- lastSegment.length === 1 &&
- lastSegment[0].dynamic &&
- Object.values(params).some((v) => v === undefined)
- ) {
+ if (lastSegment.length === 1 && Object.values(params).some((v) => v === undefined)) {
throw new AstroError({
...AstroErrorData.PrerenderDynamicEndpointPathCollide,
message: AstroErrorData.PrerenderDynamicEndpointPathCollide.message(route.route),
From c85192e17b0d7638e4db22bd719a4775f3cc855b Mon Sep 17 00:00:00 2001
From: bluwy
Date: Wed, 8 Mar 2023 21:28:50 +0800
Subject: [PATCH 31/37] Fix param check
---
packages/astro/src/core/errors/errors-data.ts | 6 +++---
packages/astro/src/core/render/core.ts | 6 ++++--
2 files changed, 7 insertions(+), 5 deletions(-)
diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts
index 89d350b66ae5..6a9d4dab7e40 100644
--- a/packages/astro/src/core/errors/errors-data.ts
+++ b/packages/astro/src/core/errors/errors-data.ts
@@ -454,7 +454,6 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
`[paginate()] page number param \`${paramName}\` not found in your filepath.`,
hint: 'Rename your file to `[page].astro` or `[...page].astro`.',
},
-
ImageMissingAlt: {
title: 'Missing alt property',
code: 3022,
@@ -505,9 +504,9 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
* When prerendering this endpoint, Astro will generate both the `/api` file and `/api/about` file. As `/api`
* is both a file and directory in the filesystem, it will cause a path collision when building.
*/
- PrerenderDynamicEndpointPathCollide: {
+ PrerenderDynamicEndpointPathCollide: {
title: 'Prerendered dynamic endpoint has path collision.',
- code: 3025,
+ code: 3026,
message: (pathname: string) =>
`Could not render \`${pathname}\` with an \`undefined\` param as the generated path will collide during prerendering. ` +
`Prevent passing \`undefined\` as \`params\` for the endpoint's \`getStaticPaths()\` function, ` +
@@ -515,6 +514,7 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
hint: (filename: string) =>
`Rename \`${filename}\` to \`${filename.replace(/\.(js|ts)/, (m) => `.json` + m)}\``,
},
+
// No headings here, that way Vite errors are merged with Astro ones in the docs, which makes more sense to users.
// Vite Errors - 4xxx
/**
diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts
index 4906ffda42d4..351cb7d76f17 100644
--- a/packages/astro/src/core/render/core.ts
+++ b/packages/astro/src/core/render/core.ts
@@ -41,9 +41,11 @@ export async function getParamsAndProps(
// at the same time. Using something like `[slug].json.ts` instead will work.
if (route.type === 'endpoint' && mod.getStaticPaths) {
const lastSegment = route.segments[route.segments.length - 1];
+ const paramValues = Object.values(params);
+ const lastParam = paramValues[paramValues.length - 1];
// Check last segment is solely `[slug]` or `[...slug]` case (dynamic). Make sure it's not
- // `foo[slug].js` by checking segment length === 1. Also check here if the params are undefined.
- if (lastSegment.length === 1 && Object.values(params).some((v) => v === undefined)) {
+ // `foo[slug].js` by checking segment length === 1. Also check here if that param is undefined.
+ if (lastSegment.length === 1 && lastSegment[0].dynamic && lastParam === undefined) {
throw new AstroError({
...AstroErrorData.PrerenderDynamicEndpointPathCollide,
message: AstroErrorData.PrerenderDynamicEndpointPathCollide.message(route.route),
From 6e89c713e79190b46c9fe10ae4c4365318bfa9c2 Mon Sep 17 00:00:00 2001
From: bluwy
Date: Wed, 8 Mar 2023 21:37:11 +0800
Subject: [PATCH 32/37] Fix test
---
packages/astro/test/dynamic-endpoint-collision.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/packages/astro/test/dynamic-endpoint-collision.js b/packages/astro/test/dynamic-endpoint-collision.js
index 6b96f3e52b97..b8620568ad31 100644
--- a/packages/astro/test/dynamic-endpoint-collision.js
+++ b/packages/astro/test/dynamic-endpoint-collision.js
@@ -18,7 +18,7 @@ describe('Dynamic endpoint collision', () => {
});
it('throw error when dynamic endpoint has path collision', async () => {
- expect(errorMsg.errorCode).to.eq(3022);
+ expect(errorMsg.errorCode).to.eq(3026);
});
});
From 8d6c9ff485901e37e76486f2de74e52a9f7f71bf Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Thu, 9 Mar 2023 05:26:16 +0000
Subject: [PATCH 33/37] fix changeset tips
---
.changeset/small-knives-sparkle.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.changeset/small-knives-sparkle.md b/.changeset/small-knives-sparkle.md
index 03596b9edb30..7271ec2b97d9 100644
--- a/.changeset/small-knives-sparkle.md
+++ b/.changeset/small-knives-sparkle.md
@@ -2,4 +2,4 @@
'astro': minor
---
-Throw better error when a dynamic endpoint without additional extensions is prerendered with `undefined` params. For example, `src/pages/blog/[slug].js` and `src/pages/blog/[...slug].js` can't have a `getStaticPaths` function that returns `undefined` for `slug`, Astro would generate both a `/blog` file and `/blog` directory (for thruthy slugs), causing a build error. To fix this, you can add an extension like `[...slug].json.js` to generate `/blog.json` instead.
+Throw better error when a dynamic endpoint without additional extensions is prerendered with `undefined` params.
From f85eaba980c5894ed33b6ec7bf0beff7b0ff114e Mon Sep 17 00:00:00 2001
From: wulinsheng123 <409187100@qq.com>
Date: Fri, 10 Mar 2023 02:14:21 +0000
Subject: [PATCH 34/37] beautify the description of the error
---
packages/astro/src/core/errors/errors-data.ts | 16 ++--------------
1 file changed, 2 insertions(+), 14 deletions(-)
diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts
index 49ca79c53c1b..980ed14804df 100644
--- a/packages/astro/src/core/errors/errors-data.ts
+++ b/packages/astro/src/core/errors/errors-data.ts
@@ -538,20 +538,8 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
* - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths)
* - [`params`](https://docs.astro.build/en/reference/api-reference/#params)
* @description
- * A dynamic endpoint with `getStaticPaths()` should not return `params` with `undefined` as prerendering
- * the endpoint would cause path collisions. For example:
- *
- * ```ts title="pages/api/[...slug].ts"
- * export function getStaticPaths() {
- * return [
- * { params: { slug: undefined },
- * { params: { slug: "about" } }
- * ];
- * }
- * ```
- *
- * When prerendering this endpoint, Astro will generate both the `/api` file and `/api/about` file. As `/api`
- * is both a file and directory in the filesystem, it will cause a path collision when building.
+ * You should add an additional extension to the endpoint's filename
+ * and A dynamic endpoint with `getStaticPaths` should not return `params` with `undefined`.
*/
PrerenderDynamicEndpointPathCollide: {
title: 'Prerendered dynamic endpoint has path collision.',
From 9c77f55484ec1dc6114d1aff97bb7b4883bcb2be Mon Sep 17 00:00:00 2001
From: wuls
Date: Wed, 15 Mar 2023 09:46:10 +0800
Subject: [PATCH 35/37] optimize the format of error
---
packages/astro/src/core/errors/errors-data.ts | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts
index cead671fe231..af2b03ba35c3 100644
--- a/packages/astro/src/core/errors/errors-data.ts
+++ b/packages/astro/src/core/errors/errors-data.ts
@@ -538,8 +538,14 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
* - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths)
* - [`params`](https://docs.astro.build/en/reference/api-reference/#params)
* @description
- * You should add an additional extension to the endpoint's filename
- * and A dynamic endpoint with `getStaticPaths` should not return `params` with `undefined`.
+ * @description
+ * The endpoint is prerendered with an `undefined` param but the generated file and folder names will collide.
+ *
+ * An additional extension can be added to the endpoint file name to generate the file with a different name.
+ *
+ * For example,
+ *
+ * renaming `pages/api/[slug].ts` to `pages/api/[slug].json.ts`.
*/
PrerenderDynamicEndpointPathCollide: {
title: 'Prerendered dynamic endpoint has path collision.',
From 0659a2569b7697ef36cfd1357b342ae372d18126 Mon Sep 17 00:00:00 2001
From: bluwy
Date: Thu, 16 Mar 2023 22:44:36 +0800
Subject: [PATCH 36/37] Update changeset and docs
---
.changeset/small-knives-sparkle.md | 2 +-
packages/astro/src/core/errors/errors-data.ts | 9 ++-------
2 files changed, 3 insertions(+), 8 deletions(-)
diff --git a/.changeset/small-knives-sparkle.md b/.changeset/small-knives-sparkle.md
index 7271ec2b97d9..e257d5e97edb 100644
--- a/.changeset/small-knives-sparkle.md
+++ b/.changeset/small-knives-sparkle.md
@@ -1,5 +1,5 @@
---
-'astro': minor
+'astro': patch
---
Throw better error when a dynamic endpoint without additional extensions is prerendered with `undefined` params.
diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts
index af2b03ba35c3..7bb2207cb4b1 100644
--- a/packages/astro/src/core/errors/errors-data.ts
+++ b/packages/astro/src/core/errors/errors-data.ts
@@ -538,14 +538,9 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
* - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths)
* - [`params`](https://docs.astro.build/en/reference/api-reference/#params)
* @description
- * @description
* The endpoint is prerendered with an `undefined` param but the generated file and folder names will collide.
- *
- * An additional extension can be added to the endpoint file name to generate the file with a different name.
- *
- * For example,
- *
- * renaming `pages/api/[slug].ts` to `pages/api/[slug].json.ts`.
+ *
+ * An additional extension can be added to the endpoint file name to generate the file with a different name. For example, renaming `pages/api/[slug].ts` to `pages/api/[slug].json.ts`.
*/
PrerenderDynamicEndpointPathCollide: {
title: 'Prerendered dynamic endpoint has path collision.',
From 56d34730f006eeb3cbd1517c66896d6545b4aa6a Mon Sep 17 00:00:00 2001
From: wuls
Date: Tue, 28 Mar 2023 10:12:19 +0800
Subject: [PATCH 37/37] fix comment
---
packages/astro/src/core/errors/errors-data.ts | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts
index fdc68abda575..760cade33fae 100644
--- a/packages/astro/src/core/errors/errors-data.ts
+++ b/packages/astro/src/core/errors/errors-data.ts
@@ -536,9 +536,9 @@ See https://docs.astro.build/en/guides/server-side-rendering/ for more informati
* - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths)
* - [`params`](https://docs.astro.build/en/reference/api-reference/#params)
* @description
- * The endpoint is prerendered with an `undefined` param but the generated file and folder names will collide.
+ * The endpoint is prerendered with an `undefined` param so the generated path will collide with another route.
*
- * An additional extension can be added to the endpoint file name to generate the file with a different name. For example, renaming `pages/api/[slug].ts` to `pages/api/[slug].json.ts`.
+ * If you cannot prevent passing `undefined`, then an additional extension can be added to the endpoint file name to generate the file with a different name. For example, renaming `pages/api/[slug].ts` to `pages/api/[slug].json.ts`.
*/
PrerenderDynamicEndpointPathCollide: {
title: 'Prerendered dynamic endpoint has path collision.',