Skip to content

Commit

Permalink
Merge branch 'main' into fix/vercel-builds
Browse files Browse the repository at this point in the history
  • Loading branch information
natemoo-re authored Sep 5, 2023
2 parents 07ee266 + 923a443 commit fd2c50c
Show file tree
Hide file tree
Showing 38 changed files with 262 additions and 82 deletions.
5 changes: 5 additions & 0 deletions .changeset/chatty-walls-happen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixed a case where dynamic imports tried to preload inlined stylesheets.
5 changes: 5 additions & 0 deletions .changeset/fair-countries-admire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/svelte': patch
---

Removed vite warnings.
5 changes: 5 additions & 0 deletions .changeset/hip-cats-jump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fix missing type for `imageConfig` export from `astro:assets`
5 changes: 5 additions & 0 deletions .changeset/spotty-glasses-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/mdx': patch
---

Add location data to MDX compile errors
5 changes: 5 additions & 0 deletions .changeset/twelve-cars-tell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fix markdown page HMR
5 changes: 5 additions & 0 deletions .changeset/weak-kids-roll.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fix scroll position when navigating back from page w/o ViewTransitions
5 changes: 4 additions & 1 deletion .eslintrc.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ module.exports = {
rules: {
// These off/configured-differently-by-default rules fit well for us
'@typescript-eslint/array-type': ['error', { default: 'array-simple' }],
'@typescript-eslint/no-unused-vars': ['error', { ignoreRestSiblings: true }],
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_', ignoreRestSiblings: true },
],
'no-only-tests/no-only-tests': 'error',
'@typescript-eslint/no-shadow': ['error'],
'no-console': 'warn',
Expand Down
2 changes: 1 addition & 1 deletion examples/blog/src/pages/rss.xml.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
import { SITE_TITLE, SITE_DESCRIPTION } from '../consts';

export async function get(context) {
export async function GET(context) {
const posts = await getCollection('blog');
return rss({
title: SITE_TITLE,
Expand Down
10 changes: 5 additions & 5 deletions examples/non-html-pages/src/pages/about.json.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
// Returns the file body for this non-HTML file.
// The content type is based off of the extension in the filename,
// in this case: about.json.
export async function get() {
return {
body: JSON.stringify({
export async function GET() {
return new Response(
JSON.stringify({
name: 'Astro',
url: 'https://astro.build/',
}),
};
})
);
}
16 changes: 7 additions & 9 deletions examples/ssr/src/pages/api/cart.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { APIContext } from 'astro';
import { userCartItems } from '../../models/session';

export function get({ cookies }: APIContext) {
export function GET({ cookies }: APIContext) {
let userId = cookies.get('user-id').value;

if (!userId || !userCartItems.has(userId)) {
Expand All @@ -12,17 +12,15 @@ export function get({ cookies }: APIContext) {
let items = userCartItems.get(userId);
let array = Array.from(items.values());

return {
body: JSON.stringify({ items: array }),
};
return new Response(JSON.stringify({ items: array }));
}

interface AddToCartItem {
id: number;
name: string;
}

export async function post({ cookies, request }: APIContext) {
export async function POST({ cookies, request }: APIContext) {
const item: AddToCartItem = await request.json();

let userId = cookies.get('user-id').value;
Expand All @@ -38,9 +36,9 @@ export async function post({ cookies, request }: APIContext) {
cart.set(item.id, { id: item.id, name: item.name, count: 1 });
}

return {
body: JSON.stringify({
return new Response(
JSON.stringify({
ok: true,
}),
};
})
);
}
6 changes: 2 additions & 4 deletions examples/ssr/src/pages/api/products.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { products } from '../../models/db';

export function get() {
return {
body: JSON.stringify(products),
};
export function GET() {
return new Response(JSON.stringify(products));
}
6 changes: 2 additions & 4 deletions examples/ssr/src/pages/api/products/[id].ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import { productMap } from '../../../models/db';
import type { APIContext } from 'astro';

export function get({ params }: APIContext) {
export function GET({ params }: APIContext) {
const id = Number(params.id);
if (productMap.has(id)) {
const product = productMap.get(id);

return {
body: JSON.stringify(product),
};
return new Response(JSON.stringify(products));
} else {
return new Response(null, {
status: 400,
Expand Down
3 changes: 2 additions & 1 deletion packages/astro/client.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ declare module 'astro:assets' {
| import('./dist/assets/types.js').ImageTransform
| import('./dist/assets/types.js').UnresolvedImageTransform
) => Promise<import('./dist/assets/types.js').GetImageResult>;
imageConfig: import('./dist/@types/astro').AstroConfig['image'];
getConfiguredImageService: typeof import('./dist/assets/index.js').getConfiguredImageService;
Image: typeof import('./components/Image.astro').default;
};
Expand All @@ -69,7 +70,7 @@ declare module 'astro:assets' {
export type RemoteImageProps = Simplify<
import('./dist/assets/types.js').RemoteImageProps<ImgAttributes>
>;
export const { getImage, getConfiguredImageService, Image }: AstroAssets;
export const { getImage, getConfiguredImageService, imageConfig, Image }: AstroAssets;
}

type InputFormat = import('./dist/assets/types.js').ImageInputFormat;
Expand Down
9 changes: 6 additions & 3 deletions packages/astro/components/ViewTransitions.astro
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ const { fallback = 'animate' } = Astro.props as Props;
// The History API does not tell you if navigation is forward or back, so
// you can figure it using an index. On pushState the index is incremented so you
// can use that to determine popstate if going forward or back.
let currentHistoryIndex = history.state?.index || 0;
if (!history.state && transitionEnabledOnThisPage()) {
persistState({ index: currentHistoryIndex, scrollY: 0 });
let currentHistoryIndex = 0;
if (history.state) {
// we reloaded a page with history state (e.g. back button or browser reload)
currentHistoryIndex = history.state.index;
scrollTo({ left: 0, top: history.state.scrollY });
}

const throttle = (cb: (...args: any[]) => any, delay: number) => {
Expand Down Expand Up @@ -352,6 +354,7 @@ const { fallback = 'animate' } = Astro.props as Props;
// The current page doesn't haven't View Transitions,
// respect that with a full page reload
// -- but only for transition managed by us (ev.state is set)
history.scrollRestoration && (history.scrollRestoration = "manual")
location.reload();
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ import Layout from '../components/Layout.astro';

<div><a id="click-one-again" href="/one">go to 1</a></div>
<div><a id="click-scroll-up" href="#longpage">go back up</a></div>
<div><a id="click-external" href="/three">leave ViewTransitions</a></div>

Morbi tristique senectus et netus et. Neque aliquam vestibulum morbi blandit cursus risus. Pharetra pharetra massa massa ultricies mi quis. Sit amet aliquam id diam maecenas ultricies mi eget mauris. Ultrices mi tempus imperdiet nulla malesuada. At consectetur lorem donec massa sapien faucibus et molestie. Non sodales neque sodales ut etiam. Eget nunc lobortis mattis aliquam faucibus purus in massa tempor. Viverra suspendisse potenti nullam ac tortor vitae purus faucibus. Pellentesque eu tincidunt tortor aliquam nulla facilisi cras fermentum. Diam vulputate ut pharetra sit. Felis donec et odio pellentesque diam. Mollis aliquam ut porttitor leo. Vitae nunc sed velit dignissim sodales. Facilisis mauris sit amet massa vitae tortor condimentum lacinia quis.

Aliquet enim tortor at auctor urna nunc id cursus. Bibendum at varius vel pharetra vel turpis nunc eget. Mattis molestie a iaculis at erat. Vel turpis nunc eget lorem dolor sed viverra ipsum nunc. Aliquam malesuada bibendum arcu vitae elementum curabitur vitae nunc sed. Nunc congue nisi vitae suscipit. Donec massa sapien faucibus et molestie ac. Nec feugiat nisl pretium fusce. At imperdiet dui accumsan sit amet nulla facilisi. Sed viverra tellus in hac.
Expand Down
21 changes: 21 additions & 0 deletions packages/astro/e2e/view-transitions.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -502,3 +502,24 @@ test.describe('View Transitions', () => {
await downloadPromise;
});
});

test('Scroll position is restored on back navigation from page w/o ViewTransitions', async ({
page,
astro,
}) => {
// Go to middle of long page
await page.goto(astro.resolveUrl('/long-page#click-external'));

let locator = page.locator('#click-external');
await expect(locator).toBeInViewport();

// Go to a page that has not enabled ViewTransistions
await page.click('#click-external');
locator = page.locator('#three');
await expect(locator).toHaveText('Page 3');

// Scroll back to long page
await page.goBack();
locator = page.locator('#click-external');
await expect(locator).toBeInViewport();
});
24 changes: 12 additions & 12 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@ export interface AstroUserConfig {
* import netlify from '@astrojs/netlify/functions';
* {
* // Example: Build for Netlify serverless deployment
* adapter: netlify(),
* adapter: netlify(),
* }
* ```
*/
Expand All @@ -658,9 +658,9 @@ export interface AstroUserConfig {
*
* Specifies the output target for builds.
*
* - 'static' - Building a static site to be deploy to any static host.
* - 'server' - Building an app to be deployed to a host supporting SSR (server-side rendering).
* - 'hybrid' - Building a static site with a few server-side rendered pages.
* - `'static'` - Building a static site to be deploy to any static host.
* - `'server'` - Building an app to be deployed to a host supporting SSR (server-side rendering).
* - `'hybrid'` - Building a static site with a few server-side rendered pages.
*
* ```js
* import { defineConfig } from 'astro/config';
Expand All @@ -685,8 +685,8 @@ export interface AstroUserConfig {
* @default `'directory'`
* @description
* Control the output file format of each page.
* - If 'file', Astro will generate an HTML file (ex: "/foo.html") for each page.
* - If 'directory', Astro will generate a directory with a nested `index.html` file (ex: "/foo/index.html") for each page.
* - If `'file'`, Astro will generate an HTML file (ex: "/foo.html") for each page.
* - If `'directory'`, Astro will generate a directory with a nested `index.html` file (ex: "/foo/index.html") for each page.
*
* ```js
* {
Expand Down Expand Up @@ -970,7 +970,7 @@ export interface AstroUserConfig {
/**
* @docs
* @kind heading
* @name Image options
* @name Image Options
*/
image?: {
/**
Expand All @@ -980,7 +980,7 @@ export interface AstroUserConfig {
* @default `{entrypoint: 'astro/assets/services/sharp', config?: {}}`
* @version 2.1.0
* @description
* Set which image service is used for Astro’s experimental assets support.
* Set which image service is used for Astro’s assets support.
*
* The value should be an object with an entrypoint for the image service to use and optionally, a config object to pass to the service.
*
Expand All @@ -1004,7 +1004,7 @@ export interface AstroUserConfig {
* @default `{domains: []}`
* @version 2.10.10
* @description
* Defines a list of permitted image source domains for local image optimization. No other remote images will be optimized by Astro.
* Defines a list of permitted image source domains for remote image optimization. No other remote images will be optimized by Astro.
*
* This option requires an array of individual domain names as strings. Wildcards are not permitted. Instead, use [`image.remotePatterns`](#imageremotepatterns) to define a list of allowed source URL patterns.
*
Expand All @@ -1027,7 +1027,7 @@ export interface AstroUserConfig {
* @default `{remotePatterns: []}`
* @version 2.10.10
* @description
* Defines a list of permitted image source URL patterns for local image optimization.
* Defines a list of permitted image source URL patterns for remote image optimization.
*
* `remotePatterns` can be configured with four properties:
* 1. protocol
Expand Down Expand Up @@ -1779,11 +1779,11 @@ export type AstroFeatureMap = {
export interface AstroAssetsFeature {
supportKind?: SupportsKind;
/**
* Whether if this adapter deploys files in an enviroment that is compatible with the library `sharp`
* Whether if this adapter deploys files in an environment that is compatible with the library `sharp`
*/
isSharpCompatible?: boolean;
/**
* Whether if this adapter deploys files in an enviroment that is compatible with the library `squoosh`
* Whether if this adapter deploys files in an environment that is compatible with the library `squoosh`
*/
isSquooshCompatible?: boolean;
}
Expand Down
2 changes: 0 additions & 2 deletions packages/astro/src/core/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,6 @@ export class App {
}
return pathname;
}
// Disable no-unused-vars to avoid breaking signature change
// eslint-disable-next-line @typescript-eslint/no-unused-vars
match(request: Request, _opts: MatchOptions = {}): RouteData | undefined {
const url = new URL(request.url);
// ignore requests matching public assets
Expand Down
4 changes: 1 addition & 3 deletions packages/astro/src/core/build/plugins/plugin-css.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] {
const inlineConfig = settings.config.build.inlineStylesheets;
const { assetsInlineLimit = 4096 } = settings.config.vite?.build ?? {};

Object.entries(bundle).forEach(([id, stylesheet]) => {
Object.entries(bundle).forEach(([_, stylesheet]) => {
if (
stylesheet.type !== 'asset' ||
stylesheet.name?.endsWith('.css') !== true ||
Expand All @@ -217,8 +217,6 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] {
? false
: assetSize <= assetsInlineLimit;

if (toBeInlined) delete bundle[id];

// there should be a single js object for each stylesheet,
// allowing the single reference to be shared and checked for duplicates
const sheet: StylesheetAsset = toBeInlined
Expand Down
5 changes: 2 additions & 3 deletions packages/astro/src/vite-plugin-markdown/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export default function markdown({ settings, logger }: AstroPluginOptions): Plug
}

const code = escapeViteEnvReferences(`
import { unescapeHTML, spreadAttributes, createComponent, render, renderComponent } from ${JSON.stringify(
import { unescapeHTML, spreadAttributes, createComponent, render, renderComponent, maybeRenderHead } from ${JSON.stringify(
astroServerRuntimeModulePath
)};
import { AstroError, AstroErrorData } from ${JSON.stringify(astroErrorModulePath)};
Expand Down Expand Up @@ -180,10 +180,9 @@ export default function markdown({ settings, logger }: AstroPluginOptions): Plug
}, {
'default': () => render\`\${unescapeHTML(html)}\`
})}\`;`
: `render\`\${unescapeHTML(html)}\`;`
: `render\`\${maybeRenderHead(result)}\${unescapeHTML(html)}\`;`
}
});
Content[Symbol.for('astro.needsHeadRendering')] = ${layout ? 'false' : 'true'};
export default Content;
`);

Expand Down
5 changes: 5 additions & 0 deletions packages/astro/test/astro-pages.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,10 @@ describe('Pages', () => {

expect($('#testing').length).to.be.greaterThan(0);
});

it('should have Vite client in dev', async () => {
const html = await fixture.fetch('/').then((res) => res.text());
expect(html).to.include('/@vite/client', 'Markdown page does not have Vite client for HMR');
});
});
});
36 changes: 36 additions & 0 deletions packages/astro/test/css-dangling-references.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { expect } from 'chai';
import { loadFixture } from './test-utils.js';

const cssAssetReferenceRegExp = /_astro\/[A-Za-z0-9\-]+\.[a0-9a-f]{8}\.css/g;

describe("When Vite's preloadModule polyfill is used", async () => {
let fixture;

before(async () => {
fixture = await loadFixture({
root: './fixtures/css-dangling-references/',
});
await fixture.build();
});

it('there are no references to deleted CSS chunks', async () => {
const fileNames = await fixture.readdir('/_astro/');
const filePaths = fileNames.map((filename) => '_astro/' + filename);

const expectations = filePaths
.filter((filePath) => filePath.endsWith('js'))
.map(async (filePath) => {
const contents = await fixture.readFile(filePath);
const cssReferences = contents.match(cssAssetReferenceRegExp);

if (cssReferences === null) return;

expect(filePaths).to.contain.members(
cssReferences,
filePath + ' contains a reference to a deleted css asset: ' + cssReferences
);
});

await Promise.all(expectations);
});
});
Loading

0 comments on commit fd2c50c

Please sign in to comment.