fix(hybrid-output): no matched route when using getStaticPaths (#7150)

* `isPrenderDefault` ---> `isPrerenderDefault`

* test: add test fixture

* test: add hybrid getStaticPaths tests

* try fix in ci

* bring back edit lost on merge conflict fix

* back static paths guard

* move function to new file to avoid bundling issues

* remove unsued import

* debugging cleanup

* chore: update fixture's package.json

* cleanup test

* small test refactoring

* `status.ts` --> `metadata.ts`

* smol refactor

* chore: changeset

* just return the prerender metadata

* refactor tests

* chore: update lock file
This commit is contained in:
Happydev 2023-05-22 12:58:03 +00:00 committed by GitHub
parent 0616ef2551
commit 8f418d13c5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 334 additions and 136 deletions

View file

@ -0,0 +1,5 @@
---
'astro': patch
---
fix no matched path when using `getStaticPaths` without `prerender` export.

View file

@ -4,6 +4,7 @@ import type { BuildInternals } from '../internal.js';
import type { AstroBuildPlugin } from '../plugin.js';
import type { StaticBuildOptions } from '../types';
import { extendManualChunks } from './util.js';
import { getPrerenderMetadata } from '../../../prerender/metadata.js';
function vitePluginPrerender(opts: StaticBuildOptions, internals: BuildInternals): VitePlugin {
return {
@ -20,7 +21,7 @@ function vitePluginPrerender(opts: StaticBuildOptions, internals: BuildInternals
if (pageInfo) {
// prerendered pages should be split into their own chunk
// Important: this can't be in the `pages/` directory!
if (meta.getModuleInfo(id)?.meta.astro?.pageOptions?.prerender) {
if (getPrerenderMetadata(meta.getModuleInfo(id))) {
pageInfo.route.prerender = true;
return 'prerender';
}

View file

@ -138,7 +138,7 @@ export async function callEndpoint<MiddlewareResult = Response | EndpointOutput>
};
}
if (env.ssr && !mod.prerender) {
if (env.ssr && !ctx.route?.prerender) {
if (response.hasOwnProperty('headers')) {
warn(
logging,

View file

@ -89,7 +89,7 @@ export async function getParamsAndProps(
routeCache.set(route, routeCacheEntry);
}
const matchedStaticPath = findPathItemByKey(routeCacheEntry.staticPaths, params, route);
if (!matchedStaticPath && (ssr ? mod.prerender : true)) {
if (!matchedStaticPath && (ssr ? route.prerender : true)) {
return GetParamsAndPropsError.NoMatchingStaticPath;
}
// Note: considered using Object.create(...) for performance

View file

@ -66,6 +66,7 @@ export async function preload({
try {
// Load the module from the Vite SSR Runtime.
const mod = (await env.loader.import(fileURLToPath(filePath))) as ComponentInstance;
return [renderers, mod];
} catch (error) {
// If the error came from Markdown or CSS, we already handled it and there's no need to enhance it

View file

@ -31,7 +31,7 @@ export async function callGetStaticPaths({
}: CallGetStaticPathsOptions): Promise<RouteCacheEntry> {
validateDynamicRouteModule(mod, { ssr, logging, route });
// No static paths in SSR mode. Return an empty RouteCacheEntry.
if (ssr && !mod.prerender) {
if (ssr && !route.prerender) {
return { staticPaths: Object.assign([], { keyed: new Map() }) };
}
// Add a check here to make TypeScript happy.

View file

@ -227,7 +227,7 @@ export function createRouteManifest(
]);
const validEndpointExtensions: Set<string> = new Set(['.js', '.ts']);
const localFs = fsMod ?? nodeFs;
const isPrenderDefault = isHybridOutput(settings.config);
const isPrerenderDefault = isHybridOutput(settings.config);
const foundInvalidFileExtensions: Set<string> = new Set();
@ -340,7 +340,7 @@ export function createRouteManifest(
component,
generate,
pathname: pathname || undefined,
prerender: isPrenderDefault,
prerender: isPrerenderDefault,
});
}
});
@ -416,7 +416,7 @@ export function createRouteManifest(
component,
generate,
pathname: pathname || void 0,
prerender: isPrenderDefault,
prerender: isPrerenderDefault,
});
});

View file

@ -32,14 +32,14 @@ export function validateDynamicRouteModule(
route: RouteData;
}
) {
if (ssr && mod.getStaticPaths && !mod.prerender) {
if (ssr && mod.getStaticPaths && !route.prerender) {
warn(
logging,
'getStaticPaths',
`getStaticPaths() in ${bold(route.component)} is ignored when "output: server" is set.`
);
}
if ((!ssr || mod.prerender) && !mod.getStaticPaths) {
if ((!ssr || route.prerender) && !mod.getStaticPaths) {
throw new AstroError({
...AstroErrorData.GetStaticPathsRequired,
location: { file: route.component },

View file

@ -0,0 +1,22 @@
import type { ModuleInfo, ModuleLoader } from '../core/module-loader';
import { viteID } from '../core/util.js';
type GetPrerenderStatusParams = {
filePath: URL;
loader: ModuleLoader;
};
export function getPrerenderStatus({
filePath,
loader,
}: GetPrerenderStatusParams): boolean | undefined {
const fileID = viteID(filePath);
const moduleInfo = loader.getModuleInfo(fileID);
if (!moduleInfo) return;
const prerenderStatus = getPrerenderMetadata(moduleInfo);
return prerenderStatus;
}
export function getPrerenderMetadata(moduleInfo: ModuleInfo) {
return moduleInfo?.meta?.astro?.pageOptions?.prerender;
}

View file

@ -19,6 +19,7 @@ import { matchAllRoutes } from '../core/routing/index.js';
import { isHybridOutput } from '../prerender/utils.js';
import { log404 } from './common.js';
import { handle404Response, writeSSRResult, writeWebResponse } from './response.js';
import { getPrerenderStatus } from '../prerender/metadata.js';
type AsyncReturnType<T extends (...args: any) => Promise<any>> = T extends (
...args: any
@ -50,6 +51,17 @@ export async function matchRoute(
for await (const maybeRoute of matches) {
const filePath = new URL(`./${maybeRoute.component}`, settings.config.root);
const preloadedComponent = await preload({ env, filePath });
// gets the prerender metadata set by the `astro:scanner` vite plugin
const prerenderStatus = getPrerenderStatus({
filePath,
loader: env.loader,
});
if (prerenderStatus !== undefined) {
maybeRoute.prerender = prerenderStatus;
}
const [, mod] = preloadedComponent;
// attempt to get static paths
// if this fails, we have a bad URL match!

View file

@ -1,131 +1,291 @@
import { expect } from 'chai';
import { loadFixture } from './test-utils.js';
import * as cheerio from 'cheerio';
import testAdapter from './test-adapter.js';
describe('prerender getStaticPaths - build calls', () => {
describe('Prerender', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;
describe('output: "server"', () => {
describe('getStaticPaths - build calls', () => {
before(async () => {
fixture = await loadFixture({
root: './fixtures/ssr-prerender-get-static-paths/',
site: 'https://mysite.dev/',
adapter: testAdapter(),
base: '/blog',
output: 'server',
});
await fixture.build();
});
before(async () => {
fixture = await loadFixture({
root: './fixtures/ssr-prerender-get-static-paths/',
site: 'https://mysite.dev/',
base: '/blog',
after(async () => {
await fixture.clean();
});
afterEach(() => {
// reset the flag used by [...calledTwiceTest].astro between each test
globalThis.isCalledOnce = false;
});
it('is only called once during build', () => {
// useless expect; if build() throws in setup then this test fails
expect(true).to.equal(true);
});
it('Astro.url sets the current pathname', async () => {
const html = await fixture.readFile('/client/food/tacos/index.html');
const $ = cheerio.load(html);
expect($('#props').text()).to.equal('10');
expect($('#url').text()).to.equal('/blog/food/tacos/');
});
});
describe('getStaticPaths - dev calls', () => {
let devServer;
before(async () => {
globalThis.isCalledOnce = false;
devServer = await fixture.startDevServer();
});
afterEach(() => {
// reset the flag used by [...calledTwiceTest].astro between each test
globalThis.isCalledOnce = false;
});
after(async () => {
devServer.stop();
});
it('only calls prerender getStaticPaths once', async () => {
let res = await fixture.fetch('/blog/a');
expect(res.status).to.equal(200);
res = await fixture.fetch('/blog/b');
expect(res.status).to.equal(200);
res = await fixture.fetch('/blog/c');
expect(res.status).to.equal(200);
});
describe('404 behavior', () => {
it('resolves 200 on matching static path - named params', async () => {
const res = await fixture.fetch('/blog/pizza/provolone-sausage');
expect(res.status).to.equal(200);
});
it('resolves 404 on pattern match without static path - named params', async () => {
const res = await fixture.fetch('/blog/pizza/provolone-pineapple');
const html = await res.text();
expect(res.status).to.equal(404);
expect(html).to.match(/404/);
});
it('resolves 200 on matching static path - rest params', async () => {
const res = await fixture.fetch('/blog/pizza/grimaldis/new-york');
expect(res.status).to.equal(200);
});
it('resolves 404 on pattern match without static path - rest params', async () => {
const res = await fixture.fetch('/blog/pizza/pizza-hut');
const html = await res.text();
expect(res.status).to.equal(404);
expect(html).to.match(/404/);
});
});
describe('route params type validation', () => {
it('resolves 200 on nested array parameters', async () => {
const res = await fixture.fetch('/blog/nested-arrays/slug1');
expect(res.status).to.equal(200);
});
it('resolves 200 on matching static path - string params', async () => {
// route provided with { params: { year: "2022", slug: "post-2" }}
const res = await fixture.fetch('/blog/blog/2022/post-1');
expect(res.status).to.equal(200);
});
it('resolves 200 on matching static path - numeric params', async () => {
// route provided with { params: { year: 2022, slug: "post-2" }}
const res = await fixture.fetch('/blog/blog/2022/post-2');
expect(res.status).to.equal(200);
});
});
it('resolves 200 on matching static paths', async () => {
// routes params provided for pages /posts/1, /posts/2, and /posts/3
for (const page of [1, 2, 3]) {
let res = await fixture.fetch(`/blog/posts/${page}`);
expect(res.status).to.equal(200);
const html = await res.text();
const $ = cheerio.load(html);
const canonical = $('link[rel=canonical]');
expect(canonical.attr('href')).to.equal(
`https://mysite.dev/blog/posts/${page}`,
`doesn't trim the /${page} route param`
);
}
});
});
await fixture.build();
});
afterEach(() => {
// reset the flag used by [...calledTwiceTest].astro between each test
globalThis.isCalledOnce = false;
});
describe('output: "hybrid"', () => {
describe('getStaticPaths - build calls', () => {
before(async () => {
fixture = await loadFixture({
root: './fixtures/ssr-prerender-get-static-paths/',
site: 'https://mysite.dev/',
adapter: testAdapter(),
base: '/blog',
output: 'hybrid',
experimental: {
hybridOutput: true,
},
vite: {
plugins: [vitePluginRemovePrerenderExport()],
},
});
await fixture.build();
});
it('is only called once during build', () => {
// useless expect; if build() throws in setup then this test fails
expect(true).to.equal(true);
});
after(async () => {
await fixture.clean();
});
it('Astro.url sets the current pathname', async () => {
const html = await fixture.readFile('/food/tacos/index.html');
const $ = cheerio.load(html);
afterEach(() => {
// reset the flag used by [...calledTwiceTest].astro between each test
globalThis.isCalledOnce = false;
});
expect($('#props').text()).to.equal('10');
expect($('#url').text()).to.equal('/blog/food/tacos/');
it('is only called once during build', () => {
// useless expect; if build() throws in setup then this test fails
expect(true).to.equal(true);
});
it('Astro.url sets the current pathname', async () => {
const html = await fixture.readFile('/client/food/tacos/index.html');
const $ = cheerio.load(html);
expect($('#props').text()).to.equal('10');
expect($('#url').text()).to.equal('/blog/food/tacos/');
});
});
describe('getStaticPaths - dev calls', () => {
let devServer;
before(async () => {
globalThis.isCalledOnce = false;
devServer = await fixture.startDevServer();
});
afterEach(() => {
// reset the flag used by [...calledTwiceTest].astro between each test
globalThis.isCalledOnce = false;
});
after(async () => {
devServer.stop();
});
it('only calls hybrid getStaticPaths once', async () => {
let res = await fixture.fetch('/blog/a');
expect(res.status).to.equal(200);
res = await fixture.fetch('/blog/b');
expect(res.status).to.equal(200);
res = await fixture.fetch('/blog/c');
expect(res.status).to.equal(200);
});
describe('404 behavior', () => {
it('resolves 200 on matching static path - named params', async () => {
const res = await fixture.fetch('/blog/pizza/provolone-sausage');
expect(res.status).to.equal(200);
});
it('resolves 404 on pattern match without static path - named params', async () => {
const res = await fixture.fetch('/blog/pizza/provolone-pineapple');
const html = await res.text();
expect(res.status).to.equal(404);
expect(html).to.match(/404/);
});
it('resolves 200 on matching static path - rest params', async () => {
const res = await fixture.fetch('/blog/pizza/grimaldis/new-york');
expect(res.status).to.equal(200);
});
it('resolves 404 on pattern match without static path - rest params', async () => {
const res = await fixture.fetch('/blog/pizza/pizza-hut');
const html = await res.text();
expect(res.status).to.equal(404);
expect(html).to.match(/404/);
});
});
describe('route params type validation', () => {
it('resolves 200 on nested array parameters', async () => {
const res = await fixture.fetch('/blog/nested-arrays/slug1');
expect(res.status).to.equal(200);
});
it('resolves 200 on matching static path - string params', async () => {
// route provided with { params: { year: "2022", slug: "post-2" }}
const res = await fixture.fetch('/blog/blog/2022/post-1');
expect(res.status).to.equal(200);
});
it('resolves 200 on matching static path - numeric params', async () => {
// route provided with { params: { year: 2022, slug: "post-2" }}
const res = await fixture.fetch('/blog/blog/2022/post-2');
expect(res.status).to.equal(200);
});
});
it('resolves 200 on matching static paths', async () => {
// routes params provided for pages /posts/1, /posts/2, and /posts/3
for (const page of [1, 2, 3]) {
let res = await fixture.fetch(`/blog/posts/${page}`);
expect(res.status).to.equal(200);
const html = await res.text();
const $ = cheerio.load(html);
const canonical = $('link[rel=canonical]');
expect(canonical.attr('href')).to.equal(
`https://mysite.dev/blog/posts/${page}`,
`doesn't trim the /${page} route param`
);
}
});
});
});
});
describe('prerender getStaticPaths - dev calls', () => {
let fixture;
let devServer;
before(async () => {
globalThis.isCalledOnce = false;
fixture = await loadFixture({
root: './fixtures/ssr-prerender-get-static-paths/',
site: 'https://mysite.dev/',
});
devServer = await fixture.startDevServer();
});
afterEach(() => {
// reset the flag used by [...calledTwiceTest].astro between each test
globalThis.isCalledOnce = false;
});
after(async () => {
devServer.stop();
});
it('only calls prerender getStaticPaths once', async () => {
let res = await fixture.fetch('/a');
expect(res.status).to.equal(200);
res = await fixture.fetch('/b');
expect(res.status).to.equal(200);
res = await fixture.fetch('/c');
expect(res.status).to.equal(200);
});
describe('404 behavior', () => {
it('resolves 200 on matching static path - named params', async () => {
const res = await fixture.fetch('/pizza/provolone-sausage');
expect(res.status).to.equal(200);
});
it('resolves 404 on pattern match without static path - named params', async () => {
const res = await fixture.fetch('/pizza/provolone-pineapple');
const html = await res.text();
expect(res.status).to.equal(404);
expect(html).to.match(/404/);
});
it('resolves 200 on matching static path - rest params', async () => {
const res = await fixture.fetch('/pizza/grimaldis/new-york');
expect(res.status).to.equal(200);
});
it('resolves 404 on pattern match without static path - rest params', async () => {
const res = await fixture.fetch('/pizza/pizza-hut');
const html = await res.text();
expect(res.status).to.equal(404);
expect(html).to.match(/404/);
});
});
describe('route params type validation', () => {
it('resolves 200 on nested array parameters', async () => {
const res = await fixture.fetch('/nested-arrays/slug1');
expect(res.status).to.equal(200);
});
it('resolves 200 on matching static path - string params', async () => {
// route provided with { params: { year: "2022", slug: "post-2" }}
const res = await fixture.fetch('/blog/2022/post-1');
expect(res.status).to.equal(200);
});
it('resolves 200 on matching static path - numeric params', async () => {
// route provided with { params: { year: 2022, slug: "post-2" }}
const res = await fixture.fetch('/blog/2022/post-2');
expect(res.status).to.equal(200);
});
});
it('resolves 200 on matching static paths', async () => {
// routes params provided for pages /posts/1, /posts/2, and /posts/3
for (const page of [1, 2, 3]) {
let res = await fixture.fetch(`/posts/${page}`);
expect(res.status).to.equal(200);
const html = await res.text();
const $ = cheerio.load(html);
const canonical = $('link[rel=canonical]');
expect(canonical.attr('href')).to.equal(
`https://mysite.dev/posts/${page}`,
`doesn't trim the /${page} route param`
);
}
});
});
/** @returns {import('vite').Plugin} */
function vitePluginRemovePrerenderExport() {
const EXTENSIONS = ['.astro', '.ts'];
/** @type {import('vite').Plugin} */
const plugin = {
name: 'remove-prerender-export',
transform(code, id) {
if (!EXTENSIONS.some((ext) => id.endsWith(ext))) return;
return code.replace(/export\s+const\s+prerender\s+=\s+true;/g, '');
},
};
return {
name: 'remove-prerender-export-injector',
configResolved(resolved) {
resolved.plugins.unshift(plugin);
},
};
}

View file

@ -5756,7 +5756,7 @@ packages:
resolution: {integrity: sha512-kkH7sWzKPq0xt3H1n+ghb4xEMP8k0U7XV3kkB+ZGy69kDk2ySFW1qPi06sjKzFY3t1j6XbJSqr4mF9L7CYVyhg==}
engines: {node: '>=6.9.0'}
dependencies:
'@babel/types': 7.18.4
'@babel/types': 7.21.5
dev: false
/@babel/helper-module-imports@7.21.4:
@ -5850,7 +5850,6 @@ packages:
/@babel/helper-string-parser@7.21.5:
resolution: {integrity: sha512-5pTUx3hAJaZIdW99sJ6ZUUgWq/Y+Hja7TowEnLNMm1VivRgZQL3vpBY3qUACVsvw+yQU6+YgfBVmcbLaZtrA1w==}
engines: {node: '>=6.9.0'}
dev: false
/@babel/helper-validator-identifier@7.19.1:
resolution: {integrity: sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w==}
@ -5904,8 +5903,7 @@ packages:
engines: {node: '>=6.0.0'}
hasBin: true
dependencies:
'@babel/types': 7.18.4
dev: false
'@babel/types': 7.21.5
/@babel/plugin-bugfix-safari-id-destructuring-collision-in-function-expression@7.18.6(@babel/core@7.18.2):
resolution: {integrity: sha512-Dgxsyg54Fx1d4Nge8UnvTrED63vrwOdPmyvPzlNN/boaliRP54pm3pGzZD1SJUwrBA+Cs/xdG8kXX6Mn/RfISQ==}
@ -6993,7 +6991,7 @@ packages:
'@babel/helper-plugin-utils': 7.21.5
'@babel/plugin-proposal-unicode-property-regex': 7.18.6(@babel/core@7.18.2)
'@babel/plugin-transform-dotall-regex': 7.18.6(@babel/core@7.18.2)
'@babel/types': 7.18.4
'@babel/types': 7.21.5
esutils: 2.0.3
dev: false
@ -7066,7 +7064,6 @@ packages:
'@babel/helper-string-parser': 7.21.5
'@babel/helper-validator-identifier': 7.19.1
to-fast-properties: 2.0.0
dev: false
/@builder.io/partytown@0.7.4:
resolution: {integrity: sha512-dcZBPNQiHbMhvDGmdWRFNe75Z/XYmeZ2bubYmC5BeQpF09ObbPcbSqIP2NaNOFonKlWLfsE6u1790o9ZmlfpIw==}
@ -8717,7 +8714,7 @@ packages:
/@ts-morph/common@0.16.0:
resolution: {integrity: sha512-SgJpzkTgZKLKqQniCjLaE3c2L2sdL7UShvmTmPBejAKd2OKV/yfMpQ2IWpAuA+VY5wy7PkSUaEObIqEK6afFuw==}
dependencies:
fast-glob: 3.2.11
fast-glob: 3.2.12
minimatch: 5.1.6
mkdirp: 1.0.4
path-browserify: 1.0.1
@ -9419,7 +9416,7 @@ packages:
/@vue/compiler-core@3.2.47:
resolution: {integrity: sha512-p4D7FDnQb7+YJmO2iPEv0SQNeNzcbHdGByJDsT4lynf63AFkOTFN07HsiRSvjGo0QrxR/o3d0hUyNCUnBU2Tig==}
dependencies:
'@babel/parser': 7.18.4
'@babel/parser': 7.21.8
'@vue/shared': 3.2.47
estree-walker: 2.0.2
source-map: 0.6.1
@ -9492,7 +9489,7 @@ packages:
/@vue/reactivity-transform@3.2.47:
resolution: {integrity: sha512-m8lGXw8rdnPVVIdIFhf0LeQ/ixyHkH5plYuS83yop5n7ggVJU+z5v0zecwEnX7fa7HNLBhh2qngJJkxpwEEmYA==}
dependencies:
'@babel/parser': 7.18.4
'@babel/parser': 7.21.8
'@vue/compiler-core': 3.2.47
'@vue/shared': 3.2.47
estree-walker: 2.0.2
@ -10124,7 +10121,7 @@ packages:
/builtins@5.0.1:
resolution: {integrity: sha512-qwVpFEHNfhYJIzNRBvd2C1kyo6jz3ZSMPyyuR47OPdiKWlbYnZNyDWuyR175qDnAJLiCo5fBBqPb3RiXgWlkOQ==}
dependencies:
semver: 7.3.8
semver: 7.5.1
dev: true
/bundle-name@3.0.0:
@ -14531,7 +14528,7 @@ packages:
resolution: {integrity: sha512-zNy02qivjjRosswoYmPi8hIKJRr8MpQyeKT6qlcq/OnOgA3Rhoae+IYOqsM9V5+JnHWmxKnWOT2GxvtqdtOCXA==}
engines: {node: '>=10'}
dependencies:
semver: 7.3.8
semver: 7.5.1
/node-addon-api@6.1.0:
resolution: {integrity: sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==}
@ -14665,7 +14662,7 @@ packages:
dependencies:
execa: 6.1.0
parse-package-name: 1.0.0
semver: 7.3.8
semver: 7.5.1
validate-npm-package-name: 4.0.0
dev: true