Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 20 commits into from May 22, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/astro/src/core/build/plugins/plugin-prerender.ts
Expand Up @@ -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/utils.js';

function vitePluginPrerender(opts: StaticBuildOptions, internals: BuildInternals): VitePlugin {
return {
Expand All @@ -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';
}
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/endpoint/index.ts
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/render/core.ts
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions packages/astro/src/core/render/dev/index.ts
Expand Up @@ -66,6 +66,9 @@ export async function preload({
try {
// Load the module from the Vite SSR Runtime.
const mod = (await env.loader.import(fileURLToPath(filePath))) as ComponentInstance;

// we should here set the prerender metadata of the module

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
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/core/render/route-cache.ts
Expand Up @@ -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.
Expand Down
6 changes: 3 additions & 3 deletions packages/astro/src/core/routing/manifest/create.ts
Expand Up @@ -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();

Expand Down Expand Up @@ -340,7 +340,7 @@ export function createRouteManifest(
component,
generate,
pathname: pathname || undefined,
prerender: isPrenderDefault,
prerender: isPrerenderDefault,
});
}
});
Expand Down Expand Up @@ -416,7 +416,7 @@ export function createRouteManifest(
component,
generate,
pathname: pathname || void 0,
prerender: isPrenderDefault,
prerender: isPrerenderDefault,
});
});

Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/core/routing/validation.ts
Expand Up @@ -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 },
Expand Down
19 changes: 19 additions & 0 deletions packages/astro/src/prerender/status.ts
MoustaphaDev marked this conversation as resolved.
Show resolved Hide resolved
@@ -0,0 +1,19 @@
import type { ModuleLoader } from '../core/module-loader';
import { viteID } from '../core/util.js';
import { getPrerenderMetadata } from './utils.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;
}
5 changes: 5 additions & 0 deletions packages/astro/src/prerender/utils.ts
@@ -1,6 +1,7 @@
// TODO: remove after the experimetal phase when

import type { AstroConfig } from '../@types/astro';
import type { ModuleInfo } from '../core/module-loader';

export function isHybridMalconfigured(config: AstroConfig) {
return config.experimental.hybridOutput ? config.output !== 'hybrid' : config.output === 'hybrid';
Expand All @@ -9,3 +10,7 @@ export function isHybridMalconfigured(config: AstroConfig) {
export function isHybridOutput(config: AstroConfig) {
return config.experimental.hybridOutput && config.output === 'hybrid';
}

export function getPrerenderMetadata(moduleInfo: ModuleInfo) {
return moduleInfo?.meta?.astro?.pageOptions?.prerender === true;
}
12 changes: 12 additions & 0 deletions packages/astro/src/vite-plugin-astro-server/route.ts
Expand Up @@ -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/status.js';

type AsyncReturnType<T extends (...args: any) => Promise<any>> = T extends (
...args: any
Expand Down Expand Up @@ -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 });

const prerenderStatus =
getPrerenderStatus({
filePath,
loader: env.loader,
}) ?? maybeRoute.prerender;

if (prerenderStatus !== undefined) {
maybeRoute.prerender = prerenderStatus;
}

const [, mod] = preloadedComponent;
// attempt to get static paths
// if this fails, we have a bad URL match!
Expand Down
@@ -0,0 +1,8 @@
{
"name": "@test/ssr-hybrid-get-static-paths",
"version": "0.0.0",
"private": true,
"dependencies": {
"astro": "workspace:*"
}
}
@@ -0,0 +1,21 @@
---
export function getStaticPaths({ paginate }) {
if (globalThis.isCalledOnce) {
throw new Error("Can only be called once!");
}
globalThis.isCalledOnce = true;
return [
{params: {calledTwiceTest: 'a'}},
{params: {calledTwiceTest: 'b'}},
{params: {calledTwiceTest: 'c'}},
];
}
const { params } = Astro;
---

<html>
<head>
<title>Page {params.calledTwiceTest}</title>
</head>
<body></body>
</html>
@@ -0,0 +1,18 @@
---
export async function getStaticPaths() {
return [
{ params: { year: '2022', slug: 'post-1' } },
{ params: { year: 2022, slug: 'post-2' } },
{ params: { slug: 'post-2', year: '2022' } },
]
}

const { year, slug } = Astro.params
---

<html>
<head>
<title>{year} | {slug}</title>
</head>
<body></body>
</html>
@@ -0,0 +1,14 @@
export async function getStaticPaths() {
return [
{ params: { slug: 'thing1' } },
{ params: { slug: 'thing2' } }
];
}

export async function get() {
return {
body: JSON.stringify({
title: '[slug]'
}, null, 4)
};
}
@@ -0,0 +1,32 @@
---
export async function getStaticPaths() {
return [
{
params: { name: 'tacos' },
props: { yum: 10 },
},
{
params: { name: 'potatoes' },
props: { yum: 7 },
},
{
params: { name: 'spaghetti' },
props: { yum: 5 },
}
]
}

const { yum } = Astro.props;
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Food</title>
</head>
<body>
<p id="url">{ Astro.url.pathname }</p>
<p id="props">{ yum }</p>
</body>
</html>
@@ -0,0 +1,9 @@
---
export function getStaticPaths() {
return [
[ { params: {slug: "slug1"} } ],
[ { params: {slug: "slug2"} } ],
]
}

---
@@ -0,0 +1,22 @@
---
export function getStaticPaths() {
return [{
params: { pizza: 'papa-johns' },
}, {
params: { pizza: 'dominos' },
}, {
params: { pizza: 'grimaldis/new-york' },
}]
}
const { pizza } = Astro.params
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>{pizza ?? 'The landing page'}</title>
</head>
<body>
<h1>Welcome to {pizza ?? 'The landing page'}</h1>
</body>
</html>
@@ -0,0 +1,21 @@
---
export function getStaticPaths() {
return [{
params: { cheese: 'mozzarella', topping: 'pepperoni' },
}, {
params: { cheese: 'provolone', topping: 'sausage' },
}]
}
const { cheese, topping } = Astro.params
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>{cheese}</title>
</head>
<body>
<h1>🍕 It's pizza time</h1>
<p>{cheese}-{topping}</p>
</body>
</html>
@@ -0,0 +1,29 @@
---
export async function getStaticPaths() {
return [
{
params: { page: 1 },
},
{
params: { page: 2 },
},
{
params: { page: 3 }
}
]
};
const { page } = Astro.params
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Posts Page {page}</title>
<link rel="canonical" href={canonicalURL.href}>
</head>
<body>
<h1>Welcome to page {page}</h1>
</body>
</html>