Compare commits

...

3 commits

Author SHA1 Message Date
unknown
dea43095c2 Define a site for examples that need it 2022-07-12 16:16:03 -04:00
unknown
a1e924e760 Fix custom 404 test 2022-07-12 16:06:13 -04:00
unknown
e9a751bccd Remove Astro.canonicalURL and make Astro.site match config 2022-07-12 15:24:24 -04:00
32 changed files with 53 additions and 117 deletions

View file

@ -5,4 +5,5 @@ import preact from '@astrojs/preact';
export default defineConfig({
// Enable the Preact integration to support Preact JSX components.
integrations: [preact()],
site: `http://astro.build`
});

View file

@ -1,10 +1,9 @@
---
import MainHead from "../components/MainHead.astro";
import Nav from "../components/Nav.astro";
import authorData from "../data/authors.json";
const { content } = Astro.props;
let canonicalURL = Astro.canonicalURL;
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
---
<html lang={content.lang || "en"}>

View file

@ -4,7 +4,7 @@ import Nav from "../components/Nav.astro";
let title = "About";
let description = "About page of an example blog on Astro";
let canonicalURL = Astro.canonicalURL;
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
---
<html lang="en">

View file

@ -13,6 +13,7 @@ export async function getStaticPaths() {
const { allPosts } = Astro.props;
const title = "Dons Blog";
const description = "An example blog on Astro";
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
/** filter posts by author, sort by date */
const posts = allPosts
@ -28,7 +29,7 @@ const author = authorData[posts[0].frontmatter.author];
{title}
{description}
image={posts[0].frontmatter.image}
canonicalURL={Astro.canonicalURL.toString()}
canonicalURL={canonicalURL.toString()}
/>
<style lang="scss">

View file

@ -12,7 +12,7 @@ import authorData from "../data/authors.json";
// All variables are available to use in the HTML template below.
let title = "Dons Blog";
let description = "An example blog on Astro";
let canonicalURL = Astro.canonicalURL;
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
// Data Fetching: List all Markdown posts in the repo.
let allPosts = await Astro.glob("./post/*.md");

View file

@ -32,7 +32,7 @@ export async function getStaticPaths({ paginate, rss }) {
// page
const title = "Dons Blog";
const description = "An example blog on Astro";
const { canonicalURL } = Astro;
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
const { page } = Astro.props;
---

View file

@ -4,4 +4,5 @@ import preact from '@astrojs/preact';
// https://astro.build/config
export default defineConfig({
integrations: [preact()],
site: `http://astro.build`
});

View file

@ -6,6 +6,7 @@ export interface Props {
description: string;
}
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
const { title, description } = Astro.props;
---
@ -21,14 +22,14 @@ const { title, description } = Astro.props;
<!-- Open Graph / Facebook -->
<meta property="og:type" content="website" />
<meta property="og:url" content={Astro.canonicalURL} />
<meta property="og:url" content={canonicalURL} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content="https://astro.build/social.png" />
<!-- Twitter -->
<meta property="twitter:card" content="summary_large_image" />
<meta property="twitter:url" content={Astro.canonicalURL} />
<meta property="twitter:url" content={canonicalURL} />
<meta property="twitter:title" content={title} />
<meta property="twitter:description" content={description} />
<meta property="twitter:image" content="https://astro.build/social.png" />

View file

@ -10,4 +10,5 @@ export default defineConfig({
// Enable React for the Algolia search component.
react(),
],
site: `http://astro.build`
});

View file

@ -5,7 +5,9 @@ export interface Props {
site: any;
canonicalURL: URL | string;
}
const { content = {}, canonicalURL } = Astro.props;
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
const { content = {} } = Astro.props;
const formattedContentTitle = content.title ? `${content.title} 🚀 ${SITE.title}` : SITE.title;
const imageSrc = content?.image?.src ?? OPEN_GRAPH.image.src;
const canonicalImageSrc = new URL(imageSrc, Astro.site);

View file

@ -9,6 +9,7 @@ import RightSidebar from "../components/RightSidebar/RightSidebar.astro";
import * as CONFIG from "../config";
const { content = {} } = Astro.props;
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
const currentPage = new URL(Astro.request.url).pathname;
const currentFile = `src/pages${currentPage.replace(/\/$/, "")}.md`;
const githubEditUrl = CONFIG.GITHUB_EDIT_URL && CONFIG.GITHUB_EDIT_URL + currentFile;
@ -17,7 +18,7 @@ const githubEditUrl = CONFIG.GITHUB_EDIT_URL && CONFIG.GITHUB_EDIT_URL + current
<html dir={content.dir ?? "ltr"} lang={content.lang ?? "en-us"} class="initial">
<head>
<HeadCommon />
<HeadSEO {content} canonicalURL={Astro.canonicalURL} />
<HeadSEO {content} canonicalURL={canonicalURL} />
<title>{content.title ? `${content.title} 🚀 ${CONFIG.SITE.title}` : CONFIG.SITE.title}</title>
<style>
body {

View file

@ -82,7 +82,7 @@
"test:e2e:match": "playwright test -g"
},
"dependencies": {
"@astrojs/compiler": "^0.18.2",
"@astrojs/compiler": "no-canonical",
"@astrojs/language-server": "^0.13.4",
"@astrojs/markdown-remark": "^0.11.5",
"@astrojs/prism": "0.5.0",

View file

@ -87,11 +87,6 @@ export interface BuildConfig {
* [Astro reference](https://docs.astro.build/reference/api-reference/#astro-global)
*/
export interface AstroGlobal extends AstroGlobalPartial {
/** Canonical URL of the current page. If the [site](https://docs.astro.build/en/reference/configuration-reference/#site) config option is set, its origin will be the origin of this URL.
*
* [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrocanonicalurl)
*/
canonicalURL: URL;
/** Parameters passed to a dynamic page generated using [getStaticPaths](https://docs.astro.build/en/reference/api-reference/#getstaticpaths)
*
* Example usage:
@ -222,11 +217,9 @@ export interface AstroGlobalPartial {
/**
* Returns a [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object built from the [site](https://docs.astro.build/en/reference/configuration-reference/#site) config option
*
* If `site` is undefined, the URL object will instead be built from `localhost`
*
* [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrosite)
*/
site: URL;
site: URL | undefined;
}
type ServerConfig = {

View file

@ -119,11 +119,7 @@ export const AstroConfigSchema = z.object({
.string()
.url()
.optional()
.transform((val) => (val ? appendForwardSlash(val) : val))
.refine((val) => !val || new URL(val).pathname.length <= 1, {
message:
'"site" must be a valid URL origin (ex: "https://example.com") but cannot contain a URL path (ex: "https://example.com/blog"). Use "base" to configure your deployed URL path',
}),
.transform((val) => (val ? appendForwardSlash(val) : val)),
base: z
.string()
.optional()

View file

@ -13,7 +13,7 @@ import type {
import { renderSlot } from '../../runtime/server/index.js';
import { LogOptions, warn } from '../logger/core.js';
import { isScriptRequest } from './script.js';
import { createCanonicalURL, isCSSRequest } from './util.js';
import { isCSSRequest } from './util.js';
function onlyAvailableInSSR(name: string) {
return function _onlyAvailableInSSR() {
@ -104,16 +104,10 @@ class Slots {
let renderMarkdown: any = null;
function isPaginatedRoute({ page }: { page?: Page }) {
return page && 'currentPage' in page;
}
export function createResult(args: CreateResultArgs): SSRResult {
const { markdown, params, pathname, props: pageProps, renderers, request, resolve, site } = args;
const { markdown, params, pathname, props: pageProps, renderers, request, resolve } = args;
const paginated = isPaginatedRoute(pageProps);
const url = new URL(request.url);
const canonicalURL = createCanonicalURL('.' + pathname, site ?? url.origin, paginated);
const headers = new Headers();
if (args.streaming) {
headers.set('Transfer-Encoding', 'chunked');
@ -150,7 +144,6 @@ export function createResult(args: CreateResultArgs): SSRResult {
const Astro = {
__proto__: astroGlobal,
canonicalURL,
params,
props,
request,

View file

@ -2,18 +2,6 @@ import npath from 'path-browserify';
import type { ModuleNode, ViteDevServer } from 'vite';
import type { Metadata } from '../../runtime/server/metadata.js';
/** Normalize URL to its canonical form */
export function createCanonicalURL(url: string, base?: string, paginated?: boolean): URL {
let pathname = url.replace(/\/index.html$/, ''); // index.html is not canonical
// Only trim the first page's /1 param if Astro's paginated() was used
if (paginated) {
pathname = pathname.replace(/\/1\/?$/, ''); // neither is a trailing /1/ (impl. detail of collections)
}
if (!npath.extname(pathname)) pathname = pathname.replace(/(\/+)?$/, '/'); // add trailing slash if theres no extension
pathname = pathname.replace(/\/+/g, '/'); // remove duplicate slashes (URL() wont)
return new URL(pathname, base);
}
/** Check if a URL is already valid */
export function isValidURL(url: string): boolean {
try {

View file

@ -34,16 +34,6 @@ export function createRequest({
});
Object.defineProperties(request, {
canonicalURL: {
get() {
warn(
logging,
'deprecation',
`Astro.request.canonicalURL has been moved to Astro.canonicalURL`
);
return undefined;
},
},
params: {
get() {
warn(logging, 'deprecation', `Astro.request.params has been moved to Astro.params`);

View file

@ -493,11 +493,11 @@ function createAstroGlobFn() {
// Inside of getStaticPaths.
export function createAstro(
filePathname: string,
_site: string,
_site: string | undefined,
projectRootStr: string
): AstroGlobalPartial {
const site = new URL(_site);
const url = new URL(filePathname, site);
const site = _site ? new URL(_site) : undefined;
const referenceURL = new URL(filePathname, `http://localhost`);
const projectRoot = new URL(projectRootStr);
return {
site,
@ -505,7 +505,7 @@ export function createAstro(
glob: createAstroGlobFn(),
// INVESTIGATE is there a use-case for multi args?
resolve(...segments: string[]) {
let resolved = segments.reduce((u, segment) => new URL(segment, u), url).pathname;
let resolved = segments.reduce((u, segment) => new URL(segment, u), referenceURL).pathname;
// When inside of project root, remove the leading path so you are
// left with only `/src/images/tower.png`
if (resolved.startsWith(projectRoot.pathname)) {

View file

@ -77,9 +77,7 @@ async function compile({
// For Windows compat, prepend the module ID with `/@fs`
pathname: `/@fs${prependForwardSlash(moduleId)}`,
projectRoot: config.root.toString(),
site: config.site
? new URL(config.base, config.site).toString()
: `http://localhost:${config.server.port}/`,
site: config.site?.toString(),
sourcefile: filename,
sourcemap: 'both',
internalURL: `/@fs${prependForwardSlash(

View file

@ -100,8 +100,8 @@ describe('getStaticPaths - numeric route params', () => {
const canonical = $('link[rel=canonical]');
expect(canonical.attr('href')).to.equal(
`https://mysite.dev/posts/${page}/`,
`doesn't trim the /${page}/ route param`
`https://mysite.dev/posts/${page}`,
`doesn't trim the /${page} route param`
);
}
});

View file

@ -8,7 +8,7 @@ describe('Astro Global', () => {
before(async () => {
fixture = await loadFixture({
root: './fixtures/astro-global/',
site: 'https://mysite.dev/',
site: 'https://mysite.dev/blog/',
base: '/blog',
});
});
@ -50,23 +50,6 @@ describe('Astro Global', () => {
expect($('#nested-child-pathname').text()).to.equal('/blog/');
});
it('Astro.canonicalURL', async () => {
// given a URL, expect the following canonical URL
const canonicalURLs = {
'/index.html': 'https://mysite.dev/blog/',
'/post/post/index.html': 'https://mysite.dev/blog/post/post/',
'/posts/1/index.html': 'https://mysite.dev/blog/posts/',
'/posts/2/index.html': 'https://mysite.dev/blog/posts/2/',
};
for (const [url, canonicalURL] of Object.entries(canonicalURLs)) {
const html = await fixture.readFile(url);
const $ = cheerio.load(html);
expect($('link[rel="canonical"]').attr('href')).to.equal(canonicalURL);
}
});
it('Astro.site', async () => {
const html = await fixture.readFile('/index.html');
const $ = cheerio.load(html);
@ -134,27 +117,10 @@ describe('Astro Global Defaults', () => {
expect($('#nested-child-pathname').text()).to.equal('/');
});
it('Astro.canonicalURL', async () => {
// given a URL, expect the following canonical URL
const canonicalURLs = {
'/index.html': /http:\/\/localhost:\d+\//,
'/post/post/index.html': /http:\/\/localhost:\d+\/post\/post\//,
'/posts/1/index.html': /http:\/\/localhost:\d+\/posts\//,
'/posts/2/index.html': /http:\/\/localhost:\d+\/posts\/2\//,
};
for (const [url, canonicalURL] of Object.entries(canonicalURLs)) {
const html = await fixture.readFile(url);
const $ = cheerio.load(html);
expect($('link[rel="canonical"]').attr('href')).to.match(canonicalURL);
}
});
it('Astro.site', async () => {
const html = await fixture.readFile('/index.html');
const $ = cheerio.load(html);
expect($('#site').attr('href')).to.match(/http:\/\/localhost:\d+\//);
expect($('#site').attr('href')).to.equal(undefined);
});
});
});

View file

@ -8,6 +8,7 @@ describe('Custom 404', () => {
before(async () => {
fixture = await loadFixture({
root: './fixtures/custom-404/',
site: 'http://example.com',
});
});
@ -35,7 +36,7 @@ describe('Custom 404', () => {
$ = cheerio.load(html);
expect($('h1').text()).to.equal('Page not found');
expect($('p').text()).to.equal('/a/');
expect($('p').text()).to.equal('/a');
});
});
});

View file

@ -14,6 +14,7 @@ export async function getStaticPaths() {
};
const { page } = Astro.params
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
---
<html lang="en">
@ -21,7 +22,7 @@ const { page } = Astro.params
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Posts Page {page}</title>
<link rel="canonical" href={Astro.canonicalURL.href}>
<link rel="canonical" href={canonicalURL.href}>
</head>
<body>
<h1>Welcome to page {page}</h1>

View file

@ -1,10 +1,11 @@
---
const { content } = Astro.props;
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site ?? `http://example.com`);
---
<html>
<head>
<title>{content.title}</title>
<link rel="canonical" href={Astro.canonicalURL.href}>
<link rel="canonical" href={canonicalURL.href}>
</head>
<body>
<slot></slot>

View file

@ -1,10 +1,11 @@
---
import Child from '../components/Child.astro';
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site ?? `http://example.com`);
---
<html>
<head>
<title>Test</title>
<link rel="canonical" href={Astro.canonicalURL.href}>
<link rel="canonical" href={canonicalURL.href}>
</head>
<body>
<div id="pathname">{new URL(Astro.request.url).pathname}</div>

View file

@ -4,7 +4,7 @@ export async function getStaticPaths({paginate}) {
return paginate(data, {pageSize: 1});
}
const { page } = Astro.props;
const { params, canonicalURL } = Astro;
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site ?? `http://example.com`);
---
<html>
@ -13,7 +13,7 @@ const { params, canonicalURL } = Astro;
<link rel="canonical" href={canonicalURL.href} />
</head>
<body>
{page.data.map((data) => (
{page.data.map((data: any) => (
<div>
<h1>{data.frontmatter.title}</h1>
<a class="post-url" href={data.url}>Read</a>

View file

@ -1,9 +1,10 @@
---
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
---
<html>
<head>
<title>Test</title>
<link rel="canonical" href={Astro.canonicalURL.href}>
<link rel="canonical" href={canonicalURL.href}>
</head>
<body>
<div id="pathname">{new URL(Astro.request.url).pathname}</div>

View file

@ -11,7 +11,8 @@ export async function getStaticPaths({paginate}) {
});
}
const { page, filter } = Astro.props;
const { params, canonicalURL} = Astro;
const { params } = Astro;
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
---
<html>

View file

@ -3,8 +3,7 @@ export async function getStaticPaths({paginate}) {
const data = await Astro.glob('../../post/*.md');
return paginate(data, {pageSize: 1});
}
const { page } = Astro.props;
const { params, canonicalURL} = Astro;
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
---
<html>

View file

@ -3,8 +3,7 @@ export async function getStaticPaths({paginate}) {
const data = await Astro.glob('../../post/*.md');
return paginate(data, {pageSize: 1});
}
const { page } = Astro.props;
const { params, canonicalURL} = Astro;
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
---
<html>

View file

@ -1,4 +1,5 @@
---
const canonicalURL = new URL(new URL(Astro.request.url).pathname, Astro.site);
---
<html lang="en">
@ -7,6 +8,6 @@
</head>
<body>
<h1>Page not found</h1>
<p>{Astro.canonicalURL.pathname}</p>
<p>{canonicalURL.pathname}</p>
</body>
</html>

View file

@ -465,7 +465,7 @@ importers:
packages/astro:
specifiers:
'@astrojs/compiler': ^0.18.2
'@astrojs/compiler': no-canonical
'@astrojs/language-server': ^0.13.4
'@astrojs/markdown-remark': ^0.11.5
'@astrojs/prism': 0.5.0
@ -550,7 +550,7 @@ importers:
yargs-parser: ^21.0.1
zod: ^3.17.3
dependencies:
'@astrojs/compiler': 0.18.2
'@astrojs/compiler': 0.19.0-pre.0
'@astrojs/language-server': 0.13.4
'@astrojs/markdown-remark': link:../markdown/remark
'@astrojs/prism': link:../astro-prism
@ -2640,8 +2640,8 @@ packages:
leven: 3.1.0
dev: true
/@astrojs/compiler/0.18.2:
resolution: {integrity: sha512-R2lOpaif3hDju2/sE6OrKvnTMgrcLRJw+jAVih9pLA2ATgy2EnhYMhflRk1vQ6+YwuhyL6Lj/dRJFXgB7r70eg==}
/@astrojs/compiler/0.19.0-pre.0:
resolution: {integrity: sha512-DHmuBQbSI5rhGRPMqiiDHSeb0DszBS6YPHq+FSp9Tw3HvwNZMYoDDpgGxq63tAfQz/xfaxkb7tVm84/nEIrKpw==}
dev: false
/@astrojs/language-server/0.13.4: