From ea426bdd827bc1f11efd92aebdd01b456b673396 Mon Sep 17 00:00:00 2001 From: Emanuele Stoppa Date: Thu, 3 Aug 2023 16:18:28 +0100 Subject: [PATCH] feat: break down `AstroErrorData` in multiple objects --- packages/astro/components/Image.astro | 5 +- packages/astro/src/assets/internal.ts | 3 +- packages/astro/src/assets/services/service.ts | 3 +- packages/astro/src/content/runtime.ts | 3 +- packages/astro/src/content/types-generator.ts | 2 +- packages/astro/src/content/utils.ts | 3 +- .../content/vite-plugin-content-imports.ts | 3 +- .../vite-plugin-content-virtual-mod.ts | 3 +- packages/astro/src/core/build/generate.ts | 3 +- packages/astro/src/core/build/static-build.ts | 3 +- packages/astro/src/core/compile/compile.ts | 4 +- packages/astro/src/core/compile/style.ts | 4 +- packages/astro/src/core/config/config.ts | 4 +- packages/astro/src/core/config/settings.ts | 3 +- packages/astro/src/core/cookies/cookies.ts | 3 +- packages/astro/src/core/endpoint/index.ts | 3 +- packages/astro/src/core/errors/dev/vite.ts | 20 +- packages/astro/src/core/errors/errors-data.ts | 2214 +++++++++-------- packages/astro/src/core/errors/errors.ts | 16 +- packages/astro/src/core/errors/index.ts | 1 - packages/astro/src/core/errors/utils.ts | 12 - .../src/core/middleware/callMiddleware.ts | 3 +- packages/astro/src/core/redirects/validate.ts | 3 +- packages/astro/src/core/render/context.ts | 3 +- packages/astro/src/core/render/paginate.ts | 3 +- .../astro/src/core/render/params-and-props.ts | 3 +- packages/astro/src/core/render/result.ts | 3 +- packages/astro/src/core/render/route-cache.ts | 4 +- packages/astro/src/core/routing/validation.ts | 3 +- packages/astro/src/core/sync/index.ts | 3 +- packages/astro/src/events/error.ts | 3 +- packages/astro/src/jsx/babel.ts | 2 +- .../src/runtime/server/astro-component.ts | 3 +- .../astro/src/runtime/server/astro-global.ts | 3 +- .../astro/src/runtime/server/hydration.ts | 3 +- .../src/runtime/server/render/astro/render.ts | 3 +- .../src/runtime/server/render/component.ts | 4 +- .../transitions/vite-plugin-transitions.ts | 1 + .../src/vite-plugin-astro-server/route.ts | 3 +- .../astro/src/vite-plugin-markdown/index.ts | 15 +- .../astro/src/vite-plugin-scanner/scan.ts | 3 +- packages/astro/test/events.test.js | 2 +- 42 files changed, 1230 insertions(+), 1158 deletions(-) diff --git a/packages/astro/components/Image.astro b/packages/astro/components/Image.astro index 00b0cc5fafbce..f80feb269550b 100644 --- a/packages/astro/components/Image.astro +++ b/packages/astro/components/Image.astro @@ -1,6 +1,7 @@ --- import { getImage, type LocalImageProps, type RemoteImageProps } from 'astro:assets'; -import { AstroError, AstroErrorData } from '../dist/core/errors/index.js'; +import { AstroError } from '../dist/core/errors/index.js'; +import { ImageMissingAlt } from '../dist/core/errors/errors-data.js'; // The TypeScript diagnostic for JSX props uses the last member of the union to suggest props, so it would be better for // LocalImageProps to be last. Unfortunately, when we do this the error messages that remote images get are complete nonsense @@ -10,7 +11,7 @@ type Props = LocalImageProps | RemoteImageProps; const props = Astro.props; if (props.alt === undefined || props.alt === null) { - throw new AstroError(AstroErrorData.ImageMissingAlt); + throw new AstroError(ImageMissingAlt); } // As a convenience, allow width and height to be string with a number in them, to match HTML's native `img`. diff --git a/packages/astro/src/assets/internal.ts b/packages/astro/src/assets/internal.ts index c56b5369c371a..c4473528928cc 100644 --- a/packages/astro/src/assets/internal.ts +++ b/packages/astro/src/assets/internal.ts @@ -1,5 +1,6 @@ import type { AstroSettings } from '../@types/astro.js'; -import { AstroError, AstroErrorData } from '../core/errors/index.js'; +import { AstroError } from '../core/errors/index.js'; +import * as AstroErrorData from '../core/errors/errors-data.js'; import { isLocalService, type ImageService } from './services/service.js'; import type { GetImageResult, ImageMetadata, ImageTransform } from './types.js'; diff --git a/packages/astro/src/assets/services/service.ts b/packages/astro/src/assets/services/service.ts index d3479c8803fa7..a243355a7de85 100644 --- a/packages/astro/src/assets/services/service.ts +++ b/packages/astro/src/assets/services/service.ts @@ -1,4 +1,5 @@ -import { AstroError, AstroErrorData } from '../../core/errors/index.js'; +import { AstroError } from '../../core/errors/index.js'; +import * as AstroErrorData from '../../core/errors/errors-data.js'; import { joinPaths } from '../../core/path.js'; import { VALID_SUPPORTED_FORMATS } from '../consts.js'; import { isESMImportedImage } from '../internal.js'; diff --git a/packages/astro/src/content/runtime.ts b/packages/astro/src/content/runtime.ts index a1afb2201226d..9f4a023dec88f 100644 --- a/packages/astro/src/content/runtime.ts +++ b/packages/astro/src/content/runtime.ts @@ -1,6 +1,7 @@ import type { MarkdownHeading } from '@astrojs/markdown-remark'; import { ZodIssueCode, string as zodString } from 'zod'; -import { AstroError, AstroErrorData } from '../core/errors/index.js'; +import { AstroError } from '../core/errors/index.js'; +import * as AstroErrorData from '../core/errors/errors-data.js'; import { prependForwardSlash } from '../core/path.js'; import { createComponent, diff --git a/packages/astro/src/content/types-generator.ts b/packages/astro/src/content/types-generator.ts index 7958c330feb74..4c4fefc33550b 100644 --- a/packages/astro/src/content/types-generator.ts +++ b/packages/astro/src/content/types-generator.ts @@ -5,7 +5,7 @@ import * as path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { normalizePath, type ViteDevServer } from 'vite'; import type { AstroSettings, ContentEntryType } from '../@types/astro.js'; -import { AstroErrorData } from '../core/errors/errors-data.js'; +import * as AstroErrorData from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/errors.js'; import { info, warn, type LogOptions } from '../core/logger/core.js'; import { isRelativePath } from '../core/path.js'; diff --git a/packages/astro/src/content/utils.ts b/packages/astro/src/content/utils.ts index d273dc105ec4d..4e835bc51a773 100644 --- a/packages/astro/src/content/utils.ts +++ b/packages/astro/src/content/utils.ts @@ -14,7 +14,8 @@ import type { ImageInputFormat, } from '../@types/astro.js'; import { VALID_INPUT_FORMATS } from '../assets/consts.js'; -import { AstroError, AstroErrorData } from '../core/errors/index.js'; +import { AstroError } from '../core/errors/index.js'; +import * as AstroErrorData from '../core/errors/errors-data.js'; import { formatYAMLException, isYAMLException } from '../core/errors/utils.js'; import { CONTENT_FLAGS, CONTENT_TYPES_FILE } from './consts.js'; diff --git a/packages/astro/src/content/vite-plugin-content-imports.ts b/packages/astro/src/content/vite-plugin-content-imports.ts index c76d72a12d53a..f727b36f6a0ea 100644 --- a/packages/astro/src/content/vite-plugin-content-imports.ts +++ b/packages/astro/src/content/vite-plugin-content-imports.ts @@ -12,7 +12,7 @@ import type { DataEntryModule, DataEntryType, } from '../@types/astro.js'; -import { AstroErrorData } from '../core/errors/errors-data.js'; +import * as AstroErrorData from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/errors.js'; import { escapeViteEnvReferences } from '../vite-plugin-utils/index.js'; import { CONTENT_FLAG, DATA_FLAG } from './consts.js'; @@ -371,6 +371,7 @@ function stringifyEntryData(data: Record): string { }); } else { throw new AstroError({ + name: 'ContentImportsPluginError', message: 'Unexpected error processing content collection data.', }); } diff --git a/packages/astro/src/content/vite-plugin-content-virtual-mod.ts b/packages/astro/src/content/vite-plugin-content-virtual-mod.ts index d7924973cc243..4da3a79a62679 100644 --- a/packages/astro/src/content/vite-plugin-content-virtual-mod.ts +++ b/packages/astro/src/content/vite-plugin-content-virtual-mod.ts @@ -5,7 +5,8 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; import pLimit from 'p-limit'; import type { Plugin } from 'vite'; import type { AstroSettings, ContentEntryType } from '../@types/astro.js'; -import { AstroError, AstroErrorData } from '../core/errors/index.js'; +import { AstroError } from '../core/errors/index.js'; +import * as AstroErrorData from '../core/errors/errors-data.js'; import { appendForwardSlash } from '../core/path.js'; import { rootRelativePath } from '../core/util.js'; import { VIRTUAL_MODULE_ID } from './consts.js'; diff --git a/packages/astro/src/core/build/generate.ts b/packages/astro/src/core/build/generate.ts index fbc88d0e48d5f..4084398e7f761 100644 --- a/packages/astro/src/core/build/generate.ts +++ b/packages/astro/src/core/build/generate.ts @@ -35,7 +35,8 @@ import { import { runHookBuildGenerated } from '../../integrations/index.js'; import { isServerLikeOutput } from '../../prerender/utils.js'; import { BEFORE_HYDRATION_SCRIPT_ID, PAGE_SCRIPT_ID } from '../../vite-plugin-scripts/index.js'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; +import * as AstroErrorData from '../errors/errors-data.js'; import { debug, info } from '../logger/core.js'; import { RedirectSinglePageBuiltModule, getRedirectLocationOrThrow } from '../redirects/index.js'; import { isEndpointResult } from '../render/core.js'; diff --git a/packages/astro/src/core/build/static-build.ts b/packages/astro/src/core/build/static-build.ts index 8e3cf8fa88024..27fd1b7eb0d69 100644 --- a/packages/astro/src/core/build/static-build.ts +++ b/packages/astro/src/core/build/static-build.ts @@ -12,13 +12,14 @@ import { eachPageData, type BuildInternals, } from '../../core/build/internal.js'; +import * as AstroErrorData from '../errors/errors-data.js'; import { emptyDir, removeEmptyDirs } from '../../core/fs/index.js'; import { appendForwardSlash, prependForwardSlash } from '../../core/path.js'; import { isModeServerWithNoAdapter } from '../../core/util.js'; import { runHookBuildSetup } from '../../integrations/index.js'; import { isServerLikeOutput } from '../../prerender/utils.js'; import { PAGE_SCRIPT_ID } from '../../vite-plugin-scripts/index.js'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; import { info } from '../logger/core.js'; import { routeIsRedirect } from '../redirects/index.js'; import { getOutDirWithinCwd } from './common.js'; diff --git a/packages/astro/src/core/compile/compile.ts b/packages/astro/src/core/compile/compile.ts index 33dcec0ccfdae..53fe374df8474 100644 --- a/packages/astro/src/core/compile/compile.ts +++ b/packages/astro/src/core/compile/compile.ts @@ -1,12 +1,11 @@ import type { TransformResult } from '@astrojs/compiler'; import type { ResolvedConfig } from 'vite'; import type { AstroConfig } from '../../@types/astro'; - +import * as AstroErrorData from '../errors/errors-data.js'; import { transform } from '@astrojs/compiler'; import { fileURLToPath } from 'node:url'; import { normalizePath } from 'vite'; import { AggregateError, AstroError, CompilerError } from '../errors/errors.js'; -import { AstroErrorData } from '../errors/index.js'; import { resolvePath } from '../util.js'; import { createStylePreprocessor } from './style.js'; @@ -87,6 +86,7 @@ function handleCompileResultErrors(result: TransformResult, cssTransformErrors: if (compilerError) { throw new CompilerError({ + name: 'CompilerError', message: compilerError.text, location: { line: compilerError.location.line, diff --git a/packages/astro/src/core/compile/style.ts b/packages/astro/src/core/compile/style.ts index 7ecb891220109..7a8ac6d46e09c 100644 --- a/packages/astro/src/core/compile/style.ts +++ b/packages/astro/src/core/compile/style.ts @@ -1,7 +1,8 @@ import type { TransformOptions } from '@astrojs/compiler'; import fs from 'node:fs'; import { preprocessCSS, type ResolvedConfig } from 'vite'; -import { AstroErrorData, CSSError, positionAt } from '../errors/index.js'; +import { CSSError, positionAt } from '../errors/index.js'; +import * as AstroErrorData from '../errors/errors-data.js'; export function createStylePreprocessor({ filename, @@ -88,6 +89,7 @@ function enhanceCSSError(err: any, filename: string, cssContent: string) { errorPosition.line += 1; return new CSSError({ + name: 'CSSError', message: err.message, location: { file: filename, diff --git a/packages/astro/src/core/config/config.ts b/packages/astro/src/core/config/config.ts index 0872145db5137..7c02dde6704ad 100644 --- a/packages/astro/src/core/config/config.ts +++ b/packages/astro/src/core/config/config.ts @@ -6,7 +6,7 @@ import type { AstroUserConfig, CLIFlags, } from '../../@types/astro'; - +import * as AstroErrorData from '../errors/errors-data.js'; import * as colors from 'kleur/colors'; import fs from 'node:fs'; import path from 'node:path'; @@ -14,7 +14,7 @@ import { fileURLToPath } from 'node:url'; import { ZodError } from 'zod'; import { eventConfigError, telemetry } from '../../events/index.js'; import { trackAstroConfigZodError } from '../errors/errors.js'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; import { formatConfigErrorMessage } from '../messages.js'; import { mergeConfig } from './merge.js'; import { createRelativeSchema } from './schema.js'; diff --git a/packages/astro/src/core/config/settings.ts b/packages/astro/src/core/config/settings.ts index b15961e5076c0..205cdcb7c6ba6 100644 --- a/packages/astro/src/core/config/settings.ts +++ b/packages/astro/src/core/config/settings.ts @@ -6,7 +6,8 @@ import { getContentPaths } from '../../content/index.js'; import jsxRenderer from '../../jsx/renderer.js'; import { markdownContentEntryType } from '../../vite-plugin-markdown/content-entry-type.js'; import { getDefaultClientDirectives } from '../client-directive/index.js'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; +import * as AstroErrorData from '../errors/errors-data.js'; import { formatYAMLException, isYAMLException } from '../errors/utils.js'; import { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from './../constants.js'; import { AstroTimer } from './timer.js'; diff --git a/packages/astro/src/core/cookies/cookies.ts b/packages/astro/src/core/cookies/cookies.ts index 604f30e63b925..5963e3a6e47fe 100644 --- a/packages/astro/src/core/cookies/cookies.ts +++ b/packages/astro/src/core/cookies/cookies.ts @@ -1,6 +1,7 @@ import type { CookieSerializeOptions } from 'cookie'; import { parse, serialize } from 'cookie'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; +import * as AstroErrorData from '../errors/errors-data.js'; interface AstroCookieSetOptions { domain?: string; diff --git a/packages/astro/src/core/endpoint/index.ts b/packages/astro/src/core/endpoint/index.ts index b35895197dd02..7b9e4324a94c0 100644 --- a/packages/astro/src/core/endpoint/index.ts +++ b/packages/astro/src/core/endpoint/index.ts @@ -10,9 +10,10 @@ import type { Environment, RenderContext } from '../render/index'; import { renderEndpoint } from '../../runtime/server/index.js'; import { ASTRO_VERSION } from '../constants.js'; import { AstroCookies, attachToResponse } from '../cookies/index.js'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; import { warn } from '../logger/core.js'; import { callMiddleware } from '../middleware/callMiddleware.js'; +import * as AstroErrorData from '../errors/errors-data.js'; const clientAddressSymbol = Symbol.for('astro.clientAddress'); const clientLocalsSymbol = Symbol.for('astro.locals'); diff --git a/packages/astro/src/core/errors/dev/vite.ts b/packages/astro/src/core/errors/dev/vite.ts index 30b3d44b3e3fa..76ada28656c76 100644 --- a/packages/astro/src/core/errors/dev/vite.ts +++ b/packages/astro/src/core/errors/dev/vite.ts @@ -3,7 +3,7 @@ import { fileURLToPath } from 'node:url'; import { getHighlighter } from 'shiki'; import type { ErrorPayload } from 'vite'; import type { ModuleLoader } from '../../module-loader/index.js'; -import { AstroErrorData } from '../errors-data.js'; +import { FailedToLoadModuleSSR, InvalidGlob, MdxIntegrationMissingError } from '../errors-data.js'; import { AstroError, type ErrorWithMetadata } from '../errors.js'; import { createSafeError } from '../utils.js'; import type { SSRLoadedRenderer } from './../../../@types/astro.js'; @@ -41,10 +41,10 @@ export function enhanceViteSSRError({ // https://github.com/vitejs/vite/blob/ee7c28a46a6563d54b828af42570c55f16b15d2c/packages/vite/src/node/ssr/ssrModuleLoader.ts#L91 let importName: string | undefined; if ((importName = safeError.message.match(/Failed to load url (.*?) \(resolved id:/)?.[1])) { - safeError.title = AstroErrorData.FailedToLoadModuleSSR.title; + safeError.title = FailedToLoadModuleSSR.title; safeError.name = 'FailedToLoadModuleSSR'; - safeError.message = AstroErrorData.FailedToLoadModuleSSR.message(importName); - safeError.hint = AstroErrorData.FailedToLoadModuleSSR.hint; + safeError.message = FailedToLoadModuleSSR.message(importName); + safeError.hint = FailedToLoadModuleSSR.hint; const line = lns.findIndex((ln) => ln.includes(importName!)); if (line !== -1) { @@ -68,8 +68,8 @@ export function enhanceViteSSRError({ fileId?.match(/\.mdx$/) ) { safeError = new AstroError({ - ...AstroErrorData.MdxIntegrationMissingError, - message: AstroErrorData.MdxIntegrationMissingError.message(JSON.stringify(fileId)), + ...MdxIntegrationMissingError, + message: MdxIntegrationMissingError.message(JSON.stringify(fileId)), location: safeError.loc, stack: safeError.stack, }) as ErrorWithMetadata; @@ -80,10 +80,10 @@ export function enhanceViteSSRError({ const globPattern = safeError.message.match(/glob: "(.+)" \(/)?.[1]; if (globPattern) { - safeError.message = AstroErrorData.InvalidGlob.message(globPattern); + safeError.message = InvalidGlob.message(globPattern); safeError.name = 'InvalidGlob'; - safeError.hint = AstroErrorData.InvalidGlob.hint; - safeError.title = AstroErrorData.InvalidGlob.title; + safeError.hint = InvalidGlob.hint; + safeError.title = InvalidGlob.title; const line = lns.findIndex((ln) => ln.includes(globPattern)); @@ -137,7 +137,7 @@ export async function getViteErrorPayload(err: ErrorWithMetadata): Promise string); hint?: string | ((...params: any) => string); } -export const AstroErrorData = { - /** - * @docs - * @kind heading - * @name Astro Errors - */ - /** - * @docs - * @message - * Unknown compiler error. - * @see - * - [withastro/compiler issues list](https://astro.build/issues/compiler) - * @description - * Astro encountered an unknown error while compiling your files. In most cases, this is not your fault, but an issue in our compiler. - * - * If there isn't one already, please [create an issue](https://astro.build/issues/compiler). - */ - UnknownCompilerError: { - title: 'Unknown compiler error.', - hint: 'This is almost always a problem with the Astro compiler, not your code. Please open an issue at https://astro.build/issues/compiler.', - }, - // 1xxx and 2xxx codes are reserved for compiler errors and warnings respectively - /** - * @docs - * @see - * - [Enabling SSR in Your Project](https://docs.astro.build/en/guides/server-side-rendering/#enabling-ssr-in-your-project) - * - [Astro.redirect](https://docs.astro.build/en/reference/api-reference/#astroredirect) - * @description - * The `Astro.redirect` function is only available when [Server-side rendering](/en/guides/server-side-rendering/) is enabled. - * - * To redirect on a static website, the [meta refresh attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) can be used. Certain hosts also provide config-based redirects (ex: [Netlify redirects](https://docs.netlify.com/routing/redirects/)). - * @deprecated since version 2.6 - */ - StaticRedirectNotAvailable: { - title: '`Astro.redirect` is not available in static mode.', - message: - "Redirects are only available when using `output: 'server'` or `output: 'hybrid'`. Update your Astro config if you need SSR features.", - hint: 'See https://docs.astro.build/en/guides/server-side-rendering/#enabling-ssr-in-your-project for more information on how to enable SSR.', - }, - /** - * @docs - * @see - * - [Official integrations](https://docs.astro.build/en/guides/integrations-guide/#official-integrations) - * - [Astro.clientAddress](https://docs.astro.build/en/reference/api-reference/#astroclientaddress) - * @description - * The adapter you're using unfortunately does not support `Astro.clientAddress`. - */ - ClientAddressNotAvailable: { - title: '`Astro.clientAddress` is not available in current adapter.', - message: (adapterName: string) => - `\`Astro.clientAddress\` is not available in the \`${adapterName}\` adapter. File an issue with the adapter to add support.`, - }, - /** - * @docs - * @see - * - [Enabling SSR in Your Project](https://docs.astro.build/en/guides/server-side-rendering/#enabling-ssr-in-your-project) - * - [Astro.clientAddress](https://docs.astro.build/en/reference/api-reference/#astroclientaddress) - * @description - * The `Astro.clientAddress` property is only available when [Server-side rendering](https://docs.astro.build/en/guides/server-side-rendering/) is enabled. - * - * To get the user's IP address in static mode, different APIs such as [Ipify](https://www.ipify.org/) can be used in a [Client-side script](https://docs.astro.build/en/guides/client-side-scripts/) or it may be possible to get the user's IP using a serverless function hosted on your hosting provider. - */ - StaticClientAddressNotAvailable: { - title: '`Astro.clientAddress` is not available in static mode.', - message: - "`Astro.clientAddress` is only available when using `output: 'server'` or `output: 'hybrid'`. Update your Astro config if you need SSR features.", - hint: 'See https://docs.astro.build/en/guides/server-side-rendering/#enabling-ssr-in-your-project for more information on how to enable SSR.', - }, - /** - * @docs - * @see - * - [getStaticPaths()](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - * @description - * A [dynamic route](https://docs.astro.build/en/core-concepts/routing/#dynamic-routes) was matched, but no corresponding path was found for the requested parameters. This is often caused by a typo in either the generated or the requested path. - */ - NoMatchingStaticPathFound: { - title: 'No static path found for requested path.', - message: (pathName: string) => - `A \`getStaticPaths()\` route pattern was matched, but no matching static path was found for requested path \`${pathName}\`.`, - hint: (possibleRoutes: string[]) => - `Possible dynamic routes being matched: ${possibleRoutes.join(', ')}.`, - }, - /** - * @docs - * @message Route returned a `RETURNED_VALUE`. Only a Response can be returned from Astro files. - * @see - * - [Response](https://docs.astro.build/en/guides/server-side-rendering/#response) - * @description - * Only instances of [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned inside Astro files. - * ```astro title="pages/login.astro" - * --- - * return new Response(null, { - * status: 404, - * statusText: 'Not found' - * }); - * - * // Alternatively, for redirects, Astro.redirect also returns an instance of Response - * return Astro.redirect('/login'); - * --- - * ``` - * - */ - OnlyResponseCanBeReturned: { - title: 'Invalid type returned by Astro page.', - message: (route: string | undefined, returnedValue: string) => - `Route \`${ - route ? route : '' - }\` returned a \`${returnedValue}\`. Only a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned from Astro files.`, - hint: 'See https://docs.astro.build/en/guides/server-side-rendering/#response for more information.', - }, - /** - * @docs - * @see - * - [`client:media`](https://docs.astro.build/en/reference/directives-reference/#clientmedia) - * @description - * A [media query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries) parameter is required when using the `client:media` directive. - * - * ```astro - * - * ``` - */ - MissingMediaQueryDirective: { - title: 'Missing value for `client:media` directive.', - message: - 'Media query not provided for `client:media` directive. A media query similar to `client:media="(max-width: 600px)"` must be provided', - }, - /** - * @docs - * @message Unable to render `COMPONENT_NAME`. There are `RENDERER_COUNT` renderer(s) configured in your `astro.config.mjs` file, but none were able to server-side render `COMPONENT_NAME`. - * @see - * - [Frameworks components](https://docs.astro.build/en/core-concepts/framework-components/) - * - [UI Frameworks](https://docs.astro.build/en/guides/integrations-guide/#official-integrations) - * @description - * None of the installed integrations were able to render the component you imported. Make sure to install the appropriate integration for the type of component you are trying to include in your page. - * - * For JSX / TSX files, [@astrojs/react](https://docs.astro.build/en/guides/integrations-guide/react/), [@astrojs/preact](https://docs.astro.build/en/guides/integrations-guide/preact/) or [@astrojs/solid-js](https://docs.astro.build/en/guides/integrations-guide/solid-js/) can be used. For Vue and Svelte files, the [@astrojs/vue](https://docs.astro.build/en/guides/integrations-guide/vue/) and [@astrojs/svelte](https://docs.astro.build/en/guides/integrations-guide/svelte/) integrations can be used respectively - */ - NoMatchingRenderer: { - title: 'No matching renderer found.', - message: ( - componentName: string, - componentExtension: string | undefined, - plural: boolean, - validRenderersCount: number - ) => - `Unable to render \`${componentName}\`. +/** + * @docs + * @kind heading + * @name Astro Errors + */ +/** + * @docs + * @message + * Unknown compiler error. + * @see + * - [withastro/compiler issues list](https://astro.build/issues/compiler) + * @description + * Astro encountered an unknown error while compiling your files. In most cases, this is not your fault, but an issue in our compiler. + * + * If there isn't one already, please [create an issue](https://astro.build/issues/compiler). + */ +export const UnknownCompilerError = { + name: 'UnknownCompilerError', + title: 'Unknown compiler error.', + hint: 'This is almost always a problem with the Astro compiler, not your code. Please open an issue at https://astro.build/issues/compiler.', +} satisfies ErrorData; +// 1xxx and 2xxx codes are reserved for compiler errors and warnings respectively +/** + * @docs + * @see + * - [Enabling SSR in Your Project](https://docs.astro.build/en/guides/server-side-rendering/#enabling-ssr-in-your-project) + * - [Astro.redirect](https://docs.astro.build/en/reference/api-reference/#astroredirect) + * @description + * The `Astro.redirect` function is only available when [Server-side rendering](/en/guides/server-side-rendering/) is enabled. + * + * To redirect on a static website, the [meta refresh attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta) can be used. Certain hosts also provide config-based redirects (ex: [Netlify redirects](https://docs.netlify.com/routing/redirects/)). + * @deprecated since version 2.6 + */ +export const StaticRedirectNotAvailable = { + name: 'StaticRedirectNotAvailable', + title: '`Astro.redirect` is not available in static mode.', + message: + "Redirects are only available when using `output: 'server'` or `output: 'hybrid'`. Update your Astro config if you need SSR features.", + hint: 'See https://docs.astro.build/en/guides/server-side-rendering/#enabling-ssr-in-your-project for more information on how to enable SSR.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [Official integrations](https://docs.astro.build/en/guides/integrations-guide/#official-integrations) + * - [Astro.clientAddress](https://docs.astro.build/en/reference/api-reference/#astroclientaddress) + * @description + * The adapter you're using unfortunately does not support `Astro.clientAddress`. + */ +export const ClientAddressNotAvailable = { + name: 'ClientAddressNotAvailable', + title: '`Astro.clientAddress` is not available in current adapter.', + message: (adapterName: string) => + `\`Astro.clientAddress\` is not available in the \`${adapterName}\` adapter. File an issue with the adapter to add support.`, +} satisfies ErrorData; +/** + * @docs + * @see + * - [Enabling SSR in Your Project](https://docs.astro.build/en/guides/server-side-rendering/#enabling-ssr-in-your-project) + * - [Astro.clientAddress](https://docs.astro.build/en/reference/api-reference/#astroclientaddress) + * @description + * The `Astro.clientAddress` property is only available when [Server-side rendering](https://docs.astro.build/en/guides/server-side-rendering/) is enabled. + * + * To get the user's IP address in static mode, different APIs such as [Ipify](https://www.ipify.org/) can be used in a [Client-side script](https://docs.astro.build/en/guides/client-side-scripts/) or it may be possible to get the user's IP using a serverless function hosted on your hosting provider. + */ +export const StaticClientAddressNotAvailable = { + name: 'StaticClientAddressNotAvailable', + title: '`Astro.clientAddress` is not available in static mode.', + message: + "`Astro.clientAddress` is only available when using `output: 'server'` or `output: 'hybrid'`. Update your Astro config if you need SSR features.", + hint: 'See https://docs.astro.build/en/guides/server-side-rendering/#enabling-ssr-in-your-project for more information on how to enable SSR.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [getStaticPaths()](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + * @description + * A [dynamic route](https://docs.astro.build/en/core-concepts/routing/#dynamic-routes) was matched, but no corresponding path was found for the requested parameters. This is often caused by a typo in either the generated or the requested path. + */ +export const NoMatchingStaticPathFound = { + name: 'NoMatchingStaticPathFound', + title: 'No static path found for requested path.', + message: (pathName: string) => + `A \`getStaticPaths()\` route pattern was matched, but no matching static path was found for requested path \`${pathName}\`.`, + hint: (possibleRoutes: string[]) => + `Possible dynamic routes being matched: ${possibleRoutes.join(', ')}.`, +} satisfies ErrorData; +/** + * @docs + * @message Route returned a `RETURNED_VALUE`. Only a Response can be returned from Astro files. + * @see + * - [Response](https://docs.astro.build/en/guides/server-side-rendering/#response) + * @description + * Only instances of [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned inside Astro files. + * ```astro title="pages/login.astro" + * --- + * return new Response(null, { + * status: 404, + * statusText: 'Not found' + * }); + * + * // Alternatively, for redirects, Astro.redirect also returns an instance of Response + * return Astro.redirect('/login'); + * --- + * ``` + * + */ +export const OnlyResponseCanBeReturned = { + name: 'OnlyResponseCanBeReturned', + title: 'Invalid type returned by Astro page.', + message: (route: string | undefined, returnedValue: string) => + `Route \`${ + route ? route : '' + }\` returned a \`${returnedValue}\`. Only a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) can be returned from Astro files.`, + hint: 'See https://docs.astro.build/en/guides/server-side-rendering/#response for more information.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [`client:media`](https://docs.astro.build/en/reference/directives-reference/#clientmedia) + * @description + * A [media query](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries) parameter is required when using the `client:media` directive. + * + * ```astro + * + * ``` + */ +export const MissingMediaQueryDirective = { + name: 'MissingMediaQueryDirective', + title: 'Missing value for `client:media` directive.', + message: + 'Media query not provided for `client:media` directive. A media query similar to `client:media="(max-width: 600px)"` must be provided', +} satisfies ErrorData; +/** + * @docs + * @message Unable to render `COMPONENT_NAME`. There are `RENDERER_COUNT` renderer(s) configured in your `astro.config.mjs` file, but none were able to server-side render `COMPONENT_NAME`. + * @see + * - [Frameworks components](https://docs.astro.build/en/core-concepts/framework-components/) + * - [UI Frameworks](https://docs.astro.build/en/guides/integrations-guide/#official-integrations) + * @description + * None of the installed integrations were able to render the component you imported. Make sure to install the appropriate integration for the type of component you are trying to include in your page. + * + * For JSX / TSX files, [@astrojs/react](https://docs.astro.build/en/guides/integrations-guide/react/), [@astrojs/preact](https://docs.astro.build/en/guides/integrations-guide/preact/) or [@astrojs/solid-js](https://docs.astro.build/en/guides/integrations-guide/solid-js/) can be used. For Vue and Svelte files, the [@astrojs/vue](https://docs.astro.build/en/guides/integrations-guide/vue/) and [@astrojs/svelte](https://docs.astro.build/en/guides/integrations-guide/svelte/) integrations can be used respectively + */ +export const NoMatchingRenderer = { + name: 'NoMatchingRenderer', + title: 'No matching renderer found.', + message: ( + componentName: string, + componentExtension: string | undefined, + plural: boolean, + validRenderersCount: number + ) => + `Unable to render \`${componentName}\`. ${ validRenderersCount > 0 @@ -169,947 +177,999 @@ but ${plural ? 'none were' : 'it was not'} able to server-side render \`${compon : `for this file extension.` }` }`, - hint: (probableRenderers: string) => - `Did you mean to enable the ${probableRenderers} integration?\n\nSee https://docs.astro.build/en/core-concepts/framework-components/ for more information on how to install and configure integrations.`, - }, - /** - * @docs - * @see - * - [addRenderer option](https://docs.astro.build/en/reference/integrations-reference/#addrenderer-option) - * - [Hydrating framework components](https://docs.astro.build/en/core-concepts/framework-components/#hydrating-interactive-components) - * @description - * Astro tried to hydrate a component on the client, but the renderer used does not provide a client entrypoint to use to hydrate. - * - */ - NoClientEntrypoint: { - title: 'No client entrypoint specified in renderer.', - message: (componentName: string, clientDirective: string, rendererName: string) => - `\`${componentName}\` component has a \`client:${clientDirective}\` directive, but no client entrypoint was provided by \`${rendererName}\`.`, - hint: 'See https://docs.astro.build/en/reference/integrations-reference/#addrenderer-option for more information on how to configure your renderer.', - }, - /** - * @docs - * @see - * - [`client:only`](https://docs.astro.build/en/reference/directives-reference/#clientonly) - * @description - * - * `client:only` components are not run on the server, as such Astro does not know (and cannot guess) which renderer to use and require a hint. Like such: - * - * ```astro - * - * ``` - */ - NoClientOnlyHint: { - title: 'Missing hint on client:only directive.', - message: (componentName: string) => - `Unable to render \`${componentName}\`. When using the \`client:only\` hydration strategy, Astro needs a hint to use the correct renderer.`, - hint: (probableRenderers: string) => - `Did you mean to pass \`client:only="${probableRenderers}"\`? See https://docs.astro.build/en/reference/directives-reference/#clientonly for more information on client:only`, - }, - /** - * @docs - * @see - * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - * - [`params`](https://docs.astro.build/en/reference/api-reference/#params) - * @description - * The `params` property in `getStaticPaths`'s return value (an array of objects) should also be an object. - * - * ```astro title="pages/blog/[id].astro" - * --- - * export async function getStaticPaths() { - * return [ - * { params: { slug: "blog" } }, - * { params: { slug: "about" } } - * ]; - *} - *--- - * ``` - */ - InvalidGetStaticPathParam: { - title: 'Invalid value returned by a `getStaticPaths` path.', - message: (paramType) => - `Invalid params given to \`getStaticPaths\` path. Expected an \`object\`, got \`${paramType}\``, - hint: 'See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.', - }, - /** - * @docs - * @see - * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - * @description - * `getStaticPaths`'s return value must be an array of objects. In most cases, this error happens because an array of array was returned. Using [`.flatMap()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) or a [`.flat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) call may be useful. - * - * ```ts title="pages/blog/[id].astro" - * export async function getStaticPaths() { - * return [ // <-- Array - * { params: { slug: "blog" } }, // <-- Object - * { params: { slug: "about" } } - * ]; - *} - * ``` - */ - InvalidGetStaticPathsEntry: { - title: "Invalid entry inside getStaticPath's return value", - message: (entryType) => - `Invalid entry returned by getStaticPaths. Expected an object, got \`${entryType}\``, - hint: "If you're using a `.map` call, you might be looking for `.flatMap()` instead. See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.", - }, - /** - * @docs - * @see - * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - * - [`params`](https://docs.astro.build/en/reference/api-reference/#params) - * @description - * `getStaticPaths`'s return value must be an array of objects. - * - * ```ts title="pages/blog/[id].astro" - * export async function getStaticPaths() { - * return [ // <-- Array - * { params: { slug: "blog" } }, - * { params: { slug: "about" } } - * ]; - *} - * ``` - */ - InvalidGetStaticPathsReturn: { - title: 'Invalid value returned by getStaticPaths.', - message: (returnType) => - `Invalid type returned by \`getStaticPaths\`. Expected an \`array\`, got \`${returnType}\``, - hint: 'See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.', - }, + hint: (probableRenderers: string) => + `Did you mean to enable the ${probableRenderers} integration?\n\nSee https://docs.astro.build/en/core-concepts/framework-components/ for more information on how to install and configure integrations.`, +} satisfies ErrorData; +/** + * @docs + * @see + * - [addRenderer option](https://docs.astro.build/en/reference/integrations-reference/#addrenderer-option) + * - [Hydrating framework components](https://docs.astro.build/en/core-concepts/framework-components/#hydrating-interactive-components) + * @description + * Astro tried to hydrate a component on the client, but the renderer used does not provide a client entrypoint to use to hydrate. + * + */ +export const NoClientEntrypoint = { + name: 'NoClientEntrypoint', + title: 'No client entrypoint specified in renderer.', + message: (componentName: string, clientDirective: string, rendererName: string) => + `\`${componentName}\` component has a \`client:${clientDirective}\` directive, but no client entrypoint was provided by \`${rendererName}\`.`, + hint: 'See https://docs.astro.build/en/reference/integrations-reference/#addrenderer-option for more information on how to configure your renderer.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [`client:only`](https://docs.astro.build/en/reference/directives-reference/#clientonly) + * @description + * + * `client:only` components are not run on the server, as such Astro does not know (and cannot guess) which renderer to use and require a hint. Like such: + * + * ```astro + * + * ``` + */ +export const NoClientOnlyHint = { + name: 'NoClientOnlyHint', + title: 'Missing hint on client:only directive.', + message: (componentName: string) => + `Unable to render \`${componentName}\`. When using the \`client:only\` hydration strategy, Astro needs a hint to use the correct renderer.`, + hint: (probableRenderers: string) => + `Did you mean to pass \`client:only="${probableRenderers}"\`? See https://docs.astro.build/en/reference/directives-reference/#clientonly for more information on client:only`, +} satisfies ErrorData; +/** + * @docs + * @see + * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + * - [`params`](https://docs.astro.build/en/reference/api-reference/#params) + * @description + * The `params` property in `getStaticPaths`'s return value (an array of objects) should also be an object. + * + * ```astro title="pages/blog/[id].astro" + * --- + * export async function getStaticPaths() { + * return [ + * { params: { slug: "blog" } }, + * { params: { slug: "about" } } + * ]; + *} + *--- + * ``` + */ +export const InvalidGetStaticPathParam = { + name: 'InvalidGetStaticPathParam', + title: 'Invalid value returned by a `getStaticPaths` path.', + message: (paramType) => + `Invalid params given to \`getStaticPaths\` path. Expected an \`object\`, got \`${paramType}\``, + hint: 'See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + * @description + * `getStaticPaths`'s return value must be an array of objects. In most cases, this error happens because an array of array was returned. Using [`.flatMap()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) or a [`.flat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) call may be useful. + * + * ```ts title="pages/blog/[id].astro" + * export async function getStaticPaths() { + * return [ // <-- Array + * { params: { slug: "blog" } }, // <-- Object + * { params: { slug: "about" } } + * ]; + *} + * ``` + */ +export const InvalidGetStaticPathsEntry = { + name: 'InvalidGetStaticPathsEntry', + title: "Invalid entry inside getStaticPath's return value", + message: (entryType) => + `Invalid entry returned by getStaticPaths. Expected an object, got \`${entryType}\``, + hint: "If you're using a `.map` call, you might be looking for `.flatMap()` instead. See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.", +} satisfies ErrorData; +/** + * @docs + * @see + * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + * - [`params`](https://docs.astro.build/en/reference/api-reference/#params) + * @description + * `getStaticPaths`'s return value must be an array of objects. + * + * ```ts title="pages/blog/[id].astro" + * export async function getStaticPaths() { + * return [ // <-- Array + * { params: { slug: "blog" } }, + * { params: { slug: "about" } } + * ]; + *} + * ``` + */ +export const InvalidGetStaticPathsReturn = { + name: 'InvalidGetStaticPathsReturn', + title: 'Invalid value returned by getStaticPaths.', + message: (returnType) => + `Invalid type returned by \`getStaticPaths\`. Expected an \`array\`, got \`${returnType}\``, + hint: 'See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.', +} satisfies ErrorData; - /** - * @docs - * @see - * - [RSS Guide](https://docs.astro.build/en/guides/rss/) - * @description - * `getStaticPaths` no longer expose an helper for generating a RSS feed. We recommend migrating to the [@astrojs/rss](https://docs.astro.build/en/guides/rss/#setting-up-astrojsrss)integration instead. - */ - GetStaticPathsRemovedRSSHelper: { - title: 'getStaticPaths RSS helper is not available anymore.', - message: - 'The RSS helper has been removed from `getStaticPaths`. Try the new @astrojs/rss package instead.', - hint: 'See https://docs.astro.build/en/guides/rss/ for more information.', - }, - /** - * @docs - * @see - * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - * - [`params`](https://docs.astro.build/en/reference/api-reference/#params) - * @description - * Every route specified by `getStaticPaths` require a `params` property specifying the path parameters needed to match the route. - * - * For instance, the following code: - * ```astro title="pages/blog/[id].astro" - * --- - * export async function getStaticPaths() { - * return [ - * { params: { id: '1' } } - * ]; - * } - * --- - * ``` - * Will create the following route: `site.com/blog/1`. - */ - GetStaticPathsExpectedParams: { - title: 'Missing params property on `getStaticPaths` route.', - message: 'Missing or empty required `params` property on `getStaticPaths` route.', - hint: 'See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.', - }, - /** - * @docs - * @see - * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - * - [`params`](https://docs.astro.build/en/reference/api-reference/#params) - * @description - * Since `params` are encoded into the URL, only certain types are supported as values. - * - * ```astro title="/route/[id].astro" - * --- - * export async function getStaticPaths() { - * return [ - * { params: { id: '1' } } // Works - * { params: { id: 2 } } // Works - * { params: { id: false } } // Does not work - * ]; - * } - * --- - * ``` - * - * In routes using [rest parameters](https://docs.astro.build/en/core-concepts/routing/#rest-parameters), `undefined` can be used to represent a path with no parameters passed in the URL: - * - * ```astro title="/route/[...id].astro" - * --- - * export async function getStaticPaths() { - * return [ - * { params: { id: 1 } } // /route/1 - * { params: { id: 2 } } // /route/2 - * { params: { id: undefined } } // /route/ - * ]; - * } - * --- - * ``` - */ - GetStaticPathsInvalidRouteParam: { - title: 'Invalid value for `getStaticPaths` route parameter.', - message: (key: string, value: any, valueType: any) => - `Invalid getStaticPaths route parameter for \`${key}\`. Expected undefined, a string or a number, received \`${valueType}\` (\`${value}\`)`, - hint: 'See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.', - }, - /** - * @docs - * @see - * - [Dynamic Routes](https://docs.astro.build/en/core-concepts/routing/#dynamic-routes) - * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - * - [Server-side Rendering](https://docs.astro.build/en/guides/server-side-rendering/) - * @description - * In [Static Mode](https://docs.astro.build/en/core-concepts/routing/#static-ssg-mode), all routes must be determined at build time. As such, dynamic routes must `export` a `getStaticPaths` function returning the different paths to generate. - */ - GetStaticPathsRequired: { - title: '`getStaticPaths()` function required for dynamic routes.', - message: - '`getStaticPaths()` function is required for dynamic routes. Make sure that you `export` a `getStaticPaths` function from your dynamic route.', - hint: `See https://docs.astro.build/en/core-concepts/routing/#dynamic-routes for more information on dynamic routes. +/** + * @docs + * @see + * - [RSS Guide](https://docs.astro.build/en/guides/rss/) + * @description + * `getStaticPaths` no longer expose an helper for generating a RSS feed. We recommend migrating to the [@astrojs/rss](https://docs.astro.build/en/guides/rss/#setting-up-astrojsrss)integration instead. + */ +export const GetStaticPathsRemovedRSSHelper = { + name: 'GetStaticPathsRemovedRSSHelper', + title: 'getStaticPaths RSS helper is not available anymore.', + message: + 'The RSS helper has been removed from `getStaticPaths`. Try the new @astrojs/rss package instead.', + hint: 'See https://docs.astro.build/en/guides/rss/ for more information.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + * - [`params`](https://docs.astro.build/en/reference/api-reference/#params) + * @description + * Every route specified by `getStaticPaths` require a `params` property specifying the path parameters needed to match the route. + * + * For instance, the following code: + * ```astro title="pages/blog/[id].astro" + * --- + * export async function getStaticPaths() { + * return [ + * { params: { id: '1' } } + * ]; + * } + * --- + * ``` + * Will create the following route: `site.com/blog/1`. + */ +export const GetStaticPathsExpectedParams = { + name: 'GetStaticPathsExpectedParams', + title: 'Missing params property on `getStaticPaths` route.', + message: 'Missing or empty required `params` property on `getStaticPaths` route.', + hint: 'See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + * - [`params`](https://docs.astro.build/en/reference/api-reference/#params) + * @description + * Since `params` are encoded into the URL, only certain types are supported as values. + * + * ```astro title="/route/[id].astro" + * --- + * export async function getStaticPaths() { + * return [ + * { params: { id: '1' } } // Works + * { params: { id: 2 } } // Works + * { params: { id: false } } // Does not work + * ]; + * } + * --- + * ``` + * + * In routes using [rest parameters](https://docs.astro.build/en/core-concepts/routing/#rest-parameters), `undefined` can be used to represent a path with no parameters passed in the URL: + * + * ```astro title="/route/[...id].astro" + * --- + * export async function getStaticPaths() { + * return [ + * { params: { id: 1 } } // /route/1 + * { params: { id: 2 } } // /route/2 + * { params: { id: undefined } } // /route/ + * ]; + * } + * --- + * ``` + */ +export const GetStaticPathsInvalidRouteParam = { + name: 'GetStaticPathsInvalidRouteParam', + title: 'Invalid value for `getStaticPaths` route parameter.', + message: (key: string, value: any, valueType: any) => + `Invalid getStaticPaths route parameter for \`${key}\`. Expected undefined, a string or a number, received \`${valueType}\` (\`${value}\`)`, + hint: 'See https://docs.astro.build/en/reference/api-reference/#getstaticpaths for more information on getStaticPaths.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [Dynamic Routes](https://docs.astro.build/en/core-concepts/routing/#dynamic-routes) + * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + * - [Server-side Rendering](https://docs.astro.build/en/guides/server-side-rendering/) + * @description + * In [Static Mode](https://docs.astro.build/en/core-concepts/routing/#static-ssg-mode), all routes must be determined at build time. As such, dynamic routes must `export` a `getStaticPaths` function returning the different paths to generate. + */ +export const GetStaticPathsRequired = { + name: 'GetStaticPathsRequired', + title: '`getStaticPaths()` function required for dynamic routes.', + message: + '`getStaticPaths()` function is required for dynamic routes. Make sure that you `export` a `getStaticPaths` function from your dynamic route.', + hint: `See https://docs.astro.build/en/core-concepts/routing/#dynamic-routes for more information on dynamic routes. Alternatively, set \`output: "server"\` in your Astro config file to switch to a non-static server build. This error can also occur if using \`export const prerender = true;\`. See https://docs.astro.build/en/guides/server-side-rendering/ for more information on non-static rendering.`, - }, - /** - * @docs - * @see - * - [Named slots](https://docs.astro.build/en/core-concepts/astro-components/#named-slots) - * @description - * Certain words cannot be used for slot names due to being already used internally. - */ - ReservedSlotName: { - title: 'Invalid slot name.', - message: (slotName: string) => - `Unable to create a slot named \`${slotName}\`. \`${slotName}\` is a reserved slot name. Please update the name of this slot.`, - }, - /** - * @docs - * @see - * - [Server-side Rendering](https://docs.astro.build/en/guides/server-side-rendering/) - * - [Adding an Adapter](https://docs.astro.build/en/guides/server-side-rendering/#adding-an-adapter) - * @description - * To use server-side rendering, an adapter needs to be installed so Astro knows how to generate the proper output for your targeted deployment platform. - */ - NoAdapterInstalled: { - title: 'Cannot use Server-side Rendering without an adapter.', - message: `Cannot use \`output: 'server'\` or \`output: 'hybrid'\` without an adapter. Please install and configure the appropriate server adapter for your final deployment.`, - hint: 'See https://docs.astro.build/en/guides/server-side-rendering/ for more information.', - }, - /** - * @docs - * @description - * No import statement was found for one of the components. If there is an import statement, make sure you are using the same identifier in both the imports and the component usage. - */ - NoMatchingImport: { - title: 'No import found for component.', - message: (componentName: string) => - `Could not render \`${componentName}\`. No matching import has been found for \`${componentName}\`.`, - hint: 'Please make sure the component is properly imported.', - }, - /** - * @docs - * @message - * **Example error messages:**
- * InvalidPrerenderExport: A `prerender` export has been detected, but its value cannot be statically analyzed. - * @description - * The `prerender` feature only supports a subset of valid JavaScript — be sure to use exactly `export const prerender = true` so that our compiler can detect this directive at build time. Variables, `let`, and `var` declarations are not supported. - */ - InvalidPrerenderExport: { - title: 'Invalid prerender export.', - message: (prefix: string, suffix: string, isHydridOuput: boolean) => { - const defaultExpectedValue = isHydridOuput ? 'false' : 'true'; - let msg = `A \`prerender\` export has been detected, but its value cannot be statically analyzed.`; - if (prefix !== 'const') msg += `\nExpected \`const\` declaration but got \`${prefix}\`.`; - if (suffix !== 'true') - msg += `\nExpected \`${defaultExpectedValue}\` value but got \`${suffix}\`.`; - return msg; - }, - hint: 'Mutable values declared at runtime are not supported. Please make sure to use exactly `export const prerender = true`.', - }, - /** - * @docs - * @message - * **Example error messages:**
- * InvalidComponentArgs: Invalid arguments passed to `` component. - * @description - * Astro components cannot be rendered manually via a function call, such as `Component()` or `{items.map(Component)}`. Prefer the component syntax `` or `{items.map(item => )}`. - */ - InvalidComponentArgs: { - title: 'Invalid component arguments.', - message: (name: string) => `Invalid arguments passed to${name ? ` <${name}>` : ''} component.`, - hint: 'Astro components cannot be rendered directly via function call, such as `Component()` or `{items.map(Component)}`.', - }, - /** - * @docs - * @see - * - [Pagination](https://docs.astro.build/en/core-concepts/routing/#pagination) - * @description - * The page number parameter was not found in your filepath. - */ - PageNumberParamNotFound: { - title: 'Page number param not found.', - message: (paramName: string) => - `[paginate()] page number param \`${paramName}\` not found in your filepath.`, - hint: 'Rename your file to `[page].astro` or `[...page].astro`.', - }, - /** - * @docs - * @see - * - [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) - * - [Image component](https://docs.astro.build/en/guides/assets/#image--astroassets) - * - [Image component#alt](https://docs.astro.build/en/guides/assets/#alt-required) - * @description - * The `alt` property allows you to provide descriptive alt text to users of screen readers and other assistive technologies. In order to ensure your images are accessible, the `Image` component requires that an `alt` be specified. - * - * If the image is merely decorative (i.e. doesn’t contribute to the understanding of the page), set `alt=""` so that screen readers know to ignore the image. - */ - ImageMissingAlt: { - title: 'Missing alt property.', - message: 'The alt property is required.', - hint: "The `alt` property is important for the purpose of accessibility, without it users using screen readers or other assistive technologies won't be able to understand what your image is supposed to represent. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-alt for more information.", - }, - /** - * @docs - * @see - * - [Image Service API](https://docs.astro.build/en/reference/image-service-reference/) - * @description - * There was an error while loading the configured image service. This can be caused by various factors, such as your image service not properly exporting a compatible object in its default export, or an incorrect path. - * - * If you believe that your service is properly configured and this error is wrong, please [open an issue](https://astro.build/issues/). - */ - InvalidImageService: { - title: 'Error while loading image service.', - message: - 'There was an error loading the configured image service. Please see the stack trace for more information.', - }, - /** - * @docs - * @message - * Missing width and height attributes for `IMAGE_URL`. When using remote images, both dimensions are always required in order to avoid cumulative layout shift (CLS). - * @see - * - [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) - * - [Image component#width-and-height](https://docs.astro.build/en/guides/assets/#width-and-height) - * @description - * For remote images, `width` and `height` cannot be inferred from the original file. As such, in order to avoid CLS, those two properties are always required. - * - * If your image is inside your `src` folder, you probably meant to import it instead. See [the Imports guide for more information](https://docs.astro.build/en/guides/imports/#other-assets). - */ - MissingImageDimension: { - title: 'Missing image dimensions', - message: (missingDimension: 'width' | 'height' | 'both', imageURL: string) => - `Missing ${ - missingDimension === 'both' - ? 'width and height attributes' - : `${missingDimension} attribute` - } for ${imageURL}. When using remote images, both dimensions are always required in order to avoid CLS.`, - hint: 'If your image is inside your `src` folder, you probably meant to import it instead. See [the Imports guide for more information](https://docs.astro.build/en/guides/imports/#other-assets).', - }, - /** - * @docs - * @description - * The built-in image services do not currently support optimizing all image formats. - * - * For unsupported formats such as SVGs and GIFs, you may be able to use an `img` tag directly: - * ```astro - * --- - * import rocket from '../assets/images/rocket.svg'; - * --- - * - * A rocketship in space. - * ``` - */ - UnsupportedImageFormat: { - title: 'Unsupported image format', - message: (format: string, imagePath: string, supportedFormats: readonly string[]) => - `Received unsupported format \`${format}\` from \`${imagePath}\`. Currently only ${supportedFormats.join( - ', ' - )} are supported by our image services.`, - hint: "Using an `img` tag directly instead of the `Image` component might be what you're looking for.", - }, - /** - * @docs - * @see - * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - * - [`params`](https://docs.astro.build/en/reference/api-reference/#params) - * @description - * The endpoint is prerendered with an `undefined` param so the generated path will collide with another route. - * - * If you cannot prevent passing `undefined`, then an additional extension can be added to the endpoint file name to generate the file with a different name. For example, renaming `pages/api/[slug].ts` to `pages/api/[slug].json.ts`. - */ - PrerenderDynamicEndpointPathCollide: { - title: 'Prerendered dynamic endpoint has path collision.', - message: (pathname: string) => - `Could not render \`${pathname}\` with an \`undefined\` param as the generated path will collide during prerendering. Prevent passing \`undefined\` as \`params\` for the endpoint's \`getStaticPaths()\` function, or add an additional extension to the endpoint's filename.`, - hint: (filename: string) => - `Rename \`${filename}\` to \`${filename.replace(/\.(js|ts)/, (m) => `.json` + m)}\``, - }, - /** - * @docs - * @see - * - [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) - * @description - * An image's `src` property is not valid. The Image component requires the `src` attribute to be either an image that has been ESM imported or a string. This is also true for the first parameter of `getImage()`. - * - * ```astro - * --- - * import { Image } from "astro:assets"; - * import myImage from "../assets/my_image.png"; - * --- - * - * ... - * ... - * ``` - * - * In most cases, this error happens when the value passed to `src` is undefined. - */ - ExpectedImage: { - title: 'Expected src to be an image.', - message: (options: string) => - `Expected \`src\` property to be either an ESM imported image or a string with the path of a remote image. Received \`${options}\`.`, - hint: 'This error can often happen because of a wrong path. Make sure the path to your image is correct.', - }, - /** - * @docs - * @see - * - [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) - * @description - * `getImage()`'s first parameter should be an object with the different properties to apply to your image. - * - * ```ts - * import { getImage } from "astro:assets"; - * import myImage from "../assets/my_image.png"; - * - * const optimizedImage = await getImage({src: myImage, width: 300, height: 300}); - * ``` - * - * In most cases, this error happens because parameters were passed directly instead of inside an object. - */ - ExpectedImageOptions: { - title: 'Expected image options.', - message: (options: string) => - `Expected getImage() parameter to be an object. Received \`${options}\`.`, - }, - /** - * @docs - * @message - * Could not find requested image `IMAGE_PATH` at `FULL_IMAGE_PATH`. - * @see - * - [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) - * @description - * Astro could not find an image you included in your Markdown content. Usually, this is simply caused by a typo in the path. - * - * Images in Markdown are relative to the current file. To refer to an image that is located in the same folder as the `.md` file, the path should start with `./` - */ - MarkdownImageNotFound: { - title: 'Image not found.', - message: (imagePath: string, fullImagePath: string | undefined) => - `Could not find requested image \`${imagePath}\`${ - fullImagePath ? ` at \`${fullImagePath}\`.` : '.' - }`, - hint: 'This is often caused by a typo in the image path. Please make sure the file exists, and is spelled correctly.', - }, - /** - * @docs - * @description - * Making changes to the response, such as setting headers, cookies, and the status code cannot be done outside of page components. - */ - ResponseSentError: { - title: 'Unable to set response.', - message: 'The response has already been sent to the browser and cannot be altered.', - }, +} satisfies ErrorData; +/** + * @docs + * @see + * - [Named slots](https://docs.astro.build/en/core-concepts/astro-components/#named-slots) + * @description + * Certain words cannot be used for slot names due to being already used internally. + */ +export const ReservedSlotName = { + name: 'ReservedSlotName', + title: 'Invalid slot name.', + message: (slotName: string) => + `Unable to create a slot named \`${slotName}\`. \`${slotName}\` is a reserved slot name. Please update the name of this slot.`, +} satisfies ErrorData; +/** + * @docs + * @see + * - [Server-side Rendering](https://docs.astro.build/en/guides/server-side-rendering/) + * - [Adding an Adapter](https://docs.astro.build/en/guides/server-side-rendering/#adding-an-adapter) + * @description + * To use server-side rendering, an adapter needs to be installed so Astro knows how to generate the proper output for your targeted deployment platform. + */ +export const NoAdapterInstalled = { + name: 'NoAdapterInstalled', + title: 'Cannot use Server-side Rendering without an adapter.', + message: `Cannot use \`output: 'server'\` or \`output: 'hybrid'\` without an adapter. Please install and configure the appropriate server adapter for your final deployment.`, + hint: 'See https://docs.astro.build/en/guides/server-side-rendering/ for more information.', +} satisfies ErrorData; +/** + * @docs + * @description + * No import statement was found for one of the components. If there is an import statement, make sure you are using the same identifier in both the imports and the component usage. + */ +export const NoMatchingImport = { + name: 'NoMatchingImport', + title: 'No import found for component.', + message: (componentName: string) => + `Could not render \`${componentName}\`. No matching import has been found for \`${componentName}\`.`, + hint: 'Please make sure the component is properly imported.', +} satisfies ErrorData; +/** + * @docs + * @message + * **Example error messages:**
+ * InvalidPrerenderExport: A `prerender` export has been detected, but its value cannot be statically analyzed. + * @description + * The `prerender` feature only supports a subset of valid JavaScript — be sure to use exactly `export const prerender = true` so that our compiler can detect this directive at build time. Variables, `let`, and `var` declarations are not supported. + */ +export const InvalidPrerenderExport = { + name: 'InvalidPrerenderExport', + title: 'Invalid prerender export.', + message: (prefix: string, suffix: string, isHydridOuput: boolean) => { + const defaultExpectedValue = isHydridOuput ? 'false' : 'true'; + let msg = `A \`prerender\` export has been detected, but its value cannot be statically analyzed.`; + if (prefix !== 'const') msg += `\nExpected \`const\` declaration but got \`${prefix}\`.`; + if (suffix !== 'true') + msg += `\nExpected \`${defaultExpectedValue}\` value but got \`${suffix}\`.`; + return msg; + }, + hint: 'Mutable values declared at runtime are not supported. Please make sure to use exactly `export const prerender = true`.', +} satisfies ErrorData; +/** + * @docs + * @message + * **Example error messages:**
+ * InvalidComponentArgs: Invalid arguments passed to `` component. + * @description + * Astro components cannot be rendered manually via a function call, such as `Component()` or `{items.map(Component)}`. Prefer the component syntax `` or `{items.map(item => )}`. + */ +export const InvalidComponentArgs = { + name: 'InvalidComponentArgs', + title: 'Invalid component arguments.', + message: (name: string) => `Invalid arguments passed to${name ? ` <${name}>` : ''} component.`, + hint: 'Astro components cannot be rendered directly via function call, such as `Component()` or `{items.map(Component)}`.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [Pagination](https://docs.astro.build/en/core-concepts/routing/#pagination) + * @description + * The page number parameter was not found in your filepath. + */ +export const PageNumberParamNotFound = { + name: 'PageNumberParamNotFound', + title: 'Page number param not found.', + message: (paramName: string) => + `[paginate()] page number param \`${paramName}\` not found in your filepath.`, + hint: 'Rename your file to `[page].astro` or `[...page].astro`.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) + * - [Image component](https://docs.astro.build/en/guides/assets/#image--astroassets) + * - [Image component#alt](https://docs.astro.build/en/guides/assets/#alt-required) + * @description + * The `alt` property allows you to provide descriptive alt text to users of screen readers and other assistive technologies. In order to ensure your images are accessible, the `Image` component requires that an `alt` be specified. + * + * If the image is merely decorative (i.e. doesn’t contribute to the understanding of the page), set `alt=""` so that screen readers know to ignore the image. + */ +export const ImageMissingAlt = { + name: 'ImageMissingAlt', + title: 'Missing alt property.', + message: 'The alt property is required.', + hint: "The `alt` property is important for the purpose of accessibility, without it users using screen readers or other assistive technologies won't be able to understand what your image is supposed to represent. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-alt for more information.", +} satisfies ErrorData; +/** + * @docs + * @see + * - [Image Service API](https://docs.astro.build/en/reference/image-service-reference/) + * @description + * There was an error while loading the configured image service. This can be caused by various factors, such as your image service not properly exporting a compatible object in its default export, or an incorrect path. + * + * If you believe that your service is properly configured and this error is wrong, please [open an issue](https://astro.build/issues/). + */ +export const InvalidImageService = { + name: 'InvalidImageService', + title: 'Error while loading image service.', + message: + 'There was an error loading the configured image service. Please see the stack trace for more information.', +} satisfies ErrorData; +/** + * @docs + * @message + * Missing width and height attributes for `IMAGE_URL`. When using remote images, both dimensions are always required in order to avoid cumulative layout shift (CLS). + * @see + * - [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) + * - [Image component#width-and-height](https://docs.astro.build/en/guides/assets/#width-and-height) + * @description + * For remote images, `width` and `height` cannot be inferred from the original file. As such, in order to avoid CLS, those two properties are always required. + * + * If your image is inside your `src` folder, you probably meant to import it instead. See [the Imports guide for more information](https://docs.astro.build/en/guides/imports/#other-assets). + */ +export const MissingImageDimension = { + name: 'MissingImageDimension', + title: 'Missing image dimensions', + message: (missingDimension: 'width' | 'height' | 'both', imageURL: string) => + `Missing ${ + missingDimension === 'both' ? 'width and height attributes' : `${missingDimension} attribute` + } for ${imageURL}. When using remote images, both dimensions are always required in order to avoid CLS.`, + hint: 'If your image is inside your `src` folder, you probably meant to import it instead. See [the Imports guide for more information](https://docs.astro.build/en/guides/imports/#other-assets).', +} satisfies ErrorData; +/** + * @docs + * @description + * The built-in image services do not currently support optimizing all image formats. + * + * For unsupported formats such as SVGs and GIFs, you may be able to use an `img` tag directly: + * ```astro + * --- + * import rocket from '../assets/images/rocket.svg'; + * --- + * + * A rocketship in space. + * ``` + */ +export const UnsupportedImageFormat = { + name: 'UnsupportedImageFormat', + title: 'Unsupported image format', + message: (format: string, imagePath: string, supportedFormats: readonly string[]) => + `Received unsupported format \`${format}\` from \`${imagePath}\`. Currently only ${supportedFormats.join( + ', ' + )} are supported by our image services.`, + hint: "Using an `img` tag directly instead of the `Image` component might be what you're looking for.", +} satisfies ErrorData; +/** + * @docs + * @see + * - [`getStaticPaths()`](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + * - [`params`](https://docs.astro.build/en/reference/api-reference/#params) + * @description + * The endpoint is prerendered with an `undefined` param so the generated path will collide with another route. + * + * If you cannot prevent passing `undefined`, then an additional extension can be added to the endpoint file name to generate the file with a different name. For example, renaming `pages/api/[slug].ts` to `pages/api/[slug].json.ts`. + */ +export const PrerenderDynamicEndpointPathCollide = { + name: 'PrerenderDynamicEndpointPathCollide', + title: 'Prerendered dynamic endpoint has path collision.', + message: (pathname: string) => + `Could not render \`${pathname}\` with an \`undefined\` param as the generated path will collide during prerendering. Prevent passing \`undefined\` as \`params\` for the endpoint's \`getStaticPaths()\` function, or add an additional extension to the endpoint's filename.`, + hint: (filename: string) => + `Rename \`${filename}\` to \`${filename.replace(/\.(js|ts)/, (m) => `.json` + m)}\``, +} satisfies ErrorData; +/** + * @docs + * @see + * - [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) + * @description + * An image's `src` property is not valid. The Image component requires the `src` attribute to be either an image that has been ESM imported or a string. This is also true for the first parameter of `getImage()`. + * + * ```astro + * --- + * import { Image } from "astro:assets"; + * import myImage from "../assets/my_image.png"; + * --- + * + * ... + * ... + * ``` + * + * In most cases, this error happens when the value passed to `src` is undefined. + */ +export const ExpectedImage = { + name: 'ExpectedImage', + title: 'Expected src to be an image.', + message: (options: string) => + `Expected \`src\` property to be either an ESM imported image or a string with the path of a remote image. Received \`${options}\`.`, + hint: 'This error can often happen because of a wrong path. Make sure the path to your image is correct.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) + * @description + * `getImage()`'s first parameter should be an object with the different properties to apply to your image. + * + * ```ts + * import { getImage } from "astro:assets"; + * import myImage from "../assets/my_image.png"; + * + * const optimizedImage = await getImage({src: myImage, width: 300, height: 300}); + * ``` + * + * In most cases, this error happens because parameters were passed directly instead of inside an object. + */ +export const ExpectedImageOptions = { + name: 'ExpectedImageOptions', + title: 'Expected image options.', + message: (options: string) => + `Expected getImage() parameter to be an object. Received \`${options}\`.`, +} satisfies ErrorData; +/** + * @docs + * @message + * Could not find requested image `IMAGE_PATH` at `FULL_IMAGE_PATH`. + * @see + * - [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) + * @description + * Astro could not find an image you included in your Markdown content. Usually, this is simply caused by a typo in the path. + * + * Images in Markdown are relative to the current file. To refer to an image that is located in the same folder as the `.md` file, the path should start with `./` + */ +export const MarkdownImageNotFound = { + name: 'MarkdownImageNotFound', + title: 'Image not found.', + message: (imagePath: string, fullImagePath: string | undefined) => + `Could not find requested image \`${imagePath}\`${ + fullImagePath ? ` at \`${fullImagePath}\`.` : '.' + }`, + hint: 'This is often caused by a typo in the image path. Please make sure the file exists, and is spelled correctly.', +} satisfies ErrorData; +/** + * @docs + * @description + * Making changes to the response, such as setting headers, cookies, and the status code cannot be done outside of page components. + */ +export const ResponseSentError = { + name: 'ResponseSentError', + title: 'Unable to set response.', + message: 'The response has already been sent to the browser and cannot be altered.', +} satisfies ErrorData; - /** - * @docs - * @description - * Thrown when the middleware does not return any data or call the `next` function. - * - * For example: - * ```ts - * import {defineMiddleware} from "astro/middleware"; - * export const onRequest = defineMiddleware((context, _) => { - * // doesn't return anything or call `next` - * context.locals.someData = false; - * }); - * ``` - */ - MiddlewareNoDataOrNextCalled: { - title: "The middleware didn't return a response or call `next`.", - message: - 'The middleware needs to either return a `Response` object or call the `next` function.', - }, +/** + * @docs + * @description + * Thrown when the middleware does not return any data or call the `next` function. + * + * For example: + * ```ts + * import {defineMiddleware} from "astro/middleware"; + * export const onRequest = defineMiddleware((context, _) => { + * // doesn't return anything or call `next` + * context.locals.someData = false; + * }); + * ``` + */ +export const MiddlewareNoDataOrNextCalled = { + name: 'MiddlewareNoDataOrNextCalled', + title: "The middleware didn't return a response or call `next`.", + message: 'The middleware needs to either return a `Response` object or call the `next` function.', +} satisfies ErrorData; - /** - * @docs - * @description - * Thrown in development mode when middleware returns something that is not a `Response` object. - * - * For example: - * ```ts - * import {defineMiddleware} from "astro/middleware"; - * export const onRequest = defineMiddleware(() => { - * return "string" - * }); - * ``` - */ - MiddlewareNotAResponse: { - title: 'The middleware returned something that is not a `Response` object.', - message: 'Any data returned from middleware must be a valid `Response` object.', - }, +/** + * @docs + * @description + * Thrown in development mode when middleware returns something that is not a `Response` object. + * + * For example: + * ```ts + * import {defineMiddleware} from "astro/middleware"; + * export const onRequest = defineMiddleware(() => { + * return "string" + * }); + * ``` + */ +export const MiddlewareNotAResponse = { + name: 'MiddlewareNotAResponse', + title: 'The middleware returned something that is not a `Response` object.', + message: 'Any data returned from middleware must be a valid `Response` object.', +} satisfies ErrorData; - /** - * @docs - * @description - * - * Thrown in development mode when `locals` is overwritten with something that is not an object - * - * For example: - * ```ts - * import {defineMiddleware} from "astro/middleware"; - * export const onRequest = defineMiddleware((context, next) => { - * context.locals = 1541; - * return next(); - * }); - * ``` - */ - LocalsNotAnObject: { - title: 'Value assigned to `locals` is not accepted.', - message: - '`locals` can only be assigned to an object. Other values like numbers, strings, etc. are not accepted.', - hint: 'If you tried to remove some information from the `locals` object, try to use `delete` or set the property to `undefined`.', - }, - /** - * @docs - * @see - * - [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) - * @description - * When using the default image services, `Image`'s and `getImage`'s `src` parameter must be either an imported image or an URL, it cannot be a filepath. - * - * ```astro - * --- - * import { Image } from "astro:assets"; - * import myImage from "../my_image.png"; - * --- - * - * - * Cool image - * - * - * Cool image - * ``` - */ - LocalImageUsedWrongly: { - title: 'ESM imported images must be passed as-is.', - message: (imageFilePath: string) => - `\`Image\`'s and \`getImage\`'s \`src\` parameter must be an imported image or an URL, it cannot be a filepath. Received \`${imageFilePath}\`.`, - }, +/** + * @docs + * @description + * + * Thrown in development mode when `locals` is overwritten with something that is not an object + * + * For example: + * ```ts + * import {defineMiddleware} from "astro/middleware"; + * export const onRequest = defineMiddleware((context, next) => { + * context.locals = 1541; + * return next(); + * }); + * ``` + */ +export const LocalsNotAnObject = { + name: 'LocalsNotAnObject', + title: 'Value assigned to `locals` is not accepted.', + message: + '`locals` can only be assigned to an object. Other values like numbers, strings, etc. are not accepted.', + hint: 'If you tried to remove some information from the `locals` object, try to use `delete` or set the property to `undefined`.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [Assets (Experimental)](https://docs.astro.build/en/guides/assets/) + * @description + * When using the default image services, `Image`'s and `getImage`'s `src` parameter must be either an imported image or an URL, it cannot be a filepath. + * + * ```astro + * --- + * import { Image } from "astro:assets"; + * import myImage from "../my_image.png"; + * --- + * + * + * Cool image + * + * + * Cool image + * ``` + */ +export const LocalImageUsedWrongly = { + name: 'LocalImageUsedWrongly', + title: 'ESM imported images must be passed as-is.', + message: (imageFilePath: string) => + `\`Image\`'s and \`getImage\`'s \`src\` parameter must be an imported image or an URL, it cannot be a filepath. Received \`${imageFilePath}\`.`, +} satisfies ErrorData; - /** - * @docs - * @see - * - [Astro.glob](https://docs.astro.build/en/reference/api-reference/#astroglob) - * @description - * `Astro.glob()` can only be used in `.astro` files. You can use [`import.meta.glob()`](https://vitejs.dev/guide/features.html#glob-import) instead to acheive the same result. - */ - AstroGlobUsedOutside: { - title: 'Astro.glob() used outside of an Astro file.', - message: (globStr: string) => - `\`Astro.glob(${globStr})\` can only be used in \`.astro\` files. \`import.meta.glob(${globStr})\` can be used instead to achieve a similar result.`, - hint: "See Vite's documentation on `import.meta.glob` for more information: https://vitejs.dev/guide/features.html#glob-import", - }, +/** + * @docs + * @see + * - [Astro.glob](https://docs.astro.build/en/reference/api-reference/#astroglob) + * @description + * `Astro.glob()` can only be used in `.astro` files. You can use [`import.meta.glob()`](https://vitejs.dev/guide/features.html#glob-import) instead to acheive the same result. + */ +export const AstroGlobUsedOutside = { + name: 'AstroGlobUsedOutside', + title: 'Astro.glob() used outside of an Astro file.', + message: (globStr: string) => + `\`Astro.glob(${globStr})\` can only be used in \`.astro\` files. \`import.meta.glob(${globStr})\` can be used instead to achieve a similar result.`, + hint: "See Vite's documentation on `import.meta.glob` for more information: https://vitejs.dev/guide/features.html#glob-import", +} satisfies ErrorData; - /** - * @docs - * @see - * - [Astro.glob](https://docs.astro.build/en/reference/api-reference/#astroglob) - * @description - * `Astro.glob()` did not return any matching files. There might be a typo in the glob pattern. - */ - AstroGlobNoMatch: { - title: 'Astro.glob() did not match any files.', - message: (globStr: string) => - `\`Astro.glob(${globStr})\` did not return any matching files. Check the pattern for typos.`, - }, - /** - * @docs - * @see - * - [Astro.redirect](https://docs.astro.build/en/reference/api-reference/#astroredirect) - * @description - * A redirect must be given a location with the `Location` header. - */ - RedirectWithNoLocation: { - title: 'A redirect must be given a location with the `Location` header.', - }, - /** - * @docs - * @see - * - [Dynamic routes](https://docs.astro.build/en/core-concepts/routing/#dynamic-routes) - * @description - * A dynamic route param is invalid. This is often caused by an `undefined` parameter or a missing [rest parameter](https://docs.astro.build/en/core-concepts/routing/#rest-parameters). - */ - InvalidDynamicRoute: { - title: 'Invalid dynamic route.', - message: (route: string, invalidParam: string, received: string) => - `The ${invalidParam} param for route ${route} is invalid. Received **${received}**.`, - }, - // No headings here, that way Vite errors are merged with Astro ones in the docs, which makes more sense to users. - // Vite Errors - 4xxx - /** - * @docs - * @see - * - [Vite troubleshooting guide](https://vitejs.dev/guide/troubleshooting.html) - * @description - * Vite encountered an unknown error while rendering your project. We unfortunately do not know what happened (or we would tell you!) - * - * If you can reliably cause this error to happen, we'd appreciate if you could [open an issue](https://astro.build/issues/) - */ - UnknownViteError: { - title: 'Unknown Vite Error.', - }, - /** - * @docs - * @see - * - [Type Imports](https://docs.astro.build/en/guides/typescript/#type-imports) - * @description - * Astro could not import the requested file. Oftentimes, this is caused by the import path being wrong (either because the file does not exist, or there is a typo in the path) - * - * This message can also appear when a type is imported without specifying that it is a [type import](https://docs.astro.build/en/guides/typescript/#type-imports). - */ - FailedToLoadModuleSSR: { - title: 'Could not import file.', - message: (importName: string) => `Could not import \`${importName}\`.`, - hint: 'This is often caused by a typo in the import path. Please make sure the file exists.', - }, - /** - * @docs - * @see - * - [Glob Patterns](https://docs.astro.build/en/guides/imports/#glob-patterns) - * @description - * Astro encountered an invalid glob pattern. This is often caused by the glob pattern not being a valid file path. - */ - InvalidGlob: { - title: 'Invalid glob pattern.', - message: (globPattern: string) => - `Invalid glob pattern: \`${globPattern}\`. Glob patterns must start with './', '../' or '/'.`, - hint: 'See https://docs.astro.build/en/guides/imports/#glob-patterns for more information on supported glob patterns.', - }, - /** - * @docs - * @description - * Astro couldn't find the correct page to render, probably because it wasn't correctly mapped for SSR usage. This is an internal error. - */ - FailedToFindPageMapSSR: { - title: "Astro couldn't find the correct page to render", - message: - "Astro couldn't find the correct page to render, probably because it wasn't correctly mapped for SSR usage. This is an internal error. Please file an issue.", - }, - /** - * @docs - * @kind heading - * @name CSS Errors - */ - // CSS Errors - 5xxx - /** - * @docs - * @see - * - [Styles and CSS](https://docs.astro.build/en/guides/styling/) - * @description - * Astro encountered an unknown error while parsing your CSS. Oftentimes, this is caused by a syntax error and the error message should contain more information. - */ - UnknownCSSError: { - title: 'Unknown CSS Error.', - }, - /** - * @docs - * @message - * **Example error messages:**
- * CSSSyntaxError: Missed semicolon
- * CSSSyntaxError: Unclosed string
- * @description - * Astro encountered an error while parsing your CSS, due to a syntax error. This is often caused by a missing semicolon. - */ - CSSSyntaxError: { - title: 'CSS Syntax Error.', - }, - /** - * @docs - * @kind heading - * @name Markdown Errors - */ - // Markdown Errors - 6xxx - /** - * @docs - * @description - * Astro encountered an unknown error while parsing your Markdown. Oftentimes, this is caused by a syntax error and the error message should contain more information. - */ - UnknownMarkdownError: { - title: 'Unknown Markdown Error.', - }, - /** - * @docs - * @message - * **Example error messages:**
- * can not read an implicit mapping pair; a colon is missed
- * unexpected end of the stream within a double quoted scalar
- * can not read a block mapping entry; a multiline key may not be an implicit key - * @description - * Astro encountered an error while parsing the frontmatter of your Markdown file. - * This is often caused by a mistake in the syntax, such as a missing colon or a missing end quote. - */ - MarkdownFrontmatterParseError: { - title: 'Failed to parse Markdown frontmatter.', - }, - /** - * @docs - * @see - * - [Modifying frontmatter programmatically](https://docs.astro.build/en/guides/markdown-content/#modifying-frontmatter-programmatically) - * @description - * A remark or rehype plugin attempted to inject invalid frontmatter. This occurs when "astro.frontmatter" is set to `null`, `undefined`, or an invalid JSON object. - */ - InvalidFrontmatterInjectionError: { - title: 'Invalid frontmatter injection.', - message: - 'A remark or rehype plugin attempted to inject invalid frontmatter. Ensure "astro.frontmatter" is set to a valid JSON object that is not `null` or `undefined`.', - hint: 'See the frontmatter injection docs https://docs.astro.build/en/guides/markdown-content/#modifying-frontmatter-programmatically for more information.', - }, - /** - * @docs - * @see - * - [MDX installation and usage](https://docs.astro.build/en/guides/integrations-guide/mdx/) - * @description - * Unable to find the official `@astrojs/mdx` integration. This error is raised when using MDX files without an MDX integration installed. - */ - MdxIntegrationMissingError: { - title: 'MDX integration missing.', - message: (file: string) => - `Unable to render ${file}. Ensure that the \`@astrojs/mdx\` integration is installed.`, - hint: 'See the MDX integration docs for installation and usage instructions: https://docs.astro.build/en/guides/integrations-guide/mdx/', - }, - // Config Errors - 7xxx - /** - * @docs - * @see - * - [Configuration Reference](https://docs.astro.build/en/reference/configuration-reference/) - * @description - * Astro encountered an unknown error loading your Astro configuration file. - * This is often caused by a syntax error in your config and the message should offer more information. - * - * If you can reliably cause this error to happen, we'd appreciate if you could [open an issue](https://astro.build/issues/) - */ - UnknownConfigError: { - title: 'Unknown configuration error.', - }, - /** - * @docs - * @see - * - [--config](https://docs.astro.build/en/reference/cli-reference/#--config-path) - * @description - * The specified configuration file using `--config` could not be found. Make sure that it exists or that the path is correct - */ - ConfigNotFound: { - title: 'Specified configuration file not found.', - message: (configFile: string) => - `Unable to resolve \`--config "${configFile}"\`. Does the file exist?`, - }, - /** - * @docs - * @see - * - [Configuration reference](https://docs.astro.build/en/reference/configuration-reference/) - * @description - * Astro detected a legacy configuration option in your configuration file. - */ - ConfigLegacyKey: { - title: 'Legacy configuration detected.', - message: (legacyConfigKey: string) => `Legacy configuration detected: \`${legacyConfigKey}\`.`, - hint: 'Please update your configuration to the new format.\nSee https://astro.build/config for more information.', - }, - /** - * @docs - * @kind heading - * @name CLI Errors - */ - // CLI Errors - 8xxx - /** - * @docs - * @description - * Astro encountered an unknown error while starting one of its CLI commands. The error message should contain more information. - * - * If you can reliably cause this error to happen, we'd appreciate if you could [open an issue](https://astro.build/issues/) - */ - UnknownCLIError: { - title: 'Unknown CLI Error.', - }, - /** - * @docs - * @description - * `astro sync` command failed to generate content collection types. - * @see - * - [Content collections documentation](https://docs.astro.build/en/guides/content-collections/) - */ - GenerateContentTypesError: { - title: 'Failed to generate content types.', - message: (errorMessage: string) => - `\`astro sync\` command failed to generate content collection types: ${errorMessage}`, - hint: 'Check your `src/content/config.*` file for typos.', - }, - /** - * @docs - * @kind heading - * @name Content Collection Errors - */ - // Content Collection Errors - 9xxx - /** - * @docs - * @description - * Astro encountered an unknown error loading your content collections. - * This can be caused by certain errors inside your `src/content/config.ts` file or some internal errors. - * - * If you can reliably cause this error to happen, we'd appreciate if you could [open an issue](https://astro.build/issues/) - */ - UnknownContentCollectionError: { - title: 'Unknown Content Collection Error.', - }, - /** - * @docs - * @message - * **Example error message:**
- * **blog** → **post.md** frontmatter does not match collection schema.
- * "title" is required.
- * "date" must be a valid date. - * @description - * A Markdown or MDX entry in `src/content/` does not match its collection schema. - * Make sure that all required fields are present, and that all fields are of the correct type. - * You can check against the collection schema in your `src/content/config.*` file. - * See the [Content collections documentation](https://docs.astro.build/en/guides/content-collections/) for more information. - */ - InvalidContentEntryFrontmatterError: { - title: 'Content entry frontmatter does not match schema.', - message: (collection: string, entryId: string, error: ZodError) => { - return [ - `**${String(collection)} → ${String( - entryId - )}** frontmatter does not match collection schema.`, - ...error.errors.map((zodError) => zodError.message), - ].join('\n'); - }, - hint: 'See https://docs.astro.build/en/guides/content-collections/ for more information on content schemas.', - }, - /** - * @docs - * @message `COLLECTION_NAME` → `ENTRY_ID` has an invalid slug. `slug` must be a string. - * @see - * - [The reserved entry `slug` field](https://docs.astro.build/en/guides/content-collections/) - * @description - * An entry in `src/content/` has an invalid `slug`. This field is reserved for generating entry slugs, and must be a string when present. - */ - InvalidContentEntrySlugError: { - title: 'Invalid content entry slug.', - message: (collection: string, entryId: string) => { - return `${String(collection)} → ${String( +/** + * @docs + * @see + * - [Astro.glob](https://docs.astro.build/en/reference/api-reference/#astroglob) + * @description + * `Astro.glob()` did not return any matching files. There might be a typo in the glob pattern. + */ +export const AstroGlobNoMatch = { + name: 'AstroGlobNoMatch', + title: 'Astro.glob() did not match any files.', + message: (globStr: string) => + `\`Astro.glob(${globStr})\` did not return any matching files. Check the pattern for typos.`, +} satisfies ErrorData; +/** + * @docs + * @see + * - [Astro.redirect](https://docs.astro.build/en/reference/api-reference/#astroredirect) + * @description + * A redirect must be given a location with the `Location` header. + */ +export const RedirectWithNoLocation = { + name: 'RedirectWithNoLocation', + title: 'A redirect must be given a location with the `Location` header.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [Dynamic routes](https://docs.astro.build/en/core-concepts/routing/#dynamic-routes) + * @description + * A dynamic route param is invalid. This is often caused by an `undefined` parameter or a missing [rest parameter](https://docs.astro.build/en/core-concepts/routing/#rest-parameters). + */ +export const InvalidDynamicRoute = { + name: 'InvalidDynamicRoute', + title: 'Invalid dynamic route.', + message: (route: string, invalidParam: string, received: string) => + `The ${invalidParam} param for route ${route} is invalid. Received **${received}**.`, +} satisfies ErrorData; +// No headings here, that way Vite errors are merged with Astro ones in the docs, which makes more sense to users. +// Vite Errors - 4xxx +/** + * @docs + * @see + * - [Vite troubleshooting guide](https://vitejs.dev/guide/troubleshooting.html) + * @description + * Vite encountered an unknown error while rendering your project. We unfortunately do not know what happened (or we would tell you!) + * + * If you can reliably cause this error to happen, we'd appreciate if you could [open an issue](https://astro.build/issues/) + */ +export const UnknownViteError = { + name: 'UnknownViteError', + title: 'Unknown Vite Error.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [Type Imports](https://docs.astro.build/en/guides/typescript/#type-imports) + * @description + * Astro could not import the requested file. Oftentimes, this is caused by the import path being wrong (either because the file does not exist, or there is a typo in the path) + * + * This message can also appear when a type is imported without specifying that it is a [type import](https://docs.astro.build/en/guides/typescript/#type-imports). + */ +export const FailedToLoadModuleSSR = { + name: 'FailedToLoadModuleSSR', + title: 'Could not import file.', + message: (importName: string) => `Could not import \`${importName}\`.`, + hint: 'This is often caused by a typo in the import path. Please make sure the file exists.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [Glob Patterns](https://docs.astro.build/en/guides/imports/#glob-patterns) + * @description + * Astro encountered an invalid glob pattern. This is often caused by the glob pattern not being a valid file path. + */ +export const InvalidGlob = { + name: 'InvalidGlob', + title: 'Invalid glob pattern.', + message: (globPattern: string) => + `Invalid glob pattern: \`${globPattern}\`. Glob patterns must start with './', '../' or '/'.`, + hint: 'See https://docs.astro.build/en/guides/imports/#glob-patterns for more information on supported glob patterns.', +} satisfies ErrorData; +/** + * @docs + * @description + * Astro couldn't find the correct page to render, probably because it wasn't correctly mapped for SSR usage. This is an internal error. + */ +export const FailedToFindPageMapSSR = { + name: 'FailedToFindPageMapSSR', + title: "Astro couldn't find the correct page to render", + message: + "Astro couldn't find the correct page to render, probably because it wasn't correctly mapped for SSR usage. This is an internal error. Please file an issue.", +} satisfies ErrorData; +/** + * @docs + * @kind heading + * @name CSS Errors + */ +// CSS Errors - 5xxx +/** + * @docs + * @see + * - [Styles and CSS](https://docs.astro.build/en/guides/styling/) + * @description + * Astro encountered an unknown error while parsing your CSS. Oftentimes, this is caused by a syntax error and the error message should contain more information. + */ +export const UnknownCSSError = { + name: 'UnknownCSSError', + title: 'Unknown CSS Error.', +} satisfies ErrorData; +/** + * @docs + * @message + * **Example error messages:**
+ * CSSSyntaxError: Missed semicolon
+ * CSSSyntaxError: Unclosed string
+ * @description + * Astro encountered an error while parsing your CSS, due to a syntax error. This is often caused by a missing semicolon. + */ +export const CSSSyntaxError = { + name: 'CSSSyntaxError', + title: 'CSS Syntax Error.', +} satisfies ErrorData; +/** + * @docs + * @kind heading + * @name Markdown Errors + */ +// Markdown Errors - 6xxx +/** + * @docs + * @description + * Astro encountered an unknown error while parsing your Markdown. Oftentimes, this is caused by a syntax error and the error message should contain more information. + */ +export const UnknownMarkdownError = { + name: 'UnknownMarkdownError', + title: 'Unknown Markdown Error.', +} satisfies ErrorData; +/** + * @docs + * @message + * **Example error messages:**
+ * can not read an implicit mapping pair; a colon is missed
+ * unexpected end of the stream within a double quoted scalar
+ * can not read a block mapping entry; a multiline key may not be an implicit key + * @description + * Astro encountered an error while parsing the frontmatter of your Markdown file. + * This is often caused by a mistake in the syntax, such as a missing colon or a missing end quote. + */ +export const MarkdownFrontmatterParseError = { + name: 'MarkdownFrontmatterParseError', + title: 'Failed to parse Markdown frontmatter.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [Modifying frontmatter programmatically](https://docs.astro.build/en/guides/markdown-content/#modifying-frontmatter-programmatically) + * @description + * A remark or rehype plugin attempted to inject invalid frontmatter. This occurs when "astro.frontmatter" is set to `null`, `undefined`, or an invalid JSON object. + */ +export const InvalidFrontmatterInjectionError = { + name: 'InvalidFrontmatterInjectionError', + title: 'Invalid frontmatter injection.', + message: + 'A remark or rehype plugin attempted to inject invalid frontmatter. Ensure "astro.frontmatter" is set to a valid JSON object that is not `null` or `undefined`.', + hint: 'See the frontmatter injection docs https://docs.astro.build/en/guides/markdown-content/#modifying-frontmatter-programmatically for more information.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [MDX installation and usage](https://docs.astro.build/en/guides/integrations-guide/mdx/) + * @description + * Unable to find the official `@astrojs/mdx` integration. This error is raised when using MDX files without an MDX integration installed. + */ +export const MdxIntegrationMissingError = { + name: 'MdxIntegrationMissingError', + title: 'MDX integration missing.', + message: (file: string) => + `Unable to render ${file}. Ensure that the \`@astrojs/mdx\` integration is installed.`, + hint: 'See the MDX integration docs for installation and usage instructions: https://docs.astro.build/en/guides/integrations-guide/mdx/', +} satisfies ErrorData; +// Config Errors - 7xxx +/** + * @docs + * @see + * - [Configuration Reference](https://docs.astro.build/en/reference/configuration-reference/) + * @description + * Astro encountered an unknown error loading your Astro configuration file. + * This is often caused by a syntax error in your config and the message should offer more information. + * + * If you can reliably cause this error to happen, we'd appreciate if you could [open an issue](https://astro.build/issues/) + */ +export const UnknownConfigError = { + name: 'UnknownConfigError', + title: 'Unknown configuration error.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [--config](https://docs.astro.build/en/reference/cli-reference/#--config-path) + * @description + * The specified configuration file using `--config` could not be found. Make sure that it exists or that the path is correct + */ +export const ConfigNotFound = { + name: 'ConfigNotFound', + title: 'Specified configuration file not found.', + message: (configFile: string) => + `Unable to resolve \`--config "${configFile}"\`. Does the file exist?`, +} satisfies ErrorData; +/** + * @docs + * @see + * - [Configuration reference](https://docs.astro.build/en/reference/configuration-reference/) + * @description + * Astro detected a legacy configuration option in your configuration file. + */ +export const ConfigLegacyKey = { + name: 'ConfigLegacyKey', + title: 'Legacy configuration detected.', + message: (legacyConfigKey: string) => `Legacy configuration detected: \`${legacyConfigKey}\`.`, + hint: 'Please update your configuration to the new format.\nSee https://astro.build/config for more information.', +} satisfies ErrorData; +/** + * @docs + * @kind heading + * @name CLI Errors + */ +// CLI Errors - 8xxx +/** + * @docs + * @description + * Astro encountered an unknown error while starting one of its CLI commands. The error message should contain more information. + * + * If you can reliably cause this error to happen, we'd appreciate if you could [open an issue](https://astro.build/issues/) + */ +export const UnknownCLIError = { + name: 'UnknownCLIError', + title: 'Unknown CLI Error.', +} satisfies ErrorData; +/** + * @docs + * @description + * `astro sync` command failed to generate content collection types. + * @see + * - [Content collections documentation](https://docs.astro.build/en/guides/content-collections/) + */ +export const GenerateContentTypesError = { + name: 'GenerateContentTypesError', + title: 'Failed to generate content types.', + message: (errorMessage: string) => + `\`astro sync\` command failed to generate content collection types: ${errorMessage}`, + hint: 'Check your `src/content/config.*` file for typos.', +} satisfies ErrorData; +/** + * @docs + * @kind heading + * @name Content Collection Errors + */ +// Content Collection Errors - 9xxx +/** + * @docs + * @description + * Astro encountered an unknown error loading your content collections. + * This can be caused by certain errors inside your `src/content/config.ts` file or some internal errors. + * + * If you can reliably cause this error to happen, we'd appreciate if you could [open an issue](https://astro.build/issues/) + */ +export const UnknownContentCollectionError = { + name: 'UnknownContentCollectionError', + title: 'Unknown Content Collection Error.', +} satisfies ErrorData; +/** + * @docs + * @message + * **Example error message:**
+ * **blog** → **post.md** frontmatter does not match collection schema.
+ * "title" is required.
+ * "date" must be a valid date. + * @description + * A Markdown or MDX entry in `src/content/` does not match its collection schema. + * Make sure that all required fields are present, and that all fields are of the correct type. + * You can check against the collection schema in your `src/content/config.*` file. + * See the [Content collections documentation](https://docs.astro.build/en/guides/content-collections/) for more information. + */ +export const InvalidContentEntryFrontmatterError = { + name: 'InvalidContentEntryFrontmatterError', + title: 'Content entry frontmatter does not match schema.', + message: (collection: string, entryId: string, error: ZodError) => { + return [ + `**${String(collection)} → ${String( entryId - )} has an invalid slug. \`slug\` must be a string.`; - }, - hint: 'See https://docs.astro.build/en/guides/content-collections/ for more on the `slug` field.', - }, - /** - * @docs - * @see - * - [The reserved entry `slug` field](https://docs.astro.build/en/guides/content-collections/#defining-custom-slugs) - * @description - * A content collection schema should not contain the `slug` field. This is reserved by Astro for generating entry slugs. Remove `slug` from your schema. You can still use custom slugs in your frontmatter. - */ - ContentSchemaContainsSlugError: { - title: 'Content Schema should not contain `slug`.', - message: (collectionName: string) => - `A content collection schema should not contain \`slug\` since it is reserved for slug generation. Remove this from your ${collectionName} collection schema.`, - hint: 'See https://docs.astro.build/en/guides/content-collections/ for more on the `slug` field.', - }, + )}** frontmatter does not match collection schema.`, + ...error.errors.map((zodError) => zodError.message), + ].join('\n'); + }, + hint: 'See https://docs.astro.build/en/guides/content-collections/ for more information on content schemas.', +} satisfies ErrorData; +/** + * @docs + * @message `COLLECTION_NAME` → `ENTRY_ID` has an invalid slug. `slug` must be a string. + * @see + * - [The reserved entry `slug` field](https://docs.astro.build/en/guides/content-collections/) + * @description + * An entry in `src/content/` has an invalid `slug`. This field is reserved for generating entry slugs, and must be a string when present. + */ +export const InvalidContentEntrySlugError = { + name: 'InvalidContentEntrySlugError', + title: 'Invalid content entry slug.', + message: (collection: string, entryId: string) => { + return `${String(collection)} → ${String( + entryId + )} has an invalid slug. \`slug\` must be a string.`; + }, + hint: 'See https://docs.astro.build/en/guides/content-collections/ for more on the `slug` field.', +} satisfies ErrorData; +/** + * @docs + * @see + * - [The reserved entry `slug` field](https://docs.astro.build/en/guides/content-collections/#defining-custom-slugs) + * @description + * A content collection schema should not contain the `slug` field. This is reserved by Astro for generating entry slugs. Remove `slug` from your schema. You can still use custom slugs in your frontmatter. + */ +export const ContentSchemaContainsSlugError = { + name: 'ContentSchemaContainsSlugError', + title: 'Content Schema should not contain `slug`.', + message: (collectionName: string) => + `A content collection schema should not contain \`slug\` since it is reserved for slug generation. Remove this from your ${collectionName} collection schema.`, + hint: 'See https://docs.astro.build/en/guides/content-collections/ for more on the `slug` field.', +} satisfies ErrorData; - /** - * @docs - * @message A collection queried via `getCollection()` does not exist. - * @description - * When querying a collection, ensure a collection directory with the requested name exists under `src/content/`. - */ - CollectionDoesNotExistError: { - title: 'Collection does not exist', - message: (collectionName: string) => - `The collection **${collectionName}** does not exist. Ensure a collection directory with this name exists.`, - hint: 'See https://docs.astro.build/en/guides/content-collections/ for more on creating collections.', - }, - /** - * @docs - * @message `COLLECTION_NAME` contains a mix of content and data entries. All entries must be of the same type. - * @see - * - [Defining content collections](https://docs.astro.build/en/guides/content-collections/#defining-collections) - * @description - * A content collection cannot contain a mix of content and data entries. You must store entries in separate collections by type. - */ - MixedContentDataCollectionError: { - title: 'Content and data cannot be in same collection.', - message: (collection: string) => { - return `**${collection}** contains a mix of content and data entries. All entries must be of the same type.`; - }, - hint: 'Store data entries in a new collection separate from your content collection.', - }, - /** - * @docs - * @message `COLLECTION_NAME` contains entries of type `ACTUAL_TYPE`, but is configured as a `EXPECTED_TYPE` collection. - * @see - * - [Defining content collections](https://docs.astro.build/en/guides/content-collections/#defining-collections) - * @description - * Content collections must contain entries of the type configured. Collections are `type: 'content'` by default. Try adding `type: 'data'` to your collection config for data collections. - */ - ContentCollectionTypeMismatchError: { - title: 'Collection contains entries of a different type.', - message: (collection: string, expectedType: string, actualType: string) => { - return `${collection} contains ${expectedType} entries, but is configured as a ${actualType} collection.`; - }, - }, - /** - * @docs - * @message `COLLECTION_ENTRY_NAME` failed to parse. - * @description - * Collection entries of `type: 'data'` must return an object with valid JSON (for `.json` entries) or YAML (for `.yaml` entries). - */ - DataCollectionEntryParseError: { - title: 'Data collection entry failed to parse.', - message: (entryId: string, errorMessage: string) => { - return `**${entryId}** failed to parse: ${errorMessage}`; - }, - hint: 'Ensure your data entry is an object with valid JSON (for `.json` entries) or YAML (for `.yaml` entries).', - }, - /** - * @docs - * @message `COLLECTION_NAME` contains multiple entries with the same slug: `SLUG`. Slugs must be unique. - * @description - * Content collection entries must have unique slugs. Duplicates are often caused by the `slug` frontmatter property. - */ - DuplicateContentEntrySlugError: { - title: 'Duplicate content entry slug.', - message: (collection: string, slug: string) => { - return `**${collection}** contains multiple entries with the same slug: \`${slug}\`. Slugs must be unique.`; - }, - }, +/** + * @docs + * @message A collection queried via `getCollection()` does not exist. + * @description + * When querying a collection, ensure a collection directory with the requested name exists under `src/content/`. + */ +export const CollectionDoesNotExistError = { + name: 'CollectionDoesNotExistError', + title: 'Collection does not exist', + message: (collectionName: string) => + `The collection **${collectionName}** does not exist. Ensure a collection directory with this name exists.`, + hint: 'See https://docs.astro.build/en/guides/content-collections/ for more on creating collections.', +} satisfies ErrorData; +/** + * @docs + * @message `COLLECTION_NAME` contains a mix of content and data entries. All entries must be of the same type. + * @see + * - [Defining content collections](https://docs.astro.build/en/guides/content-collections/#defining-collections) + * @description + * A content collection cannot contain a mix of content and data entries. You must store entries in separate collections by type. + */ +export const MixedContentDataCollectionError = { + name: 'MixedContentDataCollectionError', + title: 'Content and data cannot be in same collection.', + message: (collection: string) => { + return `**${collection}** contains a mix of content and data entries. All entries must be of the same type.`; + }, + hint: 'Store data entries in a new collection separate from your content collection.', +} satisfies ErrorData; +/** + * @docs + * @message `COLLECTION_NAME` contains entries of type `ACTUAL_TYPE`, but is configured as a `EXPECTED_TYPE` collection. + * @see + * - [Defining content collections](https://docs.astro.build/en/guides/content-collections/#defining-collections) + * @description + * Content collections must contain entries of the type configured. Collections are `type: 'content'` by default. Try adding `type: 'data'` to your collection config for data collections. + */ +export const ContentCollectionTypeMismatchError = { + name: 'ContentCollectionTypeMismatchError', + title: 'Collection contains entries of a different type.', + message: (collection: string, expectedType: string, actualType: string) => { + return `${collection} contains ${expectedType} entries, but is configured as a ${actualType} collection.`; + }, +} satisfies ErrorData; +/** + * @docs + * @message `COLLECTION_ENTRY_NAME` failed to parse. + * @description + * Collection entries of `type: 'data'` must return an object with valid JSON (for `.json` entries) or YAML (for `.yaml` entries). + */ +export const DataCollectionEntryParseError = { + name: 'DataCollectionEntryParseError', + title: 'Data collection entry failed to parse.', + message: (entryId: string, errorMessage: string) => { + return `**${entryId}** failed to parse: ${errorMessage}`; + }, + hint: 'Ensure your data entry is an object with valid JSON (for `.json` entries) or YAML (for `.yaml` entries).', +} satisfies ErrorData; +/** + * @docs + * @message `COLLECTION_NAME` contains multiple entries with the same slug: `SLUG`. Slugs must be unique. + * @description + * Content collection entries must have unique slugs. Duplicates are often caused by the `slug` frontmatter property. + */ +export const DuplicateContentEntrySlugError = { + name: 'DuplicateContentEntrySlugError', + title: 'Duplicate content entry slug.', + message: (collection: string, slug: string) => { + return `**${collection}** contains multiple entries with the same slug: \`${slug}\`. Slugs must be unique.`; + }, +} satisfies ErrorData; - /** - * @docs - * @see - * - [devalue library](https://github.com/rich-harris/devalue) - * @description - * `transform()` functions in your content config must return valid JSON, or data types compatible with the devalue library (including Dates, Maps, and Sets). - */ - UnsupportedConfigTransformError: { - title: 'Unsupported transform in content config.', - message: (parseError: string) => - `\`transform()\` functions in your content config must return valid JSON, or data types compatible with the devalue library (including Dates, Maps, and Sets).\nFull error: ${parseError}`, - hint: 'See the devalue library for all supported types: https://github.com/rich-harris/devalue', - }, +/** + * @docs + * @see + * - [devalue library](https://github.com/rich-harris/devalue) + * @description + * `transform()` functions in your content config must return valid JSON, or data types compatible with the devalue library (including Dates, Maps, and Sets). + */ +export const UnsupportedConfigTransformError = { + name: 'UnsupportedConfigTransformError', + title: 'Unsupported transform in content config.', + message: (parseError: string) => + `\`transform()\` functions in your content config must return valid JSON, or data types compatible with the devalue library (including Dates, Maps, and Sets).\nFull error: ${parseError}`, + hint: 'See the devalue library for all supported types: https://github.com/rich-harris/devalue', +} satisfies ErrorData; - // Generic catch-all - Only use this in extreme cases, like if there was a cosmic ray bit flip - UnknownError: { - title: 'Unknown Error.', - }, -} as const satisfies Record; +// Generic catch-all - Only use this in extreme cases, like if there was a cosmic ray bit flip +export const UnknownError = { name: 'UnknownError', title: 'Unknown Error.' } satisfies ErrorData; +// } as export const satisfies Record; diff --git a/packages/astro/src/core/errors/errors.ts b/packages/astro/src/core/errors/errors.ts index ca4392891d60e..1960bac4a85ef 100644 --- a/packages/astro/src/core/errors/errors.ts +++ b/packages/astro/src/core/errors/errors.ts @@ -1,10 +1,9 @@ import type { ZodError } from 'zod'; import { codeFrame } from './printer.js'; -import { getErrorDataByTitle } from './utils.js'; interface ErrorProperties { title?: string; - name?: string; + name: string; message?: string; location?: ErrorLocation; hint?: string; @@ -43,16 +42,7 @@ export class AstroError extends Error { const { name, title, message, stack, location, hint, frame } = props; this.title = title; - - if (name && name !== 'Error') { - this.name = name; - } else if (this.title) { - const errorData = getErrorDataByTitle(this.title)?.name; - - if (errorData) { - this.name = errorData; - } - } + this.name = name; if (message) this.message = message; // Only set this if we actually have a stack passed, otherwise uses Error's @@ -92,8 +82,6 @@ export class CompilerError extends AstroError { constructor(props: ErrorProperties, ...params: any) { super(props, ...params); - - this.name = 'CompilerError'; } static is(err: unknown): err is CompilerError { diff --git a/packages/astro/src/core/errors/index.ts b/packages/astro/src/core/errors/index.ts index 2b85574e9c7fe..5d64a73408812 100644 --- a/packages/astro/src/core/errors/index.ts +++ b/packages/astro/src/core/errors/index.ts @@ -1,5 +1,4 @@ export type { ErrorLocation, ErrorWithMetadata } from './errors'; -export { AstroErrorData } from './errors-data.js'; export { AggregateError, AstroError, diff --git a/packages/astro/src/core/errors/utils.ts b/packages/astro/src/core/errors/utils.ts index ea238d4414149..300787dd32032 100644 --- a/packages/astro/src/core/errors/utils.ts +++ b/packages/astro/src/core/errors/utils.ts @@ -1,7 +1,6 @@ import type { YAMLException } from 'js-yaml'; import type { ErrorPayload as ViteErrorPayload } from 'vite'; import type { SSRError } from '../../@types/astro.js'; -import { AstroErrorData, type ErrorData } from './errors-data.js'; /** * Get the line and character based on the offset @@ -105,14 +104,3 @@ export function createSafeError(err: any): Error { export function normalizeLF(code: string) { return code.replace(/\r\n|\r(?!\n)|\n/g, '\n'); } - -export function getErrorDataByTitle(title: string) { - const entry = Object.entries(AstroErrorData).find((data) => data[1].title === title); - - if (entry) { - return { - name: entry[0], - data: entry[1] as ErrorData, - }; - } -} diff --git a/packages/astro/src/core/middleware/callMiddleware.ts b/packages/astro/src/core/middleware/callMiddleware.ts index afa0156c99b13..fac6d353696dc 100644 --- a/packages/astro/src/core/middleware/callMiddleware.ts +++ b/packages/astro/src/core/middleware/callMiddleware.ts @@ -5,9 +5,10 @@ import type { MiddlewareHandler, MiddlewareNext, } from '../../@types/astro'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; import { warn } from '../logger/core.js'; import type { Environment } from '../render'; +import * as AstroErrorData from '../errors/errors-data.js'; /** * Utility function that is in charge of calling the middleware. diff --git a/packages/astro/src/core/redirects/validate.ts b/packages/astro/src/core/redirects/validate.ts index 3075e1f3b30ae..e167071c06461 100644 --- a/packages/astro/src/core/redirects/validate.ts +++ b/packages/astro/src/core/redirects/validate.ts @@ -1,4 +1,5 @@ -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; +import * as AstroErrorData from '../errors/errors-data.js'; export function getRedirectLocationOrThrow(headers: Headers): string { let location = headers.get('location'); diff --git a/packages/astro/src/core/render/context.ts b/packages/astro/src/core/render/context.ts index 5b26eda18e39b..f1c0987d13925 100644 --- a/packages/astro/src/core/render/context.ts +++ b/packages/astro/src/core/render/context.ts @@ -6,9 +6,10 @@ import type { SSRElement, SSRResult, } from '../../@types/astro'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; import type { Environment } from './environment'; import { getParamsAndProps } from './params-and-props.js'; +import * as AstroErrorData from '../errors/errors-data.js'; const clientLocalsSymbol = Symbol.for('astro.locals'); diff --git a/packages/astro/src/core/render/paginate.ts b/packages/astro/src/core/render/paginate.ts index dffabe1782697..9c87d75723b28 100644 --- a/packages/astro/src/core/render/paginate.ts +++ b/packages/astro/src/core/render/paginate.ts @@ -6,7 +6,8 @@ import type { Props, RouteData, } from '../../@types/astro'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; +import * as AstroErrorData from '../errors/errors-data.js'; export function generatePaginateFunction(routeMatch: RouteData): PaginateFunction { return function paginateUtility( diff --git a/packages/astro/src/core/render/params-and-props.ts b/packages/astro/src/core/render/params-and-props.ts index fc08c495e71f9..d899f69f0bd02 100644 --- a/packages/astro/src/core/render/params-and-props.ts +++ b/packages/astro/src/core/render/params-and-props.ts @@ -1,8 +1,9 @@ import type { ComponentInstance, Params, Props, RouteData } from '../../@types/astro'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; import type { LogOptions } from '../logger/core.js'; import { getParams } from '../routing/params.js'; import { RouteCache, callGetStaticPaths, findPathItemByKey } from './route-cache.js'; +import * as AstroErrorData from '../errors/errors-data.js'; interface GetParamsAndPropsOptions { mod: ComponentInstance; diff --git a/packages/astro/src/core/render/result.ts b/packages/astro/src/core/render/result.ts index 968b232d48f06..f4328a6b5750a 100644 --- a/packages/astro/src/core/render/result.ts +++ b/packages/astro/src/core/render/result.ts @@ -11,8 +11,9 @@ import { renderSlotToString, type ComponentSlots } from '../../runtime/server/in import { renderJSX } from '../../runtime/server/jsx.js'; import { chunkToString } from '../../runtime/server/render/index.js'; import { AstroCookies } from '../cookies/index.js'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; import { warn, type LogOptions } from '../logger/core.js'; +import * as AstroErrorData from '../errors/errors-data.js'; const clientAddressSymbol = Symbol.for('astro.clientAddress'); const responseSentSymbol = Symbol.for('astro.responseSent'); diff --git a/packages/astro/src/core/render/route-cache.ts b/packages/astro/src/core/render/route-cache.ts index 804f09183847c..0279a804795d1 100644 --- a/packages/astro/src/core/render/route-cache.ts +++ b/packages/astro/src/core/render/route-cache.ts @@ -7,9 +7,9 @@ import type { RouteData, RuntimeMode, } from '../../@types/astro'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; import { debug, warn, type LogOptions } from '../logger/core.js'; - +import * as AstroErrorData from '../errors/errors-data.js'; import { stringifyParams } from '../routing/params.js'; import { validateDynamicRouteModule, validateGetStaticPathsResult } from '../routing/validation.js'; import { generatePaginateFunction } from './paginate.js'; diff --git a/packages/astro/src/core/routing/validation.ts b/packages/astro/src/core/routing/validation.ts index b5c29b16e12ec..e627d8f005166 100644 --- a/packages/astro/src/core/routing/validation.ts +++ b/packages/astro/src/core/routing/validation.ts @@ -1,7 +1,8 @@ import type { ComponentInstance, GetStaticPathsResult, RouteData } from '../../@types/astro'; -import { AstroError, AstroErrorData } from '../errors/index.js'; +import { AstroError } from '../errors/index.js'; import type { LogOptions } from '../logger/core'; import { warn } from '../logger/core.js'; +import * as AstroErrorData from '../errors/errors-data.js'; const VALID_PARAM_TYPES = ['string', 'number', 'undefined']; diff --git a/packages/astro/src/core/sync/index.ts b/packages/astro/src/core/sync/index.ts index be51f0039b022..f65decfc0bcdc 100644 --- a/packages/astro/src/core/sync/index.ts +++ b/packages/astro/src/core/sync/index.ts @@ -15,8 +15,9 @@ import { resolveConfig } from '../config/config.js'; import { createNodeLogging } from '../config/logging.js'; import { createSettings } from '../config/settings.js'; import { createVite } from '../create-vite.js'; -import { AstroError, AstroErrorData, createSafeError, isAstroError } from '../errors/index.js'; +import { AstroError, createSafeError, isAstroError } from '../errors/index.js'; import { info, type LogOptions } from '../logger/core.js'; +import * as AstroErrorData from '../errors/errors-data.js'; export type ProcessExit = 0 | 1; diff --git a/packages/astro/src/events/error.ts b/packages/astro/src/events/error.ts index b3326091dea2d..00f08394aa776 100644 --- a/packages/astro/src/events/error.ts +++ b/packages/astro/src/events/error.ts @@ -1,6 +1,7 @@ import type { ZodError } from 'zod'; import type { ErrorData } from '../core/errors/errors-data.js'; -import { AstroError, AstroErrorData, type ErrorWithMetadata } from '../core/errors/index.js'; +import { AstroError, type ErrorWithMetadata } from '../core/errors/index.js'; +import * as AstroErrorData from '../core/errors/errors-data.js'; const EVENT_ERROR = 'ASTRO_CLI_ERROR'; diff --git a/packages/astro/src/jsx/babel.ts b/packages/astro/src/jsx/babel.ts index 1ccd05fbc4caf..890299e326a46 100644 --- a/packages/astro/src/jsx/babel.ts +++ b/packages/astro/src/jsx/babel.ts @@ -1,9 +1,9 @@ import type { PluginObj } from '@babel/core'; import * as t from '@babel/types'; -import { AstroErrorData } from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/errors.js'; import { resolvePath } from '../core/util.js'; import type { PluginMetadata } from '../vite-plugin-astro/types'; +import * as AstroErrorData from '../core/errors/errors-data.js'; const ClientOnlyPlaceholder = 'astro-client-only'; diff --git a/packages/astro/src/runtime/server/astro-component.ts b/packages/astro/src/runtime/server/astro-component.ts index 57f2d3c3bf7eb..0c4acdfa4a4d5 100644 --- a/packages/astro/src/runtime/server/astro-component.ts +++ b/packages/astro/src/runtime/server/astro-component.ts @@ -1,6 +1,7 @@ import type { PropagationHint } from '../../@types/astro'; -import { AstroError, AstroErrorData } from '../../core/errors/index.js'; +import { AstroError } from '../../core/errors/index.js'; import type { AstroComponentFactory } from './render/index.js'; +import * as AstroErrorData from '../../core/errors/errors-data.js'; function validateArgs(args: unknown[]): args is Parameters { if (args.length !== 3) return false; diff --git a/packages/astro/src/runtime/server/astro-global.ts b/packages/astro/src/runtime/server/astro-global.ts index 82855c669e778..fc18b05cc1118 100644 --- a/packages/astro/src/runtime/server/astro-global.ts +++ b/packages/astro/src/runtime/server/astro-global.ts @@ -1,6 +1,7 @@ import type { AstroGlobalPartial } from '../../@types/astro'; import { ASTRO_VERSION } from '../../core/constants.js'; -import { AstroError, AstroErrorData } from '../../core/errors/index.js'; +import { AstroError } from '../../core/errors/index.js'; +import * as AstroErrorData from '../../core/errors/errors-data.js'; /** Create the Astro.glob() runtime function. */ function createAstroGlobFn() { diff --git a/packages/astro/src/runtime/server/hydration.ts b/packages/astro/src/runtime/server/hydration.ts index 11cce522aa3a1..c8fb657981365 100644 --- a/packages/astro/src/runtime/server/hydration.ts +++ b/packages/astro/src/runtime/server/hydration.ts @@ -4,10 +4,11 @@ import type { SSRLoadedRenderer, SSRResult, } from '../../@types/astro'; -import { AstroError, AstroErrorData } from '../../core/errors/index.js'; +import { AstroError } from '../../core/errors/index.js'; import { escapeHTML } from './escape.js'; import { serializeProps } from './serialize.js'; import { serializeListValue } from './util.js'; +import * as AstroErrorData from '../../core/errors/errors-data.js'; export interface HydrationMetadata { directive: string; diff --git a/packages/astro/src/runtime/server/render/astro/render.ts b/packages/astro/src/runtime/server/render/astro/render.ts index 0c34ef98d2ea6..e1e1e754cc225 100644 --- a/packages/astro/src/runtime/server/render/astro/render.ts +++ b/packages/astro/src/runtime/server/render/astro/render.ts @@ -1,5 +1,6 @@ import type { RouteData, SSRResult } from '../../../../@types/astro'; -import { AstroError, AstroErrorData } from '../../../../core/errors/index.js'; +import { AstroError } from '../../../../core/errors/index.js'; +import * as AstroErrorData from '../../../../core/errors/errors-data.js'; import { chunkToByteArray, chunkToString, encoder, type RenderDestination } from '../common.js'; import type { AstroComponentFactory } from './factory.js'; import { isHeadAndContent } from './head-and-content.js'; diff --git a/packages/astro/src/runtime/server/render/component.ts b/packages/astro/src/runtime/server/render/component.ts index f78f11d517f74..8d9b4d717daf8 100644 --- a/packages/astro/src/runtime/server/render/component.ts +++ b/packages/astro/src/runtime/server/render/component.ts @@ -5,8 +5,8 @@ import type { SSRResult, } from '../../../@types/astro'; import type { RenderInstruction } from './types.js'; - -import { AstroError, AstroErrorData } from '../../../core/errors/index.js'; +import * as AstroErrorData from '../../../core/errors/errors-data.js'; +import { AstroError } from '../../../core/errors/index.js'; import { HTMLBytes, markHTMLString } from '../escape.js'; import { extractDirectives, generateHydrateScript } from '../hydration.js'; import { serializeProps } from '../serialize.js'; diff --git a/packages/astro/src/transitions/vite-plugin-transitions.ts b/packages/astro/src/transitions/vite-plugin-transitions.ts index 9803be2112b86..d0b885857f7dd 100644 --- a/packages/astro/src/transitions/vite-plugin-transitions.ts +++ b/packages/astro/src/transitions/vite-plugin-transitions.ts @@ -18,6 +18,7 @@ export default function astroTransitions({ config }: { config: AstroConfig }): v if (id === resolvedVirtualModuleId) { if (!config.experimental.viewTransitions) { throw new AstroError({ + name: 'TransitionError', title: 'Experimental View Transitions not enabled', message: `View Transitions support is experimental. To enable update your config to include: diff --git a/packages/astro/src/vite-plugin-astro-server/route.ts b/packages/astro/src/vite-plugin-astro-server/route.ts index ff926bca2e37a..a120682d8d93a 100644 --- a/packages/astro/src/vite-plugin-astro-server/route.ts +++ b/packages/astro/src/vite-plugin-astro-server/route.ts @@ -9,7 +9,8 @@ import type { SSRManifest, } from '../@types/astro'; import { attachToResponse } from '../core/cookies/index.js'; -import { AstroErrorData, isAstroError } from '../core/errors/index.js'; +import { isAstroError } from '../core/errors/index.js'; +import * as AstroErrorData from '../core/errors/errors-data.js'; import { warn } from '../core/logger/core.js'; import { loadMiddleware } from '../core/middleware/loadMiddleware.js'; import { isEndpointResult } from '../core/render/core.js'; diff --git a/packages/astro/src/vite-plugin-markdown/index.ts b/packages/astro/src/vite-plugin-markdown/index.ts index 3d820242202a9..2f61541642d60 100644 --- a/packages/astro/src/vite-plugin-markdown/index.ts +++ b/packages/astro/src/vite-plugin-markdown/index.ts @@ -10,7 +10,8 @@ import { fileURLToPath } from 'node:url'; import type { Plugin } from 'vite'; import { normalizePath } from 'vite'; import type { AstroSettings } from '../@types/astro'; -import { AstroError, AstroErrorData, MarkdownError } from '../core/errors/index.js'; +import { AstroError, MarkdownError } from '../core/errors/index.js'; +import * as AstroErrorData from '../core/errors/errors-data.js'; import type { LogOptions } from '../core/logger/core.js'; import { warn } from '../core/logger/core.js'; import { isMarkdownFile, rootRelativePath } from '../core/util.js'; @@ -27,6 +28,7 @@ function safeMatter(source: string, id: string) { return matter(source); } catch (err: any) { const markdownError = new MarkdownError({ + name: 'MarkdownError', message: err.message, stack: err.stack, location: { @@ -61,6 +63,10 @@ const astroErrorModulePath = normalizePath( fileURLToPath(new URL('../core/errors/index.js', import.meta.url)) ); +const astroErrorDataModulePath = normalizePath( + fileURLToPath(new URL('../core/errors/errors-data.js', import.meta.url)) +); + export default function markdown({ settings, logging }: AstroPluginOptions): Plugin { return { enforce: 'pre', @@ -116,7 +122,8 @@ export default function markdown({ settings, logging }: AstroPluginOptions): Plu const code = escapeViteEnvReferences(` import { Fragment, jsx as h } from ${JSON.stringify(astroJsxRuntimeModulePath)}; import { spreadAttributes } from ${JSON.stringify(astroServerRuntimeModulePath)}; - import { AstroError, AstroErrorData } from ${JSON.stringify(astroErrorModulePath)}; + import { AstroError } from ${JSON.stringify(astroErrorModulePath)}; + import { MarkdownImageNotFound } from ${JSON.stringify(astroErrorDataModulePath)}; ${layout ? `import Layout from ${JSON.stringify(layout)};` : ''} ${settings.config.experimental.assets ? 'import { getImage } from "astro:assets";' : ''} @@ -133,8 +140,8 @@ export default function markdown({ settings, logging }: AstroPluginOptions): Plu async function getImageSafely(imageSrc, imagePath, resolvedImagePath) { if (!imageSrc) { throw new AstroError({ - ...AstroErrorData.MarkdownImageNotFound, - message: AstroErrorData.MarkdownImageNotFound.message( + ...MarkdownImageNotFound, + message: MarkdownImageNotFound.message( imagePath, resolvedImagePath ), diff --git a/packages/astro/src/vite-plugin-scanner/scan.ts b/packages/astro/src/vite-plugin-scanner/scan.ts index 3eb834ea24db5..636543248d25e 100644 --- a/packages/astro/src/vite-plugin-scanner/scan.ts +++ b/packages/astro/src/vite-plugin-scanner/scan.ts @@ -2,7 +2,8 @@ import type { AstroSettings } from '../@types/astro.js'; import type { PageOptions } from '../vite-plugin-astro/types.js'; import * as eslexer from 'es-module-lexer'; -import { AstroError, AstroErrorData } from '../core/errors/index.js'; +import { AstroError } from '../core/errors/index.js'; +import * as AstroErrorData from '../core/errors/errors-data.js'; const BOOLEAN_EXPORTS = new Set(['prerender']); diff --git a/packages/astro/test/events.test.js b/packages/astro/test/events.test.js index 47f37b645e9a5..9c18d364bf887 100644 --- a/packages/astro/test/events.test.js +++ b/packages/astro/test/events.test.js @@ -1,5 +1,5 @@ import { expect } from 'chai'; -import { AstroErrorData } from '../dist/core/errors/errors-data.js'; +import * as AstroErrorData from '../dist/core/errors/errors-data.js'; import { AstroError } from '../dist/core/errors/errors.js'; import * as events from '../dist/events/index.js';