Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(next): make defineConfig generic #12243

Merged
merged 21 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/forty-trains-notice.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': minor
---

Improves `defineConfig` type safety. TypeScript will now error if a group of related options do not have coherent types. For example, it will now error if `i18n.defaultLocale` is not one of the locales specified in `i18n.locales`
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
40 changes: 0 additions & 40 deletions packages/astro/config.d.ts

This file was deleted.

16 changes: 0 additions & 16 deletions packages/astro/config.mjs

This file was deleted.

7 changes: 1 addition & 6 deletions packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@
},
"./compiler-runtime": "./dist/runtime/compiler/index.js",
"./runtime/*": "./dist/runtime/*",
"./config": {
"types": "./config.d.ts",
"default": "./config.mjs"
},
"./config": "./dist/config/entrypoint.js",
"./container": {
"types": "./dist/container/index.d.ts",
"default": "./dist/container/index.js"
Expand Down Expand Up @@ -93,8 +90,6 @@
"types",
"astro.js",
"index.d.ts",
"config.d.ts",
"config.mjs",
"zod.d.ts",
"zod.mjs",
"env.d.ts",
Expand Down
19 changes: 19 additions & 0 deletions packages/astro/src/config/entrypoint.ts
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import type { SharpImageServiceConfig } from '../assets/services/sharp.js';
import type { ImageServiceConfig } from '../types/public/index.js';

export { defineConfig, getViteConfig } from './index.js';
export { envField } from '../env/config.js';

export function sharpImageService(config: SharpImageServiceConfig = {}): ImageServiceConfig {
return {
entrypoint: 'astro/assets/services/sharp',
config,
};
}

export function passthroughImageService(): ImageServiceConfig {
return {
entrypoint: 'astro/assets/services/noop',
config: {},
};
}
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
29 changes: 23 additions & 6 deletions packages/astro/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,28 @@
import type { UserConfig as ViteUserConfig } from 'vite';
import type { UserConfig as ViteUserConfig, UserConfigFn as ViteUserConfigFn } from 'vite';
import { Logger } from '../core/logger/core.js';
import { createRouteManifest } from '../core/routing/index.js';
import type { AstroInlineConfig, AstroUserConfig } from '../types/public/config.js';
import type { AstroInlineConfig, AstroUserDefineConfig, Locales } from '../types/public/config.js';
import { createDevelopmentManifest } from '../vite-plugin-astro-server/plugin.js';

export function defineConfig(config: AstroUserConfig) {
/**
* See the full Astro Configuration API Documentation
* https://astro.build/config
*/
export function defineConfig<const TLocales extends Locales = never>(
config: AstroUserDefineConfig<TLocales>,
) {
return config;
}

/**
* Use Astro to generate a fully resolved Vite config
*/
export function getViteConfig(
userViteConfig: ViteUserConfig,
inlineAstroConfig: AstroInlineConfig = {},
) {
): ViteUserConfigFn {
// Return an async Vite config getter which exposes a resolved `mode` and `command`
return async ({ mode, command }: { mode: 'dev'; command: 'serve' | 'build' }) => {
return async ({ mode, command }) => {
// Vite `command` is `serve | build`, but Astro uses `dev | build`
const cmd = command === 'serve' ? 'dev' : command;

Expand Down Expand Up @@ -52,7 +61,15 @@ export function getViteConfig(
astroContentListenPlugin({ settings, logger, fs }),
],
},
{ settings, logger, mode, sync: false, manifest, ssrManifest: devSSRManifest },
{
settings,
logger,
// TODO: can the custom mode solve that?
mode: mode as 'dev' | 'build',
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
sync: false,
manifest,
ssrManifest: devSSRManifest,
},
);
await runHookConfigDone({ settings, logger });
return mergeConfig(viteConfig, userViteConfig);
Expand Down
2 changes: 1 addition & 1 deletion packages/astro/src/env/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import type {
} from './schema.js';

/**
* Return a valid env field to use in this Astro config for `experimental.env.schema`.
* Return a valid env field to use in this Astro config for `env.schema`.
*/
export const envField = {
string: (options: StringFieldInput): StringField => ({
Expand Down
50 changes: 35 additions & 15 deletions packages/astro/src/types/public/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ import type { AstroIntegration } from './integrations.js';

export type Locales = (string | { codes: string[]; path: string })[];

type NormalizeLocales<T extends Locales> = {
[K in keyof T]: T[K] extends string
? T[K]
: T[K] extends { codes: Array<string> }
? T[K]['codes'][number]
: never;
}[number];

export interface ImageServiceConfig<T extends Record<string, any> = Record<string, any>> {
entrypoint: 'astro/assets/services/sharp' | (string & {});
config?: T;
Expand Down Expand Up @@ -102,7 +110,9 @@ export interface ViteUserConfig extends OriginalViteUserConfig {
* Astro User Config
* Docs: https://docs.astro.build/reference/configuration-reference/
*/
export interface AstroUserConfig {
export type AstroUserConfig = AstroUserDefineConfig<never>;

export interface AstroUserDefineConfig<TLocales extends Locales = never> {
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved
/**
* @docs
* @kind heading
Expand Down Expand Up @@ -1205,30 +1215,31 @@ export interface AstroUserConfig {
i18n?: {
/**
* @docs
* @name i18n.defaultLocale
* @type {string}
* @name i18n.locales
* @type {Locales}
* @version 3.5.0
* @description
*
* The default locale of your website/application. This is a required field.
* A list of all locales supported by the website. This is a required field.
*
* No particular language format or syntax is enforced, but we suggest using lower-case and hyphens as needed (e.g. "es", "pt-br") for greatest compatibility.
* Languages can be listed either as individual codes (e.g. `['en', 'es', 'pt-br']`) or mapped to a shared `path` of codes (e.g. `{ path: "english", codes: ["en", "en-US"]}`). These codes will be used to determine the URL structure of your deployed site.
*
* No particular language code format or syntax is enforced, but your project folders containing your content files must match exactly the `locales` items in the list. In the case of multiple `codes` pointing to a custom URL path prefix, store your content files in a folder with the same name as the `path` configured.
*/
defaultLocale: string;
locales: [TLocales] extends [never] ? Locales : TLocales;
florian-lefebvre marked this conversation as resolved.
Show resolved Hide resolved

/**
* @docs
* @name i18n.locales
* @type {Locales}
* @name i18n.defaultLocale
* @type {string}
* @version 3.5.0
* @description
*
* A list of all locales supported by the website, including the `defaultLocale`. This is a required field.
* The default locale of your website/application, that is one of the specified `locales`. This is a required field.
*
* Languages can be listed either as individual codes (e.g. `['en', 'es', 'pt-br']`) or mapped to a shared `path` of codes (e.g. `{ path: "english", codes: ["en", "en-US"]}`). These codes will be used to determine the URL structure of your deployed site.
*
* No particular language code format or syntax is enforced, but your project folders containing your content files must match exactly the `locales` items in the list. In the case of multiple `codes` pointing to a custom URL path prefix, store your content files in a folder with the same name as the `path` configured.
* No particular language format or syntax is enforced, but we suggest using lower-case and hyphens as needed (e.g. "es", "pt-br") for greatest compatibility.
*/
locales: Locales;
defaultLocale: [TLocales] extends [never] ? string : NormalizeLocales<NoInfer<TLocales>>;

/**
* @docs
Expand Down Expand Up @@ -1258,7 +1269,14 @@ export interface AstroUserConfig {
* })
* ```
*/
fallback?: Record<string, string>;
fallback?: [TLocales] extends [never]
? Record<string, string>
: {
[Locale in NormalizeLocales<NoInfer<TLocales>>]?: Exclude<
NormalizeLocales<NoInfer<TLocales>>,
Locale
>;
};

/**
* @docs
Expand Down Expand Up @@ -1444,7 +1462,9 @@ export interface AstroUserConfig {
*
* See the [Internationalization Guide](https://docs.astro.build/en/guides/internationalization/#domains) for more details, including the limitations of this feature.
*/
domains?: Record<string, string>;
domains?: [TLocales] extends [never]
? Record<string, string>
: Partial<Record<NormalizeLocales<NoInfer<TLocales>>, string>>;
};

/** ! WARNING: SUBJECT TO CHANGE */
Expand Down
39 changes: 39 additions & 0 deletions packages/astro/test/types/define-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { describe, it } from 'node:test';
import { defineConfig } from '../../dist/config/index.js';
import type { AstroUserDefineConfig } from '../../dist/types/public/config.js';
import { expectTypeOf } from 'expect-type';

describe('defineConfig()', () => {
ematipico marked this conversation as resolved.
Show resolved Hide resolved
it('Infers generics correctly', () => {
expectTypeOf(defineConfig({})).toEqualTypeOf<AstroUserDefineConfig<never>>();

expectTypeOf(
defineConfig({
i18n: {
locales: ['en'],
defaultLocale: 'en',
},
}),
).toEqualTypeOf<AstroUserDefineConfig<['en']>>();

expectTypeOf(
defineConfig({
i18n: {
locales: ['en', 'fr'],
defaultLocale: 'fr',
},
}),
).toEqualTypeOf<AstroUserDefineConfig<['en', 'fr']>>();

expectTypeOf(
defineConfig({
i18n: {
locales: ['en', { path: 'french', codes: ['fr', 'fr-FR'] }],
defaultLocale: 'en',
},
}),
).toEqualTypeOf<
AstroUserDefineConfig<['en', { readonly path: 'french'; readonly codes: ['fr', 'fr-FR'] }]>
>();
});
});
Loading