mirror of
https://github.com/withastro/astro.git
synced 2024-12-16 21:46:22 -05:00
update formatter config (#11640)
* update formatter config * format --------- Co-authored-by: Erika <3019731+Princesseuh@users.noreply.github.com>
This commit is contained in:
parent
85de47cd98
commit
72c7ae9901
492 changed files with 1863 additions and 1848 deletions
|
@ -29,7 +29,7 @@
|
||||||
"linter": { "enabled": false },
|
"linter": { "enabled": false },
|
||||||
"javascript": {
|
"javascript": {
|
||||||
"formatter": {
|
"formatter": {
|
||||||
"trailingCommas": "es5",
|
"trailingCommas": "all",
|
||||||
"quoteStyle": "single",
|
"quoteStyle": "single",
|
||||||
"semicolons": "always"
|
"semicolons": "always"
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,7 +7,7 @@ import { getCollection } from 'astro:content';
|
||||||
import FormattedDate from '../../components/FormattedDate.astro';
|
import FormattedDate from '../../components/FormattedDate.astro';
|
||||||
|
|
||||||
const posts = (await getCollection('blog')).sort(
|
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(),
|
||||||
);
|
);
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
@ -9,7 +9,7 @@ import Hero from '../components/Hero.astro';
|
||||||
import Grid from '../components/Grid.astro';
|
import Grid from '../components/Grid.astro';
|
||||||
|
|
||||||
const projects = (await getCollection('work')).sort(
|
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(),
|
||||||
);
|
);
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|
|
@ -29,6 +29,6 @@ runHighlighterWithAstro(
|
||||||
|
|
||||||
<div>{helloAstro}</div>
|
<div>{helloAstro}</div>
|
||||||
`,
|
`,
|
||||||
'astro'
|
'astro',
|
||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|
|
@ -10,7 +10,7 @@ export function addAstro(Prism: typeof import('prismjs')) {
|
||||||
scriptLang = 'javascript';
|
scriptLang = 'javascript';
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
console.warn(
|
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(
|
(Prism.languages.astro as any).tag.pattern = re(
|
||||||
/<\/?(?:[\w.:-]+(?:<S>+(?:[\w.:$-]+(?:=(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s{'"/>=]+|<BRACES>))?|<SPREAD>))*<S>*\/?)?>/
|
/<\/?(?:[\w.:-]+(?:<S>+(?:[\w.:$-]+(?:=(?:"(?:\\[\s\S]|[^\\"])*"|'(?:\\[\s\S]|[^\\'])*'|[^\s{'"/>=]+|<BRACES>))?|<SPREAD>))*<S>*\/?)?>/
|
||||||
.source
|
.source,
|
||||||
);
|
);
|
||||||
|
|
||||||
(Prism.languages.astro as any).tag.inside['tag'].pattern = /^<\/?[^\s>/]*/;
|
(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,
|
inside: Prism.languages.astro,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
(Prism.languages.astro as any).tag
|
(Prism.languages.astro as any).tag,
|
||||||
);
|
);
|
||||||
|
|
||||||
Prism.languages.insertBefore(
|
Prism.languages.insertBefore(
|
||||||
|
@ -80,7 +80,7 @@ export function addAstro(Prism: typeof import('prismjs')) {
|
||||||
alias: `language-${scriptLang}`,
|
alias: `language-${scriptLang}`,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
(Prism.languages.astro as any).tag
|
(Prism.languages.astro as any).tag,
|
||||||
);
|
);
|
||||||
|
|
||||||
// The following will handle plain text inside tags
|
// The following will handle plain text inside tags
|
||||||
|
|
|
@ -73,8 +73,8 @@ const rssOptionsValidator = z.object({
|
||||||
// eslint-disable-next-line
|
// eslint-disable-next-line
|
||||||
console.warn(
|
console.warn(
|
||||||
yellow(
|
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);
|
return pagesGlobToRssItems(items);
|
||||||
}
|
}
|
||||||
|
@ -123,7 +123,7 @@ async function validateRssOptions(rssOptions: RSSOptions) {
|
||||||
|
|
||||||
return message;
|
return message;
|
||||||
}),
|
}),
|
||||||
].join('\n')
|
].join('\n'),
|
||||||
);
|
);
|
||||||
throw formattedError;
|
throw formattedError;
|
||||||
}
|
}
|
||||||
|
@ -134,7 +134,7 @@ export function pagesGlobToRssItems(items: GlobResult): Promise<ValidatedRSSFeed
|
||||||
const { url, frontmatter } = await getInfo();
|
const { url, frontmatter } = await getInfo();
|
||||||
if (url === undefined || url === null) {
|
if (url === undefined || url === null) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`[RSS] You can only glob entries within 'src/pages/' when passing import.meta.glob() directly. Consider mapping the result to an array of RSSFeedItems. See the RSS docs for usage examples: https://docs.astro.build/en/guides/rss/#2-list-of-rss-feed-objects`
|
`[RSS] You can only glob entries within 'src/pages/' when passing import.meta.glob() directly. Consider mapping the result to an array of RSSFeedItems. See the RSS docs for usage examples: https://docs.astro.build/en/guides/rss/#2-list-of-rss-feed-objects`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const parsedResult = rssSchema
|
const parsedResult = rssSchema
|
||||||
|
@ -151,11 +151,11 @@ export function pagesGlobToRssItems(items: GlobResult): Promise<ValidatedRSSFeed
|
||||||
[
|
[
|
||||||
`[RSS] ${filePath} has invalid or missing frontmatter.\nFix the following properties:`,
|
`[RSS] ${filePath} has invalid or missing frontmatter.\nFix the following properties:`,
|
||||||
...parsedResult.error.errors.map((zodError) => zodError.message),
|
...parsedResult.error.errors.map((zodError) => zodError.message),
|
||||||
].join('\n')
|
].join('\n'),
|
||||||
);
|
);
|
||||||
(formattedError as any).file = filePath;
|
(formattedError as any).file = filePath;
|
||||||
throw formattedError;
|
throw formattedError;
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -207,7 +207,7 @@ async function generateRSS(rssOptions: ValidatedRSSOptions): Promise<string> {
|
||||||
if (typeof rssOptions.customData === 'string')
|
if (typeof rssOptions.customData === 'string')
|
||||||
Object.assign(
|
Object.assign(
|
||||||
root.rss.channel,
|
root.rss.channel,
|
||||||
parser.parse(`<channel>${rssOptions.customData}</channel>`).channel
|
parser.parse(`<channel>${rssOptions.customData}</channel>`).channel,
|
||||||
);
|
);
|
||||||
// items
|
// items
|
||||||
root.rss.channel.item = items.map((result) => {
|
root.rss.channel.item = items.map((result) => {
|
||||||
|
@ -250,7 +250,7 @@ async function generateRSS(rssOptions: ValidatedRSSOptions): Promise<string> {
|
||||||
}
|
}
|
||||||
if (result.source) {
|
if (result.source) {
|
||||||
item.source = parser.parse(
|
item.source = parser.parse(
|
||||||
`<source url="${result.source.url}">${result.source.title}</source>`
|
`<source url="${result.source.url}">${result.source.title}</source>`,
|
||||||
).source;
|
).source;
|
||||||
}
|
}
|
||||||
if (result.enclosure) {
|
if (result.enclosure) {
|
||||||
|
@ -258,7 +258,7 @@ async function generateRSS(rssOptions: ValidatedRSSOptions): Promise<string> {
|
||||||
? result.enclosure.url
|
? result.enclosure.url
|
||||||
: createCanonicalURL(result.enclosure.url, rssOptions.trailingSlash, site);
|
: createCanonicalURL(result.enclosure.url, rssOptions.trailingSlash, site);
|
||||||
item.enclosure = parser.parse(
|
item.enclosure = parser.parse(
|
||||||
`<enclosure url="${enclosureURL}" length="${result.enclosure.length}" type="${result.enclosure.type}"/>`
|
`<enclosure url="${enclosureURL}" length="${result.enclosure.length}" type="${result.enclosure.type}"/>`,
|
||||||
).enclosure;
|
).enclosure;
|
||||||
}
|
}
|
||||||
return item;
|
return item;
|
||||||
|
|
|
@ -5,7 +5,7 @@ import type { RSSOptions } from './index.js';
|
||||||
export function createCanonicalURL(
|
export function createCanonicalURL(
|
||||||
url: string,
|
url: string,
|
||||||
trailingSlash?: RSSOptions['trailingSlash'],
|
trailingSlash?: RSSOptions['trailingSlash'],
|
||||||
base?: string
|
base?: string,
|
||||||
): string {
|
): string {
|
||||||
let pathname = url.replace(/\/index.html$/, ''); // index.html is not canonical
|
let pathname = url.replace(/\/index.html$/, ''); // index.html is not canonical
|
||||||
if (!getUrlExtension(url)) {
|
if (!getUrlExtension(url)) {
|
||||||
|
|
|
@ -16,7 +16,7 @@ describe('pagesGlobToRssItems', () => {
|
||||||
pubDate: phpFeedItem.pubDate,
|
pubDate: phpFeedItem.pubDate,
|
||||||
description: phpFeedItem.description,
|
description: phpFeedItem.description,
|
||||||
},
|
},
|
||||||
})
|
}),
|
||||||
),
|
),
|
||||||
'./posts/nested/web1.md': () =>
|
'./posts/nested/web1.md': () =>
|
||||||
new Promise((resolve) =>
|
new Promise((resolve) =>
|
||||||
|
@ -27,7 +27,7 @@ describe('pagesGlobToRssItems', () => {
|
||||||
pubDate: web1FeedItem.pubDate,
|
pubDate: web1FeedItem.pubDate,
|
||||||
description: web1FeedItem.description,
|
description: web1FeedItem.description,
|
||||||
},
|
},
|
||||||
})
|
}),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -49,7 +49,7 @@ describe('pagesGlobToRssItems', () => {
|
||||||
|
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
items.sort((a, b) => a.pubDate - b.pubDate),
|
items.sort((a, b) => a.pubDate - b.pubDate),
|
||||||
expected
|
expected,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -63,7 +63,7 @@ describe('pagesGlobToRssItems', () => {
|
||||||
pubDate: phpFeedItem.pubDate,
|
pubDate: phpFeedItem.pubDate,
|
||||||
description: phpFeedItem.description,
|
description: phpFeedItem.description,
|
||||||
},
|
},
|
||||||
})
|
}),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
return assert.rejects(pagesGlobToRssItems(globResult));
|
return assert.rejects(pagesGlobToRssItems(globResult));
|
||||||
|
@ -80,7 +80,7 @@ describe('pagesGlobToRssItems', () => {
|
||||||
pubDate: phpFeedItem.pubDate,
|
pubDate: phpFeedItem.pubDate,
|
||||||
description: undefined,
|
description: undefined,
|
||||||
},
|
},
|
||||||
})
|
}),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
return assert.rejects(pagesGlobToRssItems(globResult));
|
return assert.rejects(pagesGlobToRssItems(globResult));
|
||||||
|
@ -97,7 +97,7 @@ describe('pagesGlobToRssItems', () => {
|
||||||
pubDate: phpFeedItem.pubDate,
|
pubDate: phpFeedItem.pubDate,
|
||||||
description: phpFeedItem.description,
|
description: phpFeedItem.description,
|
||||||
},
|
},
|
||||||
})
|
}),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
return assert.doesNotReject(pagesGlobToRssItems(globResult));
|
return assert.doesNotReject(pagesGlobToRssItems(globResult));
|
||||||
|
@ -114,7 +114,7 @@ describe('pagesGlobToRssItems', () => {
|
||||||
pubDate: phpFeedItem.pubDate,
|
pubDate: phpFeedItem.pubDate,
|
||||||
description: undefined,
|
description: undefined,
|
||||||
},
|
},
|
||||||
})
|
}),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
return assert.doesNotReject(pagesGlobToRssItems(globResult));
|
return assert.doesNotReject(pagesGlobToRssItems(globResult));
|
||||||
|
|
|
@ -191,7 +191,7 @@ describe('getRssString', () => {
|
||||||
pubDate: phpFeedItem.pubDate,
|
pubDate: phpFeedItem.pubDate,
|
||||||
description: phpFeedItem.description,
|
description: phpFeedItem.description,
|
||||||
},
|
},
|
||||||
})
|
}),
|
||||||
),
|
),
|
||||||
'./posts/nested/web1.md': () =>
|
'./posts/nested/web1.md': () =>
|
||||||
new Promise((resolve) =>
|
new Promise((resolve) =>
|
||||||
|
@ -202,7 +202,7 @@ describe('getRssString', () => {
|
||||||
pubDate: web1FeedItem.pubDate,
|
pubDate: web1FeedItem.pubDate,
|
||||||
description: web1FeedItem.description,
|
description: web1FeedItem.description,
|
||||||
},
|
},
|
||||||
})
|
}),
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
@ -1127,7 +1127,7 @@
|
||||||
export function Like({ postId }: { postId: string }) {
|
export function Like({ postId }: { postId: string }) {
|
||||||
const [state, action, pending] = useActionState(
|
const [state, action, pending] = useActionState(
|
||||||
experimental_withState(actions.like),
|
experimental_withState(actions.like),
|
||||||
0 // initial likes
|
0, // initial likes
|
||||||
);
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
@ -1341,7 +1341,7 @@
|
||||||
{
|
{
|
||||||
site: 'https://example.com',
|
site: 'https://example.com',
|
||||||
trailingSlash: 'never',
|
trailingSlash: 'never',
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -1714,7 +1714,7 @@
|
||||||
middleware({
|
middleware({
|
||||||
redirectToDefaultLocale: false,
|
redirectToDefaultLocale: false,
|
||||||
prefixDefaultLocale: true,
|
prefixDefaultLocale: true,
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -1985,7 +1985,7 @@
|
||||||
detail: {
|
detail: {
|
||||||
level: 'warning',
|
level: 'warning',
|
||||||
},
|
},
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -6675,7 +6675,7 @@
|
||||||
const hydrate = await load();
|
const hydrate = await load();
|
||||||
await hydrate();
|
await hydrate();
|
||||||
},
|
},
|
||||||
{ once: true }
|
{ once: true },
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -8970,7 +8970,7 @@
|
||||||
{ darkMode: true },
|
{ darkMode: true },
|
||||||
{
|
{
|
||||||
expires: '1 month',
|
expires: '1 month',
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
const prefs = Astro.cookies.get<Prefs>('prefs').json();
|
const prefs = Astro.cookies.get<Prefs>('prefs').json();
|
||||||
|
|
|
@ -66,7 +66,7 @@ Please upgrade Node.js to a supported version: "${engines}"\n`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
console.log(
|
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/`);
|
console.log(`Documentation: https://docs.astro.build/en/guides/deploy/`);
|
||||||
if (CI_INSTRUCTIONS[platform]) {
|
if (CI_INSTRUCTIONS[platform]) {
|
||||||
|
|
2
packages/astro/client.d.ts
vendored
2
packages/astro/client.d.ts
vendored
|
@ -50,7 +50,7 @@ declare module 'astro:assets' {
|
||||||
* This is functionally equivalent to using the `<Image />` component, as the component calls this function internally.
|
* This is functionally equivalent to using the `<Image />` component, as the component calls this function internally.
|
||||||
*/
|
*/
|
||||||
getImage: (
|
getImage: (
|
||||||
options: import('./dist/assets/types.js').UnresolvedImageTransform
|
options: import('./dist/assets/types.js').UnresolvedImageTransform,
|
||||||
) => Promise<import('./dist/assets/types.js').GetImageResult>;
|
) => Promise<import('./dist/assets/types.js').GetImageResult>;
|
||||||
imageConfig: import('./dist/@types/astro.js').AstroConfig['image'];
|
imageConfig: import('./dist/@types/astro.js').AstroConfig['image'];
|
||||||
getConfiguredImageService: typeof import('./dist/assets/index.js').getConfiguredImageService;
|
getConfiguredImageService: typeof import('./dist/assets/index.js').getConfiguredImageService;
|
||||||
|
|
|
@ -53,8 +53,8 @@ const optimizedImages: GetImageResult[] = await Promise.all(
|
||||||
format: format,
|
format: format,
|
||||||
widths: props.widths,
|
widths: props.widths,
|
||||||
densities: props.densities,
|
densities: props.densities,
|
||||||
})
|
}),
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
let resultFallbackFormat = fallbackFormat ?? defaultFallbackFormat;
|
let resultFallbackFormat = fallbackFormat ?? defaultFallbackFormat;
|
||||||
|
|
|
@ -53,7 +53,7 @@ const { fallback = 'animate' } = Astro.props;
|
||||||
if (supportsViewTransitions || getFallback() !== 'none') {
|
if (supportsViewTransitions || getFallback() !== 'none') {
|
||||||
if (import.meta.env.DEV && window.matchMedia('(prefers-reduced-motion)').matches) {
|
if (import.meta.env.DEV && window.matchMedia('(prefers-reduced-motion)').matches) {
|
||||||
console.warn(
|
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) => {
|
document.addEventListener('click', (ev) => {
|
||||||
|
|
2
packages/astro/config.d.ts
vendored
2
packages/astro/config.d.ts
vendored
|
@ -17,7 +17,7 @@ export function defineConfig(config: AstroUserConfig): AstroUserConfig;
|
||||||
*/
|
*/
|
||||||
export function getViteConfig(
|
export function getViteConfig(
|
||||||
config: ViteUserConfig,
|
config: ViteUserConfig,
|
||||||
inlineAstroConfig?: AstroInlineConfig
|
inlineAstroConfig?: AstroInlineConfig,
|
||||||
): ViteUserConfigFn;
|
): ViteUserConfigFn;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -20,25 +20,25 @@ test.describe('Astro component HMR', () => {
|
||||||
const hero = page.locator('section');
|
const hero = page.locator('section');
|
||||||
await expect(hero, 'hero has background: white').toHaveCSS(
|
await expect(hero, 'hero has background: white').toHaveCSS(
|
||||||
'background-color',
|
'background-color',
|
||||||
'rgb(255, 255, 255)'
|
'rgb(255, 255, 255)',
|
||||||
);
|
);
|
||||||
await expect(hero, 'hero has color: black').toHaveCSS('color', 'rgb(0, 0, 0)');
|
await expect(hero, 'hero has color: black').toHaveCSS('color', 'rgb(0, 0, 0)');
|
||||||
|
|
||||||
// Edit the Hero component with a new background color
|
// Edit the Hero component with a new background color
|
||||||
await astro.editFile('./src/components/Hero.astro', (content) =>
|
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(
|
await expect(hero, 'background color updated').toHaveCSS(
|
||||||
'background-color',
|
'background-color',
|
||||||
'rgb(230, 230, 230)'
|
'rgb(230, 230, 230)',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('hoisted scripts', async ({ page, astro }) => {
|
test('hoisted scripts', async ({ page, astro }) => {
|
||||||
const initialLog = page.waitForEvent(
|
const initialLog = page.waitForEvent(
|
||||||
'console',
|
'console',
|
||||||
(message) => message.text() === 'Hello, Astro!'
|
(message) => message.text() === 'Hello, Astro!',
|
||||||
);
|
);
|
||||||
|
|
||||||
await page.goto(astro.resolveUrl('/'));
|
await page.goto(astro.resolveUrl('/'));
|
||||||
|
@ -49,12 +49,12 @@ test.describe('Astro component HMR', () => {
|
||||||
|
|
||||||
const updatedLog = page.waitForEvent(
|
const updatedLog = page.waitForEvent(
|
||||||
'console',
|
'console',
|
||||||
(message) => message.text() === 'Hello, updated Astro!'
|
(message) => message.text() === 'Hello, updated Astro!',
|
||||||
);
|
);
|
||||||
|
|
||||||
// Edit the hoisted script on the page
|
// Edit the hoisted script on the page
|
||||||
await astro.editFile('./src/pages/index.astro', (content) =>
|
await astro.editFile('./src/pages/index.astro', (content) =>
|
||||||
content.replace('Hello, Astro!', 'Hello, updated Astro!')
|
content.replace('Hello, Astro!', 'Hello, updated Astro!'),
|
||||||
);
|
);
|
||||||
|
|
||||||
await updatedLog;
|
await updatedLog;
|
||||||
|
@ -63,7 +63,7 @@ test.describe('Astro component HMR', () => {
|
||||||
test('inline scripts', async ({ page, astro }) => {
|
test('inline scripts', async ({ page, astro }) => {
|
||||||
const initialLog = page.waitForEvent(
|
const initialLog = page.waitForEvent(
|
||||||
'console',
|
'console',
|
||||||
(message) => message.text() === 'Hello, inline Astro!'
|
(message) => message.text() === 'Hello, inline Astro!',
|
||||||
);
|
);
|
||||||
|
|
||||||
await page.goto(astro.resolveUrl('/'));
|
await page.goto(astro.resolveUrl('/'));
|
||||||
|
@ -71,12 +71,12 @@ test.describe('Astro component HMR', () => {
|
||||||
|
|
||||||
const updatedLog = page.waitForEvent(
|
const updatedLog = page.waitForEvent(
|
||||||
'console',
|
'console',
|
||||||
(message) => message.text() === 'Hello, updated inline Astro!'
|
(message) => message.text() === 'Hello, updated inline Astro!',
|
||||||
);
|
);
|
||||||
|
|
||||||
// Edit the inline script on the page
|
// Edit the inline script on the page
|
||||||
await astro.editFile('./src/pages/index.astro', (content) =>
|
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;
|
await updatedLog;
|
||||||
|
@ -89,7 +89,7 @@ test.describe('Astro component HMR', () => {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
page.waitForLoadState('networkidle'),
|
page.waitForLoadState('networkidle'),
|
||||||
await astro.editFile('../_deps/astro-linked-lib/Component.astro', (content) =>
|
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');
|
h1 = page.locator('#astro-linked-lib');
|
||||||
|
@ -103,7 +103,7 @@ test.describe('Astro component HMR', () => {
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
page.waitForLoadState('networkidle'),
|
page.waitForLoadState('networkidle'),
|
||||||
await astro.editFile('../_deps/astro-linked-lib/Component.astro', (content) =>
|
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');
|
h1 = page.locator('#astro-linked-lib');
|
||||||
|
|
|
@ -35,7 +35,7 @@ test.describe('Astro Environment BASE_URL', () => {
|
||||||
|
|
||||||
const clientComponentBaseUrl = page.locator('id=client-component-base-url');
|
const clientComponentBaseUrl = page.locator('id=client-component-base-url');
|
||||||
await expect(clientComponentBaseUrl, 'clientComponentBaseUrl equals to /blog').toHaveText(
|
await expect(clientComponentBaseUrl, 'clientComponentBaseUrl equals to /blog').toHaveText(
|
||||||
'/blog'
|
'/blog',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -19,7 +19,7 @@ test.describe('Content Collections', () => {
|
||||||
await page.goto(astro.resolveUrl('/'));
|
await page.goto(astro.resolveUrl('/'));
|
||||||
|
|
||||||
await astro.editFile('./src/components/MyComponent.astro', (original) =>
|
await astro.editFile('./src/components/MyComponent.astro', (original) =>
|
||||||
original.replace('red', 'green')
|
original.replace('red', 'green'),
|
||||||
);
|
);
|
||||||
|
|
||||||
const h1 = page.locator('#my-heading');
|
const h1 = page.locator('#my-heading');
|
||||||
|
|
|
@ -26,7 +26,7 @@ test.describe('CSS HMR', () => {
|
||||||
await expect(h).toHaveCSS('color', 'rgb(255, 0, 0)');
|
await expect(h).toHaveCSS('color', 'rgb(255, 0, 0)');
|
||||||
|
|
||||||
await astro.editFile('./src/styles/main.css', (original) =>
|
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)');
|
await expect(h).toHaveCSS('color', 'rgb(0, 128, 0)');
|
||||||
|
|
|
@ -98,7 +98,7 @@ function testClientDirectivesShared() {
|
||||||
|
|
||||||
const clientOptions = page.locator('#options');
|
const clientOptions = page.locator('#options');
|
||||||
await expect(clientOptions).toHaveText(
|
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"}',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
@ -79,7 +79,7 @@ test.describe('Dev Toolbar - Audits', () => {
|
||||||
'astro:dev-toolbar:settings',
|
'astro:dev-toolbar:settings',
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
verbose: true,
|
verbose: true,
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -93,7 +93,7 @@ test.describe('Dev Toolbar - Audits', () => {
|
||||||
const badButton = page.locator('#bad-button');
|
const badButton = page.locator('#bad-button');
|
||||||
|
|
||||||
let consolePromise = page.waitForEvent('console', (msg) =>
|
let consolePromise = page.waitForEvent('console', (msg) =>
|
||||||
msg.text().includes('Rerunning audit lints')
|
msg.text().includes('Rerunning audit lints'),
|
||||||
);
|
);
|
||||||
await badButton.click({ clickCount: 5 });
|
await badButton.click({ clickCount: 5 });
|
||||||
await consolePromise;
|
await consolePromise;
|
||||||
|
@ -102,7 +102,7 @@ test.describe('Dev Toolbar - Audits', () => {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
logs.filter((log) => log.includes('Rerunning audit lints because the DOM has been updated'))
|
logs.filter((log) => log.includes('Rerunning audit lints because the DOM has been updated'))
|
||||||
.length === 1
|
.length === 1,
|
||||||
).toBe(true);
|
).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -114,7 +114,7 @@ test.describe('Dev Toolbar - Audits', () => {
|
||||||
'astro:dev-toolbar:settings',
|
'astro:dev-toolbar:settings',
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
verbose: true,
|
verbose: true,
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -153,7 +153,7 @@ test.describe('Dev Toolbar - Audits', () => {
|
||||||
// Make sure we only reran audits once
|
// Make sure we only reran audits once
|
||||||
expect(
|
expect(
|
||||||
logs.filter((log) => log.includes('Rerunning audit lints because the DOM has been updated'))
|
logs.filter((log) => log.includes('Rerunning audit lints because the DOM has been updated'))
|
||||||
.length === 1
|
.length === 1,
|
||||||
).toBe(true);
|
).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
|
@ -42,7 +42,7 @@ test.describe('Dev Toolbar', () => {
|
||||||
await appButton.click();
|
await appButton.click();
|
||||||
|
|
||||||
const astroAppCanvas = toolbar.locator(
|
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');
|
const astroWindow = astroAppCanvas.locator('astro-dev-toolbar-window');
|
||||||
await expect(astroWindow).toHaveCount(1);
|
await expect(astroWindow).toHaveCount(1);
|
||||||
|
@ -152,7 +152,7 @@ test.describe('Dev Toolbar', () => {
|
||||||
|
|
||||||
const code = xrayHighlightTooltip.locator('pre > code');
|
const code = xrayHighlightTooltip.locator('pre > code');
|
||||||
await expect(code).toHaveText(
|
await expect(code).toHaveText(
|
||||||
JSON.stringify({ name: `<img src='' onerror='alert(1)'>` }, undefined, 2)
|
JSON.stringify({ name: `<img src='' onerror='alert(1)'>` }, undefined, 2),
|
||||||
);
|
);
|
||||||
expect(isAlertCalled).toBe(false);
|
expect(isAlertCalled).toBe(false);
|
||||||
});
|
});
|
||||||
|
@ -264,7 +264,7 @@ test.describe('Dev Toolbar', () => {
|
||||||
await appButton.click();
|
await appButton.click();
|
||||||
|
|
||||||
const settingsAppCanvas = toolbar.locator(
|
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');
|
const settingsWindow = settingsAppCanvas.locator('astro-dev-toolbar-window');
|
||||||
await expect(settingsWindow).toHaveCount(1);
|
await expect(settingsWindow).toHaveCount(1);
|
||||||
|
@ -283,7 +283,7 @@ test.describe('Dev Toolbar', () => {
|
||||||
await appButton.click();
|
await appButton.click();
|
||||||
|
|
||||||
const settingsAppCanvas = toolbar.locator(
|
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');
|
const settingsWindow = settingsAppCanvas.locator('astro-dev-toolbar-window');
|
||||||
await expect(settingsWindow).toHaveCount(1);
|
await expect(settingsWindow).toHaveCount(1);
|
||||||
|
@ -294,7 +294,7 @@ test.describe('Dev Toolbar', () => {
|
||||||
await appButton.click();
|
await appButton.click();
|
||||||
|
|
||||||
const astroAppCanvas = toolbar.locator(
|
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');
|
const astroWindow = astroAppCanvas.locator('astro-dev-toolbar-window');
|
||||||
await expect(astroWindow).toHaveCount(1);
|
await expect(astroWindow).toHaveCount(1);
|
||||||
|
@ -311,7 +311,7 @@ test.describe('Dev Toolbar', () => {
|
||||||
await appButton.click();
|
await appButton.click();
|
||||||
|
|
||||||
const settingsAppCanvas = toolbar.locator(
|
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');
|
const settingsWindow = settingsAppCanvas.locator('astro-dev-toolbar-window');
|
||||||
await expect(settingsWindow).toHaveCount(1);
|
await expect(settingsWindow).toHaveCount(1);
|
||||||
|
@ -389,7 +389,7 @@ test.describe('Dev Toolbar', () => {
|
||||||
await settingsAppButton.click();
|
await settingsAppButton.click();
|
||||||
|
|
||||||
const settingsAppCanvas = toolbar.locator(
|
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');
|
const settingsWindow = settingsAppCanvas.locator('astro-dev-toolbar-window');
|
||||||
await expect(settingsWindow).toBeVisible();
|
await expect(settingsWindow).toBeVisible();
|
||||||
|
@ -423,7 +423,7 @@ test.describe('Dev Toolbar', () => {
|
||||||
await settingsAppButton.click();
|
await settingsAppButton.click();
|
||||||
|
|
||||||
const settingsAppCanvas = toolbar.locator(
|
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');
|
const settingsWindow = settingsAppCanvas.locator('astro-dev-toolbar-window');
|
||||||
await expect(settingsWindow).toBeVisible();
|
await expect(settingsWindow).toBeVisible();
|
||||||
|
|
|
@ -33,7 +33,7 @@ test.describe('Error display', () => {
|
||||||
// Edit the component file
|
// Edit the component file
|
||||||
await astro.editFile(
|
await astro.editFile(
|
||||||
'./src/pages/astro-syntax-error.astro',
|
'./src/pages/astro-syntax-error.astro',
|
||||||
() => `<h1>No syntax error</h1>`
|
() => `<h1>No syntax error</h1>`,
|
||||||
),
|
),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
@ -107,7 +107,7 @@ test.describe('Error display', () => {
|
||||||
// Edit the component file
|
// Edit the component file
|
||||||
astro.editFile(
|
astro.editFile(
|
||||||
'./src/components/svelte/SvelteSyntaxError.svelte',
|
'./src/components/svelte/SvelteSyntaxError.svelte',
|
||||||
() => `<h1>No mismatch</h1>`
|
() => `<h1>No mismatch</h1>`,
|
||||||
),
|
),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
|
|
@ -34,7 +34,7 @@ test.describe('Scripts with dependencies', () => {
|
||||||
await expect(h, 'original text set').toHaveText('before');
|
await expect(h, 'original text set').toHaveText('before');
|
||||||
|
|
||||||
await astro.editFile('./src/scripts/heading.js', (original) =>
|
await astro.editFile('./src/scripts/heading.js', (original) =>
|
||||||
original.replace('before', 'after')
|
original.replace('before', 'after'),
|
||||||
);
|
);
|
||||||
|
|
||||||
await expect(h, 'text changed').toHaveText('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 expect(h).toHaveCSS('color', 'rgb(0, 0, 255)');
|
||||||
|
|
||||||
await astro.editFile('./src/styles/css-external.css', (original) =>
|
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)');
|
await expect(h).toHaveCSS('color', 'rgb(255, 0, 0)');
|
||||||
|
|
|
@ -118,13 +118,13 @@ test.describe('Lit components', () => {
|
||||||
|
|
||||||
// Light DOM reconstructed correctly (slots are rendered alphabetically) and shadow dom content rendered
|
// Light DOM reconstructed correctly (slots are rendered alphabetically) and shadow dom content rendered
|
||||||
await expect(label, 'slotted text is in DOM').toHaveText(
|
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
|
// Projected content should be visible
|
||||||
await expect(
|
await expect(
|
||||||
page.locator('#client-only .default'),
|
page.locator('#client-only .default'),
|
||||||
'slotted element is visible'
|
'slotted element is visible',
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
await expect(page.locator('#client-only .foo1'), '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();
|
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
|
// Non-projected content should not be visible
|
||||||
await expect(
|
await expect(
|
||||||
page.locator('#client-only [slot="quux"]'),
|
page.locator('#client-only [slot="quux"]'),
|
||||||
'element without slot is not visible'
|
'element without slot is not visible',
|
||||||
).toBeHidden();
|
).toBeHidden();
|
||||||
|
|
||||||
// Default slot content should not be visible
|
// Default slot content should not be visible
|
||||||
await expect(
|
await expect(
|
||||||
page.locator('#client-only .defaultContent'),
|
page.locator('#client-only .defaultContent'),
|
||||||
'element without slot is not visible'
|
'element without slot is not visible',
|
||||||
).toBeHidden();
|
).toBeHidden();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -149,7 +149,7 @@ test.describe('Lit components', () => {
|
||||||
const label = counter.locator('h1');
|
const label = counter.locator('h1');
|
||||||
|
|
||||||
await astro.editFile('./src/pages/index.astro', (original) =>
|
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!');
|
await expect(label, 'slot text updated').toHaveText('Hello, updated client:idle!');
|
||||||
|
|
|
@ -109,7 +109,7 @@ test.skip('Multiple frameworks', () => {
|
||||||
await expect(slot, 'initial slot content').toHaveText('Hello Preact!');
|
await expect(slot, 'initial slot content').toHaveText('Hello Preact!');
|
||||||
|
|
||||||
await astro.editFile('./src/pages/index.astro', (content) =>
|
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!');
|
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 expect(count, 'initial count updated to 0').toHaveText('0');
|
||||||
|
|
||||||
await astro.editFile('./src/components/ReactCounter.jsx', (content) =>
|
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');
|
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 expect(count, 'initial count updated to 0').toHaveText('0');
|
||||||
|
|
||||||
await astro.editFile('./src/components/PreactCounter.tsx', (content) =>
|
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');
|
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 expect(count, 'initial count updated to 0').toHaveText('0');
|
||||||
|
|
||||||
await astro.editFile('./src/components/SolidCounter.tsx', (content) =>
|
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');
|
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 expect(count, 'initial count updated to 0').toHaveText('0');
|
||||||
|
|
||||||
await astro.editFile('./src/components/VueCounter.vue', (content) =>
|
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');
|
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 expect(count, 'initial count is 0').toHaveText('0');
|
||||||
|
|
||||||
await astro.editFile('./src/components/SvelteCounter.svelte', (content) =>
|
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');
|
await expect(count, 'initial count updated to 5').toHaveText('5');
|
||||||
|
|
|
@ -34,7 +34,7 @@ test.describe('Loading styles that are nested', () => {
|
||||||
|
|
||||||
await expect(header, 'should have background color').toHaveCSS(
|
await expect(header, 'should have background color').toHaveCSS(
|
||||||
'background-color',
|
'background-color',
|
||||||
'rgb(0, 0, 139)' // darkblue
|
'rgb(0, 0, 139)', // darkblue
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -40,7 +40,7 @@ async function expectUrlPrefetched(url, page, count) {
|
||||||
const fetchCount = reqUrls.filter((u) => u.includes(url)).length;
|
const fetchCount = reqUrls.filter((u) => u.includes(url)).length;
|
||||||
expect(
|
expect(
|
||||||
fetchCount,
|
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);
|
).toEqual(count);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -344,7 +344,7 @@ test.describe('Prefetch (default), Experimental ({ clientPrerender: true })', ()
|
||||||
expect(await scriptIsInHead(page, '?search-param=true')).toBeFalsy();
|
expect(await scriptIsInHead(page, '?search-param=true')).toBeFalsy();
|
||||||
await page.locator('#prefetch-search-param').hover();
|
await page.locator('#prefetch-search-param').hover();
|
||||||
await page.waitForFunction(
|
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();
|
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();
|
expect(await scriptIsInHead(page, '/prefetch-hover')).toBeFalsy();
|
||||||
await page.locator('#prefetch-hover').hover();
|
await page.locator('#prefetch-hover').hover();
|
||||||
await page.waitForFunction(
|
await page.waitForFunction(
|
||||||
() => document.querySelectorAll('script[type=speculationrules]').length === 2
|
() => document.querySelectorAll('script[type=speculationrules]').length === 2,
|
||||||
);
|
);
|
||||||
expect(await scriptIsInHead(page, '/prefetch-hover')).toBeTruthy();
|
expect(await scriptIsInHead(page, '/prefetch-hover')).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
@ -372,7 +372,7 @@ test.describe('Prefetch (default), Experimental ({ clientPrerender: true })', ()
|
||||||
// Scroll down to show the element
|
// Scroll down to show the element
|
||||||
await page.locator('#prefetch-viewport').scrollIntoViewIfNeeded();
|
await page.locator('#prefetch-viewport').scrollIntoViewIfNeeded();
|
||||||
await page.waitForFunction(
|
await page.waitForFunction(
|
||||||
() => document.querySelectorAll('script[type=speculationrules]').length === 2
|
() => document.querySelectorAll('script[type=speculationrules]').length === 2,
|
||||||
);
|
);
|
||||||
expect(await scriptIsInHead(page, '/prefetch-viewport')).toBeTruthy();
|
expect(await scriptIsInHead(page, '/prefetch-viewport')).toBeTruthy();
|
||||||
});
|
});
|
||||||
|
|
|
@ -134,7 +134,7 @@ export function prepareTestFactory(opts, { canReplayClicks = false } = {}) {
|
||||||
|
|
||||||
// Edit the component's initial count prop
|
// Edit the component's initial count prop
|
||||||
await astro.editFile(pageSourceFilePath, (original) =>
|
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 });
|
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) =>
|
await astro.editFile(componentFilePath, (original) =>
|
||||||
original.replace(
|
original.replace(
|
||||||
'Framework client:only component',
|
'Framework client:only component',
|
||||||
'Updated framework client:only component'
|
'Updated framework client:only component',
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
const label = page.locator('#client-only');
|
const label = page.locator('#client-only');
|
||||||
await expect(label, 'client:only component is visible').toBeVisible();
|
await expect(label, 'client:only component is visible').toBeVisible();
|
||||||
await expect(label, 'client:only slot text is visible').toHaveText(
|
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
|
// Edit the imported CSS file
|
||||||
await astro.editFile(counterCssFilePath || './src/components/Counter.css', (original) =>
|
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');
|
await expect(count, 'imported CSS updated').toHaveCSS('font-size', '24px');
|
||||||
|
|
|
@ -4,7 +4,7 @@ const { test, createTests } = prepareTestFactory(
|
||||||
{ root: './fixtures/solid-component/' },
|
{ root: './fixtures/solid-component/' },
|
||||||
{
|
{
|
||||||
canReplayClicks: true,
|
canReplayClicks: true,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
|
|
|
@ -23,7 +23,7 @@ test.describe('Tailwind CSS', () => {
|
||||||
await expect(body, 'should have classes').toHaveClass('bg-dawn text-midnight');
|
await expect(body, 'should have classes').toHaveClass('bg-dawn text-midnight');
|
||||||
await expect(body, 'should have background color').toHaveCSS(
|
await expect(body, 'should have background color').toHaveCSS(
|
||||||
'background-color',
|
'background-color',
|
||||||
'rgb(243, 233, 250)'
|
'rgb(243, 233, 250)',
|
||||||
);
|
);
|
||||||
await expect(body, 'should have color').toHaveCSS('color', 'rgb(49, 39, 74)');
|
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').toHaveCSS('appearance', 'none');
|
||||||
await expect(button, 'should have appearance-none with webkit prefix').toHaveCSS(
|
await expect(button, 'should have appearance-none with webkit prefix').toHaveCSS(
|
||||||
'-webkit-appearance',
|
'-webkit-appearance',
|
||||||
'none'
|
'none',
|
||||||
);
|
);
|
||||||
|
|
||||||
await expect(button, 'should have bg-purple-600').toHaveClass(/bg-purple-600/);
|
await expect(button, 'should have bg-purple-600').toHaveClass(/bg-purple-600/);
|
||||||
await expect(button, 'should have background color').toHaveCSS(
|
await expect(button, 'should have background color').toHaveCSS(
|
||||||
'background-color',
|
'background-color',
|
||||||
'rgb(147, 51, 234)'
|
'rgb(147, 51, 234)',
|
||||||
);
|
);
|
||||||
|
|
||||||
await expect(button, 'should have lg:py-3').toHaveClass(/lg:py-3/);
|
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 page.goto(astro.resolveUrl('/'));
|
||||||
|
|
||||||
await astro.editFile('./src/components/Button.astro', (original) =>
|
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');
|
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 bg-purple-400').toHaveClass(/bg-purple-400/);
|
||||||
await expect(button, 'should have background color').toHaveCSS(
|
await expect(button, 'should have background color').toHaveCSS(
|
||||||
'background-color',
|
'background-color',
|
||||||
'rgb(192, 132, 252)'
|
'rgb(192, 132, 252)',
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -84,7 +84,7 @@ export async function waitForHydrate(page, el) {
|
||||||
const astroIslandId = await astroIsland.last().getAttribute('uid');
|
const astroIslandId = await astroIsland.last().getAttribute('uid');
|
||||||
await page.waitForFunction(
|
await page.waitForFunction(
|
||||||
(selector) => document.querySelector(selector)?.hasAttribute('ssr') === false,
|
(selector) => document.querySelector(selector)?.hasAttribute('ssr') === false,
|
||||||
`astro-island[uid="${astroIslandId}"]`
|
`astro-island[uid="${astroIslandId}"]`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -35,7 +35,7 @@ function collectPreloads(page) {
|
||||||
mutations.forEach((mutation) =>
|
mutations.forEach((mutation) =>
|
||||||
mutation.addedNodes.forEach((node) => {
|
mutation.addedNodes.forEach((node) => {
|
||||||
if (node.nodeName === 'LINK' && node.rel === 'preload') preloads.push(node.href);
|
if (node.nodeName === 'LINK' && node.rel === 'preload') preloads.push(node.href);
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
observer.observe(document.head, { childList: true });
|
observer.observe(document.head, { childList: true });
|
||||||
|
@ -132,7 +132,7 @@ test.describe('View Transitions', () => {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
loads.length,
|
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);
|
).toEqual(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -163,7 +163,7 @@ test.describe('View Transitions', () => {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
loads.length,
|
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);
|
).toEqual(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -185,7 +185,7 @@ test.describe('View Transitions', () => {
|
||||||
await expect(p, 'should have content').toHaveText('Page 1');
|
await expect(p, 'should have content').toHaveText('Page 1');
|
||||||
expect(
|
expect(
|
||||||
loads.length,
|
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);
|
).toEqual(3);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -628,7 +628,7 @@ test.describe('View Transitions', () => {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
loads.length,
|
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);
|
).toEqual(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -770,7 +770,7 @@ test.describe('View Transitions', () => {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
loads.length,
|
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);
|
).toEqual(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1030,7 +1030,7 @@ test.describe('View Transitions', () => {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
loads.length,
|
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);
|
).toEqual(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1056,7 +1056,7 @@ test.describe('View Transitions', () => {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
loads.length,
|
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);
|
).toEqual(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1075,7 +1075,7 @@ test.describe('View Transitions', () => {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
loads.length,
|
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);
|
).toEqual(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1104,12 +1104,12 @@ test.describe('View Transitions', () => {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
loads.length,
|
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);
|
).toEqual(1);
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
postedEncodings,
|
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']);
|
).toEqual(['multipart/form-data']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1130,8 +1130,8 @@ test.describe('View Transitions', () => {
|
||||||
|
|
||||||
await page.goto(
|
await page.goto(
|
||||||
astro.resolveUrl(
|
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
|
// Submit the form
|
||||||
|
@ -1139,12 +1139,12 @@ test.describe('View Transitions', () => {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
loads.length,
|
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);
|
).toEqual(1);
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
postedEncodings,
|
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']);
|
).toEqual(['application/x-www-form-urlencoded']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1216,7 +1216,7 @@ test.describe('View Transitions', () => {
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
loads.length,
|
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);
|
).toEqual(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1333,7 +1333,7 @@ test.describe('View Transitions', () => {
|
||||||
expectedAnimations.add(name);
|
expectedAnimations.add(name);
|
||||||
expect(page.locator(selector), 'should be escaped correctly').toHaveCSS(
|
expect(page.locator(selector), 'should be escaped correctly').toHaveCSS(
|
||||||
'view-transition-name',
|
'view-transition-name',
|
||||||
name
|
name,
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -1361,36 +1361,36 @@ test.describe('View Transitions', () => {
|
||||||
await checkName('#thirteen', '___01____02______');
|
await checkName('#thirteen', '___01____02______');
|
||||||
await checkName(
|
await checkName(
|
||||||
'#batch0',
|
'#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(
|
await checkName(
|
||||||
'#batch1',
|
'#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('#batch2', '__40ABCDEFGHIJKLMNOPQRSTUVWXYZ_5b_5c_5d_5e__');
|
||||||
await checkName('#batch3', '__60abcdefghijklmnopqrstuvwxyz_7b_7c_7d_7e_7f');
|
await checkName('#batch3', '__60abcdefghijklmnopqrstuvwxyz_7b_7c_7d_7e_7f');
|
||||||
await checkName(
|
await checkName(
|
||||||
'#batch4',
|
'#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(
|
await checkName(
|
||||||
'#batch5',
|
'#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(
|
await checkName(
|
||||||
'#batch6',
|
'#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(
|
await checkName(
|
||||||
'#batch7',
|
'#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.click('#navigate');
|
||||||
await page.waitForTimeout(400); // yes, I dislike this, too. Might fix later.
|
await page.waitForTimeout(400); // yes, I dislike this, too. Might fix later.
|
||||||
expect(
|
expect(
|
||||||
expectedAnimations.size,
|
expectedAnimations.size,
|
||||||
'all animations for transition:names should have been found'
|
'all animations for transition:names should have been found',
|
||||||
).toEqual(0);
|
).toEqual(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -1425,7 +1425,7 @@ test.describe('View Transitions', () => {
|
||||||
const attributeValue = await page.$eval(
|
const attributeValue = await page.$eval(
|
||||||
':root',
|
':root',
|
||||||
(element, attributeName) => element.getAttribute(attributeName),
|
(element, attributeName) => element.getAttribute(attributeName),
|
||||||
'data-theme'
|
'data-theme',
|
||||||
);
|
);
|
||||||
expect(attributeValue).toBe('purple');
|
expect(attributeValue).toBe('purple');
|
||||||
});
|
});
|
||||||
|
|
|
@ -47,7 +47,7 @@ test('hmr works', async ({ page, astro }) => {
|
||||||
await expect(span).toHaveText('Count is 1');
|
await expect(span).toHaveText('Count is 1');
|
||||||
|
|
||||||
await astro.editFile('./src/components/State.vue', (content) =>
|
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');
|
await expect(span).toHaveText('Count is 2');
|
||||||
|
|
|
@ -74,8 +74,8 @@ async function benchmark({ fixtures, templates, numPosts }) {
|
||||||
const fixtures = formats.filter((format) => format !== 'md');
|
const fixtures = formats.filter((format) => format !== 'md');
|
||||||
console.log(
|
console.log(
|
||||||
`\n${bold('With Astro components')} ${dim(
|
`\n${bold('With Astro components')} ${dim(
|
||||||
`${numPosts} posts (${formatsToString(fixtures)})`
|
`${numPosts} posts (${formatsToString(fixtures)})`,
|
||||||
)}`
|
)}`,
|
||||||
);
|
);
|
||||||
process.env.ASTRO_PERFORMANCE_TEST_NAME = 'with-astro-components';
|
process.env.ASTRO_PERFORMANCE_TEST_NAME = 'with-astro-components';
|
||||||
await benchmark({
|
await benchmark({
|
||||||
|
@ -92,8 +92,8 @@ async function benchmark({ fixtures, templates, numPosts }) {
|
||||||
const fixtures = formats.filter((format) => format !== 'md');
|
const fixtures = formats.filter((format) => format !== 'md');
|
||||||
console.log(
|
console.log(
|
||||||
`\n${bold('With React components')} ${dim(
|
`\n${bold('With React components')} ${dim(
|
||||||
`${numPosts} posts (${formatsToString(fixtures)})`
|
`${numPosts} posts (${formatsToString(fixtures)})`,
|
||||||
)}`
|
)}`,
|
||||||
);
|
);
|
||||||
process.env.ASTRO_PERFORMANCE_TEST_NAME = 'with-react-components';
|
process.env.ASTRO_PERFORMANCE_TEST_NAME = 'with-react-components';
|
||||||
await benchmark({
|
await benchmark({
|
||||||
|
|
|
@ -23,8 +23,8 @@ export async function generatePosts({
|
||||||
Array.from(Array(numPosts).keys()).map((idx) => {
|
Array.from(Array(numPosts).keys()).map((idx) => {
|
||||||
return fs.promises.writeFile(
|
return fs.promises.writeFile(
|
||||||
`${postsDir}/post-${idx}${ext.startsWith('.') ? ext : `.${ext}`}`,
|
`${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'),
|
||||||
);
|
);
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -378,7 +378,7 @@ export interface AstroGlobalPartial {
|
||||||
*/
|
*/
|
||||||
glob(globStr: `${any}.astro`): Promise<AstroInstance[]>;
|
glob(globStr: `${any}.astro`): Promise<AstroInstance[]>;
|
||||||
glob<T extends Record<string, any>>(
|
glob<T extends Record<string, any>>(
|
||||||
globStr: `${any}${MarkdowFileExtension}`
|
globStr: `${any}${MarkdowFileExtension}`,
|
||||||
): Promise<MarkdownInstance<T>[]>;
|
): Promise<MarkdownInstance<T>[]>;
|
||||||
glob<T extends Record<string, any>>(globStr: `${any}.mdx`): Promise<MDXInstance<T>[]>;
|
glob<T extends Record<string, any>>(globStr: `${any}.mdx`): Promise<MDXInstance<T>[]>;
|
||||||
glob<T extends Record<string, any>>(globStr: string): Promise<T[]>;
|
glob<T extends Record<string, any>>(globStr: string): Promise<T[]>;
|
||||||
|
@ -2300,7 +2300,7 @@ export interface ContentEntryType {
|
||||||
contents: string;
|
contents: string;
|
||||||
fileUrl: URL;
|
fileUrl: URL;
|
||||||
viteId: string;
|
viteId: string;
|
||||||
}
|
},
|
||||||
): rollup.LoadResult | Promise<rollup.LoadResult>;
|
): rollup.LoadResult | Promise<rollup.LoadResult>;
|
||||||
contentModuleTypes?: string;
|
contentModuleTypes?: string;
|
||||||
/**
|
/**
|
||||||
|
@ -2385,7 +2385,7 @@ export type AsyncRendererComponentFn<U> = (
|
||||||
Component: any,
|
Component: any,
|
||||||
props: any,
|
props: any,
|
||||||
slots: Record<string, string>,
|
slots: Record<string, string>,
|
||||||
metadata?: AstroComponentMetadata
|
metadata?: AstroComponentMetadata,
|
||||||
) => Promise<U>;
|
) => Promise<U>;
|
||||||
|
|
||||||
/** Generic interface for a component (Astro, Svelte, React, etc.) */
|
/** 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)
|
* [Astro Reference](https://docs.astro.build/en/reference/api-reference/#getstaticpaths)
|
||||||
*/
|
*/
|
||||||
export type GetStaticPaths = (
|
export type GetStaticPaths = (
|
||||||
options: GetStaticPathsOptions
|
options: GetStaticPathsOptions,
|
||||||
) => Promise<GetStaticPathsResult> | GetStaticPathsResult;
|
) => Promise<GetStaticPathsResult> | GetStaticPathsResult;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -2493,7 +2493,7 @@ export type GetStaticPaths = (
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export type InferGetStaticParamsType<T> = T extends (
|
export type InferGetStaticParamsType<T> = T extends (
|
||||||
opts?: GetStaticPathsOptions
|
opts?: GetStaticPathsOptions,
|
||||||
) => infer R | Promise<infer R>
|
) => infer R | Promise<infer R>
|
||||||
? R extends Array<infer U>
|
? R extends Array<infer U>
|
||||||
? U extends { params: infer P }
|
? U extends { params: infer P }
|
||||||
|
@ -2526,7 +2526,7 @@ export type InferGetStaticParamsType<T> = T extends (
|
||||||
* ```
|
* ```
|
||||||
*/
|
*/
|
||||||
export type InferGetStaticPropsType<T> = T extends (
|
export type InferGetStaticPropsType<T> = T extends (
|
||||||
opts: GetStaticPathsOptions
|
opts: GetStaticPathsOptions,
|
||||||
) => infer R | Promise<infer R>
|
) => infer R | Promise<infer R>
|
||||||
? R extends Array<infer U>
|
? R extends Array<infer U>
|
||||||
? U extends { props: infer P }
|
? U extends { props: infer P }
|
||||||
|
@ -2639,7 +2639,7 @@ export type PaginateFunction = <
|
||||||
AdditionalPaginateParams extends Params,
|
AdditionalPaginateParams extends Params,
|
||||||
>(
|
>(
|
||||||
data: PaginateData[],
|
data: PaginateData[],
|
||||||
args?: PaginateOptions<AdditionalPaginateProps, AdditionalPaginateParams>
|
args?: PaginateOptions<AdditionalPaginateProps, AdditionalPaginateParams>,
|
||||||
) => {
|
) => {
|
||||||
params: Simplify<
|
params: Simplify<
|
||||||
{
|
{
|
||||||
|
@ -2755,7 +2755,7 @@ interface AstroSharedContext<
|
||||||
TInputSchema extends ActionInputSchema<TAccept>,
|
TInputSchema extends ActionInputSchema<TAccept>,
|
||||||
TAction extends ActionClient<unknown, TAccept, TInputSchema>,
|
TAction extends ActionClient<unknown, TAccept, TInputSchema>,
|
||||||
>(
|
>(
|
||||||
action: TAction
|
action: TAction,
|
||||||
) => ActionReturnType<TAction> | undefined;
|
) => ActionReturnType<TAction> | undefined;
|
||||||
/**
|
/**
|
||||||
* Call action handler from the server.
|
* Call action handler from the server.
|
||||||
|
@ -2769,7 +2769,7 @@ interface AstroSharedContext<
|
||||||
| ActionClient<TOutput, TAccept, TInputSchema>['orThrow'],
|
| ActionClient<TOutput, TAccept, TInputSchema>['orThrow'],
|
||||||
>(
|
>(
|
||||||
action: TAction,
|
action: TAction,
|
||||||
input: Parameters<TAction>[0]
|
input: Parameters<TAction>[0],
|
||||||
) => Promise<ActionReturnType<TAction>>;
|
) => Promise<ActionReturnType<TAction>>;
|
||||||
/**
|
/**
|
||||||
* Route parameters for this request if this is a dynamic route.
|
* 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<Response>;
|
export type MiddlewareNext = (rewritePayload?: RewritePayload) => Promise<Response>;
|
||||||
export type MiddlewareHandler = (
|
export type MiddlewareHandler = (
|
||||||
context: APIContext,
|
context: APIContext,
|
||||||
next: MiddlewareNext
|
next: MiddlewareNext,
|
||||||
) => Promise<Response> | Response | Promise<void> | void;
|
) => Promise<Response> | Response | Promise<void> | void;
|
||||||
|
|
||||||
// NOTE: when updating this file with other functions,
|
// NOTE: when updating this file with other functions,
|
||||||
|
@ -3258,7 +3258,7 @@ export interface SSRResult {
|
||||||
createAstro(
|
createAstro(
|
||||||
Astro: AstroGlobalPartial,
|
Astro: AstroGlobalPartial,
|
||||||
props: Record<string, any>,
|
props: Record<string, any>,
|
||||||
slots: Record<string, any> | null
|
slots: Record<string, any> | null,
|
||||||
): AstroGlobal;
|
): AstroGlobal;
|
||||||
params: Params;
|
params: Params;
|
||||||
resolve: (s: string) => Promise<string>;
|
resolve: (s: string) => Promise<string>;
|
||||||
|
@ -3326,7 +3326,7 @@ export interface PreviewServerParams {
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CreatePreviewServer = (
|
export type CreatePreviewServer = (
|
||||||
params: PreviewServerParams
|
params: PreviewServerParams,
|
||||||
) => PreviewServer | Promise<PreviewServer>;
|
) => PreviewServer | Promise<PreviewServer>;
|
||||||
|
|
||||||
export interface PreviewModule {
|
export interface PreviewModule {
|
||||||
|
@ -3351,7 +3351,7 @@ type DirectiveOptions = {
|
||||||
export type ClientDirective = (
|
export type ClientDirective = (
|
||||||
load: DirectiveLoad,
|
load: DirectiveLoad,
|
||||||
options: DirectiveOptions,
|
options: DirectiveOptions,
|
||||||
el: HTMLElement
|
el: HTMLElement,
|
||||||
) => void;
|
) => void;
|
||||||
|
|
||||||
export interface ClientDirectiveConfig {
|
export interface ClientDirectiveConfig {
|
||||||
|
@ -3399,7 +3399,7 @@ export type DevToolbarApp = {
|
||||||
init?(
|
init?(
|
||||||
canvas: ShadowRoot,
|
canvas: ShadowRoot,
|
||||||
app: ToolbarAppEventTarget,
|
app: ToolbarAppEventTarget,
|
||||||
server: ToolbarServerHelpers
|
server: ToolbarServerHelpers,
|
||||||
): void | Promise<void>;
|
): void | Promise<void>;
|
||||||
beforeTogglingOff?(canvas: ShadowRoot): boolean | Promise<boolean>;
|
beforeTogglingOff?(canvas: ShadowRoot): boolean | Promise<boolean>;
|
||||||
};
|
};
|
||||||
|
@ -3464,7 +3464,7 @@ declare global {
|
||||||
|
|
||||||
// Container types
|
// Container types
|
||||||
export type ContainerImportRendererFn = (
|
export type ContainerImportRendererFn = (
|
||||||
containerRenderer: ContainerRenderer
|
containerRenderer: ContainerRenderer,
|
||||||
) => Promise<SSRLoadedRenderer>;
|
) => Promise<SSRLoadedRenderer>;
|
||||||
|
|
||||||
export type ContainerRenderer = {
|
export type ContainerRenderer = {
|
||||||
|
|
|
@ -31,7 +31,7 @@ export default function astroActions({
|
||||||
}
|
}
|
||||||
|
|
||||||
const stringifiedActionsImport = JSON.stringify(
|
const stringifiedActionsImport = JSON.stringify(
|
||||||
viteID(new URL('./actions', params.config.srcDir))
|
viteID(new URL('./actions', params.config.srcDir)),
|
||||||
);
|
);
|
||||||
params.updateConfig({
|
params.updateConfig({
|
||||||
vite: {
|
vite: {
|
||||||
|
@ -75,7 +75,7 @@ export function vitePluginUserActions({ settings }: { settings: AstroSettings })
|
||||||
}
|
}
|
||||||
if (id === VIRTUAL_INTERNAL_MODULE_ID) {
|
if (id === VIRTUAL_INTERNAL_MODULE_ID) {
|
||||||
const resolvedModule = await this.resolve(
|
const resolvedModule = await this.resolve(
|
||||||
`${decodeURI(new URL('actions', settings.config.srcDir).pathname)}`
|
`${decodeURI(new URL('actions', settings.config.srcDir).pathname)}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!resolvedModule) {
|
if (!resolvedModule) {
|
||||||
|
@ -109,7 +109,7 @@ const vitePluginActions = (fs: typeof fsMod): VitePlugin => ({
|
||||||
|
|
||||||
let code = await fs.promises.readFile(
|
let code = await fs.promises.readFile(
|
||||||
new URL('../../templates/actions.mjs', import.meta.url),
|
new URL('../../templates/actions.mjs', import.meta.url),
|
||||||
'utf-8'
|
'utf-8',
|
||||||
);
|
);
|
||||||
if (opts?.ssr) {
|
if (opts?.ssr) {
|
||||||
code += `\nexport * from 'astro/actions/runtime/virtual/server.js';`;
|
code += `\nexport * from 'astro/actions/runtime/virtual/server.js';`;
|
||||||
|
|
|
@ -35,7 +35,7 @@ export const onRequest = defineMiddleware(async (context, next) => {
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
console.warn(
|
console.warn(
|
||||||
yellow('[astro:actions]'),
|
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();
|
return next();
|
||||||
}
|
}
|
||||||
|
|
|
@ -10,5 +10,5 @@ export const z = new Proxy(
|
||||||
get() {
|
get() {
|
||||||
throw new Error('[astro:action] `z` unexpectedly used on the client.');
|
throw new Error('[astro:action] `z` unexpectedly used on the client.');
|
||||||
},
|
},
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
|
@ -7,7 +7,7 @@ import type { ActionAccept, ActionClient } from './server.js';
|
||||||
* the user's `src/actions/index.ts` file at build-time.
|
* the user's `src/actions/index.ts` file at build-time.
|
||||||
*/
|
*/
|
||||||
export async function getAction(
|
export async function getAction(
|
||||||
path: string
|
path: string,
|
||||||
): Promise<ActionClient<unknown, ActionAccept, ZodType> | undefined> {
|
): Promise<ActionClient<unknown, ActionAccept, ZodType> | undefined> {
|
||||||
const pathKeys = path.replace('/_actions/', '').split('.');
|
const pathKeys = path.replace('/_actions/', '').split('.');
|
||||||
// @ts-expect-error virtual module
|
// @ts-expect-error virtual module
|
||||||
|
|
|
@ -25,7 +25,7 @@ export type ActionClient<
|
||||||
TInputSchema extends ActionInputSchema<TAccept> | undefined,
|
TInputSchema extends ActionInputSchema<TAccept> | undefined,
|
||||||
> = TInputSchema extends z.ZodType
|
> = TInputSchema extends z.ZodType
|
||||||
? ((
|
? ((
|
||||||
input: TAccept extends 'form' ? FormData : z.input<TInputSchema>
|
input: TAccept extends 'form' ? FormData : z.input<TInputSchema>,
|
||||||
) => Promise<
|
) => Promise<
|
||||||
SafeResult<
|
SafeResult<
|
||||||
z.input<TInputSchema> extends ErrorInferenceObject
|
z.input<TInputSchema> extends ErrorInferenceObject
|
||||||
|
@ -36,7 +36,7 @@ export type ActionClient<
|
||||||
>) & {
|
>) & {
|
||||||
queryString: string;
|
queryString: string;
|
||||||
orThrow: (
|
orThrow: (
|
||||||
input: TAccept extends 'form' ? FormData : z.input<TInputSchema>
|
input: TAccept extends 'form' ? FormData : z.input<TInputSchema>,
|
||||||
) => Promise<Awaited<TOutput>>;
|
) => Promise<Awaited<TOutput>>;
|
||||||
}
|
}
|
||||||
: (input?: any) => Promise<SafeResult<never, Awaited<TOutput>>> & {
|
: (input?: any) => Promise<SafeResult<never, Awaited<TOutput>>> & {
|
||||||
|
@ -85,7 +85,7 @@ export function defineAction<
|
||||||
|
|
||||||
function getFormServerHandler<TOutput, TInputSchema extends ActionInputSchema<'form'>>(
|
function getFormServerHandler<TOutput, TInputSchema extends ActionInputSchema<'form'>>(
|
||||||
handler: ActionHandler<TInputSchema, TOutput>,
|
handler: ActionHandler<TInputSchema, TOutput>,
|
||||||
inputSchema?: TInputSchema
|
inputSchema?: TInputSchema,
|
||||||
) {
|
) {
|
||||||
return async (unparsedInput: unknown, context: ActionAPIContext): Promise<Awaited<TOutput>> => {
|
return async (unparsedInput: unknown, context: ActionAPIContext): Promise<Awaited<TOutput>> => {
|
||||||
if (!(unparsedInput instanceof FormData)) {
|
if (!(unparsedInput instanceof FormData)) {
|
||||||
|
@ -107,7 +107,7 @@ function getFormServerHandler<TOutput, TInputSchema extends ActionInputSchema<'f
|
||||||
|
|
||||||
function getJsonServerHandler<TOutput, TInputSchema extends ActionInputSchema<'json'>>(
|
function getJsonServerHandler<TOutput, TInputSchema extends ActionInputSchema<'json'>>(
|
||||||
handler: ActionHandler<TInputSchema, TOutput>,
|
handler: ActionHandler<TInputSchema, TOutput>,
|
||||||
inputSchema?: TInputSchema
|
inputSchema?: TInputSchema,
|
||||||
) {
|
) {
|
||||||
return async (unparsedInput: unknown, context: ActionAPIContext): Promise<Awaited<TOutput>> => {
|
return async (unparsedInput: unknown, context: ActionAPIContext): Promise<Awaited<TOutput>> => {
|
||||||
if (unparsedInput instanceof FormData) {
|
if (unparsedInput instanceof FormData) {
|
||||||
|
@ -129,7 +129,7 @@ function getJsonServerHandler<TOutput, TInputSchema extends ActionInputSchema<'j
|
||||||
/** Transform form data to an object based on a Zod schema. */
|
/** Transform form data to an object based on a Zod schema. */
|
||||||
export function formDataToObject<T extends z.AnyZodObject>(
|
export function formDataToObject<T extends z.AnyZodObject>(
|
||||||
formData: FormData,
|
formData: FormData,
|
||||||
schema: T
|
schema: T,
|
||||||
): Record<string, unknown> {
|
): Record<string, unknown> {
|
||||||
const obj: Record<string, unknown> = {};
|
const obj: Record<string, unknown> = {};
|
||||||
for (const [key, baseValidator] of Object.entries(schema.shape)) {
|
for (const [key, baseValidator] of Object.entries(schema.shape)) {
|
||||||
|
@ -151,7 +151,7 @@ export function formDataToObject<T extends z.AnyZodObject>(
|
||||||
function handleFormDataGetAll(
|
function handleFormDataGetAll(
|
||||||
key: string,
|
key: string,
|
||||||
formData: FormData,
|
formData: FormData,
|
||||||
validator: z.ZodArray<z.ZodUnknown>
|
validator: z.ZodArray<z.ZodUnknown>,
|
||||||
) {
|
) {
|
||||||
const entries = Array.from(formData.getAll(key));
|
const entries = Array.from(formData.getAll(key));
|
||||||
const elementValidator = validator._def.type;
|
const elementValidator = validator._def.type;
|
||||||
|
@ -167,7 +167,7 @@ function handleFormDataGet(
|
||||||
key: string,
|
key: string,
|
||||||
formData: FormData,
|
formData: FormData,
|
||||||
validator: unknown,
|
validator: unknown,
|
||||||
baseValidator: unknown
|
baseValidator: unknown,
|
||||||
) {
|
) {
|
||||||
const value = formData.get(key);
|
const value = formData.get(key);
|
||||||
if (!value) {
|
if (!value) {
|
||||||
|
|
|
@ -41,7 +41,7 @@ const codeToStatusMap: Record<ActionErrorCode, number> = {
|
||||||
const statusToCodeMap: Record<number, ActionErrorCode> = Object.entries(codeToStatusMap).reduce(
|
const statusToCodeMap: Record<number, ActionErrorCode> = Object.entries(codeToStatusMap).reduce(
|
||||||
// reverse the key-value pairs
|
// reverse the key-value pairs
|
||||||
(acc, [key, value]) => ({ ...acc, [value]: key }),
|
(acc, [key, value]) => ({ ...acc, [value]: key }),
|
||||||
{}
|
{},
|
||||||
);
|
);
|
||||||
|
|
||||||
// T is used for error inference with SafeInput -> isInputError.
|
// T is used for error inference with SafeInput -> isInputError.
|
||||||
|
@ -92,11 +92,11 @@ export function isActionError(error?: unknown): error is ActionError {
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isInputError<T extends ErrorInferenceObject>(
|
export function isInputError<T extends ErrorInferenceObject>(
|
||||||
error?: ActionError<T>
|
error?: ActionError<T>,
|
||||||
): error is ActionInputError<T>;
|
): error is ActionInputError<T>;
|
||||||
export function isInputError(error?: unknown): error is ActionInputError<ErrorInferenceObject>;
|
export function isInputError(error?: unknown): error is ActionInputError<ErrorInferenceObject>;
|
||||||
export function isInputError<T extends ErrorInferenceObject>(
|
export function isInputError<T extends ErrorInferenceObject>(
|
||||||
error?: unknown | ActionError<T>
|
error?: unknown | ActionError<T>,
|
||||||
): error is ActionInputError<T> {
|
): error is ActionInputError<T> {
|
||||||
return (
|
return (
|
||||||
typeof error === 'object' &&
|
typeof error === 'object' &&
|
||||||
|
@ -146,7 +146,7 @@ export class ActionInputError<T extends ErrorInferenceObject> extends ActionErro
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function callSafely<TOutput>(
|
export async function callSafely<TOutput>(
|
||||||
handler: () => MaybePromise<TOutput>
|
handler: () => MaybePromise<TOutput>,
|
||||||
): Promise<SafeResult<z.ZodType, TOutput>> {
|
): Promise<SafeResult<z.ZodType, TOutput>> {
|
||||||
try {
|
try {
|
||||||
const data = await handler();
|
const data = await handler();
|
||||||
|
|
|
@ -48,7 +48,7 @@ type ImageData = { data: Uint8Array; expires: number };
|
||||||
|
|
||||||
export async function prepareAssetsGenerationEnv(
|
export async function prepareAssetsGenerationEnv(
|
||||||
pipeline: BuildPipeline,
|
pipeline: BuildPipeline,
|
||||||
totalCount: number
|
totalCount: number,
|
||||||
): Promise<AssetEnv> {
|
): Promise<AssetEnv> {
|
||||||
const { config, logger } = pipeline;
|
const { config, logger } = pipeline;
|
||||||
let useCache = true;
|
let useCache = true;
|
||||||
|
@ -61,7 +61,7 @@ export async function prepareAssetsGenerationEnv(
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.warn(
|
logger.warn(
|
||||||
null,
|
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;
|
useCache = false;
|
||||||
}
|
}
|
||||||
|
@ -96,7 +96,7 @@ export async function generateImagesForPath(
|
||||||
originalFilePath: string,
|
originalFilePath: string,
|
||||||
transformsAndPath: MapValue<AssetsGlobalStaticImagesList>,
|
transformsAndPath: MapValue<AssetsGlobalStaticImagesList>,
|
||||||
env: AssetEnv,
|
env: AssetEnv,
|
||||||
queue: PQueue
|
queue: PQueue,
|
||||||
) {
|
) {
|
||||||
const originalImageData = await loadImage(originalFilePath, env);
|
const originalImageData = await loadImage(originalFilePath, env);
|
||||||
|
|
||||||
|
@ -119,7 +119,7 @@ export async function generateImagesForPath(
|
||||||
if (transformsAndPath.originalSrcPath) {
|
if (transformsAndPath.originalSrcPath) {
|
||||||
env.logger.debug(
|
env.logger.debug(
|
||||||
'assets',
|
'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));
|
await fs.promises.unlink(getFullImagePath(originalFilePath, env));
|
||||||
}
|
}
|
||||||
|
@ -131,7 +131,7 @@ export async function generateImagesForPath(
|
||||||
async function generateImage(
|
async function generateImage(
|
||||||
originalImage: ImageData,
|
originalImage: ImageData,
|
||||||
filepath: string,
|
filepath: string,
|
||||||
options: ImageTransform
|
options: ImageTransform,
|
||||||
) {
|
) {
|
||||||
const timeStart = performance.now();
|
const timeStart = performance.now();
|
||||||
const generationData = await generateImageInternal(originalImage, filepath, options);
|
const generationData = await generateImageInternal(originalImage, filepath, options);
|
||||||
|
@ -145,7 +145,7 @@ export async function generateImagesForPath(
|
||||||
const count = `(${env.count.current}/${env.count.total})`;
|
const count = `(${env.count.current}/${env.count.total})`;
|
||||||
env.logger.info(
|
env.logger.info(
|
||||||
null,
|
null,
|
||||||
` ${green('▶')} ${filepath} ${dim(statsText)} ${dim(timeIncrease)} ${dim(count)}`
|
` ${green('▶')} ${filepath} ${dim(statsText)} ${dim(timeIncrease)} ${dim(count)}`,
|
||||||
);
|
);
|
||||||
env.count.current++;
|
env.count.current++;
|
||||||
}
|
}
|
||||||
|
@ -153,7 +153,7 @@ export async function generateImagesForPath(
|
||||||
async function generateImageInternal(
|
async function generateImageInternal(
|
||||||
originalImage: ImageData,
|
originalImage: ImageData,
|
||||||
filepath: string,
|
filepath: string,
|
||||||
options: ImageTransform
|
options: ImageTransform,
|
||||||
): Promise<GenerationData> {
|
): Promise<GenerationData> {
|
||||||
const isLocalImage = isESMImportedImage(options.src);
|
const isLocalImage = isESMImportedImage(options.src);
|
||||||
const finalFileURL = new URL('.' + filepath, env.clientRoot);
|
const finalFileURL = new URL('.' + filepath, env.clientRoot);
|
||||||
|
@ -177,7 +177,7 @@ export async function generateImagesForPath(
|
||||||
await fs.promises.unlink(cachedFileURL);
|
await fs.promises.unlink(cachedFileURL);
|
||||||
|
|
||||||
throw new Error(
|
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(
|
await imageService.transform(
|
||||||
originalImage.data,
|
originalImage.data,
|
||||||
{ ...options, src: originalImagePath },
|
{ ...options, src: originalImagePath },
|
||||||
env.imageConfig
|
env.imageConfig,
|
||||||
)
|
)
|
||||||
).data;
|
).data;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
@ -228,7 +228,7 @@ export async function generateImagesForPath(
|
||||||
...AstroErrorData.CouldNotTransformImage,
|
...AstroErrorData.CouldNotTransformImage,
|
||||||
message: AstroErrorData.CouldNotTransformImage.message(originalFilePath),
|
message: AstroErrorData.CouldNotTransformImage.message(originalFilePath),
|
||||||
},
|
},
|
||||||
{ cause: e }
|
{ cause: e },
|
||||||
);
|
);
|
||||||
|
|
||||||
throw error;
|
throw error;
|
||||||
|
@ -245,14 +245,14 @@ export async function generateImagesForPath(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
data: Buffer.from(resultData.data).toString('base64'),
|
data: Buffer.from(resultData.data).toString('base64'),
|
||||||
expires: resultData.expires,
|
expires: resultData.expires,
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
env.logger.warn(
|
env.logger.warn(
|
||||||
null,
|
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 {
|
} finally {
|
||||||
// Write the final file
|
// Write the final file
|
||||||
|
|
|
@ -8,7 +8,7 @@ export async function loadRemoteImage(src: string) {
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error(
|
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}))`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -60,7 +60,7 @@ export const GET: APIRoute = async ({ request }) => {
|
||||||
const { data, format } = await imageService.transform(
|
const { data, format } = await imageService.transform(
|
||||||
new Uint8Array(inputBuffer),
|
new Uint8Array(inputBuffer),
|
||||||
transform,
|
transform,
|
||||||
imageConfig
|
imageConfig,
|
||||||
);
|
);
|
||||||
|
|
||||||
return new Response(data, {
|
return new Response(data, {
|
||||||
|
|
|
@ -83,7 +83,7 @@ export const GET: APIRoute = async ({ request }) => {
|
||||||
|
|
||||||
if (!transform?.src) {
|
if (!transform?.src) {
|
||||||
const err = new Error(
|
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);
|
console.error('Could not parse image transform from URL:', err);
|
||||||
return new Response('Internal Server Error', { status: 500 });
|
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`,
|
import.meta.env.DEV ? `Could not process image request: ${err}` : `Internal Server Error`,
|
||||||
{
|
{
|
||||||
status: 500,
|
status: 500,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
@ -33,7 +33,7 @@ export async function getConfiguredImageService(): Promise<ImageService> {
|
||||||
|
|
||||||
export async function getImage(
|
export async function getImage(
|
||||||
options: UnresolvedImageTransform,
|
options: UnresolvedImageTransform,
|
||||||
imageConfig: AstroConfig['image']
|
imageConfig: AstroConfig['image'],
|
||||||
): Promise<GetImageResult> {
|
): Promise<GetImageResult> {
|
||||||
if (!options || typeof options !== 'object') {
|
if (!options || typeof options !== 'object') {
|
||||||
throw new AstroError({
|
throw new AstroError({
|
||||||
|
@ -47,7 +47,7 @@ export async function getImage(
|
||||||
message: AstroErrorData.ExpectedImage.message(
|
message: AstroErrorData.ExpectedImage.message(
|
||||||
options.src,
|
options.src,
|
||||||
'undefined',
|
'undefined',
|
||||||
JSON.stringify(options)
|
JSON.stringify(options),
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -101,7 +101,7 @@ export async function getImage(
|
||||||
url: await service.getURL(srcSet.transform, imageConfig),
|
url: await service.getURL(srcSet.transform, imageConfig),
|
||||||
descriptor: srcSet.descriptor,
|
descriptor: srcSet.descriptor,
|
||||||
attributes: srcSet.attributes,
|
attributes: srcSet.attributes,
|
||||||
}))
|
})),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (
|
if (
|
||||||
|
@ -113,7 +113,7 @@ export async function getImage(
|
||||||
imageURL = globalThis.astroAsset.addStaticImage(
|
imageURL = globalThis.astroAsset.addStaticImage(
|
||||||
validatedOptions,
|
validatedOptions,
|
||||||
propsToHash,
|
propsToHash,
|
||||||
originalFilePath
|
originalFilePath,
|
||||||
);
|
);
|
||||||
srcSets = srcSetTransforms.map((srcSet) => ({
|
srcSets = srcSetTransforms.map((srcSet) => ({
|
||||||
transform: srcSet.transform,
|
transform: srcSet.transform,
|
||||||
|
|
|
@ -47,7 +47,7 @@ interface SharedServiceProps<T extends Record<string, any> = Record<string, any>
|
||||||
*/
|
*/
|
||||||
getSrcSet?: (
|
getSrcSet?: (
|
||||||
options: ImageTransform,
|
options: ImageTransform,
|
||||||
imageConfig: ImageConfig<T>
|
imageConfig: ImageConfig<T>,
|
||||||
) => UnresolvedSrcSetValue[] | Promise<UnresolvedSrcSetValue[]>;
|
) => UnresolvedSrcSetValue[] | Promise<UnresolvedSrcSetValue[]>;
|
||||||
/**
|
/**
|
||||||
* Return any additional HTML attributes separate from `src` that your service requires to show the image properly.
|
* Return any additional HTML attributes separate from `src` that your service requires to show the image properly.
|
||||||
|
@ -57,7 +57,7 @@ interface SharedServiceProps<T extends Record<string, any> = Record<string, any>
|
||||||
*/
|
*/
|
||||||
getHTMLAttributes?: (
|
getHTMLAttributes?: (
|
||||||
options: ImageTransform,
|
options: ImageTransform,
|
||||||
imageConfig: ImageConfig<T>
|
imageConfig: ImageConfig<T>,
|
||||||
) => Record<string, any> | Promise<Record<string, any>>;
|
) => Record<string, any> | Promise<Record<string, any>>;
|
||||||
/**
|
/**
|
||||||
* Validate and return the options passed by the user.
|
* Validate and return the options passed by the user.
|
||||||
|
@ -69,7 +69,7 @@ interface SharedServiceProps<T extends Record<string, any> = Record<string, any>
|
||||||
*/
|
*/
|
||||||
validateOptions?: (
|
validateOptions?: (
|
||||||
options: ImageTransform,
|
options: ImageTransform,
|
||||||
imageConfig: ImageConfig<T>
|
imageConfig: ImageConfig<T>,
|
||||||
) => ImageTransform | Promise<ImageTransform>;
|
) => ImageTransform | Promise<ImageTransform>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -90,7 +90,7 @@ export interface LocalImageService<T extends Record<string, any> = Record<string
|
||||||
*/
|
*/
|
||||||
parseURL: (
|
parseURL: (
|
||||||
url: URL,
|
url: URL,
|
||||||
imageConfig: ImageConfig<T>
|
imageConfig: ImageConfig<T>,
|
||||||
) => LocalImageTransform | undefined | Promise<LocalImageTransform> | Promise<undefined>;
|
) => LocalImageTransform | undefined | Promise<LocalImageTransform> | Promise<undefined>;
|
||||||
/**
|
/**
|
||||||
* Performs the image transformations on the input image and returns both the binary data and
|
* Performs the image transformations on the input image and returns both the binary data and
|
||||||
|
@ -99,7 +99,7 @@ export interface LocalImageService<T extends Record<string, any> = Record<string
|
||||||
transform: (
|
transform: (
|
||||||
inputBuffer: Uint8Array,
|
inputBuffer: Uint8Array,
|
||||||
transform: LocalImageTransform,
|
transform: LocalImageTransform,
|
||||||
imageConfig: ImageConfig<T>
|
imageConfig: ImageConfig<T>,
|
||||||
) => Promise<{ data: Uint8Array; format: ImageOutputFormat }>;
|
) => Promise<{ data: Uint8Array; format: ImageOutputFormat }>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -148,7 +148,7 @@ export const baseService: Omit<LocalImageService, 'transform'> = {
|
||||||
message: AstroErrorData.ExpectedImage.message(
|
message: AstroErrorData.ExpectedImage.message(
|
||||||
JSON.stringify(options.src),
|
JSON.stringify(options.src),
|
||||||
typeof 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<LocalImageService, 'transform'> = {
|
||||||
message: AstroErrorData.UnsupportedImageFormat.message(
|
message: AstroErrorData.UnsupportedImageFormat.message(
|
||||||
options.src.format,
|
options.src.format,
|
||||||
options.src.src,
|
options.src.src,
|
||||||
VALID_SUPPORTED_FORMATS
|
VALID_SUPPORTED_FORMATS,
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -281,14 +281,14 @@ export const baseService: Omit<LocalImageService, 'transform'> = {
|
||||||
...densityWidths.map((width, index) => ({
|
...densityWidths.map((width, index) => ({
|
||||||
maxTargetWidth: Math.min(width, maxWidth),
|
maxTargetWidth: Math.min(width, maxWidth),
|
||||||
descriptor: `${densityValues[index]}x` as const,
|
descriptor: `${densityValues[index]}x` as const,
|
||||||
}))
|
})),
|
||||||
);
|
);
|
||||||
} else if (widths) {
|
} else if (widths) {
|
||||||
allWidths.push(
|
allWidths.push(
|
||||||
...widths.map((width) => ({
|
...widths.map((width) => ({
|
||||||
maxTargetWidth: Math.min(width, maxWidth),
|
maxTargetWidth: Math.min(width, maxWidth),
|
||||||
descriptor: `${width}w` as const,
|
descriptor: `${width}w` as const,
|
||||||
}))
|
})),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -31,7 +31,7 @@ const qualityTable: Record<
|
||||||
|
|
||||||
async function getRotationForEXIF(
|
async function getRotationForEXIF(
|
||||||
inputBuffer: Uint8Array,
|
inputBuffer: Uint8Array,
|
||||||
src?: string
|
src?: string,
|
||||||
): Promise<Operation | undefined> {
|
): Promise<Operation | undefined> {
|
||||||
const meta = await imageMetadata(inputBuffer, src);
|
const meta = await imageMetadata(inputBuffer, src);
|
||||||
if (!meta) return undefined;
|
if (!meta) return undefined;
|
||||||
|
|
|
@ -4,7 +4,7 @@ import { lookup as probe } from '../utils/vendor/image-size/lookup.js';
|
||||||
|
|
||||||
export async function imageMetadata(
|
export async function imageMetadata(
|
||||||
data: Uint8Array,
|
data: Uint8Array,
|
||||||
src?: string
|
src?: string,
|
||||||
): Promise<Omit<ImageMetadata, 'src' | 'fsPath'>> {
|
): Promise<Omit<ImageMetadata, 'src' | 'fsPath'>> {
|
||||||
try {
|
try {
|
||||||
const result = probe(data);
|
const result = probe(data);
|
||||||
|
|
|
@ -14,7 +14,7 @@ export async function emitESMImage(
|
||||||
_watchMode: boolean,
|
_watchMode: boolean,
|
||||||
// FIX: in Astro 5, this function should not be passed in dev mode at all.
|
// 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.
|
// Or rethink the API so that a function that throws isn't passed through.
|
||||||
fileEmitter?: FileEmitter
|
fileEmitter?: FileEmitter,
|
||||||
): Promise<ImageMetadata | undefined> {
|
): Promise<ImageMetadata | undefined> {
|
||||||
if (!id) {
|
if (!id) {
|
||||||
return undefined;
|
return undefined;
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
import type { ImageInputFormat, ImageMetadata } from '../types.js';
|
import type { ImageInputFormat, ImageMetadata } from '../types.js';
|
||||||
|
|
||||||
export function getOrigQueryParams(
|
export function getOrigQueryParams(
|
||||||
params: URLSearchParams
|
params: URLSearchParams,
|
||||||
): Pick<ImageMetadata, 'width' | 'height' | 'format'> | undefined {
|
): Pick<ImageMetadata, 'width' | 'height' | 'format'> | undefined {
|
||||||
const width = params.get('origWidth');
|
const width = params.get('origWidth');
|
||||||
const height = params.get('origHeight');
|
const height = params.get('origHeight');
|
||||||
|
|
|
@ -70,7 +70,7 @@ export function isRemoteAllowed(
|
||||||
{
|
{
|
||||||
domains = [],
|
domains = [],
|
||||||
remotePatterns = [],
|
remotePatterns = [],
|
||||||
}: Partial<Pick<AstroConfig['image'], 'domains' | 'remotePatterns'>>
|
}: Partial<Pick<AstroConfig['image'], 'domains' | 'remotePatterns'>>,
|
||||||
): boolean {
|
): boolean {
|
||||||
if (!isRemotePath(src)) return false;
|
if (!isRemotePath(src)) return false;
|
||||||
|
|
||||||
|
|
|
@ -18,7 +18,7 @@ export function propsToFilename(filePath: string, transform: ImageTransform, has
|
||||||
export function hashTransform(
|
export function hashTransform(
|
||||||
transform: ImageTransform,
|
transform: ImageTransform,
|
||||||
imageService: string,
|
imageService: string,
|
||||||
propertiesToHash: string[]
|
propertiesToHash: string[],
|
||||||
) {
|
) {
|
||||||
// Extract the fields we want to hash
|
// Extract the fields we want to hash
|
||||||
const hashFields = propertiesToHash.reduce(
|
const hashFields = propertiesToHash.reduce(
|
||||||
|
@ -28,7 +28,7 @@ export function hashTransform(
|
||||||
acc[prop] = transform[prop];
|
acc[prop] = transform[prop];
|
||||||
return acc;
|
return acc;
|
||||||
},
|
},
|
||||||
{ imageService } as Record<string, unknown>
|
{ imageService } as Record<string, unknown>,
|
||||||
);
|
);
|
||||||
return shorthash(deterministicString(hashFields));
|
return shorthash(deterministicString(hashFields));
|
||||||
}
|
}
|
||||||
|
|
|
@ -25,7 +25,7 @@ const resolvedVirtualModuleId = '\0' + VIRTUAL_MODULE_ID;
|
||||||
const assetRegex = new RegExp(`\\.(${VALID_INPUT_FORMATS.join('|')})`, 'i');
|
const assetRegex = new RegExp(`\\.(${VALID_INPUT_FORMATS.join('|')})`, 'i');
|
||||||
const assetRegexEnds = new RegExp(`\\.(${VALID_INPUT_FORMATS.join('|')})$`, 'i');
|
const assetRegexEnds = new RegExp(`\\.(${VALID_INPUT_FORMATS.join('|')})$`, 'i');
|
||||||
const addStaticImageFactory = (
|
const addStaticImageFactory = (
|
||||||
settings: AstroSettings
|
settings: AstroSettings,
|
||||||
): typeof globalThis.astroAsset.addStaticImage => {
|
): typeof globalThis.astroAsset.addStaticImage => {
|
||||||
return (options, hashProperties, originalFSPath) => {
|
return (options, hashProperties, originalFSPath) => {
|
||||||
if (!globalThis.astroAsset.staticImages) {
|
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)
|
// 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(
|
const finalOriginalPath = removeBase(
|
||||||
removeBase(ESMImportedImageSrc, settings.config.base),
|
removeBase(ESMImportedImageSrc, settings.config.base),
|
||||||
assetPrefix
|
assetPrefix,
|
||||||
);
|
);
|
||||||
|
|
||||||
const hash = hashTransform(options, settings.config.image.service.entrypoint, hashProperties);
|
const hash = hashTransform(options, settings.config.image.service.entrypoint, hashProperties);
|
||||||
|
@ -62,8 +62,8 @@ const addStaticImageFactory = (
|
||||||
finalFilePath = prependForwardSlash(
|
finalFilePath = prependForwardSlash(
|
||||||
joinPaths(
|
joinPaths(
|
||||||
isESMImportedImage(options.src) ? '' : settings.config.build.assets,
|
isESMImportedImage(options.src) ? '' : settings.config.build.assets,
|
||||||
prependForwardSlash(propsToFilename(finalOriginalPath, options, hash))
|
prependForwardSlash(propsToFilename(finalOriginalPath, options, hash)),
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!transformsForPath) {
|
if (!transformsForPath) {
|
||||||
|
@ -146,11 +146,11 @@ export default function assets({
|
||||||
new URL(
|
new URL(
|
||||||
isServerLikeOutput(settings.config)
|
isServerLikeOutput(settings.config)
|
||||||
? settings.config.build.client
|
? settings.config.build.client
|
||||||
: settings.config.outDir
|
: settings.config.outDir,
|
||||||
)
|
),
|
||||||
)});
|
)});
|
||||||
export const assetsDir = /* #__PURE__ */ new URL(${JSON.stringify(
|
export const assetsDir = /* #__PURE__ */ new URL(${JSON.stringify(
|
||||||
settings.config.build.assets
|
settings.config.build.assets,
|
||||||
)}, outDir);
|
)}, outDir);
|
||||||
export const getImage = async (options) => await getImageInternal(options, imageConfig);
|
export const getImage = async (options) => await getImageInternal(options, imageConfig);
|
||||||
`;
|
`;
|
||||||
|
@ -235,7 +235,7 @@ export default function assets({
|
||||||
if (options?.ssr) {
|
if (options?.ssr) {
|
||||||
return `export default ${getProxyCode(
|
return `export default ${getProxyCode(
|
||||||
imageMetadata,
|
imageMetadata,
|
||||||
isServerLikeOutput(settings.config)
|
isServerLikeOutput(settings.config),
|
||||||
)}`;
|
)}`;
|
||||||
} else {
|
} else {
|
||||||
globalThis.astroAsset.referencedImages.add(imageMetadata.fsPath);
|
globalThis.astroAsset.referencedImages.add(imageMetadata.fsPath);
|
||||||
|
|
|
@ -12,7 +12,7 @@ export function ensureImport(root: t.File, importDeclaration: t.ImportDeclaratio
|
||||||
if (specifier.local.name === specifierToFind.local.name) {
|
if (specifier.local.name === specifierToFind.local.name) {
|
||||||
specifiersToFind.splice(i, 1);
|
specifiersToFind.splice(i, 1);
|
||||||
}
|
}
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
|
@ -191,9 +191,9 @@ export async function add(names: string[], { flags }: AddOptions) {
|
||||||
'SKIP_FORMAT',
|
'SKIP_FORMAT',
|
||||||
`\n ${magenta(
|
`\n ${magenta(
|
||||||
`Astro will scaffold ${green('./db/config.ts')}${magenta(' and ')}${green(
|
`Astro will scaffold ${green('./db/config.ts')}${magenta(' and ')}${green(
|
||||||
'./db/seed.ts'
|
'./db/seed.ts',
|
||||||
)}${magenta(' files.')}`
|
)}${magenta(' files.')}`,
|
||||||
)}\n`
|
)}\n`,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (await askToContinue({ flags })) {
|
if (await askToContinue({ flags })) {
|
||||||
|
@ -205,7 +205,7 @@ export async function add(names: string[], { flags }: AddOptions) {
|
||||||
} else {
|
} else {
|
||||||
logger.info(
|
logger.info(
|
||||||
'SKIP_FORMAT',
|
'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 {
|
} else {
|
||||||
|
@ -235,8 +235,8 @@ export async function add(names: string[], { flags }: AddOptions) {
|
||||||
'SKIP_FORMAT',
|
'SKIP_FORMAT',
|
||||||
msg.cancelled(
|
msg.cancelled(
|
||||||
`Dependencies ${bold('NOT')} installed.`,
|
`Dependencies ${bold('NOT')} installed.`,
|
||||||
`Be sure to install them manually before continuing!`
|
`Be sure to install them manually before continuing!`,
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
@ -273,8 +273,8 @@ export async function add(names: string[], { flags }: AddOptions) {
|
||||||
ast,
|
ast,
|
||||||
t.importDeclaration(
|
t.importDeclaration(
|
||||||
[t.importSpecifier(defineConfig, defineConfig)],
|
[t.importSpecifier(defineConfig, defineConfig)],
|
||||||
t.stringLiteral('astro/config')
|
t.stringLiteral('astro/config'),
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
wrapDefaultExport(ast, defineConfig);
|
wrapDefaultExport(ast, defineConfig);
|
||||||
|
|
||||||
|
@ -290,9 +290,9 @@ export async function add(names: string[], { flags }: AddOptions) {
|
||||||
'SKIP_FORMAT',
|
'SKIP_FORMAT',
|
||||||
`\n ${magenta(
|
`\n ${magenta(
|
||||||
`Check our deployment docs for ${bold(
|
`Check our deployment docs for ${bold(
|
||||||
integration.packageName
|
integration.packageName,
|
||||||
)} to update your "adapter" config.`
|
)} to update your "adapter" config.`,
|
||||||
)}`
|
)}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
@ -326,7 +326,7 @@ export async function add(names: string[], { flags }: AddOptions) {
|
||||||
case UpdateResult.cancelled: {
|
case UpdateResult.cancelled: {
|
||||||
logger.info(
|
logger.info(
|
||||||
'SKIP_FORMAT',
|
'SKIP_FORMAT',
|
||||||
msg.cancelled(`Your configuration has ${bold('NOT')} been updated.`)
|
msg.cancelled(`Your configuration has ${bold('NOT')} been updated.`),
|
||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
@ -338,7 +338,7 @@ export async function add(names: string[], { flags }: AddOptions) {
|
||||||
.then((res) => JSON.parse(res.toString()));
|
.then((res) => JSON.parse(res.toString()));
|
||||||
const deps = Object.keys(Object.assign(dependencies, devDependencies));
|
const deps = Object.keys(Object.assign(dependencies, devDependencies));
|
||||||
const missingDeps = integrations.filter(
|
const missingDeps = integrations.filter(
|
||||||
(integration) => !deps.includes(integration.packageName)
|
(integration) => !deps.includes(integration.packageName),
|
||||||
);
|
);
|
||||||
if (missingDeps.length === 0) {
|
if (missingDeps.length === 0) {
|
||||||
logger.info('SKIP_FORMAT', msg.success(`Configuration up-to-date.`));
|
logger.info('SKIP_FORMAT', msg.success(`Configuration up-to-date.`));
|
||||||
|
@ -356,8 +356,8 @@ export async function add(names: string[], { flags }: AddOptions) {
|
||||||
msg.success(
|
msg.success(
|
||||||
`Added the following integration${
|
`Added the following integration${
|
||||||
integrations.length === 1 ? '' : 's'
|
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: {
|
case UpdateResult.cancelled: {
|
||||||
logger.info(
|
logger.info(
|
||||||
'SKIP_FORMAT',
|
'SKIP_FORMAT',
|
||||||
msg.cancelled(`Your TypeScript configuration has ${bold('NOT')} been updated.`)
|
msg.cancelled(`Your TypeScript configuration has ${bold('NOT')} been updated.`),
|
||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case UpdateResult.failure: {
|
case UpdateResult.failure: {
|
||||||
throw new Error(
|
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:
|
default:
|
||||||
|
@ -386,7 +386,7 @@ export async function add(names: string[], { flags }: AddOptions) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function isAdapter(
|
function isAdapter(
|
||||||
integration: IntegrationInfo
|
integration: IntegrationInfo,
|
||||||
): integration is IntegrationInfo & { type: 'adapter' } {
|
): integration is IntegrationInfo & { type: 'adapter' } {
|
||||||
return integration.type === 'adapter';
|
return integration.type === 'adapter';
|
||||||
}
|
}
|
||||||
|
@ -445,8 +445,8 @@ async function addIntegration(ast: t.File, integration: IntegrationInfo) {
|
||||||
ast,
|
ast,
|
||||||
t.importDeclaration(
|
t.importDeclaration(
|
||||||
[t.importDefaultSpecifier(integrationId)],
|
[t.importDefaultSpecifier(integrationId)],
|
||||||
t.stringLiteral(integration.packageName)
|
t.stringLiteral(integration.packageName),
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
visit(ast, {
|
visit(ast, {
|
||||||
|
@ -472,7 +472,7 @@ async function addIntegration(ast: t.File, integration: IntegrationInfo) {
|
||||||
|
|
||||||
if (!integrationsProp) {
|
if (!integrationsProp) {
|
||||||
configObject.properties.push(
|
configObject.properties.push(
|
||||||
t.objectProperty(t.identifier('integrations'), t.arrayExpression([integrationCall]))
|
t.objectProperty(t.identifier('integrations'), t.arrayExpression([integrationCall])),
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@ -484,7 +484,7 @@ async function addIntegration(ast: t.File, integration: IntegrationInfo) {
|
||||||
(expr) =>
|
(expr) =>
|
||||||
t.isCallExpression(expr) &&
|
t.isCallExpression(expr) &&
|
||||||
t.isIdentifier(expr.callee) &&
|
t.isIdentifier(expr.callee) &&
|
||||||
expr.callee.name === integrationId.name
|
expr.callee.name === integrationId.name,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (existingIntegrationCall) return;
|
if (existingIntegrationCall) return;
|
||||||
|
@ -499,7 +499,7 @@ async function setAdapter(ast: t.File, adapter: IntegrationInfo, exportName: str
|
||||||
|
|
||||||
ensureImport(
|
ensureImport(
|
||||||
ast,
|
ast,
|
||||||
t.importDeclaration([t.importDefaultSpecifier(adapterId)], t.stringLiteral(exportName))
|
t.importDeclaration([t.importDefaultSpecifier(adapterId)], t.stringLiteral(exportName)),
|
||||||
);
|
);
|
||||||
|
|
||||||
visit(ast, {
|
visit(ast, {
|
||||||
|
@ -523,7 +523,7 @@ async function setAdapter(ast: t.File, adapter: IntegrationInfo, exportName: str
|
||||||
|
|
||||||
if (!outputProp) {
|
if (!outputProp) {
|
||||||
configObject.properties.push(
|
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(
|
logger.info(
|
||||||
'SKIP_FORMAT',
|
'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) {
|
if (logAdapterInstructions) {
|
||||||
|
@ -618,9 +618,9 @@ async function updateAstroConfig({
|
||||||
'SKIP_FORMAT',
|
'SKIP_FORMAT',
|
||||||
magenta(
|
magenta(
|
||||||
` For complete deployment options, visit\n ${bold(
|
` For complete deployment options, visit\n ${bold(
|
||||||
'https://docs.astro.build/en/guides/deploy/'
|
'https://docs.astro.build/en/guides/deploy/',
|
||||||
)}\n`
|
)}\n`,
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -669,7 +669,7 @@ async function getInstallIntegrationsCommand({
|
||||||
}
|
}
|
||||||
|
|
||||||
async function convertIntegrationsToInstallSpecifiers(
|
async function convertIntegrationsToInstallSpecifiers(
|
||||||
integrations: IntegrationInfo[]
|
integrations: IntegrationInfo[],
|
||||||
): Promise<string[]> {
|
): Promise<string[]> {
|
||||||
const ranges: Record<string, string> = {};
|
const ranges: Record<string, string> = {};
|
||||||
for (let { packageName, dependencies } of integrations) {
|
for (let { packageName, dependencies } of integrations) {
|
||||||
|
@ -679,7 +679,7 @@ async function convertIntegrationsToInstallSpecifiers(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return Promise.all(
|
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(
|
logger.info(
|
||||||
'SKIP_FORMAT',
|
'SKIP_FORMAT',
|
||||||
`\n ${magenta('Astro will run the following command:')}\n ${dim(
|
`\n ${magenta('Astro will run the following command:')}\n ${dim(
|
||||||
'If you skip this step, you can always run it yourself later'
|
'If you skip this step, you can always run it yourself later',
|
||||||
)}\n${message}`
|
)}\n${message}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (await askToContinue({ flags })) {
|
if (await askToContinue({ flags })) {
|
||||||
|
@ -768,7 +768,7 @@ async function tryToInstallIntegrations({
|
||||||
cwd,
|
cwd,
|
||||||
// reset NODE_ENV to ensure install command run in dev mode
|
// reset NODE_ENV to ensure install command run in dev mode
|
||||||
env: { NODE_ENV: undefined },
|
env: { NODE_ENV: undefined },
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
spinner.succeed();
|
spinner.succeed();
|
||||||
return UpdateResult.updated;
|
return UpdateResult.updated;
|
||||||
|
@ -817,8 +817,8 @@ async function validateIntegrations(integrations: string[]): Promise<Integration
|
||||||
if (!response.askToContinue) {
|
if (!response.askToContinue) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`No problem! Find our official integrations at ${cyan(
|
`No problem! Find our official integrations at ${cyan(
|
||||||
'https://astro.build/integrations'
|
'https://astro.build/integrations',
|
||||||
)}`
|
)}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
spinner.start('Resolving with third party packages...');
|
spinner.start('Resolving with third party packages...');
|
||||||
|
@ -867,15 +867,15 @@ async function validateIntegrations(integrations: string[]): Promise<Integration
|
||||||
} else {
|
} else {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`${bold(
|
`${bold(
|
||||||
packageName
|
packageName,
|
||||||
)} doesn't appear to be an integration or an adapter. Find our official integrations at ${cyan(
|
)} doesn't appear to be an integration or an adapter. Find our official integrations at ${cyan(
|
||||||
'https://astro.build/integrations'
|
'https://astro.build/integrations',
|
||||||
)}`
|
)}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { id: integration, packageName, dependencies, type: integrationType };
|
return { id: integration, packageName, dependencies, type: integrationType };
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
spinner.succeed();
|
spinner.succeed();
|
||||||
return integrationEntries;
|
return integrationEntries;
|
||||||
|
@ -893,13 +893,13 @@ async function updateTSConfig(
|
||||||
cwd = process.cwd(),
|
cwd = process.cwd(),
|
||||||
logger: Logger,
|
logger: Logger,
|
||||||
integrationsInfo: IntegrationInfo[],
|
integrationsInfo: IntegrationInfo[],
|
||||||
flags: yargs.Arguments
|
flags: yargs.Arguments,
|
||||||
): Promise<UpdateResult> {
|
): Promise<UpdateResult> {
|
||||||
const integrations = integrationsInfo.map(
|
const integrations = integrationsInfo.map(
|
||||||
(integration) => integration.id as frameworkWithTSSettings
|
(integration) => integration.id as frameworkWithTSSettings,
|
||||||
);
|
);
|
||||||
const firstIntegrationWithTSSettings = integrations.find((integration) =>
|
const firstIntegrationWithTSSettings = integrations.find((integration) =>
|
||||||
presets.has(integration)
|
presets.has(integration),
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!firstIntegrationWithTSSettings) {
|
if (!firstIntegrationWithTSSettings) {
|
||||||
|
@ -926,7 +926,7 @@ async function updateTSConfig(
|
||||||
|
|
||||||
const outputConfig = updateTSConfigForFramework(
|
const outputConfig = updateTSConfigForFramework(
|
||||||
inputConfig.rawConfig,
|
inputConfig.rawConfig,
|
||||||
firstIntegrationWithTSSettings
|
firstIntegrationWithTSSettings,
|
||||||
);
|
);
|
||||||
|
|
||||||
const output = JSON.stringify(outputConfig, null, 2);
|
const output = JSON.stringify(outputConfig, null, 2);
|
||||||
|
@ -945,7 +945,7 @@ async function updateTSConfig(
|
||||||
|
|
||||||
logger.info(
|
logger.info(
|
||||||
'SKIP_FORMAT',
|
'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
|
// 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',
|
'SKIP_FORMAT',
|
||||||
red(
|
red(
|
||||||
` ${bold(
|
` ${bold(
|
||||||
'Caution:'
|
'Caution:',
|
||||||
)} Selected UI frameworks require conflicting tsconfig.json settings, as such only settings for ${bold(
|
)} Selected UI frameworks require conflicting tsconfig.json settings, as such only settings for ${bold(
|
||||||
firstIntegrationWithTSSettings
|
firstIntegrationWithTSSettings,
|
||||||
)} were used.\n More information: https://docs.astro.build/en/guides/typescript/#errors-typing-multiple-jsx-frameworks-at-the-same-time\n`
|
)} 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 logger = opts.logger;
|
||||||
const possibleConfigFiles = opts.possibleConfigFiles.map((p) =>
|
const possibleConfigFiles = opts.possibleConfigFiles.map((p) =>
|
||||||
fileURLToPath(new URL(p, opts.root))
|
fileURLToPath(new URL(p, opts.root)),
|
||||||
);
|
);
|
||||||
let alreadyConfigured = false;
|
let alreadyConfigured = false;
|
||||||
for (const possibleConfigPath of possibleConfigFiles) {
|
for (const possibleConfigPath of possibleConfigFiles) {
|
||||||
|
@ -1058,7 +1058,7 @@ async function setupIntegrationConfig(opts: {
|
||||||
if (!alreadyConfigured) {
|
if (!alreadyConfigured) {
|
||||||
logger.info(
|
logger.info(
|
||||||
'SKIP_FORMAT',
|
'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 })) {
|
if (await askToContinue({ flags: opts.flags })) {
|
||||||
await fs.writeFile(
|
await fs.writeFile(
|
||||||
|
@ -1066,7 +1066,7 @@ async function setupIntegrationConfig(opts: {
|
||||||
opts.defaultConfigContent,
|
opts.defaultConfigContent,
|
||||||
{
|
{
|
||||||
encoding: 'utf-8',
|
encoding: 'utf-8',
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
logger.debug('add', `Generated default ${opts.defaultConfigFile} file`);
|
logger.debug('add', `Generated default ${opts.defaultConfigFile} file`);
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,14 +12,14 @@ export async function check(flags: Arguments) {
|
||||||
'@astrojs/check',
|
'@astrojs/check',
|
||||||
logger,
|
logger,
|
||||||
getPackageOpts,
|
getPackageOpts,
|
||||||
['typescript']
|
['typescript'],
|
||||||
);
|
);
|
||||||
const typescript = await getPackage('typescript', logger, getPackageOpts);
|
const typescript = await getPackage('typescript', logger, getPackageOpts);
|
||||||
|
|
||||||
if (!checkPackage || !typescript) {
|
if (!checkPackage || !typescript) {
|
||||||
logger.error(
|
logger.error(
|
||||||
'check',
|
'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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
|
@ -18,7 +18,7 @@ export async function db({ flags }: { flags: Arguments }) {
|
||||||
if (!dbPackage) {
|
if (!dbPackage) {
|
||||||
logger.error(
|
logger.error(
|
||||||
'check',
|
'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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
|
@ -23,7 +23,7 @@ export async function dev({ flags }: DevOptions) {
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
description: `Check ${cyan(
|
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.`,
|
)} for more information.`,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
|
|
|
@ -21,7 +21,7 @@ const getPlatformSpecificCommand = (): [string] | [string, string[]] => {
|
||||||
return ['/ide/bin/remote-cli/gitpod-code', ['--openExternal']];
|
return ['/ide/bin/remote-cli/gitpod-code', ['--openExternal']];
|
||||||
default:
|
default:
|
||||||
throw new Error(
|
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`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
|
@ -93,7 +93,7 @@ async function copyToClipboard(text: string) {
|
||||||
});
|
});
|
||||||
} catch {
|
} catch {
|
||||||
console.error(
|
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.`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -21,7 +21,7 @@ export async function getPackage<T>(
|
||||||
packageName: string,
|
packageName: string,
|
||||||
logger: Logger,
|
logger: Logger,
|
||||||
options: GetPackageOptions,
|
options: GetPackageOptions,
|
||||||
otherDeps: string[] = []
|
otherDeps: string[] = [],
|
||||||
): Promise<T | undefined> {
|
): Promise<T | undefined> {
|
||||||
try {
|
try {
|
||||||
// Try to resolve with `createRequire` first to prevent ESM caching of the package
|
// Try to resolve with `createRequire` first to prevent ESM caching of the package
|
||||||
|
@ -32,7 +32,7 @@ export async function getPackage<T>(
|
||||||
} catch {
|
} catch {
|
||||||
if (options.optional) return undefined;
|
if (options.optional) return undefined;
|
||||||
let message = `To continue, Astro requires the following dependency to be installed: ${bold(
|
let message = `To continue, Astro requires the following dependency to be installed: ${bold(
|
||||||
packageName
|
packageName,
|
||||||
)}.`;
|
)}.`;
|
||||||
|
|
||||||
if (ci.isCI) {
|
if (ci.isCI) {
|
||||||
|
@ -98,7 +98,7 @@ export async function getExecCommand(packageManager?: string): Promise<string> {
|
||||||
async function installPackage(
|
async function installPackage(
|
||||||
packageNames: string[],
|
packageNames: string[],
|
||||||
options: GetPackageOptions,
|
options: GetPackageOptions,
|
||||||
logger: Logger
|
logger: Logger,
|
||||||
): Promise<boolean> {
|
): Promise<boolean> {
|
||||||
const cwd = options.cwd ?? process.cwd();
|
const cwd = options.cwd ?? process.cwd();
|
||||||
const packageManager = (await whichPm(cwd))?.name ?? 'npm';
|
const packageManager = (await whichPm(cwd))?.name ?? 'npm';
|
||||||
|
@ -120,8 +120,8 @@ async function installPackage(
|
||||||
logger.info(
|
logger.info(
|
||||||
'SKIP_FORMAT',
|
'SKIP_FORMAT',
|
||||||
`\n ${magenta('Astro will run the following command:')}\n ${dim(
|
`\n ${magenta('Astro will run the following command:')}\n ${dim(
|
||||||
'If you skip this step, you can always run it yourself later'
|
'If you skip this step, you can always run it yourself later',
|
||||||
)}\n${message}`
|
)}\n${message}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
let response;
|
let response;
|
||||||
|
@ -144,7 +144,7 @@ async function installPackage(
|
||||||
await execa(
|
await execa(
|
||||||
installCommand.pm,
|
installCommand.pm,
|
||||||
[installCommand.command, ...installCommand.flags, ...installCommand.dependencies],
|
[installCommand.command, ...installCommand.flags, ...installCommand.dependencies],
|
||||||
{ cwd: cwd }
|
{ cwd: cwd },
|
||||||
);
|
);
|
||||||
spinner.succeed();
|
spinner.succeed();
|
||||||
|
|
||||||
|
@ -163,7 +163,7 @@ async function installPackage(
|
||||||
export async function fetchPackageJson(
|
export async function fetchPackageJson(
|
||||||
scope: string | undefined,
|
scope: string | undefined,
|
||||||
name: string,
|
name: string,
|
||||||
tag: string
|
tag: string,
|
||||||
): Promise<Record<string, any> | Error> {
|
): Promise<Record<string, any> | Error> {
|
||||||
const packageName = `${scope ? `${scope}/` : ''}${name}`;
|
const packageName = `${scope ? `${scope}/` : ''}${name}`;
|
||||||
const registry = await getRegistry();
|
const registry = await getRegistry();
|
||||||
|
|
|
@ -43,7 +43,7 @@ export async function preferences(
|
||||||
subcommand: string,
|
subcommand: string,
|
||||||
key: string,
|
key: string,
|
||||||
value: string | undefined,
|
value: string | undefined,
|
||||||
{ flags }: PreferencesOptions
|
{ flags }: PreferencesOptions,
|
||||||
): Promise<number> {
|
): Promise<number> {
|
||||||
applyPolyfill();
|
applyPolyfill();
|
||||||
if (!isValidSubcommand(subcommand) || flags?.help || flags?.h) {
|
if (!isValidSubcommand(subcommand) || flags?.help || flags?.h) {
|
||||||
|
@ -98,8 +98,8 @@ export async function preferences(
|
||||||
console.error(
|
console.error(
|
||||||
msg.formatErrorMessage(
|
msg.formatErrorMessage(
|
||||||
collectErrorMetadata(new Error(`Please provide a ${type} value for "${key}"`)),
|
collectErrorMetadata(new Error(`Please provide a ${type} value for "${key}"`)),
|
||||||
true
|
true,
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
@ -128,7 +128,7 @@ interface SubcommandOptions {
|
||||||
async function getPreference(
|
async function getPreference(
|
||||||
settings: AstroSettings,
|
settings: AstroSettings,
|
||||||
key: PreferenceKey,
|
key: PreferenceKey,
|
||||||
{ location = 'project' }: SubcommandOptions
|
{ location = 'project' }: SubcommandOptions,
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
let value = await settings.preferences.get(key, { location });
|
let value = await settings.preferences.get(key, { location });
|
||||||
|
@ -155,7 +155,7 @@ async function setPreference(
|
||||||
settings: AstroSettings,
|
settings: AstroSettings,
|
||||||
key: PreferenceKey,
|
key: PreferenceKey,
|
||||||
value: unknown,
|
value: unknown,
|
||||||
{ location }: SubcommandOptions
|
{ location }: SubcommandOptions,
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const defaultType = typeof dlv(DEFAULT_PREFERENCES, key);
|
const defaultType = typeof dlv(DEFAULT_PREFERENCES, key);
|
||||||
|
@ -178,7 +178,7 @@ async function setPreference(
|
||||||
async function enablePreference(
|
async function enablePreference(
|
||||||
settings: AstroSettings,
|
settings: AstroSettings,
|
||||||
key: PreferenceKey,
|
key: PreferenceKey,
|
||||||
{ location }: SubcommandOptions
|
{ location }: SubcommandOptions,
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
await settings.preferences.set(key, true, { location });
|
await settings.preferences.set(key, true, { location });
|
||||||
|
@ -191,7 +191,7 @@ async function enablePreference(
|
||||||
async function disablePreference(
|
async function disablePreference(
|
||||||
settings: AstroSettings,
|
settings: AstroSettings,
|
||||||
key: PreferenceKey,
|
key: PreferenceKey,
|
||||||
{ location }: SubcommandOptions
|
{ location }: SubcommandOptions,
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
await settings.preferences.set(key, false, { location });
|
await settings.preferences.set(key, false, { location });
|
||||||
|
@ -204,7 +204,7 @@ async function disablePreference(
|
||||||
async function resetPreference(
|
async function resetPreference(
|
||||||
settings: AstroSettings,
|
settings: AstroSettings,
|
||||||
key: PreferenceKey,
|
key: PreferenceKey,
|
||||||
{ location }: SubcommandOptions
|
{ location }: SubcommandOptions,
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
await settings.preferences.set(key, undefined as any, { location });
|
await settings.preferences.set(key, undefined as any, { location });
|
||||||
|
@ -216,13 +216,13 @@ async function resetPreference(
|
||||||
|
|
||||||
function annotate(flat: Record<string, any>, annotation: string) {
|
function annotate(flat: Record<string, any>, annotation: string) {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
Object.entries(flat).map(([key, value]) => [key, { annotation, value }])
|
Object.entries(flat).map(([key, value]) => [key, { annotation, value }]),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
function userValues(
|
function userValues(
|
||||||
flatDefault: Record<string, string | number | boolean>,
|
flatDefault: Record<string, string | number | boolean>,
|
||||||
flatProject: Record<string, string | number | boolean>,
|
flatProject: Record<string, string | number | boolean>,
|
||||||
flatGlobal: Record<string, string | number | boolean>
|
flatGlobal: Record<string, string | number | boolean>,
|
||||||
) {
|
) {
|
||||||
const result: AnnotatedValues = {};
|
const result: AnnotatedValues = {};
|
||||||
for (const key of Object.keys(flatDefault)) {
|
for (const key of Object.keys(flatDefault)) {
|
||||||
|
@ -289,8 +289,8 @@ async function listPreferences(settings: AstroSettings, { location, json }: Subc
|
||||||
) {
|
) {
|
||||||
console.log(
|
console.log(
|
||||||
yellow(
|
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
|
// this is the real formatting for annotated values
|
||||||
function formatAnnotated(
|
function formatAnnotated(
|
||||||
mv: AnnotatedValue,
|
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);
|
return mv.annotation ? `${style(mv.value)} ${dim(mv.annotation)}` : style(mv.value);
|
||||||
}
|
}
|
||||||
|
@ -339,28 +339,28 @@ function formatTable(object: Record<string, AnnotatedValue>, columnLabels: [stri
|
||||||
i: number,
|
i: number,
|
||||||
a: string,
|
a: string,
|
||||||
b: AnnotatedValue,
|
b: AnnotatedValue,
|
||||||
style: (value: string | number | boolean) => string = (v) => v.toString()
|
style: (value: string | number | boolean) => string = (v) => v.toString(),
|
||||||
): string {
|
): string {
|
||||||
return `${dim(chars.v)} ${style(a)} ${space(colALength - a.length - 2)} ${dim(
|
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(
|
)} ${formatAnnotated(b, style)} ${space(colBLength - annotatedFormat(b).length - 3)} ${dim(
|
||||||
chars.v
|
chars.v,
|
||||||
)}`;
|
)}`;
|
||||||
}
|
}
|
||||||
const top = dim(
|
const top = dim(
|
||||||
`${chars.topLeft}${chars.h.repeat(colALength + 1)}${chars.hBottom}${chars.h.repeat(
|
`${chars.topLeft}${chars.h.repeat(colALength + 1)}${chars.hBottom}${chars.h.repeat(
|
||||||
colBLength
|
colBLength,
|
||||||
)}${chars.topRight}`
|
)}${chars.topRight}`,
|
||||||
);
|
);
|
||||||
const bottom = dim(
|
const bottom = dim(
|
||||||
`${chars.bottomLeft}${chars.h.repeat(colALength + 1)}${chars.hTop}${chars.h.repeat(
|
`${chars.bottomLeft}${chars.h.repeat(colALength + 1)}${chars.hTop}${chars.h.repeat(
|
||||||
colBLength
|
colBLength,
|
||||||
)}${chars.bottomRight}`
|
)}${chars.bottomRight}`,
|
||||||
);
|
);
|
||||||
const divider = dim(
|
const divider = dim(
|
||||||
`${chars.vRightThick}${chars.hThick.repeat(colALength + 1)}${
|
`${chars.vRightThick}${chars.hThick.repeat(colALength + 1)}${
|
||||||
chars.hThickCross
|
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];
|
const rows: string[] = [top, formatRow(-1, colA, { value: colB, annotation: '' }, bold), divider];
|
||||||
let i = 0;
|
let i = 0;
|
||||||
|
|
|
@ -23,7 +23,7 @@ export async function preview({ flags }: PreviewOptions) {
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
description: `Starts a local server to serve your static dist/ directory. Check ${cyan(
|
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.`,
|
)} for more information.`,
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
|
|
|
@ -8,7 +8,7 @@ export function defineConfig(config: AstroUserConfig) {
|
||||||
|
|
||||||
export function getViteConfig(
|
export function getViteConfig(
|
||||||
userViteConfig: ViteUserConfig,
|
userViteConfig: ViteUserConfig,
|
||||||
inlineAstroConfig: AstroInlineConfig = {}
|
inlineAstroConfig: AstroInlineConfig = {},
|
||||||
) {
|
) {
|
||||||
// Return an async Vite config getter which exposes a resolved `mode` and `command`
|
// Return an async Vite config getter which exposes a resolved `mode` and `command`
|
||||||
return async ({ mode, command }: { mode: string; command: 'serve' | 'build' }) => {
|
return async ({ mode, command }: { mode: string; command: 'serve' | 'build' }) => {
|
||||||
|
@ -48,7 +48,7 @@ export function getViteConfig(
|
||||||
astroContentListenPlugin({ settings, logger, fs }),
|
astroContentListenPlugin({ settings, logger, fs }),
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{ settings, logger, mode, sync: false }
|
{ settings, logger, mode, sync: false },
|
||||||
);
|
);
|
||||||
await runHookConfigDone({ settings, logger });
|
await runHookConfigDone({ settings, logger });
|
||||||
return mergeConfig(viteConfig, userViteConfig);
|
return mergeConfig(viteConfig, userViteConfig);
|
||||||
|
|
|
@ -105,7 +105,7 @@ export type AddClientRenderer = {
|
||||||
function createManifest(
|
function createManifest(
|
||||||
manifest?: AstroContainerManifest,
|
manifest?: AstroContainerManifest,
|
||||||
renderers?: SSRLoadedRenderer[],
|
renderers?: SSRLoadedRenderer[],
|
||||||
middleware?: MiddlewareHandler
|
middleware?: MiddlewareHandler,
|
||||||
): SSRManifest {
|
): SSRManifest {
|
||||||
const defaultMiddleware: MiddlewareHandler = (_, next) => {
|
const defaultMiddleware: MiddlewareHandler = (_, next) => {
|
||||||
return next();
|
return next();
|
||||||
|
@ -274,7 +274,7 @@ export class experimental_AstroContainer {
|
||||||
* @param {AstroContainerOptions=} containerOptions
|
* @param {AstroContainerOptions=} containerOptions
|
||||||
*/
|
*/
|
||||||
public static async create(
|
public static async create(
|
||||||
containerOptions: AstroContainerOptions = {}
|
containerOptions: AstroContainerOptions = {},
|
||||||
): Promise<experimental_AstroContainer> {
|
): Promise<experimental_AstroContainer> {
|
||||||
const { streaming = false, manifest, renderers = [], resolve } = containerOptions;
|
const { streaming = false, manifest, renderers = [], resolve } = containerOptions;
|
||||||
const astroConfig = await validateConfig(ASTRO_CONFIG_DEFAULTS, process.cwd(), 'container');
|
const astroConfig = await validateConfig(ASTRO_CONFIG_DEFAULTS, process.cwd(), 'container');
|
||||||
|
@ -315,7 +315,7 @@ export class experimental_AstroContainer {
|
||||||
if (!renderer.check || !renderer.renderToStaticMarkup) {
|
if (!renderer.check || !renderer.renderToStaticMarkup) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
"The renderer you passed isn't valid. A renderer is usually an object that exposes the `check` and `renderToStaticMarkup` functions.\n" +
|
"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)) {
|
if (isNamedRenderer(renderer)) {
|
||||||
|
@ -362,7 +362,7 @@ export class experimental_AstroContainer {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
'You tried to add the ' +
|
'You tried to add the ' +
|
||||||
name +
|
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];
|
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.
|
// 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
|
// @ematipico: I plan to use it for a possible integration that could help people
|
||||||
private static async createFromManifest(
|
private static async createFromManifest(
|
||||||
manifest: SSRManifest
|
manifest: SSRManifest,
|
||||||
): Promise<experimental_AstroContainer> {
|
): Promise<experimental_AstroContainer> {
|
||||||
const astroConfig = await validateConfig(ASTRO_CONFIG_DEFAULTS, process.cwd(), 'container');
|
const astroConfig = await validateConfig(ASTRO_CONFIG_DEFAULTS, process.cwd(), 'container');
|
||||||
const container = new experimental_AstroContainer({
|
const container = new experimental_AstroContainer({
|
||||||
|
@ -431,7 +431,7 @@ export class experimental_AstroContainer {
|
||||||
*/
|
*/
|
||||||
public async renderToString(
|
public async renderToString(
|
||||||
component: AstroComponentFactory,
|
component: AstroComponentFactory,
|
||||||
options: ContainerRenderOptions = {}
|
options: ContainerRenderOptions = {},
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const response = await this.renderToResponse(component, options);
|
const response = await this.renderToResponse(component, options);
|
||||||
return await response.text();
|
return await response.text();
|
||||||
|
@ -458,7 +458,7 @@ export class experimental_AstroContainer {
|
||||||
*/
|
*/
|
||||||
public async renderToResponse(
|
public async renderToResponse(
|
||||||
component: AstroComponentFactory,
|
component: AstroComponentFactory,
|
||||||
options: ContainerRenderOptions = {}
|
options: ContainerRenderOptions = {},
|
||||||
): Promise<Response> {
|
): Promise<Response> {
|
||||||
const { routeType = 'page', slots } = options;
|
const { routeType = 'page', slots } = options;
|
||||||
const request = options?.request ?? new Request('https://example.com/');
|
const request = options?.request ?? new Request('https://example.com/');
|
||||||
|
@ -510,7 +510,7 @@ export class experimental_AstroContainer {
|
||||||
pattern: getPattern(
|
pattern: getPattern(
|
||||||
segments,
|
segments,
|
||||||
ASTRO_CONFIG_DEFAULTS.base,
|
ASTRO_CONFIG_DEFAULTS.base,
|
||||||
ASTRO_CONFIG_DEFAULTS.trailingSlash
|
ASTRO_CONFIG_DEFAULTS.trailingSlash,
|
||||||
),
|
),
|
||||||
prerender: false,
|
prerender: false,
|
||||||
segments,
|
segments,
|
||||||
|
@ -528,7 +528,7 @@ export class experimental_AstroContainer {
|
||||||
*/
|
*/
|
||||||
#wrapComponent(
|
#wrapComponent(
|
||||||
componentFactory: AstroComponentFactory,
|
componentFactory: AstroComponentFactory,
|
||||||
params?: Record<string, string | undefined>
|
params?: Record<string, string | undefined>,
|
||||||
): ComponentInstance {
|
): ComponentInstance {
|
||||||
if (params) {
|
if (params) {
|
||||||
return {
|
return {
|
||||||
|
|
|
@ -41,7 +41,7 @@ export class ContainerPipeline extends Pipeline {
|
||||||
renderers,
|
renderers,
|
||||||
resolve,
|
resolve,
|
||||||
serverLike,
|
serverLike,
|
||||||
streaming
|
streaming,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -70,7 +70,7 @@ export class ContainerPipeline extends Pipeline {
|
||||||
|
|
||||||
async tryRewrite(
|
async tryRewrite(
|
||||||
payload: RewritePayload,
|
payload: RewritePayload,
|
||||||
request: Request
|
request: Request,
|
||||||
): Promise<[RouteData, ComponentInstance, URL]> {
|
): Promise<[RouteData, ComponentInstance, URL]> {
|
||||||
const [foundRoute, finalUrl] = findRouteToRewrite({
|
const [foundRoute, finalUrl] = findRouteToRewrite({
|
||||||
payload,
|
payload,
|
||||||
|
|
|
@ -6,7 +6,7 @@ import { emitESMImage } from '../assets/utils/node/emitAsset.js';
|
||||||
export function createImage(
|
export function createImage(
|
||||||
pluginContext: PluginContext,
|
pluginContext: PluginContext,
|
||||||
shouldEmitFile: boolean,
|
shouldEmitFile: boolean,
|
||||||
entryFilePath: string
|
entryFilePath: string,
|
||||||
) {
|
) {
|
||||||
return () => {
|
return () => {
|
||||||
return z.string().transform(async (imagePath, ctx) => {
|
return z.string().transform(async (imagePath, ctx) => {
|
||||||
|
@ -14,7 +14,7 @@ export function createImage(
|
||||||
const metadata = (await emitESMImage(
|
const metadata = (await emitESMImage(
|
||||||
resolvedFilePath,
|
resolvedFilePath,
|
||||||
pluginContext.meta.watchMode,
|
pluginContext.meta.watchMode,
|
||||||
shouldEmitFile ? pluginContext.emitFile : undefined
|
shouldEmitFile ? pluginContext.emitFile : undefined,
|
||||||
)) as OmitBrand<ImageMetadata>;
|
)) as OmitBrand<ImageMetadata>;
|
||||||
|
|
||||||
if (!metadata) {
|
if (!metadata) {
|
||||||
|
|
|
@ -65,15 +65,15 @@ export function createGetCollection({
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
console.warn(
|
console.warn(
|
||||||
`The collection ${JSON.stringify(
|
`The collection ${JSON.stringify(
|
||||||
collection
|
collection,
|
||||||
)} does not exist or is empty. Ensure a collection directory with this name exists.`
|
)} does not exist or is empty. Ensure a collection directory with this name exists.`,
|
||||||
);
|
);
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
const lazyImports = Object.values(
|
const lazyImports = Object.values(
|
||||||
type === 'content'
|
type === 'content'
|
||||||
? contentCollectionToEntryMap[collection]
|
? contentCollectionToEntryMap[collection]
|
||||||
: dataCollectionToEntryMap[collection]
|
: dataCollectionToEntryMap[collection],
|
||||||
);
|
);
|
||||||
let entries: any[] = [];
|
let entries: any[] = [];
|
||||||
// Cache `getCollection()` calls in production only
|
// Cache `getCollection()` calls in production only
|
||||||
|
@ -106,8 +106,8 @@ export function createGetCollection({
|
||||||
collection: entry.collection,
|
collection: entry.collection,
|
||||||
data: entry.data,
|
data: entry.data,
|
||||||
};
|
};
|
||||||
})
|
}),
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
cacheEntriesByCollection.set(collection, entries);
|
cacheEntriesByCollection.set(collection, entries);
|
||||||
}
|
}
|
||||||
|
@ -196,7 +196,7 @@ export function createGetEntry({
|
||||||
// Or pass a single object with the collection and identifier as properties.
|
// Or pass a single object with the collection and identifier as properties.
|
||||||
// This means the first positional arg can have different shapes.
|
// This means the first positional arg can have different shapes.
|
||||||
collectionOrLookupObject: string | EntryLookupObject,
|
collectionOrLookupObject: string | EntryLookupObject,
|
||||||
_lookupId?: string
|
_lookupId?: string,
|
||||||
): Promise<ContentEntryResult | DataEntryResult | undefined> {
|
): Promise<ContentEntryResult | DataEntryResult | undefined> {
|
||||||
let collection: string, lookupId: string;
|
let collection: string, lookupId: string;
|
||||||
if (typeof collectionOrLookupObject === 'string') {
|
if (typeof collectionOrLookupObject === 'string') {
|
||||||
|
@ -249,7 +249,7 @@ export function createGetEntry({
|
||||||
|
|
||||||
export function createGetEntries(getEntry: ReturnType<typeof createGetEntry>) {
|
export function createGetEntries(getEntry: ReturnType<typeof createGetEntry>) {
|
||||||
return async function getEntries(
|
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)));
|
return Promise.all(entries.map((e) => getEntry(e)));
|
||||||
};
|
};
|
||||||
|
@ -332,8 +332,8 @@ async function render({
|
||||||
'Content',
|
'Content',
|
||||||
propagationMod.Content,
|
propagationMod.Content,
|
||||||
props,
|
props,
|
||||||
slots
|
slots,
|
||||||
)}`
|
)}`,
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
propagation: 'self',
|
propagation: 'self',
|
||||||
|
@ -374,7 +374,7 @@ export function createReference({ lookupMap }: { lookupMap: ContentLookupMap })
|
||||||
ctx.addIssue({
|
ctx.addIssue({
|
||||||
code: ZodIssueCode.custom,
|
code: ZodIssueCode.custom,
|
||||||
message: `**${flattenedErrorPath}**: Reference to ${collection} invalid. Expected ${Object.keys(
|
message: `**${flattenedErrorPath}**: Reference to ${collection} invalid. Expected ${Object.keys(
|
||||||
entries
|
entries,
|
||||||
)
|
)
|
||||||
.map((c) => JSON.stringify(c))
|
.map((c) => JSON.stringify(c))
|
||||||
.join(' | ')}. Received ${JSON.stringify(lookupId)}.`,
|
.join(' | ')}. Received ${JSON.stringify(lookupId)}.`,
|
||||||
|
|
|
@ -29,8 +29,8 @@ export async function attachContentServerListeners({
|
||||||
logger.debug(
|
logger.debug(
|
||||||
'content',
|
'content',
|
||||||
`Watching ${cyan(
|
`Watching ${cyan(
|
||||||
contentPaths.contentDir.href.replace(settings.config.root.href, '')
|
contentPaths.contentDir.href.replace(settings.config.root.href, ''),
|
||||||
)} for changes`
|
)} for changes`,
|
||||||
);
|
);
|
||||||
const maybeTsConfigStats = await getTSConfigStatsWhenAllowJsFalse({ contentPaths, settings });
|
const maybeTsConfigStats = await getTSConfigStatsWhenAllowJsFalse({ contentPaths, settings });
|
||||||
if (maybeTsConfigStats) warnAllowJsIsFalse({ ...maybeTsConfigStats, logger });
|
if (maybeTsConfigStats) warnAllowJsIsFalse({ ...maybeTsConfigStats, logger });
|
||||||
|
@ -61,16 +61,16 @@ export async function attachContentServerListeners({
|
||||||
contentGenerator.queueEvent({ name: 'add', entry });
|
contentGenerator.queueEvent({ name: 'add', entry });
|
||||||
});
|
});
|
||||||
viteServer.watcher.on('addDir', (entry) =>
|
viteServer.watcher.on('addDir', (entry) =>
|
||||||
contentGenerator.queueEvent({ name: 'addDir', entry })
|
contentGenerator.queueEvent({ name: 'addDir', entry }),
|
||||||
);
|
);
|
||||||
viteServer.watcher.on('change', (entry) =>
|
viteServer.watcher.on('change', (entry) =>
|
||||||
contentGenerator.queueEvent({ name: 'change', entry })
|
contentGenerator.queueEvent({ name: 'change', entry }),
|
||||||
);
|
);
|
||||||
viteServer.watcher.on('unlink', (entry) => {
|
viteServer.watcher.on('unlink', (entry) => {
|
||||||
contentGenerator.queueEvent({ name: 'unlink', entry });
|
contentGenerator.queueEvent({ name: 'unlink', entry });
|
||||||
});
|
});
|
||||||
viteServer.watcher.on('unlinkDir', (entry) =>
|
viteServer.watcher.on('unlinkDir', (entry) =>
|
||||||
contentGenerator.queueEvent({ name: 'unlinkDir', entry })
|
contentGenerator.queueEvent({ name: 'unlinkDir', entry }),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -87,12 +87,12 @@ function warnAllowJsIsFalse({
|
||||||
logger.warn(
|
logger.warn(
|
||||||
'content',
|
'content',
|
||||||
`Make sure you have the ${bold('allowJs')} compiler option set to ${bold(
|
`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(
|
)} in your ${bold(tsConfigFileName)} file to have autocompletion in your ${bold(
|
||||||
contentConfigFileName
|
contentConfigFileName,
|
||||||
)} file. See ${underline(
|
)} file. See ${underline(
|
||||||
cyan('https://www.typescriptlang.org/tsconfig#allowJs')
|
cyan('https://www.typescriptlang.org/tsconfig#allowJs'),
|
||||||
)} for more information.`
|
)} for more information.`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -104,7 +104,7 @@ async function getTSConfigStatsWhenAllowJsFalse({
|
||||||
settings: AstroSettings;
|
settings: AstroSettings;
|
||||||
}) {
|
}) {
|
||||||
const isContentConfigJsFile = ['.js', '.mjs'].some((ext) =>
|
const isContentConfigJsFile = ['.js', '.mjs'].some((ext) =>
|
||||||
contentPaths.config.url.pathname.endsWith(ext)
|
contentPaths.config.url.pathname.endsWith(ext),
|
||||||
);
|
);
|
||||||
if (!isContentConfigJsFile) return;
|
if (!isContentConfigJsFile) return;
|
||||||
|
|
||||||
|
|
|
@ -112,7 +112,7 @@ export async function createContentTypesGenerator({
|
||||||
async function handleEvent(event: ContentEvent): Promise<{ shouldGenerateTypes: boolean }> {
|
async function handleEvent(event: ContentEvent): Promise<{ shouldGenerateTypes: boolean }> {
|
||||||
if (event.name === 'addDir' || event.name === 'unlinkDir') {
|
if (event.name === 'addDir' || event.name === 'unlinkDir') {
|
||||||
const collection = normalizePath(
|
const collection = normalizePath(
|
||||||
path.relative(fileURLToPath(contentPaths.contentDir), fileURLToPath(event.entry))
|
path.relative(fileURLToPath(contentPaths.contentDir), fileURLToPath(event.entry)),
|
||||||
);
|
);
|
||||||
const collectionKey = JSON.stringify(collection);
|
const collectionKey = JSON.stringify(collection);
|
||||||
// If directory is multiple levels deep, it is not a collection. Ignore event.
|
// If directory is multiple levels deep, it is not a collection. Ignore event.
|
||||||
|
@ -137,7 +137,7 @@ export async function createContentTypesGenerator({
|
||||||
fileURLToPath(event.entry),
|
fileURLToPath(event.entry),
|
||||||
contentPaths,
|
contentPaths,
|
||||||
contentEntryExts,
|
contentEntryExts,
|
||||||
dataEntryExts
|
dataEntryExts,
|
||||||
);
|
);
|
||||||
if (fileType === 'ignored') {
|
if (fileType === 'ignored') {
|
||||||
return { shouldGenerateTypes: false };
|
return { shouldGenerateTypes: false };
|
||||||
|
@ -156,9 +156,9 @@ export async function createContentTypesGenerator({
|
||||||
'content',
|
'content',
|
||||||
`${bold(
|
`${bold(
|
||||||
normalizePath(
|
normalizePath(
|
||||||
path.relative(fileURLToPath(contentPaths.contentDir), fileURLToPath(event.entry))
|
path.relative(fileURLToPath(contentPaths.contentDir), fileURLToPath(event.entry)),
|
||||||
)
|
),
|
||||||
)} must live in a ${bold('content/...')} collection subdirectory.`
|
)} must live in a ${bold('content/...')} collection subdirectory.`,
|
||||||
);
|
);
|
||||||
return { shouldGenerateTypes: false };
|
return { shouldGenerateTypes: false };
|
||||||
}
|
}
|
||||||
|
@ -406,7 +406,7 @@ async function writeContentFiles({
|
||||||
message: AstroErrorData.ContentCollectionTypeMismatchError.message(
|
message: AstroErrorData.ContentCollectionTypeMismatchError.message(
|
||||||
collectionKey,
|
collectionKey,
|
||||||
collection.type,
|
collection.type,
|
||||||
collectionConfig.type
|
collectionConfig.type,
|
||||||
),
|
),
|
||||||
hint:
|
hint:
|
||||||
collection.type === 'data'
|
collection.type === 'data'
|
||||||
|
@ -438,7 +438,7 @@ async function writeContentFiles({
|
||||||
for (const entryKey of collectionEntryKeys) {
|
for (const entryKey of collectionEntryKeys) {
|
||||||
const entryMetadata = collection.entries[entryKey];
|
const entryMetadata = collection.entries[entryKey];
|
||||||
const renderType = `{ render(): Render[${JSON.stringify(
|
const renderType = `{ render(): Render[${JSON.stringify(
|
||||||
path.extname(JSON.parse(entryKey))
|
path.extname(JSON.parse(entryKey)),
|
||||||
)}] }`;
|
)}] }`;
|
||||||
|
|
||||||
const slugType = JSON.stringify(entryMetadata.slug);
|
const slugType = JSON.stringify(entryMetadata.slug);
|
||||||
|
@ -479,14 +479,14 @@ async function writeContentFiles({
|
||||||
dateStrategy: ['format:date-time', 'format:date', 'integer'],
|
dateStrategy: ['format:date-time', 'format:date', 'integer'],
|
||||||
}),
|
}),
|
||||||
null,
|
null,
|
||||||
2
|
2,
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// This should error gracefully and not crash the dev server
|
// This should error gracefully and not crash the dev server
|
||||||
logger.warn(
|
logger.warn(
|
||||||
'content',
|
'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(
|
const configPathRelativeToCacheDir = normalizeConfigPath(
|
||||||
settings.dotAstroDir.pathname,
|
settings.dotAstroDir.pathname,
|
||||||
contentPaths.config.url.pathname
|
contentPaths.config.url.pathname,
|
||||||
);
|
);
|
||||||
|
|
||||||
for (const contentEntryType of contentEntryTypes) {
|
for (const contentEntryType of contentEntryTypes) {
|
||||||
|
@ -512,11 +512,11 @@ async function writeContentFiles({
|
||||||
typeTemplateContent = typeTemplateContent.replace('// @@DATA_ENTRY_MAP@@', dataTypesStr);
|
typeTemplateContent = typeTemplateContent.replace('// @@DATA_ENTRY_MAP@@', dataTypesStr);
|
||||||
typeTemplateContent = typeTemplateContent.replace(
|
typeTemplateContent = typeTemplateContent.replace(
|
||||||
"'@@CONTENT_CONFIG_TYPE@@'",
|
"'@@CONTENT_CONFIG_TYPE@@'",
|
||||||
contentConfig ? `typeof import(${configPathRelativeToCacheDir})` : 'never'
|
contentConfig ? `typeof import(${configPathRelativeToCacheDir})` : 'never',
|
||||||
);
|
);
|
||||||
|
|
||||||
await fs.promises.writeFile(
|
await fs.promises.writeFile(
|
||||||
new URL(CONTENT_TYPES_FILE, settings.dotAstroDir),
|
new URL(CONTENT_TYPES_FILE, settings.dotAstroDir),
|
||||||
typeTemplateContent
|
typeTemplateContent,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
@ -76,7 +76,7 @@ export async function getEntryData(
|
||||||
},
|
},
|
||||||
collectionConfig: CollectionConfig,
|
collectionConfig: CollectionConfig,
|
||||||
shouldEmitFile: boolean,
|
shouldEmitFile: boolean,
|
||||||
pluginContext: PluginContext
|
pluginContext: PluginContext,
|
||||||
) {
|
) {
|
||||||
let data;
|
let data;
|
||||||
if (collectionConfig.type === 'data') {
|
if (collectionConfig.type === 'data') {
|
||||||
|
@ -127,7 +127,7 @@ export async function getEntryData(
|
||||||
message: AstroErrorData.InvalidContentEntryFrontmatterError.message(
|
message: AstroErrorData.InvalidContentEntryFrontmatterError.message(
|
||||||
entry.collection,
|
entry.collection,
|
||||||
entry.id,
|
entry.id,
|
||||||
parsed.error
|
parsed.error,
|
||||||
),
|
),
|
||||||
location: {
|
location: {
|
||||||
file: entry._internal.filePath,
|
file: entry._internal.filePath,
|
||||||
|
@ -151,7 +151,7 @@ export function getDataEntryExts(settings: Pick<AstroSettings, 'dataEntryTypes'>
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getEntryConfigByExtMap<TEntryType extends ContentEntryType | DataEntryType>(
|
export function getEntryConfigByExtMap<TEntryType extends ContentEntryType | DataEntryType>(
|
||||||
entryTypes: TEntryType[]
|
entryTypes: TEntryType[],
|
||||||
): Map<string, TEntryType> {
|
): Map<string, TEntryType> {
|
||||||
const map = new Map<string, TEntryType>();
|
const map = new Map<string, TEntryType>();
|
||||||
for (const entryType of entryTypes) {
|
for (const entryType of entryTypes) {
|
||||||
|
@ -248,7 +248,7 @@ export function getDataEntryId({
|
||||||
const relativePath = getRelativeEntryPath(entry, collection, contentDir);
|
const relativePath = getRelativeEntryPath(entry, collection, contentDir);
|
||||||
const withoutFileExt = normalizePath(relativePath).replace(
|
const withoutFileExt = normalizePath(relativePath).replace(
|
||||||
new RegExp(path.extname(relativePath) + '$'),
|
new RegExp(path.extname(relativePath) + '$'),
|
||||||
''
|
'',
|
||||||
);
|
);
|
||||||
|
|
||||||
return withoutFileExt;
|
return withoutFileExt;
|
||||||
|
@ -290,7 +290,7 @@ export function getEntryType(
|
||||||
entryPath: string,
|
entryPath: string,
|
||||||
paths: Pick<ContentPaths, 'config' | 'contentDir'>,
|
paths: Pick<ContentPaths, 'config' | 'contentDir'>,
|
||||||
contentFileExts: string[],
|
contentFileExts: string[],
|
||||||
dataFileExts: string[]
|
dataFileExts: string[],
|
||||||
): 'content' | 'data' | 'config' | 'ignored' {
|
): 'content' | 'data' | 'config' | 'ignored' {
|
||||||
const { ext } = path.parse(entryPath);
|
const { ext } = path.parse(entryPath);
|
||||||
const fileUrl = pathToFileURL(entryPath);
|
const fileUrl = pathToFileURL(entryPath);
|
||||||
|
@ -310,7 +310,7 @@ export function getEntryType(
|
||||||
|
|
||||||
function hasUnderscoreBelowContentDirectoryPath(
|
function hasUnderscoreBelowContentDirectoryPath(
|
||||||
fileUrl: URL,
|
fileUrl: URL,
|
||||||
contentDir: ContentPaths['contentDir']
|
contentDir: ContentPaths['contentDir'],
|
||||||
): boolean {
|
): boolean {
|
||||||
const parts = fileUrl.pathname.replace(contentDir.pathname, '').split('/');
|
const parts = fileUrl.pathname.replace(contentDir.pathname, '').split('/');
|
||||||
for (const part of parts) {
|
for (const part of parts) {
|
||||||
|
@ -324,7 +324,7 @@ function getYAMLErrorLine(rawData: string | undefined, objectKey: string) {
|
||||||
const indexOfObjectKey = rawData.search(
|
const indexOfObjectKey = rawData.search(
|
||||||
// Match key either at the top of the file or after a newline
|
// Match key either at the top of the file or after a newline
|
||||||
// Ensures matching on top-level object keys only
|
// Ensures matching on top-level object keys only
|
||||||
new RegExp(`(\n|^)${objectKey}`)
|
new RegExp(`(\n|^)${objectKey}`),
|
||||||
);
|
);
|
||||||
if (indexOfObjectKey === -1) return 0;
|
if (indexOfObjectKey === -1) return 0;
|
||||||
|
|
||||||
|
@ -485,7 +485,7 @@ export type ContentPaths = {
|
||||||
|
|
||||||
export function getContentPaths(
|
export function getContentPaths(
|
||||||
{ srcDir }: Pick<AstroConfig, 'root' | 'srcDir'>,
|
{ srcDir }: Pick<AstroConfig, 'root' | 'srcDir'>,
|
||||||
fs: typeof fsMod = fsMod
|
fs: typeof fsMod = fsMod,
|
||||||
): ContentPaths {
|
): ContentPaths {
|
||||||
const configStats = search(fs, srcDir);
|
const configStats = search(fs, srcDir);
|
||||||
const pkgBase = new URL('../../', import.meta.url);
|
const pkgBase = new URL('../../', import.meta.url);
|
||||||
|
@ -499,7 +499,7 @@ export function getContentPaths(
|
||||||
}
|
}
|
||||||
function search(fs: typeof fsMod, srcDir: URL) {
|
function search(fs: typeof fsMod, srcDir: URL) {
|
||||||
const paths = ['config.mjs', 'config.js', 'config.mts', 'config.ts'].map(
|
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) {
|
for (const file of paths) {
|
||||||
if (fs.existsSync(file)) {
|
if (fs.existsSync(file)) {
|
||||||
|
|
|
@ -77,7 +77,7 @@ export function astroContentAssetPropagationPlugin({
|
||||||
: await getScriptsForURL(
|
: await getScriptsForURL(
|
||||||
pathToFileURL(basePath),
|
pathToFileURL(basePath),
|
||||||
settings.config.root,
|
settings.config.root,
|
||||||
devModuleLoader
|
devModuleLoader,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Register files we crawled to be able to retrieve the rendered styles and scripts,
|
// Register files we crawled to be able to retrieve the rendered styles and scripts,
|
||||||
|
@ -127,7 +127,7 @@ export function astroContentAssetPropagationPlugin({
|
||||||
|
|
||||||
export function astroConfigBuildPlugin(
|
export function astroConfigBuildPlugin(
|
||||||
options: StaticBuildOptions,
|
options: StaticBuildOptions,
|
||||||
internals: BuildInternals
|
internals: BuildInternals,
|
||||||
): AstroBuildPlugin {
|
): AstroBuildPlugin {
|
||||||
return {
|
return {
|
||||||
targets: ['server'],
|
targets: ['server'],
|
||||||
|
@ -176,7 +176,7 @@ export function astroConfigBuildPlugin(
|
||||||
if (entryStyles.size) {
|
if (entryStyles.size) {
|
||||||
newCode = newCode.replace(
|
newCode = newCode.replace(
|
||||||
JSON.stringify(STYLES_PLACEHOLDER),
|
JSON.stringify(STYLES_PLACEHOLDER),
|
||||||
JSON.stringify(Array.from(entryStyles))
|
JSON.stringify(Array.from(entryStyles)),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
newCode = newCode.replace(JSON.stringify(STYLES_PLACEHOLDER), '[]');
|
newCode = newCode.replace(JSON.stringify(STYLES_PLACEHOLDER), '[]');
|
||||||
|
@ -184,7 +184,7 @@ export function astroConfigBuildPlugin(
|
||||||
if (entryLinks.size) {
|
if (entryLinks.size) {
|
||||||
newCode = newCode.replace(
|
newCode = newCode.replace(
|
||||||
JSON.stringify(LINKS_PLACEHOLDER),
|
JSON.stringify(LINKS_PLACEHOLDER),
|
||||||
JSON.stringify(Array.from(entryLinks).map(prependBase))
|
JSON.stringify(Array.from(entryLinks).map(prependBase)),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
newCode = newCode.replace(JSON.stringify(LINKS_PLACEHOLDER), '[]');
|
newCode = newCode.replace(JSON.stringify(LINKS_PLACEHOLDER), '[]');
|
||||||
|
@ -210,8 +210,8 @@ export function astroConfigBuildPlugin(
|
||||||
type: 'module',
|
type: 'module',
|
||||||
},
|
},
|
||||||
children: '',
|
children: '',
|
||||||
}))
|
})),
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
newCode = newCode.replace(JSON.stringify(SCRIPTS_PLACEHOLDER), '[]');
|
newCode = newCode.replace(JSON.stringify(SCRIPTS_PLACEHOLDER), '[]');
|
||||||
|
|
|
@ -39,7 +39,7 @@ import {
|
||||||
|
|
||||||
function getContentRendererByViteId(
|
function getContentRendererByViteId(
|
||||||
viteId: string,
|
viteId: string,
|
||||||
settings: Pick<AstroSettings, 'contentEntryTypes'>
|
settings: Pick<AstroSettings, 'contentEntryTypes'>,
|
||||||
): ContentEntryType['getRenderModule'] | undefined {
|
): ContentEntryType['getRenderModule'] | undefined {
|
||||||
let ext = viteId.split('.').pop();
|
let ext = viteId.split('.').pop();
|
||||||
if (!ext) return undefined;
|
if (!ext) return undefined;
|
||||||
|
@ -215,7 +215,7 @@ type GetEntryModuleParams<TEntryType extends ContentEntryType | DataEntryType> =
|
||||||
};
|
};
|
||||||
|
|
||||||
async function getContentEntryModule(
|
async function getContentEntryModule(
|
||||||
params: GetEntryModuleParams<ContentEntryType>
|
params: GetEntryModuleParams<ContentEntryType>,
|
||||||
): Promise<ContentEntryModule> {
|
): Promise<ContentEntryModule> {
|
||||||
const { fileId, contentDir, pluginContext } = params;
|
const { fileId, contentDir, pluginContext } = params;
|
||||||
const { collectionConfig, entryConfig, entry, rawContents, collection } =
|
const { collectionConfig, entryConfig, entry, rawContents, collection } =
|
||||||
|
@ -245,7 +245,7 @@ async function getContentEntryModule(
|
||||||
{ id, collection, _internal, unvalidatedData },
|
{ id, collection, _internal, unvalidatedData },
|
||||||
collectionConfig,
|
collectionConfig,
|
||||||
params.shouldEmitFile,
|
params.shouldEmitFile,
|
||||||
pluginContext
|
pluginContext,
|
||||||
)
|
)
|
||||||
: unvalidatedData;
|
: unvalidatedData;
|
||||||
|
|
||||||
|
@ -262,7 +262,7 @@ async function getContentEntryModule(
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getDataEntryModule(
|
async function getDataEntryModule(
|
||||||
params: GetEntryModuleParams<DataEntryType>
|
params: GetEntryModuleParams<DataEntryType>,
|
||||||
): Promise<DataEntryModule> {
|
): Promise<DataEntryModule> {
|
||||||
const { fileId, contentDir, pluginContext } = params;
|
const { fileId, contentDir, pluginContext } = params;
|
||||||
const { collectionConfig, entryConfig, entry, rawContents, collection } =
|
const { collectionConfig, entryConfig, entry, rawContents, collection } =
|
||||||
|
@ -280,7 +280,7 @@ async function getDataEntryModule(
|
||||||
{ id, collection, _internal, unvalidatedData },
|
{ id, collection, _internal, unvalidatedData },
|
||||||
collectionConfig,
|
collectionConfig,
|
||||||
params.shouldEmitFile,
|
params.shouldEmitFile,
|
||||||
pluginContext
|
pluginContext,
|
||||||
)
|
)
|
||||||
: unvalidatedData;
|
: unvalidatedData;
|
||||||
|
|
||||||
|
@ -320,7 +320,7 @@ async function getEntryModuleBaseInfo<TEntryType extends ContentEntryType | Data
|
||||||
throw new AstroError({
|
throw new AstroError({
|
||||||
...AstroErrorData.UnknownContentCollectionError,
|
...AstroErrorData.UnknownContentCollectionError,
|
||||||
message: `No parser found for data entry ${JSON.stringify(
|
message: `No parser found for data entry ${JSON.stringify(
|
||||||
fileId
|
fileId,
|
||||||
)}. Did you apply an integration for this file type?`,
|
)}. Did you apply an integration for this file type?`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
@ -129,21 +129,21 @@ export async function generateContentEntryFile({
|
||||||
`import.meta.glob(${JSON.stringify(value)}, { query: { ${flag}: true } })`;
|
`import.meta.glob(${JSON.stringify(value)}, { query: { ${flag}: true } })`;
|
||||||
contentEntryGlobResult = createGlob(
|
contentEntryGlobResult = createGlob(
|
||||||
globWithUnderscoresIgnored(relContentDir, contentEntryExts),
|
globWithUnderscoresIgnored(relContentDir, contentEntryExts),
|
||||||
CONTENT_FLAG
|
CONTENT_FLAG,
|
||||||
);
|
);
|
||||||
dataEntryGlobResult = createGlob(
|
dataEntryGlobResult = createGlob(
|
||||||
globWithUnderscoresIgnored(relContentDir, dataEntryExts),
|
globWithUnderscoresIgnored(relContentDir, dataEntryExts),
|
||||||
DATA_FLAG
|
DATA_FLAG,
|
||||||
);
|
);
|
||||||
renderEntryGlobResult = createGlob(
|
renderEntryGlobResult = createGlob(
|
||||||
globWithUnderscoresIgnored(relContentDir, contentEntryExts),
|
globWithUnderscoresIgnored(relContentDir, contentEntryExts),
|
||||||
CONTENT_RENDER_FLAG
|
CONTENT_RENDER_FLAG,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
contentEntryGlobResult = getStringifiedCollectionFromLookup(
|
contentEntryGlobResult = getStringifiedCollectionFromLookup(
|
||||||
'content',
|
'content',
|
||||||
relContentDir,
|
relContentDir,
|
||||||
lookupMap
|
lookupMap,
|
||||||
);
|
);
|
||||||
dataEntryGlobResult = getStringifiedCollectionFromLookup('data', relContentDir, lookupMap);
|
dataEntryGlobResult = getStringifiedCollectionFromLookup('data', relContentDir, lookupMap);
|
||||||
renderEntryGlobResult = getStringifiedCollectionFromLookup('render', relContentDir, lookupMap);
|
renderEntryGlobResult = getStringifiedCollectionFromLookup('render', relContentDir, lookupMap);
|
||||||
|
@ -168,7 +168,7 @@ console.warn('astro:content is only supported running server-side. Using it in t
|
||||||
function getStringifiedCollectionFromLookup(
|
function getStringifiedCollectionFromLookup(
|
||||||
wantedType: 'content' | 'data' | 'render',
|
wantedType: 'content' | 'data' | 'render',
|
||||||
relContentDir: string,
|
relContentDir: string,
|
||||||
lookupMap: ContentLookupMap
|
lookupMap: ContentLookupMap,
|
||||||
) {
|
) {
|
||||||
let str = '{';
|
let str = '{';
|
||||||
// In dev, we don't need to normalize the import specifier at all. Vite handles it.
|
// In dev, we don't need to normalize the import specifier at all. Vite handles it.
|
||||||
|
@ -226,7 +226,7 @@ export async function generateLookupMap({
|
||||||
absolute: true,
|
absolute: true,
|
||||||
cwd: fileURLToPath(root),
|
cwd: fileURLToPath(root),
|
||||||
fs,
|
fs,
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
// Run 10 at a time to prevent `await getEntrySlug` from accessing the filesystem all at once.
|
// Run 10 at a time to prevent `await getEntrySlug` from accessing the filesystem all at once.
|
||||||
|
@ -276,7 +276,7 @@ export async function generateLookupMap({
|
||||||
collection,
|
collection,
|
||||||
slug,
|
slug,
|
||||||
lookupMap[collection].entries[slug],
|
lookupMap[collection].entries[slug],
|
||||||
rootRelativePath(root, filePath)
|
rootRelativePath(root, filePath),
|
||||||
),
|
),
|
||||||
hint:
|
hint:
|
||||||
slug !== generatedSlug
|
slug !== generatedSlug
|
||||||
|
@ -301,7 +301,7 @@ export async function generateLookupMap({
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -8,7 +8,7 @@ import type { OutgoingHttpHeaders } from 'node:http';
|
||||||
* @returns {OutgoingHttpHeaders} NodeJS OutgoingHttpHeaders object with multiple set-cookie handled as an array of values
|
* @returns {OutgoingHttpHeaders} NodeJS OutgoingHttpHeaders object with multiple set-cookie handled as an array of values
|
||||||
*/
|
*/
|
||||||
export const createOutgoingHttpHeaders = (
|
export const createOutgoingHttpHeaders = (
|
||||||
headers: Headers | undefined | null
|
headers: Headers | undefined | null,
|
||||||
): OutgoingHttpHeaders | undefined => {
|
): OutgoingHttpHeaders | undefined => {
|
||||||
if (!headers) {
|
if (!headers) {
|
||||||
return undefined;
|
return undefined;
|
||||||
|
|
|
@ -95,7 +95,7 @@ export class App {
|
||||||
this.#pipeline = this.#createPipeline(this.#manifestData, streaming);
|
this.#pipeline = this.#createPipeline(this.#manifestData, streaming);
|
||||||
this.#adapterLogger = new AstroIntegrationLogger(
|
this.#adapterLogger = new AstroIntegrationLogger(
|
||||||
this.#logger.options,
|
this.#logger.options,
|
||||||
this.#manifest.adapterName
|
this.#manifest.adapterName,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -114,7 +114,7 @@ export class App {
|
||||||
if (this.#manifest.checkOrigin) {
|
if (this.#manifest.checkOrigin) {
|
||||||
this.#manifest.middleware = sequence(
|
this.#manifest.middleware = sequence(
|
||||||
createOriginCheckMiddleware(),
|
createOriginCheckMiddleware(),
|
||||||
this.#manifest.middleware
|
this.#manifest.middleware,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -209,7 +209,7 @@ export class App {
|
||||||
let locale;
|
let locale;
|
||||||
const hostAsUrl = new URL(`${protocol}//${host}`);
|
const hostAsUrl = new URL(`${protocol}//${host}`);
|
||||||
for (const [domainKey, localeValue] of Object.entries(
|
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
|
// 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
|
// If not, then it means that the manifest was tampered
|
||||||
|
@ -226,7 +226,7 @@ export class App {
|
||||||
|
|
||||||
if (locale) {
|
if (locale) {
|
||||||
pathname = prependForwardSlash(
|
pathname = prependForwardSlash(
|
||||||
joinPaths(normalizeTheLocale(locale), this.removeBase(url.pathname))
|
joinPaths(normalizeTheLocale(locale), this.removeBase(url.pathname)),
|
||||||
);
|
);
|
||||||
if (url.pathname.endsWith('/')) {
|
if (url.pathname.endsWith('/')) {
|
||||||
pathname = appendForwardSlash(pathname);
|
pathname = appendForwardSlash(pathname);
|
||||||
|
@ -235,7 +235,7 @@ export class App {
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
this.#logger.error(
|
this.#logger.error(
|
||||||
'router',
|
'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}`);
|
this.#logger.error('router', `Error: ${e}`);
|
||||||
}
|
}
|
||||||
|
@ -253,7 +253,7 @@ export class App {
|
||||||
async render(
|
async render(
|
||||||
request: Request,
|
request: Request,
|
||||||
routeDataOrOptions?: RouteData | RenderOptions,
|
routeDataOrOptions?: RouteData | RenderOptions,
|
||||||
maybeLocals?: object
|
maybeLocals?: object,
|
||||||
): Promise<Response> {
|
): Promise<Response> {
|
||||||
let routeData: RouteData | undefined;
|
let routeData: RouteData | undefined;
|
||||||
let locals: object | undefined;
|
let locals: object | undefined;
|
||||||
|
@ -290,7 +290,7 @@ export class App {
|
||||||
this.#logger.debug(
|
this.#logger.debug(
|
||||||
'router',
|
'router',
|
||||||
'The adapter ' + this.#manifest.adapterName + ' provided a custom RouteData for ',
|
'The adapter ' + this.#manifest.adapterName + ' provided a custom RouteData for ',
|
||||||
request.url
|
request.url,
|
||||||
);
|
);
|
||||||
this.#logger.debug('router', 'RouteData:\n' + routeData);
|
this.#logger.debug('router', 'RouteData:\n' + routeData);
|
||||||
}
|
}
|
||||||
|
@ -370,7 +370,7 @@ export class App {
|
||||||
if (this.#renderOptionsDeprecationWarningShown) return;
|
if (this.#renderOptionsDeprecationWarningShown) return;
|
||||||
this.#logger.warn(
|
this.#logger.warn(
|
||||||
'deprecated',
|
'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;
|
this.#renderOptionsDeprecationWarningShown = true;
|
||||||
}
|
}
|
||||||
|
@ -404,7 +404,7 @@ export class App {
|
||||||
response: originalResponse,
|
response: originalResponse,
|
||||||
skipMiddleware = false,
|
skipMiddleware = false,
|
||||||
error,
|
error,
|
||||||
}: RenderErrorOptions
|
}: RenderErrorOptions,
|
||||||
): Promise<Response> {
|
): Promise<Response> {
|
||||||
const errorRoutePath = `/${status}${this.#manifest.trailingSlash === 'always' ? '/' : ''}`;
|
const errorRoutePath = `/${status}${this.#manifest.trailingSlash === 'always' ? '/' : ''}`;
|
||||||
const errorRouteData = matchRoute(errorRoutePath, this.#manifestData);
|
const errorRouteData = matchRoute(errorRoutePath, this.#manifestData);
|
||||||
|
@ -414,7 +414,7 @@ export class App {
|
||||||
const maybeDotHtml = errorRouteData.route.endsWith(`/${status}`) ? '.html' : '';
|
const maybeDotHtml = errorRouteData.route.endsWith(`/${status}`) ? '.html' : '';
|
||||||
const statusURL = new URL(
|
const statusURL = new URL(
|
||||||
`${this.#baseWithoutTrailingSlash}/${status}${maybeDotHtml}`,
|
`${this.#baseWithoutTrailingSlash}/${status}${maybeDotHtml}`,
|
||||||
url
|
url,
|
||||||
);
|
);
|
||||||
const response = await fetch(statusURL.toString());
|
const response = await fetch(statusURL.toString());
|
||||||
|
|
||||||
|
@ -459,7 +459,7 @@ export class App {
|
||||||
#mergeResponses(
|
#mergeResponses(
|
||||||
newResponse: Response,
|
newResponse: Response,
|
||||||
originalResponse?: Response,
|
originalResponse?: Response,
|
||||||
override?: { status: 404 | 500 }
|
override?: { status: 404 | 500 },
|
||||||
) {
|
) {
|
||||||
if (!originalResponse) {
|
if (!originalResponse) {
|
||||||
if (override !== undefined) {
|
if (override !== undefined) {
|
||||||
|
|
|
@ -37,7 +37,7 @@ export class NodeApp extends App {
|
||||||
render(
|
render(
|
||||||
req: NodeRequest | Request,
|
req: NodeRequest | Request,
|
||||||
routeDataOrOptions?: RouteData | RenderOptions,
|
routeDataOrOptions?: RouteData | RenderOptions,
|
||||||
maybeLocals?: object
|
maybeLocals?: object,
|
||||||
) {
|
) {
|
||||||
if (!(req instanceof Request)) {
|
if (!(req instanceof Request)) {
|
||||||
req = NodeApp.createRequest(req);
|
req = NodeApp.createRequest(req);
|
||||||
|
@ -120,7 +120,7 @@ export class NodeApp extends App {
|
||||||
// eslint-disable-next-line no-console
|
// eslint-disable-next-line no-console
|
||||||
console.error(
|
console.error(
|
||||||
`There was an uncaught error in the middle of the stream while rendering ${destination.req.url}.`,
|
`There was an uncaught error in the middle of the stream while rendering ${destination.req.url}.`,
|
||||||
err
|
err,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
|
@ -36,7 +36,7 @@ export class AppPipeline extends Pipeline {
|
||||||
| 'serverLike'
|
| 'serverLike'
|
||||||
| 'streaming'
|
| 'streaming'
|
||||||
| 'defaultRoutes'
|
| 'defaultRoutes'
|
||||||
>
|
>,
|
||||||
) {
|
) {
|
||||||
const pipeline = new AppPipeline(
|
const pipeline = new AppPipeline(
|
||||||
logger,
|
logger,
|
||||||
|
@ -55,7 +55,7 @@ export class AppPipeline extends Pipeline {
|
||||||
undefined,
|
undefined,
|
||||||
undefined,
|
undefined,
|
||||||
false,
|
false,
|
||||||
defaultRoutes
|
defaultRoutes,
|
||||||
);
|
);
|
||||||
pipeline.#manifestData = manifestData;
|
pipeline.#manifestData = manifestData;
|
||||||
return pipeline;
|
return pipeline;
|
||||||
|
@ -93,7 +93,7 @@ export class AppPipeline extends Pipeline {
|
||||||
async tryRewrite(
|
async tryRewrite(
|
||||||
payload: RewritePayload,
|
payload: RewritePayload,
|
||||||
request: Request,
|
request: Request,
|
||||||
_sourceRoute: RouteData
|
_sourceRoute: RouteData,
|
||||||
): Promise<[RouteData, ComponentInstance, URL]> {
|
): Promise<[RouteData, ComponentInstance, URL]> {
|
||||||
const [foundRoute, finalUrl] = findRouteToRewrite({
|
const [foundRoute, finalUrl] = findRouteToRewrite({
|
||||||
payload,
|
payload,
|
||||||
|
@ -125,7 +125,7 @@ export class AppPipeline extends Pipeline {
|
||||||
const importComponentInstance = this.manifest.pageMap.get(route.component);
|
const importComponentInstance = this.manifest.pageMap.get(route.component);
|
||||||
if (!importComponentInstance) {
|
if (!importComponentInstance) {
|
||||||
throw new Error(
|
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();
|
return await importComponentInstance();
|
||||||
|
@ -133,7 +133,7 @@ export class AppPipeline extends Pipeline {
|
||||||
return this.manifest.pageModule;
|
return this.manifest.pageModule;
|
||||||
}
|
}
|
||||||
throw new Error(
|
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.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -58,13 +58,13 @@ export abstract class Pipeline {
|
||||||
* Array of built-in, internal, routes.
|
* Array of built-in, internal, routes.
|
||||||
* Used to find the route module
|
* Used to find the route module
|
||||||
*/
|
*/
|
||||||
readonly defaultRoutes = createDefaultRoutes(manifest)
|
readonly defaultRoutes = createDefaultRoutes(manifest),
|
||||||
) {
|
) {
|
||||||
this.internalMiddleware = [];
|
this.internalMiddleware = [];
|
||||||
// We do use our middleware only if the user isn't using the manual setup
|
// We do use our middleware only if the user isn't using the manual setup
|
||||||
if (i18n?.strategy !== 'manual') {
|
if (i18n?.strategy !== 'manual') {
|
||||||
this.internalMiddleware.push(
|
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
|
// In SSR, getSecret should fail by default. Setting it here will run before the
|
||||||
|
@ -94,7 +94,7 @@ export abstract class Pipeline {
|
||||||
abstract tryRewrite(
|
abstract tryRewrite(
|
||||||
rewritePayload: RewritePayload,
|
rewritePayload: RewritePayload,
|
||||||
request: Request,
|
request: Request,
|
||||||
sourceRoute: RouteData
|
sourceRoute: RouteData,
|
||||||
): Promise<[RouteData, ComponentInstance, URL]>;
|
): Promise<[RouteData, ComponentInstance, URL]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
@ -10,7 +10,7 @@ function fromEntries<V>(entries: [string, V][]) {
|
||||||
|
|
||||||
export function addRollupInput(
|
export function addRollupInput(
|
||||||
inputOptions: Rollup.InputOptions,
|
inputOptions: Rollup.InputOptions,
|
||||||
newInputs: string[]
|
newInputs: string[],
|
||||||
): Rollup.InputOptions {
|
): Rollup.InputOptions {
|
||||||
// Add input module ids to existing input option, whether it's a string, array or object
|
// 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
|
// this way you can use multiple html plugins all adding their own inputs
|
||||||
|
|
|
@ -17,7 +17,7 @@ function getOutRoot(astroConfig: AstroConfig): URL {
|
||||||
export function getOutFolder(
|
export function getOutFolder(
|
||||||
astroConfig: AstroConfig,
|
astroConfig: AstroConfig,
|
||||||
pathname: string,
|
pathname: string,
|
||||||
routeData: RouteData
|
routeData: RouteData,
|
||||||
): URL {
|
): URL {
|
||||||
const outRoot = getOutRoot(astroConfig);
|
const outRoot = getOutRoot(astroConfig);
|
||||||
const routeType = routeData.type;
|
const routeType = routeData.type;
|
||||||
|
@ -59,7 +59,7 @@ export function getOutFile(
|
||||||
astroConfig: AstroConfig,
|
astroConfig: AstroConfig,
|
||||||
outFolder: URL,
|
outFolder: URL,
|
||||||
pathname: string,
|
pathname: string,
|
||||||
routeData: RouteData
|
routeData: RouteData,
|
||||||
): URL {
|
): URL {
|
||||||
const routeType = routeData.type;
|
const routeType = routeData.type;
|
||||||
switch (routeType) {
|
switch (routeType) {
|
||||||
|
|
|
@ -21,7 +21,7 @@ export function shortHashedName(settings: AstroSettings) {
|
||||||
return createNameHash(
|
return createNameHash(
|
||||||
getFirstParentId(parents),
|
getFirstParentId(parents),
|
||||||
parents.map((page) => page.id),
|
parents.map((page) => page.id),
|
||||||
settings
|
settings,
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
@ -29,7 +29,7 @@ export function shortHashedName(settings: AstroSettings) {
|
||||||
export function createNameHash(
|
export function createNameHash(
|
||||||
baseId: string | undefined,
|
baseId: string | undefined,
|
||||||
hashIds: string[],
|
hashIds: string[],
|
||||||
settings: AstroSettings
|
settings: AstroSettings,
|
||||||
): string {
|
): string {
|
||||||
const baseName = baseId ? prettifyBaseName(npath.parse(baseId).name) : 'index';
|
const baseName = baseId ? prettifyBaseName(npath.parse(baseId).name) : 'index';
|
||||||
const hash = crypto.createHash('sha256');
|
const hash = crypto.createHash('sha256');
|
||||||
|
|
|
@ -69,14 +69,14 @@ export async function generatePages(options: StaticBuildOptions, internals: Buil
|
||||||
// middleware.mjs is not emitted if there is no user middleware
|
// 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
|
// 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(
|
middleware = await import(new URL('middleware.mjs', baseDirectory).toString()).then(
|
||||||
(mod) => mod.onRequest
|
(mod) => mod.onRequest,
|
||||||
);
|
);
|
||||||
} catch {}
|
} catch {}
|
||||||
manifest = createBuildManifest(
|
manifest = createBuildManifest(
|
||||||
options.settings,
|
options.settings,
|
||||||
internals,
|
internals,
|
||||||
renderers.renderers as SSRLoadedRenderer[],
|
renderers.renderers as SSRLoadedRenderer[],
|
||||||
middleware
|
middleware,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
const pipeline = BuildPipeline.create({ internals, manifest, options });
|
const pipeline = BuildPipeline.create({ internals, manifest, options });
|
||||||
|
@ -118,7 +118,7 @@ export async function generatePages(options: StaticBuildOptions, internals: Buil
|
||||||
} else {
|
} else {
|
||||||
const ssrEntryURLPage = createEntryURL(filePath, outFolder);
|
const ssrEntryURLPage = createEntryURL(filePath, outFolder);
|
||||||
throw new Error(
|
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 {
|
} else {
|
||||||
|
@ -135,7 +135,7 @@ export async function generatePages(options: StaticBuildOptions, internals: Buil
|
||||||
}
|
}
|
||||||
logger.info(
|
logger.info(
|
||||||
null,
|
null,
|
||||||
green(`✓ Completed in ${getTimeStat(generatePagesTimer, performance.now())}.\n`)
|
green(`✓ Completed in ${getTimeStat(generatePagesTimer, performance.now())}.\n`),
|
||||||
);
|
);
|
||||||
|
|
||||||
const staticImageList = getStaticImageList();
|
const staticImageList = getStaticImageList();
|
||||||
|
@ -170,7 +170,7 @@ async function generatePage(
|
||||||
pageData: PageBuildData,
|
pageData: PageBuildData,
|
||||||
ssrEntry: SinglePageBuiltModule,
|
ssrEntry: SinglePageBuiltModule,
|
||||||
builtPaths: Set<string>,
|
builtPaths: Set<string>,
|
||||||
pipeline: BuildPipeline
|
pipeline: BuildPipeline,
|
||||||
) {
|
) {
|
||||||
// prepare information we need
|
// prepare information we need
|
||||||
const { config, logger } = pipeline;
|
const { config, logger } = pipeline;
|
||||||
|
@ -186,7 +186,7 @@ async function generatePage(
|
||||||
const scripts = pageData.hoistedScript ?? null;
|
const scripts = pageData.hoistedScript ?? null;
|
||||||
if (!pageModulePromise) {
|
if (!pageModulePromise) {
|
||||||
throw new Error(
|
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();
|
const pageModule = await pageModulePromise();
|
||||||
|
@ -241,7 +241,7 @@ async function getPathsForRoute(
|
||||||
route: RouteData,
|
route: RouteData,
|
||||||
mod: ComponentInstance,
|
mod: ComponentInstance,
|
||||||
pipeline: BuildPipeline,
|
pipeline: BuildPipeline,
|
||||||
builtPaths: Set<string>
|
builtPaths: Set<string>,
|
||||||
): Promise<Array<string>> {
|
): Promise<Array<string>> {
|
||||||
const { logger, options, routeCache, serverLike } = pipeline;
|
const { logger, options, routeCache, serverLike } = pipeline;
|
||||||
let paths: Array<string> = [];
|
let paths: Array<string> = [];
|
||||||
|
@ -263,7 +263,7 @@ async function getPathsForRoute(
|
||||||
const label = staticPaths.length === 1 ? 'page' : 'pages';
|
const label = staticPaths.length === 1 ? 'page' : 'pages';
|
||||||
logger.debug(
|
logger.debug(
|
||||||
'build',
|
'build',
|
||||||
`├── ${bold(green('√'))} ${route.component} → ${magenta(`[${staticPaths.length} ${label}]`)}`
|
`├── ${bold(green('√'))} ${route.component} → ${magenta(`[${staticPaths.length} ${label}]`)}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
paths = staticPaths
|
paths = staticPaths
|
||||||
|
@ -304,7 +304,7 @@ async function getPathsForRoute(
|
||||||
function getInvalidRouteSegmentError(
|
function getInvalidRouteSegmentError(
|
||||||
e: TypeError,
|
e: TypeError,
|
||||||
route: RouteData,
|
route: RouteData,
|
||||||
staticPath: GetStaticPathsItem
|
staticPath: GetStaticPathsItem,
|
||||||
): AstroError {
|
): AstroError {
|
||||||
const invalidParam = /^Expected "([^"]+)"/.exec(e.message)?.[1];
|
const invalidParam = /^Expected "([^"]+)"/.exec(e.message)?.[1];
|
||||||
const received = invalidParam ? staticPath.params[invalidParam] : undefined;
|
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';
|
'Learn about dynamic routes at https://docs.astro.build/en/core-concepts/routing/#dynamic-routes';
|
||||||
if (invalidParam && typeof received === 'string') {
|
if (invalidParam && typeof received === 'string') {
|
||||||
const matchingSegment = route.segments.find(
|
const matchingSegment = route.segments.find(
|
||||||
(segment) => segment[0]?.content === invalidParam
|
(segment) => segment[0]?.content === invalidParam,
|
||||||
)?.[0];
|
)?.[0];
|
||||||
const mightBeMissingSpread = matchingSegment?.dynamic && !matchingSegment?.spread;
|
const mightBeMissingSpread = matchingSegment?.dynamic && !matchingSegment?.spread;
|
||||||
if (mightBeMissingSpread) {
|
if (mightBeMissingSpread) {
|
||||||
|
@ -325,7 +325,7 @@ function getInvalidRouteSegmentError(
|
||||||
? AstroErrorData.InvalidDynamicRoute.message(
|
? AstroErrorData.InvalidDynamicRoute.message(
|
||||||
route.route,
|
route.route,
|
||||||
JSON.stringify(invalidParam),
|
JSON.stringify(invalidParam),
|
||||||
JSON.stringify(received)
|
JSON.stringify(received),
|
||||||
)
|
)
|
||||||
: `Generated path for ${route.route} is invalid.`,
|
: `Generated path for ${route.route} is invalid.`,
|
||||||
hint,
|
hint,
|
||||||
|
@ -355,7 +355,7 @@ function getUrlForPath(
|
||||||
origin: string,
|
origin: string,
|
||||||
format: AstroConfig['build']['format'],
|
format: AstroConfig['build']['format'],
|
||||||
trailingSlash: AstroConfig['trailingSlash'],
|
trailingSlash: AstroConfig['trailingSlash'],
|
||||||
routeType: RouteType
|
routeType: RouteType,
|
||||||
): URL {
|
): URL {
|
||||||
/**
|
/**
|
||||||
* Examples:
|
* Examples:
|
||||||
|
@ -402,7 +402,7 @@ async function generatePath(
|
||||||
pathname: string,
|
pathname: string,
|
||||||
pipeline: BuildPipeline,
|
pipeline: BuildPipeline,
|
||||||
gopts: GeneratePathOptions,
|
gopts: GeneratePathOptions,
|
||||||
route: RouteData
|
route: RouteData,
|
||||||
) {
|
) {
|
||||||
const { mod } = gopts;
|
const { mod } = gopts;
|
||||||
const { config, logger, options } = pipeline;
|
const { config, logger, options } = pipeline;
|
||||||
|
@ -432,7 +432,7 @@ async function generatePath(
|
||||||
options.origin,
|
options.origin,
|
||||||
config.build.format,
|
config.build.format,
|
||||||
config.trailingSlash,
|
config.trailingSlash,
|
||||||
route.type
|
route.type,
|
||||||
);
|
);
|
||||||
|
|
||||||
const request = createRequest({
|
const request = createRequest({
|
||||||
|
@ -520,7 +520,7 @@ function createBuildManifest(
|
||||||
settings: AstroSettings,
|
settings: AstroSettings,
|
||||||
internals: BuildInternals,
|
internals: BuildInternals,
|
||||||
renderers: SSRLoadedRenderer[],
|
renderers: SSRLoadedRenderer[],
|
||||||
middleware: MiddlewareHandler
|
middleware: MiddlewareHandler,
|
||||||
): SSRManifest {
|
): SSRManifest {
|
||||||
let i18nManifest: SSRManifestI18n | undefined = undefined;
|
let i18nManifest: SSRManifestI18n | undefined = undefined;
|
||||||
if (settings.config.i18n) {
|
if (settings.config.i18n) {
|
||||||
|
|
|
@ -17,7 +17,7 @@ export function getParentExtendedModuleInfos(
|
||||||
order = 0,
|
order = 0,
|
||||||
childId = '',
|
childId = '',
|
||||||
seen = new Set<string>(),
|
seen = new Set<string>(),
|
||||||
accumulated: ExtendedModuleInfo[] = []
|
accumulated: ExtendedModuleInfo[] = [],
|
||||||
): ExtendedModuleInfo[] {
|
): ExtendedModuleInfo[] {
|
||||||
seen.add(id);
|
seen.add(id);
|
||||||
|
|
||||||
|
@ -54,7 +54,7 @@ export function getParentModuleInfos(
|
||||||
ctx: { getModuleInfo: GetModuleInfo },
|
ctx: { getModuleInfo: GetModuleInfo },
|
||||||
until?: (importer: string) => boolean,
|
until?: (importer: string) => boolean,
|
||||||
seen = new Set<string>(),
|
seen = new Set<string>(),
|
||||||
accumulated: ModuleInfo[] = []
|
accumulated: ModuleInfo[] = [],
|
||||||
): ModuleInfo[] {
|
): ModuleInfo[] {
|
||||||
seen.add(id);
|
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.
|
// This could be a .astro page, a .markdown or a .md (or really any file extension for markdown files) page.
|
||||||
export function getTopLevelPageModuleInfos(
|
export function getTopLevelPageModuleInfos(
|
||||||
id: string,
|
id: string,
|
||||||
ctx: { getModuleInfo: GetModuleInfo }
|
ctx: { getModuleInfo: GetModuleInfo },
|
||||||
): ModuleInfo[] {
|
): ModuleInfo[] {
|
||||||
return getParentModuleInfos(id, ctx).filter(moduleIsTopLevelPage);
|
return getParentModuleInfos(id, ctx).filter(moduleIsTopLevelPage);
|
||||||
}
|
}
|
||||||
|
|
|
@ -61,7 +61,7 @@ export interface BuildOptions {
|
||||||
*/
|
*/
|
||||||
export default async function build(
|
export default async function build(
|
||||||
inlineConfig: AstroInlineConfig,
|
inlineConfig: AstroInlineConfig,
|
||||||
options: BuildOptions = {}
|
options: BuildOptions = {},
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
ensureProcessNodeEnv('production');
|
ensureProcessNodeEnv('production');
|
||||||
applyPolyfill();
|
applyPolyfill();
|
||||||
|
@ -140,7 +140,13 @@ class AstroBuilder {
|
||||||
middlewareMode: true,
|
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 });
|
await runHookConfigDone({ settings: this.settings, logger: logger });
|
||||||
|
|
||||||
|
@ -182,7 +188,7 @@ class AstroBuilder {
|
||||||
this.timer.buildStart = performance.now();
|
this.timer.buildStart = performance.now();
|
||||||
this.logger.info(
|
this.logger.info(
|
||||||
'build',
|
'build',
|
||||||
green(`✓ Completed in ${getTimeStat(this.timer.init, performance.now())}.`)
|
green(`✓ Completed in ${getTimeStat(this.timer.init, performance.now())}.`),
|
||||||
);
|
);
|
||||||
|
|
||||||
const opts: StaticBuildOptions = {
|
const opts: StaticBuildOptions = {
|
||||||
|
@ -221,7 +227,7 @@ class AstroBuilder {
|
||||||
.concat(
|
.concat(
|
||||||
this.settings.config.experimental.serverIslands
|
this.settings.config.experimental.serverIslands
|
||||||
? [getServerIslandRouteData(this.settings.config)]
|
? [getServerIslandRouteData(this.settings.config)]
|
||||||
: []
|
: [],
|
||||||
),
|
),
|
||||||
logging: this.logger,
|
logging: this.logger,
|
||||||
cacheManifest: internals.cacheManifestUsed,
|
cacheManifest: internals.cacheManifestUsed,
|
||||||
|
@ -256,7 +262,7 @@ class AstroBuilder {
|
||||||
// outDir gets blown away so it can't be the root.
|
// outDir gets blown away so it can't be the root.
|
||||||
if (config.outDir.toString() === config.root.toString()) {
|
if (config.outDir.toString() === config.root.toString()) {
|
||||||
throw new Error(
|
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.`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -150,7 +150,7 @@ export function trackPageData(
|
||||||
component: string,
|
component: string,
|
||||||
pageData: PageBuildData,
|
pageData: PageBuildData,
|
||||||
componentModuleId: string,
|
componentModuleId: string,
|
||||||
componentURL: URL
|
componentURL: URL,
|
||||||
): void {
|
): void {
|
||||||
pageData.moduleSpecifier = componentModuleId;
|
pageData.moduleSpecifier = componentModuleId;
|
||||||
internals.pagesByKeys.set(pageData.key, pageData);
|
internals.pagesByKeys.set(pageData.key, pageData);
|
||||||
|
@ -163,7 +163,7 @@ export function trackPageData(
|
||||||
export function trackClientOnlyPageDatas(
|
export function trackClientOnlyPageDatas(
|
||||||
internals: BuildInternals,
|
internals: BuildInternals,
|
||||||
pageData: PageBuildData,
|
pageData: PageBuildData,
|
||||||
clientOnlys: string[]
|
clientOnlys: string[],
|
||||||
) {
|
) {
|
||||||
for (const clientOnlyComponent of clientOnlys) {
|
for (const clientOnlyComponent of clientOnlys) {
|
||||||
let pageDataSet: Set<PageBuildData>;
|
let pageDataSet: Set<PageBuildData>;
|
||||||
|
@ -184,7 +184,7 @@ export function trackClientOnlyPageDatas(
|
||||||
export function trackScriptPageDatas(
|
export function trackScriptPageDatas(
|
||||||
internals: BuildInternals,
|
internals: BuildInternals,
|
||||||
pageData: PageBuildData,
|
pageData: PageBuildData,
|
||||||
scriptIds: string[]
|
scriptIds: string[],
|
||||||
) {
|
) {
|
||||||
for (const scriptId of scriptIds) {
|
for (const scriptId of scriptIds) {
|
||||||
let pageDataSet: Set<PageBuildData>;
|
let pageDataSet: Set<PageBuildData>;
|
||||||
|
@ -200,7 +200,7 @@ export function trackScriptPageDatas(
|
||||||
|
|
||||||
export function* getPageDatasByClientOnlyID(
|
export function* getPageDatasByClientOnlyID(
|
||||||
internals: BuildInternals,
|
internals: BuildInternals,
|
||||||
viteid: ViteID
|
viteid: ViteID,
|
||||||
): Generator<PageBuildData, void, unknown> {
|
): Generator<PageBuildData, void, unknown> {
|
||||||
const pagesByClientOnly = internals.pagesByClientOnly;
|
const pagesByClientOnly = internals.pagesByClientOnly;
|
||||||
if (pagesByClientOnly.size) {
|
if (pagesByClientOnly.size) {
|
||||||
|
@ -238,7 +238,7 @@ export function* getPageDatasByClientOnlyID(
|
||||||
export function getPageData(
|
export function getPageData(
|
||||||
internals: BuildInternals,
|
internals: BuildInternals,
|
||||||
route: string,
|
route: string,
|
||||||
component: string
|
component: string,
|
||||||
): PageBuildData | undefined {
|
): PageBuildData | undefined {
|
||||||
let pageData = internals.pagesByKeys.get(makePageDataKey(route, component));
|
let pageData = internals.pagesByKeys.get(makePageDataKey(route, component));
|
||||||
if (pageData) {
|
if (pageData) {
|
||||||
|
@ -271,7 +271,7 @@ function getPagesDatasByComponent(internals: BuildInternals, component: string):
|
||||||
* @param pagesByKeys A map of all page data by their internal key
|
* @param pagesByKeys A map of all page data by their internal key
|
||||||
*/
|
*/
|
||||||
export function getPageDatasWithPublicKey(
|
export function getPageDatasWithPublicKey(
|
||||||
pagesByKeys: Map<string, PageBuildData>
|
pagesByKeys: Map<string, PageBuildData>,
|
||||||
): Map<string, PageBuildData> {
|
): Map<string, PageBuildData> {
|
||||||
// Create a map to store the pages with the public key, mimicking internal.pagesByKeys
|
// Create a map to store the pages with the public key, mimicking internal.pagesByKeys
|
||||||
const pagesWithPublicKey = new Map<string, PageBuildData>();
|
const pagesWithPublicKey = new Map<string, PageBuildData>();
|
||||||
|
@ -303,7 +303,7 @@ export function getPageDatasWithPublicKey(
|
||||||
|
|
||||||
export function getPageDataByViteID(
|
export function getPageDataByViteID(
|
||||||
internals: BuildInternals,
|
internals: BuildInternals,
|
||||||
viteid: ViteID
|
viteid: ViteID,
|
||||||
): PageBuildData | undefined {
|
): PageBuildData | undefined {
|
||||||
if (internals.pagesByViteID.has(viteid)) {
|
if (internals.pagesByViteID.has(viteid)) {
|
||||||
return internals.pagesByViteID.get(viteid);
|
return internals.pagesByViteID.get(viteid);
|
||||||
|
@ -358,7 +358,7 @@ export function cssOrder(a: OrderInfo, b: OrderInfo) {
|
||||||
|
|
||||||
export function mergeInlineCss(
|
export function mergeInlineCss(
|
||||||
acc: Array<StylesheetAsset>,
|
acc: Array<StylesheetAsset>,
|
||||||
current: StylesheetAsset
|
current: StylesheetAsset,
|
||||||
): Array<StylesheetAsset> {
|
): Array<StylesheetAsset> {
|
||||||
const lastAdded = acc.at(acc.length - 1);
|
const lastAdded = acc.at(acc.length - 1);
|
||||||
const lastWasInline = lastAdded?.type === 'inline';
|
const lastWasInline = lastAdded?.type === 'inline';
|
||||||
|
@ -379,7 +379,7 @@ export function mergeInlineCss(
|
||||||
*/
|
*/
|
||||||
export function getPageDatasByHoistedScriptId(
|
export function getPageDatasByHoistedScriptId(
|
||||||
internals: BuildInternals,
|
internals: BuildInternals,
|
||||||
id: string
|
id: string,
|
||||||
): PageBuildData[] {
|
): PageBuildData[] {
|
||||||
const set = internals.hoistedScriptIdToPagesMap.get(id);
|
const set = internals.hoistedScriptIdToPagesMap.get(id);
|
||||||
const pageDatas: PageBuildData[] = [];
|
const pageDatas: PageBuildData[] = [];
|
||||||
|
|
|
@ -46,7 +46,7 @@ export function collectPagesData(opts: CollectPagesDataOptions): CollectPagesDat
|
||||||
const html = `${route.pathname}`.replace(/\/?$/, '/index.html');
|
const html = `${route.pathname}`.replace(/\/?$/, '/index.html');
|
||||||
debug(
|
debug(
|
||||||
'build',
|
'build',
|
||||||
`├── ${colors.bold(colors.green('✔'))} ${route.component} → ${colors.yellow(html)}`
|
`├── ${colors.bold(colors.green('✔'))} ${route.component} → ${colors.yellow(html)}`,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
debug('build', `├── ${colors.bold(colors.green('✔'))} ${route.component}`);
|
debug('build', `├── ${colors.bold(colors.green('✔'))} ${route.component}`);
|
||||||
|
|
|
@ -54,7 +54,7 @@ export class BuildPipeline extends Pipeline {
|
||||||
readonly options: StaticBuildOptions,
|
readonly options: StaticBuildOptions,
|
||||||
readonly config = options.settings.config,
|
readonly config = options.settings.config,
|
||||||
readonly settings = options.settings,
|
readonly settings = options.settings,
|
||||||
readonly defaultRoutes = createDefaultRoutes(manifest)
|
readonly defaultRoutes = createDefaultRoutes(manifest),
|
||||||
) {
|
) {
|
||||||
const resolveCache = new Map<string, string>();
|
const resolveCache = new Map<string, string>();
|
||||||
|
|
||||||
|
@ -87,7 +87,7 @@ export class BuildPipeline extends Pipeline {
|
||||||
manifest.renderers,
|
manifest.renderers,
|
||||||
resolve,
|
resolve,
|
||||||
serverLike,
|
serverLike,
|
||||||
streaming
|
streaming,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -114,18 +114,18 @@ export class BuildPipeline extends Pipeline {
|
||||||
*/
|
*/
|
||||||
static async retrieveManifest(
|
static async retrieveManifest(
|
||||||
staticBuildOptions: StaticBuildOptions,
|
staticBuildOptions: StaticBuildOptions,
|
||||||
internals: BuildInternals
|
internals: BuildInternals,
|
||||||
): Promise<SSRManifest> {
|
): Promise<SSRManifest> {
|
||||||
const config = staticBuildOptions.settings.config;
|
const config = staticBuildOptions.settings.config;
|
||||||
const baseDirectory = getOutputDirectory(config);
|
const baseDirectory = getOutputDirectory(config);
|
||||||
const manifestEntryUrl = new URL(
|
const manifestEntryUrl = new URL(
|
||||||
`${internals.manifestFileName}?time=${Date.now()}`,
|
`${internals.manifestFileName}?time=${Date.now()}`,
|
||||||
baseDirectory
|
baseDirectory,
|
||||||
);
|
);
|
||||||
const { manifest } = await import(manifestEntryUrl.toString());
|
const { manifest } = await import(manifestEntryUrl.toString());
|
||||||
if (!manifest) {
|
if (!manifest) {
|
||||||
throw new Error(
|
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) {
|
if (!renderers) {
|
||||||
throw new Error(
|
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 {
|
return {
|
||||||
|
@ -161,7 +161,7 @@ export class BuildPipeline extends Pipeline {
|
||||||
const scripts = createModuleScriptsSet(
|
const scripts = createModuleScriptsSet(
|
||||||
pageBuildData?.hoistedScript ? [pageBuildData.hoistedScript] : [],
|
pageBuildData?.hoistedScript ? [pageBuildData.hoistedScript] : [],
|
||||||
base,
|
base,
|
||||||
assetsPrefix
|
assetsPrefix,
|
||||||
);
|
);
|
||||||
const sortedCssAssets = pageBuildData?.styles
|
const sortedCssAssets = pageBuildData?.styles
|
||||||
.sort(cssOrder)
|
.sort(cssOrder)
|
||||||
|
@ -216,8 +216,8 @@ export class BuildPipeline extends Pipeline {
|
||||||
...getPagesFromVirtualModulePageName(
|
...getPagesFromVirtualModulePageName(
|
||||||
this.internals,
|
this.internals,
|
||||||
ASTRO_PAGE_RESOLVED_MODULE_ID,
|
ASTRO_PAGE_RESOLVED_MODULE_ID,
|
||||||
virtualModulePageName
|
virtualModulePageName,
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (virtualModulePageName.includes(RESOLVED_SPLIT_MODULE_ID)) {
|
if (virtualModulePageName.includes(RESOLVED_SPLIT_MODULE_ID)) {
|
||||||
|
@ -225,8 +225,8 @@ export class BuildPipeline extends Pipeline {
|
||||||
...getPagesFromVirtualModulePageName(
|
...getPagesFromVirtualModulePageName(
|
||||||
this.internals,
|
this.internals,
|
||||||
RESOLVED_SPLIT_MODULE_ID,
|
RESOLVED_SPLIT_MODULE_ID,
|
||||||
virtualModulePageName
|
virtualModulePageName,
|
||||||
)
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
for (const pageData of pageDatas) {
|
for (const pageData of pageDatas) {
|
||||||
|
@ -288,7 +288,7 @@ export class BuildPipeline extends Pipeline {
|
||||||
async tryRewrite(
|
async tryRewrite(
|
||||||
payload: RewritePayload,
|
payload: RewritePayload,
|
||||||
request: Request,
|
request: Request,
|
||||||
_sourceRoute: RouteData
|
_sourceRoute: RouteData,
|
||||||
): Promise<[RouteData, ComponentInstance, URL]> {
|
): Promise<[RouteData, ComponentInstance, URL]> {
|
||||||
const [foundRoute, finalUrl] = findRouteToRewrite({
|
const [foundRoute, finalUrl] = findRouteToRewrite({
|
||||||
payload,
|
payload,
|
||||||
|
@ -324,7 +324,7 @@ export class BuildPipeline extends Pipeline {
|
||||||
async #getEntryForFallbackRoute(
|
async #getEntryForFallbackRoute(
|
||||||
route: RouteData,
|
route: RouteData,
|
||||||
internals: BuildInternals,
|
internals: BuildInternals,
|
||||||
outFolder: URL
|
outFolder: URL,
|
||||||
): Promise<SinglePageBuiltModule> {
|
): Promise<SinglePageBuiltModule> {
|
||||||
if (route.type !== 'fallback') {
|
if (route.type !== 'fallback') {
|
||||||
throw new Error(`Expected a redirect route.`);
|
throw new Error(`Expected a redirect route.`);
|
||||||
|
@ -344,7 +344,7 @@ export class BuildPipeline extends Pipeline {
|
||||||
async #getEntryForRedirectRoute(
|
async #getEntryForRedirectRoute(
|
||||||
route: RouteData,
|
route: RouteData,
|
||||||
internals: BuildInternals,
|
internals: BuildInternals,
|
||||||
outFolder: URL
|
outFolder: URL,
|
||||||
): Promise<SinglePageBuiltModule> {
|
): Promise<SinglePageBuiltModule> {
|
||||||
if (route.type !== 'redirect') {
|
if (route.type !== 'redirect') {
|
||||||
throw new Error(`Expected a redirect route.`);
|
throw new Error(`Expected a redirect route.`);
|
||||||
|
|
|
@ -22,7 +22,7 @@ The emitted file has content similar to:
|
||||||
const renderers = [
|
const renderers = [
|
||||||
Object.assign(
|
Object.assign(
|
||||||
{ name: 'astro:jsx', serverEntrypoint: 'astro/jsx/server.js', jsxImportSource: 'astro' },
|
{ name: 'astro:jsx', serverEntrypoint: 'astro/jsx/server.js', jsxImportSource: 'astro' },
|
||||||
{ ssr: server_default }
|
{ ssr: server_default },
|
||||||
),
|
),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|
|
@ -28,7 +28,7 @@ function isPropagatedAsset(id: string) {
|
||||||
|
|
||||||
export function vitePluginAnalyzer(
|
export function vitePluginAnalyzer(
|
||||||
options: StaticBuildOptions,
|
options: StaticBuildOptions,
|
||||||
internals: BuildInternals
|
internals: BuildInternals,
|
||||||
): VitePlugin {
|
): VitePlugin {
|
||||||
function hoistedScriptScanner() {
|
function hoistedScriptScanner() {
|
||||||
const uniqueHoistedIds = new Map<string, string>();
|
const uniqueHoistedIds = new Map<string, string>();
|
||||||
|
@ -43,7 +43,7 @@ export function vitePluginAnalyzer(
|
||||||
async scan(
|
async scan(
|
||||||
this: PluginContext,
|
this: PluginContext,
|
||||||
scripts: AstroPluginMetadata['astro']['scripts'],
|
scripts: AstroPluginMetadata['astro']['scripts'],
|
||||||
from: string
|
from: string,
|
||||||
) {
|
) {
|
||||||
const hoistedScripts = new Set<string>();
|
const hoistedScripts = new Set<string>();
|
||||||
for (let i = 0; i < scripts.length; i++) {
|
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.
|
// `discoveredScripts` here, which will eventually be passed as inputs of the client build.
|
||||||
if (options.settings.config.experimental.directRenderScript && astro.scripts.length) {
|
if (options.settings.config.experimental.directRenderScript && astro.scripts.length) {
|
||||||
const scriptIds = astro.scripts.map(
|
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
|
// Assign as entrypoints for the client bundle
|
||||||
|
@ -204,7 +204,7 @@ export function vitePluginAnalyzer(
|
||||||
|
|
||||||
export function pluginAnalyzer(
|
export function pluginAnalyzer(
|
||||||
options: StaticBuildOptions,
|
options: StaticBuildOptions,
|
||||||
internals: BuildInternals
|
internals: BuildInternals,
|
||||||
): AstroBuildPlugin {
|
): AstroBuildPlugin {
|
||||||
return {
|
return {
|
||||||
targets: ['server'],
|
targets: ['server'],
|
||||||
|
|
|
@ -80,7 +80,7 @@ function vitePluginContent(
|
||||||
opts: StaticBuildOptions,
|
opts: StaticBuildOptions,
|
||||||
lookupMap: ContentLookupMap,
|
lookupMap: ContentLookupMap,
|
||||||
internals: BuildInternals,
|
internals: BuildInternals,
|
||||||
cachedBuildOutput: Array<{ cached: URL; dist: URL }>
|
cachedBuildOutput: Array<{ cached: URL; dist: URL }>,
|
||||||
): VitePlugin {
|
): VitePlugin {
|
||||||
const { config } = opts.settings;
|
const { config } = opts.settings;
|
||||||
const distContentRoot = getContentRoot(config);
|
const distContentRoot = getContentRoot(config);
|
||||||
|
@ -184,7 +184,7 @@ function vitePluginContent(
|
||||||
) {
|
) {
|
||||||
const [srcRelativePath] = id.replace(rootPath, '/').split('?');
|
const [srcRelativePath] = id.replace(rootPath, '/').split('?');
|
||||||
const resultId = encodeName(
|
const resultId = encodeName(
|
||||||
`${removeLeadingForwardSlash(removeFileExtension(srcRelativePath))}.render.mjs`
|
`${removeLeadingForwardSlash(removeFileExtension(srcRelativePath))}.render.mjs`,
|
||||||
);
|
);
|
||||||
return resultId;
|
return resultId;
|
||||||
}
|
}
|
||||||
|
@ -192,7 +192,7 @@ function vitePluginContent(
|
||||||
const collectionEntry = findEntryFromSrcRelativePath(
|
const collectionEntry = findEntryFromSrcRelativePath(
|
||||||
lookupMap,
|
lookupMap,
|
||||||
srcRelativePath,
|
srcRelativePath,
|
||||||
entryCache
|
entryCache,
|
||||||
);
|
);
|
||||||
if (collectionEntry) {
|
if (collectionEntry) {
|
||||||
let suffix = '.mjs';
|
let suffix = '.mjs';
|
||||||
|
@ -201,7 +201,7 @@ function vitePluginContent(
|
||||||
}
|
}
|
||||||
id =
|
id =
|
||||||
removeLeadingForwardSlash(
|
removeLeadingForwardSlash(
|
||||||
removeFileExtension(encodeName(id.replace(srcPath, '/')))
|
removeFileExtension(encodeName(id.replace(srcPath, '/'))),
|
||||||
) + suffix;
|
) + suffix;
|
||||||
return id;
|
return id;
|
||||||
}
|
}
|
||||||
|
@ -284,7 +284,7 @@ function vitePluginContent(
|
||||||
function findEntryFromSrcRelativePath(
|
function findEntryFromSrcRelativePath(
|
||||||
lookupMap: ContentLookupMap,
|
lookupMap: ContentLookupMap,
|
||||||
srcRelativePath: string,
|
srcRelativePath: string,
|
||||||
entryCache: Map<string, string>
|
entryCache: Map<string, string>,
|
||||||
) {
|
) {
|
||||||
let value = entryCache.get(srcRelativePath);
|
let value = entryCache.get(srcRelativePath);
|
||||||
if (value) return value;
|
if (value) return value;
|
||||||
|
@ -308,7 +308,7 @@ interface ContentEntries {
|
||||||
|
|
||||||
function getEntriesFromManifests(
|
function getEntriesFromManifests(
|
||||||
oldManifest: ContentManifest,
|
oldManifest: ContentManifest,
|
||||||
newManifest: ContentManifest
|
newManifest: ContentManifest,
|
||||||
): ContentEntries {
|
): ContentEntries {
|
||||||
const { entries: oldEntries } = oldManifest;
|
const { entries: oldEntries } = oldManifest;
|
||||||
const { entries: newEntries } = newManifest;
|
const { entries: newEntries } = newManifest;
|
||||||
|
@ -320,7 +320,7 @@ function getEntriesFromManifests(
|
||||||
return entries;
|
return entries;
|
||||||
}
|
}
|
||||||
const oldEntryHashMap = new Map<string, ContentManifestKey>(
|
const oldEntryHashMap = new Map<string, ContentManifestKey>(
|
||||||
oldEntries.map(([key, hash]) => [hash, key])
|
oldEntries.map(([key, hash]) => [hash, key]),
|
||||||
);
|
);
|
||||||
|
|
||||||
for (const [entry, hash] of newEntryMap) {
|
for (const [entry, hash] of newEntryMap) {
|
||||||
|
@ -367,7 +367,7 @@ function manifestState(oldManifest: ContentManifest, newManifest: ContentManifes
|
||||||
|
|
||||||
async function generateContentManifest(
|
async function generateContentManifest(
|
||||||
opts: StaticBuildOptions,
|
opts: StaticBuildOptions,
|
||||||
lookupMap: ContentLookupMap
|
lookupMap: ContentLookupMap,
|
||||||
): Promise<ContentManifest> {
|
): Promise<ContentManifest> {
|
||||||
let manifest = createContentManifest();
|
let manifest = createContentManifest();
|
||||||
manifest.version = CONTENT_MANIFEST_VERSION;
|
manifest.version = CONTENT_MANIFEST_VERSION;
|
||||||
|
@ -382,7 +382,7 @@ async function generateContentManifest(
|
||||||
limit(async () => {
|
limit(async () => {
|
||||||
const data = await fsMod.promises.readFile(fileURL, { encoding: 'utf8' });
|
const data = await fsMod.promises.readFile(fileURL, { encoding: 'utf8' });
|
||||||
manifest.entries.push([key, checksum(data, fileURL.toString())]);
|
manifest.entries.push([key, checksum(data, fileURL.toString())]);
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -480,7 +480,7 @@ export async function copyContentToCache(opts: StaticBuildOptions) {
|
||||||
|
|
||||||
export function pluginContent(
|
export function pluginContent(
|
||||||
opts: StaticBuildOptions,
|
opts: StaticBuildOptions,
|
||||||
internals: BuildInternals
|
internals: BuildInternals,
|
||||||
): AstroBuildPlugin {
|
): AstroBuildPlugin {
|
||||||
const { cacheDir, outDir } = opts.settings.config;
|
const { cacheDir, outDir } = opts.settings.config;
|
||||||
|
|
||||||
|
|
|
@ -30,7 +30,7 @@ interface PluginOptions {
|
||||||
|
|
||||||
export function pluginCSS(
|
export function pluginCSS(
|
||||||
options: StaticBuildOptions,
|
options: StaticBuildOptions,
|
||||||
internals: BuildInternals
|
internals: BuildInternals,
|
||||||
): AstroBuildPlugin {
|
): AstroBuildPlugin {
|
||||||
return {
|
return {
|
||||||
targets: ['client', 'server'],
|
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
|
// Ref: https://github.com/vitejs/vite/blob/b2c0ee04d4db4a0ef5a084c50f49782c5f88587c/packages/vite/src/node/plugins/html.ts#L690-L705
|
||||||
if (resolvedConfig.build.cssCodeSplit) return;
|
if (resolvedConfig.build.cssCodeSplit) return;
|
||||||
const cssChunk = Object.values(bundle).find(
|
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;
|
if (cssChunk === undefined) return;
|
||||||
for (const pageData of internals.pagesByKeys.values()) {
|
for (const pageData of internals.pagesByKeys.values()) {
|
||||||
|
@ -293,7 +293,7 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] {
|
||||||
function* getParentClientOnlys(
|
function* getParentClientOnlys(
|
||||||
id: string,
|
id: string,
|
||||||
ctx: { getModuleInfo: GetModuleInfo },
|
ctx: { getModuleInfo: GetModuleInfo },
|
||||||
internals: BuildInternals
|
internals: BuildInternals,
|
||||||
): Generator<PageBuildData, void, unknown> {
|
): Generator<PageBuildData, void, unknown> {
|
||||||
for (const info of getParentModuleInfos(id, ctx)) {
|
for (const info of getParentModuleInfos(id, ctx)) {
|
||||||
yield* getPageDatasByClientOnlyID(internals, info.id);
|
yield* getPageDatasByClientOnlyID(internals, info.id);
|
||||||
|
@ -310,7 +310,7 @@ function appendCSSToPage(
|
||||||
meta: ViteMetadata,
|
meta: ViteMetadata,
|
||||||
pagesToCss: Record<string, Record<string, { order: number; depth: number }>>,
|
pagesToCss: Record<string, Record<string, { order: number; depth: number }>>,
|
||||||
depth: number,
|
depth: number,
|
||||||
order: number
|
order: number,
|
||||||
) {
|
) {
|
||||||
for (const importedCssImport of meta.importedCss) {
|
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.
|
// 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(
|
function isCssScopeToRendered(
|
||||||
cssScopeTo: Record<string, string[]>,
|
cssScopeTo: Record<string, string[]>,
|
||||||
chunks: Rollup.RenderedChunk[]
|
chunks: Rollup.RenderedChunk[],
|
||||||
) {
|
) {
|
||||||
for (const moduleId in cssScopeTo) {
|
for (const moduleId in cssScopeTo) {
|
||||||
const exports = cssScopeTo[moduleId];
|
const exports = cssScopeTo[moduleId];
|
||||||
|
|
|
@ -13,7 +13,7 @@ function virtualHoistedEntry(id: string) {
|
||||||
|
|
||||||
export function vitePluginHoistedScripts(
|
export function vitePluginHoistedScripts(
|
||||||
settings: AstroSettings,
|
settings: AstroSettings,
|
||||||
internals: BuildInternals
|
internals: BuildInternals,
|
||||||
): VitePlugin {
|
): VitePlugin {
|
||||||
let assetsInlineLimit: NonNullable<BuildOptions['assetsInlineLimit']>;
|
let assetsInlineLimit: NonNullable<BuildOptions['assetsInlineLimit']>;
|
||||||
|
|
||||||
|
@ -104,7 +104,7 @@ export function vitePluginHoistedScripts(
|
||||||
|
|
||||||
export function pluginHoistedScripts(
|
export function pluginHoistedScripts(
|
||||||
options: StaticBuildOptions,
|
options: StaticBuildOptions,
|
||||||
internals: BuildInternals
|
internals: BuildInternals,
|
||||||
): AstroBuildPlugin {
|
): AstroBuildPlugin {
|
||||||
return {
|
return {
|
||||||
targets: ['client'],
|
targets: ['client'],
|
||||||
|
|
|
@ -36,7 +36,7 @@ export function vitePluginInternals(input: Set<string>, internals: BuildInternal
|
||||||
mapping.set(result.id, new Set<string>([specifier]));
|
mapping.set(result.id, new Set<string>([specifier]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
await Promise.all(promises);
|
await Promise.all(promises);
|
||||||
|
|
|
@ -78,7 +78,7 @@ function vitePluginManifest(_options: StaticBuildOptions, internals: BuildIntern
|
||||||
|
|
||||||
export function pluginManifest(
|
export function pluginManifest(
|
||||||
options: StaticBuildOptions,
|
options: StaticBuildOptions,
|
||||||
internals: BuildInternals
|
internals: BuildInternals,
|
||||||
): AstroBuildPlugin {
|
): AstroBuildPlugin {
|
||||||
return {
|
return {
|
||||||
targets: ['server'],
|
targets: ['server'],
|
||||||
|
@ -115,7 +115,7 @@ export function pluginManifest(
|
||||||
|
|
||||||
async function createManifest(
|
async function createManifest(
|
||||||
buildOpts: StaticBuildOptions,
|
buildOpts: StaticBuildOptions,
|
||||||
internals: BuildInternals
|
internals: BuildInternals,
|
||||||
): Promise<SerializedSSRManifest> {
|
): Promise<SerializedSSRManifest> {
|
||||||
if (!internals.manifestEntryChunk) {
|
if (!internals.manifestEntryChunk) {
|
||||||
throw new Error(`Did not generate an entry chunk for SSR`);
|
throw new Error(`Did not generate an entry chunk for SSR`);
|
||||||
|
@ -125,7 +125,7 @@ async function createManifest(
|
||||||
const clientStatics = new Set(
|
const clientStatics = new Set(
|
||||||
await glob('**/*', {
|
await glob('**/*', {
|
||||||
cwd: fileURLToPath(buildOpts.settings.config.build.client),
|
cwd: fileURLToPath(buildOpts.settings.config.build.client),
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
for (const file of clientStatics) {
|
for (const file of clientStatics) {
|
||||||
internals.staticFiles.add(file);
|
internals.staticFiles.add(file);
|
||||||
|
@ -149,7 +149,7 @@ function injectManifest(manifest: SerializedSSRManifest, chunk: Readonly<OutputC
|
||||||
function buildManifest(
|
function buildManifest(
|
||||||
opts: StaticBuildOptions,
|
opts: StaticBuildOptions,
|
||||||
internals: BuildInternals,
|
internals: BuildInternals,
|
||||||
staticFiles: string[]
|
staticFiles: string[],
|
||||||
): SerializedSSRManifest {
|
): SerializedSSRManifest {
|
||||||
const { settings } = opts;
|
const { settings } = opts;
|
||||||
|
|
||||||
|
@ -197,7 +197,7 @@ function buildManifest(
|
||||||
scripts.unshift(
|
scripts.unshift(
|
||||||
Object.assign({}, pageData.hoistedScript, {
|
Object.assign({}, pageData.hoistedScript, {
|
||||||
value,
|
value,
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (settings.scripts.some((script) => script.stage === 'page')) {
|
if (settings.scripts.some((script) => script.stage === 'page')) {
|
||||||
|
|
|
@ -6,7 +6,7 @@ export { MIDDLEWARE_MODULE_ID } from '../../middleware/vite-plugin.js';
|
||||||
|
|
||||||
export function pluginMiddleware(
|
export function pluginMiddleware(
|
||||||
opts: StaticBuildOptions,
|
opts: StaticBuildOptions,
|
||||||
internals: BuildInternals
|
internals: BuildInternals,
|
||||||
): AstroBuildPlugin {
|
): AstroBuildPlugin {
|
||||||
return {
|
return {
|
||||||
targets: ['server'],
|
targets: ['server'],
|
||||||
|
|
|
@ -39,7 +39,7 @@ function vitePluginPages(opts: StaticBuildOptions, internals: BuildInternals): V
|
||||||
const pageDatas = getPagesFromVirtualModulePageName(
|
const pageDatas = getPagesFromVirtualModulePageName(
|
||||||
internals,
|
internals,
|
||||||
ASTRO_PAGE_RESOLVED_MODULE_ID,
|
ASTRO_PAGE_RESOLVED_MODULE_ID,
|
||||||
id
|
id,
|
||||||
);
|
);
|
||||||
for (const pageData of pageDatas) {
|
for (const pageData of pageDatas) {
|
||||||
const resolvedPage = await this.resolve(pageData.moduleSpecifier);
|
const resolvedPage = await this.resolve(pageData.moduleSpecifier);
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue