diff options
Diffstat (limited to 'packages/astro')
139 files changed, 1089 insertions, 819 deletions
diff --git a/packages/astro/package.json b/packages/astro/package.json index 14df72e25..e3e1e7391 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -57,7 +57,7 @@ "dev": "astro-scripts dev \"src/**/*.ts\"", "postbuild": "astro-scripts copy \"src/**/*.astro\"", "benchmark": "node test/benchmark/dev.bench.js && node test/benchmark/build.bench.js", - "test": "mocha --parallel --timeout 20000 --ignore **/lit-element.test.js && mocha --timeout 20000 **/lit-element.test.js", + "test": "mocha --exit --timeout 20000 --ignore **/lit-element.test.js && mocha --timeout 20000 **/lit-element.test.js", "test:match": "mocha --timeout 20000 -g" }, "dependencies": { @@ -65,10 +65,6 @@ "@astrojs/language-server": "^0.8.10", "@astrojs/markdown-remark": "^0.6.4", "@astrojs/prism": "0.4.0", - "@astrojs/renderer-preact": "^0.5.0", - "@astrojs/renderer-react": "0.5.0", - "@astrojs/renderer-svelte": "0.5.2", - "@astrojs/renderer-vue": "0.4.0", "@astrojs/webapi": "^0.11.0", "@babel/core": "^7.17.7", "@babel/traverse": "^7.17.3", diff --git a/packages/astro/src/@types/astro.ts b/packages/astro/src/@types/astro.ts index ce089b7e6..e139faa10 100644 --- a/packages/astro/src/@types/astro.ts +++ b/packages/astro/src/@types/astro.ts @@ -1,9 +1,10 @@ +import type { AddressInfo } from 'net'; import type * as babel from '@babel/core'; +import type * as vite from 'vite'; import type { z } from 'zod'; import type { AstroConfigSchema } from '../core/config'; import type { AstroComponentFactory, Metadata } from '../runtime/server'; import type { AstroRequest } from '../core/render/request'; -import type * as vite from 'vite'; export interface AstroBuiltinProps { 'client:load'?: boolean; @@ -127,21 +128,30 @@ export interface AstroUserConfig { /** * @docs - * @name renderers - * @type {string[]} - * @default `['@astrojs/renderer-svelte','@astrojs/renderer-vue','@astrojs/renderer-react','@astrojs/renderer-preact']` + * @name integrations + * @type {AstroIntegration[]} + * @default `[]` * @description - * Set the UI framework renderers for your project. Framework renderers are what power Astro's ability to use other frameworks inside of your project, like React, Svelte, and Vue. + * Add Integrations to your project to extend Astro. + * + * Integrations are your one-stop shop to add new frameworks (like Solid.js), new features (like sitemaps), and new libraries (like Partytown and Turbolinks). * - * Setting this configuration will disable Astro's default framework support, so you will need to provide a renderer for every framework that you want to use. + * Setting this configuration will disable Astro's default integration, so it is recommended to provide a renderer for every framework that you use: + * + * Note: Integrations are currently under active development, and only first-party integrations are supported. In the future, 3rd-party integrations will be allowed. * * ```js + * import react from '@astrojs/react'; + * import vue from '@astrojs/vue'; * { - * // Use Astro + React, with no other frameworks. - * renderers: ['@astrojs/renderer-react'] + * // Example: Use Astro with Vue + React, and no other frameworks. + * integrations: [react(), vue()] * } * ``` */ + integrations?: AstroIntegration[]; + + /** @deprecated - Use "integrations" instead. Run Astro to learn more about migrating. */ renderers?: string[]; /** @@ -170,6 +180,7 @@ export interface AstroUserConfig { * } * ``` */ + /** Options for rendering markdown content */ markdownOptions?: { render?: MarkdownRenderOptions; }; @@ -379,7 +390,7 @@ export interface AstroUserConfig { /** * @docs - * @name devOptions.vite + * @name vite * @type {vite.UserConfig} * @description * @@ -422,10 +433,32 @@ export interface AstroUserConfig { // } /** + * IDs for different stages of JS script injection: + * - "before-hydration": Imported client-side, before the hydration script runs. Processed & resolved by Vite. + * - "head-inline": Injected into a script tag in the `<head>` of every page. Not processed or resolved by Vite. + * - "page": Injected into the JavaScript bundle of every page. Processed & resolved by Vite. + * - "page-ssr": Injected into the frontmatter of every Astro page. Processed & resolved by Vite. + */ +type InjectedScriptStage = 'before-hydration' | 'head-inline' | 'page' | 'page-ssr'; + +/** * Resolved Astro Config * Config with user settings along with all defaults filled in. */ -export type AstroConfig = z.output<typeof AstroConfigSchema>; +export interface AstroConfig extends z.output<typeof AstroConfigSchema> { + // Public: + // This is a more detailed type than zod validation gives us. + // TypeScript still confirms zod validation matches this type. + integrations: AstroIntegration[]; + // Private: + // We have a need to pass context based on configured state, + // that is different from the user-exposed configuration. + // TODO: Create an AstroConfig class to manage this, long-term. + _ctx: { + renderers: AstroRenderer[]; + scripts: { stage: InjectedScriptStage; content: string }[]; + }; +} export type AsyncRendererComponentFn<U> = (Component: any, props: any, children: string | undefined, metadata?: AstroComponentMetadata) => Promise<U>; @@ -560,38 +593,51 @@ export interface EndpointHandler { [method: string]: (params: any, request: AstroRequest) => EndpointOutput | Response; } -/** - * Astro Renderer - * Docs: https://docs.astro.build/reference/renderer-reference/ - */ -export interface Renderer { - /** Name of the renderer (required) */ +export interface AstroRenderer { + /** Name of the renderer. */ name: string; - /** Import statement for renderer */ - source?: string; - /** Import statement for the server renderer */ - serverEntry: string; - /** Scripts to be injected before component */ - polyfills?: string[]; - /** Polyfills that need to run before hydration ever occurs */ - hydrationPolyfills?: string[]; + /** Import entrypoint for the client/browser renderer. */ + clientEntrypoint?: string; + /** Import entrypoint for the server/build/ssr renderer. */ + serverEntrypoint: string; /** JSX identifier (e.g. 'react' or 'solid-js') */ jsxImportSource?: string; /** Babel transform options */ jsxTransformOptions?: JSXTransformFn; - /** Utilies for server-side rendering */ +} + +export interface SSRLoadedRenderer extends AstroRenderer { ssr: { check: AsyncRendererComponentFn<boolean>; renderToStaticMarkup: AsyncRendererComponentFn<{ html: string; }>; }; - /** Return configuration object for Vite ("options" should match https://vitejs.dev/guide/api-plugin.html#config) */ - viteConfig?: (options: { mode: 'string'; command: 'build' | 'serve' }) => Promise<vite.InlineConfig>; - /** @deprecated Don’t try and build these dependencies for client (deprecated in 0.21) */ - external?: string[]; - /** @deprecated Clientside requirements (deprecated in 0.21) */ - knownEntrypoints?: string[]; +} + +export interface AstroIntegration { + /** The name of the integration. */ + name: string; + /** The different hooks available to extend. */ + hooks: { + 'astro:config:setup'?: (options: { + config: AstroConfig; + command: 'dev' | 'build'; + updateConfig: (newConfig: Record<string, any>) => void; + addRenderer: (renderer: AstroRenderer) => void; + injectScript: (stage: InjectedScriptStage, content: string) => void; + // TODO: Add support for `injectElement()` for full HTML element injection, not just scripts. + // This may require some refactoring of `scripts`, `styles`, and `links` into something + // more generalized. Consider the SSR use-case as well. + // injectElement: (stage: vite.HtmlTagDescriptor, element: string) => void; + }) => void; + 'astro:config:done'?: (options: { config: AstroConfig }) => void | Promise<void>; + 'astro:server:setup'?: (options: { server: vite.ViteDevServer }) => void | Promise<void>; + 'astro:server:start'?: (options: { address: AddressInfo }) => void | Promise<void>; + 'astro:server:done'?: () => void | Promise<void>; + 'astro:build:start'?: () => void | Promise<void>; + 'astro:build:done'?: (options: { pages: { pathname: string }[]; dir: URL }) => void | Promise<void>; + }; } export type RouteType = 'page' | 'endpoint'; @@ -665,7 +711,7 @@ export interface SSRElement { } export interface SSRMetadata { - renderers: Renderer[]; + renderers: SSRLoadedRenderer[]; pathname: string; legacyBuild: boolean; } diff --git a/packages/astro/src/core/app/index.ts b/packages/astro/src/core/app/index.ts index fab55c9af..c05b713ab 100644 --- a/packages/astro/src/core/app/index.ts +++ b/packages/astro/src/core/app/index.ts @@ -1,4 +1,4 @@ -import type { ComponentInstance, ManifestData, RouteData, Renderer } from '../../@types/astro'; +import type { ComponentInstance, ManifestData, RouteData, SSRLoadedRenderer } from '../../@types/astro'; import type { SSRManifest as Manifest, RouteInfo } from './types'; import { defaultLogOptions } from '../logger.js'; @@ -6,7 +6,6 @@ import { matchRoute } from '../routing/match.js'; import { render } from '../render/core.js'; import { RouteCache } from '../render/route-cache.js'; import { createLinkStylesheetElementSet, createModuleScriptElementWithSrcSet } from '../render/ssr-element.js'; -import { createRenderer } from '../render/renderer.js'; import { prependForwardSlash } from '../path.js'; export class App { @@ -15,7 +14,7 @@ export class App { #rootFolder: URL; #routeDataToRouteInfo: Map<RouteData, RouteInfo>; #routeCache: RouteCache; - #renderersPromise: Promise<Renderer[]>; + #renderersPromise: Promise<SSRLoadedRenderer[]>; constructor(manifest: Manifest, rootFolder: URL) { this.#manifest = manifest; @@ -84,18 +83,11 @@ export class App { status: 200, }); } - async #loadRenderers(): Promise<Renderer[]> { - const rendererNames = this.#manifest.renderers; + async #loadRenderers(): Promise<SSRLoadedRenderer[]> { return await Promise.all( - rendererNames.map(async (rendererName) => { - return createRenderer(rendererName, { - renderer(name) { - return import(name); - }, - server(entry) { - return import(entry); - }, - }); + this.#manifest.renderers.map(async (renderer) => { + const mod = (await import(renderer.serverEntrypoint)) as { default: SSRLoadedRenderer['ssr'] }; + return { ...renderer, ssr: mod.default }; }) ); } diff --git a/packages/astro/src/core/app/types.ts b/packages/astro/src/core/app/types.ts index 612a60ad6..d78a94050 100644 --- a/packages/astro/src/core/app/types.ts +++ b/packages/astro/src/core/app/types.ts @@ -1,4 +1,4 @@ -import type { RouteData, SerializedRouteData, MarkdownRenderOptions } from '../../@types/astro'; +import type { RouteData, SerializedRouteData, MarkdownRenderOptions, AstroRenderer } from '../../@types/astro'; export interface RouteInfo { routeData: RouteData; @@ -17,7 +17,7 @@ export interface SSRManifest { markdown: { render: MarkdownRenderOptions; }; - renderers: string[]; + renderers: AstroRenderer[]; entryModules: Record<string, string>; } diff --git a/packages/astro/src/core/build/index.ts b/packages/astro/src/core/build/index.ts index db06851d2..8996fc559 100644 --- a/packages/astro/src/core/build/index.ts +++ b/packages/astro/src/core/build/index.ts @@ -14,6 +14,7 @@ import { collectPagesData } from './page-data.js'; import { build as scanBasedBuild } from './scan-based-build.js'; import { staticBuild } from './static-build.js'; import { RouteCache } from '../render/route-cache.js'; +import { runHookBuildDone, runHookBuildStart, runHookConfigDone, runHookConfigSetup } from '../../integrations/index.js'; export interface BuildOptions { mode?: string; @@ -57,23 +58,23 @@ class AstroBuilder { const timer: Record<string, number> = {}; timer.init = performance.now(); timer.viteStart = performance.now(); + this.config = await runHookConfigSetup({ config: this.config, command: 'build' }); const viteConfig = await createVite( - vite.mergeConfig( - { - mode: this.mode, - server: { - hmr: false, - middlewareMode: 'ssr', - }, + { + mode: this.mode, + server: { + hmr: false, + middlewareMode: 'ssr', }, - this.config.vite || {} - ), + }, { astroConfig: this.config, logging, mode: 'build' } ); + await runHookConfigDone({ config: this.config }); this.viteConfig = viteConfig; const viteServer = await vite.createServer(viteConfig); this.viteServer = viteServer; debug('build', timerMessage('Vite started', timer.viteStart)); + await runHookBuildStart({ config: this.config }); timer.loadStart = performance.now(); const { assets, allPages } = await collectPagesData({ @@ -160,6 +161,8 @@ class AstroBuilder { // You're done! Time to clean up. await viteServer.close(); + await runHookBuildDone({ config: this.config, pages: pageNames }); + if (logging.level && levels[logging.level] <= levels['info']) { await this.printStats({ logging, timeStart: timer.init, pageCount: pageNames.length }); } diff --git a/packages/astro/src/core/build/static-build.ts b/packages/astro/src/core/build/static-build.ts index 3c75435a7..36a3af840 100644 --- a/packages/astro/src/core/build/static-build.ts +++ b/packages/astro/src/core/build/static-build.ts @@ -1,31 +1,28 @@ -import type { OutputChunk, OutputAsset, RollupOutput } from 'rollup'; -import type { Plugin as VitePlugin, UserConfig, Manifest as ViteManifest } from 'vite'; -import type { AstroConfig, ComponentInstance, EndpointHandler, ManifestData, Renderer, RouteType } from '../../@types/astro'; -import type { AllPagesData } from './types'; -import type { LogOptions } from '../logger'; -import type { ViteConfigWithSSR } from '../create-vite'; -import type { PageBuildData } from './types'; -import type { BuildInternals } from '../../core/build/internal.js'; -import type { RenderOptions } from '../../core/render/core'; -import type { SerializedSSRManifest, SerializedRouteInfo } from '../app/types'; - +import glob from 'fast-glob'; import fs from 'fs'; import npath from 'path'; +import type { OutputAsset, OutputChunk, RollupOutput } from 'rollup'; import { fileURLToPath } from 'url'; -import glob from 'fast-glob'; +import type { Manifest as ViteManifest, Plugin as VitePlugin, UserConfig } from 'vite'; import * as vite from 'vite'; +import type { AstroConfig, AstroRenderer, ComponentInstance, EndpointHandler, ManifestData, RouteType, SSRLoadedRenderer } from '../../@types/astro'; +import type { BuildInternals } from '../../core/build/internal.js'; +import { createBuildInternals } from '../../core/build/internal.js'; import { debug, error } from '../../core/logger.js'; -import { prependForwardSlash, appendForwardSlash } from '../../core/path.js'; +import { appendForwardSlash, prependForwardSlash } from '../../core/path.js'; +import type { RenderOptions } from '../../core/render/core'; import { emptyDir, removeDir, resolveDependency } from '../../core/util.js'; -import { createBuildInternals } from '../../core/build/internal.js'; import { rollupPluginAstroBuildCSS } from '../../vite-plugin-build-css/index.js'; -import { vitePluginHoistedScripts } from './vite-plugin-hoisted-scripts.js'; -import { RouteCache } from '../render/route-cache.js'; +import type { SerializedRouteInfo, SerializedSSRManifest } from '../app/types'; +import type { ViteConfigWithSSR } from '../create-vite'; import { call as callEndpoint } from '../endpoint/index.js'; -import { serializeRouteData } from '../routing/index.js'; +import type { LogOptions } from '../logger'; import { render } from '../render/core.js'; +import { RouteCache } from '../render/route-cache.js'; import { createLinkStylesheetElementSet, createModuleScriptElementWithSrcSet } from '../render/ssr-element.js'; -import { createRequest } from '../render/request.js'; +import { serializeRouteData } from '../routing/index.js'; +import type { AllPagesData, PageBuildData } from './types'; +import { vitePluginHoistedScripts } from './vite-plugin-hoisted-scripts.js'; export interface StaticBuildOptions { allPages: AllPagesData; @@ -116,17 +113,8 @@ export async function staticBuild(opts: StaticBuildOptions) { // about that page, such as its paths. const facadeIdToPageDataMap = new Map<string, PageBuildData>(); - // Collects polyfills and passes them as top-level inputs - const polyfills = getRenderers(opts).flatMap((renderer) => { - return (renderer.polyfills || []).concat(renderer.hydrationPolyfills || []); - }); - for (const polyfill of polyfills) { - jsInput.add(polyfill); - } - // Build internals needed by the CSS plugin const internals = createBuildInternals(); - for (const [component, pageData] of Object.entries(allPages)) { const astroModuleURL = new URL('./' + component, astroConfig.projectRoot); const astroModuleId = prependForwardSlash(component); @@ -145,7 +133,7 @@ export async function staticBuild(opts: StaticBuildOptions) { // Any hydration directive like astro/client/idle.js ...metadata.hydrationDirectiveSpecifiers(), // The client path for each renderer - ...renderers.filter((renderer) => !!renderer.source).map((renderer) => renderer.source!), + ...renderers.filter((renderer) => !!renderer.clientEntrypoint).map((renderer) => renderer.clientEntrypoint!), ]); // Add hoisted scripts @@ -172,6 +160,7 @@ export async function staticBuild(opts: StaticBuildOptions) { // Build your project (SSR application code, assets, client JS, etc.) const ssrResult = (await ssrBuild(opts, internals, pageInput)) as RollupOutput; + await clientBuild(opts, internals, jsInput); // SSG mode, generate pages. @@ -189,10 +178,11 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp const { astroConfig, viteConfig } = opts; const ssr = astroConfig.buildOptions.experimentalSsr; const out = ssr ? getServerRoot(astroConfig) : getOutRoot(astroConfig); - + // TODO: use vite.mergeConfig() here? return await vite.build({ - logLevel: 'warn', + logLevel: 'error', mode: 'production', + css: viteConfig.css, build: { ...viteConfig.build, emptyOutDir: false, @@ -200,6 +190,9 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp outDir: fileURLToPath(out), ssr: true, rollupOptions: { + // onwarn(warn) { + // console.log(warn); + // }, input: Array.from(input), output: { format: 'esm', @@ -240,9 +233,12 @@ async function clientBuild(opts: StaticBuildOptions, internals: BuildInternals, } const out = astroConfig.buildOptions.experimentalSsr ? getClientRoot(astroConfig) : getOutRoot(astroConfig); + + // TODO: use vite.mergeConfig() here? return await vite.build({ - logLevel: 'warn', + logLevel: 'error', mode: 'production', + css: viteConfig.css, build: { emptyOutDir: false, minify: 'esbuild', @@ -275,38 +271,20 @@ async function clientBuild(opts: StaticBuildOptions, internals: BuildInternals, }); } -function getRenderers(opts: StaticBuildOptions) { - // All of the PageDatas have the same renderers, so just grab one. - const pageData = Object.values(opts.allPages)[0]; - // These renderers have been loaded through Vite. To generate pages - // we need the ESM loaded version. This creates that. - const viteLoadedRenderers = pageData.preload[0]; - - return viteLoadedRenderers; +async function loadRenderer(renderer: AstroRenderer, config: AstroConfig): Promise<SSRLoadedRenderer> { + const mod = (await import(resolveDependency(renderer.serverEntrypoint, config))) as { default: SSRLoadedRenderer['ssr'] }; + return { ...renderer, ssr: mod.default }; } -async function collectRenderers(opts: StaticBuildOptions): Promise<Renderer[]> { - const viteLoadedRenderers = getRenderers(opts); - - const renderers = await Promise.all( - viteLoadedRenderers.map(async (r) => { - const mod = await import(resolveDependency(r.serverEntry, opts.astroConfig)); - return Object.create(r, { - ssr: { - value: mod.default, - }, - }) as Renderer; - }) - ); - - return renderers; +async function loadRenderers(config: AstroConfig): Promise<SSRLoadedRenderer[]> { + return Promise.all(config._ctx.renderers.map((r) => loadRenderer(r, config))); } async function generatePages(result: RollupOutput, opts: StaticBuildOptions, internals: BuildInternals, facadeIdToPageDataMap: Map<string, PageBuildData>) { debug('build', 'Finish build. Begin generating.'); // Get renderers to be shared for each page generation. - const renderers = await collectRenderers(opts); + const renderers = await loadRenderers(opts.astroConfig); for (let output of result.output) { if (chunkIsPage(opts.astroConfig, output, internals)) { @@ -315,7 +293,13 @@ async function generatePages(result: RollupOutput, opts: StaticBuildOptions, int } } -async function generatePage(output: OutputChunk, opts: StaticBuildOptions, internals: BuildInternals, facadeIdToPageDataMap: Map<string, PageBuildData>, renderers: Renderer[]) { +async function generatePage( + output: OutputChunk, + opts: StaticBuildOptions, + internals: BuildInternals, + facadeIdToPageDataMap: Map<string, PageBuildData>, + renderers: SSRLoadedRenderer[] +) { const { astroConfig } = opts; let url = new URL('./' + output.fileName, getOutRoot(astroConfig)); @@ -359,7 +343,7 @@ interface GeneratePathOptions { linkIds: string[]; hoistedId: string | null; mod: ComponentInstance; - renderers: Renderer[]; + renderers: SSRLoadedRenderer[]; } async function generatePath(pathname: string, opts: StaticBuildOptions, gopts: GeneratePathOptions) { @@ -377,6 +361,16 @@ async function generatePath(pathname: string, opts: StaticBuildOptions, gopts: G const links = createLinkStylesheetElementSet(linkIds.reverse(), site); const scripts = createModuleScriptElementWithSrcSet(hoistedId ? [hoistedId] : [], site); + // Add all injected scripts to the page. + for (const script of astroConfig._ctx.scripts) { + if (script.stage === 'head-inline') { + scripts.add({ + props: {}, + children: script.content, + }); + } + } + try { const options: RenderOptions = { legacyBuild: false, @@ -391,6 +385,14 @@ async function generatePath(pathname: string, opts: StaticBuildOptions, gopts: G async resolve(specifier: string) { const hashedFilePath = internals.entrySpecifierToBundleMap.get(specifier); if (typeof hashedFilePath !== 'string') { + // If no "astro:scripts/before-hydration.js" script exists in the build, + // then we can assume that no before-hydration scripts are needed. + // Return this as placeholder, which will be ignored by the browser. + // TODO: In the future, we hope to run this entire script through Vite, + // removing the need to maintain our own custom Vite-mimic resolve logic. + if (specifier === 'astro:scripts/before-hydration.js') { + return 'data:text/javascript;charset=utf-8,//[no before-hydration script]'; + } throw new Error(`Cannot find the built path for ${specifier}`); } const relPath = npath.posix.relative(pathname, '/' + hashedFilePath); @@ -480,7 +482,7 @@ async function generateManifest(result: RollupOutput, opts: StaticBuildOptions, markdown: { render: astroConfig.markdownOptions.render, }, - renderers: astroConfig.renderers, + renderers: astroConfig._ctx.renderers, entryModules: Object.fromEntries(internals.entrySpecifierToBundleMap.entries()), }; @@ -628,8 +630,8 @@ export function vitePluginNewBuild(input: Set<string>, internals: BuildInternals } await Promise.all(promises); for (const [, chunk] of Object.entries(bundle)) { - if (chunk.type === 'chunk' && chunk.facadeModuleId && mapping.has(chunk.facadeModuleId)) { - const specifier = mapping.get(chunk.facadeModuleId)!; + if (chunk.type === 'chunk' && chunk.facadeModuleId) { + const specifier = mapping.get(chunk.facadeModuleId) || chunk.facadeModuleId; internals.entrySpecifierToBundleMap.set(specifier, chunk.fileName); } } diff --git a/packages/astro/src/core/config.ts b/packages/astro/src/core/config.ts index 5400a9514..6419ab27a 100644 --- a/packages/astro/src/core/config.ts +++ b/packages/astro/src/core/config.ts @@ -1,15 +1,48 @@ import type { AstroConfig, AstroUserConfig, CLIFlags } from '../@types/astro'; import type { Arguments as Flags } from 'yargs-parser'; +import type * as Postcss from 'postcss'; import * as colors from 'kleur/colors'; import path from 'path'; import { pathToFileURL, fileURLToPath } from 'url'; +import { mergeConfig as mergeViteConfig } from 'vite'; import { z } from 'zod'; import load from '@proload/core'; import loadTypeScript from '@proload/plugin-tsm'; +import postcssrc from 'postcss-load-config'; +import { arraify, isObject } from './util.js'; load.use([loadTypeScript]); +interface PostCSSConfigResult { + options: Postcss.ProcessOptions; + plugins: Postcss.Plugin[]; +} + +async function resolvePostcssConfig(inlineOptions: any, root: URL): Promise<PostCSSConfigResult> { + if (isObject(inlineOptions)) { + const options = { ...inlineOptions }; + delete options.plugins; + return { + options, + plugins: inlineOptions.plugins || [], + }; + } + const searchPath = typeof inlineOptions === 'string' ? inlineOptions : fileURLToPath(root); + try { + // @ts-ignore + return await postcssrc({}, searchPath); + } catch (err: any) { + if (!/No PostCSS Config found/.test(err.message)) { + throw err; + } + return { + options: {}, + plugins: [], + }; + } +} + export const AstroConfigSchema = z.object({ projectRoot: z .string() @@ -36,7 +69,31 @@ export const AstroConfigSchema = z.object({ .optional() .default('./dist') .transform((val) => new URL(val)), - renderers: z.array(z.string()).optional().default(['@astrojs/renderer-svelte', '@astrojs/renderer-vue', '@astrojs/renderer-react', '@astrojs/renderer-preact']), + integrations: z.preprocess( + // preprocess + (val) => (Array.isArray(val) ? val.flat(Infinity).filter(Boolean) : val), + // validate + z + .array(z.object({ name: z.string(), hooks: z.object({}).passthrough().default({}) })) + .default([]) + // validate: first-party integrations only + // TODO: Add `To use 3rd-party integrations or to create your own, use the --experimental-integrations flag.`, + .refine((arr) => arr.every((integration) => integration.name.startsWith('@astrojs/')), { + message: `Astro integrations are still experimental, and only official integrations are currently supported`, + }) + ), + styleOptions: z + .object({ + postcss: z + .object({ + options: z.any(), + plugins: z.array(z.any()), + }) + .optional() + .default({ options: {}, plugins: [] }), + }) + .optional() + .default({}), markdownOptions: z .object({ render: z.any().optional().default(['@astrojs/markdown-remark', {}]), @@ -81,6 +138,37 @@ export const AstroConfigSchema = z.object({ /** Turn raw config values into normalized values */ export async function validateConfig(userConfig: any, root: string): Promise<AstroConfig> { const fileProtocolRoot = pathToFileURL(root + path.sep); + // Manual deprecation checks + /* eslint-disable no-console */ + if (userConfig.hasOwnProperty('renderers')) { + console.error('Astro "renderers" are now "integrations"!'); + console.error('Update your configuration and install new dependencies:'); + try { + const rendererKeywords = userConfig.renderers.map((r: string) => r.replace('@astrojs/renderer-', '')); + const rendererImports = rendererKeywords.map((r: string) => ` import ${r} from '@astrojs/${r}';`).join('\n'); + const rendererIntegrations = rendererKeywords.map((r: string) => ` ${r}(),`).join('\n'); + console.error(''); + console.error(colors.dim(' // astro.config.js')); + if (rendererImports.length > 0) { + console.error(colors.green(rendererImports)); + } + console.error(''); + console.error(colors.dim(' // ...')); + if (rendererIntegrations.length > 0) { + console.error(colors.green(' integrations: [')); + console.error(colors.green(rendererIntegrations)); + console.error(colors.green(' ],')); + } else { + console.error(colors.green(' integrations: [],')); + } + console.error(''); + } catch (err) { + // We tried, better to just exit. + } + process.exit(1); + } + /* eslint-enable no-console */ + // We need to extend the global schema to add transforms that are relative to root. // This is type checked against the global schema to make sure we still match. const AstroConfigRelativeSchema = AstroConfigSchema.extend({ @@ -104,8 +192,26 @@ export async function validateConfig(userConfig: any, root: string): Promise<Ast .string() .default('./dist') .transform((val) => new URL(addTrailingSlash(val), fileProtocolRoot)), + styleOptions: z + .object({ + postcss: z.preprocess( + (val) => resolvePostcssConfig(val, fileProtocolRoot), + z + .object({ + options: z.any(), + plugins: z.array(z.any()), + }) + .optional() + .default({ options: {}, plugins: [] }) + ), + }) + .optional() + .default({}), }); - return AstroConfigRelativeSchema.parseAsync(userConfig); + return { + ...(await AstroConfigRelativeSchema.parseAsync(userConfig)), + _ctx: { scripts: [], renderers: [] }, + }; } /** Adds '/' to end of string but doesn’t double-up */ @@ -175,7 +281,11 @@ export async function loadConfig(configOptions: LoadConfigOptions): Promise<Astr if (config) { userConfig = config.value; } - // normalize, validate, and return + return resolveConfig(userConfig, root, flags); +} + +/** Attempt to resolve an Astro configuration object. Normalize, validate, and return. */ +export async function resolveConfig(userConfig: AstroUserConfig, root: string, flags: CLIFlags = {}): Promise<AstroConfig> { const mergedConfig = mergeCLIFlags(userConfig, flags); const validatedConfig = await validateConfig(mergedConfig, root); return validatedConfig; @@ -185,3 +295,42 @@ export function formatConfigError(err: z.ZodError) { const errorList = err.issues.map((issue) => ` ! ${colors.bold(issue.path.join('.'))} ${colors.red(issue.message + '.')}`); return `${colors.red('[config]')} Astro found issue(s) with your configuration:\n${errorList.join('\n')}`; } + +function mergeConfigRecursively(defaults: Record<string, any>, overrides: Record<string, any>, rootPath: string) { + const merged: Record<string, any> = { ...defaults }; + for (const key in overrides) { + const value = overrides[key]; + if (value == null) { + continue; + } + + const existing = merged[key]; + + if (existing == null) { + merged[key] = value; + continue; + } + + // fields that require special handling: + if (key === 'vite' && rootPath === '') { + merged[key] = mergeViteConfig(existing, value); + continue; + } + + if (Array.isArray(existing) || Array.isArray(value)) { + merged[key] = [...arraify(existing ?? []), ...arraify(value ?? [])]; + continue; + } + if (isObject(existing) && isObject(value)) { + merged[key] = mergeConfigRecursively(existing, value, rootPath ? `${rootPath}.${key}` : key); + continue; + } + + merged[key] = value; + } + return merged; +} + +export function mergeConfig(defaults: Record<string, any>, overrides: Record<string, any>, isRoot = true): Record<string, any> { + return mergeConfigRecursively(defaults, overrides, isRoot ? '' : '.'); +} diff --git a/packages/astro/src/core/create-vite.ts b/packages/astro/src/core/create-vite.ts index b605d063c..65cf269b7 100644 --- a/packages/astro/src/core/create-vite.ts +++ b/packages/astro/src/core/create-vite.ts @@ -5,6 +5,7 @@ import { builtinModules } from 'module'; import { fileURLToPath } from 'url'; import fs from 'fs'; import * as vite from 'vite'; +import { runHookServerSetup } from '../integrations/index.js'; import astroVitePlugin from '../vite-plugin-astro/index.js'; import astroViteServerPlugin from '../vite-plugin-astro-server/index.js'; import astroPostprocessVitePlugin from '../vite-plugin-astro-postprocess/index.js'; @@ -12,7 +13,8 @@ import configAliasVitePlugin from '../vite-plugin-config-alias/index.js'; import markdownVitePlugin from '../vite-plugin-markdown/index.js'; import jsxVitePlugin from '../vite-plugin-jsx/index.js'; import envVitePlugin from '../vite-plugin-env/index.js'; -import { resolveDependency } from './util.js'; +import astroScriptsPlugin from '../vite-plugin-scripts/index.js'; +import astroIntegrationsContainerPlugin from '../vite-plugin-integrations-container/index.js'; // Some packages are just external, and that’s the way it goes. const ALWAYS_EXTERNAL = new Set([ @@ -41,12 +43,11 @@ interface CreateViteOptions { } /** Return a common starting point for all Vite actions */ -export async function createVite(inlineConfig: ViteConfigWithSSR, { astroConfig, logging, mode }: CreateViteOptions): Promise<ViteConfigWithSSR> { +export async function createVite(commandConfig: ViteConfigWithSSR, { astroConfig, logging, mode }: CreateViteOptions): Promise<ViteConfigWithSSR> { // Scan for any third-party Astro packages. Vite needs these to be passed to `ssr.noExternal`. const astroPackages = await getAstroPackages(astroConfig); - // Start with the Vite configuration that Astro core needs - let viteConfig: ViteConfigWithSSR = { + const commonConfig: ViteConfigWithSSR = { cacheDir: fileURLToPath(new URL('./node_modules/.vite/', astroConfig.projectRoot)), // using local caches allows Astro to be used in monorepos, etc. clearScreen: false, // we want to control the output, not Vite logLevel: 'warn', // log warnings and errors only @@ -56,6 +57,7 @@ export async function createVite(inlineConfig: ViteConfigWithSSR, { astroConfig, plugins: [ configAliasVitePlugin({ config: astroConfig }), astroVitePlugin({ config: astroConfig, logging }), + astroScriptsPlugin({ config: astroConfig }), // The server plugin is for dev only and having it run during the build causes // the build to run very slow as the filewatcher is triggered often. mode === 'dev' && astroViteServerPlugin({ config: astroConfig, logging }), @@ -63,6 +65,7 @@ export async function createVite(inlineConfig: ViteConfigWithSSR, { astroConfig, markdownVitePlugin({ config: astroConfig }), jsxVitePlugin({ config: astroConfig, logging }), astroPostprocessVitePlugin({ config: astroConfig }), + astroIntegrationsContainerPlugin({ config: astroConfig }), ], publicDir: fileURLToPath(astroConfig.public), root: fileURLToPath(astroConfig.projectRoot), @@ -75,6 +78,9 @@ export async function createVite(inlineConfig: ViteConfigWithSSR, { astroConfig, // add proxies here }, }, + css: { + postcss: astroConfig.styleOptions.postcss || {}, + }, // Note: SSR API is in beta (https://vitejs.dev/guide/ssr.html) ssr: { external: [...ALWAYS_EXTERNAL], @@ -82,26 +88,16 @@ export async function createVite(inlineConfig: ViteConfigWithSSR, { astroConfig, }, }; - // Add in Astro renderers, which will extend the base config - for (const name of astroConfig.renderers) { - try { - const { default: renderer } = await import(resolveDependency(name, astroConfig)); - if (!renderer) continue; - // if a renderer provides viteConfig(), call it and pass in results - if (renderer.viteConfig) { - if (typeof renderer.viteConfig !== 'function') { - throw new Error(`${name}: viteConfig(options) must be a function! Got ${typeof renderer.viteConfig}.`); - } - const rendererConfig = await renderer.viteConfig({ mode: inlineConfig.mode, command: inlineConfig.mode === 'production' ? 'build' : 'serve' }); // is this command true? - viteConfig = vite.mergeConfig(viteConfig, rendererConfig) as ViteConfigWithSSR; - } - } catch (err) { - throw new Error(`${name}: ${err}`); - } - } - - viteConfig = vite.mergeConfig(viteConfig, inlineConfig); // merge in inline Vite config - return viteConfig; + // Merge configs: we merge vite configuration objects together in the following order, + // where future values will override previous values. + // 1. common vite config + // 2. user-provided vite config, via AstroConfig + // 3. integration-provided vite config, via the `config:setup` hook + // 4. command vite config, passed as the argument to this function + let result = commonConfig; + result = vite.mergeConfig(result, astroConfig.vite || {}); + result = vite.mergeConfig(result, commandConfig); + return result; } // Scans `projectRoot` for third-party Astro packages that could export an `.astro` file diff --git a/packages/astro/src/core/dev/index.ts b/packages/astro/src/core/dev/index.ts index be3a7ef7f..ca34b0b15 100644 --- a/packages/astro/src/core/dev/index.ts +++ b/packages/astro/src/core/dev/index.ts @@ -1,12 +1,12 @@ -import type { AstroConfig } from '../../@types/astro'; import type { AddressInfo } from 'net'; - import { performance } from 'perf_hooks'; -import { apply as applyPolyfill } from '../polyfill.js'; -import { createVite } from '../create-vite.js'; -import { defaultLogOptions, info, warn, LogOptions } from '../logger.js'; import * as vite from 'vite'; +import type { AstroConfig } from '../../@types/astro'; +import { runHookConfigDone, runHookConfigSetup, runHookServerDone, runHookServerSetup, runHookServerStart } from '../../integrations/index.js'; +import { createVite } from '../create-vite.js'; +import { defaultLogOptions, info, LogOptions, warn } from '../logger.js'; import * as msg from '../messages.js'; +import { apply as applyPolyfill } from '../polyfill.js'; import { getResolvedHostForVite } from './util.js'; export interface DevOptions { @@ -22,31 +22,36 @@ export interface DevServer { export default async function dev(config: AstroConfig, options: DevOptions = { logging: defaultLogOptions }): Promise<DevServer> { const devStart = performance.now(); applyPolyfill(); - - // TODO: remove call once --hostname is baselined - const host = getResolvedHostForVite(config); - const viteUserConfig = vite.mergeConfig( + config = await runHookConfigSetup({ config, command: 'dev' }); + const viteConfig = await createVite( { mode: 'development', - server: { host }, + // TODO: remove call once --hostname is baselined + server: { host: getResolvedHostForVite(config) }, }, - config.vite || {} + { astroConfig: config, logging: options.logging, mode: 'dev' } ); - const viteConfig = await createVite(viteUserConfig, { astroConfig: config, logging: options.logging, mode: 'dev' }); + await runHookConfigDone({ config }); const viteServer = await vite.createServer(viteConfig); + runHookServerSetup({ config, server: viteServer }); await viteServer.listen(config.devOptions.port); const devServerAddressInfo = viteServer.httpServer!.address() as AddressInfo; const site = config.buildOptions.site ? new URL(config.buildOptions.site) : undefined; - info(options.logging, null, msg.devStart({ startupTime: performance.now() - devStart, config, devServerAddressInfo, site, https: !!viteUserConfig.server?.https })); + info(options.logging, null, msg.devStart({ startupTime: performance.now() - devStart, config, devServerAddressInfo, site, https: !!viteConfig.server?.https })); const currentVersion = process.env.PACKAGE_VERSION ?? '0.0.0'; if (currentVersion.includes('-')) { warn(options.logging, null, msg.prerelease({ currentVersion })); } + await runHookServerStart({ config, address: devServerAddressInfo }); + return { address: devServerAddressInfo, - stop: () => viteServer.close(), + stop: async () => { + await viteServer.close(); + await runHookServerDone({ config }); + }, }; } diff --git a/packages/astro/src/core/render/core.ts b/packages/astro/src/core/render/core.ts index 40d28abcd..a1ea94f65 100644 --- a/packages/astro/src/core/render/core.ts +++ b/packages/astro/src/core/render/core.ts @@ -1,4 +1,4 @@ -import type { ComponentInstance, EndpointHandler, MarkdownRenderOptions, Params, Props, Renderer, RouteData, SSRElement } from '../../@types/astro'; +import type { ComponentInstance, EndpointHandler, MarkdownRenderOptions, Params, Props, SSRLoadedRenderer, RouteData, SSRElement } from '../../@types/astro'; import type { LogOptions } from '../logger.js'; import type { AstroRequest } from './request'; @@ -66,7 +66,7 @@ export interface RenderOptions { pathname: string; scripts: Set<SSRElement>; resolve: (s: string) => Promise<string>; - renderers: Renderer[]; + renderers: SSRLoadedRenderer[]; route?: RouteData; routeCache: RouteCache; site?: string; diff --git a/packages/astro/src/core/render/dev/css.ts b/packages/astro/src/core/render/dev/css.ts index 9bb84d939..82141c5cb 100644 --- a/packages/astro/src/core/render/dev/css.ts +++ b/packages/astro/src/core/render/dev/css.ts @@ -1,7 +1,7 @@ import type * as vite from 'vite'; import path from 'path'; -import { viteID } from '../../util.js'; +import { unwrapId, viteID } from '../../util.js'; // https://vitejs.dev/guide/features.html#css-pre-processors export const STYLE_EXTENSIONS = new Set(['.css', '.pcss', '.postcss', '.scss', '.sass', '.styl', '.stylus', '.less']); @@ -13,41 +13,50 @@ const cssRe = new RegExp( ); export const isCSSRequest = (request: string): boolean => cssRe.test(request); -/** - * getStylesForURL - * Given a filePath URL, crawl Vite’s module graph to find style files - */ +/** Given a filePath URL, crawl Vite’s module graph to find all style imports. */ export function getStylesForURL(filePath: URL, viteServer: vite.ViteDevServer): Set<string> { - const css = new Set<string>(); + const importedCssUrls = new Set<string>(); - // recursively crawl module graph to get all style files imported by parent id - function crawlCSS(id: string, scanned = new Set<string>()) { - // note: use .getModulesByFile() to get all related nodes of the same URL - // using .getModuleById() could cause missing style imports on initial server load - const relatedMods = viteServer.moduleGraph.getModulesByFile(id) ?? new Set(); + /** recursively crawl the module graph to get all style files imported by parent id */ + function crawlCSS(_id: string, isFile: boolean, scanned = new Set<string>()) { + const id = unwrapId(_id); const importedModules = new Set<vite.ModuleNode>(); - - for (const relatedMod of relatedMods) { - if (id === relatedMod.id) { + const moduleEntriesForId = isFile + ? // If isFile = true, then you are at the root of your module import tree. + // The `id` arg is a filepath, so use `getModulesByFile()` to collect all + // nodes for that file. This is needed for advanced imports like Tailwind. + viteServer.moduleGraph.getModulesByFile(id) ?? new Set() + : // Otherwise, you are following an import in the module import tree. + // You are safe to use getModuleById() here because Vite has already + // resolved the correct `id` for you, by creating the import you followed here. + new Set([viteServer.moduleGraph.getModuleById(id)!]); + + // Collect all imported modules for the module(s). + for (const entry of moduleEntriesForId) { + if (id === entry.id) { scanned.add(id); - for (const importedMod of relatedMod.importedModules) { - importedModules.add(importedMod); + for (const importedModule of entry.importedModules) { + importedModules.add(importedModule); } } } - // scan importedModules + // scan imported modules for CSS imports & add them to our collection. + // Then, crawl that file to follow and scan all deep imports as well. for (const importedModule of importedModules) { - if (!importedModule.id || scanned.has(importedModule.id)) continue; - const ext = path.extname(importedModule.url.toLowerCase()); + if (!importedModule.id || scanned.has(importedModule.id)) { + continue; + } + const ext = path.extname(importedModule.url).toLowerCase(); if (STYLE_EXTENSIONS.has(ext)) { - css.add(importedModule.url); // note: return `url`s for HTML (not .id, which will break Windows) + // NOTE: We use the `url` property here. `id` would break Windows. + importedCssUrls.add(importedModule.url); } - crawlCSS(importedModule.id, scanned); + crawlCSS(importedModule.id, false, scanned); } } - crawlCSS(viteID(filePath)); - - return css; + // Crawl your import graph for CSS files, populating `importedCssUrls` as a result. + crawlCSS(viteID(filePath), true); + return importedCssUrls; } diff --git a/packages/astro/src/core/render/dev/index.ts b/packages/astro/src/core/render/dev/index.ts index 288ab97a0..09abb7d7b 100644 --- a/packages/astro/src/core/render/dev/index.ts +++ b/packages/astro/src/core/render/dev/index.ts @@ -1,19 +1,15 @@ +import { fileURLToPath } from 'url'; import type * as vite from 'vite'; -import type { AstroConfig, ComponentInstance, Renderer, RouteData, RuntimeMode, SSRElement } from '../../../@types/astro'; -import type { AstroRequest } from '../request'; - +import type { AstroConfig, AstroRenderer, ComponentInstance, RouteData, RuntimeMode, SSRElement, SSRLoadedRenderer } from '../../../@types/astro'; import { LogOptions } from '../../logger.js'; -import { fileURLToPath } from 'url'; -import { getStylesForURL } from './css.js'; -import { injectTags } from './html.js'; +import { render as coreRender } from '../core.js'; +import { prependForwardSlash } from '../../../core/path.js'; import { RouteCache } from '../route-cache.js'; -import { resolveRenderers } from './renderers.js'; +import { createModuleScriptElementWithSrcSet } from '../ssr-element.js'; +import { getStylesForURL } from './css.js'; import { errorHandler } from './error.js'; import { getHmrScript } from './hmr.js'; -import { prependForwardSlash } from '../../path.js'; -import { render as coreRender } from '../core.js'; -import { createModuleScriptElementWithSrcSet } from '../ssr-element.js'; - +import { injectTags } from './html.js'; export interface SSROptions { /** an instance of the AstroConfig */ astroConfig: AstroConfig; @@ -39,15 +35,25 @@ export interface SSROptions { headers: Headers; } -export type ComponentPreload = [Renderer[], ComponentInstance]; +export type ComponentPreload = [SSRLoadedRenderer[], ComponentInstance]; export type RenderResponse = { type: 'html'; html: string } | { type: 'response'; response: Response }; const svelteStylesRE = /svelte\?svelte&type=style/; +async function loadRenderer(viteServer: vite.ViteDevServer, renderer: AstroRenderer): Promise<SSRLoadedRenderer> { + const { url } = await viteServer.moduleGraph.ensureEntryFromUrl(renderer.serverEntrypoint); + const mod = (await viteServer.ssrLoadModule(url)) as { default: SSRLoadedRenderer['ssr'] }; + return { ...renderer, ssr: mod.default }; +} + +export async function loadRenderers(viteServer: vite.ViteDevServer, astroConfig: AstroConfig): Promise<SSRLoadedRenderer[]> { + return Promise.all(astroConfig._ctx.renderers.map((r) => loadRenderer(viteServer, r))); +} + export async function preload({ astroConfig, filePath, viteServer }: Pick<SSROptions, 'astroConfig' | 'filePath' | 'viteServer'>): Promise<ComponentPreload> { // Important: This needs to happen first, in case a renderer provides polyfills. - const renderers = await resolveRenderers(viteServer, astroConfig); + const renderers = await loadRenderers(viteServer, astroConfig); // Load the module from the Vite SSR Runtime. const mod = (await viteServer.ssrLoadModule(fileURLToPath(filePath))) as ComponentInstance; @@ -55,7 +61,7 @@ export async function preload({ astroConfig, filePath, viteServer }: Pick<SSROpt } /** use Vite to SSR */ -export async function render(renderers: Renderer[], mod: ComponentInstance, ssrOpts: SSROptions): Promise<RenderResponse> { +export async function render(renderers: SSRLoadedRenderer[], mod: ComponentInstance, ssrOpts: SSROptions): Promise<RenderResponse> { const { astroConfig, filePath, logging, mode, origin, pathname, method, headers, route, routeCache, viteServer } = ssrOpts; const legacy = astroConfig.buildOptions.legacyBuild; @@ -69,10 +75,19 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO children: '', }); scripts.add({ - props: { type: 'module', src: new URL('../../../runtime/client/hmr.js', import.meta.url).pathname }, + props: { type: 'module', src: '/@id/astro/client/hmr.js' }, children: '', }); } + // TODO: We should allow adding generic HTML elements to the head, not just scripts + for (const script of astroConfig._ctx.scripts) { + if (script.stage === 'head-inline') { + scripts.add({ + props: {}, + children: script.content, + }); + } + } // Pass framework CSS in as link tags to be appended to the page. let links = new Set<SSRElement>(); @@ -105,13 +120,22 @@ export async function render(renderers: Renderer[], mod: ComponentInstance, ssrO origin, pathname, scripts, - // Resolves specifiers in the inline hydrated scripts, such as "@astrojs/renderer-preact/client.js" + // Resolves specifiers in the inline hydrated scripts, such as "@astrojs/preact/client.js" + // TODO: Can we pass the hydration code more directly through Vite, so that we + // don't need to copy-paste and maintain Vite's import resolution here? async resolve(s: string) { // The legacy build needs these to remain unresolved so that vite HTML // Can do the resolution. Without this condition the build output will be // broken in the legacy build. This can be removed once the legacy build is removed. if (!astroConfig.buildOptions.legacyBuild) { - const [, resolvedPath] = await viteServer.moduleGraph.resolveUrl(s); + const [resolvedUrl, resolvedPath] = await viteServer.moduleGraph.resolveUrl(s); + if (resolvedPath.includes('node_modules/.vite')) { + return resolvedPath.replace(/.*?node_modules\/\.vite/, '/node_modules/.vite'); + } + // NOTE: This matches the same logic that Vite uses to add the `/@id/` prefix. + if (!resolvedUrl.startsWith('.') && !resolvedUrl.startsWith('/')) { + return '/@id' + prependForwardSlash(resolvedUrl); + } return '/@fs' + prependForwardSlash(resolvedPath); } else { return s; diff --git a/packages/astro/src/core/render/dev/renderers.ts b/packages/astro/src/core/render/dev/renderers.ts deleted file mode 100644 index f76294ba6..000000000 --- a/packages/astro/src/core/render/dev/renderers.ts +++ /dev/null @@ -1,36 +0,0 @@ -import type * as vite from 'vite'; -import type { AstroConfig, Renderer } from '../../../@types/astro'; - -import { resolveDependency } from '../../util.js'; -import { createRenderer } from '../renderer.js'; - -const cache = new Map<string, Promise<Renderer>>(); - -async function resolveRenderer(viteServer: vite.ViteDevServer, renderer: string, astroConfig: AstroConfig): Promise<Renderer> { - const resolvedRenderer: Renderer = await createRenderer(renderer, { - renderer(name) { - return import(resolveDependency(name, astroConfig)); - }, - async server(entry) { - const { url } = await viteServer.moduleGraph.ensureEntryFromUrl(entry); - const mod = await viteServer.ssrLoadModule(url); - return mod; - }, - }); - - return resolvedRenderer; -} - -export async function resolveRenderers(viteServer: vite.ViteDevServer, astroConfig: AstroConfig): Promise<Renderer[]> { - const ids: string[] = astroConfig.renderers; - const renderers = await Promise.all( - ids.map((renderer) => { - if (cache.has(renderer)) return cache.get(renderer)!; - let promise = resolveRenderer(viteServer, renderer, astroConfig); - cache.set(renderer, promise); - return promise; - }) - ); - - return renderers; -} diff --git a/packages/astro/src/core/render/renderer.ts b/packages/astro/src/core/render/renderer.ts deleted file mode 100644 index 0a54b6bf0..000000000 --- a/packages/astro/src/core/render/renderer.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { Renderer } from '../../@types/astro'; - -import npath from 'path'; - -interface RendererResolverImplementation { - renderer: (name: string) => Promise<any>; - server: (entry: string) => Promise<any>; -} - -export async function createRenderer(renderer: string, impl: RendererResolverImplementation) { - const resolvedRenderer: any = {}; - // We can dynamically import the renderer by itself because it shouldn't have - // any non-standard imports, the index is just meta info. - // The other entrypoints need to be loaded through Vite. - const { - default: { name, client, polyfills, hydrationPolyfills, server }, - } = await impl.renderer(renderer); //await import(resolveDependency(renderer, astroConfig)); - - resolvedRenderer.name = name; - if (client) resolvedRenderer.source = npath.posix.join(renderer, client); - resolvedRenderer.serverEntry = npath.posix.join(renderer, server); - if (Array.isArray(hydrationPolyfills)) resolvedRenderer.hydrationPolyfills = hydrationPolyfills.map((src: string) => npath.posix.join(renderer, src)); - if (Array.isArray(polyfills)) resolvedRenderer.polyfills = polyfills.map((src: string) => npath.posix.join(renderer, src)); - - const { default: rendererSSR } = await impl.server(resolvedRenderer.serverEntry); - resolvedRenderer.ssr = rendererSSR; - - const completedRenderer: Renderer = resolvedRenderer; - return completedRenderer; -} diff --git a/packages/astro/src/core/render/result.ts b/packages/astro/src/core/render/result.ts index f43382bb3..9edef6bad 100644 --- a/packages/astro/src/core/render/result.ts +++ b/packages/astro/src/core/render/result.ts @@ -1,12 +1,10 @@ -import type { AstroGlobal, AstroGlobalPartial, MarkdownParser, MarkdownRenderOptions, Params, Renderer, SSRElement, SSRResult } from '../../@types/astro'; -import type { AstroRequest } from './request'; - import { bold } from 'kleur/colors'; -import { createRequest } from './request.js'; +import type { AstroGlobal, AstroGlobalPartial, MarkdownParser, MarkdownRenderOptions, Params, SSRElement, SSRLoadedRenderer, SSRResult } from '../../@types/astro'; +import { renderSlot } from '../../runtime/server/index.js'; +import { LogOptions, warn } from '../logger.js'; import { isCSSRequest } from './dev/css.js'; +import { createRequest } from './request.js'; import { isScriptRequest } from './script.js'; -import { renderSlot } from '../../runtime/server/index.js'; -import { warn, LogOptions } from '../logger.js'; function onlyAvailableInSSR(name: string) { return function () { @@ -23,7 +21,7 @@ export interface CreateResultArgs { markdownRender: MarkdownRenderOptions; params: Params; pathname: string; - renderers: Renderer[]; + renderers: SSRLoadedRenderer[]; resolve: (s: string) => Promise<string>; site: string | undefined; links?: Set<SSRElement>; diff --git a/packages/astro/src/core/util.ts b/packages/astro/src/core/util.ts index f4319b7cf..17f06854d 100644 --- a/packages/astro/src/core/util.ts +++ b/packages/astro/src/core/util.ts @@ -25,6 +25,16 @@ export function isValidURL(url: string): boolean { return false; } +/** Returns true if argument is an object of any prototype/class (but not null). */ +export function isObject(value: unknown): value is Record<string, any> { + return typeof value === 'object' && value != null; +} + +/** Wraps an object in an array. If an array is passed, ignore it. */ +export function arraify<T>(target: T | T[]): T[] { + return Array.isArray(target) ? target : [target]; +} + /** is a specifier an npm package? */ export function parseNpmName(spec: string): { scope?: string; name: string; subpath?: string } | undefined { // not an npm package @@ -98,6 +108,14 @@ export function viteID(filePath: URL): string { return slash(fileURLToPath(filePath)); } +export const VALID_ID_PREFIX = `/@id/`; + +// Strip valid id prefix. This is prepended to resolved Ids that are +// not valid browser import specifiers by the importAnalysis plugin. +export function unwrapId(id: string): string { + return id.startsWith(VALID_ID_PREFIX) ? id.slice(VALID_ID_PREFIX.length) : id; +} + /** An fs utility, similar to `rimraf` or `rm -rf` */ export function removeDir(_dir: URL): void { const dir = fileURLToPath(_dir); diff --git a/packages/astro/src/integrations/index.ts b/packages/astro/src/integrations/index.ts new file mode 100644 index 000000000..af6736780 --- /dev/null +++ b/packages/astro/src/integrations/index.ts @@ -0,0 +1,76 @@ +import type { AddressInfo } from 'net'; +import type { ViteDevServer } from 'vite'; +import { AstroConfig, AstroRenderer } from '../@types/astro.js'; +import { mergeConfig } from '../core/config.js'; + +export async function runHookConfigSetup({ config: _config, command }: { config: AstroConfig; command: 'dev' | 'build' }): Promise<AstroConfig> { + let updatedConfig: AstroConfig = { ..._config }; + for (const integration of _config.integrations) { + if (integration.hooks['astro:config:setup']) { + await integration.hooks['astro:config:setup']({ + config: updatedConfig, + command, + addRenderer(renderer: AstroRenderer) { + updatedConfig._ctx.renderers.push(renderer); + }, + injectScript: (stage, content) => { + updatedConfig._ctx.scripts.push({ stage, content }); + }, + updateConfig: (newConfig) => { + updatedConfig = mergeConfig(updatedConfig, newConfig) as AstroConfig; + }, + }); + } + } + return updatedConfig; +} + +export async function runHookConfigDone({ config }: { config: AstroConfig }) { + for (const integration of config.integrations) { + if (integration.hooks['astro:config:done']) { + await integration.hooks['astro:config:done']({ + config, + }); + } + } +} + +export async function runHookServerSetup({ config, server }: { config: AstroConfig; server: ViteDevServer }) { + for (const integration of config.integrations) { + if (integration.hooks['astro:server:setup']) { + await integration.hooks['astro:server:setup']({ server }); + } + } +} + +export async function runHookServerStart({ config, address }: { config: AstroConfig; address: AddressInfo }) { + for (const integration of config.integrations) { + if (integration.hooks['astro:server:start']) { + await integration.hooks['astro:server:start']({ address }); + } + } +} + +export async function runHookServerDone({ config }: { config: AstroConfig }) { + for (const integration of config.integrations) { + if (integration.hooks['astro:server:done']) { + await integration.hooks['astro:server:done'](); + } + } +} + +export async function runHookBuildStart({ config }: { config: AstroConfig }) { + for (const integration of config.integrations) { + if (integration.hooks['astro:build:start']) { + await integration.hooks['astro:build:start'](); + } + } +} + +export async function runHookBuildDone({ config, pages }: { config: AstroConfig; pages: string[] }) { + for (const integration of config.integrations) { + if (integration.hooks['astro:build:done']) { + await integration.hooks['astro:build:done']({ pages: pages.map((p) => ({ pathname: p })), dir: config.dist }); + } + } +} diff --git a/packages/astro/src/runtime/server/hydration.ts b/packages/astro/src/runtime/server/hydration.ts index 2ffdc9144..5f106d942 100644 --- a/packages/astro/src/runtime/server/hydration.ts +++ b/packages/astro/src/runtime/server/hydration.ts @@ -1,4 +1,4 @@ -import type { AstroComponentMetadata } from '../../@types/astro'; +import type { AstroComponentMetadata, SSRLoadedRenderer } from '../../@types/astro'; import type { SSRElement, SSRResult } from '../../@types/astro'; import { hydrationSpecifier, serializeListValue } from './util.js'; import serializeJavaScript from 'serialize-javascript'; @@ -81,7 +81,7 @@ export function extractDirectives(inputProps: Record<string | number, any>): Ext } interface HydrateScriptOptions { - renderer: any; + renderer: SSRLoadedRenderer; result: SSRResult; astroId: string; props: Record<string | number, any>; @@ -96,16 +96,11 @@ export async function generateHydrateScript(scriptOptions: HydrateScriptOptions, throw new Error(`Unable to resolve a componentExport for "${metadata.displayName}"! Please open an issue.`); } - let hydrationSource = ''; - if (renderer.hydrationPolyfills) { - hydrationSource += `await Promise.all([${(await Promise.all(renderer.hydrationPolyfills.map(async (src: string) => `\n import("${await result.resolve(src)}")`))).join( - ', ' - )}]);\n`; - } + let hydrationSource = ``; - hydrationSource += renderer.source + hydrationSource += renderer.clientEntrypoint ? `const [{ ${componentExport.value}: Component }, { default: hydrate }] = await Promise.all([import("${await result.resolve(componentUrl)}"), import("${await result.resolve( - renderer.source + renderer.clientEntrypoint )}")]); return (el, children) => hydrate(el)(Component, ${serializeProps(props)}, children); ` @@ -116,6 +111,7 @@ export async function generateHydrateScript(scriptOptions: HydrateScriptOptions, const hydrationScript = { props: { type: 'module', 'data-astro-component-hydration': true }, children: `import setup from '${await result.resolve(hydrationSpecifier(hydrate))}'; +${`import '${await result.resolve('astro:scripts/before-hydration.js')}';`} setup("${astroId}", {name:"${metadata.displayName}",${metadata.hydrateArgs ? `value: ${JSON.stringify(metadata.hydrateArgs)}` : ''}}, async () => { ${hydrationSource} }); diff --git a/packages/astro/src/runtime/server/index.ts b/packages/astro/src/runtime/server/index.ts index da510f2fb..d977219ac 100644 --- a/packages/astro/src/runtime/server/index.ts +++ b/packages/astro/src/runtime/server/index.ts @@ -1,19 +1,14 @@ -import type { AstroComponentMetadata, EndpointHandler, Renderer, Params } from '../../@types/astro'; -import type { AstroGlobalPartial, SSRResult, SSRElement } from '../../@types/astro'; -import type { AstroRequest } from '../../core/render/request'; - import shorthash from 'shorthash'; +import type { AstroComponentMetadata, AstroGlobalPartial, EndpointHandler, Params, SSRElement, SSRLoadedRenderer, SSRResult } from '../../@types/astro'; +import type { AstroRequest } from '../../core/render/request'; +import { escapeHTML, HTMLString, markHTMLString } from './escape.js'; import { extractDirectives, generateHydrateScript, serializeProps } from './hydration.js'; import { serializeListValue } from './util.js'; -import { escapeHTML, HTMLString, markHTMLString } from './escape.js'; +export { markHTMLString, markHTMLString as unescapeHTML } from './escape.js'; export type { Metadata } from './metadata'; export { createMetadata } from './metadata.js'; -export { markHTMLString } from './escape.js'; -// TODO(deprecated): This name has been updated in Astro runtime but not yet in the Astro compiler. -export { markHTMLString as unescapeHTML } from './escape.js'; - const voidElementNames = /^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i; const htmlBooleanAttributes = /^(allowfullscreen|async|autofocus|autoplay|controls|default|defer|disabled|disablepictureinpicture|disableremoteplayback|formnovalidate|hidden|loop|nomodule|novalidate|open|playsinline|readonly|required|reversed|scoped|seamless|itemscope)$/i; @@ -116,14 +111,14 @@ function guessRenderers(componentUrl?: string): string[] { const extname = componentUrl?.split('.').pop(); switch (extname) { case 'svelte': - return ['@astrojs/renderer-svelte']; + return ['@astrojs/svelte']; case 'vue': - return ['@astrojs/renderer-vue']; + return ['@astrojs/vue']; case 'jsx': case 'tsx': - return ['@astrojs/renderer-react', '@astrojs/renderer-preact']; + return ['@astrojs/react', '@astrojs/preact']; default: - return ['@astrojs/renderer-react', '@astrojs/renderer-preact', '@astrojs/renderer-vue', '@astrojs/renderer-svelte']; + return ['@astrojs/react', '@astrojs/preact', '@astrojs/vue', '@astrojs/svelte']; } } @@ -171,13 +166,13 @@ export async function renderComponent(result: SSRResult, displayName: string, Co if (Array.isArray(renderers) && renderers.length === 0 && typeof Component !== 'string' && !componentIsHTMLElement(Component)) { const message = `Unable to render ${metadata.displayName}! -There are no \`renderers\` set in your \`astro.config.mjs\` file. -Did you mean to enable ${formatList(probableRendererNames.map((r) => '`' + r + '`'))}?`; +There are no \`integrations\` set in your \`astro.config.mjs\` file. +Did you mean to add ${formatList(probableRendererNames.map((r) => '`' + r + '`'))}?`; throw new Error(message); } // Call the renderers `check` hook to see if any claim this component. - let renderer: Renderer | undefined; + let renderer: SSRLoadedRenderer | undefined; if (metadata.hydrate !== 'only') { for (const r of renderers) { if (await r.ssr.check(Component, props, children)) { @@ -195,7 +190,7 @@ Did you mean to enable ${formatList(probableRendererNames.map((r) => '`' + r + ' // Attempt: use explicitly passed renderer name if (metadata.hydrateArgs) { const rendererName = metadata.hydrateArgs; - renderer = renderers.filter(({ name }) => name === `@astrojs/renderer-${rendererName}` || name === rendererName)[0]; + renderer = renderers.filter(({ name }) => name === `@astrojs/${rendererName}` || name === rendererName)[0]; } // Attempt: user only has a single renderer, default to that if (!renderer && renderers.length === 1) { @@ -204,7 +199,7 @@ Did you mean to enable ${formatList(probableRendererNames.map((r) => '`' + r + ' // Attempt: can we guess the renderer from the export extension? if (!renderer) { const extname = metadata.componentUrl?.split('.').pop(); - renderer = renderers.filter(({ name }) => name === `@astrojs/renderer-${extname}` || name === extname)[0]; + renderer = renderers.filter(({ name }) => name === `@astrojs/${extname}` || name === extname)[0]; } } @@ -215,7 +210,7 @@ Did you mean to enable ${formatList(probableRendererNames.map((r) => '`' + r + ' throw new Error(`Unable to render ${metadata.displayName}! Using the \`client:only\` hydration strategy, Astro needs a hint to use the correct renderer. -Did you mean to pass <${metadata.displayName} client:only="${probableRendererNames.map((r) => r.replace('@astrojs/renderer-', '')).join('|')}" /> +Did you mean to pass <${metadata.displayName} client:only="${probableRendererNames.map((r) => r.replace('@astrojs/', '')).join('|')}" /> `); } else if (typeof Component !== 'string') { const matchingRenderers = renderers.filter((r) => probableRendererNames.includes(r.name)); @@ -264,16 +259,6 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr ); } - // This is used to add polyfill scripts to the page, if the renderer needs them. - if (renderer?.polyfills?.length) { - for (const src of renderer.polyfills) { - result.scripts.add({ - props: { type: 'module' }, - children: `import "${await result.resolve(src)}";`, - }); - } - } - if (!hydration) { return markHTMLString(html.replace(/\<\/?astro-fragment\>/g, '')); } @@ -283,7 +268,7 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr // Rather than appending this inline in the page, puts this into the `result.scripts` set that will be appended to the head. // INVESTIGATE: This will likely be a problem in streaming because the `<head>` will be gone at this point. - result.scripts.add(await generateHydrateScript({ renderer, result, astroId, props }, metadata as Required<AstroComponentMetadata>)); + result.scripts.add(await generateHydrateScript({ renderer: renderer!, result, astroId, props }, metadata as Required<AstroComponentMetadata>)); // Render a template if no fragment is provided. const needsAstroTemplate = children && !/<\/?astro-fragment\>/.test(html); diff --git a/packages/astro/src/vite-plugin-astro/compile.ts b/packages/astro/src/vite-plugin-astro/compile.ts index f9075e3e7..48bada5f4 100644 --- a/packages/astro/src/vite-plugin-astro/compile.ts +++ b/packages/astro/src/vite-plugin-astro/compile.ts @@ -122,13 +122,7 @@ export function invalidateCompilation(config: AstroConfig, filename: string) { } } -export async function cachedCompilation( - config: AstroConfig, - filename: string, - source: string | null, - viteTransform: TransformHook, - opts: { ssr: boolean } -): Promise<CompileResult> { +export async function cachedCompilation(config: AstroConfig, filename: string, source: string, viteTransform: TransformHook, opts: { ssr: boolean }): Promise<CompileResult> { let cache: CompilationCache; if (!configCache.has(config)) { cache = new Map(); @@ -139,11 +133,6 @@ export async function cachedCompilation( if (cache.has(filename)) { return cache.get(filename)!; } - - if (source === null) { - const fileUrl = new URL(`file://${filename}`); - source = await fs.promises.readFile(fileUrl, 'utf-8'); - } const compileResult = await compile(config, filename, source, viteTransform, opts); cache.set(filename, compileResult); return compileResult; diff --git a/packages/astro/src/vite-plugin-astro/index.ts b/packages/astro/src/vite-plugin-astro/index.ts index e7dce20fd..0f169caa1 100644 --- a/packages/astro/src/vite-plugin-astro/index.ts +++ b/packages/astro/src/vite-plugin-astro/index.ts @@ -35,7 +35,7 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu return slash(fileURLToPath(url)) + url.search; } - let isProduction: boolean; + let resolvedConfig: vite.ResolvedConfig; let viteTransform: TransformHook; let viteDevServer: vite.ViteDevServer | null = null; @@ -46,9 +46,9 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu return { name: 'astro:build', enforce: 'pre', // run transforms before other plugins can - configResolved(resolvedConfig) { + configResolved(_resolvedConfig) { + resolvedConfig = _resolvedConfig; viteTransform = getViteTransform(resolvedConfig); - isProduction = resolvedConfig.isProduction; }, configureServer(server) { viteDevServer = server; @@ -83,20 +83,26 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu } }, async load(id, opts) { - let { filename, query } = parseAstroRequest(id); + const parsedId = parseAstroRequest(id); + const query = parsedId.query; + if (!id.endsWith('.astro') && !query.astro) { + return null; + } + + const filename = normalizeFilename(parsedId.filename); + const fileUrl = new URL(`file://${filename}`); + let source = await fs.promises.readFile(fileUrl, 'utf-8'); + const isPage = filename.startsWith(config.pages.pathname); + if (isPage && config._ctx.scripts.some((s) => s.stage === 'page')) { + source += `\n<script hoist src="astro:scripts/page.js" />`; + } if (query.astro) { if (query.type === 'style') { - if (filename.startsWith('/@fs')) { - filename = filename.slice('/@fs'.length); - } else if (filename.startsWith('/') && !ancestor(filename, config.projectRoot.pathname)) { - filename = new URL('.' + filename, config.projectRoot).pathname; - } - if (typeof query.index === 'undefined') { throw new Error(`Requests for Astro CSS must include an index.`); } - const transformResult = await cachedCompilation(config, normalizeFilename(filename), null, viteTransform, { ssr: Boolean(opts?.ssr) }); + const transformResult = await cachedCompilation(config, filename, source, viteTransform, { ssr: Boolean(opts?.ssr) }); // Track any CSS dependencies so that HMR is triggered when they change. await trackCSSDependencies.call(this, { viteDevServer, id, filename, deps: transformResult.rawCSSDeps }); @@ -111,7 +117,7 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu throw new Error(`Requests for hoisted scripts must include an index`); } - const transformResult = await cachedCompilation(config, normalizeFilename(filename), null, viteTransform, { ssr: Boolean(opts?.ssr) }); + const transformResult = await cachedCompilation(config, filename, source, viteTransform, { ssr: Boolean(opts?.ssr) }); const scripts = transformResult.scripts; const hoistedScript = scripts[query.index]; @@ -125,13 +131,8 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu } } - if (!id.endsWith('.astro')) { - return null; - } - - const source = await fs.promises.readFile(id, { encoding: 'utf-8' }); try { - const transformResult = await cachedCompilation(config, id, source, viteTransform, { ssr: Boolean(opts?.ssr) }); + const transformResult = await cachedCompilation(config, filename, source, viteTransform, { ssr: Boolean(opts?.ssr) }); // Compile all TypeScript to JavaScript. // Also, catches invalid JS/TS in the compiled output before returning. @@ -143,9 +144,15 @@ export default function astro({ config, logging }: AstroPluginOptions): vite.Plu define: config.vite.define, }); - // Signal to Vite that we accept HMR updates - const SUFFIX = isProduction ? '' : `\nif (import.meta.hot) import.meta.hot.accept((mod) => mod);`; - + let SUFFIX = ''; + // Add HMR handling in dev mode. + if (!resolvedConfig.isProduction) { + SUFFIX += `\nif (import.meta.hot) import.meta.hot.accept((mod) => mod);`; + } + // Add handling to inject scripts into each page JS bundle, if needed. + if (isPage) { + SUFFIX += `\nimport "astro:scripts/page-ssr.js";`; + } return { code: `${code}${SUFFIX}`, map, diff --git a/packages/astro/src/vite-plugin-integrations-container/index.ts b/packages/astro/src/vite-plugin-integrations-container/index.ts new file mode 100644 index 000000000..8defa16b5 --- /dev/null +++ b/packages/astro/src/vite-plugin-integrations-container/index.ts @@ -0,0 +1,13 @@ +import { Plugin as VitePlugin, ResolvedConfig } from 'vite'; +import { AstroConfig } from '../@types/astro.js'; +import { runHookServerSetup } from '../integrations/index.js'; + +/** Connect Astro integrations into Vite, as needed. */ +export default function astroIntegrationsContainerPlugin({ config }: { config: AstroConfig }): VitePlugin { + return { + name: 'astro:integration-container', + configureServer(server) { + runHookServerSetup({ config, server }); + }, + }; +} diff --git a/packages/astro/src/vite-plugin-jsx/index.ts b/packages/astro/src/vite-plugin-jsx/index.ts index b306bd73f..65418815d 100644 --- a/packages/astro/src/vite-plugin-jsx/index.ts +++ b/packages/astro/src/vite-plugin-jsx/index.ts @@ -1,6 +1,6 @@ import type { TransformResult } from 'rollup'; import type { Plugin, ResolvedConfig } from 'vite'; -import type { AstroConfig, Renderer } from '../@types/astro'; +import type { AstroConfig, AstroRenderer } from '../@types/astro'; import type { LogOptions } from '../core/logger.js'; import babel from '@babel/core'; @@ -9,9 +9,9 @@ import * as colors from 'kleur/colors'; import * as eslexer from 'es-module-lexer'; import path from 'path'; import { error } from '../core/logger.js'; -import { parseNpmName, resolveDependency } from '../core/util.js'; +import { parseNpmName } from '../core/util.js'; -const JSX_RENDERER_CACHE = new WeakMap<AstroConfig, Map<string, Renderer>>(); +const JSX_RENDERER_CACHE = new WeakMap<AstroConfig, Map<string, AstroRenderer>>(); const JSX_EXTENSIONS = new Set(['.jsx', '.tsx']); const IMPORT_STATEMENTS: Record<string, string> = { react: "import React from 'react'", @@ -28,24 +28,16 @@ function getEsbuildLoader(fileExt: string): string { return fileExt.substr(1); } -async function importJSXRenderers(config: AstroConfig): Promise<Map<string, Renderer>> { - const renderers = new Map<string, Renderer>(); - await Promise.all( - config.renderers.map((name) => { - return import(resolveDependency(name, config)).then(({ default: renderer }) => { - if (!renderer.jsxImportSource) return; - renderers.set(renderer.jsxImportSource, renderer); - }); - }) - ); - return renderers; +function collectJSXRenderers(renderers: AstroRenderer[]): Map<string, AstroRenderer> { + const renderersWithJSXSupport = renderers.filter((r) => r.jsxImportSource); + return new Map(renderersWithJSXSupport.map((r) => [r.jsxImportSource, r] as [string, AstroRenderer])); } interface TransformJSXOptions { code: string; id: string; mode: string; - renderer: Renderer; + renderer: AstroRenderer; ssr: boolean; } @@ -100,13 +92,13 @@ export default function jsx({ config, logging }: AstroPluginJSXOptions): Plugin // load renderers (on first run only) if (!jsxRenderers) { jsxRenderers = new Map(); - const possibleRenderers = await importJSXRenderers(config); + const possibleRenderers = await collectJSXRenderers(config._ctx.renderers); if (possibleRenderers.size === 0) { // note: we have filtered out all non-JSX files, so this error should only show if a JSX file is loaded with no matching renderers throw new Error( `${colors.yellow( id - )}\nUnable to resolve a renderer that handles JSX transforms! Please include a \`renderer\` plugin which supports JSX in your \`astro.config.mjs\` file.` + )}\nUnable to resolve a JSX renderer! Did you forget to include one? Add a JSX integration like \`@astrojs/react\` to your \`astro.config.mjs\` file.` ); } for (const [importSource, renderer] of possibleRenderers) { @@ -173,7 +165,7 @@ export default function jsx({ config, logging }: AstroPluginJSXOptions): Plugin const jsxRenderer = jsxRenderers.get(importSource); // if renderer not installed for this JSX source, throw error if (!jsxRenderer) { - error(logging, 'renderer', `${colors.yellow(id)} No renderer installed for ${importSource}. Try adding \`@astrojs/renderer-${importSource}\` to your dependencies.`); + error(logging, 'renderer', `${colors.yellow(id)} No renderer installed for ${importSource}. Try adding \`@astrojs/${importSource}\` to your project.`); return null; } // downlevel any non-standard syntax, but preserve JSX @@ -183,7 +175,7 @@ export default function jsx({ config, logging }: AstroPluginJSXOptions): Plugin sourcefile: id, sourcemap: 'inline', }); - return await transformJSX({ code: jsxCode, id, renderer: jsxRenderers.get(importSource) as Renderer, mode, ssr }); + return await transformJSX({ code: jsxCode, id, renderer: jsxRenderers.get(importSource) as AstroRenderer, mode, ssr }); } // if we still can’t tell, throw error diff --git a/packages/astro/src/vite-plugin-scripts/index.ts b/packages/astro/src/vite-plugin-scripts/index.ts new file mode 100644 index 000000000..5e3d6c78d --- /dev/null +++ b/packages/astro/src/vite-plugin-scripts/index.ts @@ -0,0 +1,59 @@ +import { Plugin as VitePlugin } from 'vite'; +import { AstroConfig } from '../@types/astro.js'; + +// NOTE: We can't use the virtual "\0" ID convention because we need to +// inject these as ESM imports into actual code, where they would not +// resolve correctly. +const SCRIPT_ID_PREFIX = `astro:scripts/`; +const BEFORE_HYDRATION_SCRIPT_ID = `${SCRIPT_ID_PREFIX}before-hydration.js`; +const PAGE_SCRIPT_ID = `${SCRIPT_ID_PREFIX}page.js`; +const PAGE_SSR_SCRIPT_ID = `${SCRIPT_ID_PREFIX}page-ssr.js`; + +export default function astroScriptsPlugin({ config }: { config: AstroConfig }): VitePlugin { + return { + name: 'astro:scripts', + async resolveId(id) { + if (id.startsWith(SCRIPT_ID_PREFIX)) { + return id; + } + return undefined; + }, + + async load(id) { + if (id === BEFORE_HYDRATION_SCRIPT_ID) { + return config._ctx.scripts + .filter((s) => s.stage === 'before-hydration') + .map((s) => s.content) + .join('\n'); + } + if (id === PAGE_SCRIPT_ID) { + return config._ctx.scripts + .filter((s) => s.stage === 'page') + .map((s) => s.content) + .join('\n'); + } + if (id === PAGE_SSR_SCRIPT_ID) { + return config._ctx.scripts + .filter((s) => s.stage === 'page-ssr') + .map((s) => s.content) + .join('\n'); + } + return null; + }, + buildStart(options) { + // We only want to inject this script if we are building + // for the frontend AND some hydrated components exist in + // the final build. We can detect this by looking for a + // `astro/client/*` input, which signifies both conditions are met. + const hasHydratedComponents = Array.isArray(options.input) && options.input.some((input) => input.startsWith('astro/client')); + const hasHydrationScripts = config._ctx.scripts.some((s) => s.stage === 'before-hydration'); + if (hasHydratedComponents && hasHydrationScripts) { + this.emitFile({ + type: 'chunk', + id: BEFORE_HYDRATION_SCRIPT_ID, + name: BEFORE_HYDRATION_SCRIPT_ID, + }); + } + }, + }; +} diff --git a/packages/astro/test/0-css.test.js b/packages/astro/test/0-css.test.js index 67ae73012..6d86bf886 100644 --- a/packages/astro/test/0-css.test.js +++ b/packages/astro/test/0-css.test.js @@ -12,15 +12,7 @@ let fixture; describe('CSS', function () { before(async () => { - fixture = await loadFixture({ - projectRoot: './fixtures/0-css/', - renderers: ['@astrojs/renderer-react', '@astrojs/renderer-svelte', '@astrojs/renderer-vue'], - vite: { - build: { - assetsInlineLimit: 0, - }, - }, - }); + fixture = await loadFixture({ projectRoot: './fixtures/0-css/' }); }); // test HTML and CSS contents for accuracy diff --git a/packages/astro/test/astro-assets.test.js b/packages/astro/test/astro-assets.test.js index 7f84dbd57..84f361672 100644 --- a/packages/astro/test/astro-assets.test.js +++ b/packages/astro/test/astro-assets.test.js @@ -13,11 +13,6 @@ describe('Assets', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/astro-assets/', - vite: { - build: { - assetsInlineLimit: 0, - }, - }, }); await fixture.build(); }); diff --git a/packages/astro/test/astro-children.test.js b/packages/astro/test/astro-children.test.js index 3df65e2e6..d3f985f63 100644 --- a/packages/astro/test/astro-children.test.js +++ b/packages/astro/test/astro-children.test.js @@ -6,10 +6,7 @@ describe('Component children', () => { let fixture; before(async () => { - fixture = await loadFixture({ - projectRoot: './fixtures/astro-children/', - renderers: ['@astrojs/renderer-preact', '@astrojs/renderer-vue', '@astrojs/renderer-svelte'], - }); + fixture = await loadFixture({ projectRoot: './fixtures/astro-children/' }); await fixture.build(); }); diff --git a/packages/astro/test/astro-dynamic.test.js b/packages/astro/test/astro-dynamic.test.js index fc104c2bd..81a960ffb 100644 --- a/packages/astro/test/astro-dynamic.test.js +++ b/packages/astro/test/astro-dynamic.test.js @@ -32,24 +32,11 @@ describe('Dynamic components', () => { const html = await fixture.readFile('/client-only/index.html'); const $ = cheerio.load(html); - // test 1: <astro-root> is empty + // test 1: <astro-root> is empty. expect($('<astro-root>').html()).to.equal(''); - const script = $('script').text(); - - // Grab the svelte import - // const exp = /import\("(.+?)"\)/g; - // let match, svelteRenderer; - // while ((match = exp.exec(result.contents))) { - // if (match[1].includes('renderers/renderer-svelte/client.js')) { - // svelteRenderer = match[1]; - // } - // } - - // test 2: Svelte renderer is on the page - // expect(svelteRenderer).to.be.ok; - - // test 3: Can load svelte renderer - // const result = await fixture.fetch(svelteRenderer); - // expect(result.status).to.equal(200); + // test 2: correct script is being loaded. + // because of bundling, we don't have access to the source import, + // only the bundled import. + expect($('script').html()).to.include(`import setup from '../only`); }); }); diff --git a/packages/astro/test/astro-expr.test.js b/packages/astro/test/astro-expr.test.js index 31e10374d..679cac1cf 100644 --- a/packages/astro/test/astro-expr.test.js +++ b/packages/astro/test/astro-expr.test.js @@ -8,7 +8,6 @@ describe('Expressions', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/astro-expr/', - renderers: ['@astrojs/renderer-preact'], }); await fixture.build(); }); diff --git a/packages/astro/test/astro-fallback.test.js b/packages/astro/test/astro-fallback.test.js index 0b07840d7..f098bd177 100644 --- a/packages/astro/test/astro-fallback.test.js +++ b/packages/astro/test/astro-fallback.test.js @@ -8,7 +8,6 @@ describe('Dynamic component fallback', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/astro-fallback', - renderers: ['@astrojs/renderer-preact'], }); await fixture.build(); }); diff --git a/packages/astro/test/astro-jsx.test.js b/packages/astro/test/astro-jsx.test.js deleted file mode 100644 index 14ca9aa24..000000000 --- a/packages/astro/test/astro-jsx.test.js +++ /dev/null @@ -1,43 +0,0 @@ -import { expect } from 'chai'; -import { loadFixture } from './test-utils.js'; - -describe('JSX', () => { - let cwd = './fixtures/astro-jsx/'; - let orders = [ - ['preact', 'react', 'solid'], - ['preact', 'solid', 'react'], - ['react', 'preact', 'solid'], - ['react', 'solid', 'preact'], - ['solid', 'react', 'preact'], - ['solid', 'preact', 'react'], - ]; - let fixtures = {}; - - before(async () => { - await Promise.all( - orders.map((renderers, n) => - loadFixture({ - projectRoot: cwd, - renderers: renderers.map((name) => `@astrojs/renderer-${name}`), - dist: new URL(`${cwd}dist-${n}/`, import.meta.url), - }).then((fixture) => { - fixtures[renderers.toString()] = fixture; - return fixture.build(); - }) - ) - ); - }); - - it('Renderer order', () => { - it('JSX renderers can be defined in any order', async () => { - if (!Object.values(fixtures).length) { - throw new Error(`JSX renderers didn’t build properly`); - } - - for (const [name, fixture] of Object.entries(fixtures)) { - const html = await fixture.readFile('/index.html'); - expect(html, name).to.be.ok; - } - }); - }); -}); diff --git a/packages/astro/test/astro-markdown-plugins.test.js b/packages/astro/test/astro-markdown-plugins.test.js index ee780a738..01c6c01b2 100644 --- a/packages/astro/test/astro-markdown-plugins.test.js +++ b/packages/astro/test/astro-markdown-plugins.test.js @@ -10,7 +10,6 @@ describe('Astro Markdown plugins', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/astro-markdown-plugins/', - renderers: ['@astrojs/renderer-preact'], markdownOptions: { render: [ markdownRemark, diff --git a/packages/astro/test/astro-markdown.test.js b/packages/astro/test/astro-markdown.test.js index d079646d5..fdcd2bde2 100644 --- a/packages/astro/test/astro-markdown.test.js +++ b/packages/astro/test/astro-markdown.test.js @@ -8,10 +8,6 @@ describe('Astro Markdown', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/astro-markdown/', - renderers: ['@astrojs/renderer-preact'], - buildOptions: { - sitemap: false, - }, }); await fixture.build(); }); diff --git a/packages/astro/test/astro-partial-html.test.js b/packages/astro/test/astro-partial-html.test.js index a36981b7b..1c6b43fb6 100644 --- a/packages/astro/test/astro-partial-html.test.js +++ b/packages/astro/test/astro-partial-html.test.js @@ -2,7 +2,7 @@ import { expect } from 'chai'; import cheerio from 'cheerio'; import { loadFixture } from './test-utils.js'; -describe('Partial HTML ', async () => { +describe('Partial HTML', async () => { let fixture; let devServer; diff --git a/packages/astro/test/config-validate.test.js b/packages/astro/test/config-validate.test.js index 0b1bbcd43..b8ac459ba 100644 --- a/packages/astro/test/config-validate.test.js +++ b/packages/astro/test/config-validate.test.js @@ -31,7 +31,7 @@ describe('Config Validation', () => { it('Multiple validation errors can be formatted correctly', async () => { const veryBadConfig = { - renderers: [42], + integrations: [42], buildOptions: { pageUrlFormat: 'invalid' }, pages: {}, }; @@ -41,8 +41,34 @@ describe('Config Validation', () => { expect(formattedError).to.equal( `[config] Astro found issue(s) with your configuration: ! pages Expected string, received object. - ! renderers.0 Expected string, received number. + ! integrations.0 Expected object, received number. ! buildOptions.pageUrlFormat Invalid input.` ); }); + + it('ignores falsey "integration" values', async () => { + const result = await validateConfig({ integrations: [0, false, null, undefined] }, process.cwd()); + expect(result.integrations).to.deep.equal([]); + }); + it('normalizes "integration" values', async () => { + const result = await validateConfig({ integrations: [{ name: '@astrojs/a' }] }, process.cwd()); + expect(result.integrations).to.deep.equal([{ name: '@astrojs/a', hooks: {} }]); + }); + it('flattens array "integration" values', async () => { + const result = await validateConfig({ integrations: [{ name: '@astrojs/a' }, [{ name: '@astrojs/b' }, { name: '@astrojs/c' }]] }, process.cwd()); + expect(result.integrations).to.deep.equal([ + { name: '@astrojs/a', hooks: {} }, + { name: '@astrojs/b', hooks: {} }, + { name: '@astrojs/c', hooks: {} }, + ]); + }); + it('blocks third-party "integration" values', async () => { + const configError = await validateConfig({ integrations: [{ name: '@my-plugin/a' }] }, process.cwd()).catch((err) => err); + expect(configError instanceof z.ZodError).to.equal(true); + const formattedError = stripAnsi(formatConfigError(configError)); + expect(formattedError).to.equal( + `[config] Astro found issue(s) with your configuration: + ! integrations Astro integrations are still experimental, and only official integrations are currently supported.` + ); + }); }); diff --git a/packages/astro/test/config.test.js b/packages/astro/test/config.test.js index 84193694a..80a2668e6 100644 --- a/packages/astro/test/config.test.js +++ b/packages/astro/test/config.test.js @@ -10,9 +10,24 @@ describe('config', () => { before(async () => { [hostnameFixture, hostFixture, portFixture] = await Promise.all([ - loadFixture({ projectRoot: './fixtures/config-hostname/' }), - loadFixture({ projectRoot: './fixtures/config-host/' }), - loadFixture({ projectRoot: './fixtures/config-port/' }), + loadFixture({ + projectRoot: './fixtures/config-host/', + devOptions: { + hostname: '0.0.0.0', + }, + }), + loadFixture({ + projectRoot: './fixtures/config-host/', + devOptions: { + host: true, + }, + }), + loadFixture({ + projectRoot: './fixtures/config-host/', + devOptions: { + port: 5006, + }, + }), ]); }); diff --git a/packages/astro/test/custom-elements.test.js b/packages/astro/test/custom-elements.test.js index 927b2bedf..4224cbc83 100644 --- a/packages/astro/test/custom-elements.test.js +++ b/packages/astro/test/custom-elements.test.js @@ -2,13 +2,17 @@ import { expect } from 'chai'; import cheerio from 'cheerio'; import { loadFixture } from './test-utils.js'; -describe('Custom Elements', () => { +// TODO(fks): This seemed to test a custom renderer, but it seemed to be a copy +// fixture of lit. Should this be moved into a publicly published integration now, +// and then tested as an example? Or, should we just remove. Skipping now +// to tackle later, since our lit tests cover similar code paths. +describe.skip('Custom Elements', () => { let fixture; before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/custom-elements/', - renderers: ['@test/custom-element-renderer'], + intergrations: ['@test/custom-element-renderer'], }); await fixture.build(); }); diff --git a/packages/astro/test/dev-routing.test.js b/packages/astro/test/dev-routing.test.js index 97e4e3203..d411f5de9 100644 --- a/packages/astro/test/dev-routing.test.js +++ b/packages/astro/test/dev-routing.test.js @@ -51,7 +51,13 @@ describe('Development Routing', () => { let devServer; before(async () => { - fixture = await loadFixture({ projectRoot: './fixtures/without-subpath/' }); + fixture = await loadFixture({ + projectRoot: './fixtures/with-subpath-no-trailing-slash/', + dist: './dist-4007', + buildOptions: { + site: 'http://example.com/', + }, + }); devServer = await fixture.startDevServer(); }); @@ -87,7 +93,13 @@ describe('Development Routing', () => { let devServer; before(async () => { - fixture = await loadFixture({ projectRoot: './fixtures/with-subpath-trailing-slash/' }); + fixture = await loadFixture({ + projectRoot: './fixtures/with-subpath-no-trailing-slash/', + dist: './dist-4008', + buildOptions: { + site: 'http://example.com/blog/', + }, + }); devServer = await fixture.startDevServer(); }); @@ -133,7 +145,10 @@ describe('Development Routing', () => { let devServer; before(async () => { - fixture = await loadFixture({ projectRoot: './fixtures/with-subpath-no-trailing-slash/' }); + fixture = await loadFixture({ + projectRoot: './fixtures/with-subpath-no-trailing-slash/', + dist: './dist-4009', + }); devServer = await fixture.startDevServer(); }); @@ -179,7 +194,12 @@ describe('Development Routing', () => { let devServer; before(async () => { - fixture = await loadFixture({ projectRoot: './fixtures/with-endpoint-routes/' }); + fixture = await loadFixture({ + projectRoot: './fixtures/with-endpoint-routes/', + buildOptions: { + site: 'http://example.com/', + }, + }); devServer = await fixture.startDevServer(); }); diff --git a/packages/astro/test/errors.test.js b/packages/astro/test/errors.test.js index d85cb9e04..093dd5d8d 100644 --- a/packages/astro/test/errors.test.js +++ b/packages/astro/test/errors.test.js @@ -1,4 +1,3 @@ -import { expect } from 'chai'; import { isWindows, loadFixture } from './test-utils.js'; describe('Error display', () => { @@ -10,199 +9,18 @@ describe('Error display', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/errors', - renderers: ['@astrojs/renderer-preact', '@astrojs/renderer-react', '@astrojs/renderer-solid', '@astrojs/renderer-svelte', '@astrojs/renderer-vue'], - vite: { - optimizeDeps: false, // necessary to prevent Vite throwing on bad files - }, }); - devServer = await fixture.startDevServer(); - }); - - after(async () => { - await devServer.stop(); }); describe('Astro', () => { - it('syntax error in template', async () => { - const res = await fixture.fetch('/astro-syntax-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Unexpected "}"'); - }); - - it('syntax error in frontmatter', async () => { - const res = await fixture.fetch('/astro-frontmatter-syntax-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Unexpected end of frontmatter'); - }); - - it('runtime error', async () => { - const res = await fixture.fetch('/astro-runtime-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('ReferenceError: title is not defined'); - - // TODO: improve and test stacktrace - }); - - it('hydration error', async () => { - const res = await fixture.fetch('/astro-hydration-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Error: invalid hydration directive'); - }); - - it('client:media error', async () => { - const res = await fixture.fetch('/astro-client-media-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Error: Media query must be provided'); - }); - }); - - describe('JS', () => { - it('syntax error', async () => { - const res = await fixture.fetch('/js-syntax-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Parse failure'); - }); - - it('runtime error', async () => { - const res = await fixture.fetch('/js-runtime-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('ReferenceError: undefinedvar is not defined'); - }); - }); - - describe('Preact', () => { - it('syntax error', async () => { - const res = await fixture.fetch('/preact-syntax-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Syntax error'); - }); - - it('runtime error', async () => { - const res = await fixture.fetch('/preact-runtime-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Error: PreactRuntimeError'); - }); - }); - - describe('React', () => { - it('syntax error', async () => { - const res = await fixture.fetch('/react-syntax-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Syntax error'); - }); - - it('runtime error', async () => { - const res = await fixture.fetch('/react-runtime-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Error: ReactRuntimeError'); - }); - }); - - describe('Solid', () => { - it('syntax error', async () => { - const res = await fixture.fetch('/solid-syntax-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Syntax error'); - }); - - it('runtime error', async () => { - const res = await fixture.fetch('/solid-runtime-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Error: SolidRuntimeError'); - }); - }); - - describe('Svelte', () => { - it('syntax error', async () => { - const res = await fixture.fetch('/svelte-syntax-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Internal Error'); - }); - - it('runtime error', async () => { - const res = await fixture.fetch('/svelte-runtime-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.include('Error: SvelteRuntimeError'); - }); - }); - - describe('Vue', () => { - it('syntax error', async () => { - const res = await fixture.fetch('/vue-syntax-error'); - const body = await res.text(); - - expect(res.status).to.equal(500); - expect(body).to.include('Parse failure'); - }); - - it('runtime error', async () => { - const res = await fixture.fetch('/vue-runtime-error'); - - expect(res.status).to.equal(500); - - const body = await res.text(); - - expect(body).to.match(/Cannot read.*undefined/); // note: error differs slightly between Node versions + it('properly detect syntax errors in template', async () => { + try { + devServer = await fixture.startDevServer(); + } catch (err) { + return; + } + await devServer.stop(); + throw new Error('Expected to throw on startup'); }); }); }); diff --git a/packages/astro/test/fixtures/0-css/astro.config.mjs b/packages/astro/test/fixtures/0-css/astro.config.mjs new file mode 100644 index 000000000..c888fce93 --- /dev/null +++ b/packages/astro/test/fixtures/0-css/astro.config.mjs @@ -0,0 +1,15 @@ +import { defineConfig } from 'astro/config'; +import react from '@astrojs/react'; +import svelte from '@astrojs/svelte'; +import vue from '@astrojs/vue'; + +// https://astro.build/config +export default defineConfig({ + integrations: [react(), svelte(), vue()], + vite: { + build: { + assetsInlineLimit: 0, + }, + }, +}); + diff --git a/packages/astro/test/fixtures/0-css/package.json b/packages/astro/test/fixtures/0-css/package.json index 9a6b790a7..81a208109 100644 --- a/packages/astro/test/fixtures/0-css/package.json +++ b/packages/astro/test/fixtures/0-css/package.json @@ -3,6 +3,9 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/react": "workspace:*", + "@astrojs/svelte": "workspace:*", + "@astrojs/vue": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/astro-assets/astro.config.mjs b/packages/astro/test/fixtures/astro-assets/astro.config.mjs new file mode 100644 index 000000000..49ead6913 --- /dev/null +++ b/packages/astro/test/fixtures/astro-assets/astro.config.mjs @@ -0,0 +1,11 @@ +import { defineConfig } from 'astro/config'; + +// https://astro.build/config +export default defineConfig({ + vite: { + build: { + assetsInlineLimit: 0, + }, + }, +}); + diff --git a/packages/astro/test/fixtures/astro-attrs/astro.config.mjs b/packages/astro/test/fixtures/astro-attrs/astro.config.mjs new file mode 100644 index 000000000..8a6f1951c --- /dev/null +++ b/packages/astro/test/fixtures/astro-attrs/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import react from '@astrojs/react'; + +// https://astro.build/config +export default defineConfig({ + integrations: [react()], +}); diff --git a/packages/astro/test/fixtures/astro-attrs/package.json b/packages/astro/test/fixtures/astro-attrs/package.json index bc0a1ad19..bbf4131d9 100644 --- a/packages/astro/test/fixtures/astro-attrs/package.json +++ b/packages/astro/test/fixtures/astro-attrs/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/react": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/astro-basic/astro.config.mjs b/packages/astro/test/fixtures/astro-basic/astro.config.mjs new file mode 100644 index 000000000..08916b1fe --- /dev/null +++ b/packages/astro/test/fixtures/astro-basic/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; + +// https://astro.build/config +export default defineConfig({ + integrations: [preact()], +}); diff --git a/packages/astro/test/fixtures/astro-basic/package.json b/packages/astro/test/fixtures/astro-basic/package.json index 13d2b3681..f9aba8565 100644 --- a/packages/astro/test/fixtures/astro-basic/package.json +++ b/packages/astro/test/fixtures/astro-basic/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/preact": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/astro-children/astro.config.mjs b/packages/astro/test/fixtures/astro-children/astro.config.mjs new file mode 100644 index 000000000..26e1a83d5 --- /dev/null +++ b/packages/astro/test/fixtures/astro-children/astro.config.mjs @@ -0,0 +1,9 @@ +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; +import vue from '@astrojs/vue'; +import svelte from '@astrojs/svelte'; + +// https://astro.build/config +export default defineConfig({ + integrations: [preact(), vue(), svelte()], +}); diff --git a/packages/astro/test/fixtures/astro-children/package.json b/packages/astro/test/fixtures/astro-children/package.json index 9077a9ead..2b1ccec4c 100644 --- a/packages/astro/test/fixtures/astro-children/package.json +++ b/packages/astro/test/fixtures/astro-children/package.json @@ -3,6 +3,9 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/preact": "workspace:*", + "@astrojs/svelte": "workspace:*", + "@astrojs/vue": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/astro-client-only/astro.config.mjs b/packages/astro/test/fixtures/astro-client-only/astro.config.mjs new file mode 100644 index 000000000..77fdcd1b9 --- /dev/null +++ b/packages/astro/test/fixtures/astro-client-only/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import svelte from '@astrojs/svelte'; + +// https://astro.build/config +export default defineConfig({ + integrations: [svelte()], +}); diff --git a/packages/astro/test/fixtures/astro-client-only/package.json b/packages/astro/test/fixtures/astro-client-only/package.json index 6af00f0eb..038e6f99d 100644 --- a/packages/astro/test/fixtures/astro-client-only/package.json +++ b/packages/astro/test/fixtures/astro-client-only/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/svelte": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/astro-dynamic/astro.config.mjs b/packages/astro/test/fixtures/astro-dynamic/astro.config.mjs new file mode 100644 index 000000000..79ace5a25 --- /dev/null +++ b/packages/astro/test/fixtures/astro-dynamic/astro.config.mjs @@ -0,0 +1,8 @@ +import { defineConfig } from 'astro/config'; +import react from '@astrojs/react'; +import svelte from '@astrojs/svelte'; + +// https://astro.build/config +export default defineConfig({ + integrations: [react(), svelte()], +}); diff --git a/packages/astro/test/fixtures/astro-dynamic/package.json b/packages/astro/test/fixtures/astro-dynamic/package.json index a4db91841..7a675b3ef 100644 --- a/packages/astro/test/fixtures/astro-dynamic/package.json +++ b/packages/astro/test/fixtures/astro-dynamic/package.json @@ -3,6 +3,8 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/react": "workspace:*", + "@astrojs/svelte": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/astro-envs/astro.config.mjs b/packages/astro/test/fixtures/astro-envs/astro.config.mjs new file mode 100644 index 000000000..881930612 --- /dev/null +++ b/packages/astro/test/fixtures/astro-envs/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import vue from '@astrojs/vue'; + +// https://astro.build/config +export default defineConfig({ + integrations: [vue()], +}); diff --git a/packages/astro/test/fixtures/astro-envs/package.json b/packages/astro/test/fixtures/astro-envs/package.json index d7fec4401..4309d0833 100644 --- a/packages/astro/test/fixtures/astro-envs/package.json +++ b/packages/astro/test/fixtures/astro-envs/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/vue": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/astro-expr/astro.config.mjs b/packages/astro/test/fixtures/astro-expr/astro.config.mjs new file mode 100644 index 000000000..08916b1fe --- /dev/null +++ b/packages/astro/test/fixtures/astro-expr/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; + +// https://astro.build/config +export default defineConfig({ + integrations: [preact()], +}); diff --git a/packages/astro/test/fixtures/astro-expr/package.json b/packages/astro/test/fixtures/astro-expr/package.json index 747c37d6a..491e6cdaf 100644 --- a/packages/astro/test/fixtures/astro-expr/package.json +++ b/packages/astro/test/fixtures/astro-expr/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/preact": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/astro-fallback/astro.config.mjs b/packages/astro/test/fixtures/astro-fallback/astro.config.mjs new file mode 100644 index 000000000..08916b1fe --- /dev/null +++ b/packages/astro/test/fixtures/astro-fallback/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; + +// https://astro.build/config +export default defineConfig({ + integrations: [preact()], +}); diff --git a/packages/astro/test/fixtures/astro-fallback/package.json b/packages/astro/test/fixtures/astro-fallback/package.json index 59c27e5ca..71b110f11 100644 --- a/packages/astro/test/fixtures/astro-fallback/package.json +++ b/packages/astro/test/fixtures/astro-fallback/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/preact": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/astro-markdown-plugins/astro.config.mjs b/packages/astro/test/fixtures/astro-markdown-plugins/astro.config.mjs new file mode 100644 index 000000000..08916b1fe --- /dev/null +++ b/packages/astro/test/fixtures/astro-markdown-plugins/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; + +// https://astro.build/config +export default defineConfig({ + integrations: [preact()], +}); diff --git a/packages/astro/test/fixtures/astro-markdown-plugins/package.json b/packages/astro/test/fixtures/astro-markdown-plugins/package.json index d1552ff90..d6f815c19 100644 --- a/packages/astro/test/fixtures/astro-markdown-plugins/package.json +++ b/packages/astro/test/fixtures/astro-markdown-plugins/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/preact": "workspace:*", "astro": "workspace:*", "hast-util-select": "^5.0.1" } diff --git a/packages/astro/test/fixtures/astro-markdown/astro.config.mjs b/packages/astro/test/fixtures/astro-markdown/astro.config.mjs new file mode 100644 index 000000000..680c77bdb --- /dev/null +++ b/packages/astro/test/fixtures/astro-markdown/astro.config.mjs @@ -0,0 +1,10 @@ +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; + +// https://astro.build/config +export default defineConfig({ + integrations: [preact()], + buildOptions: { + sitemap: false, + }, +}); diff --git a/packages/astro/test/fixtures/astro-markdown/package.json b/packages/astro/test/fixtures/astro-markdown/package.json index 9fe9dae01..bf24faecd 100644 --- a/packages/astro/test/fixtures/astro-markdown/package.json +++ b/packages/astro/test/fixtures/astro-markdown/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/preact": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/astro-partial-html/astro.config.mjs b/packages/astro/test/fixtures/astro-partial-html/astro.config.mjs new file mode 100644 index 000000000..8a6f1951c --- /dev/null +++ b/packages/astro/test/fixtures/astro-partial-html/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import react from '@astrojs/react'; + +// https://astro.build/config +export default defineConfig({ + integrations: [react()], +}); diff --git a/packages/astro/test/fixtures/astro-partial-html/package.json b/packages/astro/test/fixtures/astro-partial-html/package.json index 90784b6c9..55dce70b9 100644 --- a/packages/astro/test/fixtures/astro-partial-html/package.json +++ b/packages/astro/test/fixtures/astro-partial-html/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/react": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/config-host/astro.config.mjs b/packages/astro/test/fixtures/config-host/astro.config.mjs deleted file mode 100644 index 5dceb4a1f..000000000 --- a/packages/astro/test/fixtures/config-host/astro.config.mjs +++ /dev/null @@ -1,6 +0,0 @@ - -export default { - devOptions: { - host: true - } -} diff --git a/packages/astro/test/fixtures/config-hostname/astro.config.mjs b/packages/astro/test/fixtures/config-hostname/astro.config.mjs deleted file mode 100644 index e1e33ea0a..000000000 --- a/packages/astro/test/fixtures/config-hostname/astro.config.mjs +++ /dev/null @@ -1,6 +0,0 @@ - -export default { - devOptions: { - hostname: '0.0.0.0' - } -} diff --git a/packages/astro/test/fixtures/config-hostname/package.json b/packages/astro/test/fixtures/config-hostname/package.json deleted file mode 100644 index c21fdec44..000000000 --- a/packages/astro/test/fixtures/config-hostname/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "@test/config-hostname", - "version": "0.0.0", - "private": true, - "dependencies": { - "astro": "workspace:*" - } -} diff --git a/packages/astro/test/fixtures/config-port/astro.config.mjs b/packages/astro/test/fixtures/config-port/astro.config.mjs deleted file mode 100644 index fc3fa2e49..000000000 --- a/packages/astro/test/fixtures/config-port/astro.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -export default { - devOptions: { - port: 5006 - } -} diff --git a/packages/astro/test/fixtures/config-port/package.json b/packages/astro/test/fixtures/config-port/package.json deleted file mode 100644 index cb802148b..000000000 --- a/packages/astro/test/fixtures/config-port/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "@test/config-port", - "version": "0.0.0", - "private": true, - "dependencies": { - "astro": "workspace:*" - } -} diff --git a/packages/astro/test/fixtures/errors/astro.config.mjs b/packages/astro/test/fixtures/errors/astro.config.mjs new file mode 100644 index 000000000..8f27d8fab --- /dev/null +++ b/packages/astro/test/fixtures/errors/astro.config.mjs @@ -0,0 +1,11 @@ +import { defineConfig } from 'astro/config'; +import react from '@astrojs/react'; +import preact from '@astrojs/preact'; +import solid from '@astrojs/solid-js'; +import svelte from '@astrojs/svelte'; +import vue from '@astrojs/vue'; + +// https://astro.build/config +export default defineConfig({ + integrations: [react(), preact(), solid(), svelte(), vue()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/errors/package.json b/packages/astro/test/fixtures/errors/package.json index 5f54a7d9e..54d388f16 100644 --- a/packages/astro/test/fixtures/errors/package.json +++ b/packages/astro/test/fixtures/errors/package.json @@ -3,7 +3,11 @@ "version": "0.0.0", "private": true, "dependencies": { - "astro": "workspace:*", - "@astrojs/renderer-solid": "workspace:*" + "@astrojs/react": "workspace:*", + "@astrojs/preact": "workspace:*", + "@astrojs/solid-js": "workspace:*", + "@astrojs/svelte": "workspace:*", + "@astrojs/vue": "workspace:*", + "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/fetch/astro.config.mjs b/packages/astro/test/fixtures/fetch/astro.config.mjs new file mode 100644 index 000000000..92bd62f2b --- /dev/null +++ b/packages/astro/test/fixtures/fetch/astro.config.mjs @@ -0,0 +1,10 @@ +import { defineConfig } from 'astro/config'; + +import preact from '@astrojs/preact'; +import svelte from '@astrojs/svelte'; +import vue from '@astrojs/vue'; + +// https://astro.build/config +export default defineConfig({ + integrations: [preact(), svelte(), vue()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/fetch/package.json b/packages/astro/test/fixtures/fetch/package.json index 8462f2ab5..7527db97a 100644 --- a/packages/astro/test/fixtures/fetch/package.json +++ b/packages/astro/test/fixtures/fetch/package.json @@ -3,6 +3,9 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/preact": "workspace:*", + "@astrojs/svelte": "workspace:*", + "@astrojs/vue": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/legacy-build/astro.config.mjs b/packages/astro/test/fixtures/legacy-build/astro.config.mjs index 72cd77587..8a3a38574 100644 --- a/packages/astro/test/fixtures/legacy-build/astro.config.mjs +++ b/packages/astro/test/fixtures/legacy-build/astro.config.mjs @@ -1,4 +1,7 @@ -// @ts-check -export default /** @type {import('astro').AstroUserConfig} */ ({ - renderers: ['@astrojs/renderer-vue'], -}); +import { defineConfig } from 'astro/config'; +import vue from '@astrojs/vue'; + +// https://astro.build/config +export default defineConfig({ + integrations: [vue()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/legacy-build/package.json b/packages/astro/test/fixtures/legacy-build/package.json index 24cda0b55..7708f918a 100644 --- a/packages/astro/test/fixtures/legacy-build/package.json +++ b/packages/astro/test/fixtures/legacy-build/package.json @@ -3,7 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { - "@astrojs/renderer-vue": "^0.4.0", + "@astrojs/vue": "workspace:*", "astro": "workspace:*", "preact": "~10.6.6" } diff --git a/packages/astro/test/fixtures/lit-element/astro.config.mjs b/packages/astro/test/fixtures/lit-element/astro.config.mjs new file mode 100644 index 000000000..5512041b8 --- /dev/null +++ b/packages/astro/test/fixtures/lit-element/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import lit from '@astrojs/lit'; + +// https://astro.build/config +export default defineConfig({ + integrations: [lit()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/lit-element/package.json b/packages/astro/test/fixtures/lit-element/package.json index 6903aa872..cfd45e9dc 100644 --- a/packages/astro/test/fixtures/lit-element/package.json +++ b/packages/astro/test/fixtures/lit-element/package.json @@ -3,7 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { - "astro": "workspace:*", - "@astrojs/renderer-lit": "workspace:*" + "@astrojs/lit": "workspace:*", + "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/markdown/astro.config.mjs b/packages/astro/test/fixtures/markdown/astro.config.mjs new file mode 100644 index 000000000..b4ba9c918 --- /dev/null +++ b/packages/astro/test/fixtures/markdown/astro.config.mjs @@ -0,0 +1,10 @@ +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; + +// https://astro.build/config +export default defineConfig({ + buildOptions: { + sitemap: false, + }, + integrations: [preact()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/markdown/package.json b/packages/astro/test/fixtures/markdown/package.json index 1cc75ef8f..d8934dd1d 100644 --- a/packages/astro/test/fixtures/markdown/package.json +++ b/packages/astro/test/fixtures/markdown/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/preact": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/postcss/astro.config.mjs b/packages/astro/test/fixtures/postcss/astro.config.mjs new file mode 100644 index 000000000..9bcd0bd7b --- /dev/null +++ b/packages/astro/test/fixtures/postcss/astro.config.mjs @@ -0,0 +1,9 @@ +import { defineConfig } from 'astro/config'; +import solid from '@astrojs/solid-js'; +import svelte from '@astrojs/svelte'; +import vue from '@astrojs/vue'; + +// https://astro.build/config +export default defineConfig({ + integrations: [solid(), svelte(), vue()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/postcss/package.json b/packages/astro/test/fixtures/postcss/package.json index 32ddab78c..797be3b24 100644 --- a/packages/astro/test/fixtures/postcss/package.json +++ b/packages/astro/test/fixtures/postcss/package.json @@ -3,7 +3,9 @@ "version": "0.0.0", "private": true, "dependencies": { - "@astrojs/renderer-solid": "workspace:*", + "@astrojs/solid-js": "workspace:*", + "@astrojs/svelte": "workspace:*", + "@astrojs/vue": "workspace:*", "astro": "workspace:*", "autoprefixer": "^10.4.4", "postcss": "^8.4.12" diff --git a/packages/astro/test/fixtures/preact-component/astro.config.mjs b/packages/astro/test/fixtures/preact-component/astro.config.mjs new file mode 100644 index 000000000..cd324a40f --- /dev/null +++ b/packages/astro/test/fixtures/preact-component/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; + +// https://astro.build/config +export default defineConfig({ + integrations: [preact()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/preact-component/package.json b/packages/astro/test/fixtures/preact-component/package.json index 2381a25d0..a95de2de8 100644 --- a/packages/astro/test/fixtures/preact-component/package.json +++ b/packages/astro/test/fixtures/preact-component/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/preact": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/react-component/astro.config.mjs b/packages/astro/test/fixtures/react-component/astro.config.mjs new file mode 100644 index 000000000..53d0bd03b --- /dev/null +++ b/packages/astro/test/fixtures/react-component/astro.config.mjs @@ -0,0 +1,8 @@ +import { defineConfig } from 'astro/config'; +import react from '@astrojs/react'; +import vue from '@astrojs/vue'; + +// https://astro.build/config +export default defineConfig({ + integrations: [react(), vue()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/react-component/package.json b/packages/astro/test/fixtures/react-component/package.json index c6d8b4226..020549b3f 100644 --- a/packages/astro/test/fixtures/react-component/package.json +++ b/packages/astro/test/fixtures/react-component/package.json @@ -3,6 +3,8 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/react": "workspace:*", + "@astrojs/vue": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/slots-preact/astro.config.mjs b/packages/astro/test/fixtures/slots-preact/astro.config.mjs new file mode 100644 index 000000000..cd324a40f --- /dev/null +++ b/packages/astro/test/fixtures/slots-preact/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; + +// https://astro.build/config +export default defineConfig({ + integrations: [preact()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/slots-preact/package.json b/packages/astro/test/fixtures/slots-preact/package.json index bb932726a..95f33ee50 100644 --- a/packages/astro/test/fixtures/slots-preact/package.json +++ b/packages/astro/test/fixtures/slots-preact/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/preact": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/slots-react/astro.config.mjs b/packages/astro/test/fixtures/slots-react/astro.config.mjs new file mode 100644 index 000000000..f03a45258 --- /dev/null +++ b/packages/astro/test/fixtures/slots-react/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import react from '@astrojs/react'; + +// https://astro.build/config +export default defineConfig({ + integrations: [react()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/slots-react/package.json b/packages/astro/test/fixtures/slots-react/package.json index 22336bc5e..2cba4ab09 100644 --- a/packages/astro/test/fixtures/slots-react/package.json +++ b/packages/astro/test/fixtures/slots-react/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/react": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/slots-solid/astro.config.mjs b/packages/astro/test/fixtures/slots-solid/astro.config.mjs new file mode 100644 index 000000000..6bc082cce --- /dev/null +++ b/packages/astro/test/fixtures/slots-solid/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import solid from '@astrojs/solid-js'; + +// https://astro.build/config +export default defineConfig({ + integrations: [solid()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/slots-solid/package.json b/packages/astro/test/fixtures/slots-solid/package.json index dafbef6a5..e378bd772 100644 --- a/packages/astro/test/fixtures/slots-solid/package.json +++ b/packages/astro/test/fixtures/slots-solid/package.json @@ -3,7 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { - "astro": "workspace:*", - "@astrojs/renderer-solid": "workspace:*" + "@astrojs/solid-js": "workspace:*", + "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/slots-svelte/astro.config.mjs b/packages/astro/test/fixtures/slots-svelte/astro.config.mjs new file mode 100644 index 000000000..dbf6d6b8f --- /dev/null +++ b/packages/astro/test/fixtures/slots-svelte/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import svelte from '@astrojs/svelte'; + +// https://astro.build/config +export default defineConfig({ + integrations: [svelte()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/slots-svelte/package.json b/packages/astro/test/fixtures/slots-svelte/package.json index 918fff501..53af8ea93 100644 --- a/packages/astro/test/fixtures/slots-svelte/package.json +++ b/packages/astro/test/fixtures/slots-svelte/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/svelte": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/slots-vue/astro.config.mjs b/packages/astro/test/fixtures/slots-vue/astro.config.mjs new file mode 100644 index 000000000..8a3a38574 --- /dev/null +++ b/packages/astro/test/fixtures/slots-vue/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import vue from '@astrojs/vue'; + +// https://astro.build/config +export default defineConfig({ + integrations: [vue()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/slots-vue/package.json b/packages/astro/test/fixtures/slots-vue/package.json index 47e015cd9..f6d90b40d 100644 --- a/packages/astro/test/fixtures/slots-vue/package.json +++ b/packages/astro/test/fixtures/slots-vue/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/vue": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/solid-component/astro.config.mjs b/packages/astro/test/fixtures/solid-component/astro.config.mjs new file mode 100644 index 000000000..6bc082cce --- /dev/null +++ b/packages/astro/test/fixtures/solid-component/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import solid from '@astrojs/solid-js'; + +// https://astro.build/config +export default defineConfig({ + integrations: [solid()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/solid-component/package.json b/packages/astro/test/fixtures/solid-component/package.json index a6d06e8ec..93148abca 100644 --- a/packages/astro/test/fixtures/solid-component/package.json +++ b/packages/astro/test/fixtures/solid-component/package.json @@ -3,7 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { - "astro": "workspace:*", - "@astrojs/renderer-solid": "workspace:*" + "@astrojs/solid-js": "workspace:*", + "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/static build/astro.config.mjs b/packages/astro/test/fixtures/static build/astro.config.mjs new file mode 100644 index 000000000..32807d063 --- /dev/null +++ b/packages/astro/test/fixtures/static build/astro.config.mjs @@ -0,0 +1,13 @@ +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; + +// https://astro.build/config +export default defineConfig({ + integrations: [preact()], + buildOptions: { + site: 'http://example.com/subpath/', + }, + ssr: { + noExternal: ['@test/static-build-pkg'], + }, +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/static build/package.json b/packages/astro/test/fixtures/static build/package.json index aa5623cdb..5796987a3 100644 --- a/packages/astro/test/fixtures/static build/package.json +++ b/packages/astro/test/fixtures/static build/package.json @@ -2,6 +2,7 @@ "name": "@test/static-build", "version": "0.0.0", "dependencies": { + "@astrojs/preact": "workspace:*", "@test/static-build-pkg": "workspace:*", "astro": "workspace:*" } diff --git a/packages/astro/test/fixtures/static-build-frameworks/astro.config.mjs b/packages/astro/test/fixtures/static-build-frameworks/astro.config.mjs new file mode 100644 index 000000000..d0859e214 --- /dev/null +++ b/packages/astro/test/fixtures/static-build-frameworks/astro.config.mjs @@ -0,0 +1,8 @@ +import { defineConfig } from 'astro/config'; +import react from '@astrojs/react'; +import preact from '@astrojs/preact'; + +// https://astro.build/config +export default defineConfig({ + integrations: [react(), preact()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/static-build-frameworks/package.json b/packages/astro/test/fixtures/static-build-frameworks/package.json index ab6261219..d6157074e 100644 --- a/packages/astro/test/fixtures/static-build-frameworks/package.json +++ b/packages/astro/test/fixtures/static-build-frameworks/package.json @@ -3,6 +3,8 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/react": "workspace:*", + "@astrojs/preact": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/static-build-page-url-format/astro.config.mjs b/packages/astro/test/fixtures/static-build-page-url-format/astro.config.mjs new file mode 100644 index 000000000..7c6e98cc0 --- /dev/null +++ b/packages/astro/test/fixtures/static-build-page-url-format/astro.config.mjs @@ -0,0 +1,9 @@ +import { defineConfig } from 'astro/config'; + +// https://astro.build/config +export default defineConfig({ + buildOptions: { + site: 'http://example.com/subpath/', + pageUrlFormat: 'file', + }, +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/svelte-component/astro.config.mjs b/packages/astro/test/fixtures/svelte-component/astro.config.mjs new file mode 100644 index 000000000..dbf6d6b8f --- /dev/null +++ b/packages/astro/test/fixtures/svelte-component/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import svelte from '@astrojs/svelte'; + +// https://astro.build/config +export default defineConfig({ + integrations: [svelte()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/svelte-component/package.json b/packages/astro/test/fixtures/svelte-component/package.json index 3b21caf45..e3d625aad 100644 --- a/packages/astro/test/fixtures/svelte-component/package.json +++ b/packages/astro/test/fixtures/svelte-component/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/svelte": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/tailwindcss/astro.config.mjs b/packages/astro/test/fixtures/tailwindcss/astro.config.mjs new file mode 100644 index 000000000..c3f6aad6f --- /dev/null +++ b/packages/astro/test/fixtures/tailwindcss/astro.config.mjs @@ -0,0 +1,12 @@ +import { defineConfig } from 'astro/config'; +import tailwind from '@astrojs/tailwind'; + +// https://astro.build/config +export default defineConfig({ + integrations: [tailwind()], + vite: { + build: { + assetsInlineLimit: 0, + }, + }, +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/tailwindcss/package.json b/packages/astro/test/fixtures/tailwindcss/package.json index fff7196df..6cadfb8c6 100644 --- a/packages/astro/test/fixtures/tailwindcss/package.json +++ b/packages/astro/test/fixtures/tailwindcss/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/tailwind": "workspace:*", "astro": "workspace:*", "autoprefixer": "^10.4.4", "postcss": "^8.4.12", diff --git a/packages/astro/test/fixtures/vue-component/astro.config.mjs b/packages/astro/test/fixtures/vue-component/astro.config.mjs new file mode 100644 index 000000000..8a3a38574 --- /dev/null +++ b/packages/astro/test/fixtures/vue-component/astro.config.mjs @@ -0,0 +1,7 @@ +import { defineConfig } from 'astro/config'; +import vue from '@astrojs/vue'; + +// https://astro.build/config +export default defineConfig({ + integrations: [vue()], +});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/vue-component/package.json b/packages/astro/test/fixtures/vue-component/package.json index 97a889dfa..2322b5d2d 100644 --- a/packages/astro/test/fixtures/vue-component/package.json +++ b/packages/astro/test/fixtures/vue-component/package.json @@ -3,6 +3,7 @@ "version": "0.0.0", "private": true, "dependencies": { + "@astrojs/vue": "workspace:*", "astro": "workspace:*" } } diff --git a/packages/astro/test/fixtures/with-endpoint-routes/astro.config.mjs b/packages/astro/test/fixtures/with-endpoint-routes/astro.config.mjs deleted file mode 100644 index 7ac59b341..000000000 --- a/packages/astro/test/fixtures/with-endpoint-routes/astro.config.mjs +++ /dev/null @@ -1,6 +0,0 @@ - -export default { - buildOptions: { - site: 'http://example.com/' - } -}
\ No newline at end of file diff --git a/packages/astro/test/fixtures/with-subpath-trailing-slash/astro.config.mjs b/packages/astro/test/fixtures/with-subpath-trailing-slash/astro.config.mjs deleted file mode 100644 index 5f2ab2688..000000000 --- a/packages/astro/test/fixtures/with-subpath-trailing-slash/astro.config.mjs +++ /dev/null @@ -1,6 +0,0 @@ - -export default { - buildOptions: { - site: 'http://example.com/blog/' - } -}
\ No newline at end of file diff --git a/packages/astro/test/fixtures/with-subpath-trailing-slash/package.json b/packages/astro/test/fixtures/with-subpath-trailing-slash/package.json deleted file mode 100644 index 1d1128ada..000000000 --- a/packages/astro/test/fixtures/with-subpath-trailing-slash/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "@test/with-subpath-trailing-slash", - "version": "0.0.0", - "private": true, - "dependencies": { - "astro": "workspace:*" - } -} diff --git a/packages/astro/test/fixtures/with-subpath-trailing-slash/src/pages/[id].astro b/packages/astro/test/fixtures/with-subpath-trailing-slash/src/pages/[id].astro deleted file mode 100644 index b5dbc4307..000000000 --- a/packages/astro/test/fixtures/with-subpath-trailing-slash/src/pages/[id].astro +++ /dev/null @@ -1,6 +0,0 @@ ---- -export function getStaticPaths() { - return [{ params: { id: '1' } }]; -} ---- -<h1>Post #1</h1> diff --git a/packages/astro/test/fixtures/with-subpath-trailing-slash/src/pages/another.astro b/packages/astro/test/fixtures/with-subpath-trailing-slash/src/pages/another.astro deleted file mode 100644 index d0563f414..000000000 --- a/packages/astro/test/fixtures/with-subpath-trailing-slash/src/pages/another.astro +++ /dev/null @@ -1 +0,0 @@ -<div>another page</div>
\ No newline at end of file diff --git a/packages/astro/test/fixtures/with-subpath-trailing-slash/src/pages/index.astro b/packages/astro/test/fixtures/with-subpath-trailing-slash/src/pages/index.astro deleted file mode 100644 index 8dca56dd8..000000000 --- a/packages/astro/test/fixtures/with-subpath-trailing-slash/src/pages/index.astro +++ /dev/null @@ -1 +0,0 @@ -<div>Hello world</div>
\ No newline at end of file diff --git a/packages/astro/test/fixtures/without-subpath/astro.config.mjs b/packages/astro/test/fixtures/without-subpath/astro.config.mjs deleted file mode 100644 index 7ac59b341..000000000 --- a/packages/astro/test/fixtures/without-subpath/astro.config.mjs +++ /dev/null @@ -1,6 +0,0 @@ - -export default { - buildOptions: { - site: 'http://example.com/' - } -}
\ No newline at end of file diff --git a/packages/astro/test/fixtures/without-subpath/package.json b/packages/astro/test/fixtures/without-subpath/package.json deleted file mode 100644 index de2cc4f98..000000000 --- a/packages/astro/test/fixtures/without-subpath/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "name": "@test/without-subpath", - "version": "0.0.0", - "private": true, - "dependencies": { - "astro": "workspace:*" - } -} diff --git a/packages/astro/test/fixtures/without-subpath/src/pages/[id].astro b/packages/astro/test/fixtures/without-subpath/src/pages/[id].astro deleted file mode 100644 index b5dbc4307..000000000 --- a/packages/astro/test/fixtures/without-subpath/src/pages/[id].astro +++ /dev/null @@ -1,6 +0,0 @@ ---- -export function getStaticPaths() { - return [{ params: { id: '1' } }]; -} ---- -<h1>Post #1</h1> diff --git a/packages/astro/test/fixtures/without-subpath/src/pages/another.astro b/packages/astro/test/fixtures/without-subpath/src/pages/another.astro deleted file mode 100644 index d0563f414..000000000 --- a/packages/astro/test/fixtures/without-subpath/src/pages/another.astro +++ /dev/null @@ -1 +0,0 @@ -<div>another page</div>
\ No newline at end of file diff --git a/packages/astro/test/fixtures/without-subpath/src/pages/index.astro b/packages/astro/test/fixtures/without-subpath/src/pages/index.astro deleted file mode 100644 index 42e6a5177..000000000 --- a/packages/astro/test/fixtures/without-subpath/src/pages/index.astro +++ /dev/null @@ -1 +0,0 @@ -<div>testing</div>
\ No newline at end of file diff --git a/packages/astro/test/lit-element.test.js b/packages/astro/test/lit-element.test.js index a341499a9..65f1a01fb 100644 --- a/packages/astro/test/lit-element.test.js +++ b/packages/astro/test/lit-element.test.js @@ -17,7 +17,6 @@ describe('LitElement test', function () { } fixture = await loadFixture({ projectRoot: './fixtures/lit-element/', - renderers: ['@astrojs/renderer-lit'], }); await fixture.build(); }); diff --git a/packages/astro/test/markdown.test.js b/packages/astro/test/markdown.test.js index db0ed8a4e..5d4fdefda 100644 --- a/packages/astro/test/markdown.test.js +++ b/packages/astro/test/markdown.test.js @@ -8,10 +8,6 @@ describe('Markdown tests', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/markdown/', - buildOptions: { - sitemap: false, - }, - renderers: ['@astrojs/renderer-preact'], }); await fixture.build(); }); diff --git a/packages/astro/test/postcss.test.js b/packages/astro/test/postcss.test.js index 862d37c2f..c60cf772f 100644 --- a/packages/astro/test/postcss.test.js +++ b/packages/astro/test/postcss.test.js @@ -11,7 +11,6 @@ describe('PostCSS', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/postcss', - renderers: ['@astrojs/renderer-solid', '@astrojs/renderer-svelte', '@astrojs/renderer-vue'], }); await fixture.build(); diff --git a/packages/astro/test/preact-component.test.js b/packages/astro/test/preact-component.test.js index 10d482072..e6e018068 100644 --- a/packages/astro/test/preact-component.test.js +++ b/packages/astro/test/preact-component.test.js @@ -7,11 +7,7 @@ describe('Preact component', () => { before(async () => { fixture = await loadFixture({ - devOptions: { - port: 3009, - }, projectRoot: './fixtures/preact-component/', - renderers: ['@astrojs/renderer-preact'], }); await fixture.build(); }); diff --git a/packages/astro/test/preview-routing.test.js b/packages/astro/test/preview-routing.test.js index 2f7a17b15..005eeef57 100644 --- a/packages/astro/test/preview-routing.test.js +++ b/packages/astro/test/preview-routing.test.js @@ -71,6 +71,7 @@ describe('Preview Routing', () => { fixture = await loadFixture({ projectRoot: './fixtures/with-subpath-no-trailing-slash/', dist: new URL('./fixtures/with-subpath-no-trailing-slash/dist-4001/', import.meta.url), + buildOptions: {}, devOptions: { trailingSlash: 'always', port: 4001, @@ -129,7 +130,8 @@ describe('Preview Routing', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/with-subpath-no-trailing-slash/', - dist: new URL('./fixtures/with-subpath-no-trailing-slash/dist-4002//', import.meta.url), + dist: new URL('./fixtures/with-subpath-no-trailing-slash/dist-4002/', import.meta.url), + buildOptions: {}, devOptions: { trailingSlash: 'ignore', port: 4002, diff --git a/packages/astro/test/react-component.test.js b/packages/astro/test/react-component.test.js index 8e90f88ae..b1080dc9f 100644 --- a/packages/astro/test/react-component.test.js +++ b/packages/astro/test/react-component.test.js @@ -7,11 +7,7 @@ let fixture; describe('React Components', () => { before(async () => { fixture = await loadFixture({ - devOptions: { - port: 3008, - }, projectRoot: './fixtures/react-component/', - renderers: ['@astrojs/renderer-react', '@astrojs/renderer-vue'], }); }); diff --git a/packages/astro/test/slots-preact.test.js b/packages/astro/test/slots-preact.test.js index a96bcea75..3419dfda6 100644 --- a/packages/astro/test/slots-preact.test.js +++ b/packages/astro/test/slots-preact.test.js @@ -6,7 +6,7 @@ describe('Slots: Preact', () => { let fixture; before(async () => { - fixture = await loadFixture({ projectRoot: './fixtures/slots-preact/', renderers: ['@astrojs/renderer-preact'] }); + fixture = await loadFixture({ projectRoot: './fixtures/slots-preact/' }); await fixture.build(); }); diff --git a/packages/astro/test/slots-react.test.js b/packages/astro/test/slots-react.test.js index 7a4f1863c..1c721c6e2 100644 --- a/packages/astro/test/slots-react.test.js +++ b/packages/astro/test/slots-react.test.js @@ -6,7 +6,7 @@ describe('Slots: React', () => { let fixture; before(async () => { - fixture = await loadFixture({ projectRoot: './fixtures/slots-react/', renderers: ['@astrojs/renderer-react'] }); + fixture = await loadFixture({ projectRoot: './fixtures/slots-react/' }); await fixture.build(); }); diff --git a/packages/astro/test/slots-solid.test.js b/packages/astro/test/slots-solid.test.js index d4f566930..2b45dd5d9 100644 --- a/packages/astro/test/slots-solid.test.js +++ b/packages/astro/test/slots-solid.test.js @@ -6,7 +6,7 @@ describe('Slots: Solid', () => { let fixture; before(async () => { - fixture = await loadFixture({ projectRoot: './fixtures/slots-solid/', renderers: ['@astrojs/renderer-solid'] }); + fixture = await loadFixture({ projectRoot: './fixtures/slots-solid/' }); await fixture.build(); }); diff --git a/packages/astro/test/slots-svelte.test.js b/packages/astro/test/slots-svelte.test.js index 690a61b3d..3a267ccb1 100644 --- a/packages/astro/test/slots-svelte.test.js +++ b/packages/astro/test/slots-svelte.test.js @@ -6,7 +6,7 @@ describe('Slots: Svelte', () => { let fixture; before(async () => { - fixture = await loadFixture({ projectRoot: './fixtures/slots-svelte/', renderers: ['@astrojs/renderer-svelte'] }); + fixture = await loadFixture({ projectRoot: './fixtures/slots-svelte/' }); await fixture.build(); }); diff --git a/packages/astro/test/slots-vue.test.js b/packages/astro/test/slots-vue.test.js index ba76c7cfd..c598d346b 100644 --- a/packages/astro/test/slots-vue.test.js +++ b/packages/astro/test/slots-vue.test.js @@ -6,7 +6,7 @@ describe('Slots: Vue', () => { let fixture; before(async () => { - fixture = await loadFixture({ projectRoot: './fixtures/slots-vue/', renderers: ['@astrojs/renderer-vue'] }); + fixture = await loadFixture({ projectRoot: './fixtures/slots-vue/' }); await fixture.build(); }); diff --git a/packages/astro/test/solid-component.test.js b/packages/astro/test/solid-component.test.js index 2e9f82469..07e01fba0 100644 --- a/packages/astro/test/solid-component.test.js +++ b/packages/astro/test/solid-component.test.js @@ -7,11 +7,7 @@ describe('Solid component', () => { before(async () => { fixture = await loadFixture({ - devOptions: { - port: 3006, - }, projectRoot: './fixtures/solid-component/', - renderers: ['@astrojs/renderer-solid'], }); }); diff --git a/packages/astro/test/static-build-code-component.test.js b/packages/astro/test/static-build-code-component.test.js index 4c712f2ab..ec5e33945 100644 --- a/packages/astro/test/static-build-code-component.test.js +++ b/packages/astro/test/static-build-code-component.test.js @@ -8,8 +8,6 @@ describe('Code component inside static build', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/static-build-code-component/', - renderers: [], - buildOptions: {}, }); await fixture.build(); }); diff --git a/packages/astro/test/static-build-frameworks.test.js b/packages/astro/test/static-build-frameworks.test.js index bea8fb11b..9b6d50028 100644 --- a/packages/astro/test/static-build-frameworks.test.js +++ b/packages/astro/test/static-build-frameworks.test.js @@ -12,8 +12,6 @@ describe('Static build - frameworks', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/static-build-frameworks/', - renderers: ['@astrojs/renderer-preact', '@astrojs/renderer-react'], - buildOptions: {}, }); await fixture.build(); }); diff --git a/packages/astro/test/static-build-page-url-format.test.js b/packages/astro/test/static-build-page-url-format.test.js index 6f43a441b..4a21419cc 100644 --- a/packages/astro/test/static-build-page-url-format.test.js +++ b/packages/astro/test/static-build-page-url-format.test.js @@ -12,11 +12,6 @@ describe("Static build - pageUrlFormat: 'file'", () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/static-build-page-url-format/', - renderers: [], - buildOptions: { - site: 'http://example.com/subpath/', - pageUrlFormat: 'file', - }, }); await fixture.build(); }); diff --git a/packages/astro/test/static-build.test.js b/packages/astro/test/static-build.test.js index 310c41648..0f04724ca 100644 --- a/packages/astro/test/static-build.test.js +++ b/packages/astro/test/static-build.test.js @@ -12,13 +12,6 @@ describe('Static build', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/static build/', - renderers: ['@astrojs/renderer-preact'], - buildOptions: { - site: 'http://example.com/subpath/', - }, - ssr: { - noExternal: ['@test/static-build-pkg'], - }, }); await fixture.build(); }); diff --git a/packages/astro/test/svelte-component.test.js b/packages/astro/test/svelte-component.test.js index 61f03663f..c088bf9b5 100644 --- a/packages/astro/test/svelte-component.test.js +++ b/packages/astro/test/svelte-component.test.js @@ -7,11 +7,7 @@ describe('Svelte component', () => { before(async () => { fixture = await loadFixture({ - devOptions: { - port: 3007, - }, projectRoot: './fixtures/svelte-component/', - renderers: ['@astrojs/renderer-svelte'], }); }); diff --git a/packages/astro/test/tailwindcss.test.js b/packages/astro/test/tailwindcss.test.js index 93516b8cf..2b5d202d4 100644 --- a/packages/astro/test/tailwindcss.test.js +++ b/packages/astro/test/tailwindcss.test.js @@ -10,12 +10,6 @@ describe('Tailwind', () => { before(async () => { fixture = await loadFixture({ projectRoot: './fixtures/tailwindcss/', - renderers: [], - vite: { - build: { - assetsInlineLimit: 0, - }, - }, }); }); @@ -84,7 +78,6 @@ describe('Tailwind', () => { expect(res.status).to.equal(200); const text = await res.text(); - expect(text, 'includes used component classes').to.match(/\.bg-purple-600/); // tests a random tailwind class that isn't used on the page diff --git a/packages/astro/test/test-utils.js b/packages/astro/test/test-utils.js index 494047ae3..004f75b66 100644 --- a/packages/astro/test/test-utils.js +++ b/packages/astro/test/test-utils.js @@ -2,7 +2,7 @@ import { execa } from 'execa'; import { polyfill } from '@astrojs/webapi'; import fs from 'fs'; import { fileURLToPath } from 'url'; -import { loadConfig } from '../dist/core/config.js'; +import { resolveConfig, loadConfig } from '../dist/core/config.js'; import dev from '../dist/core/dev/index.js'; import build from '../dist/core/build/index.js'; import preview from '../dist/core/preview/index.js'; @@ -57,6 +57,7 @@ export async function loadFixture(inlineConfig) { // load config let cwd = inlineConfig.projectRoot; + delete inlineConfig.projectRoot; if (typeof cwd === 'string') { try { cwd = new URL(cwd.replace(/\/?$/, '/')); @@ -64,11 +65,7 @@ export async function loadFixture(inlineConfig) { cwd = new URL(cwd.replace(/\/?$/, '/'), import.meta.url); } } - - // merge configs - if (!inlineConfig.buildOptions) inlineConfig.buildOptions = {}; - if (inlineConfig.buildOptions.sitemap === undefined) inlineConfig.buildOptions.sitemap = false; - if (!inlineConfig.devOptions) inlineConfig.devOptions = {}; + // Load the config. let config = await loadConfig({ cwd: fileURLToPath(cwd) }); config = merge(config, { ...inlineConfig, projectRoot: cwd }); @@ -77,14 +74,12 @@ export async function loadFixture(inlineConfig) { startDevServer: async (opts = {}) => { const devResult = await dev(config, { logging: 'error', ...opts }); config.devOptions.port = devResult.address.port; // update port - inlineConfig.devOptions.port = devResult.address.port; return devResult; }, config, fetch: (url, init) => fetch(`http://${'127.0.0.1'}:${config.devOptions.port}${url.replace(/^\/?/, '/')}`, init), preview: async (opts = {}) => { const previewServer = await preview(config, { logging: 'error', ...opts }); - inlineConfig.devOptions.port = previewServer.port; // update port for fetch return previewServer; }, loadSSRApp: () => loadApp(new URL('./server/', config.dist)), diff --git a/packages/astro/test/vue-component.test.js b/packages/astro/test/vue-component.test.js index 7b226b911..b15f6a759 100644 --- a/packages/astro/test/vue-component.test.js +++ b/packages/astro/test/vue-component.test.js @@ -7,11 +7,7 @@ describe('Vue component', () => { before(async () => { fixture = await loadFixture({ - devOptions: { - port: 3005, - }, projectRoot: './fixtures/vue-component/', - renderers: ['@astrojs/renderer-vue'], }); }); |