diff --git a/biome.json b/biome.json index 9da3b4db06..8effd9cfce 100644 --- a/biome.json +++ b/biome.json @@ -29,7 +29,7 @@ "linter": { "enabled": false }, "javascript": { "formatter": { - "trailingCommas": "es5", + "trailingCommas": "all", "quoteStyle": "single", "semicolons": "always" } diff --git a/examples/blog/src/pages/blog/index.astro b/examples/blog/src/pages/blog/index.astro index 5dfb9c9c61..a1019da5b9 100644 --- a/examples/blog/src/pages/blog/index.astro +++ b/examples/blog/src/pages/blog/index.astro @@ -7,7 +7,7 @@ import { getCollection } from 'astro:content'; import FormattedDate from '../../components/FormattedDate.astro'; const posts = (await getCollection('blog')).sort( - (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf() + (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(), ); --- diff --git a/examples/portfolio/src/pages/work.astro b/examples/portfolio/src/pages/work.astro index 14fe4945ac..233c760bf8 100644 --- a/examples/portfolio/src/pages/work.astro +++ b/examples/portfolio/src/pages/work.astro @@ -9,7 +9,7 @@ import Hero from '../components/Hero.astro'; import Grid from '../components/Grid.astro'; const projects = (await getCollection('work')).sort( - (a, b) => b.data.publishDate.valueOf() - a.data.publishDate.valueOf() + (a, b) => b.data.publishDate.valueOf() - a.data.publishDate.valueOf(), ); --- diff --git a/packages/astro-prism/README.md b/packages/astro-prism/README.md index f5627d0620..b2dff218c2 100644 --- a/packages/astro-prism/README.md +++ b/packages/astro-prism/README.md @@ -29,6 +29,6 @@ runHighlighterWithAstro(
{helloAstro}
`, - 'astro' + 'astro', ); ``` diff --git a/packages/astro-prism/src/plugin.ts b/packages/astro-prism/src/plugin.ts index a50b9d7ef6..057433f404 100644 --- a/packages/astro-prism/src/plugin.ts +++ b/packages/astro-prism/src/plugin.ts @@ -10,7 +10,7 @@ export function addAstro(Prism: typeof import('prismjs')) { scriptLang = 'javascript'; // eslint-disable-next-line no-console console.warn( - 'Prism TypeScript language not loaded, Astro scripts will be treated as JavaScript.' + 'Prism TypeScript language not loaded, Astro scripts will be treated as JavaScript.', ); } @@ -41,7 +41,7 @@ export function addAstro(Prism: typeof import('prismjs')) { (Prism.languages.astro as any).tag.pattern = re( /<\/?(?:[\w.:-]+(?:+(?:[\w.:$-]+(?:=(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s{'"/>=]+|))?|))**\/?)?>/ - .source + .source, ); (Prism.languages.astro as any).tag.inside['tag'].pattern = /^<\/?[^\s>/]*/; @@ -60,7 +60,7 @@ export function addAstro(Prism: typeof import('prismjs')) { inside: Prism.languages.astro, }, }, - (Prism.languages.astro as any).tag + (Prism.languages.astro as any).tag, ); Prism.languages.insertBefore( @@ -80,7 +80,7 @@ export function addAstro(Prism: typeof import('prismjs')) { alias: `language-${scriptLang}`, }, }, - (Prism.languages.astro as any).tag + (Prism.languages.astro as any).tag, ); // The following will handle plain text inside tags diff --git a/packages/astro-rss/src/index.ts b/packages/astro-rss/src/index.ts index 84cdad0d90..b84e81e739 100644 --- a/packages/astro-rss/src/index.ts +++ b/packages/astro-rss/src/index.ts @@ -73,8 +73,8 @@ const rssOptionsValidator = z.object({ // eslint-disable-next-line console.warn( yellow( - '[RSS] Passing a glob result directly has been deprecated. Please migrate to the `pagesGlobToRssItems()` helper: https://docs.astro.build/en/guides/rss/' - ) + '[RSS] Passing a glob result directly has been deprecated. Please migrate to the `pagesGlobToRssItems()` helper: https://docs.astro.build/en/guides/rss/', + ), ); return pagesGlobToRssItems(items); } @@ -123,7 +123,7 @@ async function validateRssOptions(rssOptions: RSSOptions) { return message; }), - ].join('\n') + ].join('\n'), ); throw formattedError; } @@ -134,7 +134,7 @@ export function pagesGlobToRssItems(items: GlobResult): Promise zodError.message), - ].join('\n') + ].join('\n'), ); (formattedError as any).file = filePath; throw formattedError; - }) + }), ); } @@ -207,7 +207,7 @@ async function generateRSS(rssOptions: ValidatedRSSOptions): Promise { if (typeof rssOptions.customData === 'string') Object.assign( root.rss.channel, - parser.parse(`${rssOptions.customData}`).channel + parser.parse(`${rssOptions.customData}`).channel, ); // items root.rss.channel.item = items.map((result) => { @@ -250,7 +250,7 @@ async function generateRSS(rssOptions: ValidatedRSSOptions): Promise { } if (result.source) { item.source = parser.parse( - `${result.source.title}` + `${result.source.title}`, ).source; } if (result.enclosure) { @@ -258,7 +258,7 @@ async function generateRSS(rssOptions: ValidatedRSSOptions): Promise { ? result.enclosure.url : createCanonicalURL(result.enclosure.url, rssOptions.trailingSlash, site); item.enclosure = parser.parse( - `` + ``, ).enclosure; } return item; diff --git a/packages/astro-rss/src/util.ts b/packages/astro-rss/src/util.ts index a709d942d4..43de370dd7 100644 --- a/packages/astro-rss/src/util.ts +++ b/packages/astro-rss/src/util.ts @@ -5,7 +5,7 @@ import type { RSSOptions } from './index.js'; export function createCanonicalURL( url: string, trailingSlash?: RSSOptions['trailingSlash'], - base?: string + base?: string, ): string { let pathname = url.replace(/\/index.html$/, ''); // index.html is not canonical if (!getUrlExtension(url)) { diff --git a/packages/astro-rss/test/pagesGlobToRssItems.test.js b/packages/astro-rss/test/pagesGlobToRssItems.test.js index 560ede268c..36613c96c8 100644 --- a/packages/astro-rss/test/pagesGlobToRssItems.test.js +++ b/packages/astro-rss/test/pagesGlobToRssItems.test.js @@ -16,7 +16,7 @@ describe('pagesGlobToRssItems', () => { pubDate: phpFeedItem.pubDate, description: phpFeedItem.description, }, - }) + }), ), './posts/nested/web1.md': () => new Promise((resolve) => @@ -27,7 +27,7 @@ describe('pagesGlobToRssItems', () => { pubDate: web1FeedItem.pubDate, description: web1FeedItem.description, }, - }) + }), ), }; @@ -49,7 +49,7 @@ describe('pagesGlobToRssItems', () => { assert.deepEqual( items.sort((a, b) => a.pubDate - b.pubDate), - expected + expected, ); }); @@ -63,7 +63,7 @@ describe('pagesGlobToRssItems', () => { pubDate: phpFeedItem.pubDate, description: phpFeedItem.description, }, - }) + }), ), }; return assert.rejects(pagesGlobToRssItems(globResult)); @@ -80,7 +80,7 @@ describe('pagesGlobToRssItems', () => { pubDate: phpFeedItem.pubDate, description: undefined, }, - }) + }), ), }; return assert.rejects(pagesGlobToRssItems(globResult)); @@ -97,7 +97,7 @@ describe('pagesGlobToRssItems', () => { pubDate: phpFeedItem.pubDate, description: phpFeedItem.description, }, - }) + }), ), }; return assert.doesNotReject(pagesGlobToRssItems(globResult)); @@ -114,7 +114,7 @@ describe('pagesGlobToRssItems', () => { pubDate: phpFeedItem.pubDate, description: undefined, }, - }) + }), ), }; return assert.doesNotReject(pagesGlobToRssItems(globResult)); diff --git a/packages/astro-rss/test/rss.test.js b/packages/astro-rss/test/rss.test.js index 547b75b4e6..5a0fd1fd0b 100644 --- a/packages/astro-rss/test/rss.test.js +++ b/packages/astro-rss/test/rss.test.js @@ -191,7 +191,7 @@ describe('getRssString', () => { pubDate: phpFeedItem.pubDate, description: phpFeedItem.description, }, - }) + }), ), './posts/nested/web1.md': () => new Promise((resolve) => @@ -202,7 +202,7 @@ describe('getRssString', () => { pubDate: web1FeedItem.pubDate, description: web1FeedItem.description, }, - }) + }), ), }; diff --git a/packages/astro/CHANGELOG.md b/packages/astro/CHANGELOG.md index 9e354d9cab..8149b867af 100644 --- a/packages/astro/CHANGELOG.md +++ b/packages/astro/CHANGELOG.md @@ -1127,7 +1127,7 @@ export function Like({ postId }: { postId: string }) { const [state, action, pending] = useActionState( experimental_withState(actions.like), - 0 // initial likes + 0, // initial likes ); return ( @@ -1341,7 +1341,7 @@ { site: 'https://example.com', trailingSlash: 'never', - } + }, ); ``` @@ -1714,7 +1714,7 @@ middleware({ redirectToDefaultLocale: false, prefixDefaultLocale: true, - }) + }), ); ``` @@ -1985,7 +1985,7 @@ detail: { level: 'warning', }, - }) + }), ); ``` @@ -6675,7 +6675,7 @@ const hydrate = await load(); await hydrate(); }, - { once: true } + { once: true }, ); }; @@ -8970,7 +8970,7 @@ { darkMode: true }, { expires: '1 month', - } + }, ); const prefs = Astro.cookies.get('prefs').json(); diff --git a/packages/astro/astro.js b/packages/astro/astro.js index 38bb099edc..2000ca5666 100755 --- a/packages/astro/astro.js +++ b/packages/astro/astro.js @@ -66,7 +66,7 @@ Please upgrade Node.js to a supported version: "${engines}"\n`); } } console.log( - `${ci.name} CI Environment Detected!\nAdditional steps may be needed to set your Node.js version:` + `${ci.name} CI Environment Detected!\nAdditional steps may be needed to set your Node.js version:`, ); console.log(`Documentation: https://docs.astro.build/en/guides/deploy/`); if (CI_INSTRUCTIONS[platform]) { diff --git a/packages/astro/client.d.ts b/packages/astro/client.d.ts index 149af6f649..ed5c1b894d 100644 --- a/packages/astro/client.d.ts +++ b/packages/astro/client.d.ts @@ -50,7 +50,7 @@ declare module 'astro:assets' { * This is functionally equivalent to using the `` component, as the component calls this function internally. */ getImage: ( - options: import('./dist/assets/types.js').UnresolvedImageTransform + options: import('./dist/assets/types.js').UnresolvedImageTransform, ) => Promise; imageConfig: import('./dist/@types/astro.js').AstroConfig['image']; getConfiguredImageService: typeof import('./dist/assets/index.js').getConfiguredImageService; diff --git a/packages/astro/components/Picture.astro b/packages/astro/components/Picture.astro index 593dd80973..c85548404d 100644 --- a/packages/astro/components/Picture.astro +++ b/packages/astro/components/Picture.astro @@ -53,8 +53,8 @@ const optimizedImages: GetImageResult[] = await Promise.all( format: format, widths: props.widths, densities: props.densities, - }) - ) + }), + ), ); let resultFallbackFormat = fallbackFormat ?? defaultFallbackFormat; diff --git a/packages/astro/components/ViewTransitions.astro b/packages/astro/components/ViewTransitions.astro index 84a68d61e6..8bda7b780f 100644 --- a/packages/astro/components/ViewTransitions.astro +++ b/packages/astro/components/ViewTransitions.astro @@ -53,7 +53,7 @@ const { fallback = 'animate' } = Astro.props; if (supportsViewTransitions || getFallback() !== 'none') { if (import.meta.env.DEV && window.matchMedia('(prefers-reduced-motion)').matches) { console.warn( - `[transitions]: all view transition animations, including fallback animation, are disabled as this device has the prefer-reduced-motion setting enabled.` + `[transitions]: all view transition animations, including fallback animation, are disabled as this device has the prefer-reduced-motion setting enabled.`, ); } document.addEventListener('click', (ev) => { diff --git a/packages/astro/config.d.ts b/packages/astro/config.d.ts index a7d827a1fd..9f4c6bfd11 100644 --- a/packages/astro/config.d.ts +++ b/packages/astro/config.d.ts @@ -17,7 +17,7 @@ export function defineConfig(config: AstroUserConfig): AstroUserConfig; */ export function getViteConfig( config: ViteUserConfig, - inlineAstroConfig?: AstroInlineConfig + inlineAstroConfig?: AstroInlineConfig, ): ViteUserConfigFn; /** diff --git a/packages/astro/e2e/astro-component.test.js b/packages/astro/e2e/astro-component.test.js index c96e9b1c47..0e9c1eaed4 100644 --- a/packages/astro/e2e/astro-component.test.js +++ b/packages/astro/e2e/astro-component.test.js @@ -20,25 +20,25 @@ test.describe('Astro component HMR', () => { const hero = page.locator('section'); await expect(hero, 'hero has background: white').toHaveCSS( 'background-color', - 'rgb(255, 255, 255)' + 'rgb(255, 255, 255)', ); await expect(hero, 'hero has color: black').toHaveCSS('color', 'rgb(0, 0, 0)'); // Edit the Hero component with a new background color await astro.editFile('./src/components/Hero.astro', (content) => - content.replace('background: white', 'background: rgb(230, 230, 230)') + content.replace('background: white', 'background: rgb(230, 230, 230)'), ); await expect(hero, 'background color updated').toHaveCSS( 'background-color', - 'rgb(230, 230, 230)' + 'rgb(230, 230, 230)', ); }); test('hoisted scripts', async ({ page, astro }) => { const initialLog = page.waitForEvent( 'console', - (message) => message.text() === 'Hello, Astro!' + (message) => message.text() === 'Hello, Astro!', ); await page.goto(astro.resolveUrl('/')); @@ -49,12 +49,12 @@ test.describe('Astro component HMR', () => { const updatedLog = page.waitForEvent( 'console', - (message) => message.text() === 'Hello, updated Astro!' + (message) => message.text() === 'Hello, updated Astro!', ); // Edit the hoisted script on the page await astro.editFile('./src/pages/index.astro', (content) => - content.replace('Hello, Astro!', 'Hello, updated Astro!') + content.replace('Hello, Astro!', 'Hello, updated Astro!'), ); await updatedLog; @@ -63,7 +63,7 @@ test.describe('Astro component HMR', () => { test('inline scripts', async ({ page, astro }) => { const initialLog = page.waitForEvent( 'console', - (message) => message.text() === 'Hello, inline Astro!' + (message) => message.text() === 'Hello, inline Astro!', ); await page.goto(astro.resolveUrl('/')); @@ -71,12 +71,12 @@ test.describe('Astro component HMR', () => { const updatedLog = page.waitForEvent( 'console', - (message) => message.text() === 'Hello, updated inline Astro!' + (message) => message.text() === 'Hello, updated inline Astro!', ); // Edit the inline script on the page await astro.editFile('./src/pages/index.astro', (content) => - content.replace('Hello, inline Astro!', 'Hello, updated inline Astro!') + content.replace('Hello, inline Astro!', 'Hello, updated inline Astro!'), ); await updatedLog; @@ -89,7 +89,7 @@ test.describe('Astro component HMR', () => { await Promise.all([ page.waitForLoadState('networkidle'), await astro.editFile('../_deps/astro-linked-lib/Component.astro', (content) => - content.replace('>astro-linked-lib<', '>astro-linked-lib-update<') + content.replace('>astro-linked-lib<', '>astro-linked-lib-update<'), ), ]); h1 = page.locator('#astro-linked-lib'); @@ -103,7 +103,7 @@ test.describe('Astro component HMR', () => { await Promise.all([ page.waitForLoadState('networkidle'), await astro.editFile('../_deps/astro-linked-lib/Component.astro', (content) => - content.replace('color: red', 'color: green') + content.replace('color: red', 'color: green'), ), ]); h1 = page.locator('#astro-linked-lib'); diff --git a/packages/astro/e2e/astro-envs.test.js b/packages/astro/e2e/astro-envs.test.js index 668510e3d0..f6f3c5031a 100644 --- a/packages/astro/e2e/astro-envs.test.js +++ b/packages/astro/e2e/astro-envs.test.js @@ -35,7 +35,7 @@ test.describe('Astro Environment BASE_URL', () => { const clientComponentBaseUrl = page.locator('id=client-component-base-url'); await expect(clientComponentBaseUrl, 'clientComponentBaseUrl equals to /blog').toHaveText( - '/blog' + '/blog', ); }); }); diff --git a/packages/astro/e2e/content-collections.test.js b/packages/astro/e2e/content-collections.test.js index eaa40d1b8f..63c5077c9b 100644 --- a/packages/astro/e2e/content-collections.test.js +++ b/packages/astro/e2e/content-collections.test.js @@ -19,7 +19,7 @@ test.describe('Content Collections', () => { await page.goto(astro.resolveUrl('/')); await astro.editFile('./src/components/MyComponent.astro', (original) => - original.replace('red', 'green') + original.replace('red', 'green'), ); const h1 = page.locator('#my-heading'); diff --git a/packages/astro/e2e/css.test.js b/packages/astro/e2e/css.test.js index fff197a392..fd4de700e9 100644 --- a/packages/astro/e2e/css.test.js +++ b/packages/astro/e2e/css.test.js @@ -26,7 +26,7 @@ test.describe('CSS HMR', () => { await expect(h).toHaveCSS('color', 'rgb(255, 0, 0)'); await astro.editFile('./src/styles/main.css', (original) => - original.replace('--h1-color: red;', '--h1-color: green;') + original.replace('--h1-color: red;', '--h1-color: green;'), ); await expect(h).toHaveCSS('color', 'rgb(0, 128, 0)'); diff --git a/packages/astro/e2e/custom-client-directives.test.js b/packages/astro/e2e/custom-client-directives.test.js index 118a5d53f5..ef9de808a1 100644 --- a/packages/astro/e2e/custom-client-directives.test.js +++ b/packages/astro/e2e/custom-client-directives.test.js @@ -98,7 +98,7 @@ function testClientDirectivesShared() { const clientOptions = page.locator('#options'); await expect(clientOptions).toHaveText( - 'Passed options are: {"message":"Hello! I was passed as an option"}' + 'Passed options are: {"message":"Hello! I was passed as an option"}', ); }); } diff --git a/packages/astro/e2e/dev-toolbar-audits.test.js b/packages/astro/e2e/dev-toolbar-audits.test.js index 9a628a1c06..6ef63cc1e2 100644 --- a/packages/astro/e2e/dev-toolbar-audits.test.js +++ b/packages/astro/e2e/dev-toolbar-audits.test.js @@ -79,7 +79,7 @@ test.describe('Dev Toolbar - Audits', () => { 'astro:dev-toolbar:settings', JSON.stringify({ verbose: true, - }) + }), ); }); @@ -93,7 +93,7 @@ test.describe('Dev Toolbar - Audits', () => { const badButton = page.locator('#bad-button'); let consolePromise = page.waitForEvent('console', (msg) => - msg.text().includes('Rerunning audit lints') + msg.text().includes('Rerunning audit lints'), ); await badButton.click({ clickCount: 5 }); await consolePromise; @@ -102,7 +102,7 @@ test.describe('Dev Toolbar - Audits', () => { expect( logs.filter((log) => log.includes('Rerunning audit lints because the DOM has been updated')) - .length === 1 + .length === 1, ).toBe(true); }); @@ -114,7 +114,7 @@ test.describe('Dev Toolbar - Audits', () => { 'astro:dev-toolbar:settings', JSON.stringify({ verbose: true, - }) + }), ); }); @@ -153,7 +153,7 @@ test.describe('Dev Toolbar - Audits', () => { // Make sure we only reran audits once expect( logs.filter((log) => log.includes('Rerunning audit lints because the DOM has been updated')) - .length === 1 + .length === 1, ).toBe(true); }); diff --git a/packages/astro/e2e/dev-toolbar.test.js b/packages/astro/e2e/dev-toolbar.test.js index 3055778523..ae8b6ef5c0 100644 --- a/packages/astro/e2e/dev-toolbar.test.js +++ b/packages/astro/e2e/dev-toolbar.test.js @@ -42,7 +42,7 @@ test.describe('Dev Toolbar', () => { await appButton.click(); const astroAppCanvas = toolbar.locator( - 'astro-dev-toolbar-app-canvas[data-app-id="astro:home"]' + 'astro-dev-toolbar-app-canvas[data-app-id="astro:home"]', ); const astroWindow = astroAppCanvas.locator('astro-dev-toolbar-window'); await expect(astroWindow).toHaveCount(1); @@ -152,7 +152,7 @@ test.describe('Dev Toolbar', () => { const code = xrayHighlightTooltip.locator('pre > code'); await expect(code).toHaveText( - JSON.stringify({ name: `` }, undefined, 2) + JSON.stringify({ name: `` }, undefined, 2), ); expect(isAlertCalled).toBe(false); }); @@ -264,7 +264,7 @@ test.describe('Dev Toolbar', () => { await appButton.click(); const settingsAppCanvas = toolbar.locator( - 'astro-dev-toolbar-app-canvas[data-app-id="astro:settings"]' + 'astro-dev-toolbar-app-canvas[data-app-id="astro:settings"]', ); const settingsWindow = settingsAppCanvas.locator('astro-dev-toolbar-window'); await expect(settingsWindow).toHaveCount(1); @@ -283,7 +283,7 @@ test.describe('Dev Toolbar', () => { await appButton.click(); const settingsAppCanvas = toolbar.locator( - 'astro-dev-toolbar-app-canvas[data-app-id="astro:settings"]' + 'astro-dev-toolbar-app-canvas[data-app-id="astro:settings"]', ); const settingsWindow = settingsAppCanvas.locator('astro-dev-toolbar-window'); await expect(settingsWindow).toHaveCount(1); @@ -294,7 +294,7 @@ test.describe('Dev Toolbar', () => { await appButton.click(); const astroAppCanvas = toolbar.locator( - 'astro-dev-toolbar-app-canvas[data-app-id="astro:home"]' + 'astro-dev-toolbar-app-canvas[data-app-id="astro:home"]', ); const astroWindow = astroAppCanvas.locator('astro-dev-toolbar-window'); await expect(astroWindow).toHaveCount(1); @@ -311,7 +311,7 @@ test.describe('Dev Toolbar', () => { await appButton.click(); const settingsAppCanvas = toolbar.locator( - 'astro-dev-toolbar-app-canvas[data-app-id="astro:settings"]' + 'astro-dev-toolbar-app-canvas[data-app-id="astro:settings"]', ); const settingsWindow = settingsAppCanvas.locator('astro-dev-toolbar-window'); await expect(settingsWindow).toHaveCount(1); @@ -389,7 +389,7 @@ test.describe('Dev Toolbar', () => { await settingsAppButton.click(); const settingsAppCanvas = toolbar.locator( - 'astro-dev-toolbar-app-canvas[data-app-id="astro:settings"]' + 'astro-dev-toolbar-app-canvas[data-app-id="astro:settings"]', ); const settingsWindow = settingsAppCanvas.locator('astro-dev-toolbar-window'); await expect(settingsWindow).toBeVisible(); @@ -423,7 +423,7 @@ test.describe('Dev Toolbar', () => { await settingsAppButton.click(); const settingsAppCanvas = toolbar.locator( - 'astro-dev-toolbar-app-canvas[data-app-id="astro:settings"]' + 'astro-dev-toolbar-app-canvas[data-app-id="astro:settings"]', ); const settingsWindow = settingsAppCanvas.locator('astro-dev-toolbar-window'); await expect(settingsWindow).toBeVisible(); diff --git a/packages/astro/e2e/errors.test.js b/packages/astro/e2e/errors.test.js index 9087ac484a..c015ea1233 100644 --- a/packages/astro/e2e/errors.test.js +++ b/packages/astro/e2e/errors.test.js @@ -33,7 +33,7 @@ test.describe('Error display', () => { // Edit the component file await astro.editFile( './src/pages/astro-syntax-error.astro', - () => `

No syntax error

` + () => `

No syntax error

`, ), ]); @@ -107,7 +107,7 @@ test.describe('Error display', () => { // Edit the component file astro.editFile( './src/components/svelte/SvelteSyntaxError.svelte', - () => `

No mismatch

` + () => `

No mismatch

`, ), ]); diff --git a/packages/astro/e2e/hmr.test.js b/packages/astro/e2e/hmr.test.js index e6c054300f..72eaf83751 100644 --- a/packages/astro/e2e/hmr.test.js +++ b/packages/astro/e2e/hmr.test.js @@ -34,7 +34,7 @@ test.describe('Scripts with dependencies', () => { await expect(h, 'original text set').toHaveText('before'); await astro.editFile('./src/scripts/heading.js', (original) => - original.replace('before', 'after') + original.replace('before', 'after'), ); await expect(h, 'text changed').toHaveText('after'); @@ -64,7 +64,7 @@ test.describe('Styles', () => { await expect(h).toHaveCSS('color', 'rgb(0, 0, 255)'); await astro.editFile('./src/styles/css-external.css', (original) => - original.replace('blue', 'red') + original.replace('blue', 'red'), ); await expect(h).toHaveCSS('color', 'rgb(255, 0, 0)'); diff --git a/packages/astro/e2e/lit-component.test.js b/packages/astro/e2e/lit-component.test.js index 54eb990741..d68f5f7b80 100644 --- a/packages/astro/e2e/lit-component.test.js +++ b/packages/astro/e2e/lit-component.test.js @@ -118,13 +118,13 @@ test.describe('Lit components', () => { // Light DOM reconstructed correctly (slots are rendered alphabetically) and shadow dom content rendered await expect(label, 'slotted text is in DOM').toHaveText( - 'Framework client:only component Should not be visible Shadow dom default content should not be visible' + 'Framework client:only component Should not be visible Shadow dom default content should not be visible', ); // Projected content should be visible await expect( page.locator('#client-only .default'), - 'slotted element is visible' + 'slotted element is visible', ).toBeVisible(); await expect(page.locator('#client-only .foo1'), 'slotted element is visible').toBeVisible(); await expect(page.locator('#client-only .foo2'), 'slotted element is visible').toBeVisible(); @@ -132,13 +132,13 @@ test.describe('Lit components', () => { // Non-projected content should not be visible await expect( page.locator('#client-only [slot="quux"]'), - 'element without slot is not visible' + 'element without slot is not visible', ).toBeHidden(); // Default slot content should not be visible await expect( page.locator('#client-only .defaultContent'), - 'element without slot is not visible' + 'element without slot is not visible', ).toBeHidden(); }); @@ -149,7 +149,7 @@ test.describe('Lit components', () => { const label = counter.locator('h1'); await astro.editFile('./src/pages/index.astro', (original) => - original.replace('Hello, client:idle!', 'Hello, updated client:idle!') + original.replace('Hello, client:idle!', 'Hello, updated client:idle!'), ); await expect(label, 'slot text updated').toHaveText('Hello, updated client:idle!'); diff --git a/packages/astro/e2e/multiple-frameworks.test.js b/packages/astro/e2e/multiple-frameworks.test.js index e067b03576..08a2fb6486 100644 --- a/packages/astro/e2e/multiple-frameworks.test.js +++ b/packages/astro/e2e/multiple-frameworks.test.js @@ -109,7 +109,7 @@ test.skip('Multiple frameworks', () => { await expect(slot, 'initial slot content').toHaveText('Hello Preact!'); await astro.editFile('./src/pages/index.astro', (content) => - content.replace('Hello Preact!', 'Hello Preact, updated!') + content.replace('Hello Preact!', 'Hello Preact, updated!'), ); await expect(slot, 'slot content updated').toHaveText('Hello Preact, updated!'); @@ -122,7 +122,7 @@ test.skip('Multiple frameworks', () => { await expect(count, 'initial count updated to 0').toHaveText('0'); await astro.editFile('./src/components/ReactCounter.jsx', (content) => - content.replace('useState(0)', 'useState(5)') + content.replace('useState(0)', 'useState(5)'), ); await expect(count, 'initial count updated to 5').toHaveText('5'); @@ -135,7 +135,7 @@ test.skip('Multiple frameworks', () => { await expect(count, 'initial count updated to 0').toHaveText('0'); await astro.editFile('./src/components/PreactCounter.tsx', (content) => - content.replace('useState(0)', 'useState(5)') + content.replace('useState(0)', 'useState(5)'), ); await expect(count, 'initial count updated to 5').toHaveText('5'); @@ -148,7 +148,7 @@ test.skip('Multiple frameworks', () => { await expect(count, 'initial count updated to 0').toHaveText('0'); await astro.editFile('./src/components/SolidCounter.tsx', (content) => - content.replace('createSignal(0)', 'createSignal(5)') + content.replace('createSignal(0)', 'createSignal(5)'), ); await expect(count, 'initial count updated to 5').toHaveText('5'); @@ -161,7 +161,7 @@ test.skip('Multiple frameworks', () => { await expect(count, 'initial count updated to 0').toHaveText('0'); await astro.editFile('./src/components/VueCounter.vue', (content) => - content.replace('ref(0)', 'ref(5)') + content.replace('ref(0)', 'ref(5)'), ); await expect(count, 'initial count updated to 5').toHaveText('5'); @@ -174,7 +174,7 @@ test.skip('Multiple frameworks', () => { await expect(count, 'initial count is 0').toHaveText('0'); await astro.editFile('./src/components/SvelteCounter.svelte', (content) => - content.replace('let count = 0;', 'let count = 5;') + content.replace('let count = 0;', 'let count = 5;'), ); await expect(count, 'initial count updated to 5').toHaveText('5'); diff --git a/packages/astro/e2e/nested-styles.test.js b/packages/astro/e2e/nested-styles.test.js index 0dc5b868b5..c482570f09 100644 --- a/packages/astro/e2e/nested-styles.test.js +++ b/packages/astro/e2e/nested-styles.test.js @@ -34,7 +34,7 @@ test.describe('Loading styles that are nested', () => { await expect(header, 'should have background color').toHaveCSS( 'background-color', - 'rgb(0, 0, 139)' // darkblue + 'rgb(0, 0, 139)', // darkblue ); }); }); diff --git a/packages/astro/e2e/prefetch.test.js b/packages/astro/e2e/prefetch.test.js index 7ac85135bb..84ead590cb 100644 --- a/packages/astro/e2e/prefetch.test.js +++ b/packages/astro/e2e/prefetch.test.js @@ -40,7 +40,7 @@ async function expectUrlPrefetched(url, page, count) { const fetchCount = reqUrls.filter((u) => u.includes(url)).length; expect( fetchCount, - `${url} should be prefetched ${count} time(s), but is prefetch with link ${linkCount} time(s) and with fetch ${fetchCount} time(s)` + `${url} should be prefetched ${count} time(s), but is prefetch with link ${linkCount} time(s) and with fetch ${fetchCount} time(s)`, ).toEqual(count); } } @@ -344,7 +344,7 @@ test.describe('Prefetch (default), Experimental ({ clientPrerender: true })', () expect(await scriptIsInHead(page, '?search-param=true')).toBeFalsy(); await page.locator('#prefetch-search-param').hover(); await page.waitForFunction( - () => document.querySelectorAll('script[type=speculationrules]').length === 2 + () => document.querySelectorAll('script[type=speculationrules]').length === 2, ); expect(await scriptIsInHead(page, '?search-param=true')).toBeTruthy(); }); @@ -361,7 +361,7 @@ test.describe('Prefetch (default), Experimental ({ clientPrerender: true })', () expect(await scriptIsInHead(page, '/prefetch-hover')).toBeFalsy(); await page.locator('#prefetch-hover').hover(); await page.waitForFunction( - () => document.querySelectorAll('script[type=speculationrules]').length === 2 + () => document.querySelectorAll('script[type=speculationrules]').length === 2, ); expect(await scriptIsInHead(page, '/prefetch-hover')).toBeTruthy(); }); @@ -372,7 +372,7 @@ test.describe('Prefetch (default), Experimental ({ clientPrerender: true })', () // Scroll down to show the element await page.locator('#prefetch-viewport').scrollIntoViewIfNeeded(); await page.waitForFunction( - () => document.querySelectorAll('script[type=speculationrules]').length === 2 + () => document.querySelectorAll('script[type=speculationrules]').length === 2, ); expect(await scriptIsInHead(page, '/prefetch-viewport')).toBeTruthy(); }); diff --git a/packages/astro/e2e/shared-component-tests.js b/packages/astro/e2e/shared-component-tests.js index ccce25b0b0..024f1aade8 100644 --- a/packages/astro/e2e/shared-component-tests.js +++ b/packages/astro/e2e/shared-component-tests.js @@ -134,7 +134,7 @@ export function prepareTestFactory(opts, { canReplayClicks = false } = {}) { // Edit the component's initial count prop await astro.editFile(pageSourceFilePath, (original) => - original.replace('id="client-idle" {...someProps}', 'id="client-idle" count={5}') + original.replace('id="client-idle" {...someProps}', 'id="client-idle" count={5}'), ); await expect(count, 'count prop updated').toHaveText('5', { timeout: 10000 }); @@ -144,19 +144,19 @@ export function prepareTestFactory(opts, { canReplayClicks = false } = {}) { await astro.editFile(componentFilePath, (original) => original.replace( 'Framework client:only component', - 'Updated framework client:only component' - ) + 'Updated framework client:only component', + ), ); const label = page.locator('#client-only'); await expect(label, 'client:only component is visible').toBeVisible(); await expect(label, 'client:only slot text is visible').toHaveText( - 'Updated framework client:only component' + 'Updated framework client:only component', ); // Edit the imported CSS file await astro.editFile(counterCssFilePath || './src/components/Counter.css', (original) => - original.replace('font-size: 2em;', 'font-size: 24px;') + original.replace('font-size: 2em;', 'font-size: 24px;'), ); await expect(count, 'imported CSS updated').toHaveCSS('font-size', '24px'); diff --git a/packages/astro/e2e/solid-component.test.js b/packages/astro/e2e/solid-component.test.js index 81e6894e80..b998d18732 100644 --- a/packages/astro/e2e/solid-component.test.js +++ b/packages/astro/e2e/solid-component.test.js @@ -4,7 +4,7 @@ const { test, createTests } = prepareTestFactory( { root: './fixtures/solid-component/' }, { canReplayClicks: true, - } + }, ); const config = { diff --git a/packages/astro/e2e/tailwindcss.test.js b/packages/astro/e2e/tailwindcss.test.js index f8b1200810..e58e10dfde 100644 --- a/packages/astro/e2e/tailwindcss.test.js +++ b/packages/astro/e2e/tailwindcss.test.js @@ -23,7 +23,7 @@ test.describe('Tailwind CSS', () => { await expect(body, 'should have classes').toHaveClass('bg-dawn text-midnight'); await expect(body, 'should have background color').toHaveCSS( 'background-color', - 'rgb(243, 233, 250)' + 'rgb(243, 233, 250)', ); await expect(body, 'should have color').toHaveCSS('color', 'rgb(49, 39, 74)'); }); @@ -37,13 +37,13 @@ test.describe('Tailwind CSS', () => { await expect(button, 'should have appearance: none').toHaveCSS('appearance', 'none'); await expect(button, 'should have appearance-none with webkit prefix').toHaveCSS( '-webkit-appearance', - 'none' + 'none', ); await expect(button, 'should have bg-purple-600').toHaveClass(/bg-purple-600/); await expect(button, 'should have background color').toHaveCSS( 'background-color', - 'rgb(147, 51, 234)' + 'rgb(147, 51, 234)', ); await expect(button, 'should have lg:py-3').toHaveClass(/lg:py-3/); @@ -58,7 +58,7 @@ test.describe('Tailwind CSS', () => { await page.goto(astro.resolveUrl('/')); await astro.editFile('./src/components/Button.astro', (original) => - original.replace('bg-purple-600', 'bg-purple-400') + original.replace('bg-purple-600', 'bg-purple-400'), ); const button = page.locator('button'); @@ -66,7 +66,7 @@ test.describe('Tailwind CSS', () => { await expect(button, 'should have bg-purple-400').toHaveClass(/bg-purple-400/); await expect(button, 'should have background color').toHaveCSS( 'background-color', - 'rgb(192, 132, 252)' + 'rgb(192, 132, 252)', ); }); }); diff --git a/packages/astro/e2e/test-utils.js b/packages/astro/e2e/test-utils.js index 7d07ee953d..48fcd17bd7 100644 --- a/packages/astro/e2e/test-utils.js +++ b/packages/astro/e2e/test-utils.js @@ -84,7 +84,7 @@ export async function waitForHydrate(page, el) { const astroIslandId = await astroIsland.last().getAttribute('uid'); await page.waitForFunction( (selector) => document.querySelector(selector)?.hasAttribute('ssr') === false, - `astro-island[uid="${astroIslandId}"]` + `astro-island[uid="${astroIslandId}"]`, ); } diff --git a/packages/astro/e2e/view-transitions.test.js b/packages/astro/e2e/view-transitions.test.js index cbcd38497b..135ec5571a 100644 --- a/packages/astro/e2e/view-transitions.test.js +++ b/packages/astro/e2e/view-transitions.test.js @@ -35,7 +35,7 @@ function collectPreloads(page) { mutations.forEach((mutation) => mutation.addedNodes.forEach((node) => { if (node.nodeName === 'LINK' && node.rel === 'preload') preloads.push(node.href); - }) + }), ); }); observer.observe(document.head, { childList: true }); @@ -132,7 +132,7 @@ test.describe('View Transitions', () => { expect( loads.length, - 'There should be 2 page loads. The original, then going from 3 to 2' + 'There should be 2 page loads. The original, then going from 3 to 2', ).toEqual(2); }); @@ -163,7 +163,7 @@ test.describe('View Transitions', () => { expect( loads.length, - 'There should be only 2 page loads (for page one & three), but no additional loads for the hash change' + 'There should be only 2 page loads (for page one & three), but no additional loads for the hash change', ).toEqual(2); }); @@ -185,7 +185,7 @@ test.describe('View Transitions', () => { await expect(p, 'should have content').toHaveText('Page 1'); expect( loads.length, - 'There should be 3 page loads (for page one & three), and an additional loads for the back navigation' + 'There should be 3 page loads (for page one & three), and an additional loads for the back navigation', ).toEqual(3); }); @@ -628,7 +628,7 @@ test.describe('View Transitions', () => { expect( loads.length, - 'There should be only 1 page load. No additional loads for going back on same page' + 'There should be only 1 page load. No additional loads for going back on same page', ).toEqual(1); }); @@ -770,7 +770,7 @@ test.describe('View Transitions', () => { expect( loads.length, - 'There should only be the initial page load and two normal transitions' + 'There should only be the initial page load and two normal transitions', ).toEqual(1); }); @@ -1030,7 +1030,7 @@ test.describe('View Transitions', () => { expect( loads.length, - 'There should be only 1 page load. No additional loads for the form submission' + 'There should be only 1 page load. No additional loads for the form submission', ).toEqual(1); }); @@ -1056,7 +1056,7 @@ test.describe('View Transitions', () => { expect( loads.length, - 'There should be only 1 page load. No additional loads for the form submission' + 'There should be only 1 page load. No additional loads for the form submission', ).toEqual(1); }); @@ -1075,7 +1075,7 @@ test.describe('View Transitions', () => { expect( loads.length, - 'There should be only 1 page load. No additional loads for the form submission' + 'There should be only 1 page load. No additional loads for the form submission', ).toEqual(1); }); @@ -1104,12 +1104,12 @@ test.describe('View Transitions', () => { expect( loads.length, - 'There should be only 1 page load. No additional loads for the form submission' + 'There should be only 1 page load. No additional loads for the form submission', ).toEqual(1); expect( postedEncodings, - 'There should be 1 POST, with encoding set to `multipart/form-data`' + 'There should be 1 POST, with encoding set to `multipart/form-data`', ).toEqual(['multipart/form-data']); }); @@ -1130,8 +1130,8 @@ test.describe('View Transitions', () => { await page.goto( astro.resolveUrl( - `/form-one?${new URLSearchParams({ enctype: 'application/x-www-form-urlencoded' })}` - ) + `/form-one?${new URLSearchParams({ enctype: 'application/x-www-form-urlencoded' })}`, + ), ); // Submit the form @@ -1139,12 +1139,12 @@ test.describe('View Transitions', () => { expect( loads.length, - 'There should be only 1 page load. No additional loads for the form submission' + 'There should be only 1 page load. No additional loads for the form submission', ).toEqual(1); expect( postedEncodings, - 'There should be 1 POST, with encoding set to `multipart/form-data`' + 'There should be 1 POST, with encoding set to `multipart/form-data`', ).toEqual(['application/x-www-form-urlencoded']); }); @@ -1216,7 +1216,7 @@ test.describe('View Transitions', () => { expect( loads.length, - 'There should be only 1 page load. No additional loads for the form submission' + 'There should be only 1 page load. No additional loads for the form submission', ).toEqual(1); }); @@ -1333,7 +1333,7 @@ test.describe('View Transitions', () => { expectedAnimations.add(name); expect(page.locator(selector), 'should be escaped correctly').toHaveCSS( 'view-transition-name', - name + name, ); }; @@ -1361,36 +1361,36 @@ test.describe('View Transitions', () => { await checkName('#thirteen', '___01____02______'); await checkName( '#batch0', - '__00_01_02_03_04_05_06_07_08_09_0a_0b_0c_0d_0e_0f_10_11_12_13_14_15_16_17_18_19_1a_1b_1c_1d_1e_1f' + '__00_01_02_03_04_05_06_07_08_09_0a_0b_0c_0d_0e_0f_10_11_12_13_14_15_16_17_18_19_1a_1b_1c_1d_1e_1f', ); await checkName( '#batch1', - '__20_21_22_23_24_25_26_27_28_29_2a_2b_2c-_2e_2f0123456789_3a_3b_3c_3d_3e_3f' + '__20_21_22_23_24_25_26_27_28_29_2a_2b_2c-_2e_2f0123456789_3a_3b_3c_3d_3e_3f', ); await checkName('#batch2', '__40ABCDEFGHIJKLMNOPQRSTUVWXYZ_5b_5c_5d_5e__'); await checkName('#batch3', '__60abcdefghijklmnopqrstuvwxyz_7b_7c_7d_7e_7f'); await checkName( '#batch4', - '\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f' + '\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f', ); await checkName( '#batch5', - '\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf' + '\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf', ); await checkName( '#batch6', - '\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf' + '\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf', ); await checkName( '#batch7', - '\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' + '\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff', ); await page.click('#navigate'); await page.waitForTimeout(400); // yes, I dislike this, too. Might fix later. expect( expectedAnimations.size, - 'all animations for transition:names should have been found' + 'all animations for transition:names should have been found', ).toEqual(0); }); @@ -1425,7 +1425,7 @@ test.describe('View Transitions', () => { const attributeValue = await page.$eval( ':root', (element, attributeName) => element.getAttribute(attributeName), - 'data-theme' + 'data-theme', ); expect(attributeValue).toBe('purple'); }); diff --git a/packages/astro/e2e/vue-component.test.js b/packages/astro/e2e/vue-component.test.js index ca491de908..3be31af85f 100644 --- a/packages/astro/e2e/vue-component.test.js +++ b/packages/astro/e2e/vue-component.test.js @@ -47,7 +47,7 @@ test('hmr works', async ({ page, astro }) => { await expect(span).toHaveText('Count is 1'); await astro.editFile('./src/components/State.vue', (content) => - content.replace('ref(1)', 'ref(2)') + content.replace('ref(1)', 'ref(2)'), ); await expect(span).toHaveText('Count is 2'); diff --git a/packages/astro/performance/content-benchmark.mjs b/packages/astro/performance/content-benchmark.mjs index bd362c8078..a710bd7625 100644 --- a/packages/astro/performance/content-benchmark.mjs +++ b/packages/astro/performance/content-benchmark.mjs @@ -74,8 +74,8 @@ async function benchmark({ fixtures, templates, numPosts }) { const fixtures = formats.filter((format) => format !== 'md'); console.log( `\n${bold('With Astro components')} ${dim( - `${numPosts} posts (${formatsToString(fixtures)})` - )}` + `${numPosts} posts (${formatsToString(fixtures)})`, + )}`, ); process.env.ASTRO_PERFORMANCE_TEST_NAME = 'with-astro-components'; await benchmark({ @@ -92,8 +92,8 @@ async function benchmark({ fixtures, templates, numPosts }) { const fixtures = formats.filter((format) => format !== 'md'); console.log( `\n${bold('With React components')} ${dim( - `${numPosts} posts (${formatsToString(fixtures)})` - )}` + `${numPosts} posts (${formatsToString(fixtures)})`, + )}`, ); process.env.ASTRO_PERFORMANCE_TEST_NAME = 'with-react-components'; await benchmark({ diff --git a/packages/astro/performance/scripts/generate-posts.mjs b/packages/astro/performance/scripts/generate-posts.mjs index b97ac8f4b5..37466cad30 100644 --- a/packages/astro/performance/scripts/generate-posts.mjs +++ b/packages/astro/performance/scripts/generate-posts.mjs @@ -23,8 +23,8 @@ export async function generatePosts({ Array.from(Array(numPosts).keys()).map((idx) => { return fs.promises.writeFile( `${postsDir}/post-${idx}${ext.startsWith('.') ? ext : `.${ext}`}`, - fs.readFileSync(new URL(`./templates/${template}`, import.meta.url), 'utf8') + fs.readFileSync(new URL(`./templates/${template}`, import.meta.url), 'utf8'), ); - }) + }), ); } diff --git a/packages/astro/src/@types/astro.ts b/packages/astro/src/@types/astro.ts index 1a3cf60bb2..9500950051 100644 --- a/packages/astro/src/@types/astro.ts +++ b/packages/astro/src/@types/astro.ts @@ -378,7 +378,7 @@ export interface AstroGlobalPartial { */ glob(globStr: `${any}.astro`): Promise; glob>( - globStr: `${any}${MarkdowFileExtension}` + globStr: `${any}${MarkdowFileExtension}`, ): Promise[]>; glob>(globStr: `${any}.mdx`): Promise[]>; glob>(globStr: string): Promise; @@ -2300,7 +2300,7 @@ export interface ContentEntryType { contents: string; fileUrl: URL; viteId: string; - } + }, ): rollup.LoadResult | Promise; contentModuleTypes?: string; /** @@ -2385,7 +2385,7 @@ export type AsyncRendererComponentFn = ( Component: any, props: any, slots: Record, - metadata?: AstroComponentMetadata + metadata?: AstroComponentMetadata, ) => Promise; /** Generic interface for a component (Astro, Svelte, React, etc.) */ @@ -2470,7 +2470,7 @@ export type GetStaticPathsResultKeyed = GetStaticPathsResult & { * [Astro Reference](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) */ export type GetStaticPaths = ( - options: GetStaticPathsOptions + options: GetStaticPathsOptions, ) => Promise | GetStaticPathsResult; /** @@ -2493,7 +2493,7 @@ export type GetStaticPaths = ( * ``` */ export type InferGetStaticParamsType = T extends ( - opts?: GetStaticPathsOptions + opts?: GetStaticPathsOptions, ) => infer R | Promise ? R extends Array ? U extends { params: infer P } @@ -2526,7 +2526,7 @@ export type InferGetStaticParamsType = T extends ( * ``` */ export type InferGetStaticPropsType = T extends ( - opts: GetStaticPathsOptions + opts: GetStaticPathsOptions, ) => infer R | Promise ? R extends Array ? U extends { props: infer P } @@ -2639,7 +2639,7 @@ export type PaginateFunction = < AdditionalPaginateParams extends Params, >( data: PaginateData[], - args?: PaginateOptions + args?: PaginateOptions, ) => { params: Simplify< { @@ -2755,7 +2755,7 @@ interface AstroSharedContext< TInputSchema extends ActionInputSchema, TAction extends ActionClient, >( - action: TAction + action: TAction, ) => ActionReturnType | undefined; /** * Call action handler from the server. @@ -2769,7 +2769,7 @@ interface AstroSharedContext< | ActionClient['orThrow'], >( action: TAction, - input: Parameters[0] + input: Parameters[0], ) => Promise>; /** * Route parameters for this request if this is a dynamic route. @@ -3142,7 +3142,7 @@ export type RewritePayload = string | URL | Request; export type MiddlewareNext = (rewritePayload?: RewritePayload) => Promise; export type MiddlewareHandler = ( context: APIContext, - next: MiddlewareNext + next: MiddlewareNext, ) => Promise | Response | Promise | void; // NOTE: when updating this file with other functions, @@ -3258,7 +3258,7 @@ export interface SSRResult { createAstro( Astro: AstroGlobalPartial, props: Record, - slots: Record | null + slots: Record | null, ): AstroGlobal; params: Params; resolve: (s: string) => Promise; @@ -3326,7 +3326,7 @@ export interface PreviewServerParams { } export type CreatePreviewServer = ( - params: PreviewServerParams + params: PreviewServerParams, ) => PreviewServer | Promise; export interface PreviewModule { @@ -3351,7 +3351,7 @@ type DirectiveOptions = { export type ClientDirective = ( load: DirectiveLoad, options: DirectiveOptions, - el: HTMLElement + el: HTMLElement, ) => void; export interface ClientDirectiveConfig { @@ -3399,7 +3399,7 @@ export type DevToolbarApp = { init?( canvas: ShadowRoot, app: ToolbarAppEventTarget, - server: ToolbarServerHelpers + server: ToolbarServerHelpers, ): void | Promise; beforeTogglingOff?(canvas: ShadowRoot): boolean | Promise; }; @@ -3464,7 +3464,7 @@ declare global { // Container types export type ContainerImportRendererFn = ( - containerRenderer: ContainerRenderer + containerRenderer: ContainerRenderer, ) => Promise; export type ContainerRenderer = { diff --git a/packages/astro/src/actions/index.ts b/packages/astro/src/actions/index.ts index f176988ff0..04a911856f 100644 --- a/packages/astro/src/actions/index.ts +++ b/packages/astro/src/actions/index.ts @@ -31,7 +31,7 @@ export default function astroActions({ } const stringifiedActionsImport = JSON.stringify( - viteID(new URL('./actions', params.config.srcDir)) + viteID(new URL('./actions', params.config.srcDir)), ); params.updateConfig({ vite: { @@ -75,7 +75,7 @@ export function vitePluginUserActions({ settings }: { settings: AstroSettings }) } if (id === VIRTUAL_INTERNAL_MODULE_ID) { const resolvedModule = await this.resolve( - `${decodeURI(new URL('actions', settings.config.srcDir).pathname)}` + `${decodeURI(new URL('actions', settings.config.srcDir).pathname)}`, ); if (!resolvedModule) { @@ -109,7 +109,7 @@ const vitePluginActions = (fs: typeof fsMod): VitePlugin => ({ let code = await fs.promises.readFile( new URL('../../templates/actions.mjs', import.meta.url), - 'utf-8' + 'utf-8', ); if (opts?.ssr) { code += `\nexport * from 'astro/actions/runtime/virtual/server.js';`; diff --git a/packages/astro/src/actions/runtime/middleware.ts b/packages/astro/src/actions/runtime/middleware.ts index 3d430b04a4..0b93eb72fd 100644 --- a/packages/astro/src/actions/runtime/middleware.ts +++ b/packages/astro/src/actions/runtime/middleware.ts @@ -35,7 +35,7 @@ export const onRequest = defineMiddleware(async (context, next) => { // eslint-disable-next-line no-console console.warn( yellow('[astro:actions]'), - 'POST requests should not be sent to prerendered pages. If you\'re using Actions, disable prerendering with `export const prerender = "false".' + 'POST requests should not be sent to prerendered pages. If you\'re using Actions, disable prerendering with `export const prerender = "false".', ); return next(); } diff --git a/packages/astro/src/actions/runtime/virtual/client.ts b/packages/astro/src/actions/runtime/virtual/client.ts index ddeba9a758..424552a9fe 100644 --- a/packages/astro/src/actions/runtime/virtual/client.ts +++ b/packages/astro/src/actions/runtime/virtual/client.ts @@ -10,5 +10,5 @@ export const z = new Proxy( get() { throw new Error('[astro:action] `z` unexpectedly used on the client.'); }, - } + }, ); diff --git a/packages/astro/src/actions/runtime/virtual/get-action.ts b/packages/astro/src/actions/runtime/virtual/get-action.ts index 052849c482..cb9addd9dd 100644 --- a/packages/astro/src/actions/runtime/virtual/get-action.ts +++ b/packages/astro/src/actions/runtime/virtual/get-action.ts @@ -7,7 +7,7 @@ import type { ActionAccept, ActionClient } from './server.js'; * the user's `src/actions/index.ts` file at build-time. */ export async function getAction( - path: string + path: string, ): Promise | undefined> { const pathKeys = path.replace('/_actions/', '').split('.'); // @ts-expect-error virtual module diff --git a/packages/astro/src/actions/runtime/virtual/server.ts b/packages/astro/src/actions/runtime/virtual/server.ts index 94a993f041..a711f10326 100644 --- a/packages/astro/src/actions/runtime/virtual/server.ts +++ b/packages/astro/src/actions/runtime/virtual/server.ts @@ -25,7 +25,7 @@ export type ActionClient< TInputSchema extends ActionInputSchema | undefined, > = TInputSchema extends z.ZodType ? (( - input: TAccept extends 'form' ? FormData : z.input + input: TAccept extends 'form' ? FormData : z.input, ) => Promise< SafeResult< z.input extends ErrorInferenceObject @@ -36,7 +36,7 @@ export type ActionClient< >) & { queryString: string; orThrow: ( - input: TAccept extends 'form' ? FormData : z.input + input: TAccept extends 'form' ? FormData : z.input, ) => Promise>; } : (input?: any) => Promise>> & { @@ -85,7 +85,7 @@ export function defineAction< function getFormServerHandler>( handler: ActionHandler, - inputSchema?: TInputSchema + inputSchema?: TInputSchema, ) { return async (unparsedInput: unknown, context: ActionAPIContext): Promise> => { if (!(unparsedInput instanceof FormData)) { @@ -107,7 +107,7 @@ function getFormServerHandler>( handler: ActionHandler, - inputSchema?: TInputSchema + inputSchema?: TInputSchema, ) { return async (unparsedInput: unknown, context: ActionAPIContext): Promise> => { if (unparsedInput instanceof FormData) { @@ -129,7 +129,7 @@ function getJsonServerHandler( formData: FormData, - schema: T + schema: T, ): Record { const obj: Record = {}; for (const [key, baseValidator] of Object.entries(schema.shape)) { @@ -151,7 +151,7 @@ export function formDataToObject( function handleFormDataGetAll( key: string, formData: FormData, - validator: z.ZodArray + validator: z.ZodArray, ) { const entries = Array.from(formData.getAll(key)); const elementValidator = validator._def.type; @@ -167,7 +167,7 @@ function handleFormDataGet( key: string, formData: FormData, validator: unknown, - baseValidator: unknown + baseValidator: unknown, ) { const value = formData.get(key); if (!value) { diff --git a/packages/astro/src/actions/runtime/virtual/shared.ts b/packages/astro/src/actions/runtime/virtual/shared.ts index e00a89c684..962a0bec8a 100644 --- a/packages/astro/src/actions/runtime/virtual/shared.ts +++ b/packages/astro/src/actions/runtime/virtual/shared.ts @@ -41,7 +41,7 @@ const codeToStatusMap: Record = { const statusToCodeMap: Record = Object.entries(codeToStatusMap).reduce( // reverse the key-value pairs (acc, [key, value]) => ({ ...acc, [value]: key }), - {} + {}, ); // T is used for error inference with SafeInput -> isInputError. @@ -92,11 +92,11 @@ export function isActionError(error?: unknown): error is ActionError { } export function isInputError( - error?: ActionError + error?: ActionError, ): error is ActionInputError; export function isInputError(error?: unknown): error is ActionInputError; export function isInputError( - error?: unknown | ActionError + error?: unknown | ActionError, ): error is ActionInputError { return ( typeof error === 'object' && @@ -146,7 +146,7 @@ export class ActionInputError extends ActionErro } export async function callSafely( - handler: () => MaybePromise + handler: () => MaybePromise, ): Promise> { try { const data = await handler(); diff --git a/packages/astro/src/assets/build/generate.ts b/packages/astro/src/assets/build/generate.ts index 52edeafbec..fcc19f4f53 100644 --- a/packages/astro/src/assets/build/generate.ts +++ b/packages/astro/src/assets/build/generate.ts @@ -48,7 +48,7 @@ type ImageData = { data: Uint8Array; expires: number }; export async function prepareAssetsGenerationEnv( pipeline: BuildPipeline, - totalCount: number + totalCount: number, ): Promise { const { config, logger } = pipeline; let useCache = true; @@ -61,7 +61,7 @@ export async function prepareAssetsGenerationEnv( } catch (err) { logger.warn( null, - `An error was encountered while creating the cache directory. Proceeding without caching. Error: ${err}` + `An error was encountered while creating the cache directory. Proceeding without caching. Error: ${err}`, ); useCache = false; } @@ -96,7 +96,7 @@ export async function generateImagesForPath( originalFilePath: string, transformsAndPath: MapValue, env: AssetEnv, - queue: PQueue + queue: PQueue, ) { const originalImageData = await loadImage(originalFilePath, env); @@ -119,7 +119,7 @@ export async function generateImagesForPath( if (transformsAndPath.originalSrcPath) { env.logger.debug( 'assets', - `Deleting ${originalFilePath} as it's not referenced outside of image processing.` + `Deleting ${originalFilePath} as it's not referenced outside of image processing.`, ); await fs.promises.unlink(getFullImagePath(originalFilePath, env)); } @@ -131,7 +131,7 @@ export async function generateImagesForPath( async function generateImage( originalImage: ImageData, filepath: string, - options: ImageTransform + options: ImageTransform, ) { const timeStart = performance.now(); const generationData = await generateImageInternal(originalImage, filepath, options); @@ -145,7 +145,7 @@ export async function generateImagesForPath( const count = `(${env.count.current}/${env.count.total})`; env.logger.info( null, - ` ${green('▶')} ${filepath} ${dim(statsText)} ${dim(timeIncrease)} ${dim(count)}` + ` ${green('▶')} ${filepath} ${dim(statsText)} ${dim(timeIncrease)} ${dim(count)}`, ); env.count.current++; } @@ -153,7 +153,7 @@ export async function generateImagesForPath( async function generateImageInternal( originalImage: ImageData, filepath: string, - options: ImageTransform + options: ImageTransform, ): Promise { const isLocalImage = isESMImportedImage(options.src); const finalFileURL = new URL('.' + filepath, env.clientRoot); @@ -177,7 +177,7 @@ export async function generateImagesForPath( await fs.promises.unlink(cachedFileURL); throw new Error( - `Malformed cache entry for ${filepath}, cache will be regenerated for this file.` + `Malformed cache entry for ${filepath}, cache will be regenerated for this file.`, ); } @@ -219,7 +219,7 @@ export async function generateImagesForPath( await imageService.transform( originalImage.data, { ...options, src: originalImagePath }, - env.imageConfig + env.imageConfig, ) ).data; } catch (e) { @@ -228,7 +228,7 @@ export async function generateImagesForPath( ...AstroErrorData.CouldNotTransformImage, message: AstroErrorData.CouldNotTransformImage.message(originalFilePath), }, - { cause: e } + { cause: e }, ); throw error; @@ -245,14 +245,14 @@ export async function generateImagesForPath( JSON.stringify({ data: Buffer.from(resultData.data).toString('base64'), expires: resultData.expires, - }) + }), ); } } } catch (e) { env.logger.warn( null, - `An error was encountered while creating the cache directory. Proceeding without caching. Error: ${e}` + `An error was encountered while creating the cache directory. Proceeding without caching. Error: ${e}`, ); } finally { // Write the final file diff --git a/packages/astro/src/assets/build/remote.ts b/packages/astro/src/assets/build/remote.ts index c3d4bb9bae..08f8f45191 100644 --- a/packages/astro/src/assets/build/remote.ts +++ b/packages/astro/src/assets/build/remote.ts @@ -8,7 +8,7 @@ export async function loadRemoteImage(src: string) { if (!res.ok) { throw new Error( - `Failed to load remote image ${src}. The request did not return a 200 OK response. (received ${res.status}))` + `Failed to load remote image ${src}. The request did not return a 200 OK response. (received ${res.status}))`, ); } diff --git a/packages/astro/src/assets/endpoint/generic.ts b/packages/astro/src/assets/endpoint/generic.ts index 4180bffe2c..5238f3721a 100644 --- a/packages/astro/src/assets/endpoint/generic.ts +++ b/packages/astro/src/assets/endpoint/generic.ts @@ -60,7 +60,7 @@ export const GET: APIRoute = async ({ request }) => { const { data, format } = await imageService.transform( new Uint8Array(inputBuffer), transform, - imageConfig + imageConfig, ); return new Response(data, { diff --git a/packages/astro/src/assets/endpoint/node.ts b/packages/astro/src/assets/endpoint/node.ts index ecbb75179b..4c50fe95fd 100644 --- a/packages/astro/src/assets/endpoint/node.ts +++ b/packages/astro/src/assets/endpoint/node.ts @@ -83,7 +83,7 @@ export const GET: APIRoute = async ({ request }) => { if (!transform?.src) { const err = new Error( - 'Incorrect transform returned by `parseURL`. Expected a transform with a `src` property.' + 'Incorrect transform returned by `parseURL`. Expected a transform with a `src` property.', ); console.error('Could not parse image transform from URL:', err); return new Response('Internal Server Error', { status: 500 }); @@ -122,7 +122,7 @@ export const GET: APIRoute = async ({ request }) => { import.meta.env.DEV ? `Could not process image request: ${err}` : `Internal Server Error`, { status: 500, - } + }, ); } }; diff --git a/packages/astro/src/assets/internal.ts b/packages/astro/src/assets/internal.ts index 7265e85dfb..38afbf19fc 100644 --- a/packages/astro/src/assets/internal.ts +++ b/packages/astro/src/assets/internal.ts @@ -33,7 +33,7 @@ export async function getConfiguredImageService(): Promise { export async function getImage( options: UnresolvedImageTransform, - imageConfig: AstroConfig['image'] + imageConfig: AstroConfig['image'], ): Promise { if (!options || typeof options !== 'object') { throw new AstroError({ @@ -47,7 +47,7 @@ export async function getImage( message: AstroErrorData.ExpectedImage.message( options.src, 'undefined', - JSON.stringify(options) + JSON.stringify(options), ), }); } @@ -101,7 +101,7 @@ export async function getImage( url: await service.getURL(srcSet.transform, imageConfig), descriptor: srcSet.descriptor, attributes: srcSet.attributes, - })) + })), ); if ( @@ -113,7 +113,7 @@ export async function getImage( imageURL = globalThis.astroAsset.addStaticImage( validatedOptions, propsToHash, - originalFilePath + originalFilePath, ); srcSets = srcSetTransforms.map((srcSet) => ({ transform: srcSet.transform, diff --git a/packages/astro/src/assets/services/service.ts b/packages/astro/src/assets/services/service.ts index 0a4ff4064e..9cd6d0ecba 100644 --- a/packages/astro/src/assets/services/service.ts +++ b/packages/astro/src/assets/services/service.ts @@ -47,7 +47,7 @@ interface SharedServiceProps = Record */ getSrcSet?: ( options: ImageTransform, - imageConfig: ImageConfig + imageConfig: ImageConfig, ) => UnresolvedSrcSetValue[] | Promise; /** * Return any additional HTML attributes separate from `src` that your service requires to show the image properly. @@ -57,7 +57,7 @@ interface SharedServiceProps = Record */ getHTMLAttributes?: ( options: ImageTransform, - imageConfig: ImageConfig + imageConfig: ImageConfig, ) => Record | Promise>; /** * Validate and return the options passed by the user. @@ -69,7 +69,7 @@ interface SharedServiceProps = Record */ validateOptions?: ( options: ImageTransform, - imageConfig: ImageConfig + imageConfig: ImageConfig, ) => ImageTransform | Promise; } @@ -90,7 +90,7 @@ export interface LocalImageService = Record + imageConfig: ImageConfig, ) => LocalImageTransform | undefined | Promise | Promise; /** * Performs the image transformations on the input image and returns both the binary data and @@ -99,7 +99,7 @@ export interface LocalImageService = Record + imageConfig: ImageConfig, ) => Promise<{ data: Uint8Array; format: ImageOutputFormat }>; /** @@ -148,7 +148,7 @@ export const baseService: Omit = { message: AstroErrorData.ExpectedImage.message( JSON.stringify(options.src), typeof options.src, - JSON.stringify(options, (_, v) => (v === undefined ? null : v)) + JSON.stringify(options, (_, v) => (v === undefined ? null : v)), ), }); } @@ -188,7 +188,7 @@ export const baseService: Omit = { message: AstroErrorData.UnsupportedImageFormat.message( options.src.format, options.src.src, - VALID_SUPPORTED_FORMATS + VALID_SUPPORTED_FORMATS, ), }); } @@ -281,14 +281,14 @@ export const baseService: Omit = { ...densityWidths.map((width, index) => ({ maxTargetWidth: Math.min(width, maxWidth), descriptor: `${densityValues[index]}x` as const, - })) + })), ); } else if (widths) { allWidths.push( ...widths.map((width) => ({ maxTargetWidth: Math.min(width, maxWidth), descriptor: `${width}w` as const, - })) + })), ); } diff --git a/packages/astro/src/assets/services/squoosh.ts b/packages/astro/src/assets/services/squoosh.ts index ddadaabf38..6eb78db4b2 100644 --- a/packages/astro/src/assets/services/squoosh.ts +++ b/packages/astro/src/assets/services/squoosh.ts @@ -31,7 +31,7 @@ const qualityTable: Record< async function getRotationForEXIF( inputBuffer: Uint8Array, - src?: string + src?: string, ): Promise { const meta = await imageMetadata(inputBuffer, src); if (!meta) return undefined; diff --git a/packages/astro/src/assets/utils/metadata.ts b/packages/astro/src/assets/utils/metadata.ts index 645a2a5c66..d212bdeb7c 100644 --- a/packages/astro/src/assets/utils/metadata.ts +++ b/packages/astro/src/assets/utils/metadata.ts @@ -4,7 +4,7 @@ import { lookup as probe } from '../utils/vendor/image-size/lookup.js'; export async function imageMetadata( data: Uint8Array, - src?: string + src?: string, ): Promise> { try { const result = probe(data); diff --git a/packages/astro/src/assets/utils/node/emitAsset.ts b/packages/astro/src/assets/utils/node/emitAsset.ts index 09a9475387..b20ce49330 100644 --- a/packages/astro/src/assets/utils/node/emitAsset.ts +++ b/packages/astro/src/assets/utils/node/emitAsset.ts @@ -14,7 +14,7 @@ export async function emitESMImage( _watchMode: boolean, // FIX: in Astro 5, this function should not be passed in dev mode at all. // Or rethink the API so that a function that throws isn't passed through. - fileEmitter?: FileEmitter + fileEmitter?: FileEmitter, ): Promise { if (!id) { return undefined; diff --git a/packages/astro/src/assets/utils/queryParams.ts b/packages/astro/src/assets/utils/queryParams.ts index 56bb4b3ff9..b073c9786a 100644 --- a/packages/astro/src/assets/utils/queryParams.ts +++ b/packages/astro/src/assets/utils/queryParams.ts @@ -1,7 +1,7 @@ import type { ImageInputFormat, ImageMetadata } from '../types.js'; export function getOrigQueryParams( - params: URLSearchParams + params: URLSearchParams, ): Pick | undefined { const width = params.get('origWidth'); const height = params.get('origHeight'); diff --git a/packages/astro/src/assets/utils/remotePattern.ts b/packages/astro/src/assets/utils/remotePattern.ts index 3384e313e1..5feefb89fe 100644 --- a/packages/astro/src/assets/utils/remotePattern.ts +++ b/packages/astro/src/assets/utils/remotePattern.ts @@ -70,7 +70,7 @@ export function isRemoteAllowed( { domains = [], remotePatterns = [], - }: Partial> + }: Partial>, ): boolean { if (!isRemotePath(src)) return false; diff --git a/packages/astro/src/assets/utils/transformToPath.ts b/packages/astro/src/assets/utils/transformToPath.ts index 9a91098cc8..554761487d 100644 --- a/packages/astro/src/assets/utils/transformToPath.ts +++ b/packages/astro/src/assets/utils/transformToPath.ts @@ -18,7 +18,7 @@ export function propsToFilename(filePath: string, transform: ImageTransform, has export function hashTransform( transform: ImageTransform, imageService: string, - propertiesToHash: string[] + propertiesToHash: string[], ) { // Extract the fields we want to hash const hashFields = propertiesToHash.reduce( @@ -28,7 +28,7 @@ export function hashTransform( acc[prop] = transform[prop]; return acc; }, - { imageService } as Record + { imageService } as Record, ); return shorthash(deterministicString(hashFields)); } diff --git a/packages/astro/src/assets/vite-plugin-assets.ts b/packages/astro/src/assets/vite-plugin-assets.ts index 949a6e6722..4c9314e85f 100644 --- a/packages/astro/src/assets/vite-plugin-assets.ts +++ b/packages/astro/src/assets/vite-plugin-assets.ts @@ -25,7 +25,7 @@ const resolvedVirtualModuleId = '\0' + VIRTUAL_MODULE_ID; const assetRegex = new RegExp(`\\.(${VALID_INPUT_FORMATS.join('|')})`, 'i'); const assetRegexEnds = new RegExp(`\\.(${VALID_INPUT_FORMATS.join('|')})$`, 'i'); const addStaticImageFactory = ( - settings: AstroSettings + settings: AstroSettings, ): typeof globalThis.astroAsset.addStaticImage => { return (options, hashProperties, originalFSPath) => { if (!globalThis.astroAsset.staticImages) { @@ -46,7 +46,7 @@ const addStaticImageFactory = ( // This is the path to the original image, from the dist root, without the base or the asset prefix (e.g. /_astro/image.hash.png) const finalOriginalPath = removeBase( removeBase(ESMImportedImageSrc, settings.config.base), - assetPrefix + assetPrefix, ); const hash = hashTransform(options, settings.config.image.service.entrypoint, hashProperties); @@ -62,8 +62,8 @@ const addStaticImageFactory = ( finalFilePath = prependForwardSlash( joinPaths( isESMImportedImage(options.src) ? '' : settings.config.build.assets, - prependForwardSlash(propsToFilename(finalOriginalPath, options, hash)) - ) + prependForwardSlash(propsToFilename(finalOriginalPath, options, hash)), + ), ); if (!transformsForPath) { @@ -146,11 +146,11 @@ export default function assets({ new URL( isServerLikeOutput(settings.config) ? settings.config.build.client - : settings.config.outDir - ) + : settings.config.outDir, + ), )}); export const assetsDir = /* #__PURE__ */ new URL(${JSON.stringify( - settings.config.build.assets + settings.config.build.assets, )}, outDir); export const getImage = async (options) => await getImageInternal(options, imageConfig); `; @@ -235,7 +235,7 @@ export default function assets({ if (options?.ssr) { return `export default ${getProxyCode( imageMetadata, - isServerLikeOutput(settings.config) + isServerLikeOutput(settings.config), )}`; } else { globalThis.astroAsset.referencedImages.add(imageMetadata.fsPath); diff --git a/packages/astro/src/cli/add/imports.ts b/packages/astro/src/cli/add/imports.ts index bae8c74437..375ca1dd8a 100644 --- a/packages/astro/src/cli/add/imports.ts +++ b/packages/astro/src/cli/add/imports.ts @@ -12,7 +12,7 @@ export function ensureImport(root: t.File, importDeclaration: t.ImportDeclaratio if (specifier.local.name === specifierToFind.local.name) { specifiersToFind.splice(i, 1); } - }) + }), ); } }, diff --git a/packages/astro/src/cli/add/index.ts b/packages/astro/src/cli/add/index.ts index 48cdb41a27..7d33fe33a5 100644 --- a/packages/astro/src/cli/add/index.ts +++ b/packages/astro/src/cli/add/index.ts @@ -191,9 +191,9 @@ export async function add(names: string[], { flags }: AddOptions) { 'SKIP_FORMAT', `\n ${magenta( `Astro will scaffold ${green('./db/config.ts')}${magenta(' and ')}${green( - './db/seed.ts' - )}${magenta(' files.')}` - )}\n` + './db/seed.ts', + )}${magenta(' files.')}`, + )}\n`, ); if (await askToContinue({ flags })) { @@ -205,7 +205,7 @@ export async function add(names: string[], { flags }: AddOptions) { } else { logger.info( 'SKIP_FORMAT', - `\n Astro DB requires additional configuration. Please refer to https://astro.build/db/config` + `\n Astro DB requires additional configuration. Please refer to https://astro.build/db/config`, ); } } else { @@ -235,8 +235,8 @@ export async function add(names: string[], { flags }: AddOptions) { 'SKIP_FORMAT', msg.cancelled( `Dependencies ${bold('NOT')} installed.`, - `Be sure to install them manually before continuing!` - ) + `Be sure to install them manually before continuing!`, + ), ); break; } @@ -273,8 +273,8 @@ export async function add(names: string[], { flags }: AddOptions) { ast, t.importDeclaration( [t.importSpecifier(defineConfig, defineConfig)], - t.stringLiteral('astro/config') - ) + t.stringLiteral('astro/config'), + ), ); wrapDefaultExport(ast, defineConfig); @@ -290,9 +290,9 @@ export async function add(names: string[], { flags }: AddOptions) { 'SKIP_FORMAT', `\n ${magenta( `Check our deployment docs for ${bold( - integration.packageName - )} to update your "adapter" config.` - )}` + integration.packageName, + )} to update your "adapter" config.`, + )}`, ); } } else { @@ -326,7 +326,7 @@ export async function add(names: string[], { flags }: AddOptions) { case UpdateResult.cancelled: { logger.info( 'SKIP_FORMAT', - msg.cancelled(`Your configuration has ${bold('NOT')} been updated.`) + msg.cancelled(`Your configuration has ${bold('NOT')} been updated.`), ); break; } @@ -338,7 +338,7 @@ export async function add(names: string[], { flags }: AddOptions) { .then((res) => JSON.parse(res.toString())); const deps = Object.keys(Object.assign(dependencies, devDependencies)); const missingDeps = integrations.filter( - (integration) => !deps.includes(integration.packageName) + (integration) => !deps.includes(integration.packageName), ); if (missingDeps.length === 0) { logger.info('SKIP_FORMAT', msg.success(`Configuration up-to-date.`)); @@ -356,8 +356,8 @@ export async function add(names: string[], { flags }: AddOptions) { msg.success( `Added the following integration${ integrations.length === 1 ? '' : 's' - } to your project:\n${list}` - ) + } to your project:\n${list}`, + ), ); } } @@ -371,13 +371,13 @@ export async function add(names: string[], { flags }: AddOptions) { case UpdateResult.cancelled: { logger.info( 'SKIP_FORMAT', - msg.cancelled(`Your TypeScript configuration has ${bold('NOT')} been updated.`) + msg.cancelled(`Your TypeScript configuration has ${bold('NOT')} been updated.`), ); break; } case UpdateResult.failure: { throw new Error( - `Unknown error parsing tsconfig.json or jsconfig.json. Could not update TypeScript settings.` + `Unknown error parsing tsconfig.json or jsconfig.json. Could not update TypeScript settings.`, ); } default: @@ -386,7 +386,7 @@ export async function add(names: string[], { flags }: AddOptions) { } function isAdapter( - integration: IntegrationInfo + integration: IntegrationInfo, ): integration is IntegrationInfo & { type: 'adapter' } { return integration.type === 'adapter'; } @@ -445,8 +445,8 @@ async function addIntegration(ast: t.File, integration: IntegrationInfo) { ast, t.importDeclaration( [t.importDefaultSpecifier(integrationId)], - t.stringLiteral(integration.packageName) - ) + t.stringLiteral(integration.packageName), + ), ); visit(ast, { @@ -472,7 +472,7 @@ async function addIntegration(ast: t.File, integration: IntegrationInfo) { if (!integrationsProp) { configObject.properties.push( - t.objectProperty(t.identifier('integrations'), t.arrayExpression([integrationCall])) + t.objectProperty(t.identifier('integrations'), t.arrayExpression([integrationCall])), ); return; } @@ -484,7 +484,7 @@ async function addIntegration(ast: t.File, integration: IntegrationInfo) { (expr) => t.isCallExpression(expr) && t.isIdentifier(expr.callee) && - expr.callee.name === integrationId.name + expr.callee.name === integrationId.name, ); if (existingIntegrationCall) return; @@ -499,7 +499,7 @@ async function setAdapter(ast: t.File, adapter: IntegrationInfo, exportName: str ensureImport( ast, - t.importDeclaration([t.importDefaultSpecifier(adapterId)], t.stringLiteral(exportName)) + t.importDeclaration([t.importDefaultSpecifier(adapterId)], t.stringLiteral(exportName)), ); visit(ast, { @@ -523,7 +523,7 @@ async function setAdapter(ast: t.File, adapter: IntegrationInfo, exportName: str if (!outputProp) { configObject.properties.push( - t.objectProperty(t.identifier('output'), t.stringLiteral('server')) + t.objectProperty(t.identifier('output'), t.stringLiteral('server')), ); } @@ -610,7 +610,7 @@ async function updateAstroConfig({ logger.info( 'SKIP_FORMAT', - `\n ${magenta('Astro will make the following changes to your config file:')}\n${message}` + `\n ${magenta('Astro will make the following changes to your config file:')}\n${message}`, ); if (logAdapterInstructions) { @@ -618,9 +618,9 @@ async function updateAstroConfig({ 'SKIP_FORMAT', magenta( ` For complete deployment options, visit\n ${bold( - 'https://docs.astro.build/en/guides/deploy/' - )}\n` - ) + 'https://docs.astro.build/en/guides/deploy/', + )}\n`, + ), ); } @@ -669,7 +669,7 @@ async function getInstallIntegrationsCommand({ } async function convertIntegrationsToInstallSpecifiers( - integrations: IntegrationInfo[] + integrations: IntegrationInfo[], ): Promise { const ranges: Record = {}; for (let { packageName, dependencies } of integrations) { @@ -679,7 +679,7 @@ async function convertIntegrationsToInstallSpecifiers( } } return Promise.all( - Object.entries(ranges).map(([name, range]) => resolveRangeToInstallSpecifier(name, range)) + Object.entries(ranges).map(([name, range]) => resolveRangeToInstallSpecifier(name, range)), ); } @@ -749,8 +749,8 @@ async function tryToInstallIntegrations({ logger.info( 'SKIP_FORMAT', `\n ${magenta('Astro will run the following command:')}\n ${dim( - 'If you skip this step, you can always run it yourself later' - )}\n${message}` + 'If you skip this step, you can always run it yourself later', + )}\n${message}`, ); if (await askToContinue({ flags })) { @@ -768,7 +768,7 @@ async function tryToInstallIntegrations({ cwd, // reset NODE_ENV to ensure install command run in dev mode env: { NODE_ENV: undefined }, - } + }, ); spinner.succeed(); return UpdateResult.updated; @@ -817,8 +817,8 @@ async function validateIntegrations(integrations: string[]): Promise { const integrations = integrationsInfo.map( - (integration) => integration.id as frameworkWithTSSettings + (integration) => integration.id as frameworkWithTSSettings, ); const firstIntegrationWithTSSettings = integrations.find((integration) => - presets.has(integration) + presets.has(integration), ); if (!firstIntegrationWithTSSettings) { @@ -926,7 +926,7 @@ async function updateTSConfig( const outputConfig = updateTSConfigForFramework( inputConfig.rawConfig, - firstIntegrationWithTSSettings + firstIntegrationWithTSSettings, ); const output = JSON.stringify(outputConfig, null, 2); @@ -945,7 +945,7 @@ async function updateTSConfig( logger.info( 'SKIP_FORMAT', - `\n ${magenta(`Astro will make the following changes to your ${configFileName}:`)}\n${message}` + `\n ${magenta(`Astro will make the following changes to your ${configFileName}:`)}\n${message}`, ); // Every major framework, apart from Vue and Svelte requires different `jsxImportSource`, as such it's impossible to config @@ -961,11 +961,11 @@ async function updateTSConfig( 'SKIP_FORMAT', red( ` ${bold( - 'Caution:' + 'Caution:', )} Selected UI frameworks require conflicting tsconfig.json settings, as such only settings for ${bold( - firstIntegrationWithTSSettings - )} were used.\n More information: https://docs.astro.build/en/guides/typescript/#errors-typing-multiple-jsx-frameworks-at-the-same-time\n` - ) + firstIntegrationWithTSSettings, + )} were used.\n More information: https://docs.astro.build/en/guides/typescript/#errors-typing-multiple-jsx-frameworks-at-the-same-time\n`, + ), ); } @@ -1046,7 +1046,7 @@ async function setupIntegrationConfig(opts: { }) { const logger = opts.logger; const possibleConfigFiles = opts.possibleConfigFiles.map((p) => - fileURLToPath(new URL(p, opts.root)) + fileURLToPath(new URL(p, opts.root)), ); let alreadyConfigured = false; for (const possibleConfigPath of possibleConfigFiles) { @@ -1058,7 +1058,7 @@ async function setupIntegrationConfig(opts: { if (!alreadyConfigured) { logger.info( 'SKIP_FORMAT', - `\n ${magenta(`Astro will generate a minimal ${bold(opts.defaultConfigFile)} file.`)}\n` + `\n ${magenta(`Astro will generate a minimal ${bold(opts.defaultConfigFile)} file.`)}\n`, ); if (await askToContinue({ flags: opts.flags })) { await fs.writeFile( @@ -1066,7 +1066,7 @@ async function setupIntegrationConfig(opts: { opts.defaultConfigContent, { encoding: 'utf-8', - } + }, ); logger.debug('add', `Generated default ${opts.defaultConfigFile} file`); } diff --git a/packages/astro/src/cli/check/index.ts b/packages/astro/src/cli/check/index.ts index 00bc3d11a2..a95e1074a5 100644 --- a/packages/astro/src/cli/check/index.ts +++ b/packages/astro/src/cli/check/index.ts @@ -12,14 +12,14 @@ export async function check(flags: Arguments) { '@astrojs/check', logger, getPackageOpts, - ['typescript'] + ['typescript'], ); const typescript = await getPackage('typescript', logger, getPackageOpts); if (!checkPackage || !typescript) { logger.error( 'check', - 'The `@astrojs/check` and `typescript` packages are required for this command to work. Please manually install them into your project and try again.' + 'The `@astrojs/check` and `typescript` packages are required for this command to work. Please manually install them into your project and try again.', ); return; } diff --git a/packages/astro/src/cli/db/index.ts b/packages/astro/src/cli/db/index.ts index d7ac76efe1..dc6da36e1d 100644 --- a/packages/astro/src/cli/db/index.ts +++ b/packages/astro/src/cli/db/index.ts @@ -18,7 +18,7 @@ export async function db({ flags }: { flags: Arguments }) { if (!dbPackage) { logger.error( 'check', - 'The `@astrojs/db` package is required for this command to work. Please manually install it in your project and try again.' + 'The `@astrojs/db` package is required for this command to work. Please manually install it in your project and try again.', ); return; } diff --git a/packages/astro/src/cli/dev/index.ts b/packages/astro/src/cli/dev/index.ts index 5db47fb970..531cddde4c 100644 --- a/packages/astro/src/cli/dev/index.ts +++ b/packages/astro/src/cli/dev/index.ts @@ -23,7 +23,7 @@ export async function dev({ flags }: DevOptions) { ], }, description: `Check ${cyan( - 'https://docs.astro.build/en/reference/cli-reference/#astro-dev' + 'https://docs.astro.build/en/reference/cli-reference/#astro-dev', )} for more information.`, }); return; diff --git a/packages/astro/src/cli/docs/open.ts b/packages/astro/src/cli/docs/open.ts index 1227ebff4a..3913ccec4f 100644 --- a/packages/astro/src/cli/docs/open.ts +++ b/packages/astro/src/cli/docs/open.ts @@ -21,7 +21,7 @@ const getPlatformSpecificCommand = (): [string] | [string, string[]] => { return ['/ide/bin/remote-cli/gitpod-code', ['--openExternal']]; default: throw new Error( - `It looks like your platform ("${platform}") isn't supported!\nTo view Astro's docs, please visit https://docs.astro.build` + `It looks like your platform ("${platform}") isn't supported!\nTo view Astro's docs, please visit https://docs.astro.build`, ); } }; diff --git a/packages/astro/src/cli/info/index.ts b/packages/astro/src/cli/info/index.ts index 8a253f4373..cb61e45bfc 100644 --- a/packages/astro/src/cli/info/index.ts +++ b/packages/astro/src/cli/info/index.ts @@ -93,7 +93,7 @@ async function copyToClipboard(text: string) { }); } catch { console.error( - colors.red(`\nSorry, something went wrong!`) + ` Please copy the text above manually.` + colors.red(`\nSorry, something went wrong!`) + ` Please copy the text above manually.`, ); } } diff --git a/packages/astro/src/cli/install-package.ts b/packages/astro/src/cli/install-package.ts index 46dfac4a36..637390ef3c 100644 --- a/packages/astro/src/cli/install-package.ts +++ b/packages/astro/src/cli/install-package.ts @@ -21,7 +21,7 @@ export async function getPackage( packageName: string, logger: Logger, options: GetPackageOptions, - otherDeps: string[] = [] + otherDeps: string[] = [], ): Promise { try { // Try to resolve with `createRequire` first to prevent ESM caching of the package @@ -32,7 +32,7 @@ export async function getPackage( } catch { if (options.optional) return undefined; let message = `To continue, Astro requires the following dependency to be installed: ${bold( - packageName + packageName, )}.`; if (ci.isCI) { @@ -98,7 +98,7 @@ export async function getExecCommand(packageManager?: string): Promise { async function installPackage( packageNames: string[], options: GetPackageOptions, - logger: Logger + logger: Logger, ): Promise { const cwd = options.cwd ?? process.cwd(); const packageManager = (await whichPm(cwd))?.name ?? 'npm'; @@ -120,8 +120,8 @@ async function installPackage( logger.info( 'SKIP_FORMAT', `\n ${magenta('Astro will run the following command:')}\n ${dim( - 'If you skip this step, you can always run it yourself later' - )}\n${message}` + 'If you skip this step, you can always run it yourself later', + )}\n${message}`, ); let response; @@ -144,7 +144,7 @@ async function installPackage( await execa( installCommand.pm, [installCommand.command, ...installCommand.flags, ...installCommand.dependencies], - { cwd: cwd } + { cwd: cwd }, ); spinner.succeed(); @@ -163,7 +163,7 @@ async function installPackage( export async function fetchPackageJson( scope: string | undefined, name: string, - tag: string + tag: string, ): Promise | Error> { const packageName = `${scope ? `${scope}/` : ''}${name}`; const registry = await getRegistry(); diff --git a/packages/astro/src/cli/preferences/index.ts b/packages/astro/src/cli/preferences/index.ts index aa63690dac..5735a9b6c2 100644 --- a/packages/astro/src/cli/preferences/index.ts +++ b/packages/astro/src/cli/preferences/index.ts @@ -43,7 +43,7 @@ export async function preferences( subcommand: string, key: string, value: string | undefined, - { flags }: PreferencesOptions + { flags }: PreferencesOptions, ): Promise { applyPolyfill(); if (!isValidSubcommand(subcommand) || flags?.help || flags?.h) { @@ -98,8 +98,8 @@ export async function preferences( console.error( msg.formatErrorMessage( collectErrorMetadata(new Error(`Please provide a ${type} value for "${key}"`)), - true - ) + true, + ), ); return 1; } @@ -128,7 +128,7 @@ interface SubcommandOptions { async function getPreference( settings: AstroSettings, key: PreferenceKey, - { location = 'project' }: SubcommandOptions + { location = 'project' }: SubcommandOptions, ) { try { let value = await settings.preferences.get(key, { location }); @@ -155,7 +155,7 @@ async function setPreference( settings: AstroSettings, key: PreferenceKey, value: unknown, - { location }: SubcommandOptions + { location }: SubcommandOptions, ) { try { const defaultType = typeof dlv(DEFAULT_PREFERENCES, key); @@ -178,7 +178,7 @@ async function setPreference( async function enablePreference( settings: AstroSettings, key: PreferenceKey, - { location }: SubcommandOptions + { location }: SubcommandOptions, ) { try { await settings.preferences.set(key, true, { location }); @@ -191,7 +191,7 @@ async function enablePreference( async function disablePreference( settings: AstroSettings, key: PreferenceKey, - { location }: SubcommandOptions + { location }: SubcommandOptions, ) { try { await settings.preferences.set(key, false, { location }); @@ -204,7 +204,7 @@ async function disablePreference( async function resetPreference( settings: AstroSettings, key: PreferenceKey, - { location }: SubcommandOptions + { location }: SubcommandOptions, ) { try { await settings.preferences.set(key, undefined as any, { location }); @@ -216,13 +216,13 @@ async function resetPreference( function annotate(flat: Record, annotation: string) { return Object.fromEntries( - Object.entries(flat).map(([key, value]) => [key, { annotation, value }]) + Object.entries(flat).map(([key, value]) => [key, { annotation, value }]), ); } function userValues( flatDefault: Record, flatProject: Record, - flatGlobal: Record + flatGlobal: Record, ) { const result: AnnotatedValues = {}; for (const key of Object.keys(flatDefault)) { @@ -289,8 +289,8 @@ async function listPreferences(settings: AstroSettings, { location, json }: Subc ) { console.log( yellow( - 'The dev toolbar is currently disabled. To enable it, set devToolbar: {enabled: true} in your astroConfig file.' - ) + 'The dev toolbar is currently disabled. To enable it, set devToolbar: {enabled: true} in your astroConfig file.', + ), ); } @@ -327,7 +327,7 @@ function annotatedFormat(mv: AnnotatedValue) { // this is the real formatting for annotated values function formatAnnotated( mv: AnnotatedValue, - style: (value: string | number | boolean) => string = (v) => v.toString() + style: (value: string | number | boolean) => string = (v) => v.toString(), ) { return mv.annotation ? `${style(mv.value)} ${dim(mv.annotation)}` : style(mv.value); } @@ -339,28 +339,28 @@ function formatTable(object: Record, columnLabels: [stri i: number, a: string, b: AnnotatedValue, - style: (value: string | number | boolean) => string = (v) => v.toString() + style: (value: string | number | boolean) => string = (v) => v.toString(), ): string { return `${dim(chars.v)} ${style(a)} ${space(colALength - a.length - 2)} ${dim( - chars.v + chars.v, )} ${formatAnnotated(b, style)} ${space(colBLength - annotatedFormat(b).length - 3)} ${dim( - chars.v + chars.v, )}`; } const top = dim( `${chars.topLeft}${chars.h.repeat(colALength + 1)}${chars.hBottom}${chars.h.repeat( - colBLength - )}${chars.topRight}` + colBLength, + )}${chars.topRight}`, ); const bottom = dim( `${chars.bottomLeft}${chars.h.repeat(colALength + 1)}${chars.hTop}${chars.h.repeat( - colBLength - )}${chars.bottomRight}` + colBLength, + )}${chars.bottomRight}`, ); const divider = dim( `${chars.vRightThick}${chars.hThick.repeat(colALength + 1)}${ chars.hThickCross - }${chars.hThick.repeat(colBLength)}${chars.vLeftThick}` + }${chars.hThick.repeat(colBLength)}${chars.vLeftThick}`, ); const rows: string[] = [top, formatRow(-1, colA, { value: colB, annotation: '' }, bold), divider]; let i = 0; diff --git a/packages/astro/src/cli/preview/index.ts b/packages/astro/src/cli/preview/index.ts index 0d569e2fba..387c1f241a 100644 --- a/packages/astro/src/cli/preview/index.ts +++ b/packages/astro/src/cli/preview/index.ts @@ -23,7 +23,7 @@ export async function preview({ flags }: PreviewOptions) { ], }, description: `Starts a local server to serve your static dist/ directory. Check ${cyan( - 'https://docs.astro.build/en/reference/cli-reference/#astro-preview' + 'https://docs.astro.build/en/reference/cli-reference/#astro-preview', )} for more information.`, }); return; diff --git a/packages/astro/src/config/index.ts b/packages/astro/src/config/index.ts index fb97288a6b..3c5faf2fa0 100644 --- a/packages/astro/src/config/index.ts +++ b/packages/astro/src/config/index.ts @@ -8,7 +8,7 @@ export function defineConfig(config: AstroUserConfig) { export function getViteConfig( userViteConfig: ViteUserConfig, - inlineAstroConfig: AstroInlineConfig = {} + inlineAstroConfig: AstroInlineConfig = {}, ) { // Return an async Vite config getter which exposes a resolved `mode` and `command` return async ({ mode, command }: { mode: string; command: 'serve' | 'build' }) => { @@ -48,7 +48,7 @@ export function getViteConfig( astroContentListenPlugin({ settings, logger, fs }), ], }, - { settings, logger, mode, sync: false } + { settings, logger, mode, sync: false }, ); await runHookConfigDone({ settings, logger }); return mergeConfig(viteConfig, userViteConfig); diff --git a/packages/astro/src/container/index.ts b/packages/astro/src/container/index.ts index d17ec7846d..292b49ece1 100644 --- a/packages/astro/src/container/index.ts +++ b/packages/astro/src/container/index.ts @@ -105,7 +105,7 @@ export type AddClientRenderer = { function createManifest( manifest?: AstroContainerManifest, renderers?: SSRLoadedRenderer[], - middleware?: MiddlewareHandler + middleware?: MiddlewareHandler, ): SSRManifest { const defaultMiddleware: MiddlewareHandler = (_, next) => { return next(); @@ -274,7 +274,7 @@ export class experimental_AstroContainer { * @param {AstroContainerOptions=} containerOptions */ public static async create( - containerOptions: AstroContainerOptions = {} + containerOptions: AstroContainerOptions = {}, ): Promise { const { streaming = false, manifest, renderers = [], resolve } = containerOptions; const astroConfig = await validateConfig(ASTRO_CONFIG_DEFAULTS, process.cwd(), 'container'); @@ -315,7 +315,7 @@ export class experimental_AstroContainer { if (!renderer.check || !renderer.renderToStaticMarkup) { throw new Error( "The renderer you passed isn't valid. A renderer is usually an object that exposes the `check` and `renderToStaticMarkup` functions.\n" + - "Usually, the renderer is exported by a /server.js entrypoint e.g. `import renderer from '@astrojs/react/server.js'`" + "Usually, the renderer is exported by a /server.js entrypoint e.g. `import renderer from '@astrojs/react/server.js'`", ); } if (isNamedRenderer(renderer)) { @@ -362,7 +362,7 @@ export class experimental_AstroContainer { throw new Error( 'You tried to add the ' + name + - " client renderer, but its server renderer wasn't added. You must add the server renderer first. Use the `addServerRenderer` function." + " client renderer, but its server renderer wasn't added. You must add the server renderer first. Use the `addServerRenderer` function.", ); } const renderer = this.#pipeline.manifest.renderers[rendererIndex]; @@ -374,7 +374,7 @@ export class experimental_AstroContainer { // NOTE: we keep this private via TS instead via `#` so it's still available on the surface, so we can play with it. // @ematipico: I plan to use it for a possible integration that could help people private static async createFromManifest( - manifest: SSRManifest + manifest: SSRManifest, ): Promise { const astroConfig = await validateConfig(ASTRO_CONFIG_DEFAULTS, process.cwd(), 'container'); const container = new experimental_AstroContainer({ @@ -431,7 +431,7 @@ export class experimental_AstroContainer { */ public async renderToString( component: AstroComponentFactory, - options: ContainerRenderOptions = {} + options: ContainerRenderOptions = {}, ): Promise { const response = await this.renderToResponse(component, options); return await response.text(); @@ -458,7 +458,7 @@ export class experimental_AstroContainer { */ public async renderToResponse( component: AstroComponentFactory, - options: ContainerRenderOptions = {} + options: ContainerRenderOptions = {}, ): Promise { const { routeType = 'page', slots } = options; const request = options?.request ?? new Request('https://example.com/'); @@ -510,7 +510,7 @@ export class experimental_AstroContainer { pattern: getPattern( segments, ASTRO_CONFIG_DEFAULTS.base, - ASTRO_CONFIG_DEFAULTS.trailingSlash + ASTRO_CONFIG_DEFAULTS.trailingSlash, ), prerender: false, segments, @@ -528,7 +528,7 @@ export class experimental_AstroContainer { */ #wrapComponent( componentFactory: AstroComponentFactory, - params?: Record + params?: Record, ): ComponentInstance { if (params) { return { diff --git a/packages/astro/src/container/pipeline.ts b/packages/astro/src/container/pipeline.ts index 1ad905bb59..ff2718b8fb 100644 --- a/packages/astro/src/container/pipeline.ts +++ b/packages/astro/src/container/pipeline.ts @@ -41,7 +41,7 @@ export class ContainerPipeline extends Pipeline { renderers, resolve, serverLike, - streaming + streaming, ); } @@ -70,7 +70,7 @@ export class ContainerPipeline extends Pipeline { async tryRewrite( payload: RewritePayload, - request: Request + request: Request, ): Promise<[RouteData, ComponentInstance, URL]> { const [foundRoute, finalUrl] = findRouteToRewrite({ payload, diff --git a/packages/astro/src/content/runtime-assets.ts b/packages/astro/src/content/runtime-assets.ts index 42969042c6..95b5092fe3 100644 --- a/packages/astro/src/content/runtime-assets.ts +++ b/packages/astro/src/content/runtime-assets.ts @@ -6,7 +6,7 @@ import { emitESMImage } from '../assets/utils/node/emitAsset.js'; export function createImage( pluginContext: PluginContext, shouldEmitFile: boolean, - entryFilePath: string + entryFilePath: string, ) { return () => { return z.string().transform(async (imagePath, ctx) => { @@ -14,7 +14,7 @@ export function createImage( const metadata = (await emitESMImage( resolvedFilePath, pluginContext.meta.watchMode, - shouldEmitFile ? pluginContext.emitFile : undefined + shouldEmitFile ? pluginContext.emitFile : undefined, )) as OmitBrand; if (!metadata) { diff --git a/packages/astro/src/content/runtime.ts b/packages/astro/src/content/runtime.ts index 6fd017c85c..34d2f10e92 100644 --- a/packages/astro/src/content/runtime.ts +++ b/packages/astro/src/content/runtime.ts @@ -65,15 +65,15 @@ export function createGetCollection({ // eslint-disable-next-line no-console console.warn( `The collection ${JSON.stringify( - collection - )} does not exist or is empty. Ensure a collection directory with this name exists.` + collection, + )} does not exist or is empty. Ensure a collection directory with this name exists.`, ); return []; } const lazyImports = Object.values( type === 'content' ? contentCollectionToEntryMap[collection] - : dataCollectionToEntryMap[collection] + : dataCollectionToEntryMap[collection], ); let entries: any[] = []; // Cache `getCollection()` calls in production only @@ -106,8 +106,8 @@ export function createGetCollection({ collection: entry.collection, data: entry.data, }; - }) - ) + }), + ), ); cacheEntriesByCollection.set(collection, entries); } @@ -196,7 +196,7 @@ export function createGetEntry({ // Or pass a single object with the collection and identifier as properties. // This means the first positional arg can have different shapes. collectionOrLookupObject: string | EntryLookupObject, - _lookupId?: string + _lookupId?: string, ): Promise { let collection: string, lookupId: string; if (typeof collectionOrLookupObject === 'string') { @@ -249,7 +249,7 @@ export function createGetEntry({ export function createGetEntries(getEntry: ReturnType) { return async function getEntries( - entries: { collection: string; id: string }[] | { collection: string; slug: string }[] + entries: { collection: string; id: string }[] | { collection: string; slug: string }[], ) { return Promise.all(entries.map((e) => getEntry(e))); }; @@ -332,8 +332,8 @@ async function render({ 'Content', propagationMod.Content, props, - slots - )}` + slots, + )}`, ); }, propagation: 'self', @@ -374,7 +374,7 @@ export function createReference({ lookupMap }: { lookupMap: ContentLookupMap }) ctx.addIssue({ code: ZodIssueCode.custom, message: `**${flattenedErrorPath}**: Reference to ${collection} invalid. Expected ${Object.keys( - entries + entries, ) .map((c) => JSON.stringify(c)) .join(' | ')}. Received ${JSON.stringify(lookupId)}.`, diff --git a/packages/astro/src/content/server-listeners.ts b/packages/astro/src/content/server-listeners.ts index 590d6f8c10..5d7868d589 100644 --- a/packages/astro/src/content/server-listeners.ts +++ b/packages/astro/src/content/server-listeners.ts @@ -29,8 +29,8 @@ export async function attachContentServerListeners({ logger.debug( 'content', `Watching ${cyan( - contentPaths.contentDir.href.replace(settings.config.root.href, '') - )} for changes` + contentPaths.contentDir.href.replace(settings.config.root.href, ''), + )} for changes`, ); const maybeTsConfigStats = await getTSConfigStatsWhenAllowJsFalse({ contentPaths, settings }); if (maybeTsConfigStats) warnAllowJsIsFalse({ ...maybeTsConfigStats, logger }); @@ -61,16 +61,16 @@ export async function attachContentServerListeners({ contentGenerator.queueEvent({ name: 'add', entry }); }); viteServer.watcher.on('addDir', (entry) => - contentGenerator.queueEvent({ name: 'addDir', entry }) + contentGenerator.queueEvent({ name: 'addDir', entry }), ); viteServer.watcher.on('change', (entry) => - contentGenerator.queueEvent({ name: 'change', entry }) + contentGenerator.queueEvent({ name: 'change', entry }), ); viteServer.watcher.on('unlink', (entry) => { contentGenerator.queueEvent({ name: 'unlink', entry }); }); viteServer.watcher.on('unlinkDir', (entry) => - contentGenerator.queueEvent({ name: 'unlinkDir', entry }) + contentGenerator.queueEvent({ name: 'unlinkDir', entry }), ); } } @@ -87,12 +87,12 @@ function warnAllowJsIsFalse({ logger.warn( 'content', `Make sure you have the ${bold('allowJs')} compiler option set to ${bold( - 'true' + 'true', )} in your ${bold(tsConfigFileName)} file to have autocompletion in your ${bold( - contentConfigFileName + contentConfigFileName, )} file. See ${underline( - cyan('https://www.typescriptlang.org/tsconfig#allowJs') - )} for more information.` + cyan('https://www.typescriptlang.org/tsconfig#allowJs'), + )} for more information.`, ); } @@ -104,7 +104,7 @@ async function getTSConfigStatsWhenAllowJsFalse({ settings: AstroSettings; }) { const isContentConfigJsFile = ['.js', '.mjs'].some((ext) => - contentPaths.config.url.pathname.endsWith(ext) + contentPaths.config.url.pathname.endsWith(ext), ); if (!isContentConfigJsFile) return; diff --git a/packages/astro/src/content/types-generator.ts b/packages/astro/src/content/types-generator.ts index 3a646154d3..ea0c3cc80e 100644 --- a/packages/astro/src/content/types-generator.ts +++ b/packages/astro/src/content/types-generator.ts @@ -112,7 +112,7 @@ export async function createContentTypesGenerator({ async function handleEvent(event: ContentEvent): Promise<{ shouldGenerateTypes: boolean }> { if (event.name === 'addDir' || event.name === 'unlinkDir') { const collection = normalizePath( - path.relative(fileURLToPath(contentPaths.contentDir), fileURLToPath(event.entry)) + path.relative(fileURLToPath(contentPaths.contentDir), fileURLToPath(event.entry)), ); const collectionKey = JSON.stringify(collection); // If directory is multiple levels deep, it is not a collection. Ignore event. @@ -137,7 +137,7 @@ export async function createContentTypesGenerator({ fileURLToPath(event.entry), contentPaths, contentEntryExts, - dataEntryExts + dataEntryExts, ); if (fileType === 'ignored') { return { shouldGenerateTypes: false }; @@ -156,9 +156,9 @@ export async function createContentTypesGenerator({ 'content', `${bold( normalizePath( - path.relative(fileURLToPath(contentPaths.contentDir), fileURLToPath(event.entry)) - ) - )} must live in a ${bold('content/...')} collection subdirectory.` + path.relative(fileURLToPath(contentPaths.contentDir), fileURLToPath(event.entry)), + ), + )} must live in a ${bold('content/...')} collection subdirectory.`, ); return { shouldGenerateTypes: false }; } @@ -406,7 +406,7 @@ async function writeContentFiles({ message: AstroErrorData.ContentCollectionTypeMismatchError.message( collectionKey, collection.type, - collectionConfig.type + collectionConfig.type, ), hint: collection.type === 'data' @@ -438,7 +438,7 @@ async function writeContentFiles({ for (const entryKey of collectionEntryKeys) { const entryMetadata = collection.entries[entryKey]; const renderType = `{ render(): Render[${JSON.stringify( - path.extname(JSON.parse(entryKey)) + path.extname(JSON.parse(entryKey)), )}] }`; const slugType = JSON.stringify(entryMetadata.slug); @@ -479,14 +479,14 @@ async function writeContentFiles({ dateStrategy: ['format:date-time', 'format:date', 'integer'], }), null, - 2 - ) + 2, + ), ); } catch (err) { // This should error gracefully and not crash the dev server logger.warn( 'content', - `An error was encountered while creating the JSON schema for the ${collectionKey} collection. Proceeding without it. Error: ${err}` + `An error was encountered while creating the JSON schema for the ${collectionKey} collection. Proceeding without it. Error: ${err}`, ); } } @@ -500,7 +500,7 @@ async function writeContentFiles({ const configPathRelativeToCacheDir = normalizeConfigPath( settings.dotAstroDir.pathname, - contentPaths.config.url.pathname + contentPaths.config.url.pathname, ); for (const contentEntryType of contentEntryTypes) { @@ -512,11 +512,11 @@ async function writeContentFiles({ typeTemplateContent = typeTemplateContent.replace('// @@DATA_ENTRY_MAP@@', dataTypesStr); typeTemplateContent = typeTemplateContent.replace( "'@@CONTENT_CONFIG_TYPE@@'", - contentConfig ? `typeof import(${configPathRelativeToCacheDir})` : 'never' + contentConfig ? `typeof import(${configPathRelativeToCacheDir})` : 'never', ); await fs.promises.writeFile( new URL(CONTENT_TYPES_FILE, settings.dotAstroDir), - typeTemplateContent + typeTemplateContent, ); } diff --git a/packages/astro/src/content/utils.ts b/packages/astro/src/content/utils.ts index a38aee0d14..ce6dc63ca8 100644 --- a/packages/astro/src/content/utils.ts +++ b/packages/astro/src/content/utils.ts @@ -76,7 +76,7 @@ export async function getEntryData( }, collectionConfig: CollectionConfig, shouldEmitFile: boolean, - pluginContext: PluginContext + pluginContext: PluginContext, ) { let data; if (collectionConfig.type === 'data') { @@ -127,7 +127,7 @@ export async function getEntryData( message: AstroErrorData.InvalidContentEntryFrontmatterError.message( entry.collection, entry.id, - parsed.error + parsed.error, ), location: { file: entry._internal.filePath, @@ -151,7 +151,7 @@ export function getDataEntryExts(settings: Pick } export function getEntryConfigByExtMap( - entryTypes: TEntryType[] + entryTypes: TEntryType[], ): Map { const map = new Map(); for (const entryType of entryTypes) { @@ -248,7 +248,7 @@ export function getDataEntryId({ const relativePath = getRelativeEntryPath(entry, collection, contentDir); const withoutFileExt = normalizePath(relativePath).replace( new RegExp(path.extname(relativePath) + '$'), - '' + '', ); return withoutFileExt; @@ -290,7 +290,7 @@ export function getEntryType( entryPath: string, paths: Pick, contentFileExts: string[], - dataFileExts: string[] + dataFileExts: string[], ): 'content' | 'data' | 'config' | 'ignored' { const { ext } = path.parse(entryPath); const fileUrl = pathToFileURL(entryPath); @@ -310,7 +310,7 @@ export function getEntryType( function hasUnderscoreBelowContentDirectoryPath( fileUrl: URL, - contentDir: ContentPaths['contentDir'] + contentDir: ContentPaths['contentDir'], ): boolean { const parts = fileUrl.pathname.replace(contentDir.pathname, '').split('/'); for (const part of parts) { @@ -324,7 +324,7 @@ function getYAMLErrorLine(rawData: string | undefined, objectKey: string) { const indexOfObjectKey = rawData.search( // Match key either at the top of the file or after a newline // Ensures matching on top-level object keys only - new RegExp(`(\n|^)${objectKey}`) + new RegExp(`(\n|^)${objectKey}`), ); if (indexOfObjectKey === -1) return 0; @@ -485,7 +485,7 @@ export type ContentPaths = { export function getContentPaths( { srcDir }: Pick, - fs: typeof fsMod = fsMod + fs: typeof fsMod = fsMod, ): ContentPaths { const configStats = search(fs, srcDir); const pkgBase = new URL('../../', import.meta.url); @@ -499,7 +499,7 @@ export function getContentPaths( } function search(fs: typeof fsMod, srcDir: URL) { const paths = ['config.mjs', 'config.js', 'config.mts', 'config.ts'].map( - (p) => new URL(`./content/${p}`, srcDir) + (p) => new URL(`./content/${p}`, srcDir), ); for (const file of paths) { if (fs.existsSync(file)) { diff --git a/packages/astro/src/content/vite-plugin-content-assets.ts b/packages/astro/src/content/vite-plugin-content-assets.ts index cba907bbf6..dd6dacc7ca 100644 --- a/packages/astro/src/content/vite-plugin-content-assets.ts +++ b/packages/astro/src/content/vite-plugin-content-assets.ts @@ -77,7 +77,7 @@ export function astroContentAssetPropagationPlugin({ : await getScriptsForURL( pathToFileURL(basePath), settings.config.root, - devModuleLoader + devModuleLoader, ); // Register files we crawled to be able to retrieve the rendered styles and scripts, @@ -127,7 +127,7 @@ export function astroContentAssetPropagationPlugin({ export function astroConfigBuildPlugin( options: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): AstroBuildPlugin { return { targets: ['server'], @@ -176,7 +176,7 @@ export function astroConfigBuildPlugin( if (entryStyles.size) { newCode = newCode.replace( JSON.stringify(STYLES_PLACEHOLDER), - JSON.stringify(Array.from(entryStyles)) + JSON.stringify(Array.from(entryStyles)), ); } else { newCode = newCode.replace(JSON.stringify(STYLES_PLACEHOLDER), '[]'); @@ -184,7 +184,7 @@ export function astroConfigBuildPlugin( if (entryLinks.size) { newCode = newCode.replace( JSON.stringify(LINKS_PLACEHOLDER), - JSON.stringify(Array.from(entryLinks).map(prependBase)) + JSON.stringify(Array.from(entryLinks).map(prependBase)), ); } else { newCode = newCode.replace(JSON.stringify(LINKS_PLACEHOLDER), '[]'); @@ -210,8 +210,8 @@ export function astroConfigBuildPlugin( type: 'module', }, children: '', - })) - ) + })), + ), ); } else { newCode = newCode.replace(JSON.stringify(SCRIPTS_PLACEHOLDER), '[]'); diff --git a/packages/astro/src/content/vite-plugin-content-imports.ts b/packages/astro/src/content/vite-plugin-content-imports.ts index 91f411f075..de642329a3 100644 --- a/packages/astro/src/content/vite-plugin-content-imports.ts +++ b/packages/astro/src/content/vite-plugin-content-imports.ts @@ -39,7 +39,7 @@ import { function getContentRendererByViteId( viteId: string, - settings: Pick + settings: Pick, ): ContentEntryType['getRenderModule'] | undefined { let ext = viteId.split('.').pop(); if (!ext) return undefined; @@ -215,7 +215,7 @@ type GetEntryModuleParams = }; async function getContentEntryModule( - params: GetEntryModuleParams + params: GetEntryModuleParams, ): Promise { const { fileId, contentDir, pluginContext } = params; const { collectionConfig, entryConfig, entry, rawContents, collection } = @@ -245,7 +245,7 @@ async function getContentEntryModule( { id, collection, _internal, unvalidatedData }, collectionConfig, params.shouldEmitFile, - pluginContext + pluginContext, ) : unvalidatedData; @@ -262,7 +262,7 @@ async function getContentEntryModule( } async function getDataEntryModule( - params: GetEntryModuleParams + params: GetEntryModuleParams, ): Promise { const { fileId, contentDir, pluginContext } = params; const { collectionConfig, entryConfig, entry, rawContents, collection } = @@ -280,7 +280,7 @@ async function getDataEntryModule( { id, collection, _internal, unvalidatedData }, collectionConfig, params.shouldEmitFile, - pluginContext + pluginContext, ) : unvalidatedData; @@ -320,7 +320,7 @@ async function getEntryModuleBaseInfo { if (!headers) { return undefined; diff --git a/packages/astro/src/core/app/index.ts b/packages/astro/src/core/app/index.ts index 42027098f3..d19a4da7d3 100644 --- a/packages/astro/src/core/app/index.ts +++ b/packages/astro/src/core/app/index.ts @@ -95,7 +95,7 @@ export class App { this.#pipeline = this.#createPipeline(this.#manifestData, streaming); this.#adapterLogger = new AstroIntegrationLogger( this.#logger.options, - this.#manifest.adapterName + this.#manifest.adapterName, ); } @@ -114,7 +114,7 @@ export class App { if (this.#manifest.checkOrigin) { this.#manifest.middleware = sequence( createOriginCheckMiddleware(), - this.#manifest.middleware + this.#manifest.middleware, ); } @@ -209,7 +209,7 @@ export class App { let locale; const hostAsUrl = new URL(`${protocol}//${host}`); for (const [domainKey, localeValue] of Object.entries( - this.#manifest.i18n.domainLookupTable + this.#manifest.i18n.domainLookupTable, )) { // This operation should be safe because we force the protocol via zod inside the configuration // If not, then it means that the manifest was tampered @@ -226,7 +226,7 @@ export class App { if (locale) { pathname = prependForwardSlash( - joinPaths(normalizeTheLocale(locale), this.removeBase(url.pathname)) + joinPaths(normalizeTheLocale(locale), this.removeBase(url.pathname)), ); if (url.pathname.endsWith('/')) { pathname = appendForwardSlash(pathname); @@ -235,7 +235,7 @@ export class App { } catch (e: any) { this.#logger.error( 'router', - `Astro tried to parse ${protocol}//${host} as an URL, but it threw a parsing error. Check the X-Forwarded-Host and X-Forwarded-Proto headers.` + `Astro tried to parse ${protocol}//${host} as an URL, but it threw a parsing error. Check the X-Forwarded-Host and X-Forwarded-Proto headers.`, ); this.#logger.error('router', `Error: ${e}`); } @@ -253,7 +253,7 @@ export class App { async render( request: Request, routeDataOrOptions?: RouteData | RenderOptions, - maybeLocals?: object + maybeLocals?: object, ): Promise { let routeData: RouteData | undefined; let locals: object | undefined; @@ -290,7 +290,7 @@ export class App { this.#logger.debug( 'router', 'The adapter ' + this.#manifest.adapterName + ' provided a custom RouteData for ', - request.url + request.url, ); this.#logger.debug('router', 'RouteData:\n' + routeData); } @@ -370,7 +370,7 @@ export class App { if (this.#renderOptionsDeprecationWarningShown) return; this.#logger.warn( 'deprecated', - `The adapter ${this.#manifest.adapterName} is using a deprecated signature of the 'app.render()' method. From Astro 4.0, locals and routeData are provided as properties on an optional object to this method. Using the old signature will cause an error in Astro 5.0. See https://github.com/withastro/astro/pull/9199 for more information.` + `The adapter ${this.#manifest.adapterName} is using a deprecated signature of the 'app.render()' method. From Astro 4.0, locals and routeData are provided as properties on an optional object to this method. Using the old signature will cause an error in Astro 5.0. See https://github.com/withastro/astro/pull/9199 for more information.`, ); this.#renderOptionsDeprecationWarningShown = true; } @@ -404,7 +404,7 @@ export class App { response: originalResponse, skipMiddleware = false, error, - }: RenderErrorOptions + }: RenderErrorOptions, ): Promise { const errorRoutePath = `/${status}${this.#manifest.trailingSlash === 'always' ? '/' : ''}`; const errorRouteData = matchRoute(errorRoutePath, this.#manifestData); @@ -414,7 +414,7 @@ export class App { const maybeDotHtml = errorRouteData.route.endsWith(`/${status}`) ? '.html' : ''; const statusURL = new URL( `${this.#baseWithoutTrailingSlash}/${status}${maybeDotHtml}`, - url + url, ); const response = await fetch(statusURL.toString()); @@ -459,7 +459,7 @@ export class App { #mergeResponses( newResponse: Response, originalResponse?: Response, - override?: { status: 404 | 500 } + override?: { status: 404 | 500 }, ) { if (!originalResponse) { if (override !== undefined) { diff --git a/packages/astro/src/core/app/node.ts b/packages/astro/src/core/app/node.ts index 537c7f5e77..f9afa6189d 100644 --- a/packages/astro/src/core/app/node.ts +++ b/packages/astro/src/core/app/node.ts @@ -37,7 +37,7 @@ export class NodeApp extends App { render( req: NodeRequest | Request, routeDataOrOptions?: RouteData | RenderOptions, - maybeLocals?: object + maybeLocals?: object, ) { if (!(req instanceof Request)) { req = NodeApp.createRequest(req); @@ -120,7 +120,7 @@ export class NodeApp extends App { // eslint-disable-next-line no-console console.error( `There was an uncaught error in the middle of the stream while rendering ${destination.req.url}.`, - err + err, ); }); }); diff --git a/packages/astro/src/core/app/pipeline.ts b/packages/astro/src/core/app/pipeline.ts index 64c2fdcb86..b784ba9164 100644 --- a/packages/astro/src/core/app/pipeline.ts +++ b/packages/astro/src/core/app/pipeline.ts @@ -36,7 +36,7 @@ export class AppPipeline extends Pipeline { | 'serverLike' | 'streaming' | 'defaultRoutes' - > + >, ) { const pipeline = new AppPipeline( logger, @@ -55,7 +55,7 @@ export class AppPipeline extends Pipeline { undefined, undefined, false, - defaultRoutes + defaultRoutes, ); pipeline.#manifestData = manifestData; return pipeline; @@ -93,7 +93,7 @@ export class AppPipeline extends Pipeline { async tryRewrite( payload: RewritePayload, request: Request, - _sourceRoute: RouteData + _sourceRoute: RouteData, ): Promise<[RouteData, ComponentInstance, URL]> { const [foundRoute, finalUrl] = findRouteToRewrite({ payload, @@ -125,7 +125,7 @@ export class AppPipeline extends Pipeline { const importComponentInstance = this.manifest.pageMap.get(route.component); if (!importComponentInstance) { throw new Error( - `Unexpectedly unable to find a component instance for route ${route.route}` + `Unexpectedly unable to find a component instance for route ${route.route}`, ); } return await importComponentInstance(); @@ -133,7 +133,7 @@ export class AppPipeline extends Pipeline { return this.manifest.pageModule; } throw new Error( - "Astro couldn't find the correct page to render, probably because it wasn't correctly mapped for SSR usage. This is an internal error, please file an issue." + "Astro couldn't find the correct page to render, probably because it wasn't correctly mapped for SSR usage. This is an internal error, please file an issue.", ); } } diff --git a/packages/astro/src/core/base-pipeline.ts b/packages/astro/src/core/base-pipeline.ts index b3884b841b..01e18bfa03 100644 --- a/packages/astro/src/core/base-pipeline.ts +++ b/packages/astro/src/core/base-pipeline.ts @@ -58,13 +58,13 @@ export abstract class Pipeline { * Array of built-in, internal, routes. * Used to find the route module */ - readonly defaultRoutes = createDefaultRoutes(manifest) + readonly defaultRoutes = createDefaultRoutes(manifest), ) { this.internalMiddleware = []; // We do use our middleware only if the user isn't using the manual setup if (i18n?.strategy !== 'manual') { this.internalMiddleware.push( - createI18nMiddleware(i18n, manifest.base, manifest.trailingSlash, manifest.buildFormat) + createI18nMiddleware(i18n, manifest.base, manifest.trailingSlash, manifest.buildFormat), ); } // In SSR, getSecret should fail by default. Setting it here will run before the @@ -94,7 +94,7 @@ export abstract class Pipeline { abstract tryRewrite( rewritePayload: RewritePayload, request: Request, - sourceRoute: RouteData + sourceRoute: RouteData, ): Promise<[RouteData, ComponentInstance, URL]>; /** diff --git a/packages/astro/src/core/build/add-rollup-input.ts b/packages/astro/src/core/build/add-rollup-input.ts index f45aef731c..073fb55823 100644 --- a/packages/astro/src/core/build/add-rollup-input.ts +++ b/packages/astro/src/core/build/add-rollup-input.ts @@ -10,7 +10,7 @@ function fromEntries(entries: [string, V][]) { export function addRollupInput( inputOptions: Rollup.InputOptions, - newInputs: string[] + newInputs: string[], ): Rollup.InputOptions { // Add input module ids to existing input option, whether it's a string, array or object // this way you can use multiple html plugins all adding their own inputs diff --git a/packages/astro/src/core/build/common.ts b/packages/astro/src/core/build/common.ts index badfa561e5..a479aed390 100644 --- a/packages/astro/src/core/build/common.ts +++ b/packages/astro/src/core/build/common.ts @@ -17,7 +17,7 @@ function getOutRoot(astroConfig: AstroConfig): URL { export function getOutFolder( astroConfig: AstroConfig, pathname: string, - routeData: RouteData + routeData: RouteData, ): URL { const outRoot = getOutRoot(astroConfig); const routeType = routeData.type; @@ -59,7 +59,7 @@ export function getOutFile( astroConfig: AstroConfig, outFolder: URL, pathname: string, - routeData: RouteData + routeData: RouteData, ): URL { const routeType = routeData.type; switch (routeType) { diff --git a/packages/astro/src/core/build/css-asset-name.ts b/packages/astro/src/core/build/css-asset-name.ts index 1876c08771..fbee7f2e20 100644 --- a/packages/astro/src/core/build/css-asset-name.ts +++ b/packages/astro/src/core/build/css-asset-name.ts @@ -21,7 +21,7 @@ export function shortHashedName(settings: AstroSettings) { return createNameHash( getFirstParentId(parents), parents.map((page) => page.id), - settings + settings, ); }; } @@ -29,7 +29,7 @@ export function shortHashedName(settings: AstroSettings) { export function createNameHash( baseId: string | undefined, hashIds: string[], - settings: AstroSettings + settings: AstroSettings, ): string { const baseName = baseId ? prettifyBaseName(npath.parse(baseId).name) : 'index'; const hash = crypto.createHash('sha256'); diff --git a/packages/astro/src/core/build/generate.ts b/packages/astro/src/core/build/generate.ts index e3fca61206..5897ba7e4d 100644 --- a/packages/astro/src/core/build/generate.ts +++ b/packages/astro/src/core/build/generate.ts @@ -69,14 +69,14 @@ export async function generatePages(options: StaticBuildOptions, internals: Buil // middleware.mjs is not emitted if there is no user middleware // in which case the import fails with ERR_MODULE_NOT_FOUND, and we fall back to a no-op middleware middleware = await import(new URL('middleware.mjs', baseDirectory).toString()).then( - (mod) => mod.onRequest + (mod) => mod.onRequest, ); } catch {} manifest = createBuildManifest( options.settings, internals, renderers.renderers as SSRLoadedRenderer[], - middleware + middleware, ); } const pipeline = BuildPipeline.create({ internals, manifest, options }); @@ -118,7 +118,7 @@ export async function generatePages(options: StaticBuildOptions, internals: Buil } else { const ssrEntryURLPage = createEntryURL(filePath, outFolder); throw new Error( - `Unable to find the manifest for the module ${ssrEntryURLPage.toString()}. This is unexpected and likely a bug in Astro, please report.` + `Unable to find the manifest for the module ${ssrEntryURLPage.toString()}. This is unexpected and likely a bug in Astro, please report.`, ); } } else { @@ -135,7 +135,7 @@ export async function generatePages(options: StaticBuildOptions, internals: Buil } logger.info( null, - green(`✓ Completed in ${getTimeStat(generatePagesTimer, performance.now())}.\n`) + green(`✓ Completed in ${getTimeStat(generatePagesTimer, performance.now())}.\n`), ); const staticImageList = getStaticImageList(); @@ -170,7 +170,7 @@ async function generatePage( pageData: PageBuildData, ssrEntry: SinglePageBuiltModule, builtPaths: Set, - pipeline: BuildPipeline + pipeline: BuildPipeline, ) { // prepare information we need const { config, logger } = pipeline; @@ -186,7 +186,7 @@ async function generatePage( const scripts = pageData.hoistedScript ?? null; if (!pageModulePromise) { throw new Error( - `Unable to find the module for ${pageData.component}. This is unexpected and likely a bug in Astro, please report.` + `Unable to find the module for ${pageData.component}. This is unexpected and likely a bug in Astro, please report.`, ); } const pageModule = await pageModulePromise(); @@ -241,7 +241,7 @@ async function getPathsForRoute( route: RouteData, mod: ComponentInstance, pipeline: BuildPipeline, - builtPaths: Set + builtPaths: Set, ): Promise> { const { logger, options, routeCache, serverLike } = pipeline; let paths: Array = []; @@ -263,7 +263,7 @@ async function getPathsForRoute( const label = staticPaths.length === 1 ? 'page' : 'pages'; logger.debug( 'build', - `├── ${bold(green('√'))} ${route.component} → ${magenta(`[${staticPaths.length} ${label}]`)}` + `├── ${bold(green('√'))} ${route.component} → ${magenta(`[${staticPaths.length} ${label}]`)}`, ); paths = staticPaths @@ -304,7 +304,7 @@ async function getPathsForRoute( function getInvalidRouteSegmentError( e: TypeError, route: RouteData, - staticPath: GetStaticPathsItem + staticPath: GetStaticPathsItem, ): AstroError { const invalidParam = /^Expected "([^"]+)"/.exec(e.message)?.[1]; const received = invalidParam ? staticPath.params[invalidParam] : undefined; @@ -312,7 +312,7 @@ function getInvalidRouteSegmentError( 'Learn about dynamic routes at https://docs.astro.build/en/core-concepts/routing/#dynamic-routes'; if (invalidParam && typeof received === 'string') { const matchingSegment = route.segments.find( - (segment) => segment[0]?.content === invalidParam + (segment) => segment[0]?.content === invalidParam, )?.[0]; const mightBeMissingSpread = matchingSegment?.dynamic && !matchingSegment?.spread; if (mightBeMissingSpread) { @@ -325,7 +325,7 @@ function getInvalidRouteSegmentError( ? AstroErrorData.InvalidDynamicRoute.message( route.route, JSON.stringify(invalidParam), - JSON.stringify(received) + JSON.stringify(received), ) : `Generated path for ${route.route} is invalid.`, hint, @@ -355,7 +355,7 @@ function getUrlForPath( origin: string, format: AstroConfig['build']['format'], trailingSlash: AstroConfig['trailingSlash'], - routeType: RouteType + routeType: RouteType, ): URL { /** * Examples: @@ -402,7 +402,7 @@ async function generatePath( pathname: string, pipeline: BuildPipeline, gopts: GeneratePathOptions, - route: RouteData + route: RouteData, ) { const { mod } = gopts; const { config, logger, options } = pipeline; @@ -432,7 +432,7 @@ async function generatePath( options.origin, config.build.format, config.trailingSlash, - route.type + route.type, ); const request = createRequest({ @@ -520,7 +520,7 @@ function createBuildManifest( settings: AstroSettings, internals: BuildInternals, renderers: SSRLoadedRenderer[], - middleware: MiddlewareHandler + middleware: MiddlewareHandler, ): SSRManifest { let i18nManifest: SSRManifestI18n | undefined = undefined; if (settings.config.i18n) { diff --git a/packages/astro/src/core/build/graph.ts b/packages/astro/src/core/build/graph.ts index d4c4089f33..e017bcb0f7 100644 --- a/packages/astro/src/core/build/graph.ts +++ b/packages/astro/src/core/build/graph.ts @@ -17,7 +17,7 @@ export function getParentExtendedModuleInfos( order = 0, childId = '', seen = new Set(), - accumulated: ExtendedModuleInfo[] = [] + accumulated: ExtendedModuleInfo[] = [], ): ExtendedModuleInfo[] { seen.add(id); @@ -54,7 +54,7 @@ export function getParentModuleInfos( ctx: { getModuleInfo: GetModuleInfo }, until?: (importer: string) => boolean, seen = new Set(), - accumulated: ModuleInfo[] = [] + accumulated: ModuleInfo[] = [], ): ModuleInfo[] { seen.add(id); @@ -88,7 +88,7 @@ export function moduleIsTopLevelPage(info: ModuleInfo): boolean { // This could be a .astro page, a .markdown or a .md (or really any file extension for markdown files) page. export function getTopLevelPageModuleInfos( id: string, - ctx: { getModuleInfo: GetModuleInfo } + ctx: { getModuleInfo: GetModuleInfo }, ): ModuleInfo[] { return getParentModuleInfos(id, ctx).filter(moduleIsTopLevelPage); } diff --git a/packages/astro/src/core/build/index.ts b/packages/astro/src/core/build/index.ts index de8e48b9d2..8df72d8b22 100644 --- a/packages/astro/src/core/build/index.ts +++ b/packages/astro/src/core/build/index.ts @@ -61,7 +61,7 @@ export interface BuildOptions { */ export default async function build( inlineConfig: AstroInlineConfig, - options: BuildOptions = {} + options: BuildOptions = {}, ): Promise { ensureProcessNodeEnv('production'); applyPolyfill(); @@ -140,7 +140,13 @@ class AstroBuilder { middlewareMode: true, }, }, - { settings: this.settings, logger: this.logger, mode: 'build', command: 'build', sync: false } + { + settings: this.settings, + logger: this.logger, + mode: 'build', + command: 'build', + sync: false, + }, ); await runHookConfigDone({ settings: this.settings, logger: logger }); @@ -182,7 +188,7 @@ class AstroBuilder { this.timer.buildStart = performance.now(); this.logger.info( 'build', - green(`✓ Completed in ${getTimeStat(this.timer.init, performance.now())}.`) + green(`✓ Completed in ${getTimeStat(this.timer.init, performance.now())}.`), ); const opts: StaticBuildOptions = { @@ -221,7 +227,7 @@ class AstroBuilder { .concat( this.settings.config.experimental.serverIslands ? [getServerIslandRouteData(this.settings.config)] - : [] + : [], ), logging: this.logger, cacheManifest: internals.cacheManifestUsed, @@ -256,7 +262,7 @@ class AstroBuilder { // outDir gets blown away so it can't be the root. if (config.outDir.toString() === config.root.toString()) { throw new Error( - `the outDir cannot be the root folder. Please build to a folder such as dist.` + `the outDir cannot be the root folder. Please build to a folder such as dist.`, ); } } diff --git a/packages/astro/src/core/build/internal.ts b/packages/astro/src/core/build/internal.ts index efab9baca2..5c28a4d40e 100644 --- a/packages/astro/src/core/build/internal.ts +++ b/packages/astro/src/core/build/internal.ts @@ -150,7 +150,7 @@ export function trackPageData( component: string, pageData: PageBuildData, componentModuleId: string, - componentURL: URL + componentURL: URL, ): void { pageData.moduleSpecifier = componentModuleId; internals.pagesByKeys.set(pageData.key, pageData); @@ -163,7 +163,7 @@ export function trackPageData( export function trackClientOnlyPageDatas( internals: BuildInternals, pageData: PageBuildData, - clientOnlys: string[] + clientOnlys: string[], ) { for (const clientOnlyComponent of clientOnlys) { let pageDataSet: Set; @@ -184,7 +184,7 @@ export function trackClientOnlyPageDatas( export function trackScriptPageDatas( internals: BuildInternals, pageData: PageBuildData, - scriptIds: string[] + scriptIds: string[], ) { for (const scriptId of scriptIds) { let pageDataSet: Set; @@ -200,7 +200,7 @@ export function trackScriptPageDatas( export function* getPageDatasByClientOnlyID( internals: BuildInternals, - viteid: ViteID + viteid: ViteID, ): Generator { const pagesByClientOnly = internals.pagesByClientOnly; if (pagesByClientOnly.size) { @@ -238,7 +238,7 @@ export function* getPageDatasByClientOnlyID( export function getPageData( internals: BuildInternals, route: string, - component: string + component: string, ): PageBuildData | undefined { let pageData = internals.pagesByKeys.get(makePageDataKey(route, component)); if (pageData) { @@ -271,7 +271,7 @@ function getPagesDatasByComponent(internals: BuildInternals, component: string): * @param pagesByKeys A map of all page data by their internal key */ export function getPageDatasWithPublicKey( - pagesByKeys: Map + pagesByKeys: Map, ): Map { // Create a map to store the pages with the public key, mimicking internal.pagesByKeys const pagesWithPublicKey = new Map(); @@ -303,7 +303,7 @@ export function getPageDatasWithPublicKey( export function getPageDataByViteID( internals: BuildInternals, - viteid: ViteID + viteid: ViteID, ): PageBuildData | undefined { if (internals.pagesByViteID.has(viteid)) { return internals.pagesByViteID.get(viteid); @@ -358,7 +358,7 @@ export function cssOrder(a: OrderInfo, b: OrderInfo) { export function mergeInlineCss( acc: Array, - current: StylesheetAsset + current: StylesheetAsset, ): Array { const lastAdded = acc.at(acc.length - 1); const lastWasInline = lastAdded?.type === 'inline'; @@ -379,7 +379,7 @@ export function mergeInlineCss( */ export function getPageDatasByHoistedScriptId( internals: BuildInternals, - id: string + id: string, ): PageBuildData[] { const set = internals.hoistedScriptIdToPagesMap.get(id); const pageDatas: PageBuildData[] = []; diff --git a/packages/astro/src/core/build/page-data.ts b/packages/astro/src/core/build/page-data.ts index b6cc03002c..210b31a0e5 100644 --- a/packages/astro/src/core/build/page-data.ts +++ b/packages/astro/src/core/build/page-data.ts @@ -46,7 +46,7 @@ export function collectPagesData(opts: CollectPagesDataOptions): CollectPagesDat const html = `${route.pathname}`.replace(/\/?$/, '/index.html'); debug( 'build', - `├── ${colors.bold(colors.green('✔'))} ${route.component} → ${colors.yellow(html)}` + `├── ${colors.bold(colors.green('✔'))} ${route.component} → ${colors.yellow(html)}`, ); } else { debug('build', `├── ${colors.bold(colors.green('✔'))} ${route.component}`); diff --git a/packages/astro/src/core/build/pipeline.ts b/packages/astro/src/core/build/pipeline.ts index 7ef94acd9a..4e0d94c57e 100644 --- a/packages/astro/src/core/build/pipeline.ts +++ b/packages/astro/src/core/build/pipeline.ts @@ -54,7 +54,7 @@ export class BuildPipeline extends Pipeline { readonly options: StaticBuildOptions, readonly config = options.settings.config, readonly settings = options.settings, - readonly defaultRoutes = createDefaultRoutes(manifest) + readonly defaultRoutes = createDefaultRoutes(manifest), ) { const resolveCache = new Map(); @@ -87,7 +87,7 @@ export class BuildPipeline extends Pipeline { manifest.renderers, resolve, serverLike, - streaming + streaming, ); } @@ -114,18 +114,18 @@ export class BuildPipeline extends Pipeline { */ static async retrieveManifest( staticBuildOptions: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): Promise { const config = staticBuildOptions.settings.config; const baseDirectory = getOutputDirectory(config); const manifestEntryUrl = new URL( `${internals.manifestFileName}?time=${Date.now()}`, - baseDirectory + baseDirectory, ); const { manifest } = await import(manifestEntryUrl.toString()); if (!manifest) { throw new Error( - "Astro couldn't find the emitted manifest. This is an internal error, please file an issue." + "Astro couldn't find the emitted manifest. This is an internal error, please file an issue.", ); } @@ -140,7 +140,7 @@ export class BuildPipeline extends Pipeline { if (!renderers) { throw new Error( - "Astro couldn't find the emitted renderers. This is an internal error, please file an issue." + "Astro couldn't find the emitted renderers. This is an internal error, please file an issue.", ); } return { @@ -161,7 +161,7 @@ export class BuildPipeline extends Pipeline { const scripts = createModuleScriptsSet( pageBuildData?.hoistedScript ? [pageBuildData.hoistedScript] : [], base, - assetsPrefix + assetsPrefix, ); const sortedCssAssets = pageBuildData?.styles .sort(cssOrder) @@ -216,8 +216,8 @@ export class BuildPipeline extends Pipeline { ...getPagesFromVirtualModulePageName( this.internals, ASTRO_PAGE_RESOLVED_MODULE_ID, - virtualModulePageName - ) + virtualModulePageName, + ), ); } if (virtualModulePageName.includes(RESOLVED_SPLIT_MODULE_ID)) { @@ -225,8 +225,8 @@ export class BuildPipeline extends Pipeline { ...getPagesFromVirtualModulePageName( this.internals, RESOLVED_SPLIT_MODULE_ID, - virtualModulePageName - ) + virtualModulePageName, + ), ); } for (const pageData of pageDatas) { @@ -288,7 +288,7 @@ export class BuildPipeline extends Pipeline { async tryRewrite( payload: RewritePayload, request: Request, - _sourceRoute: RouteData + _sourceRoute: RouteData, ): Promise<[RouteData, ComponentInstance, URL]> { const [foundRoute, finalUrl] = findRouteToRewrite({ payload, @@ -324,7 +324,7 @@ export class BuildPipeline extends Pipeline { async #getEntryForFallbackRoute( route: RouteData, internals: BuildInternals, - outFolder: URL + outFolder: URL, ): Promise { if (route.type !== 'fallback') { throw new Error(`Expected a redirect route.`); @@ -344,7 +344,7 @@ export class BuildPipeline extends Pipeline { async #getEntryForRedirectRoute( route: RouteData, internals: BuildInternals, - outFolder: URL + outFolder: URL, ): Promise { if (route.type !== 'redirect') { throw new Error(`Expected a redirect route.`); diff --git a/packages/astro/src/core/build/plugins/README.md b/packages/astro/src/core/build/plugins/README.md index 410b81da67..2949233e66 100644 --- a/packages/astro/src/core/build/plugins/README.md +++ b/packages/astro/src/core/build/plugins/README.md @@ -22,7 +22,7 @@ The emitted file has content similar to: const renderers = [ Object.assign( { name: 'astro:jsx', serverEntrypoint: 'astro/jsx/server.js', jsxImportSource: 'astro' }, - { ssr: server_default } + { ssr: server_default }, ), ]; diff --git a/packages/astro/src/core/build/plugins/plugin-analyzer.ts b/packages/astro/src/core/build/plugins/plugin-analyzer.ts index b0ba0e74d5..b007e318f5 100644 --- a/packages/astro/src/core/build/plugins/plugin-analyzer.ts +++ b/packages/astro/src/core/build/plugins/plugin-analyzer.ts @@ -28,7 +28,7 @@ function isPropagatedAsset(id: string) { export function vitePluginAnalyzer( options: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): VitePlugin { function hoistedScriptScanner() { const uniqueHoistedIds = new Map(); @@ -43,7 +43,7 @@ export function vitePluginAnalyzer( async scan( this: PluginContext, scripts: AstroPluginMetadata['astro']['scripts'], - from: string + from: string, ) { const hoistedScripts = new Set(); for (let i = 0; i < scripts.length; i++) { @@ -178,7 +178,7 @@ export function vitePluginAnalyzer( // `discoveredScripts` here, which will eventually be passed as inputs of the client build. if (options.settings.config.experimental.directRenderScript && astro.scripts.length) { const scriptIds = astro.scripts.map( - (_, i) => `${id.replace('/@fs', '')}?astro&type=script&index=${i}&lang.ts` + (_, i) => `${id.replace('/@fs', '')}?astro&type=script&index=${i}&lang.ts`, ); // Assign as entrypoints for the client bundle @@ -204,7 +204,7 @@ export function vitePluginAnalyzer( export function pluginAnalyzer( options: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): AstroBuildPlugin { return { targets: ['server'], diff --git a/packages/astro/src/core/build/plugins/plugin-content.ts b/packages/astro/src/core/build/plugins/plugin-content.ts index 68ff981a0e..9c6d5add0b 100644 --- a/packages/astro/src/core/build/plugins/plugin-content.ts +++ b/packages/astro/src/core/build/plugins/plugin-content.ts @@ -80,7 +80,7 @@ function vitePluginContent( opts: StaticBuildOptions, lookupMap: ContentLookupMap, internals: BuildInternals, - cachedBuildOutput: Array<{ cached: URL; dist: URL }> + cachedBuildOutput: Array<{ cached: URL; dist: URL }>, ): VitePlugin { const { config } = opts.settings; const distContentRoot = getContentRoot(config); @@ -184,7 +184,7 @@ function vitePluginContent( ) { const [srcRelativePath] = id.replace(rootPath, '/').split('?'); const resultId = encodeName( - `${removeLeadingForwardSlash(removeFileExtension(srcRelativePath))}.render.mjs` + `${removeLeadingForwardSlash(removeFileExtension(srcRelativePath))}.render.mjs`, ); return resultId; } @@ -192,7 +192,7 @@ function vitePluginContent( const collectionEntry = findEntryFromSrcRelativePath( lookupMap, srcRelativePath, - entryCache + entryCache, ); if (collectionEntry) { let suffix = '.mjs'; @@ -201,7 +201,7 @@ function vitePluginContent( } id = removeLeadingForwardSlash( - removeFileExtension(encodeName(id.replace(srcPath, '/'))) + removeFileExtension(encodeName(id.replace(srcPath, '/'))), ) + suffix; return id; } @@ -284,7 +284,7 @@ function vitePluginContent( function findEntryFromSrcRelativePath( lookupMap: ContentLookupMap, srcRelativePath: string, - entryCache: Map + entryCache: Map, ) { let value = entryCache.get(srcRelativePath); if (value) return value; @@ -308,7 +308,7 @@ interface ContentEntries { function getEntriesFromManifests( oldManifest: ContentManifest, - newManifest: ContentManifest + newManifest: ContentManifest, ): ContentEntries { const { entries: oldEntries } = oldManifest; const { entries: newEntries } = newManifest; @@ -320,7 +320,7 @@ function getEntriesFromManifests( return entries; } const oldEntryHashMap = new Map( - oldEntries.map(([key, hash]) => [hash, key]) + oldEntries.map(([key, hash]) => [hash, key]), ); for (const [entry, hash] of newEntryMap) { @@ -367,7 +367,7 @@ function manifestState(oldManifest: ContentManifest, newManifest: ContentManifes async function generateContentManifest( opts: StaticBuildOptions, - lookupMap: ContentLookupMap + lookupMap: ContentLookupMap, ): Promise { let manifest = createContentManifest(); manifest.version = CONTENT_MANIFEST_VERSION; @@ -382,7 +382,7 @@ async function generateContentManifest( limit(async () => { const data = await fsMod.promises.readFile(fileURL, { encoding: 'utf8' }); manifest.entries.push([key, checksum(data, fileURL.toString())]); - }) + }), ); } } @@ -480,7 +480,7 @@ export async function copyContentToCache(opts: StaticBuildOptions) { export function pluginContent( opts: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): AstroBuildPlugin { const { cacheDir, outDir } = opts.settings.config; diff --git a/packages/astro/src/core/build/plugins/plugin-css.ts b/packages/astro/src/core/build/plugins/plugin-css.ts index 2693648426..0ebc7e618d 100644 --- a/packages/astro/src/core/build/plugins/plugin-css.ts +++ b/packages/astro/src/core/build/plugins/plugin-css.ts @@ -30,7 +30,7 @@ interface PluginOptions { export function pluginCSS( options: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): AstroBuildPlugin { return { targets: ['client', 'server'], @@ -206,7 +206,7 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] { // Ref: https://github.com/vitejs/vite/blob/b2c0ee04d4db4a0ef5a084c50f49782c5f88587c/packages/vite/src/node/plugins/html.ts#L690-L705 if (resolvedConfig.build.cssCodeSplit) return; const cssChunk = Object.values(bundle).find( - (chunk) => chunk.type === 'asset' && chunk.name === 'style.css' + (chunk) => chunk.type === 'asset' && chunk.name === 'style.css', ); if (cssChunk === undefined) return; for (const pageData of internals.pagesByKeys.values()) { @@ -293,7 +293,7 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] { function* getParentClientOnlys( id: string, ctx: { getModuleInfo: GetModuleInfo }, - internals: BuildInternals + internals: BuildInternals, ): Generator { for (const info of getParentModuleInfos(id, ctx)) { yield* getPageDatasByClientOnlyID(internals, info.id); @@ -310,7 +310,7 @@ function appendCSSToPage( meta: ViteMetadata, pagesToCss: Record>, depth: number, - order: number + order: number, ) { for (const importedCssImport of meta.importedCss) { // CSS is prioritized based on depth. Shared CSS has a higher depth due to being imported by multiple pages. @@ -341,7 +341,7 @@ function appendCSSToPage( */ function isCssScopeToRendered( cssScopeTo: Record, - chunks: Rollup.RenderedChunk[] + chunks: Rollup.RenderedChunk[], ) { for (const moduleId in cssScopeTo) { const exports = cssScopeTo[moduleId]; diff --git a/packages/astro/src/core/build/plugins/plugin-hoisted-scripts.ts b/packages/astro/src/core/build/plugins/plugin-hoisted-scripts.ts index 7d31aed633..7c37849093 100644 --- a/packages/astro/src/core/build/plugins/plugin-hoisted-scripts.ts +++ b/packages/astro/src/core/build/plugins/plugin-hoisted-scripts.ts @@ -13,7 +13,7 @@ function virtualHoistedEntry(id: string) { export function vitePluginHoistedScripts( settings: AstroSettings, - internals: BuildInternals + internals: BuildInternals, ): VitePlugin { let assetsInlineLimit: NonNullable; @@ -104,7 +104,7 @@ export function vitePluginHoistedScripts( export function pluginHoistedScripts( options: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): AstroBuildPlugin { return { targets: ['client'], diff --git a/packages/astro/src/core/build/plugins/plugin-internals.ts b/packages/astro/src/core/build/plugins/plugin-internals.ts index 3f5467aae8..01d5245151 100644 --- a/packages/astro/src/core/build/plugins/plugin-internals.ts +++ b/packages/astro/src/core/build/plugins/plugin-internals.ts @@ -36,7 +36,7 @@ export function vitePluginInternals(input: Set, internals: BuildInternal mapping.set(result.id, new Set([specifier])); } } - }) + }), ); } await Promise.all(promises); diff --git a/packages/astro/src/core/build/plugins/plugin-manifest.ts b/packages/astro/src/core/build/plugins/plugin-manifest.ts index 491b9187ac..bb1add5b45 100644 --- a/packages/astro/src/core/build/plugins/plugin-manifest.ts +++ b/packages/astro/src/core/build/plugins/plugin-manifest.ts @@ -78,7 +78,7 @@ function vitePluginManifest(_options: StaticBuildOptions, internals: BuildIntern export function pluginManifest( options: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): AstroBuildPlugin { return { targets: ['server'], @@ -115,7 +115,7 @@ export function pluginManifest( async function createManifest( buildOpts: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): Promise { if (!internals.manifestEntryChunk) { throw new Error(`Did not generate an entry chunk for SSR`); @@ -125,7 +125,7 @@ async function createManifest( const clientStatics = new Set( await glob('**/*', { cwd: fileURLToPath(buildOpts.settings.config.build.client), - }) + }), ); for (const file of clientStatics) { internals.staticFiles.add(file); @@ -149,7 +149,7 @@ function injectManifest(manifest: SerializedSSRManifest, chunk: Readonly script.stage === 'page')) { diff --git a/packages/astro/src/core/build/plugins/plugin-middleware.ts b/packages/astro/src/core/build/plugins/plugin-middleware.ts index 701422a5b7..6b982053f6 100644 --- a/packages/astro/src/core/build/plugins/plugin-middleware.ts +++ b/packages/astro/src/core/build/plugins/plugin-middleware.ts @@ -6,7 +6,7 @@ export { MIDDLEWARE_MODULE_ID } from '../../middleware/vite-plugin.js'; export function pluginMiddleware( opts: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): AstroBuildPlugin { return { targets: ['server'], diff --git a/packages/astro/src/core/build/plugins/plugin-pages.ts b/packages/astro/src/core/build/plugins/plugin-pages.ts index 4df70eac4b..2dc400a6c2 100644 --- a/packages/astro/src/core/build/plugins/plugin-pages.ts +++ b/packages/astro/src/core/build/plugins/plugin-pages.ts @@ -39,7 +39,7 @@ function vitePluginPages(opts: StaticBuildOptions, internals: BuildInternals): V const pageDatas = getPagesFromVirtualModulePageName( internals, ASTRO_PAGE_RESOLVED_MODULE_ID, - id + id, ); for (const pageData of pageDatas) { const resolvedPage = await this.resolve(pageData.moduleSpecifier); diff --git a/packages/astro/src/core/build/plugins/plugin-prerender.ts b/packages/astro/src/core/build/plugins/plugin-prerender.ts index a8ace9a254..25b9517941 100644 --- a/packages/astro/src/core/build/plugins/plugin-prerender.ts +++ b/packages/astro/src/core/build/plugins/plugin-prerender.ts @@ -46,7 +46,7 @@ function getNonPrerenderOnlyChunks(bundle: Rollup.OutputBundle, internals: Build const pageDatas = getPagesFromVirtualModulePageName( internals, ASTRO_PAGE_RESOLVED_MODULE_ID, - chunk.facadeModuleId + chunk.facadeModuleId, ); const prerender = pageDatas.every((pageData) => pageData.route.prerender); if (prerender) { @@ -102,7 +102,7 @@ function getNonPrerenderOnlyChunks(bundle: Rollup.OutputBundle, internals: Build export function pluginPrerender( opts: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): AstroBuildPlugin { // Static output can skip prerender completely because we're already rendering all pages if (opts.settings.config.output === 'static') { diff --git a/packages/astro/src/core/build/plugins/plugin-ssr.ts b/packages/astro/src/core/build/plugins/plugin-ssr.ts index f4857402a1..f395141a0f 100644 --- a/packages/astro/src/core/build/plugins/plugin-ssr.ts +++ b/packages/astro/src/core/build/plugins/plugin-ssr.ts @@ -22,7 +22,7 @@ export const RESOLVED_SSR_VIRTUAL_MODULE_ID = '\0' + SSR_VIRTUAL_MODULE_ID; function vitePluginSSR( internals: BuildInternals, adapter: AstroAdapter, - options: StaticBuildOptions + options: StaticBuildOptions, ): VitePlugin { return { name: '@astrojs/vite-plugin-astro-ssr-server', @@ -60,7 +60,7 @@ function vitePluginSSR( } const virtualModuleName = getVirtualModulePageName( ASTRO_PAGE_MODULE_ID, - pageData.component + pageData.component, ); let module = await this.resolve(virtualModuleName); if (module) { @@ -106,7 +106,7 @@ function vitePluginSSR( export function pluginSSR( options: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): AstroBuildPlugin { const ssr = isServerLikeOutput(options.settings.config); const functionPerRouteEnabled = isFunctionPerRouteEnabled(options.settings.adapter); @@ -149,7 +149,7 @@ export const RESOLVED_SPLIT_MODULE_ID = '\0@astro-page-split:'; function vitePluginSSRSplit( internals: BuildInternals, adapter: AstroAdapter, - options: StaticBuildOptions + options: StaticBuildOptions, ): VitePlugin { return { name: '@astrojs/vite-plugin-astro-ssr-split', @@ -217,7 +217,7 @@ function vitePluginSSRSplit( export function pluginSSRSplit( options: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): AstroBuildPlugin { const ssr = isServerLikeOutput(options.settings.config); const functionPerRouteEnabled = isFunctionPerRouteEnabled(options.settings.adapter); @@ -301,7 +301,7 @@ function storeEntryPoint( moduleKey: string, options: StaticBuildOptions, internals: BuildInternals, - fileName: string + fileName: string, ) { const componentPath = getComponentFromVirtualModulePageName(RESOLVED_SPLIT_MODULE_ID, moduleKey); for (const pageData of Object.values(options.allPages)) { diff --git a/packages/astro/src/core/build/plugins/util.ts b/packages/astro/src/core/build/plugins/util.ts index de2c53e81e..c636928d0b 100644 --- a/packages/astro/src/core/build/plugins/util.ts +++ b/packages/astro/src/core/build/plugins/util.ts @@ -82,7 +82,7 @@ export function getVirtualModulePageName(virtualModulePrefix: string, path: stri export function getPagesFromVirtualModulePageName( internals: BuildInternals, virtualModulePrefix: string, - id: string + id: string, ): PageBuildData[] { const path = getComponentFromVirtualModulePageName(virtualModulePrefix, id); @@ -105,7 +105,7 @@ export function getPagesFromVirtualModulePageName( */ export function getComponentFromVirtualModulePageName( virtualModulePrefix: string, - id: string + id: string, ): string { return id.slice(virtualModulePrefix.length).replace(ASTRO_PAGE_EXTENSION_POST_PATTERN, '.'); } @@ -113,7 +113,7 @@ export function getComponentFromVirtualModulePageName( export function shouldInlineAsset( assetContent: string, assetPath: string, - assetsInlineLimit: NonNullable + assetsInlineLimit: NonNullable, ) { if (typeof assetsInlineLimit === 'function') { const result = assetsInlineLimit(assetPath, Buffer.from(assetContent)); diff --git a/packages/astro/src/core/build/static-build.ts b/packages/astro/src/core/build/static-build.ts index da651effdc..8626019562 100644 --- a/packages/astro/src/core/build/static-build.ts +++ b/packages/astro/src/core/build/static-build.ts @@ -141,7 +141,7 @@ export async function staticBuild( opts: StaticBuildOptions, internals: BuildInternals, ssrOutputChunkNames: string[], - contentFileNames?: string[] + contentFileNames?: string[], ) { const { settings } = opts; switch (true) { @@ -171,7 +171,7 @@ async function ssrBuild( internals: BuildInternals, input: Set, container: AstroBuildPluginContainer, - logger: Logger + logger: Logger, ) { const buildID = Date.now().toString(); const { allPages, settings, viteConfig } = opts; @@ -245,7 +245,7 @@ async function ssrBuild( return makeAstroPageEntryPointFileName( ASTRO_PAGE_RESOLVED_MODULE_ID, chunkInfo.facadeModuleId, - routes + routes, ); } else if (chunkInfo.facadeModuleId?.startsWith(RESOLVED_SPLIT_MODULE_ID)) { return makeSplitEntryPointFileName(chunkInfo.facadeModuleId, routes); @@ -303,7 +303,7 @@ async function clientBuild( opts: StaticBuildOptions, internals: BuildInternals, input: Set, - container: AstroBuildPluginContainer + container: AstroBuildPluginContainer, ) { const { settings, viteConfig } = opts; const ssr = isServerLikeOutput(settings.config); @@ -364,7 +364,7 @@ async function clientBuild( async function runPostBuildHooks( container: AstroBuildPluginContainer, ssrOutputs: vite.Rollup.RollupOutput[], - clientOutputs: vite.Rollup.RollupOutput[] + clientOutputs: vite.Rollup.RollupOutput[], ) { const mutations = await container.runPostHook(ssrOutputs, clientOutputs); const config = container.options.settings.config; @@ -401,7 +401,7 @@ async function cleanStaticOutput(opts: StaticBuildOptions, internals: BuildInter await fs.promises.writeFile( url, "// Contents removed by Astro as it's used for prerendering only", - 'utf-8' + 'utf-8', ); } else { await fs.promises.unlink(url); @@ -410,7 +410,7 @@ async function cleanStaticOutput(opts: StaticBuildOptions, internals: BuildInter // Best-effort only. Sometimes some chunks may be deleted by other plugins, like pure CSS chunks, // so they may already not exist. } - }) + }), ); } @@ -418,7 +418,7 @@ async function cleanServerOutput( opts: StaticBuildOptions, ssrOutputChunkNames: string[], contentFileNames: string[] | undefined, - internals: BuildInternals + internals: BuildInternals, ) { const out = getOutDirWithinCwd(opts.settings.config.outDir); // The SSR output chunks for Astro are all .mjs files @@ -434,7 +434,7 @@ async function cleanServerOutput( files.map(async (filename) => { const url = new URL(filename, out); await fs.promises.rm(url); - }) + }), ); removeEmptyDirs(out); @@ -447,7 +447,7 @@ async function cleanServerOutput( await Promise.all( fileNames .filter((fileName) => fileName.endsWith('.d.ts')) - .map((fileName) => fs.promises.rm(new URL(fileName, out))) + .map((fileName) => fs.promises.rm(new URL(fileName, out))), ); // Copy assets before cleaning directory if outside root await copyFiles(out, opts.settings.config.outDir, true); @@ -471,7 +471,7 @@ export async function copyFiles(fromFolder: URL, toFolder: URL, includeDotfiles const p = await fs.promises.copyFile(from, to, fs.constants.COPYFILE_FICLONE); return p; }); - }) + }), ); } @@ -499,7 +499,7 @@ async function ssrMoveAssets(opts: StaticBuildOptions) { // that includes the folder paths in `assetFileNames if (!fs.existsSync(dir)) await fs.promises.mkdir(dir, { recursive: true }); return fs.promises.rename(currentUrl, clientUrl); - }) + }), ); removeEmptyDirs(serverAssets); } @@ -526,7 +526,7 @@ async function ssrMoveAssets(opts: StaticBuildOptions) { export function makeAstroPageEntryPointFileName( prefix: string, facadeModuleId: string, - routes: RouteData[] + routes: RouteData[], ) { const pageModuleId = facadeModuleId .replace(prefix, '') @@ -555,7 +555,7 @@ export function makeSplitEntryPointFileName(facadeModuleId: string, routes: Rout const filePath = `${makeAstroPageEntryPointFileName( RESOLVED_SPLIT_MODULE_ID, facadeModuleId, - routes + routes, )}`; const pathComponents = filePath.split(path.sep); diff --git a/packages/astro/src/core/build/util.ts b/packages/astro/src/core/build/util.ts index 96a5ec2f28..9dc61f06fd 100644 --- a/packages/astro/src/core/build/util.ts +++ b/packages/astro/src/core/build/util.ts @@ -12,7 +12,7 @@ export function getTimeStat(timeStart: number, timeEnd: number) { */ export function shouldAppendForwardSlash( trailingSlash: AstroConfig['trailingSlash'], - buildFormat: AstroConfig['build']['format'] + buildFormat: AstroConfig['build']['format'], ): boolean { switch (trailingSlash) { case 'always': @@ -57,7 +57,7 @@ export function encodeName(name: string): string { } export function viteBuildReturnToRollupOutputs( - viteBuildReturn: ViteBuildReturn + viteBuildReturn: ViteBuildReturn, ): Rollup.RollupOutput[] { const result: Rollup.RollupOutput[] = []; if (Array.isArray(viteBuildReturn)) { diff --git a/packages/astro/src/core/config/config.ts b/packages/astro/src/core/config/config.ts index 4c0f0aa3d4..2e43661a43 100644 --- a/packages/astro/src/core/config/config.ts +++ b/packages/astro/src/core/config/config.ts @@ -74,7 +74,7 @@ interface ResolveConfigPathOptions { * Resolve the file URL of the user's `astro.config.js|cjs|mjs|ts` file */ export async function resolveConfigPath( - options: ResolveConfigPathOptions + options: ResolveConfigPathOptions, ): Promise { let userConfigPath: string | undefined; if (options.configFile) { @@ -95,7 +95,7 @@ export async function resolveConfigPath( async function loadConfig( root: string, configFile?: string | false, - fsMod = fs + fsMod = fs, ): Promise> { if (configFile === false) return {}; @@ -155,7 +155,7 @@ interface ResolveConfigResult { export async function resolveConfig( inlineConfig: AstroInlineConfig, command: string, - fsMod = fs + fsMod = fs, ): Promise { const root = resolveRoot(inlineConfig.root); const { inlineUserConfig, inlineOnlyConfig } = splitInlineConfig(inlineConfig); diff --git a/packages/astro/src/core/config/merge.ts b/packages/astro/src/core/config/merge.ts index 81b3b70f37..c897c1441a 100644 --- a/packages/astro/src/core/config/merge.ts +++ b/packages/astro/src/core/config/merge.ts @@ -4,7 +4,7 @@ import { arraify, isObject, isURL } from '../util.js'; function mergeConfigRecursively( defaults: Record, overrides: Record, - rootPath: string + rootPath: string, ) { const merged: Record = { ...defaults }; for (const key in overrides) { @@ -67,7 +67,7 @@ function mergeConfigRecursively( export function mergeConfig( defaults: Record, overrides: Record, - isRoot = true + isRoot = true, ): Record { return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.'); } diff --git a/packages/astro/src/core/config/schema.ts b/packages/astro/src/core/config/schema.ts index 60941b17b5..9ffb58934b 100644 --- a/packages/astro/src/core/config/schema.ts +++ b/packages/astro/src/core/config/schema.ts @@ -143,7 +143,7 @@ export const AstroConfigSchema = z.object({ // validate z .array(z.object({ name: z.string(), hooks: z.object({}).passthrough().default({}) })) - .default(ASTRO_CONFIG_DEFAULTS.integrations) + .default(ASTRO_CONFIG_DEFAULTS.integrations), ), build: z .object({ @@ -177,7 +177,7 @@ export const AstroConfigSchema = z.object({ }, { message: 'The `fallback` is mandatory when defining the option as an object.', - } + }, ), serverEntry: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.serverEntry), redirects: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.redirects), @@ -206,7 +206,7 @@ export const AstroConfigSchema = z.object({ port: z.number().optional().default(ASTRO_CONFIG_DEFAULTS.server.port), headers: z.custom().optional(), }) - .default({}) + .default({}), ), redirects: z .record( @@ -225,7 +225,7 @@ export const AstroConfigSchema = z.object({ ]), destination: z.string(), }), - ]) + ]), ) .default(ASTRO_CONFIG_DEFAULTS.redirects), prefetch: z @@ -263,7 +263,7 @@ export const AstroConfigSchema = z.object({ (val) => !val.includes('*') || val.startsWith('*.') || val.startsWith('**.'), { message: 'wildcards can only be placed at the beginning of the hostname', - } + }, ) .optional(), port: z.string().optional(), @@ -273,7 +273,7 @@ export const AstroConfigSchema = z.object({ message: 'wildcards can only be placed at the end of a pathname', }) .optional(), - }) + }), ) .default([]), }) @@ -318,7 +318,7 @@ export const AstroConfigSchema = z.object({ .record( z .enum(Object.keys(bundledThemes) as [BuiltinTheme, ...BuiltinTheme[]]) - .or(z.custom()) + .or(z.custom()), ) .default(ASTRO_CONFIG_DEFAULTS.markdown.shikiConfig.themes!), defaultColor: z @@ -381,7 +381,7 @@ export const AstroConfigSchema = z.object({ path: z.string(), codes: z.string().array().nonempty(), }), - ]) + ]), ), domains: z .record( @@ -389,8 +389,8 @@ export const AstroConfigSchema = z.object({ z .string() .url( - "The domain value must be a valid URL, and it has to start with 'https' or 'http'." - ) + "The domain value must be a valid URL, and it has to start with 'https' or 'http'.", + ), ) .optional(), fallback: z.record(z.string(), z.string()).optional(), @@ -409,8 +409,8 @@ export const AstroConfigSchema = z.object({ { message: 'The option `i18n.redirectToDefaultLocale` is only useful when the `i18n.prefixDefaultLocale` is set to `true`. Remove the option `i18n.redirectToDefaultLocale`, or change its value to `true`.', - } - ) + }, + ), ) .optional() .default({}), @@ -497,7 +497,7 @@ export const AstroConfigSchema = z.object({ } } } - }) + }), ), security: z .object({ @@ -540,7 +540,7 @@ export const AstroConfigSchema = z.object({ .default(ASTRO_CONFIG_DEFAULTS.experimental.serverIslands), }) .strict( - `Invalid or outdated experimental feature.\nCheck for incorrect spelling or outdated Astro version.\nSee https://docs.astro.build/en/reference/configuration-reference/#experimental-flags for a list of all current experiments.` + `Invalid or outdated experimental feature.\nCheck for incorrect spelling or outdated Astro version.\nSee https://docs.astro.build/en/reference/configuration-reference/#experimental-flags for a list of all current experiments.`, ) .default({}), legacy: z.object({}).default({}), @@ -605,7 +605,7 @@ export function createRelativeSchema(cmd: string, fileProtocolRoot: string) { }, { message: 'The `fallback` is mandatory when defining the option as an object.', - } + }, ), serverEntry: z.string().optional().default(ASTRO_CONFIG_DEFAULTS.build.serverEntry), redirects: z.boolean().optional().default(ASTRO_CONFIG_DEFAULTS.build.redirects), @@ -641,7 +641,7 @@ export function createRelativeSchema(cmd: string, fileProtocolRoot: string) { streaming: z.boolean().optional().default(true), }) .optional() - .default({}) + .default({}), ), }) .transform((config) => { diff --git a/packages/astro/src/core/config/settings.ts b/packages/astro/src/core/config/settings.ts index 9c82118b75..c3c62edd45 100644 --- a/packages/astro/src/core/config/settings.ts +++ b/packages/astro/src/core/config/settings.ts @@ -35,7 +35,7 @@ export function createBaseSettings(config: AstroConfig): AstroSettings { const pathRelToContentDir = path.relative( fileURLToPath(contentDir), - fileURLToPath(fileUrl) + fileURLToPath(fileUrl), ); let data; try { @@ -45,7 +45,7 @@ export function createBaseSettings(config: AstroConfig): AstroSettings { ...AstroErrorData.DataCollectionEntryParseError, message: AstroErrorData.DataCollectionEntryParseError.message( pathRelToContentDir, - e instanceof Error ? e.message : 'contains invalid JSON.' + e instanceof Error ? e.message : 'contains invalid JSON.', ), location: { file: fileUrl.pathname }, stack: e instanceof Error ? e.stack : undefined, @@ -57,7 +57,7 @@ export function createBaseSettings(config: AstroConfig): AstroSettings { ...AstroErrorData.DataCollectionEntryParseError, message: AstroErrorData.DataCollectionEntryParseError.message( pathRelToContentDir, - 'data is not an object.' + 'data is not an object.', ), location: { file: fileUrl.pathname }, }); @@ -77,7 +77,7 @@ export function createBaseSettings(config: AstroConfig): AstroSettings { } catch (e) { const pathRelToContentDir = path.relative( fileURLToPath(contentDir), - fileURLToPath(fileUrl) + fileURLToPath(fileUrl), ); const formattedError = isYAMLException(e) ? formatYAMLException(e) @@ -87,7 +87,7 @@ export function createBaseSettings(config: AstroConfig): AstroSettings { ...AstroErrorData.DataCollectionEntryParseError, message: AstroErrorData.DataCollectionEntryParseError.message( pathRelToContentDir, - formattedError.message + formattedError.message, ), stack: formattedError.stack, location: @@ -122,7 +122,7 @@ export async function createSettings(config: AstroConfig, cwd?: string): Promise if (typeof tsconfig !== 'string') { watchFiles.push( - ...[tsconfig.tsconfigFile, ...(tsconfig.extended ?? []).map((e) => e.tsconfigFile)] + ...[tsconfig.tsconfigFile, ...(tsconfig.extended ?? []).map((e) => e.tsconfigFile)], ); settings.tsConfig = tsconfig.tsconfig; settings.tsConfigPath = tsconfig.tsconfigFile; diff --git a/packages/astro/src/core/config/tsconfig.ts b/packages/astro/src/core/config/tsconfig.ts index 9813b200d8..03d89e30cc 100644 --- a/packages/astro/src/core/config/tsconfig.ts +++ b/packages/astro/src/core/config/tsconfig.ts @@ -64,7 +64,7 @@ type TSConfigResult = Promise< */ export async function loadTSConfig( root: string | undefined, - findUp = false + findUp = false, ): Promise> { const safeCwd = root ?? process.cwd(); @@ -74,8 +74,8 @@ export async function loadTSConfig( find(join(safeCwd, './dummy.txt'), { root: findUp ? undefined : root, configName: configName, - }) - ) + }), + ), ); // If we have both files, prefer tsconfig.json @@ -132,7 +132,7 @@ async function safeParse(tsconfigPath: string, options: TSConfckParseOptions = { export function updateTSConfigForFramework( target: TSConfig, - framework: frameworkWithTSSettings + framework: frameworkWithTSSettings, ): TSConfig { if (!presets.has(framework)) { return target; diff --git a/packages/astro/src/core/config/validate.ts b/packages/astro/src/core/config/validate.ts index 8d1207a85b..4f4497b784 100644 --- a/packages/astro/src/core/config/validate.ts +++ b/packages/astro/src/core/config/validate.ts @@ -5,7 +5,7 @@ import { createRelativeSchema } from './schema.js'; export async function validateConfig( userConfig: any, root: string, - cmd: string + cmd: string, ): Promise { const AstroConfigRelativeSchema = createRelativeSchema(cmd, root); diff --git a/packages/astro/src/core/cookies/cookies.ts b/packages/astro/src/core/cookies/cookies.ts index c176fc7572..852be913d6 100644 --- a/packages/astro/src/core/cookies/cookies.ts +++ b/packages/astro/src/core/cookies/cookies.ts @@ -26,7 +26,7 @@ interface AstroCookiesInterface { set( key: string, value: string | number | boolean | Record, - options?: AstroCookieSetOptions + options?: AstroCookieSetOptions, ): void; delete(key: string, options?: AstroCookieDeleteOptions): void; } @@ -105,7 +105,7 @@ class AstroCookies implements AstroCookiesInterface { */ get( key: string, - options: AstroCookieGetOptions | undefined = undefined + options: AstroCookieGetOptions | undefined = undefined, ): AstroCookie | undefined { // Check for outgoing Set-Cookie values first if (this.#outgoing?.has(key)) { @@ -153,7 +153,7 @@ class AstroCookies implements AstroCookiesInterface { const warning = new Error( 'Astro.cookies.set() was called after the cookies had already been sent to the browser.\n' + 'This may have happened if this method was called in an imported component.\n' + - 'Please make sure that Astro.cookies.set() is only called in the frontmatter of the main page.' + 'Please make sure that Astro.cookies.set() is only called in the frontmatter of the main page.', ); warning.name = 'Warning'; // eslint-disable-next-line no-console diff --git a/packages/astro/src/core/create-vite.ts b/packages/astro/src/core/create-vite.ts index f0986e82ca..0570d9d5d5 100644 --- a/packages/astro/src/core/create-vite.ts +++ b/packages/astro/src/core/create-vite.ts @@ -75,7 +75,7 @@ const ONLY_DEV_EXTERNAL = [ /** Return a base vite config as a common starting point for all Vite commands. */ export async function createVite( commandConfig: vite.InlineConfig, - { settings, logger, mode, command, fs = nodeFs, sync }: CreateViteOptions + { settings, logger, mode, command, fs = nodeFs, sync }: CreateViteOptions, ): Promise { const astroPkgsConfig = await crawlFrameworkPkgs({ root: fileURLToPath(settings.config.root), @@ -312,7 +312,7 @@ function isCommonNotAstro(dep: string): boolean { (prefix) => prefix.startsWith('@') ? dep.startsWith(prefix) - : dep.substring(dep.lastIndexOf('/') + 1).startsWith(prefix) // check prefix omitting @scope/ + : dep.substring(dep.lastIndexOf('/') + 1).startsWith(prefix), // check prefix omitting @scope/ ) ); } diff --git a/packages/astro/src/core/dev/container.ts b/packages/astro/src/core/dev/container.ts index aaf6506e9d..fc401ca710 100644 --- a/packages/astro/src/core/dev/container.ts +++ b/packages/astro/src/core/dev/container.ts @@ -88,7 +88,7 @@ export async function createContainer({ include: rendererClientEntries, }, }, - { settings, logger, mode: 'dev', command: 'dev', fs, sync: false } + { settings, logger, mode: 'dev', command: 'dev', fs, sync: false }, ); await runHookConfigDone({ settings, logger }); await syncInternal({ diff --git a/packages/astro/src/core/dev/dev.ts b/packages/astro/src/core/dev/dev.ts index 25165f0280..3d8424174f 100644 --- a/packages/astro/src/core/dev/dev.ts +++ b/packages/astro/src/core/dev/dev.ts @@ -70,7 +70,7 @@ export default async function dev(inlineConfig: AstroInlineConfig): Promise { const { logger, fs, inlineConfig } = container; const newContainer = await createContainer({ @@ -34,7 +34,7 @@ const preferencesRE = /.*\.astro\/settings.json$/; function shouldRestartContainer( { settings, inlineConfig, restartInFlight }: Container, - changedFile: string + changedFile: string, ): boolean { if (restartInFlight) return false; @@ -59,7 +59,7 @@ function shouldRestartContainer( if (!shouldRestart && settings.watchFiles.length > 0) { // If the config file didn't change, check if any of the watched files changed. shouldRestart = settings.watchFiles.some( - (path) => vite.normalizePath(path) === vite.normalizePath(changedFile) + (path) => vite.normalizePath(path) === vite.normalizePath(changedFile), ); } @@ -81,7 +81,7 @@ async function restartContainer(container: Container): Promise { if (_latestVersion) { return _latestVersion; diff --git a/packages/astro/src/core/errors/dev/vite.ts b/packages/astro/src/core/errors/dev/vite.ts index cc723e6493..56688877a8 100644 --- a/packages/astro/src/core/errors/dev/vite.ts +++ b/packages/astro/src/core/errors/dev/vite.ts @@ -157,7 +157,7 @@ export async function getViteErrorPayload(err: ErrorWithMetadata): Promise `Unable to render \`${componentName}\`. @@ -576,7 +576,7 @@ export const UnsupportedImageFormat = { title: 'Unsupported image format', message: (format: string, imagePath: string, supportedFormats: readonly string[]) => `Received unsupported format \`${format}\` from \`${imagePath}\`. Currently only ${supportedFormats.join( - ', ' + ', ', )} are supported by our image services.`, hint: "Using an `img` tag directly instead of the `Image` component might be what you're looking for.", } satisfies ErrorData; @@ -1488,7 +1488,7 @@ export const InvalidContentEntryFrontmatterError = { message(collection: string, entryId: string, error: ZodError) { return [ `**${String(collection)} → ${String( - entryId + entryId, )}** frontmatter does not match collection schema.`, ...error.errors.map((zodError) => zodError.message), ].join('\n'); @@ -1508,7 +1508,7 @@ export const InvalidContentEntrySlugError = { title: 'Invalid content entry slug.', message(collection: string, entryId: string) { return `${String(collection)} → ${String( - entryId + entryId, )} has an invalid slug. \`slug\` must be a string.`; }, hint: 'See https://docs.astro.build/en/guides/content-collections/ for more on the `slug` field.', diff --git a/packages/astro/src/core/errors/overlay.ts b/packages/astro/src/core/errors/overlay.ts index c4caa3e8de..0579f5b1f2 100644 --- a/packages/astro/src/core/errors/overlay.ts +++ b/packages/astro/src/core/errors/overlay.ts @@ -677,7 +677,7 @@ class ErrorOverlay extends HTMLElement { 'afterend', `\n^` + }ch;">^`, ); } } diff --git a/packages/astro/src/core/errors/utils.ts b/packages/astro/src/core/errors/utils.ts index ef0a10b4f6..05dd49071a 100644 --- a/packages/astro/src/core/errors/utils.ts +++ b/packages/astro/src/core/errors/utils.ts @@ -9,7 +9,7 @@ import type { SSRError } from '../../@types/astro.js'; */ export function positionAt( offset: number, - text: string + text: string, ): { line: number; column: number; diff --git a/packages/astro/src/core/errors/zod-error-map.ts b/packages/astro/src/core/errors/zod-error-map.ts index c3372b708b..647fc0db38 100644 --- a/packages/astro/src/core/errors/zod-error-map.ts +++ b/packages/astro/src/core/errors/zod-error-map.ts @@ -32,7 +32,7 @@ export const errorMap: ZodErrorMap = (baseError, ctx) => { let messages: string[] = [ prefix( baseErrorPath, - typeOrLiteralErrByPath.size ? 'Did not match union:' : 'Did not match union.' + typeOrLiteralErrByPath.size ? 'Did not match union:' : 'Did not match union.', ), ]; return { @@ -46,8 +46,8 @@ export const errorMap: ZodErrorMap = (baseError, ctx) => { key === baseErrorPath ? // Avoid printing the key again if it's a base error `> ${getTypeOrLiteralMsg(error)}` - : `> ${prefix(key, getTypeOrLiteralMsg(error))}` - ) + : `> ${prefix(key, getTypeOrLiteralMsg(error))}`, + ), ) .join('\n'), }; @@ -60,7 +60,7 @@ export const errorMap: ZodErrorMap = (baseError, ctx) => { code: baseError.code, received: (baseError as any).received, expected: [baseError.expected], - }) + }), ), }; } else if (baseError.message) { @@ -76,11 +76,11 @@ const getTypeOrLiteralMsg = (error: TypeOrLiteralErrByPathEntry): string => { switch (error.code) { case 'invalid_type': return `Expected type \`${unionExpectedVals(expectedDeduped)}\`, received ${JSON.stringify( - error.received + error.received, )}`; case 'invalid_literal': return `Expected \`${unionExpectedVals(expectedDeduped)}\`, received ${JSON.stringify( - error.received + error.received, )}`; } }; diff --git a/packages/astro/src/core/logger/core.ts b/packages/astro/src/core/logger/core.ts index 8cef7c4e3c..530399ac42 100644 --- a/packages/astro/src/core/logger/core.ts +++ b/packages/astro/src/core/logger/core.ts @@ -77,7 +77,7 @@ export function log( level: LoggerLevel, label: string | null, message: string, - newLine = true + newLine = true, ) { const logLevel = opts.level; const dest = opts.dest; diff --git a/packages/astro/src/core/logger/node.ts b/packages/astro/src/core/logger/node.ts index aa858cd52b..f78d4d247b 100644 --- a/packages/astro/src/core/logger/node.ts +++ b/packages/astro/src/core/logger/node.ts @@ -44,6 +44,6 @@ export function enableVerboseLogging() { debug('cli', '--verbose flag enabled! Enabling: DEBUG="astro:*,vite:*"'); debug( 'cli', - 'Tip: Set the DEBUG env variable directly for more control. Example: "DEBUG=astro:*,vite:* astro build".' + 'Tip: Set the DEBUG env variable directly for more control. Example: "DEBUG=astro:*,vite:* astro build".', ); } diff --git a/packages/astro/src/core/logger/vite.ts b/packages/astro/src/core/logger/vite.ts index 317a037826..ed62adc8d0 100644 --- a/packages/astro/src/core/logger/vite.ts +++ b/packages/astro/src/core/logger/vite.ts @@ -24,7 +24,7 @@ const viteShortcutHelpMsg = /press (.+?) to (.+)$/s; export function createViteLogger( astroLogger: AstroLogger, - viteLogLevel: LogLevel = 'info' + viteLogLevel: LogLevel = 'info', ): ViteLogger { const warnedMessages = new Set(); const loggedErrors = new WeakSet(); diff --git a/packages/astro/src/core/messages.ts b/packages/astro/src/core/messages.ts index ed59e848f8..8104d993b1 100644 --- a/packages/astro/src/core/messages.ts +++ b/packages/astro/src/core/messages.ts @@ -93,7 +93,7 @@ export function serverStart({ const messages = [ '', `${bgGreen(bold(` astro `))} ${green(`v${version}`)} ${dim(`ready in`)} ${Math.round( - startupTime + startupTime, )} ${dim('ms')}`, '', ...localUrlMessages, @@ -151,7 +151,7 @@ export function preferenceDefaultIntro(name: string) { export function preferenceDefault(name: string, value: any) { return `${yellow('◯')} ${name} has not been set. It defaults to ${bgYellow( - black(` ${JSON.stringify(value)} `) + black(` ${JSON.stringify(value)} `), )}\n`; } @@ -233,10 +233,10 @@ function getNetworkLogging(host: string | boolean): 'none' | 'host-to-expose' | export function formatConfigErrorMessage(err: ZodError) { const errorList = err.issues.map( - (issue) => ` ! ${bold(issue.path.join('.'))} ${red(issue.message + '.')}` + (issue) => ` ! ${bold(issue.path.join('.'))} ${red(issue.message + '.')}`, ); return `${red('[config]')} Astro found issue(s) with your configuration:\n${errorList.join( - '\n' + '\n', )}`; } @@ -246,7 +246,7 @@ const IRRELEVANT_STACK_REGEXP = /node_modules|astro[/\\]dist/g; function formatErrorStackTrace( err: Error | ErrorWithMetadata, - showFullStacktrace: boolean + showFullStacktrace: boolean, ): string { const stackLines = (err.stack || '').split('\n').filter((line) => STACK_LINE_REGEXP.test(line)); // If full details are required, just return the entire stack trace. @@ -355,8 +355,8 @@ export function printHelp({ message.push( linebreak(), ` ${bgGreen(black(` ${commandName} `))} ${green( - `v${process.env.PACKAGE_VERSION ?? ''}` - )} ${headline}` + `v${process.env.PACKAGE_VERSION ?? ''}`, + )} ${headline}`, ); } diff --git a/packages/astro/src/core/middleware/callMiddleware.ts b/packages/astro/src/core/middleware/callMiddleware.ts index 5f2102f75f..3bdc6052da 100644 --- a/packages/astro/src/core/middleware/callMiddleware.ts +++ b/packages/astro/src/core/middleware/callMiddleware.ts @@ -45,8 +45,8 @@ export async function callMiddleware( apiContext: APIContext, responseFunction: ( apiContext: APIContext, - rewritePayload?: RewritePayload - ) => Promise | Response + rewritePayload?: RewritePayload, + ) => Promise | Response, ): Promise { let nextCalled = false; let responseFunctionPromise: Promise | Response | undefined = undefined; diff --git a/packages/astro/src/core/middleware/sequence.ts b/packages/astro/src/core/middleware/sequence.ts index 8b2c2b49c5..ee08381e6f 100644 --- a/packages/astro/src/core/middleware/sequence.ts +++ b/packages/astro/src/core/middleware/sequence.ts @@ -39,7 +39,7 @@ export function sequence(...handlers: MiddlewareHandler[]): MiddlewareHandler { } else { newRequest = new Request( new URL(payload, handleContext.url.origin), - handleContext.request + handleContext.request, ); } carriedPayload = payload; diff --git a/packages/astro/src/core/middleware/vite-plugin.ts b/packages/astro/src/core/middleware/vite-plugin.ts index 4472e16c2c..bb7b54e727 100644 --- a/packages/astro/src/core/middleware/vite-plugin.ts +++ b/packages/astro/src/core/middleware/vite-plugin.ts @@ -28,7 +28,7 @@ export function vitePluginMiddleware({ settings }: { settings: AstroSettings }): async resolveId(id) { if (id === MIDDLEWARE_MODULE_ID) { const middlewareId = await this.resolve( - `${decodeURI(settings.config.srcDir.pathname)}${MIDDLEWARE_PATH_SEGMENT_NAME}` + `${decodeURI(settings.config.srcDir.pathname)}${MIDDLEWARE_PATH_SEGMENT_NAME}`, ); userMiddlewareIsPresent = !!middlewareId; if (middlewareId) { @@ -91,7 +91,7 @@ export const onRequest = sequence( function createMiddlewareImports( entrypoints: string[], - prefix: string + prefix: string, ): { importsCode: string; sequenceCode: string; @@ -114,7 +114,7 @@ function createMiddlewareImports( export function vitePluginMiddlewareBuild( opts: StaticBuildOptions, - internals: BuildInternals + internals: BuildInternals, ): VitePlugin { return { name: '@astro/plugin-middleware-build', diff --git a/packages/astro/src/core/preview/index.ts b/packages/astro/src/core/preview/index.ts index e7e3282ff3..b46cf1becc 100644 --- a/packages/astro/src/core/preview/index.ts +++ b/packages/astro/src/core/preview/index.ts @@ -40,7 +40,7 @@ export default async function preview(inlineConfig: AstroInlineConfig): Promise< if (!fs.existsSync(settings.config.outDir)) { const outDirPath = fileURLToPath(settings.config.outDir); throw new Error( - `[preview] The output directory ${outDirPath} does not exist. Did you run \`astro build\`?` + `[preview] The output directory ${outDirPath} does not exist. Did you run \`astro build\`?`, ); } const server = await createStaticPreviewServer(settings, logger); @@ -51,7 +51,7 @@ export default async function preview(inlineConfig: AstroInlineConfig): Promise< } if (!settings.adapter.previewEntrypoint) { throw new Error( - `[preview] The ${settings.adapter.name} adapter does not support the preview command.` + `[preview] The ${settings.adapter.name} adapter does not support the preview command.`, ); } // We need to use require.resolve() here so that advanced package managers like pnpm @@ -59,7 +59,7 @@ export default async function preview(inlineConfig: AstroInlineConfig): Promise< // preview entrypoint of the integration package, relative to the user's project root. const require = createRequire(settings.config.root); const previewEntrypointUrl = pathToFileURL( - require.resolve(settings.adapter.previewEntrypoint) + require.resolve(settings.adapter.previewEntrypoint), ).href; const previewModule = (await import(previewEntrypointUrl)) as Partial; diff --git a/packages/astro/src/core/preview/static-preview-server.ts b/packages/astro/src/core/preview/static-preview-server.ts index 57aa48a1d0..68ca3236b2 100644 --- a/packages/astro/src/core/preview/static-preview-server.ts +++ b/packages/astro/src/core/preview/static-preview-server.ts @@ -18,7 +18,7 @@ export interface PreviewServer { export default async function createStaticPreviewServer( settings: AstroSettings, - logger: Logger + logger: Logger, ): Promise { const startServerTime = performance.now(); @@ -54,7 +54,7 @@ export default async function createStaticPreviewServer( resolvedUrls: previewServer.resolvedUrls ?? { local: [], network: [] }, host: settings.config.server.host, base: settings.config.base, - }) + }), ); // Resolves once the server is closed diff --git a/packages/astro/src/core/render-context.ts b/packages/astro/src/core/render-context.ts index 4a824bfb09..97e1b25d92 100644 --- a/packages/astro/src/core/render-context.ts +++ b/packages/astro/src/core/render-context.ts @@ -56,7 +56,7 @@ export class RenderContext { protected cookies = new AstroCookies(request), public params = getParams(routeData, pathname), protected url = new URL(request.url), - public props: Props = {} + public props: Props = {}, ) { this.originalRoute = routeData; } @@ -92,7 +92,7 @@ export class RenderContext { undefined, undefined, undefined, - props + props, ); } @@ -109,7 +109,7 @@ export class RenderContext { */ async render( componentInstance: ComponentInstance | undefined, - slots: Record = {} + slots: Record = {}, ): Promise { const { cookies, middleware, pipeline } = this; const { logger, serverLike, streaming } = pipeline; @@ -143,7 +143,7 @@ export class RenderContext { const [routeData, component] = await pipeline.tryRewrite( payload, this.request, - this.originalRoute + this.originalRoute, ); this.routeData = routeData; componentInstance = component; @@ -168,7 +168,7 @@ export class RenderContext { props, slots, streaming, - this.routeData + this.routeData, ); } catch (e) { // If there is an error in the page's frontmatter or instantiation of the RenderTemplate fails midway, @@ -226,7 +226,7 @@ export class RenderContext { const [routeData, component, newURL] = await this.pipeline.tryRewrite( reroutePayload, this.request, - this.originalRoute + this.originalRoute, ); this.routeData = routeData; if (reroutePayload instanceof Request) { @@ -374,20 +374,20 @@ export class RenderContext { result: SSRResult, astroStaticPartial: AstroGlobalPartial, props: Record, - slotValues: Record | null + slotValues: Record | null, ): AstroGlobal { let astroPagePartial; // During rewriting, we must recompute the Astro global, because we need to purge the previous params/props/etc. if (this.isRewriting) { astroPagePartial = this.#astroPagePartial = this.createAstroPagePartial( result, - astroStaticPartial + astroStaticPartial, ); } else { // Create page partial with static partial so they can be cached together. astroPagePartial = this.#astroPagePartial ??= this.createAstroPagePartial( result, - astroStaticPartial + astroStaticPartial, ); } // Create component-level partials. `Astro.self` is added by the compiler. @@ -396,7 +396,7 @@ export class RenderContext { // Create final object. `Astro.slots` will be lazily created. const Astro: Omit = Object.assign( Object.create(astroPagePartial), - astroComponentPartial + astroComponentPartial, ); // Handle `Astro.slots` @@ -407,7 +407,7 @@ export class RenderContext { _slots = new Slots( result, slotValues, - this.pipeline.logger + this.pipeline.logger, ) as unknown as AstroGlobal['slots']; } return _slots; @@ -419,7 +419,7 @@ export class RenderContext { createAstroPagePartial( result: SSRResult, - astroStaticPartial: AstroGlobalPartial + astroStaticPartial: AstroGlobalPartial, ): Omit { const renderContext = this; const { cookies, locals, params, pipeline, url } = this; diff --git a/packages/astro/src/core/render/paginate.ts b/packages/astro/src/core/render/paginate.ts index 591d739c5b..e962d98d31 100644 --- a/packages/astro/src/core/render/paginate.ts +++ b/packages/astro/src/core/render/paginate.ts @@ -9,11 +9,11 @@ import type { import { AstroError, AstroErrorData } from '../errors/index.js'; export function generatePaginateFunction( - routeMatch: RouteData + routeMatch: RouteData, ): (...args: Parameters) => ReturnType { return function paginateUtility( data: any[], - args: PaginateOptions = {} + args: PaginateOptions = {}, ): ReturnType { let { pageSize: _pageSize, params: _params, props: _props } = args; const pageSize = _pageSize || 10; @@ -54,7 +54,7 @@ export function generatePaginateFunction( ...params, page: !includesFirstPageNumber && pageNum - 1 === 1 ? undefined : String(pageNum - 1), - }) + }), ); const first = pageNum === 1 @@ -63,7 +63,7 @@ export function generatePaginateFunction( routeMatch.generate({ ...params, page: includesFirstPageNumber ? '1' : undefined, - }) + }), ); const last = pageNum === lastPage diff --git a/packages/astro/src/core/render/params-and-props.ts b/packages/astro/src/core/render/params-and-props.ts index fb02a997d7..cf7d02d483 100644 --- a/packages/astro/src/core/render/params-and-props.ts +++ b/packages/astro/src/core/render/params-and-props.ts @@ -92,7 +92,7 @@ export function getParams(route: RouteData, pathname: string): Params { function validatePrerenderEndpointCollision( route: RouteData, mod: ComponentInstance, - params: Params + params: Params, ) { if (route.type === 'endpoint' && mod.getStaticPaths) { const lastSegment = route.segments[route.segments.length - 1]; diff --git a/packages/astro/src/core/render/renderer.ts b/packages/astro/src/core/render/renderer.ts index 4b6015bbb2..42cc8fd05d 100644 --- a/packages/astro/src/core/render/renderer.ts +++ b/packages/astro/src/core/render/renderer.ts @@ -3,7 +3,7 @@ import type { ModuleLoader } from '../module-loader/index.js'; export async function loadRenderer( renderer: AstroRenderer, - moduleLoader: ModuleLoader + moduleLoader: ModuleLoader, ): Promise { const mod = await moduleLoader.import(renderer.serverEntrypoint); if (typeof mod.default !== 'undefined') { diff --git a/packages/astro/src/core/render/route-cache.ts b/packages/astro/src/core/render/route-cache.ts index b6542222be..399795675e 100644 --- a/packages/astro/src/core/render/route-cache.ts +++ b/packages/astro/src/core/render/route-cache.ts @@ -122,7 +122,7 @@ export function findPathItemByKey( staticPaths: GetStaticPathsResultKeyed, params: Params, route: RouteData, - logger: Logger + logger: Logger, ) { const paramsKey = stringifyParams(params, route); const matchedStaticPath = staticPaths.keyed.get(paramsKey); diff --git a/packages/astro/src/core/render/slots.ts b/packages/astro/src/core/render/slots.ts index b590237bab..ab87204e46 100644 --- a/packages/astro/src/core/render/slots.ts +++ b/packages/astro/src/core/render/slots.ts @@ -53,7 +53,7 @@ export class Slots { if (!Array.isArray(args)) { this.#logger.warn( null, - `Expected second parameter to be an array, received a ${typeof args}. If you're trying to pass an array as a single argument and getting unexpected results, make sure you're passing your array as a item of an array. Ex: Astro.slots.render('default', [["Hello", "World"]])` + `Expected second parameter to be an array, received a ${typeof args}. If you're trying to pass an array as a single argument and getting unexpected results, make sure you're passing your array as a item of an array. Ex: Astro.slots.render('default', [["Hello", "World"]])`, ); } else if (args.length > 0) { const slotValue = this.#slots[name]; @@ -71,7 +71,7 @@ export class Slots { // JSX if (typeof component === 'function') { return await renderJSX(result, (component as any)(...args)).then((res) => - res != null ? String(res) : res + res != null ? String(res) : res, ); } } diff --git a/packages/astro/src/core/render/ssr-element.ts b/packages/astro/src/core/render/ssr-element.ts index a82dd0bc9f..7c766ee20e 100644 --- a/packages/astro/src/core/render/ssr-element.ts +++ b/packages/astro/src/core/render/ssr-element.ts @@ -17,7 +17,7 @@ export function createAssetLink(href: string, base?: string, assetsPrefix?: Asse export function createStylesheetElement( stylesheet: StylesheetAsset, base?: string, - assetsPrefix?: AssetsPrefix + assetsPrefix?: AssetsPrefix, ): SSRElement { if (stylesheet.type === 'inline') { return { @@ -38,7 +38,7 @@ export function createStylesheetElement( export function createStylesheetElementSet( stylesheets: StylesheetAsset[], base?: string, - assetsPrefix?: AssetsPrefix + assetsPrefix?: AssetsPrefix, ): Set { return new Set(stylesheets.map((s) => createStylesheetElement(s, base, assetsPrefix))); } @@ -46,7 +46,7 @@ export function createStylesheetElementSet( export function createModuleScriptElement( script: { type: 'inline' | 'external'; value: string }, base?: string, - assetsPrefix?: AssetsPrefix + assetsPrefix?: AssetsPrefix, ): SSRElement { if (script.type === 'external') { return createModuleScriptElementWithSrc(script.value, base, assetsPrefix); @@ -63,7 +63,7 @@ export function createModuleScriptElement( export function createModuleScriptElementWithSrc( src: string, base?: string, - assetsPrefix?: AssetsPrefix + assetsPrefix?: AssetsPrefix, ): SSRElement { return { props: { @@ -77,9 +77,9 @@ export function createModuleScriptElementWithSrc( export function createModuleScriptsSet( scripts: { type: 'inline' | 'external'; value: string }[], base?: string, - assetsPrefix?: AssetsPrefix + assetsPrefix?: AssetsPrefix, ): Set { return new Set( - scripts.map((script) => createModuleScriptElement(script, base, assetsPrefix)) + scripts.map((script) => createModuleScriptElement(script, base, assetsPrefix)), ); } diff --git a/packages/astro/src/core/request.ts b/packages/astro/src/core/request.ts index 27cd67a0d4..93b5529017 100644 --- a/packages/astro/src/core/request.ts +++ b/packages/astro/src/core/request.ts @@ -55,7 +55,7 @@ export function createRequest({ // Examples include `:method`, `:scheme`, `:authority`, and `:path`. // They are always prefixed with a colon to distinguish them from other headers, and it is an error to add the to a Headers object manually. // See https://httpwg.org/specs/rfc7540.html#HttpRequest - Object.entries(headers as Record).filter(([name]) => !name.startsWith(':')) + Object.entries(headers as Record).filter(([name]) => !name.startsWith(':')), ); if (typeof url === 'string') url = new URL(url); @@ -83,7 +83,7 @@ export function createRequest({ get() { logger.warn( null, - `\`Astro.request.headers\` is unavailable in "static" output mode, and in prerendered pages within "hybrid" and "server" output modes. If you need access to request headers, make sure that \`output\` is configured as either \`"server"\` or \`output: "hybrid"\` in your config file, and that the page accessing the headers is rendered on-demand.` + `\`Astro.request.headers\` is unavailable in "static" output mode, and in prerendered pages within "hybrid" and "server" output modes. If you need access to request headers, make sure that \`output\` is configured as either \`"server"\` or \`output: "hybrid"\` in your config file, and that the page accessing the headers is rendered on-demand.`, ); return _headers; }, diff --git a/packages/astro/src/core/routing/astro-designed-error-pages.ts b/packages/astro/src/core/routing/astro-designed-error-pages.ts index b834fb2027..4e4b41b70c 100644 --- a/packages/astro/src/core/routing/astro-designed-error-pages.ts +++ b/packages/astro/src/core/routing/astro-designed-error-pages.ts @@ -45,7 +45,7 @@ async function default404Page({ pathname }: { pathname: string }) { tabTitle: '404: Not Found', pathname, }), - { status: 404, headers: { 'Content-Type': 'text/html; charset=utf-8' } } + { status: 404, headers: { 'Content-Type': 'text/html; charset=utf-8' } }, ); } // mark the function as an AstroComponentFactory for the rendering internals diff --git a/packages/astro/src/core/routing/manifest/create.ts b/packages/astro/src/core/routing/manifest/create.ts index a92d089eff..f9c19b9ed0 100644 --- a/packages/astro/src/core/routing/manifest/create.ts +++ b/packages/astro/src/core/routing/manifest/create.ts @@ -133,7 +133,7 @@ export interface CreateRouteManifestParams { function createFileBasedRoutes( { settings, cwd, fsMod }: CreateRouteManifestParams, - logger: Logger + logger: Logger, ): RouteData[] { const components: string[] = []; const routes: RouteData[] = []; @@ -150,7 +150,7 @@ function createFileBasedRoutes( fs: typeof nodeFs, dir: string, parentSegments: RoutePart[][], - parentParams: string[] + parentParams: string[], ) { let items: Item[] = []; const files = fs.readdirSync(dir); @@ -172,8 +172,8 @@ function createFileBasedRoutes( logger.warn( null, `Unsupported file type ${bold( - resolved - )} found. Prefix filename with an underscore (\`_\`) to ignore.` + resolved, + )} found. Prefix filename with an underscore (\`_\`) to ignore.`, ); continue; @@ -346,7 +346,7 @@ function createInjectedRoutes({ settings, cwd }: CreateRouteManifestParams): Pri function createRedirectRoutes( { settings }: CreateRouteManifestParams, routeMap: Map, - logger: Logger + logger: Logger, ): PrioritizedRoutesData { const { config } = settings; const trailingSlash = config.trailingSlash; @@ -387,7 +387,7 @@ function createRedirectRoutes( if (/^https?:\/\//.test(destination)) { logger.warn( 'redirects', - `Redirecting to an external URL is not officially supported: ${from} -> ${destination}` + `Redirecting to an external URL is not officially supported: ${from} -> ${destination}`, ); } @@ -450,11 +450,11 @@ function detectRouteCollision(a: RouteData, b: RouteData, _config: AstroConfig, // such that one of them will never be matched. logger.warn( 'router', - `The route "${a.route}" is defined in both "${a.component}" and "${b.component}". A static route cannot be defined more than once.` + `The route "${a.route}" is defined in both "${a.component}" and "${b.component}". A static route cannot be defined more than once.`, ); logger.warn( 'router', - 'A collision will result in an hard error in following versions of Astro.' + 'A collision will result in an hard error in following versions of Astro.', ); return; } @@ -488,7 +488,7 @@ function detectRouteCollision(a: RouteData, b: RouteData, _config: AstroConfig, // Both routes are guaranteed to collide such that one will never be matched. logger.warn( 'router', - `The route "${a.route}" is defined in both "${a.component}" and "${b.component}" using SSR mode. A dynamic SSR route cannot be defined more than once.` + `The route "${a.route}" is defined in both "${a.component}" and "${b.component}" using SSR mode. A dynamic SSR route cannot be defined more than once.`, ); logger.warn('router', 'A collision will result in an hard error in following versions of Astro.'); } @@ -496,7 +496,7 @@ function detectRouteCollision(a: RouteData, b: RouteData, _config: AstroConfig, /** Create manifest of all static routes */ export function createRouteManifest( params: CreateRouteManifestParams, - logger: Logger + logger: Logger, ): ManifestData { const { settings } = params; const { config } = settings; @@ -520,7 +520,7 @@ export function createRouteManifest( const routes: RouteData[] = [ ...injectedRoutes['legacy'].sort(routeComparator), ...[...fileBasedRoutes, ...injectedRoutes['normal'], ...redirectRoutes['normal']].sort( - routeComparator + routeComparator, ), ...redirectRoutes['legacy'].sort(routeComparator), ]; @@ -543,7 +543,7 @@ export function createRouteManifest( if (!index) { let relativePath = path.relative( fileURLToPath(settings.config.root), - fileURLToPath(new URL('pages', settings.config.srcDir)) + fileURLToPath(new URL('pages', settings.config.srcDir)), ); throw new AstroError({ ...MissingIndexForInternationalization, diff --git a/packages/astro/src/core/routing/manifest/generator.ts b/packages/astro/src/core/routing/manifest/generator.ts index 734aee726d..4ab635ec66 100644 --- a/packages/astro/src/core/routing/manifest/generator.ts +++ b/packages/astro/src/core/routing/manifest/generator.ts @@ -8,7 +8,7 @@ import { compile } from 'path-to-regexp'; * @returns {Record} The sanitized parameters object. */ function sanitizeParams( - params: Record + params: Record, ): Record { return Object.fromEntries( Object.entries(params).map(([key, value]) => { @@ -16,13 +16,13 @@ function sanitizeParams( return [key, value.normalize().replace(/#/g, '%23').replace(/\?/g, '%3F')]; } return [key, value]; - }) + }), ); } export function getRouteGenerator( segments: RoutePart[][], - addTrailingSlash: AstroConfig['trailingSlash'] + addTrailingSlash: AstroConfig['trailingSlash'], ) { const template = segments .map((segment) => { diff --git a/packages/astro/src/core/routing/manifest/pattern.ts b/packages/astro/src/core/routing/manifest/pattern.ts index ee0cfaf655..65f223aa0c 100644 --- a/packages/astro/src/core/routing/manifest/pattern.ts +++ b/packages/astro/src/core/routing/manifest/pattern.ts @@ -3,7 +3,7 @@ import type { AstroConfig, RoutePart } from '../../../@types/astro.js'; export function getPattern( segments: RoutePart[][], base: AstroConfig['base'], - addTrailingSlash: AstroConfig['trailingSlash'] + addTrailingSlash: AstroConfig['trailingSlash'], ) { const pathname = segments .map((segment) => { diff --git a/packages/astro/src/core/routing/manifest/serialization.ts b/packages/astro/src/core/routing/manifest/serialization.ts index 431febcb80..852aa703bf 100644 --- a/packages/astro/src/core/routing/manifest/serialization.ts +++ b/packages/astro/src/core/routing/manifest/serialization.ts @@ -4,7 +4,7 @@ import { getRouteGenerator } from './generator.js'; export function serializeRouteData( routeData: RouteData, - trailingSlash: AstroConfig['trailingSlash'] + trailingSlash: AstroConfig['trailingSlash'], ): SerializedRouteData { return { ...routeData, diff --git a/packages/astro/src/core/routing/validation.ts b/packages/astro/src/core/routing/validation.ts index b68d5f3e89..1f11f55e6c 100644 --- a/packages/astro/src/core/routing/validation.ts +++ b/packages/astro/src/core/routing/validation.ts @@ -26,7 +26,7 @@ export function validateDynamicRouteModule( }: { ssr: boolean; route: RouteData; - } + }, ) { if ((!ssr || route.prerender) && !mod.getStaticPaths) { throw new AstroError({ @@ -40,7 +40,7 @@ export function validateDynamicRouteModule( export function validateGetStaticPathsResult( result: GetStaticPathsResult, logger: Logger, - route: RouteData + route: RouteData, ) { if (!Array.isArray(result)) { throw new AstroError({ @@ -57,7 +57,7 @@ export function validateGetStaticPathsResult( throw new AstroError({ ...AstroErrorData.InvalidGetStaticPathsEntry, message: AstroErrorData.InvalidGetStaticPathsEntry.message( - Array.isArray(pathObject) ? 'array' : typeof pathObject + Array.isArray(pathObject) ? 'array' : typeof pathObject, ), }); } @@ -81,14 +81,14 @@ export function validateGetStaticPathsResult( logger.warn( 'router', `getStaticPaths() returned an invalid path param: "${key}". A string, number or undefined value was expected, but got \`${JSON.stringify( - val - )}\`.` + val, + )}\`.`, ); } if (typeof val === 'string' && val === '') { logger.warn( 'router', - `getStaticPaths() returned an invalid path param: "${key}". \`undefined\` expected for an optional param, but got empty string.` + `getStaticPaths() returned an invalid path param: "${key}". \`undefined\` expected for an optional param, but got empty string.`, ); } } diff --git a/packages/astro/src/core/sync/index.ts b/packages/astro/src/core/sync/index.ts index 7441aabc7e..7b0d3268a0 100644 --- a/packages/astro/src/core/sync/index.ts +++ b/packages/astro/src/core/sync/index.ts @@ -88,7 +88,7 @@ export async function syncInternal({ optional: true, cwd, }, - [] + [], ); try { @@ -104,7 +104,7 @@ export async function syncInternal({ const error = createSafeError(err); logger.error( 'types', - formatErrorMessage(collectErrorMetadata(error), logger.level() === 'debug') + '\n' + formatErrorMessage(collectErrorMetadata(error), logger.level() === 'debug') + '\n', ); // Will return exit code 1 in CLI throw error; @@ -127,7 +127,7 @@ export async function syncInternal({ */ async function syncContentCollections( settings: AstroSettings, - { logger, fs }: Required> + { logger, fs }: Required>, ): Promise { // Needed to load content config const tempViteServer = await createServer( @@ -138,8 +138,8 @@ async function syncContentCollections( ssr: { external: [] }, logLevel: 'silent', }, - { settings, logger, mode: 'build', command: 'build', fs, sync: true } - ) + { settings, logger, mode: 'build', command: 'build', fs, sync: true }, + ), ); // Patch `hot.send` to bubble up error events @@ -186,7 +186,7 @@ async function syncContentCollections( hint, message: AstroErrorData.GenerateContentTypesError.message(safeError.message), }, - { cause: e } + { cause: e }, ); } finally { await tempViteServer.close(); diff --git a/packages/astro/src/core/sync/setup-env-ts.ts b/packages/astro/src/core/sync/setup-env-ts.ts index 5a380271a2..39eb062e5b 100644 --- a/packages/astro/src/core/sync/setup-env-ts.ts +++ b/packages/astro/src/core/sync/setup-env-ts.ts @@ -16,8 +16,8 @@ function getDotAstroTypeReference({ const relativePath = normalizePath( path.relative( fileURLToPath(settings.config.srcDir), - fileURLToPath(new URL(filename, settings.dotAstroDir)) - ) + fileURLToPath(new URL(filename, settings.dotAstroDir)), + ), ); return `/// `; @@ -36,7 +36,7 @@ export async function setUpEnvTs({ }) { const envTsPath = new URL('env.d.ts', settings.config.srcDir); const envTsPathRelativetoRoot = normalizePath( - path.relative(fileURLToPath(settings.config.root), fileURLToPath(envTsPath)) + path.relative(fileURLToPath(settings.config.root), fileURLToPath(envTsPath)), ); const injectedTypes: Array = [ diff --git a/packages/astro/src/core/util.ts b/packages/astro/src/core/util.ts index 7ee4e4261f..2dd4ddd3b4 100644 --- a/packages/astro/src/core/util.ts +++ b/packages/astro/src/core/util.ts @@ -55,7 +55,7 @@ export function getOutputFilename(astroConfig: AstroConfig, name: string, type: /** is a specifier an npm package? */ export function parseNpmName( - spec: string + spec: string, ): { scope?: string; name: string; subpath?: string } | undefined { // not an npm package if (!spec || spec[0] === '.' || spec[0] === '/') return undefined; diff --git a/packages/astro/src/core/viteUtils.ts b/packages/astro/src/core/viteUtils.ts index 61ca26a3dc..bfe1eaadcd 100644 --- a/packages/astro/src/core/viteUtils.ts +++ b/packages/astro/src/core/viteUtils.ts @@ -20,7 +20,7 @@ export function resolvePath(specifier: string, importer: string) { export function rootRelativePath( root: URL, idOrUrl: URL | string, - shouldPrependForwardSlash = true + shouldPrependForwardSlash = true, ) { let id: string; if (typeof idOrUrl !== 'string') { diff --git a/packages/astro/src/env/runtime.ts b/packages/astro/src/env/runtime.ts index af63d3e5c7..a2017b617f 100644 --- a/packages/astro/src/env/runtime.ts +++ b/packages/astro/src/env/runtime.ts @@ -27,12 +27,12 @@ export function getEnv(...args: Parameters) { export function createInvalidVariablesError( key: string, type: string, - result: ValidationResultInvalid + result: ValidationResultInvalid, ) { return new AstroError({ ...AstroErrorData.EnvInvalidVariables, message: AstroErrorData.EnvInvalidVariables.message( - invalidVariablesToError([{ key, type, errors: result.errors }]) + invalidVariablesToError([{ key, type, errors: result.errors }]), ), }); } diff --git a/packages/astro/src/env/schema.ts b/packages/astro/src/env/schema.ts index bd88fbb46e..2fc6b003bc 100644 --- a/packages/astro/src/env/schema.ts +++ b/packages/astro/src/env/schema.ts @@ -37,7 +37,7 @@ const EnumSchema = z.object({ .string() .refine((v) => !v.includes("'"), { message: `The "'" character can't be used as an enum value`, - }) + }), ), optional: z.boolean().optional(), default: z.string().optional(), diff --git a/packages/astro/src/env/validators.ts b/packages/astro/src/env/validators.ts index 8776793cb0..f506bb8e7e 100644 --- a/packages/astro/src/env/validators.ts +++ b/packages/astro/src/env/validators.ts @@ -159,7 +159,7 @@ function selectValidator(options: EnvFieldType): ValueValidator { export function validateEnvVariable( value: string | undefined, - options: EnvFieldType + options: EnvFieldType, ): ValidationResult { const isOptional = options.optional || options.default !== undefined; if (isOptional && value === undefined) { diff --git a/packages/astro/src/env/vite-plugin-env.ts b/packages/astro/src/env/vite-plugin-env.ts index 9aae2cf94c..fdcd6ce401 100644 --- a/packages/astro/src/env/vite-plugin-env.ts +++ b/packages/astro/src/env/vite-plugin-env.ts @@ -45,7 +45,7 @@ export function astroEnv({ const loadedEnv = loadEnv( mode === 'dev' ? 'development' : 'production', fileURLToPath(settings.config.root), - '' + '', ); for (const [key, value] of Object.entries(loadedEnv)) { if (value !== undefined) { @@ -138,7 +138,7 @@ function validatePublicVariables({ function getTemplates( schema: EnvSchema, fs: typeof fsMod, - validatedVariables: ReturnType + validatedVariables: ReturnType, ) { let client = ''; let server = fs.readFileSync(MODULE_TEMPLATE_URL, 'utf-8'); diff --git a/packages/astro/src/events/error.ts b/packages/astro/src/events/error.ts index 97b9f49dba..fc8eddfd85 100644 --- a/packages/astro/src/events/error.ts +++ b/packages/astro/src/events/error.ts @@ -105,7 +105,7 @@ function getSafeErrorMessage(message: string | Function): string { `${match1 .split(/\.?(?=[A-Z])/) .join('_') - .toUpperCase()}` + .toUpperCase()}`, ) .replace(/\\`/g, '`'); } diff --git a/packages/astro/src/events/session.ts b/packages/astro/src/events/session.ts index d9c492cb0f..18049ac04d 100644 --- a/packages/astro/src/events/session.ts +++ b/packages/astro/src/events/session.ts @@ -41,7 +41,7 @@ type StringLiteral = T extends string ? (string extends T ? never : T) : neve * results in an error, to make sure generic user input is never measured directly. */ function measureStringLiteral( - val: StringLiteral | boolean | undefined + val: StringLiteral | boolean | undefined, ): string | boolean | undefined { return val; } @@ -62,7 +62,7 @@ function sanitizeConfigInfo(obj: object | undefined, validKeys: string[]): Confi result[key] = measureIsDefined((obj as Record)[key]); return result; }, - {} as Record + {} as Record, ); } @@ -82,23 +82,23 @@ function createAnonymousConfigInfo(userConfig: AstroUserConfig) { ...sanitizeConfigInfo(userConfig, Object.keys(AstroConfigSchema.shape)), build: sanitizeConfigInfo( userConfig.build, - Object.keys(AstroConfigSchema.shape.build._def.innerType.shape) + Object.keys(AstroConfigSchema.shape.build._def.innerType.shape), ), image: sanitizeConfigInfo( userConfig.image, - Object.keys(AstroConfigSchema.shape.image._def.innerType.shape) + Object.keys(AstroConfigSchema.shape.image._def.innerType.shape), ), markdown: sanitizeConfigInfo( userConfig.markdown, - Object.keys(AstroConfigSchema.shape.markdown._def.innerType.shape) + Object.keys(AstroConfigSchema.shape.markdown._def.innerType.shape), ), experimental: sanitizeConfigInfo( userConfig.experimental, - Object.keys(AstroConfigSchema.shape.experimental._def.innerType.shape) + Object.keys(AstroConfigSchema.shape.experimental._def.innerType.shape), ), legacy: sanitizeConfigInfo( userConfig.legacy, - Object.keys(AstroConfigSchema.shape.legacy._def.innerType.shape) + Object.keys(AstroConfigSchema.shape.legacy._def.innerType.shape), ), vite: userConfig.vite ? sanitizeConfigInfo(userConfig.vite, Object.keys(userConfig.vite)) @@ -123,7 +123,7 @@ function createAnonymousConfigInfo(userConfig: AstroUserConfig) { export function eventCliSession( cliCommand: string, userConfig: AstroUserConfig, - flags?: Record + flags?: Record, ): { eventName: string; payload: EventPayload }[] { // Filter out yargs default `_` flag which is the cli command const cliFlags = flags ? Object.keys(flags).filter((name) => name != '_') : undefined; diff --git a/packages/astro/src/i18n/index.ts b/packages/astro/src/i18n/index.ts index 28ddfcf515..aa38b63bbe 100644 --- a/packages/astro/src/i18n/index.ts +++ b/packages/astro/src/i18n/index.ts @@ -387,7 +387,7 @@ export function createMiddleware( i18nManifest: SSRManifest['i18n'], base: SSRManifest['base'], trailingSlash: SSRManifest['trailingSlash'], - format: SSRManifest['buildFormat'] + format: SSRManifest['buildFormat'], ) { return createI18nMiddleware(i18nManifest, base, trailingSlash, format); } diff --git a/packages/astro/src/i18n/middleware.ts b/packages/astro/src/i18n/middleware.ts index 9f9c7348e0..0973328057 100644 --- a/packages/astro/src/i18n/middleware.ts +++ b/packages/astro/src/i18n/middleware.ts @@ -15,7 +15,7 @@ export function createI18nMiddleware( i18n: SSRManifest['i18n'], base: SSRManifest['base'], trailingSlash: SSRManifest['trailingSlash'], - format: SSRManifest['buildFormat'] + format: SSRManifest['buildFormat'], ): MiddlewareHandler { if (!i18n) return (_, next) => next(); const payload: MiddlewarePayload = { diff --git a/packages/astro/src/i18n/utils.ts b/packages/astro/src/i18n/utils.ts index e6b91c589b..052fe01fce 100644 --- a/packages/astro/src/i18n/utils.ts +++ b/packages/astro/src/i18n/utils.ts @@ -183,7 +183,7 @@ export type RoutingStrategies = | 'domains-prefix-always-no-redirect'; export function toRoutingStrategy( routing: NonNullable['routing'], - domains: NonNullable['domains'] + domains: NonNullable['domains'], ) { let strategy: RoutingStrategies; const hasDomains = domains ? Object.keys(domains).length > 0 : false; diff --git a/packages/astro/src/integrations/features-validation.ts b/packages/astro/src/integrations/features-validation.ts index 2b45e04616..87de3592b7 100644 --- a/packages/astro/src/integrations/features-validation.ts +++ b/packages/astro/src/integrations/features-validation.ts @@ -34,7 +34,7 @@ export function validateSupportedFeatures( featureMap: AstroFeatureMap, config: AstroConfig, adapterFeatures: AstroAdapterFeatures | undefined, - logger: Logger + logger: Logger, ): ValidationResult { const { assets = UNSUPPORTED_ASSETS_FEATURE, @@ -51,7 +51,7 @@ export function validateSupportedFeatures( adapterName, logger, 'staticOutput', - () => config?.output === 'static' + () => config?.output === 'static', ); validationResult.hybridOutput = validateSupportKind( @@ -59,7 +59,7 @@ export function validateSupportedFeatures( adapterName, logger, 'hybridOutput', - () => config?.output === 'hybrid' + () => config?.output === 'hybrid', ); validationResult.serverOutput = validateSupportKind( @@ -67,7 +67,7 @@ export function validateSupportedFeatures( adapterName, logger, 'serverOutput', - () => config?.output === 'server' + () => config?.output === 'server', ); validationResult.assets = validateAssetsFeature(assets, adapterName, config, logger); @@ -79,12 +79,12 @@ export function validateSupportedFeatures( 'i18nDomains', () => { return config?.output === 'server' && !config?.site; - } + }, ); if (adapterFeatures?.functionPerRoute) { logger.error( 'config', - 'The Astro feature `i18nDomains` is incompatible with the Adapter feature `functionPerRoute`' + 'The Astro feature `i18nDomains` is incompatible with the Adapter feature `functionPerRoute`', ); } } @@ -94,7 +94,7 @@ export function validateSupportedFeatures( adapterName, logger, 'astro:env getSecret', - () => config?.experimental?.env !== undefined + () => config?.experimental?.env !== undefined, ); return validationResult; @@ -105,7 +105,7 @@ function validateSupportKind( adapterName: string, logger: Logger, featureName: string, - hasCorrectConfig: () => boolean + hasCorrectConfig: () => boolean, ): boolean { if (supportKind === STABLE) { return true; @@ -130,14 +130,14 @@ function featureIsUnsupported(adapterName: string, logger: Logger, featureName: function featureIsExperimental(adapterName: string, logger: Logger, featureName: string) { logger.warn( 'config', - `The feature "${featureName}" is experimental and subject to change (used by ${adapterName}).` + `The feature "${featureName}" is experimental and subject to change (used by ${adapterName}).`, ); } function featureIsDeprecated(adapterName: string, logger: Logger, featureName: string) { logger.warn( 'config', - `The feature "${featureName}" is deprecated and will be removed in the future (used by ${adapterName}).` + `The feature "${featureName}" is deprecated and will be removed in the future (used by ${adapterName}).`, ); } @@ -148,7 +148,7 @@ function validateAssetsFeature( assets: AstroAssetsFeature, adapterName: string, config: AstroConfig, - logger: Logger + logger: Logger, ): boolean { const { supportKind = UNSUPPORTED, @@ -158,7 +158,7 @@ function validateAssetsFeature( if (config?.image?.service?.entrypoint === SHARP_SERVICE && !isSharpCompatible) { logger.warn( null, - `The currently selected adapter \`${adapterName}\` is not compatible with the image service "Sharp".` + `The currently selected adapter \`${adapterName}\` is not compatible with the image service "Sharp".`, ); return false; } @@ -166,7 +166,7 @@ function validateAssetsFeature( if (config?.image?.service?.entrypoint === SQUOOSH_SERVICE && !isSquooshCompatible) { logger.warn( null, - `The currently selected adapter \`${adapterName}\` is not compatible with the image service "Squoosh".` + `The currently selected adapter \`${adapterName}\` is not compatible with the image service "Squoosh".`, ); return false; } diff --git a/packages/astro/src/integrations/hooks.ts b/packages/astro/src/integrations/hooks.ts index 33a7c7c0c5..9b2859e48b 100644 --- a/packages/astro/src/integrations/hooks.ts +++ b/packages/astro/src/integrations/hooks.ts @@ -39,8 +39,8 @@ async function withTakingALongTimeMsg({ logger.info( 'build', `Waiting for integration ${bold(JSON.stringify(name))}, hook ${bold( - JSON.stringify(hookName) - )}...` + JSON.stringify(hookName), + )}...`, ); }, timeoutMs); const result = await hookResult; @@ -176,7 +176,7 @@ export async function runHookConfigSetup({ if (injectRoute.entrypoint == null && 'entryPoint' in injectRoute) { logger.warn( null, - `The injected route "${injectRoute.pattern}" by ${integration.name} specifies the entry point with the "entryPoint" property. This property is deprecated, please use "entrypoint" instead.` + `The injected route "${injectRoute.pattern}" by ${integration.name} specifies the entry point with the "entryPoint" property. This property is deprecated, please use "entrypoint" instead.`, ); injectRoute.entrypoint = injectRoute.entryPoint as string; } @@ -195,26 +195,26 @@ export async function runHookConfigSetup({ addClientDirective: ({ name, entrypoint }) => { if (updatedSettings.clientDirectives.has(name) || addedClientDirectives.has(name)) { throw new Error( - `The "${integration.name}" integration is trying to add the "${name}" client directive, but it already exists.` + `The "${integration.name}" integration is trying to add the "${name}" client directive, but it already exists.`, ); } // TODO: this should be performed after astro:config:done addedClientDirectives.set( name, - buildClientDirectiveEntrypoint(name, entrypoint, settings.config.root) + buildClientDirectiveEntrypoint(name, entrypoint, settings.config.root), ); }, addMiddleware: ({ order, entrypoint }) => { if (typeof updatedSettings.middlewares[order] === 'undefined') { throw new Error( - `The "${integration.name}" integration is trying to add middleware but did not specify an order.` + `The "${integration.name}" integration is trying to add middleware but did not specify an order.`, ); } logger.debug( 'middleware', `The integration ${integration.name} has added middleware that runs ${ order === 'pre' ? 'before' : 'after' - } any application middleware you define.` + } any application middleware you define.`, ); updatedSettings.middlewares[order].push(entrypoint); }, @@ -296,12 +296,12 @@ export async function runHookConfigDone({ setAdapter(adapter) { if (settings.adapter && settings.adapter.name !== adapter.name) { throw new Error( - `Integration "${integration.name}" conflicts with "${settings.adapter.name}". You can only configure one deployment integration.` + `Integration "${integration.name}" conflicts with "${settings.adapter.name}". You can only configure one deployment integration.`, ); } if (!adapter.supportedAstroFeatures) { throw new Error( - `The adapter ${adapter.name} doesn't provide a feature map. It is required in Astro 4.0.` + `The adapter ${adapter.name} doesn't provide a feature map. It is required in Astro 4.0.`, ); } else { const validationResult = validateSupportedFeatures( @@ -310,7 +310,7 @@ export async function runHookConfigDone({ settings.config, // SAFETY: we checked before if it's not present, and we throw an error adapter.adapterFeatures, - logger + logger, ); for (const [featureName, supported] of Object.entries(validationResult)) { // If `supported` / `validationResult[featureName]` only allows boolean, @@ -320,7 +320,7 @@ export async function runHookConfigDone({ if (!supported && featureName !== 'assets') { logger.error( null, - `The adapter ${adapter.name} doesn't support the feature ${featureName}. Your project won't be built. You should not use it.` + `The adapter ${adapter.name} doesn't support the feature ${featureName}. Your project won't be built. You should not use it.`, ); } } diff --git a/packages/astro/src/jsx/babel.ts b/packages/astro/src/jsx/babel.ts index 02280031b1..648831481a 100644 --- a/packages/astro/src/jsx/babel.ts +++ b/packages/astro/src/jsx/babel.ts @@ -58,15 +58,15 @@ function jsxAttributeToString(attr: t.JSXAttribute): string { function addClientMetadata( node: t.JSXElement, - meta: { resolvedPath: string; path: string; name: string } + meta: { resolvedPath: string; path: string; name: string }, ) { const existingAttributes = node.openingElement.attributes.map((attr) => - t.isJSXAttribute(attr) ? jsxAttributeToString(attr) : null + t.isJSXAttribute(attr) ? jsxAttributeToString(attr) : null, ); if (!existingAttributes.find((attr) => attr === 'client:component-path')) { const componentPath = t.jsxAttribute( t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-path')), - t.stringLiteral(meta.resolvedPath) + t.stringLiteral(meta.resolvedPath), ); node.openingElement.attributes.push(componentPath); } @@ -76,13 +76,13 @@ function addClientMetadata( } const componentExport = t.jsxAttribute( t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-export')), - t.stringLiteral(meta.name) + t.stringLiteral(meta.name), ); node.openingElement.attributes.push(componentExport); } if (!existingAttributes.find((attr) => attr === 'client:component-hydration')) { const staticMarker = t.jsxAttribute( - t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-hydration')) + t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-hydration')), ); node.openingElement.attributes.push(staticMarker); } @@ -90,30 +90,30 @@ function addClientMetadata( function addClientOnlyMetadata( node: t.JSXElement, - meta: { resolvedPath: string; path: string; name: string } + meta: { resolvedPath: string; path: string; name: string }, ) { const tagName = getTagName(node); node.openingElement = t.jsxOpeningElement( t.jsxIdentifier(ClientOnlyPlaceholder), - node.openingElement.attributes + node.openingElement.attributes, ); if (node.closingElement) { node.closingElement = t.jsxClosingElement(t.jsxIdentifier(ClientOnlyPlaceholder)); } const existingAttributes = node.openingElement.attributes.map((attr) => - t.isJSXAttribute(attr) ? jsxAttributeToString(attr) : null + t.isJSXAttribute(attr) ? jsxAttributeToString(attr) : null, ); if (!existingAttributes.find((attr) => attr === 'client:display-name')) { const displayName = t.jsxAttribute( t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('display-name')), - t.stringLiteral(tagName) + t.stringLiteral(tagName), ); node.openingElement.attributes.push(displayName); } if (!existingAttributes.find((attr) => attr === 'client:component-path')) { const componentPath = t.jsxAttribute( t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-path')), - t.stringLiteral(meta.resolvedPath) + t.stringLiteral(meta.resolvedPath), ); node.openingElement.attributes.push(componentPath); } @@ -123,13 +123,13 @@ function addClientOnlyMetadata( } const componentExport = t.jsxAttribute( t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-export')), - t.stringLiteral(meta.name) + t.stringLiteral(meta.name), ); node.openingElement.attributes.push(componentExport); } if (!existingAttributes.find((attr) => attr === 'client:component-hydration')) { const staticMarker = t.jsxAttribute( - t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-hydration')) + t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-hydration')), ); node.openingElement.attributes.push(staticMarker); } @@ -151,8 +151,8 @@ export default function astroJSX(): PluginObj { 0, t.importDeclaration( [t.importSpecifier(t.identifier('Fragment'), t.identifier('Fragment'))], - t.stringLiteral('astro/jsx-runtime') - ) + t.stringLiteral('astro/jsx-runtime'), + ), ); }, }, @@ -242,8 +242,8 @@ export default function astroJSX(): PluginObj { } else { throw new Error( `Unable to match <${getTagName( - parentNode - )}> with client:* directive to an import statement!` + parentNode, + )}> with client:* directive to an import statement!`, ); } }, @@ -286,7 +286,7 @@ export default function astroJSX(): PluginObj { if (name.startsWith('client:')) { // eslint-disable-next-line console.warn( - `You are attempting to render <${displayName} ${name} />, but ${displayName} is an Astro component. Astro components do not render in the client and should not have a hydration directive. Please use a framework component for client rendering.` + `You are attempting to render <${displayName} ${name} />, but ${displayName} is an Astro component. Astro components do not render in the client and should not have a hydration directive. Please use a framework component for client rendering.`, ); } } diff --git a/packages/astro/src/jsx/rehype.ts b/packages/astro/src/jsx/rehype.ts index c18124796c..6dcb08d0be 100644 --- a/packages/astro/src/jsx/rehype.ts +++ b/packages/astro/src/jsx/rehype.ts @@ -47,14 +47,14 @@ export const rehypeAnalyzeAstroMetadata: RehypePlugin = () => { // work on Astro components as it's server-side only. Warn the user about this. if (matchedImport.path.endsWith('.astro')) { const clientAttribute = node.attributes.find( - (attr) => attr.type === 'mdxJsxAttribute' && attr.name.startsWith('client:') + (attr) => attr.type === 'mdxJsxAttribute' && attr.name.startsWith('client:'), ) as MdxJsxAttribute | undefined; if (clientAttribute) { // eslint-disable-next-line console.warn( `You are attempting to render <${node.name!} ${ clientAttribute.name - } />, but ${node.name!} is an Astro component. Astro components do not render in the client and should not have a hydration directive. Please use a framework component for client rendering.` + } />, but ${node.name!} is an Astro component. Astro components do not render in the client and should not have a hydration directive. Please use a framework component for client rendering.`, ); } } @@ -165,13 +165,13 @@ function isComponent(tagName: string) { function hasClientDirective(node: MdxJsxFlowElementHast | MdxJsxTextElementHast) { return node.attributes.some( - (attr) => attr.type === 'mdxJsxAttribute' && attr.name.startsWith('client:') + (attr) => attr.type === 'mdxJsxAttribute' && attr.name.startsWith('client:'), ); } function hasClientOnlyDirective(node: MdxJsxFlowElementHast | MdxJsxTextElementHast) { return node.attributes.some( - (attr) => attr.type === 'mdxJsxAttribute' && attr.name === 'client:only' + (attr) => attr.type === 'mdxJsxAttribute' && attr.name === 'client:only', ); } @@ -202,7 +202,7 @@ type MatchedImport = { name: string; path: string }; */ function findMatchingImport( tagName: string, - imports: Map> + imports: Map>, ): MatchedImport | undefined { const tagSpecifier = tagName.split('.')[0]; for (const [source, specs] of imports) { @@ -239,7 +239,7 @@ function findMatchingImport( function addClientMetadata( node: MdxJsxFlowElementHast | MdxJsxTextElementHast, meta: MatchedImport, - resolvedPath: string + resolvedPath: string, ) { const attributeNames = node.attributes .map((attr) => (attr.type === 'mdxJsxAttribute' ? attr.name : null)) @@ -274,7 +274,7 @@ function addClientMetadata( function addClientOnlyMetadata( node: MdxJsxFlowElementHast | MdxJsxTextElementHast, meta: { path: string; name: string }, - resolvedPath: string + resolvedPath: string, ) { const attributeNames = node.attributes .map((attr) => (attr.type === 'mdxJsxAttribute' ? attr.name : null)) diff --git a/packages/astro/src/jsx/server.ts b/packages/astro/src/jsx/server.ts index f460094e15..73b584baea 100644 --- a/packages/astro/src/jsx/server.ts +++ b/packages/astro/src/jsx/server.ts @@ -10,7 +10,7 @@ const slotName = (str: string) => str.trim().replace(/[-_]([a-z])/g, (_, w) => w export async function check( Component: any, props: any, - { default: children = null, ...slotted } = {} + { default: children = null, ...slotted } = {}, ) { if (typeof Component !== 'function') return false; const slots: Record = {}; @@ -31,7 +31,7 @@ export async function renderToStaticMarkup( this: any, Component: any, props = {}, - { default: children = null, ...slotted } = {} + { default: children = null, ...slotted } = {}, ) { const slots: Record = {}; for (const [key, value] of Object.entries(slotted)) { diff --git a/packages/astro/src/preferences/index.ts b/packages/astro/src/preferences/index.ts index 48493c0f35..9318824bf6 100644 --- a/packages/astro/src/preferences/index.ts +++ b/packages/astro/src/preferences/index.ts @@ -49,12 +49,12 @@ export interface PreferenceList extends Record( key: Key, - opts?: PreferenceOptions + opts?: PreferenceOptions, ): Promise>; set( key: Key, value: GetDotKey, - opts?: PreferenceOptions + opts?: PreferenceOptions, ): Promise; getAll(): Promise; list(opts?: PreferenceOptions): Promise; @@ -104,7 +104,7 @@ export default function createPreferences(config: AstroConfig): AstroPreferences {}, DEFAULT_PREFERENCES, stores['global'].getAll(), - stores['project'].getAll() + stores['project'].getAll(), ); const { _variables, ...prefs } = allPrefs; @@ -122,7 +122,7 @@ export default function createPreferences(config: AstroConfig): AstroPreferences function mapFrom(defaults: Preferences, astroConfig: Record) { return Object.fromEntries( - Object.entries(defaults).map(([key, _]) => [key, astroConfig[key]]) + Object.entries(defaults).map(([key, _]) => [key, astroConfig[key]]), ); } }, diff --git a/packages/astro/src/preferences/store.ts b/packages/astro/src/preferences/store.ts index d8e8895e79..c999566e81 100644 --- a/packages/astro/src/preferences/store.ts +++ b/packages/astro/src/preferences/store.ts @@ -8,7 +8,7 @@ export class PreferenceStore { constructor( private dir: string, - filename = 'settings.json' + filename = 'settings.json', ) { this.file = path.join(this.dir, filename); } diff --git a/packages/astro/src/prefetch/index.ts b/packages/astro/src/prefetch/index.ts index bdf8676e7e..177945f379 100644 --- a/packages/astro/src/prefetch/index.ts +++ b/packages/astro/src/prefetch/index.ts @@ -62,7 +62,7 @@ function initTapStrategy() { prefetch(e.target.href, { ignoreSlowConnection: true }); } }, - { passive: true } + { passive: true }, ); } } @@ -81,7 +81,7 @@ function initHoverStrategy() { handleHoverIn(e); } }, - { passive: true } + { passive: true }, ); document.body.addEventListener('focusout', handleHoverOut, { passive: true }); @@ -159,7 +159,7 @@ function createViewportIntersectionObserver() { observer.unobserve(anchor); timeouts.delete(anchor); prefetch(anchor.href); - }, 300) as unknown as number + }, 300) as unknown as number, ); } else { // If exited viewport but haven't prefetched, cancel it diff --git a/packages/astro/src/prefetch/vite-plugin-prefetch.ts b/packages/astro/src/prefetch/vite-plugin-prefetch.ts index 9e56536d92..d64c6d5008 100644 --- a/packages/astro/src/prefetch/vite-plugin-prefetch.ts +++ b/packages/astro/src/prefetch/vite-plugin-prefetch.ts @@ -52,7 +52,7 @@ export default function astroPrefetch({ settings }: { settings: AstroSettings }) .replace('__PREFETCH_DEFAULT_STRATEGY__', JSON.stringify(prefetch?.defaultStrategy)) .replace( '__EXPERIMENTAL_CLIENT_PRERENDER__', - JSON.stringify(settings.config.experimental.clientPrerender) + JSON.stringify(settings.config.experimental.clientPrerender), ); } }, diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/astro.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/astro.ts index c70338ea8a..e63667a12d 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/astro.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/astro.ts @@ -368,12 +368,12 @@ export default { (link) => `` : `>${link.icon}` - }${link.name}` + }${link.name}`, ) .join('')} - ` + `, ); const copyDebugButton = @@ -381,7 +381,7 @@ export default { copyDebugButton?.addEventListener('click', () => { navigator.clipboard.writeText( - '```\n' + (window as DevToolbarMetadata).__astro_dev_toolbar__.debugInfo + '\n```' + '```\n' + (window as DevToolbarMetadata).__astro_dev_toolbar__.debugInfo + '\n```', ); copyDebugButton.textContent = 'Copied to clipboard!'; @@ -431,7 +431,7 @@ export default { integrationImage.append(icon); integrationImage.style.setProperty( '--integration-image-background', - colorForIntegration() + colorForIntegration(), ); } diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/index.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/index.ts index 703b0a523e..6a6aba42d1 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/index.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/index.ts @@ -32,7 +32,7 @@ export default { async init(canvas, eventTarget) { let audits: Audit[] = []; let auditWindow = document.createElement( - 'astro-dev-toolbar-audit-window' + 'astro-dev-toolbar-audit-window', ) as DevToolbarAuditListWindow; let hasCreatedUI = false; @@ -60,7 +60,7 @@ export default { if (showState) createAuditsUI(); }); }, - { timeout: 300 } + { timeout: 300 }, ); } else { // Fallback for old versions of Safari, we'll assume that things are less likely to be busy after 150ms. @@ -174,7 +174,7 @@ export default { detail: { state: audits.length > 0, }, - }) + }), ); } diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/rules/a11y.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/rules/a11y.ts index c26236c16b..a20e140389 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/rules/a11y.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/rules/a11y.ts @@ -194,14 +194,14 @@ const input_type_to_implicit_role = new Map([ const ariaAttributes = new Set( 'activedescendant atomic autocomplete busy checked colcount colindex colspan controls current describedby description details disabled dropeffect errormessage expanded flowto grabbed haspopup hidden invalid keyshortcuts label labelledby level live modal multiline multiselectable orientation owns placeholder posinset pressed readonly relevant required roledescription rowcount rowindex rowspan selected setsize sort valuemax valuemin valuenow valuetext'.split( - ' ' - ) + ' ', + ), ); const ariaRoles = new Set( 'alert alertdialog application article banner button cell checkbox columnheader combobox complementary contentinfo definition dialog directory document feed figure form grid gridcell group heading img link list listbox listitem log main marquee math menu menubar menuitem menuitemcheckbox menuitemradio navigation none note option presentation progressbar radio radiogroup region row rowgroup rowheader scrollbar search searchbox separator slider spinbutton status switch tab tablist tabpanel textbox timer toolbar tooltip tree treegrid treeitem'.split( - ' ' - ) + ' ', + ), ); function isInteractive(element: Element): boolean { @@ -315,7 +315,7 @@ export const a11y: AuditRuleWithSelector[] = [ if (!tracks.length) return true; const hasCaptionTrack = Array.from(tracks).some( - (track) => track.getAttribute('kind') === 'captions' + (track) => track.getAttribute('kind') === 'captions', ); return !hasCaptionTrack; @@ -338,7 +338,7 @@ export const a11y: AuditRuleWithSelector[] = [ a11y_required_attributes[element.localName as keyof typeof a11y_required_attributes]; const missingAttributes = requiredAttributes.filter( - (attribute) => !element.hasAttribute(attribute) + (attribute) => !element.hasAttribute(attribute), ); return `${ @@ -561,7 +561,7 @@ export const a11y: AuditRuleWithSelector[] = [ return `${ element.localName } element has ARIA attributes that are not supported by its role (${role}): ${unsupported.join( - ', ' + ', ', )}`; }, selector: '*', @@ -575,7 +575,7 @@ export const a11y: AuditRuleWithSelector[] = [ const attributes = getAttributeObject(element); const unsupportedAttributes = aria.keys().filter((attribute) => !(attribute in props)); const invalidAttributes: string[] = Object.keys(attributes).filter( - (key) => key.startsWith('aria-') && unsupportedAttributes.includes(key as any) + (key) => key.startsWith('aria-') && unsupportedAttributes.includes(key as any), ); if (invalidAttributes.length > 0) { (element as any).__astro_role = elementRole; @@ -681,7 +681,7 @@ function getAttributeObject(element: Element): Record { function is_semantic_role_element( role: ARIARoleDefinitionKey, tag_name: string, - attributes: Record + attributes: Record, ) { for (const [schema, ax_object] of elementAXObjects.entries()) { if ( diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/rules/index.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/rules/index.ts index 7d22a50c7c..935f5376f8 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/rules/index.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/rules/index.ts @@ -22,7 +22,7 @@ export interface ResolvedAuditRule { export interface AuditRuleWithSelector extends AuditRule { selector: string; match?: ( - element: Element + element: Element, ) => | boolean | null diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/rules/perf.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/rules/perf.ts index 7a3de23071..6a1749d001 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/rules/perf.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/rules/perf.ts @@ -91,7 +91,7 @@ export const perf: AuditRuleWithSelector[] = [ title: 'Server-rendered component took a long time to render', message: (element) => `This component took an unusually long time to render on the server (${getCleanRenderingTime( - element.getAttribute('server-render-time') + element.getAttribute('server-render-time'), )}). This might be a sign that it's doing too much work on the server, or something is blocking rendering.`, selector: 'astro-island[server-render-time]', match(element) { @@ -109,7 +109,7 @@ export const perf: AuditRuleWithSelector[] = [ title: 'Client-rendered component took a long time to hydrate', message: (element) => `This component took an unusually long time to render on the server (${getCleanRenderingTime( - element.getAttribute('client-render-time') + element.getAttribute('client-render-time'), )}). This could be a sign that something is blocking the main thread and preventing the component from hydrating quickly.`, selector: 'astro-island[client-render-time]', match(element) { diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-list-window.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-list-window.ts index 86fa7b7435..472e8d7c64 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-list-window.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-list-window.ts @@ -317,7 +317,7 @@ export class DevToolbarAuditListWindow extends HTMLElement { rulesCategories.forEach((category) => { const headerEntryContainer = document.createElement('div'); const auditCount = this.audits.filter( - (audit) => getAuditCategory(audit.rule) === category.code + (audit) => getAuditCategory(audit.rule) === category.code, ).length; const categoryBadge = createRoundedBadge(category.icon); @@ -334,7 +334,7 @@ export class DevToolbarAuditListWindow extends HTMLElement { if (backToListButton) { backToListButton.addEventListener('click', () => { const activeAudit = this.shadowRoot.querySelector( - 'astro-dev-toolbar-audit-list-item[active]' + 'astro-dev-toolbar-audit-list-item[active]', ); if (activeAudit) { activeAudit.toggleAttribute('active', false); @@ -355,7 +355,7 @@ export class DevToolbarAuditListWindow extends HTMLElement { if (this.audits.length > 0) { for (const category of rulesCategories) { const template = this.shadowRoot.getElementById( - 'category-template' + 'category-template', ) as HTMLTemplateElement; if (!template) return; @@ -368,7 +368,7 @@ export class DevToolbarAuditListWindow extends HTMLElement { const categoryContent = clone.querySelector('.category-content')!; const categoryAudits = this.audits.filter( - (audit) => getAuditCategory(audit.rule) === category.code + (audit) => getAuditCategory(audit.rule) === category.code, ); for (const audit of categoryAudits) { @@ -399,7 +399,7 @@ export class DevToolbarAuditListWindow extends HTMLElement { updateBadgeCounts() { for (const category of rulesCategories) { const auditCount = this.audits.filter( - (audit) => getAuditCategory(audit.rule) === category.code + (audit) => getAuditCategory(audit.rule) === category.code, ).length; this.badges[category.code].updateCount(auditCount); } diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.ts index e2833e8040..38559e0f9a 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.ts @@ -79,7 +79,7 @@ function buildAuditTooltip(rule: ResolvedAuditRule, element: Element) { tooltip.sections.push({ content: elementFileWithPosition.slice( - (window as DevToolbarMetadata).__astro_dev_toolbar__.root.length - 1 // We want to keep the final slash, so minus one. + (window as DevToolbarMetadata).__astro_dev_toolbar__.root.length - 1, // We want to keep the final slash, so minus one. ), clickDescription: 'Click to go to file', async clickAction() { @@ -97,10 +97,10 @@ function buildAuditCard( rule: ResolvedAuditRule, highlightElement: HTMLElement, auditedElement: Element, - audits: Audit[] + audits: Audit[], ) { const card = document.createElement( - 'astro-dev-toolbar-audit-list-item' + 'astro-dev-toolbar-audit-list-item', ) as DevToolbarAuditListItem; card.clickAction = () => { diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/settings.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/settings.ts index eb97bd34e8..7ee42da849 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/settings.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/settings.ts @@ -163,7 +163,7 @@ export default { Run astro preferences disable devToolbar in your terminal to disable the toolbar. Learn more. - ` + `, ); const general = windowElement.querySelector('#general')!; for (const settingsRow of settingsRows) { @@ -196,7 +196,7 @@ export default { option.selected = true; } option.textContent = `${placement.slice(0, 1).toUpperCase()}${placement.slice( - 1 + 1, )}`.replace('-', ' '); astroSelect.append(option); }); diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/utils/highlight.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/utils/highlight.ts index 661b68730d..50be27b0ea 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/utils/highlight.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/utils/highlight.ts @@ -4,7 +4,7 @@ import type { Icon } from '../../ui-library/icons.js'; export function createHighlight( rect: DOMRect, icon?: Icon, - additionalAttributes?: Record + additionalAttributes?: Record, ) { const highlight = document.createElement('astro-dev-toolbar-highlight'); if (icon) highlight.icon = icon; @@ -57,7 +57,7 @@ export function positionHighlight(highlight: DevToolbarHighlight, rect: DOMRect) export function attachTooltipToHighlight( highlight: DevToolbarHighlight, tooltip: HTMLElement, - originalElement: Element + originalElement: Element, ) { highlight.shadowRoot.append(tooltip); diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/utils/icons.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/utils/icons.ts index ec5a34ad89..cddee0c263 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/utils/icons.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/utils/icons.ts @@ -13,7 +13,7 @@ const categoryIcons = new Map( analytics: ['checkCircle', 'compress', 'searchFile'], accessibility: ['approveUser', 'checkCircle'], other: ['checkCircle', 'grid', 'puzzle', 'sitemap'], - }) + }), ); export function iconForIntegration(integration: Integration) { diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/utils/window.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/utils/window.ts index fb76c2a9ac..87dee93da5 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/utils/window.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/utils/window.ts @@ -10,7 +10,7 @@ export function createWindowElement(content: string, placement = settings.config export function closeOnOutsideClick( eventTarget: EventTarget, - additionalCheck?: (target: Element) => boolean + additionalCheck?: (target: Element) => boolean, ) { function onPageClick(event: MouseEvent) { const target = event.target as Element | null; @@ -23,7 +23,7 @@ export function closeOnOutsideClick( detail: { state: false, }, - }) + }), ); } eventTarget.addEventListener('app-toggled', (event: any) => { diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/xray.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/xray.ts index 6dae6f6cac..2e56b0f244 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/xray.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/xray.ts @@ -71,7 +71,7 @@ export default {

It looks like there are no interactive component islands on this page. Did you forget to add a client directive to your interactive UI component?

- ` + `, ); canvas.append(window); @@ -140,13 +140,13 @@ export default { // Display the props if we have any // Ignore the "data-astro-cid-XXXXXX" prop (internal) const islandPropsEntries = Object.entries(islandProps).filter( - (prop: any) => !prop[0].startsWith('data-astro-cid-') + (prop: any) => !prop[0].startsWith('data-astro-cid-'), ); if (islandPropsEntries.length > 0) { const stringifiedProps = JSON.stringify( Object.fromEntries(islandPropsEntries.map((prop: any) => [prop[0], prop[1][1]])), undefined, - 2 + 2, ); tooltip.sections.push({ title: 'Props', @@ -167,8 +167,8 @@ export default { '/__open-in-editor?file=' + encodeURIComponent( (window as DevToolbarMetadata).__astro_dev_toolbar__.root + - islandComponentPath.slice(1) - ) + islandComponentPath.slice(1), + ), ); }, }); diff --git a/packages/astro/src/runtime/client/dev-toolbar/entrypoint.ts b/packages/astro/src/runtime/client/dev-toolbar/entrypoint.ts index 48cdac72f7..9731f3597f 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/entrypoint.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/entrypoint.ts @@ -270,11 +270,11 @@ document.addEventListener('DOMContentLoaded', async () => { hiddenApps.some( (p) => p.notification.state === true && - p.notification.level === notificationLevel - ) + p.notification.level === notificationLevel, + ), ) ?? 'error', }, - }) + }), ); }); } @@ -286,7 +286,7 @@ document.addEventListener('DOMContentLoaded', async () => { const apps: DevToolbarApp[] = [ ...[astroDevToolApp, astroXrayApp, astroAuditApp, astroSettingsApp, astroMoreApp].map( - (appDef) => prepareApp(appDef, true) + (appDef) => prepareApp(appDef, true), ), ...customAppsDefinitions.map((appDef) => prepareApp(appDef, false)), ]; diff --git a/packages/astro/src/runtime/client/dev-toolbar/helpers.ts b/packages/astro/src/runtime/client/dev-toolbar/helpers.ts index c205d0003d..a8250ed819 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/helpers.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/helpers.ts @@ -35,7 +35,7 @@ export class ToolbarAppEventTarget extends EventTarget { state: options.state, level: options.state === true ? options.level : undefined, } satisfies NotificationPayload, - }) + }), ); } @@ -50,7 +50,7 @@ export class ToolbarAppEventTarget extends EventTarget { detail: { state: options.state, } satisfies AppStatePayload, - }) + }), ); } diff --git a/packages/astro/src/runtime/client/dev-toolbar/settings.ts b/packages/astro/src/runtime/client/dev-toolbar/settings.ts index 34ab7b5c05..2f5eabe6d3 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/settings.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/settings.ts @@ -39,7 +39,7 @@ function getSettings() { console[level]( `%cAstro`, 'background: linear-gradient(66.77deg, #D83333 0%, #F041FF 100%); color: white; padding-inline: 4px; border-radius: 2px; font-family: monospace;', - message + message, ); } diff --git a/packages/astro/src/runtime/client/dev-toolbar/toolbar.ts b/packages/astro/src/runtime/client/dev-toolbar/toolbar.ts index 3f9db6b1dc..08ea61cace 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/toolbar.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/toolbar.ts @@ -284,13 +284,13 @@ export class AstroDevToolbar extends HTMLElement { ${ this.apps.filter((app) => !app.builtIn).length > this.customAppsToShow ? this.getAppTemplate( - this.apps.find((app) => app.builtIn && app.id === 'astro:more')! + this.apps.find((app) => app.builtIn && app.id === 'astro:more')!, ) : '' }
${this.getAppTemplate( - this.apps.find((app) => app.builtIn && app.id === 'astro:settings')! + this.apps.find((app) => app.builtIn && app.id === 'astro:settings')!, )} @@ -315,7 +315,7 @@ export class AstroDevToolbar extends HTMLElement { async () => { this.apps.map((app) => this.initApp(app)); }, - { timeout: 300 } + { timeout: 300 }, ); } else { setTimeout(async () => { @@ -433,7 +433,7 @@ export class AstroDevToolbar extends HTMLElement { getAppCanvasById(id: string) { return this.shadowRoot.querySelector( - `astro-dev-toolbar-app-canvas[data-app-id="${id}"]` + `astro-dev-toolbar-app-canvas[data-app-id="${id}"]`, ); } @@ -482,7 +482,7 @@ export class AstroDevToolbar extends HTMLElement { app.active = newStatus ?? !app.active; const mainBarButton = this.getAppButtonById(app.id); const moreBarButton = this.getAppCanvasById('astro:more')?.shadowRoot?.querySelector( - `[data-app-id="${app.id}"]` + `[data-app-id="${app.id}"]`, ); if (mainBarButton) { @@ -513,7 +513,7 @@ export class AstroDevToolbar extends HTMLElement { state: app.active, app, }, - }) + }), ); }); @@ -586,7 +586,7 @@ export class AstroDevToolbar extends HTMLElement { detail: { placement: newPlacement, }, - }) + }), ); }); } diff --git a/packages/astro/src/runtime/client/dev-toolbar/ui-library/badge.ts b/packages/astro/src/runtime/client/dev-toolbar/ui-library/badge.ts index 0a4f30cfc2..f018e8f82d 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/ui-library/badge.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/ui-library/badge.ts @@ -17,7 +17,7 @@ export class DevToolbarBadge extends HTMLElement { set size(value) { if (!sizes.includes(value)) { settings.logger.error( - `Invalid size: ${value}, expected one of ${sizes.join(', ')}, got ${value}.` + `Invalid size: ${value}, expected one of ${sizes.join(', ')}, got ${value}.`, ); return; } @@ -32,7 +32,7 @@ export class DevToolbarBadge extends HTMLElement { set badgeStyle(value) { if (!styles.includes(value)) { settings.logger.error( - `Invalid style: ${value}, expected one of ${styles.join(', ')}, got ${value}.` + `Invalid style: ${value}, expected one of ${styles.join(', ')}, got ${value}.`, ); return; } diff --git a/packages/astro/src/runtime/client/dev-toolbar/ui-library/button.ts b/packages/astro/src/runtime/client/dev-toolbar/ui-library/button.ts index 067a1cf2ac..0f13c67ec3 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/ui-library/button.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/ui-library/button.ts @@ -20,7 +20,7 @@ export class DevToolbarButton extends HTMLElement { set size(value) { if (!sizes.includes(value)) { settings.logger.error( - `Invalid size: ${value}, expected one of ${sizes.join(', ')}, got ${value}.` + `Invalid size: ${value}, expected one of ${sizes.join(', ')}, got ${value}.`, ); return; } @@ -35,7 +35,7 @@ export class DevToolbarButton extends HTMLElement { set buttonStyle(value) { if (!styles.includes(value)) { settings.logger.error( - `Invalid style: ${value}, expected one of ${styles.join(', ')}, got ${value}.` + `Invalid style: ${value}, expected one of ${styles.join(', ')}, got ${value}.`, ); return; } @@ -50,7 +50,7 @@ export class DevToolbarButton extends HTMLElement { set buttonBorderRadius(value) { if (!borderRadii.includes(value)) { settings.logger.error( - `Invalid border-radius: ${value}, expected one of ${borderRadii.join(', ')}, got ${value}.` + `Invalid border-radius: ${value}, expected one of ${borderRadii.join(', ')}, got ${value}.`, ); return; } diff --git a/packages/astro/src/runtime/client/dev-toolbar/ui-library/card.ts b/packages/astro/src/runtime/client/dev-toolbar/ui-library/card.ts index bba46a9433..abaf90efa1 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/ui-library/card.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/ui-library/card.ts @@ -18,7 +18,7 @@ export class DevToolbarCard extends HTMLElement { set cardStyle(value) { if (!styles.includes(value)) { settings.logger.error( - `Invalid style: ${value}, expected one of ${styles.join(', ')}, got ${value}.` + `Invalid style: ${value}, expected one of ${styles.join(', ')}, got ${value}.`, ); return; } diff --git a/packages/astro/src/runtime/client/dev-toolbar/ui-library/highlight.ts b/packages/astro/src/runtime/client/dev-toolbar/ui-library/highlight.ts index 2dd85edd9b..c77d2103bf 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/ui-library/highlight.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/ui-library/highlight.ts @@ -16,7 +16,7 @@ export class DevToolbarHighlight extends HTMLElement { set highlightStyle(value) { if (!styles.includes(value)) { settings.logger.error( - `Invalid style: ${value}, expected one of ${styles.join(', ')}, got ${value}.` + `Invalid style: ${value}, expected one of ${styles.join(', ')}, got ${value}.`, ); return; } diff --git a/packages/astro/src/runtime/client/dev-toolbar/ui-library/icons.ts b/packages/astro/src/runtime/client/dev-toolbar/ui-library/icons.ts index cc8fb78290..bc47970c23 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/ui-library/icons.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/ui-library/icons.ts @@ -8,7 +8,7 @@ export function isDefinedIcon(icon: Icon): icon is DefinedIcon { export function getIconElement(name: DefinedIcon): SVGElement; export function getIconElement(name: string & NonNullable): undefined; export function getIconElement( - name: DefinedIcon | (string & NonNullable) + name: DefinedIcon | (string & NonNullable), ): SVGElement | undefined { const icon = icons[name as DefinedIcon]; diff --git a/packages/astro/src/runtime/client/dev-toolbar/ui-library/window.ts b/packages/astro/src/runtime/client/dev-toolbar/ui-library/window.ts index 35cd0aa677..8b040ab441 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/ui-library/window.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/ui-library/window.ts @@ -18,7 +18,7 @@ export class DevToolbarWindow extends HTMLElement { set placement(value) { if (!isValidPlacement(value)) { settings.logger.error( - `Invalid placement: ${value}, expected one of ${placements.join(', ')}, got ${value}.` + `Invalid placement: ${value}, expected one of ${placements.join(', ')}, got ${value}.`, ); return; } diff --git a/packages/astro/src/runtime/server/astro-component.ts b/packages/astro/src/runtime/server/astro-component.ts index 9acc099a9d..928d23ad82 100644 --- a/packages/astro/src/runtime/server/astro-component.ts +++ b/packages/astro/src/runtime/server/astro-component.ts @@ -10,7 +10,7 @@ function validateArgs(args: unknown[]): args is Parameters) => { @@ -44,7 +44,7 @@ function createComponentWithOptions(opts: CreateComponentOptions) { export function createComponent( arg1: AstroComponentFactory | CreateComponentOptions, moduleId?: string, - propagation?: PropagationHint + propagation?: PropagationHint, ) { if (typeof arg1 === 'function') { return baseCreateComponent(arg1, moduleId, propagation); diff --git a/packages/astro/src/runtime/server/astro-island.ts b/packages/astro/src/runtime/server/astro-island.ts index 22d9dd00a5..3c0404435a 100644 --- a/packages/astro/src/runtime/server/astro-island.ts +++ b/packages/astro/src/runtime/server/astro-island.ts @@ -8,7 +8,7 @@ declare const Astro: { [k in directiveAstroKeys]?: ( fn: () => Promise<() => void>, opts: Record, - root: HTMLElement + root: HTMLElement, ) => unknown; }; @@ -123,7 +123,7 @@ declare const Astro: { return this.hydrate; }, opts, - this + this, ); } catch (e) { // eslint-disable-next-line no-console @@ -182,7 +182,7 @@ declare const Astro: { console.error( `[hydrate] Error parsing props for component ${componentName}`, this.getAttribute('props'), - e + e, ); throw e; } @@ -195,7 +195,7 @@ declare const Astro: { if (process.env.NODE_ENV === 'development' && hydrationTimeStart) this.setAttribute( 'client-render-time', - (performance.now() - hydrationTimeStart).toString() + (performance.now() - hydrationTimeStart).toString(), ); this.removeAttribute('ssr'); this.dispatchEvent(new CustomEvent('astro:hydrate')); diff --git a/packages/astro/src/runtime/server/endpoint.ts b/packages/astro/src/runtime/server/endpoint.ts index 8cd6763912..900d604fd5 100644 --- a/packages/astro/src/runtime/server/endpoint.ts +++ b/packages/astro/src/runtime/server/endpoint.ts @@ -10,7 +10,7 @@ export async function renderEndpoint( mod: EndpointHandler, context: APIContext, ssr: boolean, - logger: Logger + logger: Logger, ) { const { request, url } = context; @@ -21,8 +21,8 @@ export async function renderEndpoint( logger.warn( 'router', `${url.pathname} ${bold( - method - )} requests are not available for a static site. Update your config to \`output: 'server'\` or \`output: 'hybrid'\` to enable.` + method, + )} requests are not available for a static site. Update your config to \`output: 'server'\` or \`output: 'hybrid'\` to enable.`, ); } if (handler === undefined) { @@ -34,7 +34,7 @@ export async function renderEndpoint( .join(', ')}\n` + ('all' in mod ? `One of the exported handlers is "all" (lowercase), did you mean to export 'ALL'?\n` - : '') + : ''), ); // No handler matching the verb found, so this should be a // 404. Should be handled by 404.astro route if possible. @@ -45,7 +45,7 @@ export async function renderEndpoint( 'router', `The route "${ url.pathname - }" exports a value for the method "${method}", but it is of the type ${typeof handler} instead of a function.` + }" exports a value for the method "${method}", but it is of the type ${typeof handler} instead of a function.`, ); return new Response(null, { status: 500 }); } diff --git a/packages/astro/src/runtime/server/escape.ts b/packages/astro/src/runtime/server/escape.ts index 6674b08ffe..1dbfd3725a 100644 --- a/packages/astro/src/runtime/server/escape.ts +++ b/packages/astro/src/runtime/server/escape.ts @@ -82,7 +82,7 @@ function* unescapeChunks(iterable: Iterable): any { } export function unescapeHTML( - str: any + str: any, ): | BlessedType | Promise> diff --git a/packages/astro/src/runtime/server/hydration.ts b/packages/astro/src/runtime/server/hydration.ts index 28b5ff674e..ab6396566b 100644 --- a/packages/astro/src/runtime/server/hydration.ts +++ b/packages/astro/src/runtime/server/hydration.ts @@ -34,7 +34,7 @@ const transitionDirectivesToCopyOnIsland = Object.freeze([ // Finds these special props and removes them from what gets passed into the component. export function extractDirectives( inputProps: Props, - clientDirectives: SSRResult['clientDirectives'] + clientDirectives: SSRResult['clientDirectives'], ): ExtractedProps { let extracted: ExtractedProps = { isPage: false, @@ -84,7 +84,7 @@ export function extractDirectives( .map((d) => `client:${d}`) .join(', '); throw new Error( - `Error: invalid hydration directive "${key}". Supported hydration methods: ${hydrationMethods}` + `Error: invalid hydration directive "${key}". Supported hydration methods: ${hydrationMethods}`, ); } @@ -125,7 +125,7 @@ interface HydrateScriptOptions { /** For hydrated components, generate a `); @@ -38,7 +38,7 @@ export async function handle500Response( writeHtmlResponse( res, 500, - `${err.name}` + `${err.name}`, ); } } @@ -102,7 +102,7 @@ export async function writeWebResponse(res: http.ServerResponse, webResponse: Re export async function writeSSRResult( webRequest: Request, webResponse: Response, - res: http.ServerResponse + res: http.ServerResponse, ) { Reflect.set(webRequest, Symbol.for('astro.responseSent'), true); return writeWebResponse(res, webResponse); diff --git a/packages/astro/src/vite-plugin-astro-server/route.ts b/packages/astro/src/vite-plugin-astro-server/route.ts index 07d6cd2b14..aa70d53245 100644 --- a/packages/astro/src/vite-plugin-astro-server/route.ts +++ b/packages/astro/src/vite-plugin-astro-server/route.ts @@ -47,7 +47,7 @@ function getCustom500Route(manifestData: ManifestData): RouteData | undefined { export async function matchRoute( pathname: string, manifestData: ManifestData, - pipeline: DevPipeline + pipeline: DevPipeline, ): Promise { const { config, logger, routeCache, serverLike, settings } = pipeline; const matches = matchAllRoutes(pathname, manifestData); @@ -97,8 +97,8 @@ export async function matchRoute( logger.warn( 'router', `${AstroErrorData.NoMatchingStaticPathFound.message( - pathname - )}\n\n${AstroErrorData.NoMatchingStaticPathFound.hint(possibleRoutes)}` + pathname, + )}\n\n${AstroErrorData.NoMatchingStaticPathFound.hint(possibleRoutes)}`, ); } @@ -234,7 +234,7 @@ export async function handleRoute({ statusCode: isRewrite ? response.status : status ?? response.status, isRewrite, reqTime: timeEnd - timeStart, - }) + }), ); } if (response.status === 404 && response.headers.get(REROUTE_DIRECTIVE_HEADER) !== 'no') { diff --git a/packages/astro/src/vite-plugin-astro-server/scripts.ts b/packages/astro/src/vite-plugin-astro-server/scripts.ts index 4b94d12f57..e21d441163 100644 --- a/packages/astro/src/vite-plugin-astro-server/scripts.ts +++ b/packages/astro/src/vite-plugin-astro-server/scripts.ts @@ -9,7 +9,7 @@ import { crawlGraph } from './vite.js'; export async function getScriptsForURL( filePath: URL, root: URL, - loader: ModuleLoader + loader: ModuleLoader, ): Promise<{ scripts: Set; crawledFiles: Set }> { const elements = new Set(); const crawledFiles = new Set(); diff --git a/packages/astro/src/vite-plugin-astro-server/vite.ts b/packages/astro/src/vite-plugin-astro-server/vite.ts index bd327081b5..1478539542 100644 --- a/packages/astro/src/vite-plugin-astro-server/vite.ts +++ b/packages/astro/src/vite-plugin-astro-server/vite.ts @@ -18,7 +18,7 @@ export async function* crawlGraph( loader: ModuleLoader, _id: string, isRootFile: boolean, - scanned = new Set() + scanned = new Set(), ): AsyncGenerator { const id = unwrapId(_id); const importedModules = new Set(); diff --git a/packages/astro/src/vite-plugin-astro/compile.ts b/packages/astro/src/vite-plugin-astro/compile.ts index c7845568a8..8dfb68a16f 100644 --- a/packages/astro/src/vite-plugin-astro/compile.ts +++ b/packages/astro/src/vite-plugin-astro/compile.ts @@ -61,12 +61,12 @@ export async function compileAstro({ const { fileId: file, fileUrl: url } = getFileInfo( compileProps.filename, - compileProps.astroConfig + compileProps.astroConfig, ); let SUFFIX = ''; SUFFIX += `\nconst $$file = ${JSON.stringify(file)};\nconst $$url = ${JSON.stringify( - url + url, )};export { $$file as file, $$url as url };\n`; // Add HMR handling in dev mode. @@ -126,7 +126,7 @@ async function enhanceCompileError({ if (frontmatterErr?.message) { frontmatterErr.message = frontmatterErr.message.replace( 'end of file', - 'end of frontmatter' + 'end of frontmatter', ); } throw frontmatterErr; diff --git a/packages/astro/src/vite-plugin-astro/hmr.ts b/packages/astro/src/vite-plugin-astro/hmr.ts index 17c10e7682..93fecc7aa1 100644 --- a/packages/astro/src/vite-plugin-astro/hmr.ts +++ b/packages/astro/src/vite-plugin-astro/hmr.ts @@ -10,7 +10,7 @@ export interface HandleHotUpdateOptions { export async function handleHotUpdate( ctx: HmrContext, - { logger, astroFileToCompileMetadata }: HandleHotUpdateOptions + { logger, astroFileToCompileMetadata }: HandleHotUpdateOptions, ) { // HANDLING 1: Invalidate compile metadata if CSS dependency updated // diff --git a/packages/astro/src/vite-plugin-astro/index.ts b/packages/astro/src/vite-plugin-astro/index.ts index 456b7677de..d5968a9059 100644 --- a/packages/astro/src/vite-plugin-astro/index.ts +++ b/packages/astro/src/vite-plugin-astro/index.ts @@ -112,7 +112,7 @@ export default function astro({ settings, logger }: AstroPluginOptions): vite.Pl if (!compileMetadata) { throw new Error( `No cached compile metadata found for "${id}". The main Astro module "${filename}" should have ` + - `compiled and filled the metadata first, before its virtual modules can be requested.` + `compiled and filled the metadata first, before its virtual modules can be requested.`, ); } @@ -166,7 +166,7 @@ export default function astro({ settings, logger }: AstroPluginOptions): vite.Pl if (src.startsWith('/') && !isBrowserPath(src)) { const publicDir = config.publicDir.pathname.replace(/\/$/, '').split('/').pop() + '/'; throw new Error( - `\n\n