diff --git a/astro.config.ts b/astro.config.ts index 7777abd60f5e2..a959a93947a7c 100644 --- a/astro.config.ts +++ b/astro.config.ts @@ -16,7 +16,7 @@ const previewSite = previewBranch ? `https://${previewBranch}.previews.docs.astro.build/` : undefined; -const site = previewSite || 'https://docs.astro.build/'; +const site = previewSite || 'https://v7.docs.astro.build/'; // https://astro.build/config export default defineConfig({ diff --git a/astro.sidebar.ts b/astro.sidebar.ts index c808283eaf9f9..4b1f8e67873d6 100644 --- a/astro.sidebar.ts +++ b/astro.sidebar.ts @@ -71,7 +71,6 @@ export const sidebar = [ 'guides/content-collections', 'guides/images', 'guides/data-fetching', - 'guides/astro-db', ], }), group('guides.serverRendering', { @@ -88,6 +87,7 @@ export const sidebar = [ group('guides.upgrade.major', { collapsed: true, items: [ + 'guides/upgrade-to/v7', 'guides/upgrade-to/v6', 'guides/upgrade-to/v5', 'guides/upgrade-to/v4', @@ -130,6 +130,8 @@ export const sidebar = [ 'reference/modules/astro-config', 'reference/modules/astro-content', 'reference/modules/astro-env', + 'reference/modules/astro-fetch', + 'reference/modules/astro-hono', 'reference/modules/astro-i18n', 'reference/modules/astro-middleware', 'reference/modules/astro-static-paths', @@ -147,6 +149,7 @@ export const sidebar = [ 'reference/dev-toolbar-app-reference', 'reference/session-driver-reference', 'reference/font-provider-reference', + 'reference/logger-reference', 'reference/container-reference', 'reference/programmatic-reference', ], @@ -159,10 +162,6 @@ export const sidebar = [ 'reference/experimental-flags/content-intellisense', 'reference/experimental-flags/chrome-devtools-workspace', 'reference/experimental-flags/svg-optimization', - 'reference/experimental-flags/queued-rendering', - 'reference/experimental-flags/rust-compiler', - 'reference/experimental-flags/advanced-routing', - 'reference/experimental-flags/logger', ], }), 'reference/legacy-flags', @@ -196,7 +195,6 @@ export const sidebar = [ group('ecosystem.integrations.other', { collapsed: true, items: [ - 'guides/integrations-guide/db', 'guides/integrations-guide/markdoc', 'guides/integrations-guide/mdx', 'guides/integrations-guide/partytown', diff --git a/package.json b/package.json index d36e39d1a8a73..fe3f244a353b7 100644 --- a/package.json +++ b/package.json @@ -54,7 +54,7 @@ "typescript-eslint": "^8.59.3", "unified": "^11.0.5", "unist-util-visit": "^5.1.0", - "wrangler": "^4.88.0" + "wrangler": "^4.99.0" }, "dependencies": { "@astrojs/check": "^0.9.9", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d304ab2765fe0..2abd7e25afabd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -136,8 +136,8 @@ importers: specifier: ^5.1.0 version: 5.1.0 wrangler: - specifier: ^4.88.0 - version: 4.88.0 + specifier: ^4.99.0 + version: 4.99.0 packages: @@ -406,32 +406,32 @@ packages: workerd: optional: true - '@cloudflare/workerd-darwin-64@1.20260504.1': - resolution: {integrity: sha512-IOMjYoftNRXabFt+QzY2Bo2mR2TNl8xsGvE0HnQ+K0S2c61VOUGUkr9gpJjnwrJ65yA9Qed4xfg0RRqXHO+nfA==} + '@cloudflare/workerd-darwin-64@1.20260609.1': + resolution: {integrity: sha512-AK8tYLQm+8BqQMzjZ55ZfuhfIm1eCkj+Ykxz6kWXojdACwjjU03MrwdM9fBDdgzU3upXOs4e1scOFHySlfVQjA==} engines: {node: '>=16'} cpu: [x64] os: [darwin] - '@cloudflare/workerd-darwin-arm64@1.20260504.1': - resolution: {integrity: sha512-7iMXxIU0N5KklZpQm2kuwTm0XtrpHXNqhejJyGquky8gSTnm31zBdutjMekH8VRr6ckbvZIl6lvqXzXdfOEojg==} + '@cloudflare/workerd-darwin-arm64@1.20260609.1': + resolution: {integrity: sha512-4kKXfr7ZHU6xQ/R9ShdSuj1A1bEouoRcHzUWdjnuMPBlRsAAVanlxAVYISotFUulLEinayOpRFbhpsfwzrpSSw==} engines: {node: '>=16'} cpu: [arm64] os: [darwin] - '@cloudflare/workerd-linux-64@1.20260504.1': - resolution: {integrity: sha512-YLB0EH5FQV++oWlalFgPF3p2Bp3dn/D6RWNMw0ukEC8gKnNX6o61A+dlFUl8hRD35ja1zKRxGFUojs4U2+MoJA==} + '@cloudflare/workerd-linux-64@1.20260609.1': + resolution: {integrity: sha512-T2Ebir2OPHAvvZ0HUh5mi1lN8q30sVi4lf7LIpc28AHoWtoOmJ0jA5AJK4IYJm1MKEbBldq+QsckaHOCQFmRpQ==} engines: {node: '>=16'} cpu: [x64] os: [linux] - '@cloudflare/workerd-linux-arm64@1.20260504.1': - resolution: {integrity: sha512-FAh/82jDXDArfn9xDih6f/IJfF2SHXBb4nFeQAyHyvXrn18zM6Q3yl2Vj0U7LybbNbmu7TNGghwaM2NoSQS+0A==} + '@cloudflare/workerd-linux-arm64@1.20260609.1': + resolution: {integrity: sha512-INfcYoSsKqEIvPL69/3RkqYoP8WUR0VEN6loWN/3tekXLoJrVOj3E5NjIetsdS8MJN6zc3st/ae4bMuWRRzoDg==} engines: {node: '>=16'} cpu: [arm64] os: [linux] - '@cloudflare/workerd-windows-64@1.20260504.1': - resolution: {integrity: sha512-QUg/B3dfrK/KHHHhiJzdkLkTg5mG7lA3t8iplbBoUa3XKCLOHOOXhbU4WSYlLqg8YnsQ6XLZ1HVA99fmZhJh7A==} + '@cloudflare/workerd-windows-64@1.20260609.1': + resolution: {integrity: sha512-EWhfxKI1aqUr7S8xuGxgmRCumEzB8iSsCIz6oEqJN+3pZuW3EWiKDGFW4EY1BmwNINLW1eO5VMGYb8Fj6FVYxA==} engines: {node: '>=16'} cpu: [x64] os: [win32] @@ -1155,8 +1155,8 @@ packages: resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==} engines: {node: '>=18'} - '@speed-highlight/core@1.2.15': - resolution: {integrity: sha512-BMq1K3DsElxDWawkX6eLg9+CKJrTVGCBAWVuHXVUV2u0s2711qiChLSId6ikYPfxhdYocLNt3wWwSvDiTvFabw==} + '@speed-highlight/core@1.2.16': + resolution: {integrity: sha512-yNm/fYEcnpRjYduLMaddTK9XKYil6xB88+qFg79ZdZhHu1PadfoQmFW7pVTx7FZqMBNcUuThiAhxhENgtAO2/w==} '@textlint/ast-node-types@13.4.1': resolution: {integrity: sha512-qrZyhCh8Ekk6nwArx3BROybm9BnX6vF7VcZbijetV/OM3yfS4rTYhoMWISmhVEP2H2re0CtWEyMl/XF+WdvVLQ==} @@ -2744,8 +2744,8 @@ packages: resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} engines: {node: '>=8.6'} - miniflare@4.20260504.0: - resolution: {integrity: sha512-HeI/HLx+rbeo/UB4qb6NsNcFdUVD7xDzyCexZJTVtFMlfpfexUKEDmdeTRRpzeHrJseZFGua+v9JO1kfPublUw==} + miniflare@4.20260609.0: + resolution: {integrity: sha512-4ZfNh9ACDa/mKKQvTSO2vigyQS2MB7dEU02KRPle4FqL7S6nek+2Fq6WGzazZbt1OORYgb4OGVLnOCx+My2NNA==} engines: {node: '>=22.0.0'} hasBin: true @@ -3811,17 +3811,17 @@ packages: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} - workerd@1.20260504.1: - resolution: {integrity: sha512-AQTXSHbYNP9tLPgJNn0TmizyE4aDh2VuZZXlTAL0uu4fbCY436NAnQSJIzZbaFHM3DnAtVs9G8tkiJztSdYqDg==} + workerd@1.20260609.1: + resolution: {integrity: sha512-KF/Y/8f4VoXCk87NuU6RqmO0X5fdzcrxU3XzAgoPUpnH9t1ZyzRgX1O/9sJvjItxroCBTEBzKssda02Dz9i6BA==} engines: {node: '>=16'} hasBin: true - wrangler@4.88.0: - resolution: {integrity: sha512-f470QwbeT/JM1S0duq+sLtkss7UBxIFDtYHgujv9tdQUyA/dLGDq51am0rqrsuFtCi97lTM1P5sqtt8xra1AlA==} + wrangler@4.99.0: + resolution: {integrity: sha512-i7GA2mZETTyq3ljWdEzM908FjLaMWZ1AaAHKaOJ8pFA/tonf2VqIWDyBGzKleIVBbNQxOTIY2wnbv0iaK3rC6g==} engines: {node: '>=22.0.0'} hasBin: true peerDependencies: - '@cloudflare/workers-types': ^4.20260504.1 + '@cloudflare/workers-types': ^4.20260609.1 peerDependenciesMeta: '@cloudflare/workers-types': optional: true @@ -3834,8 +3834,8 @@ packages: resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==} engines: {node: '>=12'} - ws@8.18.0: - resolution: {integrity: sha512-8VbfWfHLbbwu3+N6OKsOMpBdT4kXPDDB9cJk2bJ6mh9ucxdlnNvH1e+roYkKmN9Nxw2yjz7VzeO9oOz2zJ04Pw==} + ws@8.20.1: + resolution: {integrity: sha512-It4dO0K5v//JtTXuPkfEOaI3uUN87iYPnqo/ZzqCoG3g8uhA66QUMs/SrM0YK7/NAu+r4LMh/9dq2A7k+rHs+w==} engines: {node: '>=10.0.0'} peerDependencies: bufferutil: ^4.0.1 @@ -4290,25 +4290,25 @@ snapshots: '@cloudflare/kv-asset-handler@0.5.0': {} - '@cloudflare/unenv-preset@2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260504.1)': + '@cloudflare/unenv-preset@2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260609.1)': dependencies: unenv: 2.0.0-rc.24 optionalDependencies: - workerd: 1.20260504.1 + workerd: 1.20260609.1 - '@cloudflare/workerd-darwin-64@1.20260504.1': + '@cloudflare/workerd-darwin-64@1.20260609.1': optional: true - '@cloudflare/workerd-darwin-arm64@1.20260504.1': + '@cloudflare/workerd-darwin-arm64@1.20260609.1': optional: true - '@cloudflare/workerd-linux-64@1.20260504.1': + '@cloudflare/workerd-linux-64@1.20260609.1': optional: true - '@cloudflare/workerd-linux-arm64@1.20260504.1': + '@cloudflare/workerd-linux-arm64@1.20260609.1': optional: true - '@cloudflare/workerd-windows-64@1.20260504.1': + '@cloudflare/workerd-windows-64@1.20260609.1': optional: true '@cspotcode/source-map-support@0.8.1': @@ -4887,7 +4887,7 @@ snapshots: '@sindresorhus/is@7.2.0': {} - '@speed-highlight/core@1.2.15': {} + '@speed-highlight/core@1.2.16': {} '@textlint/ast-node-types@13.4.1': {} @@ -7183,13 +7183,13 @@ snapshots: braces: 3.0.3 picomatch: 2.3.1 - miniflare@4.20260504.0: + miniflare@4.20260609.0: dependencies: '@cspotcode/source-map-support': 0.8.1 sharp: 0.34.5 undici: 7.24.8 - workerd: 1.20260504.1 - ws: 8.18.0 + workerd: 1.20260609.1 + ws: 8.20.1 youch: 4.1.0-beta.10 transitivePeerDependencies: - bufferutil @@ -8407,24 +8407,24 @@ snapshots: word-wrap@1.2.5: {} - workerd@1.20260504.1: + workerd@1.20260609.1: optionalDependencies: - '@cloudflare/workerd-darwin-64': 1.20260504.1 - '@cloudflare/workerd-darwin-arm64': 1.20260504.1 - '@cloudflare/workerd-linux-64': 1.20260504.1 - '@cloudflare/workerd-linux-arm64': 1.20260504.1 - '@cloudflare/workerd-windows-64': 1.20260504.1 + '@cloudflare/workerd-darwin-64': 1.20260609.1 + '@cloudflare/workerd-darwin-arm64': 1.20260609.1 + '@cloudflare/workerd-linux-64': 1.20260609.1 + '@cloudflare/workerd-linux-arm64': 1.20260609.1 + '@cloudflare/workerd-windows-64': 1.20260609.1 - wrangler@4.88.0: + wrangler@4.99.0: dependencies: '@cloudflare/kv-asset-handler': 0.5.0 - '@cloudflare/unenv-preset': 2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260504.1) + '@cloudflare/unenv-preset': 2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260609.1) blake3-wasm: 2.1.5 esbuild: 0.27.3 - miniflare: 4.20260504.0 + miniflare: 4.20260609.0 path-to-regexp: 6.3.0 unenv: 2.0.0-rc.24 - workerd: 1.20260504.1 + workerd: 1.20260609.1 optionalDependencies: fsevents: 2.3.3 transitivePeerDependencies: @@ -8443,7 +8443,7 @@ snapshots: string-width: 5.1.2 strip-ansi: 7.1.0 - ws@8.18.0: {} + ws@8.20.1: {} xmlcreate@2.0.4: {} @@ -8496,7 +8496,7 @@ snapshots: dependencies: '@poppinss/colors': 4.1.6 '@poppinss/dumper': 0.6.5 - '@speed-highlight/core': 1.2.15 + '@speed-highlight/core': 1.2.16 cookie: 1.1.1 youch-core: 0.3.3 diff --git a/public/.assetsignore b/public/.assetsignore new file mode 100644 index 0000000000000..b7ccb6cba31c5 --- /dev/null +++ b/public/.assetsignore @@ -0,0 +1,2 @@ +_worker.js +_routes.json diff --git a/public/_headers b/public/_headers index b505fec8b57ad..3967f74787ff9 100644 --- a/public/_headers +++ b/public/_headers @@ -1,3 +1,6 @@ +# TODO: Remove this before merging to main +/* + x-robots-tag: no-index /* cache-control: max-age=60 cache-control: public @@ -5,3 +8,4 @@ cache-control: max-age=31536000 cache-control: immutable cache-control: public + diff --git a/src/content.config.ts b/src/content.config.ts index d870fb9b257c6..0f25a6f4fbfd1 100644 --- a/src/content.config.ts +++ b/src/content.config.ts @@ -171,7 +171,6 @@ export const collections = { const packages = [ '@astrojs/alpinejs', '@astrojs/cloudflare', - '@astrojs/db', '@astrojs/markdoc', '@astrojs/mdx', '@astrojs/netlify', diff --git a/src/content/docs/en/contribute.mdx b/src/content/docs/en/contribute.mdx index 01537b81a9cb4..dbaec73a4bb71 100644 --- a/src/content/docs/en/contribute.mdx +++ b/src/content/docs/en/contribute.mdx @@ -25,7 +25,7 @@ Visit [Astro's GitHub profile](https://github.com/withastro) to find the reposit - [Astro Docs](https://github.com/withastro/docs), an entire Astro website! Contribute not just written content, but also Astro code addressing a11y, CSS, UI, and UX concerns. We also make our documentation available in several languages, so we need help translating the entire site. -- The [Astro compiler](https://github.com/withastro/compiler), written in Go, distributed as WASM. +- The [Astro compiler](https://github.com/withastro/compiler-rs), written in Rust, distributed as WASM. - Astro's [language tools](https://github.com/withastro/astro/tree/main/packages/language-tools), the editor tooling required for the Astro language (`.astro` files). diff --git a/src/content/docs/en/getting-started.mdx b/src/content/docs/en/getting-started.mdx index 717be6e7fe541..dcb3791c0c4b2 100644 --- a/src/content/docs/en/getting-started.mdx +++ b/src/content/docs/en/getting-started.mdx @@ -5,6 +5,9 @@ i18nReady: true tableOfContents: false editUrl: false next: false +banner: + content: | + Astro v7 is here! Learn how to upgrade your site hero: title: Astro Docs tagline: Guides, resources, and API references to help you build with Astro. diff --git a/src/content/docs/en/guides/astro-db.mdx b/src/content/docs/en/guides/astro-db.mdx deleted file mode 100644 index 08017b50f0e65..0000000000000 --- a/src/content/docs/en/guides/astro-db.mdx +++ /dev/null @@ -1,801 +0,0 @@ ---- -title: 'Astro DB' -description: Learn how to use Astro DB, a fully-managed SQL database designed exclusively for Astro. -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -import { Steps } from '@astrojs/starlight/components'; - -:::caution[Deprecated] -The `@astrojs/db` integration has been deprecated in Astro v6.5 and is no longer maintained. - -If you were using this integration in your project, we recommend that you use a database client (e.g., Drizzle, Kysely) directly in your Astro project. -::: - -Astro DB is a fully-managed SQL database designed for the Astro ecosystem. Develop locally in Astro and deploy to any libSQL-compatible database. - -Astro DB is a complete solution to configuring, developing, and querying your data. A local database is created in `.astro/content.db` whenever you run `astro dev` to manage your data without the need for Docker or a network connection. - -## Installation - -Install the [`@astrojs/db` integration](/en/guides/integrations-guide/db/) using the built-in `astro add` command: - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -## Define your database - -Installing `@astrojs/db` with the `astro add` command will automatically create a `db/config.ts` file in your project where you will define your database tables: - -```ts title="db/config.ts" -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: { }, -}) -``` - -### Tables - -Data in Astro DB is stored using SQL tables. Tables structure your data into rows and columns, where columns enforce the type of each row value. - -Define your tables in your `db/config.ts` file by providing the structure of the data in your existing libSQL database, or the data you will collect in a new database. This will allow Astro to generate a TypeScript interface to query that table from your project. The result is full TypeScript support when you access your data with property autocompletion and type-checking. - -To configure a database table, import and use the `defineTable()` and `column` utilities from `astro:db`. Then, define a name (case-sensitive) for your table and the type of data in each column. - -This example configures a `Comment` table with required text columns for `author` and `body`. Then, makes it available to your project through the `defineDb()` export. - -```ts title="db/config.ts" "Comment" -import { defineDb, defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } -}) - -export default defineDb({ - tables: { Comment }, -}) -``` - -See the [table configuration reference](/en/guides/integrations-guide/db/#table-configuration-reference) for a complete reference of table options. - -### Columns - -Astro DB supports the following column types: - -```ts title="db/config.ts" "column.text()" "column.number()" "column.boolean()" "column.date()" "column.json()" -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - // A string of text. - author: column.text(), - // A whole integer value. - likes: column.number(), - // A true or false value. - flagged: column.boolean(), - // Date/time values queried as JavaScript Date objects. - published: column.date(), - // An untyped JSON object. - metadata: column.json(), - } -}); -``` - -See the [table columns reference](/en/guides/integrations-guide/db/#table-configuration-reference) for more details. - -### Table References - -Relationships between tables are a common pattern in database design. For example, a `Blog` table may be closely related to other tables of `Comment`, `Author`, and `Category`. - -You can define these relations between tables and save them into your database schema using **reference columns**. To establish a relationship, you will need: - -- An **identifier column** on the referenced table. This is usually an `id` column with the `primaryKey` property. -- A column on the base table to **store the referenced `id`**. This uses the `references` property to establish a relationship. - -This example shows a `Comment` table's `authorId` column referencing an `Author` table's `id` column. - -```ts title="db/config.ts" {3, 10} -const Author = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - } -}); - -const Comment = defineTable({ - columns: { - authorId: column.number({ references: () => Author.columns.id }), - body: column.text(), - } -}); -``` - -## Seed your database for development - -In development, Astro will use your DB config to generate local types according to your schemas. These will be generated fresh from your seed file each time the dev server is started, and will allow you to query and work with the shape of your data with type safety and autocompletion. - -You will not have access to production data during development unless you [connect to a remote database](#connecting-to-remote-databases) during development. This protects your data while allowing you to test and develop with a working database with type-safety. - -To seed development data for testing and debugging into your Astro project, create a `db/seed.ts` file. Import both the `db` object and your tables defined in `astro:db`. `insert` some initial data into each table. This development data should match the form of both your database schema and production data. - -The following example defines two rows of development data for a `Comment` table, and an `Author` table: - -```ts title="db/seed.ts" -import { db, Comment, Author } from 'astro:db'; - -export default async function() { - await db.insert(Author).values([ - { id: 1, name: "Kasim" }, - { id: 2, name: "Mina" }, - ]); - - await db.insert(Comment).values([ - { authorId: 1, body: 'Hope you like Astro DB!' }, - { authorId: 2, body: 'Enjoy!'}, - ]) -} -``` - -Your development server will automatically restart your database whenever this file changes, regenerating your types and seeding this development data from `seed.ts` fresh each time. - -## Connect a libSQL database for production - -Astro DB can connect to any local libSQL database or to any server that exposes the libSQL remote protocol, whether managed or self-hosted. - -To connect Astro DB to a libSQL database, set the following environment variables obtained from your database provider: - -- `ASTRO_DB_REMOTE_URL`: the connection URL to the location of your local or remote libSQL DB. This may include [URL configuration options](#remote-url-configuration-options) such as sync and encryption as parameters. -- `ASTRO_DB_APP_TOKEN`: the auth token to your libSQL server. This is required for remote databases, and not needed for [local DBs like files or in-memory](#url-scheme-and-host) databases - -Depending on your service, you may have access to a CLI or web UI to retrieve these values. The following section will demonstrate connecting to Turso and setting these values as an example, but you are free to use any provider. - -### Getting started with Turso - -Turso is the company behind [libSQL](https://github.com/tursodatabase/libsql), the open-source fork of SQLite that powers Astro DB. They provide a fully managed libSQL database platform and are fully compatible with Astro. - -The steps below will guide you through the process of installing the Turso CLI, logging in (or signing up), creating a new database, getting the required environmental variables, and pushing the schema to the remote database. - - - -1. Install the [Turso CLI](https://docs.turso.tech/cli/installation). - -2. [Log in or sign up](https://docs.turso.tech/cli/authentication) to Turso. - -3. Create a new database. In this example the database name is `andromeda`. - - ```sh "andromeda" - turso db create andromeda - ``` - -4. Run the `show` command to see information about the newly created database: - - ```sh "andromeda" - turso db show andromeda - ``` - - Copy the `URL` value and set it as the value for `ASTRO_DB_REMOTE_URL`. - - - ```dotenv title=".env" "libsql://andromeda-houston.turso.io" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ``` - -5. Create a new token to authenticate requests to the database: - - ```sh "andromeda" - turso db tokens create andromeda - ``` - - Copy the output of the command and set it as the value for `ASTRO_DB_APP_TOKEN`. - - ```dotenv title=".env" add={2} "eyJhbGciOiJF...3ahJpTkKDw" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ASTRO_DB_APP_TOKEN=eyJhbGciOiJF...3ahJpTkKDw - ``` - -6. Push your DB schema and metadata to the new Turso database. - - ```sh - astro db push --remote - ``` - -7. Congratulations, now you have a database connected! Give yourself a break. 👾 - - ```sh - turso relax - ``` - - - -To explore more features of Turso, check out the [Turso docs](https://docs.turso.tech). - -### Connecting to remote databases - -Astro DB allows you to connect to both local and remote databases. By default, Astro uses a local database file for `dev` and `build` commands, recreating tables and inserting development seed data each time. - -To connect to a hosted remote database, use the `--remote` flag. This flag enables both readable and writable access to your remote database, allowing you to [accept and persist user data](#insert) in production environments. - -Configure your build command to use the `--remote` flag: - -```json title="package.json" "--remote" -{ - "scripts": { - "build": "astro build --remote" - } -} -``` - -You can also use the flag directly in the command line: - -```bash -# Build with a remote connection -astro build --remote - -# Develop with a remote connection -astro dev --remote -``` - -:::caution -Be careful when using `--remote` in development. This connects to your live production database, and all changes (inserts, updates, deletions) will be persisted. -::: - -The `--remote` flag uses the connection to the remote DB both locally during the build and on the server. Ensure you set the necessary environment variables in both your local development environment and your deployment platform. Additionally, you may need to [configure web mode](/en/guides/integrations-guide/db/#mode) for non-Node.js runtimes such as Cloudflare Workers or Deno. - -When deploying your Astro DB project, make sure your deployment platform's build command is set to `npm run build` (or the equivalent for your package manager) to utilize the `--remote` flag configured in your `package.json`. - -### Remote URL configuration options - -The `ASTRO_DB_REMOTE_URL` environment variable configures the location of your database as well as other options like sync and encryption. - -#### URL scheme and host - -libSQL supports both HTTP and WebSockets as the transport protocol for a remote server. It also supports using a local file or an in-memory DB. Those can be configured using the following URL schemes in the connection URL: - -- `memory:` will use an in-memory DB. The host must be empty in this case. -- `file:` will use a local file. The host is the path to the file (`file:path/to/file.db`). -- `libsql:` will use a remote server through the protocol preferred by the library (this might be different across versions). The host is the address of the server (`libsql://your.server.io`). -- `http:` will use a remote server through HTTP. `https:` can be used to enable a secure connection. The host is the same as for `libsql:`. -- `ws:` will use a remote server through WebSockets. `wss:` can be used to enable a secure connection. The host is the same as for `libsql:`. - -Details of the libSQL connection (e.g. encryption key, replication, sync interval) can be configured as query parameters in the remote connection URL. - -For example, to have an encrypted local file work as an embedded replica to a libSQL server, you can set the following environment variables: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io -ASTRO_DB_APP_TOKEN=token-to-your-remote-url -``` - -:::caution -Using a database file is an advanced feature, and care should be taken when deploying to prevent overriding your database and losing your production data. - -Additionally, this method will not work in serverless deployments, as the file system is not persisted in those environments. -::: - -#### `encryptionKey` - -libSQL has native support for encrypted databases. Passing this search parameter will enable encryption using the given key: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file:path/to/file.db?encryptionKey=your-encryption-key -``` - -#### `syncUrl` - -Embedded replicas are a feature of libSQL clients that creates a full synchronized copy of your database on a local file or in memory for ultra-fast reads. Writes are sent to a remote database defined on the `syncUrl` and synchronized with the local copy. - -Use this property to pass a separate connection URL to turn the database into an embedded replica of another database. This should only be used with the schemes `file:` and `memory:`. The parameter must be URL encoded. - -For example, to have an in-memory embedded replica of a database on `libsql://your.server.io`, you can set the connection URL as such: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io -``` - -#### `syncInterval` - -Interval between embedded replica synchronizations in seconds. By default it only synchronizes on startup and after writes. - -This property is only used when `syncUrl` is also set. For example, to set an in-memory embedded replica to synchronize every minute set the following environment variable: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io&syncInterval=60 -``` - -## Query your database - -You can query your database from any [Astro page](/en/basics/astro-pages/#astro-pages), [endpoint](/en/guides/endpoints/), or [action](/en/guides/actions/) in your project using the provided `db` ORM and query builder. - -### Drizzle ORM - -```ts -import { db } from 'astro:db'; -``` - -Astro DB includes a built-in [Drizzle ORM](https://orm.drizzle.team/) client. There is no setup or manual configuration required to use the client. The Astro DB `db` client is automatically configured to communicate with your database (local or remote) when you run Astro. It uses your exact database schema definition for type-safe SQL queries with TypeScript errors when you reference a column or table that doesn't exist. - -### Select - -The following example selects all rows of a `Comment` table. This returns the complete array of seeded development data from `db/seed.ts` which is then available for use in your page template: - -```astro title="src/pages/index.astro" ---- -import { db, Comment } from 'astro:db'; - -const comments = await db.select().from(Comment); ---- - -

Comments

- -{ - comments.map(({ author, body }) => ( -
-

Author: {author}

-

{body}

-
- )) -} -``` - -See the [Drizzle `select()` API reference](https://orm.drizzle.team/docs/select) for a complete overview. - -### Insert - -To accept user input, such as handling form requests and inserting data into your remote hosted database, configure your Astro project for [on-demand rendering](/en/guides/on-demand-rendering/) and [add an adapter](/en/guides/on-demand-rendering/#add-an-adapter) for your deployment environment. - -This example inserts a row into a `Comment` table based on a parsed form POST request: - -```astro ---- -// src/pages/index.astro -import { db, Comment } from 'astro:db'; - -if (Astro.request.method === 'POST') { - // Parse form data - const formData = await Astro.request.formData(); - const author = formData.get('author'); - const body = formData.get('body'); - if (typeof author === 'string' && typeof body === 'string') { - // Insert form data into the Comment table - await db.insert(Comment).values({ author, body }); - } -} - -// Render the new list of comments on each request -const comments = await db.select().from(Comment); ---- - -
- - - - - - - -
- - -``` - -You can also use [Astro actions](/en/guides/actions/) to insert data into an Astro DB table. The following example inserts a row into a `Comment` table using an action: - -```ts -// src/actions/index.ts -import { db, Comment } from 'astro:db'; -import { defineAction } from 'astro:actions'; -import { z } from 'astro/zod'; - -export const server = { - addComment: defineAction({ - // Actions include type safety with Zod, removing the need - // to check if typeof {value} === 'string' in your pages - input: z.object({ - author: z.string(), - body: z.string(), - }), - handler: async (input) => { - const updatedComments = await db - .insert(Comment) - .values(input) - .returning(); // Return the updated comments - return updatedComments; - }, - }), -}; -``` - - - -See the [Drizzle `insert()` API reference](https://orm.drizzle.team/docs/insert) for a complete overview. - - - -### Delete - -You can also query your database from an API endpoint. This example deletes a row from a `Comment` table by the `id` parameter: - -```ts -// src/pages/api/comments/[id].ts -import type { APIRoute } from "astro"; -import { db, Comment, eq } from 'astro:db'; - -export const DELETE: APIRoute = async (ctx) => { - await db.delete(Comment).where(eq(Comment.id, ctx.params.id )); - return new Response(null, { status: 204 }); -} -``` - - - -See the [Drizzle `delete()` API reference](https://orm.drizzle.team/docs/delete) for a complete overview. - - - -### Filtering - -To query for table results by a specific property, use [Drizzle options for partial selects](https://orm.drizzle.team/docs/select#partial-select). For example, add [a `.where()` call](https://orm.drizzle.team/docs/select#filtering) to your `select()` query and pass the comparison you want to make. - -The following example queries for all rows in a `Comment` table that contain the phrase "Astro DB." Use [the `like()` operator](https://orm.drizzle.team/docs/operators#like) to check if a phrase is present within the `body`: - - -```astro title="src/pages/index.astro" ---- -import { db, Comment, like } from 'astro:db'; - -const comments = await db.select().from(Comment).where( - like(Comment.body, '%Astro DB%') -); ---- -``` - -### Drizzle utilities - -All Drizzle utilities for building queries are exposed from the `astro:db` module. This includes: - -- [Filter operators](https://orm.drizzle.team/docs/operators) like `eq()` and `gt()` -- [Aggregation helpers](https://orm.drizzle.team/docs/select#aggregations-helpers) like `count()` -- [The `sql` helper](https://orm.drizzle.team/docs/sql) for writing raw SQL queries - -```ts -import { eq, gt, count, sql } from 'astro:db'; -``` - -### Relationships - -You can query related data from multiple tables using a SQL join. To create a join query, extend your `db.select()` statement with a join operator. Each function accepts a table to join with and a condition to match rows between the two tables. - -This example uses an `innerJoin()` function to join `Comment` authors with their related `Author` information based on the `authorId` column. This returns an array of objects with each `Author` and `Comment` row as top-level properties: - -```astro title="src/pages/index.astro" ---- -import { db, eq, Comment, Author } from 'astro:db'; - -const comments = await db.select() - .from(Comment) - .innerJoin(Author, eq(Comment.authorId, Author.id)); ---- - -

Comments

- -{ - comments.map(({ Author, Comment }) => ( -
-

Author: {Author.name}

-

{Comment.body}

-
- )) -} -``` - - - -See the [Drizzle join reference](https://orm.drizzle.team/docs/joins#join-types) for all available join operators and config options. - - - -### Batch Transactions - -All remote database queries are made as a network request. You may need to "batch" queries together into a single transaction when making a large number of queries, or to have automatic rollbacks if any query fails. - -This example seeds multiple rows in a single request using the `db.batch()` method: - -```ts -// db/seed.ts -import { db, Author, Comment } from 'astro:db'; - -export default async function () { - const queries = []; - // Seed 100 sample comments into your remote database - // with a single network request. - for (let i = 0; i < 100; i++) { - queries.push(db.insert(Comment).values({ body: `Test comment ${i}` })); - } - await db.batch(queries); -} -``` - - - -See the [Drizzle `db.batch()`](https://orm.drizzle.team/docs/batch-api) docs for more details. - - - -## Pushing changes to your database - -You can push changes made during development to your database. - -### Pushing table schemas - -Your table schema may change over time as your project grows. You can safely test configuration changes locally and push to your remote database when you deploy. - -You can push your local schema changes to your remote database via the CLI using the `astro db push --remote` command: - - - - ```sh - npm run astro db push --remote - ``` - - - ```sh - pnpm astro db push --remote - ``` - - - ```sh - yarn astro db push --remote - ``` - - - -This command will verify that your local changes can be made without data loss and, if necessary, suggest how to safely make changes to your schema in order to resolve conflicts. - -#### Pushing breaking schema changes - -:::danger -__This will destroy your database__. Only perform this command if you do not need your production data. -::: - -If you must change your table schema in a way that is incompatible with your existing data hosted on your remote database, you will need to reset your production database. - -To push a table schema update that includes a breaking change, add the `--force-reset` flag to reset all production data: - - - - ```sh - npm run astro db push --remote --force-reset - ``` - - - ```sh - pnpm astro db push --remote --force-reset - ``` - - - ```sh - yarn astro db push --remote --force-reset - ``` - - - -### Renaming tables - -It is possible to rename a table after pushing your schema to your remote database. - -If you **do not have any important production data**, then you can [reset your database](#pushing-breaking-schema-changes) using the `--force-reset` flag. This flag will drop all of the tables in the database and create new ones so that it matches your current schema exactly. - -To rename a table while preserving your production data, you must perform a series of non-breaking changes to push your local schema to your remote database safely. - -The following example renames a table from `Comment` to `Feedback`: - - - -1. In your database config file, add the `deprecated: true` property to the table you want to rename: - - ```ts title="db/config.ts" ins={2} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -2. Add a new table schema (matching the existing table's properties exactly) with the new name: - - ```ts title="db/config.ts" ins={8-14} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -3. [Push to your remote database](#pushing-table-schemas) with `astro db push --remote`. This will add the new table and mark the old as deprecated. -4. Update any of your local project code to use the new table instead of the old table. You might need to migrate data to the new table as well. -5. Once you are confident that the old table is no longer used in your project, you can remove the schema from your `config.ts`: - ```ts title="db/config.ts" del={1-7} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` -6. Push to your remote database again with `astro db push --remote`. The old table will be dropped, leaving only the new, renamed table. - - -### Pushing table data - -You may need to push data to your remote database for seeding or data migrations. You can author a `.ts` file with the `astro:db` module to write type-safe queries. Then, execute the file against your remote database using the command `astro db execute --remote`: - -The following Comments can be seeded using the command `astro db execute db/seed.ts --remote`: - -```ts -// db/seed.ts -import { Comment } from 'astro:db'; - -export default async function () { - await db.insert(Comment).values([ - { authorId: 1, body: 'Hope you like Astro DB!' }, - { authorId: 2, body: 'Enjoy!' }, - ]) -} -``` - - - -See the [CLI reference](/en/guides/integrations-guide/db/#astro-db-cli-reference) for a complete list of commands. - - - -## Building Astro DB integrations - -[Astro integrations](/en/reference/integrations-reference/) can extend user projects with additional Astro DB tables and seed data. - -Use the `extendDb()` method in the `astro:db:setup` hook to register additional Astro DB config and seed files. -The `defineDbIntegration()` helper provides TypeScript support and auto-complete for the `astro:db:setup` hook. - -```js {8-13} -// my-integration/index.ts -import { defineDbIntegration } from '@astrojs/db/utils'; - -export default function MyIntegration() { - return defineDbIntegration({ - name: 'my-astro-db-powered-integration', - hooks: { - 'astro:db:setup': ({ extendDb }) => { - extendDb({ - configEntrypoint: '@astronaut/my-package/config', - seedEntrypoint: '@astronaut/my-package/seed', - }); - }, - // Other integration hooks... - }, - }); -} -``` - -Integration [config](#define-your-database) and [seed](#seed-your-database-for-development) files follow the same format as their user-defined equivalents. - -### Type safe operations in integrations - -While working on integrations, you may not be able to benefit from Astro’s generated table types exported from `astro:db`. -For full type safety, use the `asDrizzleTable()` utility to create a table reference object you can use for database operations. - -For example, given an integration setting up the following `Pets` database table: - -```js -// my-integration/config.ts -import { defineDb, defineTable, column } from 'astro:db'; - -export const Pets = defineTable({ - columns: { - name: column.text(), - species: column.text(), - }, -}); - -export default defineDb({ tables: { Pets } }); -``` - -The seed file can import `Pets` and use `asDrizzleTable()` to insert rows into your table with type checking: - -```js {2,7} /typeSafePets(?! )/ -// my-integration/seed.ts -import { asDrizzleTable } from '@astrojs/db/utils'; -import { db } from 'astro:db'; -import { Pets } from './config'; - -export default async function() { - const typeSafePets = asDrizzleTable('Pets', Pets); - - await db.insert(typeSafePets).values([ - { name: 'Palomita', species: 'cat' }, - { name: 'Pan', species: 'dog' }, - ]); -} -``` - -The value returned by `asDrizzleTable('Pets', Pets)` is equivalent to `import { Pets } from 'astro:db'`, but is available even when Astro’s type generation can’t run. -You can use it in any integration code that needs to query or insert into the database. - - - - -## Migrate from Astro Studio to Turso - - - -1. In the [Studio dashboard](https://studio.astro.build/), navigate to the project you wish to migrate. In the settings tab, use the "Export Database" button to download a dump of your database. -2. Follow the official instructions to [install the Turso CLI](https://docs.turso.tech/cli/installation) and [sign up or log in](https://docs.turso.tech/cli/authentication) to your Turso account. -3. Create a new database on Turso using the `turso db create` command. - ```sh - turso db create [database-name] - ``` -4. Fetch the database URL using the Turso CLI, and use it as the environment variable `ASTRO_DB_REMOTE_URL`. - ```sh - turso db show [database-name] - ``` - ```dotenv - ASTRO_DB_REMOTE_URL=[your-database-url] - ``` -5. Create a token to access your database, and use it as the environment variable `ASTRO_DB_APP_TOKEN`. - ```sh - turso db tokens create [database-name] - ``` - ```dotenv - ASTRO_DB_APP_TOKEN=[your-app-token] - ``` -6. Push your DB schema and metadata to the new Turso database. - ```sh - astro db push --remote - ``` -7. Import the database dump from step 1 into your new Turso DB. - ```sh - turso db shell [database-name] < ./path/to/dump.sql - ``` -8. Once you have confirmed your project connects to the new database, you can safely delete the project from Astro Studio. - - diff --git a/src/content/docs/en/guides/build-with-ai.mdx b/src/content/docs/en/guides/build-with-ai.mdx index 500c92ed07ed5..5763d582929f9 100644 --- a/src/content/docs/en/guides/build-with-ai.mdx +++ b/src/content/docs/en/guides/build-with-ai.mdx @@ -9,6 +9,8 @@ i18nReady: true description: Resources and tips for building Astro sites with AI assistance --- +import Since from '~/components/Since.astro'; +import ReadMore from '~/components/ReadMore.astro'; import { Steps, LinkButton, Card, Tabs, TabItem } from '@astrojs/starlight/components'; AI-powered editors and agentic coding tools generally have good knowledge of Astro's core APIs and concepts. However, some may use older APIs and may not be aware of newer features or recent changes to the framework. @@ -356,6 +358,28 @@ The same technology that powers Astro's MCP server is also available as a chatbo **Conversations with the chatbot are public, and are subject to the same server rules for language and behavior as the rest of our channels**, but they are not actively visited by our volunteer support members. For assistance from the community, please create a thread in our regular `#support` channel. +## Background mode + +

+ +When an AI coding agent is detected, `astro dev` automatically starts the dev server as a detached background process. This prevents the dev server from blocking the agent's terminal and allows it to continue working while the server runs. + +A lock file (`.astro/dev.json`) is written when the dev server starts, recording the server's URL, port, and PID. This prevents duplicate servers from being started for the same project. + +If you are not using an AI coding agent, `astro dev` starts in the foreground process and logs to the terminal. + +To opt out of automatic background mode, set the `ASTRO_DEV_BACKGROUND` environment variable before running `astro dev`: + +```shell +ASTRO_DEV_BACKGROUND=0 astro dev +``` + +See the [CLI reference](/en/reference/cli-reference/#astro-dev) for the full list of `astro dev` flags and subcommands. + +### Health endpoint + +The dev server exposes a `/_astro/status` endpoint that returns `{"ok": true}` as JSON. This allows agents and other tools to check programmatically whether the dev server is ready to accept requests. This endpoint is only available in the dev server and does not exist in production builds. + ## Tips for AI-Powered Astro Development - **Start with templates**: Rather than building from scratch, ask AI tools to start with an existing [Astro template](https://astro.build/themes/) or use `npm create astro@latest` with a template option. diff --git a/src/content/docs/en/guides/integrations-guide/cloudflare.mdx b/src/content/docs/en/guides/integrations-guide/cloudflare.mdx index e663d1a1971aa..047e4e903395e 100644 --- a/src/content/docs/en/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/en/guides/integrations-guide/cloudflare.mdx @@ -428,6 +428,58 @@ export default defineConfig({ }); ``` +## Using advanced routing + +

+ +The Cloudflare adapter provides companion handlers that apply Cloudflare-specific setup to your [advanced routing pipeline](/en/guides/routing/#advanced-routing). These handlers configure session KV binding injection, static asset serving via the `ASSETS` binding, `Astro.locals.cfContext`, client address from the `cf-connecting-ip` header, `waitUntil`, and prerendered error page fetching. + +You can use the [`astro/fetch`](/en/reference/modules/astro-fetch/) and [`astro/hono`](/en/reference/modules/astro-hono/) APIs from `src/fetch.ts` on Cloudflare without these handlers. The adapter's default entrypoint takes care of Cloudflare-specific setup for you. These companion handlers are useful when you already have a [custom worker entrypoint](https://developers.cloudflare.com/workers/wrangler/configuration/#inheritable-keys) (`src/worker.ts`), for example, to export a Durable Object, and want to use the advanced routing APIs directly from that file instead. + +When using these handlers in your worker entrypoint, they replace the functionality of the adapter's default handler, so you should not use both at the same time. Place the Cloudflare handler before other Astro handlers so that bindings and locals are available to the rest of the pipeline. + +### With the Fetch API + +

+ +For use with [`astro/fetch`](/en/reference/modules/astro-fetch/). The `cf()` function imported from `@astrojs/cloudflare/fetch` receives a [`FetchState`](/en/reference/modules/astro-fetch/#fetchstate), the Cloudflare `env`, and the `ExecutionContext`. It returns a `Response` for static asset hits, or `undefined` when the request should continue to Astro rendering: + +```ts title="src/worker.ts" +import { astro, FetchState } from 'astro/fetch'; +import { cf } from '@astrojs/cloudflare/fetch'; + +export default { + async fetch(request: Request, env: Env, ctx: ExecutionContext) { + const state = new FetchState(request); + const asset = await cf(state, env, ctx); + if (asset) return asset; + return astro(state); + }, +}; +``` + +### With Hono + +

+ +For use with [`astro/hono`](/en/reference/modules/astro-hono/). The `cf()` function imported from `@astrojs/cloudflare/hono` returns a Hono middleware that reads `env` and `executionCtx` from the Hono context automatically: + +```ts title="src/worker.ts" +import { Hono } from 'hono'; +import { actions, middleware, pages, i18n } from 'astro/hono'; +import { cf } from '@astrojs/cloudflare/hono'; + +const app = new Hono<{ Bindings: Env }>(); + +app.use(cf()); +app.use(actions()); +app.use(middleware()); +app.use(pages()); +app.use(i18n()); + +export default app; +``` + ## Upgrading to v13 and Astro 6 Astro 6 brings significant improvements to the Cloudflare development experience and requires `@astrojs/cloudflare` v13 or later. Now, `astro dev` uses Cloudflare's Vite plugin and `workerd` runtime to closely mirror production behavior. diff --git a/src/content/docs/en/guides/integrations-guide/db.mdx b/src/content/docs/en/guides/integrations-guide/db.mdx index 808eda519aa5b..3f4f08a057f2c 100644 --- a/src/content/docs/en/guides/integrations-guide/db.mdx +++ b/src/content/docs/en/guides/integrations-guide/db.mdx @@ -1,399 +1,11 @@ --- -type: integration title: '@astrojs/db' description: Learn how to use the @astrojs/db integration in your Astro project. -sidebar: - label: DB -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -category: other i18nReady: true --- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -:::caution[Deprecated] -The Astro DB integration has been deprecated in Astro v6.5 and is no longer maintained. +:::caution[Removed] +The Astro DB integration was deprecated in v6.4 and has been removed since Astro v7.0. -If you were using this integration in your project, we recommend that you use a database client (e.g., Drizzle, Kysely) directly in your Astro project. +If you were using this integration in your project, we recommend migrating to a third-party library for database functionality. See the [Astro v7.0 migration guide](/en/guides/upgrade-to/v7/#removed-astrojsdb) for more details and recommendations on how to update your project. ::: - -Astro DB is a fully-managed SQL database designed for the Astro ecosystem: develop locally in Astro and deploy to any [libSQL-compatible database](/en/guides/astro-db/). - -With Astro DB you have a powerful, local, type-safe tool to query and model content as a relational database. - -See the [Astro DB guide](/en/guides/astro-db/) for full usage and examples. - -## Installation - -Astro includes an `astro add` command to automate the setup of official integrations. If you prefer, you can [install integrations manually](#manual-installation) instead. - -Run one of the following commands in a new terminal window. - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -#### Manual Installation - -If you prefer to set things up from scratch yourself, skip `astro add` and follow these instructions to install Astro DB yourself. - -##### 1. Install the integration from npm via a package manager - - - - ```shell - npm install @astrojs/db - ``` - - - ```shell - pnpm add @astrojs/db - ``` - - - ```shell - yarn add @astrojs/db - ``` - - - -##### 2. Add the integration to `astro.config.mjs` - - ```js title="astro.config.mjs" ins={2,6} - import { defineConfig } from 'astro/config'; - import db from '@astrojs/db'; - - export default defineConfig({ - integrations: [ - db() - ] - }); - ``` - -##### 3. Configure your database - -Create a `db/config.ts` file at the root of your project. This is a special file that Astro will automatically load and use to configure your database tables. - -```ts -// db/config.ts -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: {}, -}) -``` - -## Configuration - -### `mode` - -

- -**Type:** `'node' | 'web'`
-**Default:** `'node'`
- -

- -Configures the driver to use to connect to your database in production. - -By default, Astro DB uses a Node.js-based libSQL driver for production deployments. The `node` driver mode is sufficient for most Astro hosted or self-hosted websites with Node.js runtimes. This allows you to connect to your database over several protocols, including `memory:`, `file:`, `ws:`, `wss:`, `libsql`, `http`, and `https`, as well as allowing for more advanced features such as [embedded replicas](/en/guides/astro-db/#syncurl). - -When deploying to a serverless environment on a non-Node.js runtime, such as Cloudflare Workers or Deno, a web-based libSQL driver is available. When deploying using the `web` mode, you will be able to make web-based connections over `libsql`, `http`, or `https`. - -To use the web libSQL driver mode for non-Node.js environments, set the `mode` property in your adapter's configuration: - -```ts title="astro.config.mjs" ins={7} -import { defineConfig } from 'astro/config'; -import db from '@astrojs/db'; - -export default defineConfig({ - integrations: [ - db({ - mode: 'web' - }) - ] -}); -``` - -## Table configuration reference - -### `columns` - -

- -**Type:** `ColumnsConfig` -

- -Table columns are configured using the `columns` object: - -```ts -import { defineTable, column, NOW } from 'astro:db'; - -const Comment = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - author: column.text(), - content: column.text({ optional: true }), - published: column.date({ default: NOW }), - }, -}); -``` - -Columns are configured using the `column` utility. `column` supports the following types: - -- **`column.text(...)`** - store either plain or rich text content -- **`column.number(...)`** - store integer and floating point values -- **`column.boolean(...)`** - store true / false values -- **`column.date(...)`** - store `Date` objects, parsed as ISO strings for data storage -- **`column.json(...)`** - store arbitrary JSON blobs, parsed as stringified JSON for data storage - -There are a few shared configuration values across all columns: - -- `primaryKey` - Set a `number` or `text` column as the unique identifier. -- `optional` - Astro DB uses `NOT NULL` for all columns by default. Set `optional` to `true` to allow null values. -- `default` - Set the default value for newly inserted entries. This accepts either a static value or a string of `sql` for generated values like timestamps. -- `unique` - Mark a column as unique. This prevents duplicate values across entries in the table. -- `references` - Reference a related table by column. This establishes a foreign key constraint, meaning each column value must have a matching value in the referenced table. - -A `text` column can optionally define a list of string literals to serve as an enum for generating types. However, **no runtime validation will be performed**. Removing, adding, and changing values should be handled in your project code. - -```ts title="db/config.ts" {8} -import { defineTable, column } from 'astro:db'; - -// Table definition -const UserTable = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - rank: column.text({ enum: ['user', 'mod', 'admin'] }), - }, -}); - -// Resulting type definition -type UserTableInferInsert = { - id?: string; - name: string; - rank: "user" | "mod" | "admin"; -} -``` - -### `indexes` - -

- -**Type:** `{ on: string | string[]; unique?: boolean | undefined; name?: string | undefined; }[]` -

- -Table indexes are used to improve lookup speeds on a given column or combination of columns. The `indexes` property accepts an array of configuration objects specifying the columns to index: - -```ts title="db/config.ts" {9-11} -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - authorId: column.number(), - published: column.date(), - body: column.text(), - }, - indexes: [ - { on: ["authorId", "published"], unique: true }, - ] -}); -``` - -This will generate a unique index on the `authorId` and `published` columns with the name `Comment_authorId_published_idx`. - -The following configuration options are available for each index: - -- `on` - A single column or array of column names to index. -- `unique` (optional) - Set to `true` to enforce unique values across the indexed columns. -- `name` (optional) - A custom name for the unique index. This will override Astro's generated name based on the table and column names being indexed (e.g. `Comment_authorId_published_idx`). Custom names are global, so ensure index names do not conflict between tables. - -### `foreignKeys` - -

- -**Type:** `{ columns: string | string[]; references: () => Column | Column[]; }[]` -

- -:::tip - -`foreignKeys` is an advanced API for relating multiple table columns. If you only need to reference a single column, try using [the column `references` property.](#columns) - -::: - -Foreign keys are used to establish a relationship between two tables. The `foreignKeys` property accepts an array of configuration objects that may relate one or more columns between tables: - -```ts title="db/config.ts" {12-20} -import { defineTable, column } from 'astro:db'; - -const Author = defineTable({ - columns: { - firstName: column.text(), - lastName: column.text(), - }, -}); - -const Comment = defineTable({ - columns: { - authorFirstName: column.text(), - authorLastName: column.text(), - body: column.text(), - }, - foreignKeys: [ - { - columns: ["authorFirstName", "authorLastName"], - references: () => [Author.columns.firstName, Author.columns.lastName], - }, - ], -}); -``` - -Each foreign key configuration object accepts the following properties: - -- `columns` - A single column or array of column names to relate to the referenced table. -- `references` - A function that returns a single column or an array of columns from the referenced table. - -## Astro DB CLI reference - -Astro DB includes a set of CLI commands to interact with your local and libSQL-compatible database. - -These commands are called automatically when using a GitHub CI action, and can be called manually using the `astro db` CLI. - -### `astro db push` - -**Flags:** - -- `--db-app-token ` Provide the remote database app token directly instead of `ASTRO_DB_APP_TOKEN`. -- `--dry-run` Print the generated SQL statements without applying them. -- `--force-reset` Reset all production data if a breaking schema change is required. -- `--remote` Push to your remote database instead of the local database file. Requires the `ASTRO_DB_REMOTE_URL` environment variable to be set, and either `ASTRO_DB_APP_TOKEN` to be set in the environment or a value passed with the `--db-app-token` command-line argument. - -Safely push database configuration changes to your project database. This will check for any risk of data loss and guide you on any recommended migration steps. Use `--remote` to apply changes to your remote database. If a breaking schema change must be made, use `--force-reset` to reset all production data. - -### `astro db verify` - -**Flags:** - -- `--db-app-token ` Provide the remote database app token directly instead of `ASTRO_DB_APP_TOKEN`. -- `--json` Print a machine-readable JSON result from `verify`. -- `--remote` Compare against your remote database instead of the local database file. Requires the `ASTRO_DB_REMOTE_URL` environment variable to be set, and either `ASTRO_DB_APP_TOKEN` to be set in the environment or a value passed with the `--db-app-token` command-line argument. - -Compares your local schema against the remote database to check for any differences between your local and remote database configurations. This is automatically run by `astro db push`. - -`verify` will compare your local `db/config.ts` file with the remote database and warn if changes are detected. It will exit with a non-zero code if changes are required or unsafe, making it useful for CI. - -### `astro db execute ` - -**Flags:** - -- `--db-app-token ` Provide the remote database app token directly instead of `ASTRO_DB_APP_TOKEN`. -- `--remote` Run against your libSQL-compatible database. Omit to run against your local database file. Requires the `ASTRO_DB_REMOTE_URL` environment variable to be set, and either `ASTRO_DB_APP_TOKEN` to be set in the environment or a value passed with the `--db-app-token` command-line argument. - -Execute a `.ts` or `.js` file to read or write to your database. This accepts a file path as an argument, and supports usage of the `astro:db` module to write type-safe queries. Use the `--remote` flag to run against your libSQL-compatible database, or omit the flag to run against your local database file. See how to [seed development data](/en/guides/astro-db/#seed-your-database-for-development) for an example file. - -### `astro db shell --query ` - -**Flags:** - -- `--query` Raw SQL query to execute. -- `--remote` Run against your libSQL-compatible database. Omit to run against your local database file. Requires the `ASTRO_DB_REMOTE_URL` environment variable to be set, and either `ASTRO_DB_APP_TOKEN` to be set in the environment or a value passed with the `--db-app-token` command-line argument. - -Execute a raw SQL query against your database. - -The following example selects all rows from a `Comment` table in a remote database: - -```sh -npx astro db shell --query "SELECT * FROM Comment;" --remote -``` - -## Astro DB utility reference - -The following utilities are imported from the `astro:db` module: - -```ts -import { - isDbError, - getDbError -} from "astro:db"; -``` - -### `isDbError()` - -

- -**Type:** `(err: unknown) => boolean`
- -

- -Checks if an error is a libSQL database exception. This may include a foreign key constraint error when using references, or missing fields when inserting data. You can combine `isDbError()` with a try / catch block to handle database errors in your application: - -```ts title="src/pages/api/comment/[id].ts" "idDbError" -import { db, Comment, isDbError } from 'astro:db'; -import type { APIRoute } from 'astro'; - -export const POST: APIRoute = (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - if (isDbError(e)) { - return new Response(`Cannot insert comment with id ${id}\n\n${e.message}`, { status: 400 }); - } - return new Response('An unexpected error occurred', { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; -``` - -### `getDbError()` - -

- -**Type:** `(err: unknown) => LibsqlError | undefined`
- -

- -Walks through an error's cause chain to find the underlying libSQL database exception. This returns a `LibsqlError` or `undefined` if the error is not from LibSQL. This is useful when another error (e.g. `DrizzleQueryError`) may wrap the database error. - -The following example extracts the database error from a caught exception and returns the error code and message in the response: - -```ts title="src/pages/api/comment/[id].ts" "getDbError" -import { getDbError } from 'astro:db'; - -export const POST: APIRoute = (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - const dbError = getDbError(e); - if (dbError) { - return new Response(`Database error: ${dbError.code}\n\n${dbError.message}`, { status: 400 }); - } - return new Response('An unexpected error occurred', { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; -``` diff --git a/src/content/docs/en/guides/integrations-guide/mdx.mdx b/src/content/docs/en/guides/integrations-guide/mdx.mdx index 0560b639fe9b2..e35b6a9eeafa0 100644 --- a/src/content/docs/en/guides/integrations-guide/mdx.mdx +++ b/src/content/docs/en/guides/integrations-guide/mdx.mdx @@ -266,10 +266,9 @@ All [`markdown` configuration options](/en/reference/configuration-reference/#ma ```js title="astro.config.mjs" import { defineConfig } from 'astro/config'; -import { unified } from '@astrojs/markdown-remark'; +import { satteri } from '@astrojs/markdown-satteri'; import mdx from '@astrojs/mdx'; -import remarkToc from 'remark-toc'; -import rehypePresetMinify from 'rehype-preset-minify'; +import { myMdastPlugin } from './my-satteri-plugin.mjs'; export default defineConfig({ // ... @@ -277,11 +276,9 @@ export default defineConfig({ mdx({ syntaxHighlight: 'shiki', shikiConfig: { theme: 'dracula' }, - processor: unified({ - remarkPlugins: [remarkToc], - rehypePlugins: [rehypePresetMinify], - remarkRehype: { footnoteLabel: 'Footnotes' }, - gfm: false + processor: satteri({ + mdastPlugins: [myMdastPlugin()], + features: { gfm: false }, }), }), ], @@ -301,16 +298,16 @@ export default defineConfig({ By default, `.mdx` files render through the same [Markdown processor](/en/guides/markdown-content/#choosing-a-markdown-processor) as your `.md` files. Set `processor` to use a different processor, or the same processor with different options, for `.mdx` files only. -For example, to keep the default remark/rehype processor for `.md` files while rendering `.mdx` files with [Sätteri](https://satteri.bruits.org/) using `@astrojs/markdown-satteri`: +For example, to keep the default [Sätteri](https://satteri.bruits.org/) processor for `.md` files while rendering `.mdx` files with remark and rehype using `@astrojs/markdown-remark`: ```js title="astro.config.mjs" import { defineConfig } from 'astro/config'; -import { satteri } from '@astrojs/markdown-satteri'; +import { unified } from '@astrojs/markdown-remark'; import mdx from '@astrojs/mdx'; export default defineConfig({ integrations: [ - mdx({ processor: satteri() }), + mdx({ processor: unified() }), ], }); ``` @@ -330,14 +327,14 @@ For example, say you need a different syntax highlighter and a different set of ```js title="astro.config.mjs" import { defineConfig } from 'astro/config'; -import { unified } from '@astrojs/markdown-remark'; +import { satteri } from '@astrojs/markdown-satteri'; import mdx from '@astrojs/mdx'; export default defineConfig({ // ... markdown: { syntaxHighlight: 'prism', - processor: unified({ remarkPlugins: [remarkPlugin1] }), + processor: satteri({ mdastPlugins: [mdastPlugin1] }), }, integrations: [ mdx({ @@ -346,7 +343,7 @@ export default defineConfig({ syntaxHighlight: 'shiki', // `markdown.processor` gets overridden for `.mdx` files by this option - processor: unified({ remarkPlugins: [remarkPlugin2] }), + processor: satteri({ mdastPlugins: [mdastPlugin2] }), }), ], }); @@ -356,19 +353,19 @@ You may also need to disable `markdown` config extension in MDX. For this, set ` ```js title="astro.config.mjs" import { defineConfig } from 'astro/config'; -import { unified } from '@astrojs/markdown-remark'; +import { satteri } from '@astrojs/markdown-satteri'; import mdx from '@astrojs/mdx'; export default defineConfig({ // ... markdown: { - processor: unified({ remarkPlugins: [remarkPlugin] }), + processor: satteri({ mdastPlugins: [mdastPlugin] }), }, integrations: [ mdx({ // Markdown config now ignored extendMarkdownConfig: false, - // Default `unified()` processor used + // Default `satteri()` processor used }), ], }); @@ -385,6 +382,8 @@ export default defineConfig({ These are plugins that modify the output [estree](https://github.com/estree/estree) directly. This is useful for modifying or injecting JavaScript variables in your MDX files. +Since Astro v7, the default Markdown processor does not support Recma plugins. If your project depends on them, you can [use the `unified()` processor](/en/guides/markdown-content/#switching-to-the-unified-processor). + We suggest [using AST Explorer](https://astexplorer.net/) to play with estree outputs, and trying [`estree-util-visit`](https://unifiedjs.com/explore/package/estree-util-visit/) for searching across JavaScript nodes. ### `optimize` diff --git a/src/content/docs/en/guides/markdown-content.mdx b/src/content/docs/en/guides/markdown-content.mdx index 4289cd93df991..695bcad7feeb7 100644 --- a/src/content/docs/en/guides/markdown-content.mdx +++ b/src/content/docs/en/guides/markdown-content.mdx @@ -10,6 +10,7 @@ import { FileTree } from '@astrojs/starlight/components'; import RecipeLinks from "~/components/RecipeLinks.astro"; import ReadMore from '~/components/ReadMore.astro'; import { Steps, Tabs, TabItem } from '@astrojs/starlight/components'; +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; [Markdown](https://daringfireball.net/projects/markdown/) is commonly used to author text-heavy content like blog posts and documentation. Astro includes built-in support for Markdown files that can also include [frontmatter YAML](https://dev.to/paulasantamaria/introduction-to-yaml-125f) (or [TOML](https://toml.io)) to define custom properties such as a title, description, and tags. @@ -72,7 +73,7 @@ const posts = Object.values(import.meta.glob('./posts/*.md', { eager: true })); When fetching data from your collections with the helper functions `getCollection()` or `getEntry()`, your Markdown's frontmatter properties are available on a `data` object (e.g. `post.data.title`). Additionally, `body` contains the raw, uncompiled body content as a string. -The [`render()`](/en/reference/modules/astro-content/#render) function returns your Markdown body content, a generated list of headings, as well as a modified frontmatter object after any remark or rehype plugins have been applied. +The [`render()`](/en/reference/modules/astro-content/#render) function returns your Markdown body content, a generated list of headings, as well as a modified frontmatter object after any Markdown plugins have been applied. Read more about [using content returned by a collections query](/en/guides/content-collections/#using-content-in-astro-templates). @@ -164,17 +165,17 @@ You can customize these heading IDs with a [Markdown processor](#choosing-a-mark Astro injects `id` attributes after your custom plugins have run, so any ID set by a plugin is preserved. If one of your custom plugins needs to access the IDs injected by Astro, you can import Astro's heading ids plugin and place it before any plugins that rely on it: - + ```js title="astro.config.mjs" ins={2-3, 9} import { defineConfig } from 'astro/config'; - import { unified, rehypeHeadingIds } from '@astrojs/markdown-remark'; + import { satteri, satteriHeadingIdsPlugin } from '@astrojs/markdown-satteri'; import { otherPluginThatReliesOnHeadingIDs } from 'some/plugin/source'; export default defineConfig({ markdown: { - processor: unified({ - rehypePlugins: [ - rehypeHeadingIds, + processor: satteri({ + hastPlugins: [ + satteriHeadingIdsPlugin(), otherPluginThatReliesOnHeadingIDs, ], }), @@ -182,17 +183,17 @@ Astro injects `id` attributes after your custom plugins have run, so any ID set }); ``` - + ```js title="astro.config.mjs" ins={2-3, 9} import { defineConfig } from 'astro/config'; - import { satteri, satteriHeadingIdsPlugin } from '@astrojs/markdown-satteri'; + import { unified, rehypeHeadingIds } from '@astrojs/markdown-remark'; import { otherPluginThatReliesOnHeadingIDs } from 'some/plugin/source'; export default defineConfig({ markdown: { - processor: satteri({ - hastPlugins: [ - satteriHeadingIdsPlugin(), + processor: unified({ + rehypePlugins: [ + rehypeHeadingIds, otherPluginThatReliesOnHeadingIDs, ], }), @@ -204,26 +205,82 @@ Astro injects `id` attributes after your custom plugins have run, so any ID set ## Markdown Plugins -Astro renders Markdown using a configurable **Markdown processor**. By default, this is the [unified](https://unifiedjs.com/) pipeline of [remark](https://remark.js.org/) and [rehype](https://github.com/rehypejs/rehype), with an active plugin ecosystem. +Astro renders Markdown using a configurable **Markdown processor**. By default, this is [Sätteri](https://satteri.bruits.org/), Astro's native Markdown and MDX pipeline, included with Astro. Astro applies [GitHub-Flavored Markdown](https://github.github.com/gfm/) and [SmartyPants](https://daringfireball.net/projects/smartypants/) automatically. This brings some niceties like generating clickable links from text, and formatting for quotations and em-dashes. -You can extend Markdown processing with plugins, enable additional parser features, or [switch to a different processor entirely](#switching-to-the-sätteri-processor). See the full list of [Markdown configuration options](/en/reference/configuration-reference/#markdown-options). +You can extend Markdown processing with plugins, enable additional parser features, or [switch to a different processor entirely](#switching-to-the-unified-processor). See the full list of [Markdown configuration options](/en/reference/configuration-reference/#markdown-options). ### Choosing a Markdown processor The [`markdown.processor` option](/en/reference/configuration-reference/#markdownprocessor) controls which engine renders your `.md` and `.mdx` files. Astro provides two official options: -- **`unified()`** (default): the [remark](https://remark.js.org/) and [rehype](https://github.com/rehypejs/rehype) pipeline, with its large plugin ecosystem. -- **`satteri()`**: the native [Sätteri](https://satteri.bruits.org/) pipeline, a faster Markdown and MDX compiler with its own plugin model. Provided by `@astrojs/markdown-satteri`, which you install separately. +- **`satteri()`** (default): the native [Sätteri](https://satteri.bruits.org/) pipeline, a fast Markdown and MDX compiler with its own plugin model. Included with Astro, so no extra installation is needed. +- **`unified()`**: the [remark](https://remark.js.org/) and [rehype](https://github.com/rehypejs/rehype) pipeline, with its large plugin ecosystem. Provided by `@astrojs/markdown-remark`, which you install separately. + +### Using Sätteri plugins and features + +The default `satteri()` processor accepts its own plugins through `mdastPlugins` and `hastPlugins`, and toggles optional parser features through `features`. See the [Sätteri documentation](https://satteri.bruits.org/docs/) for the available plugins and features. + +Import `satteri` from `@astrojs/markdown-satteri` and pass your options to it through `markdown.processor`. This example adds an mdast plugin and enables the `directive` parser feature: + +```js title="astro.config.mjs" +import { defineConfig } from 'astro/config'; +import { satteri } from '@astrojs/markdown-satteri'; +import { myMdastPlugin } from './my-satteri-plugin.mjs'; -### Using remark and rehype plugins +export default defineConfig({ + markdown: { + processor: satteri({ + mdastPlugins: [myMdastPlugin()], + features: { directive: true }, + }), + }, +}); +``` -The default `unified()` processor accepts third-party [remark](https://github.com/remarkjs/remark) and [rehype](https://github.com/rehypejs/rehype) plugins. These plugins allow you to extend your Markdown with new capabilities, like [auto-generating a table of contents](https://github.com/remarkjs/remark-toc), [applying accessible emoji labels](https://github.com/florianeckerstorfer/remark-a11y-emoji), and [styling your Markdown](/en/guides/styling/#markdown-styling). +### Switching to the unified processor + +To use [remark and rehype](https://unifiedjs.com/) instead of Sätteri, install `@astrojs/markdown-remark`, then import `unified` and pass it to `markdown.processor`: + + + + ```shell + npm install @astrojs/markdown-remark + ``` + + + ```shell + pnpm add @astrojs/markdown-remark + ``` + + + ```shell + yarn add @astrojs/markdown-remark + ``` + + + +```js title="astro.config.mjs" +import { defineConfig } from 'astro/config'; +import { unified } from '@astrojs/markdown-remark'; + +export default defineConfig({ + markdown: { + processor: unified(), + }, +}); +``` + +Switching processors replaces Sätteri for both `.md` and `.mdx` files. Any Sätteri plugins in your config will not apply. To use remark and rehype only for `.mdx` files, set the [`processor` option on the MDX integration](/en/guides/integrations-guide/mdx/#processor) instead. + +#### Using remark and rehype plugins + +The `unified()` processor accepts third-party [remark](https://github.com/remarkjs/remark) and [rehype](https://github.com/rehypejs/rehype) plugins. These plugins allow you to extend your Markdown with new capabilities, like [auto-generating a table of contents](https://github.com/remarkjs/remark-toc), [applying accessible emoji labels](https://github.com/florianeckerstorfer/remark-a11y-emoji), and [styling your Markdown](/en/guides/styling/#markdown-styling). We encourage you to browse [awesome-remark](https://github.com/remarkjs/awesome-remark) and [awesome-rehype](https://github.com/rehypejs/awesome-rehype) for popular plugins! See each plugin's own README for specific installation instructions. -Import `unified` from `@astrojs/markdown-remark` and pass your plugins to it through `markdown.processor`. This example applies [`remark-toc`](https://github.com/remarkjs/remark-toc) and [`rehype-accessible-emojis`](https://www.npmjs.com/package/rehype-accessible-emojis) to Markdown files: +After [switching to the `unified()` processor](#switching-to-the-unified-processor), pass your plugins to it through `markdown.processor`. This example applies [`remark-toc`](https://github.com/remarkjs/remark-toc) and [`rehype-accessible-emojis`](https://www.npmjs.com/package/rehype-accessible-emojis) to Markdown files: ```js title="astro.config.mjs" import { defineConfig } from 'astro/config'; @@ -241,7 +298,7 @@ export default defineConfig({ }); ``` -### Customizing a remark or rehype plugin +#### Customizing a remark or rehype plugin In order to customize a plugin, provide an options object after it in a nested array. @@ -264,29 +321,6 @@ export default defineConfig({ }); ``` -### Switching to the Sätteri processor - -To use [Sätteri](https://satteri.bruits.org/) instead of remark and rehype, install `@astrojs/markdown-satteri`, then import `satteri` and pass it to `markdown.processor`: - -```js title="astro.config.mjs" -import { defineConfig } from 'astro/config'; -import { satteri } from '@astrojs/markdown-satteri'; -import { myMdastPlugin } from './my-satteri-plugin.mjs'; - -export default defineConfig({ - markdown: { - processor: satteri({ - mdastPlugins: [myMdastPlugin()], - features: { directive: true }, - }), - }, -}); -``` - -The Sätteri processor accepts its own plugins through `mdastPlugins` and `hastPlugins`, and toggles optional parser features through `features`. See the [Sätteri documentation](https://satteri.bruits.org/docs/) for the available plugins and features. - -Switching processors replaces remark and rehype for both `.md` and `.mdx` files. Any remark or rehype plugins in your config will not apply. To use Sätteri only for `.mdx` files, set the [`processor` option on the MDX integration](/en/guides/integrations-guide/mdx/#processor) instead. - ### Modifying frontmatter programmatically When using the [remark/rehype processor](#using-remark-and-rehype-plugins), you can add frontmatter properties to all of your Markdown and MDX files with a remark or rehype plugin. @@ -353,21 +387,21 @@ The following example uses a different syntax highlighter and a different set of ```ts title="astro.config.mjs" import { defineConfig } from 'astro/config'; -import { unified } from '@astrojs/markdown-remark'; +import { satteri } from '@astrojs/markdown-satteri'; import mdx from '@astrojs/mdx'; export default defineConfig({ markdown: { syntaxHighlight: 'prism', - processor: unified({ remarkPlugins: [remarkPlugin1] }), + processor: satteri({ mdastPlugins: [mdastPlugin1] }), }, integrations: [ mdx({ // `markdown.syntaxHighlight` gets overridden for `.mdx` files by this option syntaxHighlight: 'shiki', - // `markdown.processor` gets overridden for `.mdx` files with a different remark plugin - processor: unified({ remarkPlugins: [remarkPlugin2] }), + // `markdown.processor` gets overridden for `.mdx` files with a different plugin + processor: satteri({ mdastPlugins: [mdastPlugin2] }), }) ] }); @@ -377,18 +411,18 @@ To avoid extending your Markdown config from MDX, set [the `extendMarkdownConfig ```ts title="astro.config.mjs" import { defineConfig } from 'astro/config'; -import { unified } from '@astrojs/markdown-remark'; +import { satteri } from '@astrojs/markdown-satteri'; import mdx from '@astrojs/mdx'; export default defineConfig({ markdown: { - processor: unified({ remarkPlugins: [remarkPlugin] }), + processor: satteri({ mdastPlugins: [mdastPlugin] }), }, integrations: [ mdx({ // Markdown config now ignored extendMarkdownConfig: false, - // Default `unified()` processor used with no plugins + // Default `satteri()` processor used with no plugins }) ] }); diff --git a/src/content/docs/en/guides/routing.mdx b/src/content/docs/en/guides/routing.mdx index 30e5a801b2913..3d73381673093 100644 --- a/src/content/docs/en/guides/routing.mdx +++ b/src/content/docs/en/guides/routing.mdx @@ -575,3 +575,149 @@ In this example, only `src/pages/index.astro` and `src/pages/projects/project1.m - _utils.js - **project1.md** + +## Advanced routing + +

+ +By default, Astro handles every request with a built-in pipeline that runs the handlers in a fixed order: trailing-slash normalization, redirects, sessions, actions, user middleware, page rendering, i18n, and caching. This pipeline is designed to cover the most common use cases for routing and request handling, but it may not fit every project’s needs. + +Astro's advanced routing allows you to replace this pipeline with your own. You can choose which built-in features to use and where to use them. You can also add your own custom logic anywhere in the pipeline. This gives you full control over how Astro handles incoming requests. + +### Creating a custom entrypoint + +When the default pipeline does not fit your needs, you can override it by creating a `src/fetch.ts` file that default-exports an object with a `fetch()` method. This method receives a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) and must return a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). + +```ts title="src/fetch.ts" +import type { Fetchable } from 'astro'; + +export default { + async fetch(request) { + // Your custom request handling logic here + return new Response("Hello from advanced routing!"); + } +} satisfies Fetchable; +``` + +Astro supports several file formats for its advanced routing entrypoint: `.ts`, `.js`, `.mjs`, and `.mts`. We recommend using `.js` in most cases or `.ts` if you need TypeScript support. + +### Changing the entrypoint filename + +By default, Astro looks for `src/fetch.ts` as the advanced routing entrypoint. You can change this by setting the [`fetchFile`](/en/reference/configuration-reference/#fetchfile) option in your Astro config file. + +The following example tells Astro to look for `src/handler.ts` instead of `src/fetch.ts`: + +```js title="astro.config.mjs" +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + fetchFile: 'handler', +}); +``` + +Set `fetchFile` to `null` to disable the entrypoint entirely. This is useful if you already have a `src/fetch.ts` file used for other purposes: + +```js title="astro.config.mjs" +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + fetchFile: null, +}); +``` + +### Adding custom logic + +The main benefit of advanced routing is the ability to insert custom logic into the request pipeline. You can run code before Astro touches the request, between pipeline stages, or after the response is produced. + +You can do this in two ways: + +- Use the [`astro()` handler](/en/reference/modules/astro-fetch/#astro) to run the full built-in pipeline, and add logic before or after it. +- Compose individual handlers from [`astro/fetch`](/en/reference/modules/astro-fetch/) or [`astro/hono`](/en/reference/modules/astro-hono/) for more control over execution order. + +#### Running the full pipeline with `astro()` + +Use [`astro()`](/en/reference/modules/astro-fetch/#astro) when you want to keep Astro's built-in routing behavior, but need custom logic around it. This approach preserves the default pipeline order and lets you add pre-processing and post-processing in one place. For many use cases, such as adding auth guards, request logging, and custom headers, `astro()` is all you need. + +The following example checks if a user can access a dashboard before running the Astro pipeline, and adds a custom header to the response once Astro has finished running: + +```ts title="src/fetch.ts" +import { FetchState, astro } from 'astro/fetch'; + +export default { + async fetch(request: Request): Promise { + const state = new FetchState(request); + + // Custom pre-processing, runs before any Astro handler + const url = new URL(request.url); + if (url.pathname.startsWith('/dashboard')) { + const cookie = request.headers.get('cookie') ?? ''; + if (!cookie.includes('session=')) { + return new Response(null, { + status: 302, + headers: { Location: '/login' }, + }); + } + } + + const response = await astro(state); + + // Custom post-processing, runs after Astro renders + response.headers.set('X-Powered-By', 'Astro'); + return response; + }, +}; +``` + +#### Composing individual handlers + +When you need more control over the pipeline execution order, or want to omit certain features, you can compose individual handler functions from [`astro/fetch`](/en/reference/modules/astro-fetch/). Each handler operates on a [`FetchState` object](/en/reference/modules/astro-fetch/#fetchstate) that tracks per-request data, such as the matched route, cookies, and session. You can call handlers in any order and insert custom logic between stages. + +The following example runs only the handlers used in the project and adds custom logic after actions and before page rendering: + +```ts title="src/fetch.ts" +import { + FetchState, + actions, + middleware, + pages, + i18n, +} from 'astro/fetch'; + +export default { + async fetch(request: Request): Promise { + const state = new FetchState(request); + + const actionResponse = await actions(state); + if (actionResponse) return actionResponse; + + // Custom logic between actions and page rendering + console.log(`Rendering ${new URL(request.url).pathname}`); + + const response = await middleware(state, (s) => pages(s)); + return i18n(state, response); + }, +}; +``` + +### Using with Hono + +Astro also provides Hono-compatible wrappers for all handler functions via [`astro/hono`](/en/reference/modules/astro-hono/). If you prefer to use [Hono](https://hono.dev/) as your routing framework, you can export a Hono app from `src/fetch.ts`: + +```ts title="src/fetch.ts" +import { Hono } from 'hono'; +import { logger } from 'hono/logger'; +import { actions, middleware, pages, i18n } from 'astro/hono'; + +const app = new Hono(); + +// Hono middleware +app.use(logger()); + +// Astro handlers (as Hono middleware) +app.use(actions()); +app.use(middleware()); +app.use(pages()); +app.use(i18n()); + +export default app; +``` diff --git a/src/content/docs/en/guides/upgrade-to/v7.mdx b/src/content/docs/en/guides/upgrade-to/v7.mdx new file mode 100644 index 0000000000000..5fe22ea394447 --- /dev/null +++ b/src/content/docs/en/guides/upgrade-to/v7.mdx @@ -0,0 +1,248 @@ +--- +title: Upgrade to Astro v7 +description: How to upgrade your project to Astro v7.0. +sidebar: + label: v7.0 +i18nReady: false +--- +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' +import { Steps } from '@astrojs/starlight/components'; +import ReadMore from '~/components/ReadMore.astro' +import SourcePR from '~/components/SourcePR.astro' + +:::tip[Using a coding agent?] +Copy this prompt to upgrade your project: + +``` +Upgrade my Astro project to v7. Follow the migration guide at +https://v7.docs.astro.build/en/guides/upgrade-to/v7/ +``` +::: + +This guide will help you migrate from Astro v6 to Astro v7. + +Need to upgrade an older project to v6 first? See our [older migration guide](/en/guides/upgrade-to/v6/). + +Need to see the v6 docs? Visit this [older version of the docs site (unmaintained v6 snapshot)](https://v6.docs.astro.build/). + +## Upgrade Astro + +Update your project's version of Astro to the latest version using your package manager: + + + + ```shell + # Upgrade Astro and official integrations together + npx @astrojs/upgrade beta + ``` + + + ```shell + # Upgrade Astro and official integrations together + pnpm dlx @astrojs/upgrade beta + ``` + + + ```shell + # Upgrade Astro and official integrations together + yarn dlx @astrojs/upgrade beta + ``` + + + +You can also [upgrade your Astro integrations manually](/en/guides/integrations/#manual-upgrading) if needed, and you may also need to upgrade other dependencies in your project. + +:::note[Need to continue?] +After upgrading Astro, you may not need to make any changes to your project at all! + +But, if you notice errors or unexpected behavior, please check below for what has changed that might need updating in your project. +::: + +Astro v7.0 includes [potentially breaking changes](#breaking-changes), as well as the removal of some previously deprecated features. + +If your project doesn't work as expected after upgrading to v7.0, check this guide for an overview of all breaking changes and instructions on how to update your codebase. + +See [the Astro changelog](https://github.com/withastro/astro/blob/main/packages/astro/CHANGELOG.md) for full release notes. + +## Breaking Changes + +### Dependency Upgrades + +#### Vite 8 + +Astro v7.0 upgrades to [Vite 8](https://vite.dev/blog/announcing-vite-8) as the development server and production bundler. + +##### What should I do? + +If you are using Vite-specific plugins, configuration, or APIs, check the [Vite 8 migration guide](https://vite.dev/guide/migration) for their breaking changes and upgrade your project as needed. + +Most Astro users should be able to upgrade without any changes to their project code. This is primarily a breaking change for Astro integrations and plugins that depend on Vite internals. + +### Experimental Flags + +Experimental flags allow you to opt in to features while they are in early development. The following experimental flags have been removed in Astro 7.0 and are now stable, or the new default behavior. + +Remove these experimental flags from your Astro config if you were previously using them: + +```js del={5-10} title="astro.config.mjs" +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + experimental: { + logger: logHandlers.json({ pretty: true }), + queuedRendering: { + enabled: true, + }, + rustCompiler: true, + advancedRouting: true, + }, +}) +``` + +#### Experimental features now stable: + +- `logger`: The new logging system is now stable and the experimental flag is no longer needed to use it. If you were using this flag, you can now set your logger directly in the top-level `logger` field of your Astro config. + +- `queuedRendering`: Queued rendering is now the default behavior, and the experimental flag has been removed. No action is required to enable this feature in your project. All projects now benefit from the improved performance. + +- `rustCompiler`: The Rust-based Astro compiler is now the default and only compiler, replacing the previous Go-based compiler. No action is required for most projects. If you encounter any issues, please report them on [GitHub](https://github.com/withastro/astro/issues). + +- `advancedRouting`: Advanced routing is now enabled by default. See the [advanced routing guide](/en/guides/routing/#advanced-routing) for more information. Note that `src/fetch.ts` is now a [reserved file name](#reserved-file-name-srcfetchts). + +### Reserved file name: `src/fetch.ts` + +Astro v7.0 introduces [advanced routing](/en/guides/routing/#advanced-routing), which uses `src/fetch.ts` (or `src/fetch.js`) as a special file name, similar to `src/middleware.ts`. Astro will automatically import this file to configure routing behavior. + +If your project already has a `src/fetch.ts` file used for other purposes, Astro will attempt to process it as an advanced routing configuration, which may cause unexpected errors. + +#### What should I do? + +If you have an existing `src/fetch.ts` file that is not related to advanced routing, you have two options: + +* **Configure `fetchFile`**: you can specify a different filename or `null` to disable advanced routing. This is useful if you want to keep using `src/fetch.ts` for another purpose, or don't need advanced routing features: + + ```js title="astro.config.mjs" ins={5} + import { defineConfig } from 'astro/config'; + + export default defineConfig({ + // specify a different file for advanced routing configuration: + fetchFile: './src/router.ts', + // or disable advanced routing entirely: + // fetchFile: null, + }); + ``` + +* **Rename your file** to something else (e.g. `src/fetcher.ts`, `src/main.ts`), and update any imports that reference it. + +### New default Markdown processor: Sätteri + + + +Astro now renders your `.md` and `.mdx` files with [Sätteri](https://satteri.bruits.org/), its native Markdown pipeline, instead of the remark/rehype pipeline. As a result, `@astrojs/markdown-remark` is no longer installed by default. + +#### What should I do? + +If you don't use remark or rehype plugins, you don't need to do anything. Your Markdown and MDX will now be rendered by Sätteri, which applies GitHub-Flavored Markdown and SmartyPants just like before. + +If you depend on remark and rehype plugins, you can port them to [Sätteri MDAST or HAST plugins](https://satteri.bruits.org/docs/plugins/). If you depend on recma plugins, or if you are not yet ready or able to port your remark and rehype plugins, you can [stay on the `unified()` pipeline](/en/guides/markdown-content/#switching-to-the-unified-processor). + +To keep using unified plugins: + + + +1. Install `@astrojs/markdown-remark`: + + + + ```shell + npm install @astrojs/markdown-remark + ``` + + + ```shell + pnpm add @astrojs/markdown-remark + ``` + + + ```shell + yarn add @astrojs/markdown-remark + ``` + + + +2. Set [`unified()` as your Markdown processor](/en/guides/markdown-content/#switching-to-the-unified-processor): + + ```js title="astro.config.mjs" ins={2,6} + import { defineConfig } from 'astro/config'; + import { unified } from '@astrojs/markdown-remark'; + + export default defineConfig({ + markdown: { + processor: unified(), + }, + }); + ``` + + +The deprecated `markdown.remarkPlugins`, `markdown.rehypePlugins`, and `markdown.remarkRehype` options still work, but now also require `@astrojs/markdown-remark` to be installed. + +## Removed + +The following features have now been entirely removed from the code base and can no longer be used. Some of these features may have continued to work in your project even after deprecation. Others may have silently had no effect. + +Projects now containing these removed features will be unable to build, and there will no longer be any supporting documentation prompting you to remove these features. + +### Removed: `@astrojs/db` + +The `@astrojs/db` package has been removed in Astro v7.0 and is no longer maintained. + +#### What should I do? + +Remove `@astrojs/db` from your project's dependencies and replace it with one of the following alternatives: + +- **Node.js built-in SQLite**: Node.js now includes a built-in [`node:sqlite`](https://nodejs.org/api/sqlite.html) module (available since Node.js v22.5.0). This is a good option if you are using the Node.js adapter and were using `@astrojs/db` for local SQLite storage. + +- **[Drizzle ORM](https://orm.drizzle.team/)**: If you were using `@astrojs/db` for its Drizzle-based schema and query API, you can use Drizzle directly with any supported database. + +- **Other database libraries**: Use any database library that suits your deployment platform (e.g. [Turso](https://turso.tech/), [PlanetScale](https://planetscale.com/), [Neon](https://neon.tech/)). + +### Removed: exposed `astro:transitions` internals + + + +In Astro 6.x, some helpers available in `astro:transitions` and `astro:transitions/client` were deprecated. + +In Astro 7.0, the following APIs can no longer be used in your project: +- `TRANSITION_BEFORE_PREPARATION` +- `TRANSITION_AFTER_PREPARATION` +- `TRANSITION_BEFORE_SWAP` +- `TRANSITION_AFTER_SWAP` +- `TRANSITION_PAGE_LOAD` +- `isTransitionBeforePreparationEvent()` +- `isTransitionBeforeSwapEvent()` +- `createAnimationScope()` + +#### What should I do? + +Remove any occurrence of `createAnimationScope()`: + +```diff +-import { createAnimationScope } from 'astro:transitions'; +``` + +Replace any occurrence of the other APIs using the [lifecycle event names](/en/reference/modules/astro-transitions/#lifecycle-events) directly: + +```diff +-import { +- TRANSITION_AFTER_SWAP, +- isTransitionBeforePreparationEvent, +-} from 'astro:transitions/client'; + +-console.log(isTransitionBeforePreparationEvent(event)); ++console.log(event.type === 'astro:before-preparation'); + +-console.log(TRANSITION_AFTER_SWAP); ++console.log('astro:after-swap'); +``` + +Learn more about all utilities available in the [View Transitions Router API Reference](/en/reference/modules/astro-transitions/). diff --git a/src/content/docs/en/reference/api-reference.mdx b/src/content/docs/en/reference/api-reference.mdx index df1dc39c77d6c..a9c37984e760b 100644 --- a/src/content/docs/en/reference/api-reference.mdx +++ b/src/content/docs/en/reference/api-reference.mdx @@ -1229,3 +1229,55 @@ content=" " > ``` +### `logger` + +

+ + **Type**: `object | undefined` + +

+ +An object that allows you to add additional logs during the rendering of a page. This is particularly useful with [on-demand routes](/en/guides/on-demand-rendering/) and when connecting log aggregation services (e.g. Kibana, Grafana, Loki). +#### `logger.error()` +

+ + **Type**: `(msg: string) => void` + +

+ +Emits a message with `error` level. + +```astro title="src/pages/index.astro" +--- +Astro.logger.error("Can't find the checkout ID."); +--- +``` + +#### `logger.warn()` +

+ + **Type**: `(msg: string) => void` + +

+Emits a message with `warn` level. + +```astro title="src/pages/index.astro" +--- +Astro.logger.warn("Can't find the checkout ID."); +--- +``` + +#### `logger.info()` +

+ + **Type**: `(msg: string) => void` + +

+ +Emits a message with `info` level. + +```astro title="src/pages/index.astro" +--- +Astro.logger.info("Can't find the checkout ID."); +--- +``` diff --git a/src/content/docs/en/reference/cli-reference.mdx b/src/content/docs/en/reference/cli-reference.mdx index 9de5573bd64cd..154aaf7a9ae94 100644 --- a/src/content/docs/en/reference/cli-reference.mdx +++ b/src/content/docs/en/reference/cli-reference.mdx @@ -111,15 +111,21 @@ You can add the `--help` flag after any command to get a list of all the flags f The following message will display in your terminal: ```bash -astro dev [...flags] +astro dev [command] [...flags] + +Commands + stop Stop a running background dev server. + status Check if a dev server is running. + logs [--follow] View logs from a background dev server. Flags - --port Specify which port to run on. Defaults to 4321. - --host Listen on all addresses, including LAN and public addresses. + --background Start the dev server as a background process. + --port Specify which port to run on. Defaults to 4321. + --host Listen on all addresses, including LAN and public addresses. --host Expose on a network IP address at - --open Automatically open the app in the browser on server start - --force Clear the content layer cache, forcing a full rebuild. - --help (-h) See all available flags. + --open Automatically open the app in the browser on server start + --force Clear the content layer cache, forcing a full rebuild. + --help (-h) See all available flags. ``` :::note @@ -186,6 +192,48 @@ The following hotkeys can be used in the terminal where the Astro development se - `o + enter` to open your Astro site in the browser. - `q + enter` to quit the development server. +

Flags

+ +

+ +#### `--background` + +Starts the dev server as a detached background process and enables [JSON logging](#--json). This flag is provided automatically when an AI agent is detected. You can also use it manually: + +```shell +astro dev --background +``` + +If a server is already running for the project, the command prints the existing server's info and exits without starting a new one. Use the `--force` flag to stop the existing server and start a new one. + +```shell +astro dev --background --force +``` + +See [Background mode for AI coding agents](/en/guides/build-with-ai/#background-mode) for more about automatic agent detection and the health endpoint. + +

Subcommands

+ +

+ +#### `astro dev stop` + +Stops a running background dev server. Sends `SIGTERM` and waits up to 5 seconds for the server to exit gracefully. If the process is still running after that, it escalates to `SIGKILL`. + +#### `astro dev status` + +Checks whether a background dev server is running and displays its URL, PID, and uptime. + +#### `astro dev logs` + +Displays logs from a background dev server. Only works when the server was started with `astro dev --background`, since foreground servers write logs directly to the terminal. + +##### Flags + +###### `--follow` (`-f`) + +Stream new log output as it's written, similar to `tail -f`. Without this flag, the current log file contents are printed and the command exits. + ## `astro build` Builds your site for deployment. By default, this will generate static files and place them in a `dist/` directory. If any routes are [rendered on demand](/en/guides/on-demand-rendering/), this will generate the necessary server files to serve your site. @@ -266,7 +314,6 @@ Running `astro dev`, `astro build` or `astro check` will run the `sync` command Generates TypeScript types for all Astro modules. This sets up a [`.astro/types.d.ts` file](/en/guides/typescript/#setup) for type inferencing, and defines modules for features that rely on generated types: - The `astro:content` module for the [Content Collections API](/en/guides/content-collections/). -- The `astro:db` module for [Astro DB](/en/guides/astro-db/). - The `astro:env` module for [Astro Env](/en/guides/environment-variables/). - The `astro:actions` module for [Astro Actions](/en/guides/actions/) @@ -479,6 +526,12 @@ Enables silent logging, which will run the server without any console output. Automatically opens the app in the browser on server start. Can be passed a full URL string (e.g. `--open http://example.com`) or a pathname (e.g. `--open /about`) to specify the URL to open. +### `--json` + +

+ +Enables [JSON logging](/en/reference/logger-reference/#loghandlersjson), which is useful for machine-readable output. + ## Global flags Use these flags to get information about the `astro` CLI. diff --git a/src/content/docs/en/reference/configuration-reference.mdx b/src/content/docs/en/reference/configuration-reference.mdx index 8a710c7e08a6c..3388f49d15fb2 100644 --- a/src/content/docs/en/reference/configuration-reference.mdx +++ b/src/content/docs/en/reference/configuration-reference.mdx @@ -1223,6 +1223,103 @@ Pass a full URL string (e.g. "http://example.com") or a pathname (e.g. "/about") Set custom HTTP response headers to be sent in `astro dev` and `astro preview`. +## fetchFile + +

+ +**Type:** `string | null`
+**Default:** `'fetch'`
+ +

+ +Customizes the file used as the fetch entrypoint inside `srcDir`. +Defaults to `'fetch'`, meaning Astro looks for `src/fetch.ts` (or `.js` / `.mjs` / `.mts`). + +The fetch file allows you to compose Astro's request pipeline with the +Web Fetch standard or your own Hono middleware. + +If you already have a `src/fetch.ts` file in use for other purposes, define a +different filename or set the value to `null` to disable the entrypoint: + +```js +// astro.config.mjs +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + fetchFile: 'handler', +}); +``` + +Learn more about customizing the request pipeline in the [advanced routing guide](https://v7.docs.astro.build/en/guides/routing/#advanced-routing). + +## Logger Options + +

+ +**Type:** `LoggerHandlerConfig`
+**Default:** `undefined`
+ +

+ +Configures how Astro logs messages during development and production. + +By default, Astro uses a built-in logger that outputs human-friendly logs to the console. You can customize this behavior by providing [your own logger handler](https://v7.docs.astro.build/en/reference/logger-reference/#custom-loggers) or by using one of the [built-in log handlers](https://v7.docs.astro.build/en/reference/logger-reference/#built-in-loggers): + +```js +// astro.config.mjs +import { defineConfig, logHandlers } from 'astro/config'; + +export default defineConfig({ + logger: logHandlers.json({ level: 'info' }) +}); +``` + +See [the logger API reference](https://v7.docs.astro.build/en/reference/logger-reference/) for more information. + +### logger.entrypoint + +

+ +**Type:** `string`
+ +

+ +The entrypoint of the log handler. This can be a path to a file in your project or an npm package: + +```js title="astro.config.mjs" +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + logger: { + entrypoint: "@org/astro-logger", + } +}); +``` + +### logger.config + +

+ +**Type:** `Record | undefined`
+**Default:** `{}`
+ +

+ +The configuration object for the log handler. The options depend on the configured logger. + +```js title="astro.config.mjs" +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + logger: { + entrypoint: "@org/astro-logger", + config: { + level: "error" + } + } +}); +``` + ## Session Options

@@ -1995,8 +2092,24 @@ Pass options to [remark-rehype](https://github.com/remarkjs/remark-rehype#api).

-Configures the Markdown processor used to render `.md` files. Defaults to `unified()` from -`@astrojs/markdown-remark` (the remark/rehype pipeline). +Configures the Markdown processor used to render `.md` files. Defaults to `satteri()` from +`@astrojs/markdown-satteri`, Astro's native Markdown pipeline. + +```js +// astro.config.mjs +import { defineConfig } from 'astro/config'; +import { satteri } from '@astrojs/markdown-satteri'; + +export default defineConfig({ + markdown: { + processor: satteri({ + features: { gfm: false }, + }), + }, +}); +``` + +To keep the remark/rehype pipeline, install `@astrojs/markdown-remark` and pass `unified()`: ```js // astro.config.mjs diff --git a/src/content/docs/en/reference/experimental-flags/advanced-routing.mdx b/src/content/docs/en/reference/experimental-flags/advanced-routing.mdx deleted file mode 100644 index b3cc1b1eb4e4c..0000000000000 --- a/src/content/docs/en/reference/experimental-flags/advanced-routing.mdx +++ /dev/null @@ -1,529 +0,0 @@ ---- -title: Experimental advanced routing -sidebar: - label: Advanced routing -i18nReady: true ---- - -import Since from '~/components/Since.astro' - -

- -**Type:** `boolean`
-**Default:** `false`
- -

- -Enables `src/app.ts` as a custom request pipeline entrypoint, giving you full control over how Astro handles incoming requests. - -By default, Astro handles every request with a built-in pipeline that runs trailing-slash normalization, redirects, sessions, actions, user middleware, page rendering, i18n, and caching in a fixed order. Advanced routing lets you replace this pipeline with your own, composing Astro's built-in handler functions with custom logic in any order you choose. - -```js title="astro.config.mjs" -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - experimental: { - advancedRouting: true, - }, -}); -``` - -## Creating `src/app.ts` - -When `advancedRouting` is enabled, create a `src/app.ts` (or `.js`, `.mjs`, `.mts`) file that default-exports an object with a `fetch` method. The `fetch` method receives a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) and must return a [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response). - -If no `src/app.ts` file exists (or `advancedRouting` is not enabled), Astro uses its built-in pipeline, which runs all features automatically. - -You can optionally import the `Fetchable` type from `astro` to type-check your entrypoint: - -```ts title="src/app.ts" -import type { Fetchable } from 'astro'; - -export default { - async fetch(request: Request): Promise { - // ... - }, -} satisfies Fetchable; -``` - -### Customizing the entrypoint file - -By default, Astro looks for `src/app.ts` as the advanced routing entrypoint. Pass an object to `advancedRouting` with a `fetchFile` option to use a different file: - -```js title="astro.config.mjs" -export default defineConfig({ - experimental: { - advancedRouting: { - fetchFile: 'fetch.ts', - }, - }, -}); -``` - -With this configuration, Astro will look for `src/fetch.ts` instead of `src/app.ts`. - -Set `fetchFile` to `null` to disable the entrypoint entirely. This is useful if you already have a `src/app.ts` file used for other purposes: - -```js title="astro.config.mjs" -export default defineConfig({ - experimental: { - advancedRouting: { - fetchFile: null, - }, - }, -}); -``` - -### Using `astro()` - -The easiest way to get started is with the [`astro()` handler](#astro), which runs Astro's full built-in pipeline (sessions, cache, redirects, trailing-slash, actions, middleware, pages, and i18n) in the default order. This lets you add custom logic before or after Astro without changing how the internal pipeline works: - -```ts title="src/app.ts" -import { FetchState, astro } from 'astro/fetch'; - -export default { - async fetch(request: Request): Promise { - const state = new FetchState(request); - - // Custom pre-processing, runs before any Astro handler - const url = new URL(request.url); - if (url.pathname.startsWith('/dashboard')) { - const cookie = request.headers.get('cookie') ?? ''; - if (!cookie.includes('session=')) { - return new Response(null, { - status: 302, - headers: { Location: '/login' }, - }); - } - } - - const response = await astro(state); - - // Custom post-processing, runs after Astro renders - response.headers.set('X-Powered-By', 'Astro'); - return response; - }, -}; -``` - -For many use cases, such as adding auth guards, request logging, and custom headers, `astro()` is all you need. - -### Composing individual handlers - -When you need more control over the pipeline order, or want to omit certain features entirely, you can compose individual handler functions from `astro/fetch`: - -```ts title="src/app.ts" -import { - FetchState, - sessions, - actions, - middleware, - pages, - i18n, -} from 'astro/fetch'; - -export default { - async fetch(request: Request): Promise { - const state = new FetchState(request); - await sessions(state); - try { - const actionResponse = await actions(state); - if (actionResponse) return actionResponse; - - const response = await middleware(state, (s) => pages(s)); - return i18n(state, response); - } finally { - await state.finalizeAll(); - } - }, -}; -``` - -Each function operates on a [`FetchState` object](#fetchstate) that tracks per-request data like the matched route, cookies, and session. You can call them in any order and mix them with your own logic. - -## Adding custom logic - -The main benefit of advanced routing is the ability to insert custom logic anywhere in the request pipeline. You can run code before Astro touches the request, between pipeline stages, or after the response is produced. - -The [`astro()` handler](#astro) is the simplest way to add pre- or post-processing around the full pipeline. When you need to insert logic *between* specific stages, such as running custom code after actions but before page rendering, compose the individual handlers instead: - -```ts title="src/app.ts" -import { - FetchState, - actions, - middleware, - pages, - i18n, -} from 'astro/fetch'; - -export default { - async fetch(request: Request): Promise { - const state = new FetchState(request); - - const actionResponse = await actions(state); - if (actionResponse) return actionResponse; - - // Custom logic between actions and page rendering - console.log(`Rendering ${new URL(request.url).pathname}`); - - const response = await middleware(state, (s) => pages(s)); - return i18n(state, response); - }, -}; -``` - -## Typing custom providers with `App.Providers` - -When you register custom context providers with [`state.provide()`](#stateprovide), you can declare their types using the `App.Providers` interface so that `Astro` and `ctx` are fully typed in your components and middleware: - -```ts title="src/env.d.ts" -declare namespace App { - interface Providers { - oauth: import('./lib/oauth').OAuthSession; - } -} -``` - -After declaring a provider, `ctx.oauth` (and `Astro.oauth` in `.astro` files) will be typed automatically. - -## `astro/fetch` handler reference - -All handler functions are imported from `astro/fetch` and operate on a `FetchState` object. - -### `FetchState` - -The per-request state object. Create one at the start of your `fetch` method: - -```ts -import { FetchState } from 'astro/fetch'; - -const state = new FetchState(request); -``` - -`FetchState` tracks the matched route, cookies, session providers, and other per-request data. All handler functions require it as their first argument. - -#### Properties - -##### `state.request` - -**Type:** `Request` - -The incoming [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object. - -##### `state.url` - -**Type:** `URL` - -A normalized [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) derived from the request. - -##### `state.pathname` - -**Type:** `string` - -The base-stripped, decoded pathname of the request (e.g. `/about` or `/blog/my-post`). - -##### `state.routeData` - -**Type:** `RouteData | undefined` - -The matched route for this request, if any. This is resolved automatically when the `FetchState` is created. - -##### `state.cookies` - -**Type:** `AstroCookies` - -An [`AstroCookies`](/en/reference/api-reference/#cookies) instance for reading and setting cookies on this request. - -##### `state.locals` - -**Type:** `App.Locals` - -A request-scoped object for storing custom data. This is the same `locals` object available in [middleware](/en/guides/middleware/) and [API routes](/en/guides/endpoints/#server-endpoints-api-routes). - -##### `state.params` - -**Type:** `Params | undefined` - -Route parameters derived from the matched route and pathname (e.g. `{ slug: 'my-post' }` for a `[slug].astro` route). - -##### `state.status` - -

- -**Type:** `number`
-**Default:** `200` -

- -The HTTP status code for the response. You can set this before rendering to control the response status (e.g. `state.status = 404`). - -##### `state.response` - -

- -**Type:** `Response | undefined`
-**Default:** `undefined` -

- -The `Response` produced by handlers after rendering completes. This is set automatically by [`pages()`](#pages) and [`middleware()`](#middleware), allowing you to inspect or use the response later in the pipeline: - -```ts -const response = await middleware(state, (s) => pages(s)); -// state.response is now the same object as response -``` - -#### Methods - -##### `state.rewrite()` - -

- -**Type:** (payload: RewritePayload) => Promise\ -

- -Triggers a [rewrite](/en/guides/routing/#rewrites) to a different route. The `payload` can be a pathname string (`'/other-page'`), a URL, or a `Request`: - -```ts -const response = await state.rewrite('/other-page'); -``` - -##### `state.provide()` - -

- -**Type:** `(key: string, provider: ContextProvider) => void` -

- -Registers a context provider under the given key. The provider's `create()` function is called lazily on the first [`state.resolve()`](#stateresolve), and its optional `finalize()` callback runs during [`state.finalizeAll()`](#statefinalizeall): - -```ts -state.provide('myService', { - create: () => new MyService(), - finalize: (service) => service.close(), -}); -``` - -##### `state.resolve()` - -

- -**Type:** `(key: string) => T | undefined` -

- -Returns the value for a previously registered provider, calling its `create` function on first access. Returns `undefined` if no provider was registered for the key: - -```ts -const service = state.resolve('myService'); -``` - -##### `state.finalizeAll()` - -

- -**Type:** `() => Promise | void` -

- -Runs all registered provider `finalize` callbacks. Call this after the response is produced, typically in a `finally` block, to persist session data and clean up resources: - -```ts -await sessions(state); -try { - // ...render pipeline... - return response; -} finally { - await state.finalizeAll(); -} -``` - -### `astro()` - -

- -**Type:** (state: FetchState) => Promise\ -

- -The all-in-one handler that runs the full Astro pipeline (sessions, cache, redirects, trailing-slash, actions, middleware, pages, and i18n) in the default order. Use this when you want to add logic before or after Astro without changing the internal pipeline order: - -```ts title="src/app.ts" -import { FetchState, astro } from 'astro/fetch'; - -export default { - async fetch(request: Request): Promise { - const state = new FetchState(request); - // custom pre-processing here... - const response = await astro(state); - // custom post-processing here... - return response; - }, -}; -``` - -### `pages()` - -

- -**Type:** (state: FetchState) => Promise\ -

- -Dispatches the request to the matched Astro route (page, endpoint, or fallback). This is the core rendering handler, and most custom pipelines will include it. - -### `middleware()` - -

- -**Type:** (state: FetchState, next: (state: FetchState) => Promise\) => Promise\ -

- -Runs Astro's middleware chain (from `src/middleware.ts`). The `next` callback is called at the bottom of the chain to produce the response, typically by calling `pages()`: - -```ts -const response = await middleware(state, (s) => pages(s)); -``` - -### `actions()` - -

- -**Type:** (state: FetchState) => Promise\ | undefined -

- -Handles [Astro Actions](/en/guides/actions/) (RPC and form submissions). Returns a `Response` for RPC actions, or `undefined` for form actions and non-action requests. Check the return value to decide whether to continue rendering: - -```ts -const actionResponse = await actions(state); -if (actionResponse) return actionResponse; -// otherwise continue to page rendering... -``` - -### `sessions()` - -

- -**Type:** (state: FetchState) => Promise\ | void -

- -Registers the [session](/en/guides/sessions/) provider. Sessions are created lazily when your code accesses `ctx.session` and persisted when `state.finalizeAll()` is called. Call this early in the pipeline, and call `finalizeAll()` in a `finally` block: - -```ts -await sessions(state); -try { - // ...render pipeline... -} finally { - await state.finalizeAll(); -} -``` - -### `i18n()` - -

- -**Type:** (state: FetchState, response: Response) => Promise\ -

- -Post-processes a response against your [i18n configuration](/en/guides/internationalization/). Handles locale redirects, 404s for invalid locales, and fallback routing. Call this after rendering: - -```ts -const response = await middleware(state, (s) => pages(s)); -return i18n(state, response); -``` - -### `redirects()` - -

- -**Type:** (state: FetchState) => Promise\ | undefined -

- -Handles redirect routes defined in your [Astro config](/en/reference/configuration-reference/#redirects). Returns a redirect `Response` if the matched route is a redirect, or `undefined` if the caller should continue processing. - -### `cache()` - -

- -**Type:** (state: FetchState, next: () => Promise\) => Promise\ -

- -Wraps a render callback with [cache](/en/reference/experimental-flags/route-caching/) provider logic. Handles runtime caching, CDN-based providers, and the no-cache case. - -### `trailingSlash()` - -

- -**Type:** (state: FetchState) => Response | undefined -

- -Checks if the request pathname needs [trailing-slash](/en/reference/configuration-reference/#trailingslash) normalization and returns a redirect `Response` if so. Returns `undefined` when no redirect is needed. - -## Using with Hono - -Astro also provides Hono-compatible wrappers for all handler functions via `astro/hono`. If you prefer to use [Hono](https://hono.dev/) as your routing framework, you can export a Hono app from `src/app.ts`: - -```ts title="src/app.ts" -import { Hono } from 'hono'; -import { logger } from 'hono/logger'; -import { actions, middleware, pages, i18n } from 'astro/hono'; - -const app = new Hono(); - -// Hono middleware -app.use(logger()); - -// Astro handlers (as Hono middleware) -app.use(actions()); -app.use(middleware()); -app.use(pages()); -app.use(i18n()); - -export default app; -``` - -The `astro/hono` module exports the same handler names as `astro/fetch` (`astro`, `pages`, `middleware`, `actions`, `sessions`, `redirects`, `cache`, `i18n`, `trailingSlash`), but each returns a Hono middleware function. This lets you mix Astro handlers with any Hono middleware from the ecosystem. - -## Cloudflare adapter - -The [`@astrojs/cloudflare`](/en/guides/integrations-guide/cloudflare/) adapter provides companion handlers that apply Cloudflare-specific setup to your advanced routing pipeline. These handlers configure session KV binding injection, static asset serving via the `ASSETS` binding, `Astro.locals.cfContext`, client address from the `cf-connecting-ip` header, `waitUntil`, and prerendered error page fetching. - -You can use the `astro/fetch` and `astro/hono` APIs from `src/app.ts` on Cloudflare without these handlers. The adapter's default entrypoint takes care of Cloudflare-specific setup for you. These companion handlers are useful when you already have a [custom worker entrypoint](https://developers.cloudflare.com/workers/wrangler/configuration/#inheritable-keys) (`src/worker.ts`), for example, to export a Durable Object, and want to use the advanced routing APIs directly from that file instead. - -When using these handlers in your worker entrypoint, they replace the functionality of the adapter's default handler, so you should not use both at the same time. Place the Cloudflare handler before other Astro handlers so that bindings and locals are available to the rest of the pipeline. - -### `@astrojs/cloudflare/fetch` - -

- -For use with `astro/fetch`. The `cf()` function receives a `FetchState`, the Cloudflare `env`, and the `ExecutionContext`. It returns a `Response` for static asset hits, or `undefined` when the request should continue to Astro rendering: - -```ts title="src/worker.ts" -import { astro, FetchState } from 'astro/fetch'; -import { cf } from '@astrojs/cloudflare/fetch'; - -export default { - async fetch(request: Request, env: Env, ctx: ExecutionContext) { - const state = new FetchState(request); - const asset = await cf(state, env, ctx); - if (asset) return asset; - return astro(state); - }, -}; -``` - -### `@astrojs/cloudflare/hono` - -

- -For use with `astro/hono`. The `cf()` function returns a Hono middleware that reads `env` and `executionCtx` from the Hono context automatically: - -```ts title="src/worker.ts" -import { Hono } from 'hono'; -import { actions, middleware, pages, i18n } from 'astro/hono'; -import { cf } from '@astrojs/cloudflare/hono'; - -const app = new Hono<{ Bindings: Env }>(); - -app.use(cf()); -app.use(actions()); -app.use(middleware()); -app.use(pages()); -app.use(i18n()); - -export default app; -``` diff --git a/src/content/docs/en/reference/experimental-flags/queued-rendering.mdx b/src/content/docs/en/reference/experimental-flags/queued-rendering.mdx deleted file mode 100644 index c0aeaba79d289..0000000000000 --- a/src/content/docs/en/reference/experimental-flags/queued-rendering.mdx +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Experimental queued rendering -sidebar: - label: Queued rendering -i18nReady: true ---- - -import Since from '~/components/Since.astro'; - -

- -**Type:** `object`
-**Default:** `{ enabled: false }`
- -

- -Enables an experimental, more performant rendering infrastructure that is based on a queue instead of recursion. - -By default, Astro renders `.astro`, `.md`, and `.mdx` files using a recursion algorithm. It takes as input a series of components that are serialised in a tree-like structure, and for each node of the tree, Astro calls a render function. - -When queued rendering is enabled, Astro traverses all nodes in the tree and emits a [depth-first](https://en.wikipedia.org/wiki/Depth-first_search) list of nodes. This list is then iterated and rendered, without the need of a recursion algorithm. This rendering is more memory efficient, and it should provide more benefits in big projects. - -To enable this feature with default settings, set `queuedRendering.enabled` to `true` in your Astro config: - -```js title="astro.config.mjs" ins={5-7} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - queuedRendering: { - enabled: true - } - } -}); -``` - -In a future major version, Astro will use this new compiler by default, but you can opt in to the future behavior early using the `experimental.queuedRendering` flag. - -## Configuration - -The queued rendering engine comes with additional, low-level features, which allow you to experiment with other possible optimizations. These optimisations aren't directly part of the queued engine, and may be removed if they are proven inefficient during this experimental phase of testing. - - -### Node pooling - -

- -**Type:** `number`
-**Default:** `1000`
- -

- - -Node pooling is a caching system designed to reuse component nodes across renders. This feature is automatically enabled with a reasonable default according to our early testing. However, you can configure the size of the pool to increase or decrease the number of nodes combined in a single pool according to your project needs. To disable this feature entirely, set `poolSize` to `0`. - -The node pooling is very effective when rendering static pages because it saves some memory when building websites with many pages that share the same components. - -The node pooling is turned off for pages rendered on demand because these rendering requests do not share memory, and there are therefore no savings to be gained with this strategy. - -```js title="astro.config.mjs" ins={7} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - queuedRendering: { - enabled: true, - poolSize: 3000 // use a pool of 3000 nodes - } - } -}); -``` - -### Content caching - -

- -**Type:** `boolean`
-**Default:** `false`
- -

- - -Content caching is another technique to reuse values (usually strings) during the rendering of a page. Currently, this feature can only be enabled or disabled with no further configuration. It's disabled by default, but when enabled, the experimental queued engine will choose a reasonable default cache size for most large content collections: - -```js title="astro.config.mjs" ins={7} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - queuedRendering: { - enabled: true, - contentCache: true - } - } -}); -``` diff --git a/src/content/docs/en/reference/experimental-flags/rust-compiler.mdx b/src/content/docs/en/reference/experimental-flags/rust-compiler.mdx deleted file mode 100644 index 7c4b4d9073be2..0000000000000 --- a/src/content/docs/en/reference/experimental-flags/rust-compiler.mdx +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Experimental Rust compiler -sidebar: - label: Rust compiler -i18nReady: true ---- - -import Since from '~/components/Since.astro' -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' - -

- - **Type:** `boolean`
- **Default:** `false`
- -

- -Enables using the new Rust-based compiler for Astro files. This compiler is faster, provides better error messages, and generally has better support for modern JavaScript, TypeScript, and CSS features. - -In a future major version, Astro will use this new compiler by default, but you can opt in to the future behavior early using the `experimental.rustCompiler` flag. - -To give feedback on the compiler, or to keep up with its development, see the [RFC for a new compiler for Astro](https://github.com/withastro/roadmap/discussions/1306) for more information and discussion. - -## Usage - -This experimental flag requires no specific usage and only affects which compiler Astro uses for your project. - -To enable the Rust compiler, add the following to your `astro.config.mjs`: - -```js title="astro.config.mjs" ins={4-6} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - rustCompiler: true - } -}); -``` - -and then install the `@astrojs/compiler-rs` package into your project: - - - - ```shell - npm install @astrojs/compiler-rs - ``` - - - ```shell - pnpm add @astrojs/compiler-rs - ``` - - - ```shell - yarn add @astrojs/compiler-rs - ``` - - - -### Expected differences - -Unlike Astro's current Go compiler, this experimental Rust compiler will not correct invalid HTML structure. For example, the following notable patterns will be left as written, and no longer corrected: - - - `

Bad nesting

` (instead of removing the `div` from of the `p`) - - `

My paragraph` (instead of adding the missing closing `

` tag) - -This means that if your Astro files contain invalid HTML, you may see a different output from the Rust compiler than you did with the previous compiler, or may encounter errors while building. - -## Limitations - -At this time, the Rust compiler does not output the required metadata for the dev toolbar audits to work correctly. diff --git a/src/content/docs/en/reference/experimental-flags/logger.mdx b/src/content/docs/en/reference/logger-reference.mdx similarity index 64% rename from src/content/docs/en/reference/experimental-flags/logger.mdx rename to src/content/docs/en/reference/logger-reference.mdx index 8f1be3cba772c..8831d0fdc4069 100644 --- a/src/content/docs/en/reference/experimental-flags/logger.mdx +++ b/src/content/docs/en/reference/logger-reference.mdx @@ -1,51 +1,109 @@ --- -title: Experimental logger +title: Astro Logger API sidebar: - label: Logger + label: Logger API i18nReady: true --- - import Since from '~/components/Since.astro';

- -**Type:** `object`
-**Default:** `undefined`
- +

-Enables an experimental, custom logger that can be controlled by the user. -When provided, the user has total control over the logs emitted by Astro. Additionally, the feature comes with some built-in loggers that can be used via the new `logHandlers`. +The Logger API provides greater control over Astro's logging infrastructure. This allows you to replace the default console output with custom logging implementations and connect to log aggregation services. -The following example enables the built-in JSON logger, with a pretty output: +This API includes three ready-to-use loggers and allows you to integrate your own loggers and compose them. -```js title="astro.config.mjs" {5} ins="logHandlers" -import { defineConfig, logHandlers } from 'astro/config'; +## Custom loggers + +You can create a custom logger by providing the correct configuration to the `logger` setting. It accepts an object with a mandatory `entrypoint`, the module where the logger is exported, and an optional configuration to pass to the logger. The configuration must be serializable. + +The logger function must be exported as `default`. + +When you define a custom logger, you are in charge of all logs, even the ones emitted by Astro. + +The following example defines a custom logger exported by the `@org/custom-logger` package and accepting only one parameter to configure the logging `level`: + +```js title="astro.config.mjs" +import { defineConfig } from 'astro/config'; export default defineConfig({ - experimental: { - logger: logHandlers.json({ pretty: true }) + logger: { + entrypoint: "@org/custom-logger", + config: { + level: "warn" + } } }); ``` -Alternatively, you can enable JSON logging for the `dev`, `build`, and `sync` commands using the `--experimentalJson` flag: +The following example implements a minimal logger returning an [`AstroLoggerDestination` object](#astrologgerdestination) with the required `write()` function: + +```ts title="@org/custom-logger/index.ts" +import type { + AstroLoggerLevel, + AstroLoggerDestination, + AstroLoggerMessage +} from "astro"; +import { matchesLevel } from "astro/logger"; + +type LoggerOptions = { + level: AstroLoggerLevel +} + +function orgLogger(options: LoggerOptions = {}): AstroLoggerDestination { + const { level = 'info' } = options; + return { + write(message: AstroLoggerMessage) { + // Use this utility to understand if the message should be printed + if (matchesLevel(message.level, level)) { + // log message somewhere and take the level into consideration + } + } + } +} + +export default orgLogger; +``` + +You can now add your own logs during the rendering of a page using [the runtime APIs](/en/reference/api-reference/#logger). + +## Log level + +A level is an internal, arbitrary score assigned to each message. When a logger is configured with a certain level, only the messages with a level equal to or higher are printed. + +There are three levels, from the highest to the lowest score: +1. `error` +2. `warn` +3. `info` + +The following example configures the JSON logger to print only messages that have the `warn` level or higher: + +```js title="astro.config.mjs" {4} ins='level: "warn"' +import { defineConfig, logHandlers } from 'astro/config'; -```shell -astro dev --experimentalJson -astro sync --experimentalJson -astro build --experimentalJson +export default defineConfig({ + logger: logHandlers.json({ level: "warn" }) +}); ``` +The `astro/logger` package exposes a [`matchesLevel()`](#matcheslevel) helper to check the log level. This can be useful when [building a custom logger](#custom-loggers). + +```js +import { matchesLevel } from "astro/logger"; + +matchesLevel("error", "info"); +``` ## Built-in loggers -The feature comes with three built-in loggers. +Astro offers built-in loggers that applications can use. -### `logHandlers.json` +### `logHandlers.json()` A logger that outputs messages in a JSON format. A log would look like this: + ```json { "message": "", "label": "router", "level": "info", "time": "" } ``` @@ -53,9 +111,9 @@ A logger that outputs messages in a JSON format. A log would look like this: #### JSON logger options

-**Type:** `{ pretty: boolean; level: AstroLoggerLevel; }`
-**Default:** `{ pretty: false, level: 'info' }` - + **Type:** `{ pretty: boolean; level: AstroLoggerLevel; }`
+ **Default:** `{ pretty: false, level: 'info' }` +

The `json` logger accepts the following options: @@ -63,17 +121,15 @@ The `json` logger accepts the following options: - `pretty`: when `true`, the JSON log is printed on multiple lines. Defaults to `false`. - `level`: the [level](#log-level) of logs that should be printed. -```js title="astro.config.mjs" {5} ins="json" +```js title="astro.config.mjs" {4} ins="json" import { defineConfig, logHandlers } from 'astro/config'; export default defineConfig({ - experimental: { - logger: logHandlers.json({ pretty: true }) - } + logger: logHandlers.json({ pretty: true }) }); ``` -### `logHandlers.console` +### `logHandlers.console()` A logger that prints messages using the `console` as its destination. Based on the level of the message, it uses different channels: @@ -84,26 +140,24 @@ A logger that prints messages using the `console` as its destination. Based on t #### Console logger options

-**Type:** `{ level: AstroLoggerLevel }`
-**Default:** `{ level: 'info' }` - + **Type:** `{ level: AstroLoggerLevel }`
+ **Default:** `{ level: 'info' }` +

The `console` logger accepts the following options: - `level`: the [level](#log-level) of logs that should be printed. -```js title="astro.config.mjs" {5} ins="console" +```js title="astro.config.mjs" {4} ins="console" import { defineConfig, logHandlers } from 'astro/config'; export default defineConfig({ - experimental: { - logger: logHandlers.console({ level: 'warn' }) - } + logger: logHandlers.console({ level: 'warn' }) }); ``` -### `logHandlers.node` +### `logHandlers.node()` A logger that prints messages to [`process.stdout`](https://nodejs.org/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/api/process.html#processstderr). Level `error` messages are printed to `stderr`, while the others are printed to `stdout`. @@ -112,26 +166,24 @@ This is Astro's default logger. #### Node logger options

-**Type:** `{ level: AstroLoggerLevel }`
-**Default:** `{ level: 'info' }` - + **Type:** `{ level: AstroLoggerLevel }`
+ **Default:** `{ level: 'info' }` +

The `node` logger accepts the following options: - `level`: the [level](#log-level) of logs that should be printed. -```js title="astro.config.mjs" {5} ins="node" +```js title="astro.config.mjs" {4} ins="node" import { defineConfig, logHandlers } from 'astro/config'; export default defineConfig({ - experimental: { - logger: logHandlers.node({ level: 'warn' }) - } + logger: logHandlers.node({ level: 'warn' }) }); ``` -### `logHandlers.compose` +### `logHandlers.compose()` A particular function that allows configuring multiple loggers in an arbitrary order. The same message is broadcast to all loggers. @@ -141,115 +193,13 @@ The following example composes the console logger and JSON logger using the defa import { defineConfig, logHandlers } from 'astro/config'; export default defineConfig({ - experimental: { - logger: logHandlers.compose( - logHandlers.console(), - logHandlers.json() - ) - } -}); -``` - -## Custom loggers - -You can create a custom logger by providing the correct configuration to the `logger` setting. It accepts an object with a mandatory `entrypoint`, the module where the logger is exported, and an optional configuration to pass to the logger. The configuration must be serializable. - -The logger function must be exported as `default`. - -When you define a custom logger, you are in charge of all logs, even the ones emitted by Astro. - -The following example defines a custom logger exported by the `@org/custom-logger` package and accepting only one parameter to configure the logging `level`: - -```js title="astro.config.mjs" -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: { - entrypoint: "@org/custom-logger", - config: { - level: "warn" - } - } - } -}); -``` - -The following example implements a minimal logger returning an [`AstroLoggerDestination` object](#astrologgerdestination) with the required `write()` function: - -```ts title="@org/custom-logger/index.ts" -import type { - AstroLoggerLevel, - AstroLoggerDestination, - AstroLoggerMessage -} from "astro"; -import { matchesLevel } from "astro/logger"; - -type LoggerOptions = { - level: AstroLoggerLevel -} - -function orgLogger(options: LoggerOptions = {}): AstroLoggerDestination { - const { level = 'info' } = options; - return { - write(message: AstroLoggerMessage) { - // Use this utility to understand if the message should be printed - if (matchesLevel(message.level, level)) { - // log message somewhere and take the level into consideration - } - } - } -} - -export default orgLogger; -``` - -## Runtime - -The [context object](/en/reference/api-reference/#the-context-object) now exposes a `logger` object containing the following functions: - -- `error()`, which emits a message with `error` level. -- `warn()`, which emits a message with `warn` level. -- `info()`, which emits a message with `info` level. - -```astro ---- -Astro.logger.error("This is an error"); -Astro.logger.warn("This is a warning"); -Astro.logger.info("This is an info"); ---- -``` - -## Log level - -A level is an internal, arbitrary score assigned to each message. When a logger is configured with a certain level, only the messages with a level equal to or higher are printed. - -There are three levels, from the highest to the lowest score: -1. `error` -2. `warn` -3. `info` - -The following example configures the JSON logger to print only messages that have the `warn` level or higher: - -```js title="astro.config.mjs" {5} ins='level: "warn"' -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.json({ level: "warn" }) - } + logger: logHandlers.compose( + logHandlers.console(), + logHandlers.json() + ) }); ``` -The `astro/logger` package exposes a [`matchesLevel()`](#matcheslevel) helper to check the log level. This can be useful when [building a custom logger](#custom-loggers). - -```js -import { matchesLevel } from "astro/logger"; - -matchesLevel("error", "info"); -``` - - ## Types reference The following types can be imported from the `astro` specifier. @@ -262,7 +212,7 @@ This is the interface that custom loggers must implement.

-**Type:** `(message: AstroLoggerMessage) => void` + **Type:** `(message: AstroLoggerMessage) => void`

A mandatory method called for each log and accepting an [`AstroLoggerMessage`](#astrologgermessage). @@ -271,7 +221,7 @@ A mandatory method called for each log and accepting an [`AstroLoggerMessage`](#

-**Type:** `() => Promise | void` + **Type:** `() => Promise | void`

An optional function called at the end of each request. This is useful for advanced loggers that need to flush log messages while keeping the connection to the destination alive. @@ -280,44 +230,48 @@ An optional function called at the end of each request. This is useful for advan

-**Type:** `() => Promise | void` + **Type:** `() => Promise | void`

An optional function called before a server is shut down. This function is usually called by adapters such as `@astrojs/node`. ### `AstroLoggerLevel` -The level of the message. Available variants: -- `'debug'` -- `'info'` -- `'warn'` -- `'error'` -- `'silent'` +

+ +**Type:** `'debug' |'info' |'warn' | 'error' | 'silent'` +

+ +Specifies the verbosity level of logs: +- `info`, `warn`, and `error`: defines the minimal [log level](#log-level) to print. +- `silent`: this is equivalent to the [`--silent` CLI flag](/en/reference/cli-reference/#--silent) and enables silent logging. +- `debug`: this is equivalent to the [`--debug` CLI flag](/en/reference/cli-reference/#--verbose) and enables verbose logging, including Vite logging. ### `AstroLoggerMessage`

-**Type:** `{ label: string | null; level: AstroLoggerLevel; message: string; newLine: boolean; }` + **Type:** `{ label: string | null; level: AstroLoggerLevel; message: string; newLine: boolean; }`

+ The incoming object from the [`AstroLoggerDestination.write()`](#astrologgerdestinationwrite) function: - `message`: the message being logged. - `level`: the level of the message. - `label`: an arbitrary label assigned to the log message. - `newLine`: whether this message should add a trailing newline. -## APIs reference +## APIs reference The following APIs can be imported from the `astro/logger` specifier. -### `matchesLevel` +### `matchesLevel()`

-**Type:** `matchesLevel(messageLevel: AstroLoggerLevel, configuredLevel: AstroLoggerLevel) => boolean` + **Type:** `matchesLevel(messageLevel: AstroLoggerLevel, configuredLevel: AstroLoggerLevel) => boolean`

-Given two [log levels](#log-level), it returns whether the first level matches the second level. +Given two [log levels](#log-level), it returns whether the first level matches the second level. ```js import { matchesLevel } from "astro/logger"; diff --git a/src/content/docs/en/reference/modules/astro-assets.mdx b/src/content/docs/en/reference/modules/astro-assets.mdx index 7c3fd7674a516..6af95d9fa4d5c 100644 --- a/src/content/docs/en/reference/modules/astro-assets.mdx +++ b/src/content/docs/en/reference/modules/astro-assets.mdx @@ -788,7 +788,7 @@ Describes the [properties of a remote image](#image-). This ensures that when [`

-**Type:** `{ src: Array<{ url: string; format?: string; tech?: string }>; weight?: string; style?: string; }`
+**Type:** `{ src: Array<{ url: string; format?: string; tech?: string }>; weight?: string; style?: string; subset?: string; }`

@@ -821,6 +821,16 @@ Specifies the font weight (e.g. `400`, `600`). Specifies the font style (e.g. `normal`, `italic`). +#### `FontData.subset` + +

+ +**Type:** `string` + +

+ +Specifies the font subset (e.g. `latin`, `cyrillic`). + ## Imports from `astro/assets` The following helpers are imported from the regular assets module: diff --git a/src/content/docs/en/reference/modules/astro-config.mdx b/src/content/docs/en/reference/modules/astro-config.mdx index 59d987b3f4735..0accf396c1f98 100644 --- a/src/content/docs/en/reference/modules/astro-config.mdx +++ b/src/content/docs/en/reference/modules/astro-config.mdx @@ -138,6 +138,7 @@ import { envField, fontProviders, getViteConfig, + logHandlers, mergeConfig, passthroughImageService, sessionDrivers, @@ -307,6 +308,16 @@ Describes the [built-in provider](/en/reference/font-provider-reference/#built-i Retrieves the Vite configuration to use by merging a custom Vite configuration object and an optional Astro configuration object. This is useful [to set up Vitest for testing](/en/guides/testing/#vitest). +### `logHandlers` + +

+ +**Type:** `object`
+ +

+ +Describes the [available built-in log handlers](/en/reference/logger-reference/#built-in-loggers) that can be used to [configure a logger](/en/reference/configuration-reference/#logger-options) in your Astro configuration. + ### `mergeConfig()` See [`mergeConfig()` in the Programmatic API reference](/en/reference/programmatic-reference/#mergeconfig). diff --git a/src/content/docs/en/reference/modules/astro-fetch.mdx b/src/content/docs/en/reference/modules/astro-fetch.mdx new file mode 100644 index 0000000000000..340540a503023 --- /dev/null +++ b/src/content/docs/en/reference/modules/astro-fetch.mdx @@ -0,0 +1,266 @@ +--- +title: Fetch routing API reference +sidebar: + label: 'astro/fetch' +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 4 +--- +import ReadMore from '~/components/ReadMore.astro'; +import Since from '~/components/Since.astro'; + +

+ +The `astro/fetch` module provides [advanced routing](/en/guides/routing/#advanced-routing) handlers built on top of the standard Fetch API. + +## Imports from `astro/fetch` + +```ts +import { + FetchState, + astro, + actions, + cache, + i18n, + middleware, + pages, + redirects, + sessions, + trailingSlash, +} from "astro/fetch"; +``` + +### `FetchState` + +The per-request state object. Create one at the start of your `fetch` method: + +```ts +import { FetchState } from 'astro/fetch'; + +const state = new FetchState(request); +``` + +`FetchState` tracks the matched route, cookies, session providers, and other per-request data. All handler functions require it as their first argument. + +Learn how to [compose handlers](/en/guides/routing/#composing-individual-handlers) with `FetchState` in the advanced routing guide. + +#### Properties + +##### `state.request` + +

+ +**Type:** `Request` +

+ +The incoming [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object. + +##### `state.url` + +

+ +**Type:** `URL` +

+ +A normalized [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) derived from the request. + +##### `state.pathname` + +

+ +**Type:** `string` +

+ +The base-stripped, decoded pathname of the request (e.g. `/about` or `/blog/my-post`). + +##### `state.routeData` + +

+ +**Type:** RouteData | undefined +

+ +The matched route for this request, if any. This is resolved automatically when the `FetchState` is created. + +##### `state.cookies` + +

+ +**Type:** `AstroCookies` +

+ +An [`AstroCookies`](/en/reference/api-reference/#cookies) instance for reading and setting cookies on this request. + +##### `state.locals` + +

+ +**Type:** `App.Locals` +

+ +A request-scoped object for storing custom data. This is the same [`locals`](/en/reference/api-reference/#locals) object available in [middleware](/en/guides/middleware/) and [API routes](/en/guides/endpoints/#server-endpoints-api-routes). + +##### `state.params` + +

+ +**Type:** `Params | undefined` +

+ +Route parameters derived from the matched route and pathname (e.g. `{ slug: 'my-post' }` for a `[slug].astro` route). + +##### `state.status` + +

+ +**Type:** `number`
+**Default:** `200` +

+ +The HTTP status code for the response. You can set this before rendering to control the response status (e.g. `state.status = 404`). + +##### `state.response` + +

+ +**Type:** `Response | undefined`
+**Default:** `undefined` +

+ +The `Response` produced by handlers after rendering completes. This is set automatically by [`pages()`](#pages) and [`middleware()`](#middleware), allowing you to inspect or use the response later in the pipeline: + +```ts +const response = await middleware(state, (s) => pages(s)); +// state.response is now the same object as response +``` + +#### Methods + +##### `state.rewrite()` + +

+ +**Type:** (payload: RewritePayload) => Promise\ +

+ +Triggers a [rewrite](/en/guides/routing/#rewrites) to a different route. The `payload` can be a pathname string (`'/other-page'`), a URL, or a `Request`: + +```ts +const response = await state.rewrite('/other-page'); +``` + +### `astro()` + +

+ +**Type:** (state: FetchState) => Promise\ +

+ +The all-in-one handler that runs the full Astro pipeline (sessions, cache, redirects, trailing-slash, actions, middleware, pages, and i18n) in the default order. Use this when you want to add logic before or after Astro without changing the internal pipeline order: + +```ts title="src/fetch.ts" +import { FetchState, astro } from 'astro/fetch'; + +export default { + async fetch(request: Request): Promise { + const state = new FetchState(request); + // custom pre-processing here... + const response = await astro(state); + // custom post-processing here... + return response; + }, +}; +``` + +### `actions()` + +

+ +**Type:** (state: FetchState) => Promise\ | undefined +

+ +Handles [Astro Actions](/en/guides/actions/) (RPC and form submissions). Returns a `Response` for RPC actions, or `undefined` for form actions and non-action requests. Check the return value to decide whether to continue rendering: + +```ts +const actionResponse = await actions(state); +if (actionResponse) return actionResponse; +// otherwise continue to page rendering... +``` + +### `cache()` + +

+ +**Type:** (state: FetchState, next: () => Promise\) => Promise\ +

+ +Wraps a render callback with [cache](/en/reference/experimental-flags/route-caching/) provider logic. Handles runtime caching, CDN-based providers, and the no-cache case. + +### `i18n()` + +

+ +**Type:** (state: FetchState, response: Response) => Promise\ +

+ +Post-processes a response against your [i18n configuration](/en/guides/internationalization/). Handles locale redirects, 404s for invalid locales, and fallback routing. Call this after rendering: + +```ts +const response = await middleware(state, (s) => pages(s)); +return i18n(state, response); +``` + +### `middleware()` + +

+ +**Type:** (state: FetchState, next: (state: FetchState) => Promise\) => Promise\ +

+ +Runs Astro's middleware chain (from `src/middleware.ts`). The `next` callback is called at the bottom of the chain to produce the response, typically by calling `pages()`: + +```ts +const response = await middleware(state, (s) => pages(s)); +``` + +### `pages()` + +

+ +**Type:** (state: FetchState) => Promise\ +

+ +Dispatches the request to the matched Astro route (page, endpoint, or fallback). This is the core rendering handler, and most custom pipelines will include it. + +### `redirects()` + +

+ +**Type:** (state: FetchState) => Promise\ | undefined +

+ +Handles redirect routes defined in your [Astro config](/en/reference/configuration-reference/#redirects). Returns a redirect `Response` if the matched route is a redirect, or `undefined` if the caller should continue processing. + +### `sessions()` + +

+ +**Type:** (state: FetchState) => Promise\ | void +

+ +Registers the [session](/en/guides/sessions/) provider. Sessions are created lazily when your code accesses `ctx.session` and persisted automatically at the end of the request. Call this early in the pipeline (before middleware runs): + +```ts +await sessions(state); +// ...render pipeline... +``` + +### `trailingSlash()` + +

+ +**Type:** (state: FetchState) => Response | undefined +

+ +Checks if the request pathname needs [trailing-slash](/en/reference/configuration-reference/#trailingslash) normalization and returns a redirect `Response` if so. Returns `undefined` when no redirect is needed. diff --git a/src/content/docs/en/reference/modules/astro-hono.mdx b/src/content/docs/en/reference/modules/astro-hono.mdx new file mode 100644 index 0000000000000..c2648b0b46c86 --- /dev/null +++ b/src/content/docs/en/reference/modules/astro-hono.mdx @@ -0,0 +1,36 @@ +--- +title: Hono routing API reference +sidebar: + label: 'astro/hono' +i18nReady: true +tableOfContents: + minHeadingLevel: 2 + maxHeadingLevel: 4 +--- +import ReadMore from '~/components/ReadMore.astro'; +import Since from '~/components/Since.astro'; + +

+ +The `astro/hono` module provides [advanced routing](/en/guides/routing/#advanced-routing) handlers built as Hono-compatible wrappers. + +## Imports from `astro/hono` + +```ts +import { + FetchState, + astro, + actions, + cache, + i18n, + middleware, + pages, + redirects, + sessions, + trailingSlash, +} from "astro/hono"; +``` + +The `astro/hono` module exports the same handler names as [`astro/fetch`](/en/reference/modules/astro-fetch/), but each returns a Hono middleware function. This lets you mix Astro handlers with any Hono middleware from the ecosystem. + +Learn how to [use Hono](/en/guides/routing/#using-with-hono) with Astro in the advanced routing guide. diff --git a/src/content/docs/en/reference/modules/astro-transitions.mdx b/src/content/docs/en/reference/modules/astro-transitions.mdx index b4e8095410178..2ae6dd61bed74 100644 --- a/src/content/docs/en/reference/modules/astro-transitions.mdx +++ b/src/content/docs/en/reference/modules/astro-transitions.mdx @@ -118,14 +118,6 @@ import { supportsViewTransitions, swapFunctions, transitionEnabledOnThisPage, - /* The following were deprecated in v6: */ - isTransitionBeforePreparationEvent, - isTransitionBeforeSwapEvent, - TRANSITION_AFTER_PREPARATION, - TRANSITION_AFTER_SWAP, - TRANSITION_BEFORE_PREPARATION, - TRANSITION_BEFORE_SWAP, - TRANSITION_PAGE_LOAD, } from 'astro:transitions/client'; ``` @@ -304,211 +296,6 @@ Stores the element in focus on the current page and returns a function that when Replaces the old body with the new body. Then, goes through every element in the old body that should be persisted and have a matching element in the new body and swaps the old element back in place. -### Deprecated imports - -The following imports are deprecated in v6 and will be removed in v7. You can still use them in your project, but you may prefer to update your code now. [See how to upgrade](/en/guides/upgrade-to/v6/#deprecated-exposed-astrotransitions-internals). - -

`isTransitionBeforePreparationEvent()`

- -

- -**Type:** `(value: any) => boolean`
- -

- -:::caution[Deprecated] -This function is deprecated in v6 and will be removed in v7. You can still use it in your project, but you may prefer to update your code now. -::: - -Determines whether the given value matches a [`TransitionBeforePreparationEvent`](#transitionbeforepreparationevent). This can be useful when you need to narrow the type of an event in an event listener. - -```astro title="src/pages/index.astro" "isTransitionBeforePreparationEvent" ---- ---- - - -``` - -

`isTransitionBeforeSwapEvent()`

- -

- -**Type:** `(value: any) => boolean`
- -

- -:::caution[Deprecated] -This function is deprecated in v6 and will be removed in v7. You can still use it in your project, but you may prefer to update your code now. -::: - -Determines whether the given value matches a [`TransitionBeforeSwapEvent`](#transitionbeforeswapevent). This can be useful when you need to narrow the type of an event in an event listener. - -```astro title="src/pages/index.astro" "isTransitionBeforeSwapEvent" ---- ---- - - -``` - -

`TRANSITION_BEFORE_PREPARATION`

- -

- -**Type:** `'astro:before-preparation'`
- -

- -:::caution[Deprecated] -This constant is deprecated in v6 and will be removed in v7. You can still use it in your project, but you may prefer to update your code now. -::: - -A constant to avoid writing the `astro:before-preparation` event name in plain text when you define an event. - -```astro title="src/pages/index.astro" "TRANSITION_BEFORE_PREPARATION" ---- ---- - - -``` - -

`TRANSITION_AFTER_PREPARATION`

- -

- -**Type:** `'astro:after-preparation'`
- -

- -:::caution[Deprecated] -This constant is deprecated in v6 and will be removed in v7. You can still use it in your project, but you may prefer to update your code now. -::: - -A constant to avoid writing the `astro:after-preparation` event name in plain text when you define an event. - -```astro title="src/pages/index.astro" "TRANSITION_AFTER_PREPARATION" ---- ---- - - -``` - -

`TRANSITION_BEFORE_SWAP`

- -

- -**Type:** `'astro:before-swap'`
- -

- -:::caution[Deprecated] -This constant is deprecated in v6 and will be removed in v7. You can still use it in your project, but you may prefer to update your code now. -::: - -A constant to avoid writing the `astro:before-swap` event name in plain text when you define an event. - -```astro title="src/pages/index.astro" "TRANSITION_BEFORE_SWAP" ---- ---- - - -``` - -

`TRANSITION_AFTER_SWAP`

- -

- -**Type:** `'astro:after-swap'`
- -

- -:::caution[Deprecated] -This constant is deprecated in v6 and will be removed in v7. You can still use it in your project, but you may prefer to update your code now. -::: - -A constant to avoid writing the `astro:after-swap` event name in plain text when you define an event. - -```astro title="src/pages/index.astro" "TRANSITION_AFTER_SWAP" ---- ---- - - -``` - -

`TRANSITION_PAGE_LOAD`

- -

- -**Type:** `'astro:page-load'`
- -

- -:::caution[Deprecated] -This constant is deprecated in v6 and will be removed in v7. You can still use it in your project, but you may prefer to update your code now. -::: - -A constant to avoid writing the `astro:page-load` event name in plain text when you define an event. - -```astro title="src/pages/index.astro" "TRANSITION_PAGE_LOAD" ---- ---- - - -``` - ## `astro:transitions/client` types ```ts diff --git a/src/content/docs/en/upgrade-astro.mdx b/src/content/docs/en/upgrade-astro.mdx index 0e5fb1dac497a..0df056043e4b7 100644 --- a/src/content/docs/en/upgrade-astro.mdx +++ b/src/content/docs/en/upgrade-astro.mdx @@ -102,6 +102,7 @@ The main Astro documentation pages are always **accurate for the latest released See the upgrade guides below for an explanation of changes, comparing the new version to the old. The upgrade guides include everything that could require you to change your own code: breaking changes, deprecations, feature removals and replacements as well as updated usage guidance. Each change to Astro includes a "What should I do?" section to help you successfully update your project code. +- [Upgrade to v7](/en/guides/upgrade-to/v7/) - [Upgrade to v6](/en/guides/upgrade-to/v6/) - [Upgrade to v5](/en/guides/upgrade-to/v5/) - [Upgrade to v4](/en/guides/upgrade-to/v4/) diff --git a/src/content/docs/es/guides/astro-db.mdx b/src/content/docs/es/guides/astro-db.mdx deleted file mode 100644 index 53d32c8ea0eb5..0000000000000 --- a/src/content/docs/es/guides/astro-db.mdx +++ /dev/null @@ -1,792 +0,0 @@ ---- -title: 'Astro DB' -description: Aprende a usar Astro DB, una base de datos SQL completamente gestionada diseñada exclusivamente para Astro. -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -import { Steps } from '@astrojs/starlight/components'; - -Astro DB es una base de datos SQL completamente gestionada diseñada para el ecosistema de Astro. Desarrolla localmente en Astro y despliega en cualquier base de datos compatible con libSQL. - -Astro DB es una solución completa para configurar, desarrollar y consultar tus datos. Una base de datos local se crea en `.astro/content.db` cada vez que ejecutas `astro dev` para gestionar tus datos sin necesidad de Docker o una conexión de red. - -## Instalación - -Instala la integración [`@astrojs/db`](/es/guides/integrations-guide/db/) usando el comando incorporado `astro add`: - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -## Define tu base de datos - -Instalar `@astrojs/db` con el comando `astro add` creará automáticamente un archivo `db/config.ts` en tu proyecto donde definirás las tablas de tu base de datos: - -```ts title="db/config.ts" -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: { }, -}) -``` - -### Tablas - -Los datos en Astro DB se almacenan usando tablas SQL. Las tablas estructuran tus datos en filas y columnas, donde las columnas hacen cumplir el tipo de cada valor de fila. - -Define tus tablas en tu archivo `db/config.ts` proporcionando la estructura de los datos en tu base de datos libSQL existente, o los datos que recopilarás en una nueva base de datos. Esto permitirá a Astro generar una interfaz de TypeScript para consultar esa tabla desde tu proyecto. El resultado es soporte completo de TypeScript cuando accedes a tus datos con autocompletado de propiedades y verificación de tipos. - -Para configurar una tabla de base de datos, importa y usa las utilidades `defineTable()` y `column` desde `astro:db`. Luego, define un nombre (sensible a mayúsculas) para tu tabla y el tipo de datos en cada columna. - -Este ejemplo configura una tabla `Comment` con columnas de texto obligatorias para `author` y `body`. Luego, la hace disponible para tu proyecto a través de la exportación `defineDb()`. - -```ts title="db/config.ts" "Comment" -import { defineDb, defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } -}) - -export default defineDb({ - tables: { Comment }, -}) -``` - -Consulta la [referencia de configuración de tablas](/es/guides/integrations-guide/db/#table-configuration-reference) para una referencia completa de las opciones de tabla. - -### Columnas - -Astro DB admite los siguientes tipos de columna: - -```ts title="db/config.ts" "column.text()" "column.number()" "column.boolean()" "column.date()" "column.json()" -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - // Una cadena de texto. - author: column.text(), - // Un valor entero completo. - likes: column.number(), - // Un valor verdadero o falso. - flagged: column.boolean(), - // Valores de fecha/hora consultados como objetos Date de JavaScript. - published: column.date(), - // Un objeto JSON sin tipo. - metadata: column.json(), - } -}); -``` - -Consulta la [referencia de columnas de tabla](/es/guides/integrations-guide/db/#table-configuration-reference) para más detalles. - -### Referencias de Tabla - -Las relaciones entre tablas son un patrón común en el diseño de bases de datos. Por ejemplo, una tabla `Blog` puede estar estrechamente relacionada con otras tablas de `Comment`, `Author` y `Category`. - -Puedes definir estas relaciones entre tablas y guardarlas en tu esquema de base de datos usando **columnas de referencia**. Para establecer una relación, necesitarás: - -- Una **columna identificadora** en la tabla referenciada. Suele ser una columna `id` con la propiedad `primaryKey`. -- Una columna en la tabla base para **almacenar el `id` referenciado**. Esto usa la propiedad `references` para establecer una relación. - -Este ejemplo muestra una columna `authorId` de la tabla `Comment` que referencia una columna `id` de la tabla `Author`. - -```ts title="db/config.ts" {3, 10} -const Author = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - } -}); - -const Comment = defineTable({ - columns: { - authorId: column.number({ references: () => Author.columns.id }), - body: column.text(), - } -}); -``` - -## Sembrar tu base de datos para desarrollo - -En desarrollo, Astro usará tu configuración de DB para generar tipos locales según tus esquemas. Estos se generarán de nuevo desde tu archivo de semilla cada vez que se inicie el servidor de desarrollo, y te permitirán consultar y trabajar con la forma de tus datos con seguridad de tipos y autocompletado. - -No tendrás acceso a datos de producción durante el desarrollo a menos que [te conectes a una base de datos remota](#conectando-a-bases-de-datos-remotas) durante el desarrollo. Esto protege tus datos mientras te permite probar y desarrollar con una base de datos funcional con seguridad de tipos. - -Para sembrar datos de desarrollo para pruebas y depuración en tu proyecto de Astro, crea un archivo `db/seed.ts`. Importa tanto el objeto `db` como tus tablas definidas en `astro:db`. `inserta` algunos datos iniciales en cada tabla. Estos datos de desarrollo deben coincidir con la forma de tu esquema de base de datos y de los datos de producción. - -El siguiente ejemplo define dos filas de datos de desarrollo para una tabla `Comment` y una tabla `Author`: - -```ts title="db/seed.ts" -import { db, Comment, Author } from 'astro:db'; - -export default async function() { - await db.insert(Author).values([ - { id: 1, name: "Kasim" }, - { id: 2, name: "Mina" }, - ]); - - await db.insert(Comment).values([ - { authorId: 1, body: '¡Espero que te guste Astro DB!' }, - { authorId: 2, body: '¡Disfrútalo!'}, - ]) -} -``` - -Tu servidor de desarrollo reiniciará automáticamente tu base de datos cada vez que este archivo cambie, regenerando tus tipos y sembrando estos datos de desarrollo desde `seed.ts` de nuevo cada vez. - -## Conecta una base de datos libSQL para producción - -Astro DB puede conectarse a cualquier base de datos libSQL local o a cualquier servidor que exponga el protocolo remoto de libSQL, ya sea gestionado o autoalojado. - -Para conectar Astro DB a una base de datos libSQL, establece las siguientes variables de entorno obtenidas de tu proveedor de base de datos: - -- `ASTRO_DB_REMOTE_URL`: la URL de conexión a la ubicación de tu base de datos libSQL local o remota. Esto puede incluir [opciones de configuración de URL](#opciones-de-configuración-de-url-remota) como sincronización y cifrado como parámetros. -- `ASTRO_DB_APP_TOKEN`: el token de autenticación para tu servidor libSQL. Esto es obligatorio para bases de datos remotas, y no es necesario para [bases de datos locales como archivos o en memoria](#esquema-de-url-y-host) - -Dependiendo de tu servicio, puedes tener acceso a una CLI o interfaz web para recuperar estos valores. La siguiente sección demostrará conectarse a Turso y establecer estos valores como ejemplo, pero eres libre de usar cualquier proveedor. - -### Comenzando con Turso - -Turso es la empresa detrás de [libSQL](https://github.com/tursodatabase/libsql), el fork de código abierto de SQLite que impulsa Astro DB. Proporcionan una plataforma de base de datos libSQL completamente gestionada y son totalmente compatibles con Astro. - -Los pasos a continuación te guiarán a través del proceso de instalar la CLI de Turso, iniciar sesión (o registrarte), crear una nueva base de datos, obtener las variables de entorno requeridas y empujar el esquema a la base de datos remota. - - - -1. Instala la [CLI de Turso](https://docs.turso.tech/cli/installation). - -2. [Inicia sesión o regístrate](https://docs.turso.tech/cli/authentication) en Turso. - -3. Crea una nueva base de datos. En este ejemplo el nombre de la base de datos es `andromeda`. - - ```sh "andromeda" - turso db create andromeda - ``` - -4. Ejecuta el comando `show` para ver información sobre la base de datos recién creada: - - ```sh "andromeda" - turso db show andromeda - ``` - - Copia el valor `URL` y establécelo como el valor para `ASTRO_DB_REMOTE_URL`. - - - ```dotenv title=".env" "libsql://andromeda-houston.turso.io" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ``` - -5. Crea un nuevo token para autenticar las solicitudes a la base de datos: - - ```sh "andromeda" - turso db tokens create andromeda - ``` - - Copia la salida del comando y establécelo como el valor para `ASTRO_DB_APP_TOKEN`. - - ```dotenv title=".env" add={2} "eyJhbGciOiJF...3ahJpTkKDw" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ASTRO_DB_APP_TOKEN=eyJhbGciOiJF...3ahJpTkKDw - ``` - -6. Empuja tu esquema de DB y metadatos a la nueva base de datos de Turso. - - ```sh - astro db push --remote - ``` - -7. ¡Felicidades, ahora tienes una base de datos conectada! Date un descanso. 👾 - - ```sh - turso relax - ``` - - - -Para explorar más características de Turso, consulta la [documentación de Turso](https://docs.turso.tech). - -### Conectando a bases de datos remotas - -Astro DB te permite conectarte tanto a bases de datos locales como remotas. Por defecto, Astro usa un archivo de base de datos local para los comandos `dev` y `build`, recreando tablas e insertando datos de semilla de desarrollo cada vez. - -Para conectarte a una base de datos remota alojada, usa la bandera `--remote`. Esta bandera habilita tanto acceso de lectura como escritura a tu base de datos remota, permitiéndote [aceptar y persistir datos de usuarios](#insertar) en entornos de producción. - -Configura tu comando de construcción para usar la bandera `--remote`: - -```json title="package.json" "--remote" -{ - "scripts": { - "build": "astro build --remote" - } -} -``` - -También puedes usar la bandera directamente en la línea de comandos: - -```bash -# Construir con una conexión remota -astro build --remote - -# Desarrollar con una conexión remota -astro dev --remote -``` - -:::caution -Ten cuidado al usar `--remote` en desarrollo. Esto se conecta a tu base de datos de producción en vivo, y todos los cambios (inserciones, actualizaciones, eliminaciones) persistirán. -::: - -La bandera `--remote` usa la conexión a la base de datos remota tanto localmente durante la construcción como en el servidor. Asegúrate de establecer las variables de entorno necesarias tanto en tu entorno de desarrollo local como en tu plataforma de despliegue. Además, es posible que necesites [configurar el modo web](/es/guides/integrations-guide/db/#mode) para entornos de ejecución que no sean Node.js, como Cloudflare Workers o Deno. - -Al desplegar tu proyecto de Astro DB, asegúrate de que el comando de construcción de tu plataforma de despliegue esté configurado como `npm run build` (o el equivalente para tu gestor de paquetes) para utilizar la bandera `--remote` configurada en tu `package.json`. - -### Opciones de configuración de URL remota - -La variable de entorno `ASTRO_DB_REMOTE_URL` configura la ubicación de tu base de datos, así como otras opciones como sincronización y cifrado. - -#### Esquema de URL y host - -libSQL admite tanto HTTP como WebSockets como protocolo de transporte para un servidor remoto. También admite usar un archivo local o una base de datos en memoria. Estos se pueden configurar usando los siguientes esquemas de URL en la URL de conexión: - -- `memory:` usará una base de datos en memoria. El host debe estar vacío en este caso. -- `file:` usará un archivo local. El host es la ruta al archivo (`file:path/to/file.db`). -- `libsql:` usará un servidor remoto a través del protocolo preferido por la biblioteca (esto puede variar entre versiones). El host es la dirección del servidor (`libsql://your.server.io`). -- `http:` usará un servidor remoto a través de HTTP. Se puede usar `https:` para habilitar una conexión segura. El host es el mismo que para `libsql:`. -- `ws:` usará un servidor remoto a través de WebSockets. Se puede usar `wss:` para habilitar una conexión segura. El host es el mismo que para `libsql:`. - -Los detalles de la conexión libSQL (por ejemplo, clave de cifrado, replicación, intervalo de sincronización) se pueden configurar como parámetros de consulta en la URL de conexión remota. - -Por ejemplo, para tener un archivo local cifrado que funcione como una réplica embebida de un servidor libSQL, puedes establecer las siguientes variables de entorno: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io -ASTRO_DB_APP_TOKEN=token-to-your-remote-url -``` - -:::caution -Usar un archivo de base de datos es una característica avanzada, y se debe tener cuidado al desplegar para evitar sobrescribir tu base de datos y perder tus datos de producción. - -Además, este método no funcionará en despliegues sin servidor (serverless), ya que el sistema de archivos no persiste en esos entornos. -::: - -#### `encryptionKey` - -libSQL tiene soporte nativo para bases de datos cifradas. Pasar este parámetro de búsqueda habilitará el cifrado usando la clave dada: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file:path/to/file.db?encryptionKey=your-encryption-key -``` - -#### `syncUrl` - -Las réplicas embebidas son una característica de los clientes libSQL que crea una copia completamente sincronizada de tu base de datos en un archivo local o en memoria para lecturas ultrarrápidas. Las escrituras se envían a una base de datos remota definida en `syncUrl` y se sincronizan con la copia local. - -Usa esta propiedad para pasar una URL de conexión separada para convertir la base de datos en una réplica embebida de otra base de datos. Esto solo debe usarse con los esquemas `file:` y `memory:`. El parámetro debe estar codificado en URL. - -Por ejemplo, para tener una réplica embebida en memoria de una base de datos en `libsql://your.server.io`, puedes establecer la URL de conexión así: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io -``` - -#### `syncInterval` - -Intervalo entre sincronizaciones de réplicas embebidas en segundos. Por defecto solo se sincroniza al inicio y después de escrituras. - -Esta propiedad solo se usa cuando `syncUrl` también está establecida. Por ejemplo, para establecer una réplica embebida en memoria que se sincronice cada minuto, establece la siguiente variable de entorno: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io&syncInterval=60 -``` - -## Consulta tu base de datos - -Puedes consultar tu base de datos desde cualquier [página de Astro](/es/basics/astro-pages/#páginas-de-astro), [endpoint](/es/guides/endpoints/), o [acción](/es/guides/actions/) en tu proyecto usando el ORM `db` y el constructor de consultas proporcionados. - -### Drizzle ORM - -```ts -import { db } from 'astro:db'; -``` - -Astro DB incluye un cliente [Drizzle ORM](https://orm.drizzle.team/) incorporado. No se requiere configuración o configuración manual para usar el cliente. El cliente `db` de Astro DB se configura automáticamente para comunicarse con tu base de datos (local o remota) cuando ejecutas Astro. Usa tu definición exacta de esquema de base de datos para consultas SQL con seguridad de tipos con errores de TypeScript cuando haces referencia a una columna o tabla que no existe. - -### Seleccionar - -El siguiente ejemplo selecciona todas las filas de una tabla `Comment`. Esto devuelve el arreglo completo de datos de desarrollo sembrados desde `db/seed.ts` que luego está disponible para usar en tu plantilla de página: - -```astro title="src/pages/index.astro" ---- -import { db, Comment } from 'astro:db'; - -const comments = await db.select().from(Comment); ---- - -

Comentarios

- -{ - comments.map(({ author, body }) => ( -
-

Autor: {author}

-

{body}

-
- )) -} -``` - -Consulta la [referencia de la API `select()` de Drizzle](https://orm.drizzle.team/docs/select) para una descripción completa. - -### Insertar - -Para aceptar entrada de usuario, como manejar solicitudes de formularios e insertar datos en tu base de datos remota alojada, configura tu proyecto de Astro para [renderizado bajo demanda](/es/guides/on-demand-rendering/) y [agrega un adaptador](/es/guides/on-demand-rendering/#agrega-un-adaptador) para tu entorno de despliegue. - -Este ejemplo inserta una fila en una tabla `Comment` basada en una solicitud POST de formulario analizada: - -```astro ---- -// src/pages/index.astro -import { db, Comment } from 'astro:db'; - -if (Astro.request.method === 'POST') { - // Analiza los datos del formulario - const formData = await Astro.request.formData(); - const author = formData.get('author'); - const body = formData.get('body'); - if (typeof author === 'string' && typeof body === 'string') { - // Inserta los datos del formulario en la tabla Comment - await db.insert(Comment).values({ author, body }); - } -} - -// Renderiza la nueva lista de comentarios en cada solicitud -const comments = await db.select().from(Comment); ---- - -
- - - - - - - -
- - -``` - -También puedes usar [acciones de Astro](/es/guides/actions/) para insertar datos en una tabla de Astro DB. El siguiente ejemplo inserta una fila en una tabla `Comment` usando una acción: - -```ts -// src/actions/index.ts -import { db, Comment } from 'astro:db'; -import { defineAction } from 'astro:actions'; -import { z } from 'astro/zod'; - -export const server = { - addComment: defineAction({ - // Las acciones incluyen seguridad de tipos con Zod, eliminando la necesidad - // de verificar si typeof {valor} === 'string' en tus páginas - input: z.object({ - author: z.string(), - body: z.string(), - }), - handler: async (input) => { - const updatedComments = await db - .insert(Comment) - .values(input) - .returning(); // Devuelve los comentarios actualizados - return updatedComments; - }, - }), -}; -``` - - - -Consulta la [referencia de la API `insert()` de Drizzle](https://orm.drizzle.team/docs/insert) para una descripción completa. - - - -### Eliminar - -También puedes consultar tu base de datos desde un endpoint de API. Este ejemplo elimina una fila de una tabla `Comment` por el parámetro `id`: - -```ts -// src/pages/api/comments/[id].ts -import type { APIRoute } from "astro"; -import { db, Comment, eq } from 'astro:db'; - -export const DELETE: APIRoute = async (ctx) => { - await db.delete(Comment).where(eq(Comment.id, ctx.params.id )); - return new Response(null, { status: 204 }); -} -``` - - - -Consulta la [referencia de la API `delete()` de Drizzle](https://orm.drizzle.team/docs/delete) para una descripción completa. - - - -### Filtrado - -Para consultar resultados de tabla por una propiedad específica, usa [opciones de Drizzle para selecciones parciales](https://orm.drizzle.team/docs/select#partial-select). Por ejemplo, agrega [una llamada `.where()`](https://orm.drizzle.team/docs/select#filtering) a tu consulta `select()` y pasa la comparación que quieres hacer. - -El siguiente ejemplo consulta todas las filas en una tabla `Comment` que contengan la frase "Astro DB". Usa [el operador `like()`](https://orm.drizzle.team/docs/operators#like) para verificar si una frase está presente dentro del `body`: - - -```astro title="src/pages/index.astro" ---- -import { db, Comment, like } from 'astro:db'; - -const comments = await db.select().from(Comment).where( - like(Comment.body, '%Astro DB%') -); ---- -``` - -### Utilidades de Drizzle - -Todas las utilidades de Drizzle para construir consultas están expuestas desde el módulo `astro:db`. Esto incluye: - -- [Operadores de filtro](https://orm.drizzle.team/docs/operators) como `eq()` y `gt()` -- [Ayudantes de agregación](https://orm.drizzle.team/docs/select#aggregations-helpers) como `count()` -- [El ayudante `sql`](https://orm.drizzle.team/docs/sql) para escribir consultas SQL crudas - -```ts -import { eq, gt, count, sql } from 'astro:db'; -``` - -### Relaciones - -Puedes consultar datos relacionados desde múltiples tablas usando un join de SQL. Para crear una consulta de join, extiende tu sentencia `db.select()` con un operador de join. Cada función acepta una tabla con la que unir y una condición para emparejar filas entre las dos tablas. - -Este ejemplo usa una función `innerJoin()` para unir autores de `Comment` con su información de `Author` relacionada basada en la columna `authorId`. Esto devuelve un arreglo de objetos con cada fila de `Author` y `Comment` como propiedades de primer nivel: - -```astro title="src/pages/index.astro" ---- -import { db, eq, Comment, Author } from 'astro:db'; - -const comments = await db.select() - .from(Comment) - .innerJoin(Author, eq(Comment.authorId, Author.id)); ---- - -

Comentarios

- -{ - comments.map(({ Author, Comment }) => ( -
-

Autor: {Author.name}

-

{Comment.body}

-
- )) -} -``` - - - -Consulta la [referencia de join de Drizzle](https://orm.drizzle.team/docs/joins#join-types) para todos los operadores de join y opciones de configuración disponibles. - - - -### Transacciones por Lotes - -Todas las consultas a bases de datos remotas se realizan como una solicitud de red. Es posible que necesites "agrupar" consultas juntas en una sola transacción cuando hagas un gran número de consultas, o para tener reversiones automáticas si falla alguna consulta. - -Este ejemplo siembra múltiples filas en una sola solicitud usando el método `db.batch()`: - -```ts -// db/seed.ts -import { db, Author, Comment } from 'astro:db'; - -export default async function () { - const queries = []; - // Siembra 100 comentarios de ejemplo en tu base de datos remota - // con una sola solicitud de red. - for (let i = 0; i < 100; i++) { - queries.push(db.insert(Comment).values({ body: `Comentario de prueba ${i}` })); - } - await db.batch(queries); -} -``` - - - -Consulta la documentación de [`db.batch()` de Drizzle](https://orm.drizzle.team/docs/batch-api) para más detalles. - - - -## Empujando cambios a tu base de datos - -Puedes empujar cambios realizados durante el desarrollo a tu base de datos. - -### Empujando esquemas de tabla - -Tu esquema de tabla puede cambiar con el tiempo a medida que tu proyecto crece. Puedes probar de manera segura cambios de configuración localmente y empujar a tu base de datos remota cuando despliegues. - -Puedes empujar tus cambios de esquema local a tu base de datos remota a través de la CLI usando el comando `astro db push --remote`: - - - - ```sh - npm run astro db push --remote - ``` - - - ```sh - pnpm astro db push --remote - ``` - - - ```sh - yarn astro db push --remote - ``` - - - -Este comando verificará que tus cambios locales se pueden realizar sin pérdida de datos y, si es necesario, sugerirá cómo hacer cambios en tu esquema de manera segura para resolver conflictos. - -#### Empujando cambios de esquema que rompen compatibilidad - -:::danger -__Esto destruirá tu base de datos__. Solo realiza este comando si no necesitas tus datos de producción. -::: - -Si debes cambiar tu esquema de tabla de una manera que es incompatible con tus datos existentes alojados en tu base de datos remota, necesitarás resetear tu base de datos de producción. - -Para empujar una actualización de esquema de tabla que incluya un cambio que rompe compatibilidad, agrega la bandera `--force-reset` para resetear todos los datos de producción: - - - - ```sh - npm run astro db push --remote --force-reset - ``` - - - ```sh - pnpm astro db push --remote --force-reset - ``` - - - ```sh - yarn astro db push --remote --force-reset - ``` - - - -### Renombrando tablas - -Es posible renombrar una tabla después de haber empujado tu esquema a tu base de datos remota. - -Si **no tienes datos de producción importantes**, entonces puedes [resetear tu base de datos](#empujando-cambios-de-esquema-que-rompen-compatibilidad) usando la bandera `--force-reset`. Esta bandera eliminará todas las tablas de la base de datos y creará nuevas para que coincida exactamente con tu esquema actual. - -Para renombrar una tabla mientras preservas tus datos de producción, debes realizar una serie de cambios no destructivos para empujar tu esquema local a tu base de datos remota de manera segura. - -El siguiente ejemplo renombra una tabla de `Comment` a `Feedback`: - - - -1. En tu archivo de configuración de base de datos, agrega la propiedad `deprecated: true` a la tabla que quieres renombrar: - - ```ts title="db/config.ts" ins={2} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -2. Agrega un nuevo esquema de tabla (coincidiendo exactamente con las propiedades de la tabla existente) con el nuevo nombre: - - ```ts title="db/config.ts" ins={8-14} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -3. [Empuja a tu base de datos remota](#empujando-esquemas-de-tabla) con `astro db push --remote`. Esto agregará la nueva tabla y marcará la antigua como obsoleta. -4. Actualiza cualquier código de tu proyecto local para usar la nueva tabla en lugar de la antigua. Es posible que también necesites migrar datos a la nueva tabla. -5. Una vez que estés seguro de que la tabla antigua ya no se usa en tu proyecto, puedes eliminar el esquema de tu `config.ts`: - ```ts title="db/config.ts" del={1-7} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` -6. Empuja a tu base de datos remota nuevamente con `astro db push --remote`. La tabla antigua será eliminada, dejando solo la nueva tabla renombrada. - - -### Empujando datos de tabla - -Es posible que necesites empujar datos a tu base de datos remota para sembrar o migraciones de datos. Puedes crear un archivo `.ts` con el módulo `astro:db` para escribir consultas con seguridad de tipos. Luego, ejecuta el archivo contra tu base de datos remota usando el comando `astro db execute --remote`: - -Los siguientes Comentarios se pueden sembrar usando el comando `astro db execute db/seed.ts --remote`: - -```ts -// db/seed.ts -import { Comment } from 'astro:db'; - -export default async function () { - await db.insert(Comment).values([ - { authorId: 1, body: '¡Espero que te guste Astro DB!' }, - { authorId: 2, body: '¡Disfrútalo!' }, - ]) -} -``` - - - -Consulta la [referencia de la CLI](/es/guides/integrations-guide/db/#astro-db-cli-reference) para una lista completa de comandos. - - - -## Construyendo integraciones de Astro DB - -Las [integraciones de Astro](/es/reference/integrations-reference/) pueden extender proyectos de usuario con tablas adicionales de Astro DB y datos de semilla. - -Usa el método `extendDb()` en el hook `astro:db:setup` para registrar configuraciones adicionales de Astro DB y archivos de semilla. -El ayudante `defineDbIntegration()` proporciona soporte de TypeScript y autocompletado para el hook `astro:db:setup`. - -```js {8-13} -// my-integration/index.ts -import { defineDbIntegration } from '@astrojs/db/utils'; - -export default function MyIntegration() { - return defineDbIntegration({ - name: 'mi-integracion-impulsada-por-astro-db', - hooks: { - 'astro:db:setup': ({ extendDb }) => { - extendDb({ - configEntrypoint: '@astronaut/my-package/config', - seedEntrypoint: '@astronaut/my-package/seed', - }); - }, - // Otros hooks de integración... - }, - }); -} -``` - -Los archivos de [configuración](#define-tu-base-de-datos) y [semilla](#sembrar-tu-base-de-datos-para-desarrollo) de integración siguen el mismo formato que sus equivalentes definidos por el usuario. - -### Operaciones con seguridad de tipos en integraciones - -Mientras trabajas en integraciones, es posible que no puedas beneficiarte de los tipos de tabla generados por Astro exportados desde `astro:db`. -Para seguridad de tipos completa, usa la utilidad `asDrizzleTable()` para crear un objeto de referencia de tabla que puedas usar para operaciones de base de datos. - -Por ejemplo, dada una integración configurando la siguiente tabla de base de datos `Pets`: - -```js -// my-integration/config.ts -import { defineDb, defineTable, column } from 'astro:db'; - -export const Pets = defineTable({ - columns: { - name: column.text(), - species: column.text(), - }, -}); - -export default defineDb({ tables: { Pets } }); -``` - -El archivo de semilla puede importar `Pets` y usar `asDrizzleTable()` para insertar filas en tu tabla con verificación de tipos: - -```js {2,7} /typeSafePets(?! )/ -// my-integration/seed.ts -import { asDrizzleTable } from '@astrojs/db/utils'; -import { db } from 'astro:db'; -import { Pets } from './config'; - -export default async function() { - const typeSafePets = asDrizzleTable('Pets', Pets); - - await db.insert(typeSafePets).values([ - { name: 'Palomita', species: 'cat' }, - { name: 'Pan', species: 'dog' }, - ]); -} -``` - -El valor devuelto por `asDrizzleTable('Pets', Pets)` es equivalente a `import { Pets } from 'astro:db'`, pero está disponible incluso cuando la generación de tipos de Astro no puede ejecutarse. -Puedes usarlo en cualquier código de integración que necesite consultar o insertar en la base de datos. - -## Migrar de Astro Studio a Turso - - - -1. En el [panel de control de Studio](https://studio.astro.build/), navega al proyecto que deseas migrar. En la pestaña de configuración, usa el botón "Exportar Base de Datos" para descargar un volcado de tu base de datos. -2. Sigue las instrucciones oficiales para [instalar la CLI de Turso](https://docs.turso.tech/cli/installation) y [registrarte o iniciar sesión](https://docs.turso.tech/cli/authentication) en tu cuenta de Turso. -3. Crea una nueva base de datos en Turso usando el comando `turso db create`. - ```sh - turso db create [nombre-de-la-base-de-datos] - ``` -4. Obtén la URL de la base de datos usando la CLI de Turso, y úsala como la variable de entorno `ASTRO_DB_REMOTE_URL`. - ```sh - turso db show [nombre-de-la-base-de-datos] - ``` - ```dotenv - ASTRO_DB_REMOTE_URL=[tu-url-de-base-de-datos] - ``` -5. Crea un token para acceder a tu base de datos, y úsalo como la variable de entorno `ASTRO_DB_APP_TOKEN`. - ```sh - turso db tokens create [nombre-de-la-base-de-datos] - ``` - ```dotenv - ASTRO_DB_APP_TOKEN=[tu-token-de-aplicación] - ``` -6. Empuja tu esquema de DB y metadatos a la nueva base de datos de Turso. - ```sh - astro db push --remote - ``` -7. Importa el volcado de base de datos del paso 1 en tu nueva DB de Turso. - ```sh - turso db shell [nombre-de-la-base-de-datos] < ./ruta/al/volcado.sql - ``` -8. Una vez que hayas confirmado que tu proyecto se conecta a la nueva base de datos, puedes eliminar de manera segura el proyecto de Astro Studio. - - diff --git a/src/content/docs/es/reference/experimental-flags/rust-compiler.mdx b/src/content/docs/es/reference/experimental-flags/rust-compiler.mdx deleted file mode 100644 index c65202c2b84c8..0000000000000 --- a/src/content/docs/es/reference/experimental-flags/rust-compiler.mdx +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Compilador experimental en Rust -sidebar: - label: Compilador en Rust -i18nReady: true ---- - -import Since from '~/components/Since.astro' -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' - -

- - **Tipo:** `boolean`
- **Por defecto:** `false`
- -

- -Habilita el uso del nuevo compilador de Astro basado en Rust para archivos Astro. Este compilador es más rápido, ofrece mejores mensajes de error y, en general, mejor soporte para funcionalidades modernas de JavaScript, TypeScript y CSS. - -En una futura versión mayor, Astro usará este nuevo compilador por defecto, pero puedes adelantar ese comportamiento usando el flag `experimental.rustCompiler`. - -Para dar feedback sobre el compilador o seguir su desarrollo, consulta la [RFC del nuevo compilador de Astro](https://github.com/withastro/roadmap/discussions/1306) para más información y discusión. - -## Uso - -Este flag experimental no requiere uso específico y solo afecta a qué compilador usa Astro en tu proyecto. - -Para habilitar el compilador en Rust, agrega lo siguiente en tu `astro.config.mjs`: - -```js title="astro.config.mjs" ins={4-6} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - rustCompiler: true - } -}); -``` - -y luego instala el paquete `@astrojs/compiler-rs` en tu proyecto: - - - - ```shell - npm install @astrojs/compiler-rs - ``` - - - ```shell - pnpm add @astrojs/compiler-rs - ``` - - - ```shell - yarn add @astrojs/compiler-rs - ``` - - - -### Diferencias esperadas - -A diferencia del compilador actual de Astro (Go), este compilador experimental en Rust no corregirá automáticamente estructuras HTML inválidas. Por ejemplo, estos patrones se dejarán tal como están y ya no se corregirán: - -- `

Bad nesting

` (en lugar de sacar el `div` fuera del `p`) -- `

My paragraph` (en lugar de añadir la etiqueta de cierre `

` faltante) - -Esto significa que, si tus archivos Astro contienen HTML inválido, puedes ver un resultado distinto con el compilador en Rust respecto al compilador anterior, o encontrar errores durante el build. - -## Limitaciones - -Actualmente, el compilador en Rust no genera los metadatos necesarios para que las auditorías de la barra de herramientas de desarrollo funcionen correctamente. diff --git a/src/content/docs/fr/guides/astro-db.mdx b/src/content/docs/fr/guides/astro-db.mdx deleted file mode 100644 index 3126395abe42a..0000000000000 --- a/src/content/docs/fr/guides/astro-db.mdx +++ /dev/null @@ -1,801 +0,0 @@ ---- -title: 'Astro DB' -description: Apprenez à utiliser Astro DB, une base de données SQL entièrement gérée, conçue exclusivement pour Astro. -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -import { Steps } from '@astrojs/starlight/components'; - -:::caution[Déprécié] -L'intégration `@astrojs/db` a été dépréciée dans la v6.5 d'Astro et n'est plus maintenue. - -Si vous utilisiez cette intégration dans votre projet, nous vous recommandons d'utiliser un client de base de données (par exemple, Drizzle, Kysely) directement dans votre projet Astro. -::: - -Astro DB est une base de données SQL entièrement gérée conçue pour l'écosystème Astro. Développez localement dans Astro et déployez vers n'importe quelle base de données compatible libSQL. - -Astro DB est une solution complète pour configurer, développer et interroger vos données. Une base de données locale est créée dans `.astro/content.db` chaque fois que vous exécutez `astro dev` pour gérer vos données sans avoir besoin de Docker ou d'une connexion réseau. - -## Installation - -Installez [l'intégration `@astrojs/db`](/fr/guides/integrations-guide/db/) à l'aide de la commande intégrée `astro add` : - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -## Définir votre base de données - -L'installation de `@astrojs/db` avec la commande `astro add` créera automatiquement un fichier `db/config.ts` dans votre projet où vous définirez vos tables de base de données : - -```ts title="db/config.ts" -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: { }, -}) -``` - -### Tables - -Dans Astro DB, les données sont stockées dans des tables SQL. Les tables structurent vos données en lignes et en colonnes, où les colonnes imposent le type de chaque valeur de ligne. - -Définissez vos tables dans votre fichier `db/config.ts` en fournissant la structure des données de votre base de données libSQL existante ou les données que vous collecterez dans une nouvelle base de données. Cela permettra à Astro de générer une interface TypeScript pour interroger cette table à partir de votre projet. Le résultat est une prise en charge complète de TypeScript lorsque vous accédez à vos données avec la saisie semi-automatique des propriétés et la vérification des types. - -Pour configurer une table de base de données, importez et utilisez les utilitaires `defineTable()` et `column` depuis `astro:db`. Ensuite, définissez un nom (sensible à la casse) pour votre table et le type de données dans chaque colonne. - -Cet exemple configure une table `Comment` avec les colonnes de texte requises pour `author` et `body` et la rend disponible pour votre projet via l'exportation `defineDb()`. - -```ts title="db/config.ts" "Comment" -import { defineDb, defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } -}) - -export default defineDb({ - tables: { Comment }, -}) -``` - -Voir la [référence de configuration des tables](/fr/guides/integrations-guide/db/#référence-de-configuration-des-tables) pour une référence complète des options de table. - -### Colonnes - -Astro DB prend en charge les types de colonnes suivants : - -```ts title="db/config.ts" "column.text()" "column.number()" "column.boolean()" "column.date()" "column.json()" -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - // Une chaîne de texte. - author: column.text(), - // Une valeur entière. - likes: column.number(), - // Une valeur vraie ou fausse. - flagged: column.boolean(), - // Valeurs de date et d'heure interrogées sous forme d'Objets JavaScript de type date. - published: column.date(), - // Un objet JSON non typé. - metadata: column.json(), - } -}); -``` - -Voir la [référence des colonnes de la table](/fr/guides/integrations-guide/db/#référence-de-configuration-des-tables) pour plus de détails. - -### Références des tables - -Les relations entre les tables sont un modèle courant dans la conception des bases de données. Par exemple, une table `Blog` peut être en relation étroite avec d'autres tables `Comment`, `Author`, et `Category`. - -Vous pouvez définir ces relations entre les tables et les enregistrer dans votre schéma de base de données à l'aide de **colonnes de référence**. Pour établir une relation, vous aurez besoin de : - -- Une **colonne identifiant** de la table référencée. Il s'agit généralement d'une colonne `id` avec la propriété `primaryKey`. -- Une colonne sur la table de base pour **stocker l'`id` référencé**. Celle-ci utilise la propriété `references` pour établir une relation. - -Cet exemple montre que la colonne `authorId` d'une table `Comment` fait référence à la colonne `id` d'une table `Author`. - -```ts title="db/config.ts" {3, 10} -const Author = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - } -}); - -const Comment = defineTable({ - columns: { - authorId: column.number({ references: () => Author.columns.id }), - body: column.text(), - } -}); -``` - -## Alimenter votre base de données pour le développement - -En cours de développement, Astro utilisera la configuration de votre base de données pour générer des types locaux en fonction de vos schémas. Ces derniers seront générés à partir de votre fichier de départ à chaque démarrage du serveur de développement et vous permettront d'interroger et de travailler avec la forme de vos données avec la sûreté du typage et la saisie semi-automatique. - -Vous n'aurez pas accès aux données de production pendant le développement, sauf si vous vous [connectez à une base de données distante](#connexion-à-des-bases-de-données-distantes) pendant le développement. Cela protège vos données tout en vous permettant de tester et de développer avec une base de données fonctionnelle et la sûreté du typage. - -Pour introduire des données de développement à des fins de test et de débogage dans votre projet Astro, créez un fichier `db/seed.ts`. Importez à la fois l'objet `db` et vos tables définies dans `astro:db`. Puis insérez des données initiales dans chaque table. Ces données de développement doivent correspondre à la forme de votre schéma de base de données et de vos données de production. - -L'exemple suivant définit deux lignes de données de développement pour une table `Comment` et une table `Author` : - -```ts title="db/seed.ts" -import { db, Comment, Author } from 'astro:db'; - -export default async function() { - await db.insert(Author).values([ - { id: 1, name: "Kasim" }, - { id: 2, name: "Mina" }, - ]); - - await db.insert(Comment).values([ - { authorId: 1, body: 'Nous espérons que vous aimez Astro DB !' }, - { authorId: 2, body: 'Profitez-en !'}, - ]) -} -``` - -Votre serveur de développement redémarrera automatiquement votre base de données chaque fois que ce fichier sera modifié, en régénérant vos types et en initialisant ces données de développement à partir de `seed.ts` à chaque fois. - -## Connecter une base de données libSQL pour la production - -Astro DB peut se connecter à n'importe quelle base de données libSQL locale ou à n'importe quel serveur qui expose le protocole distant libSQL, qu'il soit géré ou auto-hébergé. - -Pour connecter Astro DB à une base de données libSQL, définissez les variables d'environnement suivantes obtenues auprès de votre fournisseur de base de données : - -- `ASTRO_DB_REMOTE_URL` : l'URL de connexion à l'emplacement de votre base de données libSQL locale ou distante. Cela peut inclure des [options de configuration d'URL](#options-de-configuration-durl-distantes) telles que la synchronisation et le chiffrement en tant que paramètres. -- `ASTRO_DB_APP_TOKEN` : le jeton d'authentification de votre serveur libSQL. Ceci est nécessaire pour les bases de données distantes et n'est pas nécessaire pour [les bases de données locales comme les fichiers ou les bases de données en mémoire](#schéma-durl-et-hôte). - -Selon votre service, vous pouvez avoir accès à une interface CLI ou à une interface web pour récupérer ces valeurs. La section suivante illustre la connexion à Turso et la définition de ces valeurs à titre d'exemple, mais vous êtes libre d'utiliser n'importe quel fournisseur. - -### Premiers pas avec Turso - -Turso est l'entreprise à l'origine de [libSQL](https://github.com/tursodatabase/libsql), le fork open source de SQLite qui alimente Astro DB. Ils fournissent une plate-forme de base de données libSQL entièrement gérée et sont entièrement compatibles avec Astro. - -Les étapes ci-dessous vous guideront tout au long du processus d'installation de la CLI de Turso, de connexion (ou d'inscription), de création d'une nouvelle base de données, d'obtention des variables d'environnement requises et de transmission du schéma à la base de données distante. - - - -1. Installez la [CLI de Turso](https://docs.turso.tech/cli/installation). - -2. [Connectez-vous ou inscrivez-vous](https://docs.turso.tech/cli/authentication) à Turso. - -3. Créez une nouvelle base de données. Dans cet exemple, le nom de la base de données est `andromeda`. - - ```sh "andromeda" - turso db create andromeda - ``` - -4. Exécutez la commande `show` pour voir les informations sur la base de données nouvellement créée : - - ```sh "andromeda" - turso db show andromeda - ``` - - Copiez la valeur `URL` et définissez-la comme valeur pour `ASTRO_DB_REMOTE_URL`. - - - ```dotenv title=".env" "libsql://andromeda-houston.turso.io" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ``` - -5. Créez un nouveau jeton pour authentifier les requêtes vers la base de données : - - ```sh "andromeda" - turso db tokens create andromeda - ``` - - Copiez la sortie de la commande et définissez-la comme valeur pour `ASTRO_DB_APP_TOKEN`. - - ```dotenv title=".env" add={2} "eyJhbGciOiJF...3ahJpTkKDw" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ASTRO_DB_APP_TOKEN=eyJhbGciOiJF...3ahJpTkKDw - ``` - -6. Transférez vos schéma et métadonnées de base de données vers la nouvelle base de données Turso. - - ```sh - astro db push --remote - ``` - -7. Félicitations, vous avez maintenant une base de données connectée ! Accordez-vous une pause. 👾 - - ```sh - turso relax - ``` - - - -Pour découvrir davantage de fonctionnalités de Turso, consultez la [documentation de Turso](https://docs.turso.tech). - -### Connexion à des bases de données distantes - -Astro DB vous permet de vous connecter à des bases de données locales et distantes. Par défaut, Astro utilise un fichier de base de données local pour les commandes `dev` et `build`, recréant des tables et insérant des données de développement à chaque fois. - -Pour vous connecter à une base de données distante hébergée, utilisez l'option `--remote`. Celle-ci permet un accès en lecture et en écriture à votre base de données distante, ce qui vous permet d'[accepter et de conserver les données utilisateur](#insérer) dans les environnements de production. - -Configurez votre commande de compilation pour utiliser l'option `--remote` : - -```json title="package.json" "--remote" -{ - "scripts": { - "build": "astro build --remote" - } -} -``` - -Vous pouvez également utiliser l'option directement dans la ligne de commande : - -```bash -# Compiler avec une connexion à distance -astro build --remote - -# Développer avec une connexion à distance -astro dev --remote -``` - -:::caution -Soyez prudent lorsque vous utilisez `--remote` en développement. Cela entraîne la connexion à votre base de données de production en direct et toutes les modifications (insertions, mises à jour, suppressions) seront conservées. -::: - -L'option `--remote` utilise la connexion à la base de données distante à la fois localement pendant la compilation et sur le serveur. Assurez-vous de définir les variables d'environnement nécessaires à la fois dans votre environnement de développement local et sur votre plateforme de déploiement. De plus, vous devrez peut-être [configurer le mode web](/fr/guides/integrations-guide/db/#mode) pour les environnements d'exécution n'utilisant pas Node.js tels que Cloudflare Workers ou Deno. - -Lors du déploiement de votre projet Astro DB, assurez-vous que la commande de compilation de votre plate-forme de déploiement est définie sur `npm run build` (ou l'équivalent pour votre gestionnaire de paquets) pour utiliser l'option `--remote` configurée dans votre fichier `package.json`. - -### Options de configuration d'URL distantes - -La variable d'environnement `ASTRO_DB_REMOTE_URL` configure l'emplacement de votre base de données ainsi que d'autres options telles que la synchronisation et le chiffrement. - -#### Schéma d'URL et hôte - -libSQL prend en charge HTTP et WebSockets comme protocole de transport pour un serveur distant. Il prend également en charge l'utilisation d'un fichier local ou d'une base de données en mémoire. Ceux-ci peuvent être configurés à l'aide des schémas d'URL suivants dans l'URL de connexion : - -- `memory:` utilisera une base de données en mémoire. L'hôte doit être vide dans ce cas. -- `file:` utilisera un fichier local. L'hôte est le chemin d'accès au fichier (`file:path/to/file.db`). -- `libsql:` utilisera un serveur distant via le protocole préféré par la bibliothèque (cela peut être différent selon les versions). L'hôte est l'adresse du serveur (`libsql://your.server.io`). -- `http:` utilisera un serveur distant via HTTP. `https:` peut être utilisé pour activer une connexion sécurisée. L'hôte est le même que pour `libsql:`. -- `ws:` utilisera un serveur distant via WebSockets. `wss:` peut être utilisé pour activer une connexion sécurisée. L'hôte est le même que pour `libsql:`. - -Les détails de la connexion libSQL (par exemple, la clé de chiffrement, la réplication, l'intervalle de synchronisation) peuvent être configurés comme paramètres de requête dans l'URL de connexion à distance. - -Par exemple, pour qu'un fichier local chiffré fonctionne comme une réplique intégrée sur un serveur libSQL, vous pouvez définir les variables d'environnement suivantes : - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io -ASTRO_DB_APP_TOKEN=token-to-your-remote-url -``` - -:::caution -L'utilisation d'un fichier de base de données est une fonctionnalité avancée et des précautions doivent être prises lors du déploiement pour éviter de remplacer votre base de données et de perdre vos données de production. - -De plus, cette méthode ne fonctionnera pas dans les déploiements sans serveur, car le système de fichiers n’est pas conservé dans ces environnements. -::: - -#### `encryptionKey` - -libSQL prend en charge nativement les bases de données chiffrées. La transmission de ce paramètre de recherche activera le chiffrement à l'aide de la clé donnée : - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file:path/to/file.db?encryptionKey=your-encryption-key -``` - -#### `syncUrl` - -Les répliques intégrées sont une fonctionnalité des clients libSQL qui crée une copie synchronisée complète de votre base de données sur un fichier local ou en mémoire pour des lectures ultra-rapides. Les écritures sont envoyées vers une base de données distante définie sur `syncUrl` et synchronisées avec la copie locale. - -Utilisez cette propriété pour transmettre une URL de connexion distincte afin de transformer la base de données en une réplique intégrée d'une autre base de données. Cela ne doit être utilisé qu'avec les schémas `file:` et `memory:`. Le paramètre doit être codé au format URL. - -Par exemple, pour avoir une réplique intégrée en mémoire d'une base de données sur `libsql://votre.server.io`, vous pouvez définir l'URL de connexion comme suit : - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io -``` - -#### `syncInterval` - -Intervalle en secondes entre les synchronisations de répliques intégrées. Par défaut, la synchronisation se fait uniquement au démarrage et après les écritures. - -Cette propriété n'est utilisée que lorsque `syncUrl` est également définie. Par exemple, pour configurer une réplique intégrée en mémoire afin qu'elle se synchronise toutes les minutes, définissez la variable d'environnement suivante : - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io&syncInterval=60 -``` - -## Interroger votre base de données - -Vous pouvez interroger votre base de données depuis n'importe quelle [page Astro](/fr/basics/astro-pages/#pages-astro) ou [point de terminaison](/fr/guides/endpoints/) ou [action](/fr/guides/actions/) de votre projet en utilisant l'ORM `db` et le constructeur de requêtes fourni. - -### Drizzle ORM - -```ts -import { db } from 'astro:db'; -``` - -Astro DB comprend un client intégré [Drizzle ORM](https://orm.drizzle.team/). Il n'y a pas d'installation ou de configuration manuelle requise pour utiliser le client. Le client Astro DB `db` est automatiquement configuré pour communiquer avec votre base de données (locale ou distante) lorsque vous lancez Astro. Il utilise la définition exacte de votre schéma de base de données pour des requêtes SQL avec sûreté du typage et des erreurs TypeScript lorsque vous référencez une colonne ou une table qui n'existe pas. - -### Sélectionner - -L'exemple suivant sélectionne toutes les lignes d'une table `Comment`. Cela renvoie le tableau complet des données de développement provenant de `db/seed.ts`, qui est alors disponible pour être utilisé dans votre modèle de page : - -```astro title="src/pages/index.astro" ---- -import { db, Comment } from 'astro:db'; - -const comments = await db.select().from(Comment); ---- - -

Commentaires

- -{ - comments.map(({ author, body }) => ( -
-

Auteur : {author}

-

{body}

-
- )) -} -``` - -Consultez la [référence de l'API `select()` de Drizzle](https://orm.drizzle.team/docs/select) pour un aperçu complet. - -### Insérer - -Pour accepter les entrées de l'utilisateur, comme le traitement des demandes de formulaire et l'insertion de données dans votre base de données hébergée à distance, configurez votre projet Astro pour [un rendu à la demande](/fr/guides/on-demand-rendering/) et [ajoutez un adaptateur](/fr/guides/on-demand-rendering/#ajouter-un-adaptateur) pour votre environnement de déploiement. - -Cet exemple insère une ligne dans une table `Comment` sur la base d'une requête POST de formulaire analysée : - -```astro ---- -// src/pages/index.astro -import { db, Comment } from 'astro:db'; - -if (Astro.request.method === 'POST') { - // Analyser les données du formulaire - const formData = await Astro.request.formData(); - const author = formData.get('author'); - const content = formData.get('content'); - if (typeof author === 'string' && typeof content === 'string') { - // Insérer les données du formulaire dans la table Comment - await db.insert(Comment).values({ author, content }); - } -} - -// Affiche la nouvelle liste des commentaires sur chaque demande -const comments = await db.select().from(Comment); ---- - -
- - - - - - - -
- - -``` - -Vous pouvez également utiliser [Astro Actions](/fr/guides/actions/) pour insérer des données dans une table Astro DB. L'exemple suivant insère une ligne dans une table `Comment` à l'aide d'une action : - -```ts -// src/actions/index.ts -import { db, Comment } from 'astro:db'; -import { defineAction } from 'astro:actions'; -import { z } from 'astro/zod'; - -export const server = { - addComment: defineAction({ - // Les actions incluent la sûreté du typage avec Zod, supprimant ainsi le - // besoin de vérifier si typeof {value} === 'string' dans vos pages - input: z.object({ - author: z.string(), - body: z.string(), - }), - handler: async (input) => { - const updatedComments = await db - .insert(Comment) - .values(input) - .returning(); // Renvoie les commentaires mis à jour - return updatedComments; - }, - }), -}; -``` - - - -Consultez la [référence de l'API `insert()` de Drizzle](https://orm.drizzle.team/docs/insert) pour une vue d'ensemble complète. - - - -### Supprimer - -Vous pouvez également interroger votre base de données à partir d'un point de terminaison d'API. Cet exemple supprime une ligne d'une table `Comment` par le paramètre `id` : - -```ts -// src/pages/api/comments/[id].ts -import type { APIRoute } from "astro"; -import { db, Comment, eq } from 'astro:db'; - -export const DELETE: APIRoute = async (ctx) => { - await db.delete(Comment).where(eq(Comment.id, ctx.params.id )); - return new Response(null, { status: 204 }); -} -``` - - - -Consultez la [référence de l'API `delete()` de Drizzle](https://orm.drizzle.team/docs/delete) pour un aperçu complet. - - - -### Filtrage - -Pour rechercher les résultats d'une table en fonction d'une propriété spécifique, utilisez [les options de Drizzle pour les sélections partielles](https://orm.drizzle.team/docs/select#partial-select). Par exemple, ajoutez [un appel à `.where()`](https://orm.drizzle.team/docs/select#filtering) à votre requête `select()` et passez la comparaison que vous voulez faire. - -L'exemple suivant recherche toutes les lignes d'une table `Comment` qui contiennent l'expression « Astro DB ». Utilisez [l'opérateur `like()`](https://orm.drizzle.team/docs/operators#like) pour vérifier si une phrase est présente dans le `body` : - - -```astro title="src/pages/index.astro" ---- -import { db, Comment, like } from 'astro:db'; - -const comments = await db.select().from(Comment).where( - like(Comment.body, '%Astro DB%') -); ---- -``` - -### Utilitaires de Drizzle - -Tous les utilitaires de Drizzle permettant de construire des requêtes sont exposés à partir du module `astro:db`. Cela inclut : - -- [Les opérateurs de filtre](https://orm.drizzle.team/docs/operators) comme `eq()` et `gt()` -- [Les aides à l'agrégation](https://orm.drizzle.team/docs/select#aggregations-helpers) comme `count()` -- [L'aide `sql`](https://orm.drizzle.team/docs/sql) pour écrire des requêtes SQL brutes - -```ts -import { eq, gt, count, sql } from 'astro:db'; -``` - -### Les relations - -Vous pouvez interroger des données liées provenant de plusieurs tables à l'aide d'une liaison SQL. Pour créer une requête de liaison, ajoutez un opérateur de liaison à votre déclaration `db.select()`. Chaque fonction accepte une table à l'origine de la liaison et une condition pour faire correspondre les lignes entre les deux tables. - -Cet exemple utilise une fonction `innerJoin()` pour faire la liaison entre les auteurs de commmentaires (`Comment`) et leurs informations `Author` sur la base de la colonne `authorId`. Cette fonction retourne un tableau d'objets avec chaque ligne `Author` et `Comment` comme propriétés de premier niveau : - -```astro title="src/pages/index.astro" ---- -import { db, eq, Comment, Author } from 'astro:db'; - -const comments = await db.select() - .from(Comment) - .innerJoin(Author, eq(Comment.authorId, Author.id)); ---- - -

Commentaires

- -{ - comments.map(({ Author, Comment }) => ( -
-

Auteur : {Author.name}

-

{Comment.body}

-
- )) -} -``` - - - -Voir la [référence de liaison Drizzle](https://orm.drizzle.team/docs/joins#join-types) pour tous les opérateurs de liaison disponibles et les options de configuration. - - - -### Transactions par paquets - -Toutes les requêtes de bases de données distantes sont effectuées sous la forme d'une requête réseau. Vous pouvez avoir besoin de regrouper les requêtes en une seule transaction lorsque vous effectuez un grand nombre de requêtes, ou de procéder à des retours en arrière automatiques en cas d'échec d'une requête. - -Cet exemple permet de lancer plusieurs lignes en une seule requête à l'aide de la méthode `db.batch()` : - -```ts -// db/seed.ts -import { db, Author, Comment } from 'astro:db'; - -export default async function () { - let queries; - // Envoyez 100 exemples de commentaires dans votre base de données distante - // avec une seule demande de réseau. - for (let i = 0; i < 100; i++) { - queries.push(db.insert(Comment).values({ body: `Test comment ${i}` })); - } - await db.batch(queries); -} -``` - - - -Voir la documentation [de `db.batch()` sur Drizzle](https://orm.drizzle.team/docs/batch-api) pour plus de détails. - - - -## Envoi des modifications vers votre base de données - -Vous pouvez transférer les modifications apportées pendant le développement vers votre base de données. - -### Pousser les schémas de table - -Votre schéma de table peut changer au fil du temps à mesure que votre projet se développe. Vous pouvez tester en toute sécurité les modifications de configuration localement et les transférer vers votre base de données distante lors du déploiement. - -Vous pouvez transférer les modifications de votre schéma local vers votre base de données distante via la CLI à l'aide de la commande `astro db push --remote` : - - - - ```sh - npm run astro db push --remote - ``` - - - ```sh - pnpm astro db push --remote - ``` - - - ```sh - yarn astro db push --remote - ``` - - - -Cette commande vérifiera que vos modifications locales peuvent être effectuées sans perte de données et, si nécessaire, vous suggérera comment apporter des modifications en toute sécurité à votre schéma afin de résoudre les conflits. - -#### Pousser les changements majeurs de schéma - -:::danger -__Cela détruira votre base de données__. N'exécutez cette commande que si vous n'avez pas besoin de vos données de production. -::: - -Si vous devez modifier le schéma de votre table d'une manière incompatible avec vos données existantes hébergées sur votre base de données distante, vous devrez réinitialiser votre base de données de production. - -Pour pousser une mise à jour du schéma de table qui inclut un changement radical, ajoutez l'option `--force-reset` pour réinitialiser toutes les données de production : - - - - ```sh - npm run astro db push --remote --force-reset - ``` - - - ```sh - pnpm astro db push --remote --force-reset - ``` - - - ```sh - yarn astro db push --remote --force-reset - ``` - - - -### Renommer des tables - -Il est possible de renommer une table après avoir transmis votre schéma à votre base de données distante. - -Si vous **n'avez pas de données de production importantes**, alors vous pouvez [réinitialiser votre base de données](#pousser-les-changements-majeurs-de-schéma) en utilisant l'option `--force-reset`. Celle-ci supprimera toutes les tables de la base de données et en créera de nouvelles afin qu'elles correspondent exactement à votre schéma actuel. - -Pour renommer une table tout en préservant vos données de production, vous devez effectuer une série de modifications non cassantes pour transférer votre schéma local vers votre base de données distante en toute sécurité. - -L'exemple suivant renomme une table `Comment` en `Feedback` : - - - -1. Dans le fichier de configuration de votre base de données, ajoutez la propriété `deprecated: true` à la table que vous voulez renommer : - - ```ts title="db/config.ts" ins={2} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -2. Ajoutez un nouveau schéma de table (correspondant exactement aux propriétés de la table existante) avec le nouveau nom : - - ```ts title="db/config.ts" ins={8-14} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` -3. [Poussez vers votre base de données distante](#pousser-les-schémas-de-table) avec `astro db push --remote`. Cela ajoutera la nouvelle table et marquera l'ancienne comme obsolète. -4. Mettez à jour le code de votre projet local pour utiliser la nouvelle table au lieu de l'ancienne. Il se peut que vous deviez également migrer des données vers la nouvelle table. -5. Une fois que vous êtes sûr que l'ancienne table n'est plus utilisée dans votre projet, vous pouvez supprimer le schéma de votre `config.ts` : - ```ts title="db/config.ts" del={1-7} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` -6. Poussez à nouveau vers votre base de données distante avec `astro db push --remote`. L'ancienne table sera supprimée, ne laissant que la nouvelle table renommée. - - -### Pousser les données d'une table - -Vous devrez peut-être transférer des données vers votre base de données distante pour l'amorçage ou les migrations de données. Vous pouvez créer un fichier `.ts` avec le module `astro:db` pour écrire des requêtes avec sûreté du typage. Ensuite, exécutez le fichier sur votre base de données distante à l'aide de la commande `astro db execute --remote` : - -Les commentaires suivants peuvent être initiés à l'aide de la commande `astro db execute db/seed.ts --remote` : - -```ts -// db/seed.ts -import { Comment } from 'astro:db'; - -export default async function () { - await db.insert(Comment).values([ - { authorId: 1, body: "J'espère que vous aimerez Astro DB !" }, - { authorId: 2, body: 'Profitez !' }, - ]) -} -``` - - - -Consultez la [référence de la CLI](/fr/guides/integrations-guide/db/#référence-de-la-cli-dastro-db) pour une liste complète des commandes. - - - -## Construire des intégrations Astro DB - -Les [intégrations Astro](/fr/reference/integrations-reference/) permettent d'étendre les projets des utilisateurs avec des tables Astro DB supplémentaires et des données de départ. - -Utilisez la méthode `extendDb()` dans le hook `astro:db:setup` pour enregistrer des fichiers de configuration et de données initiales (_seed_) Astro DB supplémentaires. -L'aide `defineDbIntegration()` fournit la prise en charge de TypeScript et l'auto-complétion pour le hook `astro:db:setup`. - -```js {8-13} -// my-integration/index.ts -import { defineDbIntegration } from '@astrojs/db/utils'; - -export default function MyIntegration() { - return defineDbIntegration({ - name: 'my-astro-db-powered-integration', - hooks: { - 'astro:db:setup': ({ extendDb }) => { - extendDb({ - configEntrypoint: '@astronaut/my-package/config', - seedEntrypoint: '@astronaut/my-package/seed', - }); - }, - // Autres hooks d'intégration... - }, - }); -} -``` - -Les fichiers de [configuration](#définir-votre-base-de-données) et de [données initiales](#alimenter-votre-base-de-données-pour-le-développement) des intégrations suivent le même format que leurs équivalents définis par l'utilisateur. - -### Opérations avec sûreté du typage dans les intégrations - -Lorsque vous travaillez sur des intégrations, il se peut que vous ne puissiez pas bénéficier des types de table générés par Astro et exportés depuis `astro:db`. -Pour une sûreté totale du typage, utilisez l'utilitaire `asDrizzleTable()` pour créer un objet de référence de table que vous pouvez utiliser pour les opérations de base de données. - -Par exemple, dans le cas d'une intégration mettant en place la table de base de données `Pets` suivante : - -```js -// my-integration/config.ts -import { defineDb, defineTable, column } from 'astro:db'; - -export const Pets = defineTable({ - columns: { - name: column.text(), - species: column.text(), - }, -}); - -export default defineDb({ tables: { Pets } }); -``` - -Le fichier de données initiales (« seed ») peut importer `Pets` et utiliser `asDrizzleTable()` pour insérer des lignes dans votre table avec vérification du type : - -```js {2,7} /typeSafePets(?! )/ -// my-integration/seed.ts -import { asDrizzleTable } from '@astrojs/db/utils'; -import { db } from 'astro:db'; -import { Pets } from './config'; - -export default async function() { - const typeSafePets = asDrizzleTable('Pets', Pets); - - await db.insert(typeSafePets).values([ - { name: 'Palomita', species: 'cat' }, - { name: 'Pan', species: 'dog' }, - ]); -} -``` - -La valeur retournée par `asDrizzleTable('Pets', Pets)` est équivalente à `import { Pets } from 'astro:db'`, mais elle est disponible même si la génération de type d'Astro ne peut pas fonctionner. -Vous pouvez l'utiliser dans tout code d'intégration qui doit interroger ou insérer dans la base de données. - - - - -### Migrer depuis Astro Studio vers Turso - - - -1. Dans le [tableau de bord de Studio](https://studio.astro.build/), accédez au projet que vous souhaitez migrer. Dans l'onglet Paramètres, utilisez le bouton « Exporter la base de données » pour télécharger une copie de votre base de données. -2. Suivez les instructions officielles pour [installer la CLI de Turso](https://docs.turso.tech/cli/installation) et [inscrivez-vous ou connectez-vous](https://docs.turso.tech/cli/authentication) à votre compte Turso. -3. Créez une nouvelle base de données sur Turso en utilisant la commande `turso db create`. - ```sh - turso db create [database-name] - ``` -4. Récupérez l'URL de la base de données à l'aide de Turso CLI et utilisez-la comme variable d'environnement `ASTRO_DB_REMOTE_URL`. - ```sh - turso db show [database-name] - ``` - ```dotenv - ASTRO_DB_REMOTE_URL=[your-database-url] - ``` -5. Créez un jeton pour accéder à votre base de données et utilisez-le comme variable d'environnement `ASTRO_DB_APP_TOKEN`. - ```sh - turso db tokens create [database-name] - ``` - ```dotenv - ASTRO_DB_APP_TOKEN=[your-app-token] - ``` -6. Transférez votre schéma de base de données et vos métadonnées vers la nouvelle base de données Turso. - ```sh - astro db push --remote - ``` -7. Importez l'exportation de la base de données de l’étape 1 dans votre nouvelle base de données Turso. - ```sh - turso db shell [database-name] < ./path/to/dump.sql - ``` -8. Une fois que vous avez confirmé que votre projet se connecte à la nouvelle base de données, vous pouvez supprimer le projet en toute sécurité dans Astro Studio. - - diff --git a/src/content/docs/fr/guides/integrations-guide/db.mdx b/src/content/docs/fr/guides/integrations-guide/db.mdx deleted file mode 100644 index 6dd1f5e66cf6a..0000000000000 --- a/src/content/docs/fr/guides/integrations-guide/db.mdx +++ /dev/null @@ -1,399 +0,0 @@ ---- -type: integration -title: '@astrojs/db' -description: "Apprenez à utiliser l'intégration @astrojs/db dans votre projet Astro." -sidebar: - label: DB -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -category: other -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; - -:::caution[Déprécié] -L'intégration `@astrojs/db` a été dépréciée dans la v6.5 d'Astro et n'est plus maintenue. - -Si vous utilisiez cette intégration dans votre projet, nous vous recommandons d'utiliser un client de base de données (par exemple, Drizzle, Kysely) directement dans votre projet Astro. -::: - -Astro DB est une base de données SQL entièrement gérée, conçue pour l'écosystème Astro : développez localement dans Astro et déployer vers n'importe quelle [base de données compatible libSQL](/fr/guides/astro-db/). - -Avec Astro DB, vous disposez d'un outil puissant, local et sûr pour interroger et modéliser le contenu comme une base de données relationnelle. - -Consultez le [guide Astro DB](/fr/guides/astro-db/) pour une utilisation complète et des exemples. - -## Installation - -Astro inclut une commande `astro add` pour automatiser l'installation des intégrations officielles. Si vous préférez, vous pouvez [installer les intégrations manuellement](/fr/guides/integrations-guide/mdx/#installation-manuelle) à la place. - -Exécutez l'une des commandes suivantes dans une nouvelle fenêtre de terminal. - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -#### Installation manuelle - -Si vous préférez configurer les choses vous-même à partir de zéro, ignorez `astro add` et suivez ces instructions pour installer Astro DB vous-même. - -##### 1. Installer l'intégration à partir de npm via un gestionnaire de paquets - - - - ```shell - npm install @astrojs/db - ``` - - - ```shell - pnpm add @astrojs/db - ``` - - - ```shell - yarn add @astrojs/db - ``` - - - -##### 2. Ajouter l'intégration à `astro.config.mjs` - - ```js title="astro.config.mjs" ins={2,6} - import { defineConfig } from 'astro/config'; - import db from '@astrojs/db'; - - export default defineConfig({ - integrations: [ - db() - ] - }); - ``` - -##### 3. Configurer votre base de données - -Créez un fichier `db/config.ts` à la racine de votre projet. Il s'agit d'un fichier spécial qu'Astro chargera automatiquement et utilisera pour configurer les tables de votre base de données. - -```ts -// db/config.ts -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: {}, -}) -``` - -## Configuration - -### `mode` - -

- -**Type :** `'node' | 'web'`
-**Par défaut :** `'node'`
- -

- -Configure le pilote à utiliser pour se connecter à votre base de données en production. - -Par défaut, Astro DB utilise un pilote libSQL reposant sur Node.js pour les déploiements en production. Le mode `node` du pilote est suffisant pour la plupart des sites web hébergés ou auto-hébergés par Astro avec des environnements d'exécution Node.js. Cela vous permet de vous connecter à votre base de données via plusieurs protocoles, notamment `memory:`, `file:`, `ws:`, `wss:`, `libsql`, `http` et `https`, ainsi que d'accéder à des fonctionnalités plus avancées telles que les [répliques intégrées](/fr/guides/astro-db/#syncurl). - -Lors d'un déploiement dans un environnement serverless dans un environnement d'exécution autre que Node.js, comme Cloudflare Workers ou Deno, un pilote libSQL est disponible. Lors du déploiement à l'aide du mode `web`, vous pourrez établir des connexions web via `libsql`, `http` ou `https`. - -Pour utiliser le mode web du pilote libSQL pour les environnements n'utilisant pas Node.js, définissez la propriété `mode` dans la configuration de votre adaptateur : - -```ts title="astro.config.mjs" ins={7} -import { defineConfig } from 'astro/config'; -import db from '@astrojs/db'; - -export default defineConfig({ - integrations: [ - db({ - mode: 'web' - }) - ] -}); -``` - -## Référence de configuration des tables - -### `columns` - -

- -**Type :** `ColumnsConfig` -

- -Les colonnes de la table sont configurées à l'aide de l'objet `columns` : - -```ts -import { defineTable, column, NOW } from 'astro:db'; - -const Comment = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - author: column.text(), - content: column.text({ optional: true }), - published: column.date({ default: NOW }), - }, -}); -``` - -Les colonnes sont configurées en utilisant l'utilitaire `column`. `column` prend en charge les types suivants : - -- **`column.text(...)`** - Stocke du contenu textuel simple ou enrichi -- **`column.number(...)`** - Stocke des valeurs entières et des valeurs à virgule flottante -- **`column.boolean(...)`** - Stocke des valeurs vraies / fausses -- **`column.date(...)`** - Stocke les objets `Date`, analysés comme des chaînes ISO pour le stockage des données. -- **`column.json(...)`** - Stocke des blobs JSON arbitraires, analysés en tant que JSON stringifié pour le stockage des données - -Quelques valeurs de configuration sont communes à toutes les colonnes : - -- `primaryKey` - Définit une colonne `number` ou `text` comme identifiant unique. -- `optional` - Astro DB utilise `NOT NULL` pour toutes les colonnes par défaut. Définissez `optional` sur `true` pour autoriser les valeurs nulles. -- `default` - Définit la valeur par défaut pour les entrées nouvellement insérées. Ceci accepte soit une valeur statique, soit une chaîne de `sql` pour les valeurs générées comme les timestamps. -- `unique` - Marque une colonne comme unique. Cela permet d'éviter les valeurs dupliquées dans les entrées de la table. -- `references` - Fait référence à une table liée par une colonne. Cela établit une contrainte de clé étrangère, ce qui signifie que chaque valeur de colonne doit avoir une valeur correspondante dans la table référencée. - -Une colonne `texte` peut éventuellement définir une liste de chaînes de caractères litérales qui sera utilisée en tant qu'énumération pour la génération des types. Cependant, **aucune validation ne sera effectuée au moment de l'exécution**. La suppression, l'ajout et la modification de valeurs doivent être gérés dans le code de votre projet. - -```ts title="db/config.ts" {8} -import { defineTable, column } from 'astro:db'; - -// Définition de la table -const UserTable = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - rank: column.text({ enum: ['user', 'mod', 'admin'] }), - }, -}); - -// Définition de type résultant -type UserTableInferInsert = { - id?: string; - name: string; - rank: "user" | "mod" | "admin"; -} -``` - -### `indexes` - -

- -**Type :** `{ on: string | string[]; unique?: boolean | undefined; name?: string | undefined; }[]` -

- -Les index de table sont utilisés pour améliorer la vitesse de recherche sur une colonne donnée ou une combinaison de colonnes. La propriété `indexes` accepte un tableau d'objets de configuration spécifiant les colonnes à indexer : - -```ts title="db/config.ts" {9-11} -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - authorId: column.number(), - published: column.date(), - body: column.text(), - }, - indexes: [ - { on: ["authorId", "published"], unique: true }, - ] -}); -``` - -Cela générera un index unique sur les colonnes `authorId` et `published` avec le nom `Comment_authorId_published_idx`. - -Les options de configuration suivantes sont disponibles pour chaque index : - -- `on` - Une seule colonne ou un tableau de noms de colonnes à indexer. -- `unique` - Définir sur `true` pour imposer des valeurs uniques à travers les colonnes indexées. -- `name` (Optionnel) - Un nom personnalisé pour l'index unique. Il remplacera le nom généré par Astro basé sur les noms de la table et de la colonne indexée (par exemple `Comment_authorId_published_idx`). Les noms personnalisés sont globaux, il faut donc s'assurer que les noms d'index n'entrent pas en conflit entre les tables. - -### `foreignKeys` - -

- -**Type :** `{ columns: string | string[]; references: () => Column | Column[]; }[]` -

- -:::tip - -`foreignKeys` est une API avancée pour relier plusieurs colonnes d'une table. Si vous n'avez besoin de référencer qu'une seule colonne, essayez d'utiliser [la propriété `references` de la colonne](#columns). - -::: - -Les clés étrangères sont utilisées pour établir une relation entre deux tables. La propriété `foreignKeys` accepte un tableau d'objets de configuration qui peuvent relier une ou plusieurs colonnes entre les tables : - -```ts title="db/config.ts" {12-20} -import { defineTable, column } from 'astro:db'; - -const Author = defineTable({ - columns: { - firstName: column.text(), - lastName: column.text(), - }, -}); - -const Comment = defineTable({ - columns: { - authorFirstName: column.text(), - authorLastName: column.text(), - body: column.text(), - }, - foreignKeys: [ - { - columns: ["authorFirstName", "authorLastName"], - references: () => [Author.columns.firstName, Author.columns.lastName], - }, - ], -}); -``` - -Chaque objet de configuration de clé étrangère accepte les propriétés suivantes : - -- `columns` - Un tableau de noms de colonnes à associer à la table référencée. -- `references` - Une fonction qui renvoie un tableau de colonnes de la table référencée. - -## Référence de la CLI d'Astro DB - -Astro DB inclut un ensemble de commandes CLI pour interagir pour interagir avec votre base de données locale et compatible libSQL. - -Ces commandes sont appelées automatiquement lors de l'utilisation d'une action CI GitHub, et peuvent être appelées manuellement en utilisant la CLI `astro db`. - -### `astro db push` - -**Options :** - -- `--db-app-token ` Fournir directement le jeton de l'application de base de données distante au lieu de `ASTRO_DB_APP_TOKEN`. -- `--dry-run` Imprimer les instructions SQL générées sans les appliquer. -- `--force-reset` Réinitialiser toutes les données de production si une modification du schéma avec rupture de compatibilité est nécessaire. -- `--remote` Transférer vers votre base de données distante plutôt que vers le fichier de base de données local. Nécessite que la variable d'environnement `ASTRO_DB_REMOTE_URL` soit définie, et soit que `ASTRO_DB_APP_TOKEN` soit défini dans l'environnement, soit qu'une valeur soit transmise avec l'argument de ligne de commande `--db-app-token`. - -Transférez en toute sécurité les modifications apportées à la configuration de la base de données dans la base de données de votre projet. Cela vérifiera tout risque de perte de données et vous guidera sur les étapes de migration recommandées. Utilisez `--remote` pour appliquer les modifications à votre base de données distante. Si une modification de schéma avec rupture de compatibilité est nécessaire, utilisez `--force-reset` pour réinitialiser toutes les données de production. - -### `astro db verify` - -**Options :** - -- `--db-app-token ` Fournir directement le jeton de l'application de base de données distante au lieu de `ASTRO_DB_APP_TOKEN`. -- `--json` Imprimer un résultat JSON lisible par machine à partir de `verify`. -- `--remote` Comparer avec votre base de données distante plutôt qu'avec le fichier de base de données local. Nécessite que la variable d'environnement `ASTRO_DB_REMOTE_URL` soit définie, et soit que `ASTRO_DB_APP_TOKEN` soit défini dans l'environnement, soit qu'une valeur soit transmise avec l'argument de ligne de commande `--db-app-token`. - -Compare votre schéma local à la base de données distante afin de vérifier les éventuelles différences entre les configurations de vos bases de données locale et distante. Cette opération est exécutée automatiquement par `astro db push`. - -`verify` comparera votre fichier `db/config.ts` local avec la base de données distante et vous avertira si des modifications sont détectées. Elle renverra un code d'erreur si des modifications sont nécessaires ou non sécurisées, ce qui la rend utile pour l'intégration continue (CI). - -### `astro db execute ` - -**Options :** - -- `--db-app-token ` Fournir directement le jeton de l'application de base de données distante au lieu de `ASTRO_DB_APP_TOKEN`. -- `--remote` Exécuter cette commande sur votre base de données compatible libSQL. Omettre cette option pour exécuter la commande sur votre fichier de base de données local. Nécessite que la variable d'environnement `ASTRO_DB_REMOTE_URL` soit définie, et soit que `ASTRO_DB_APP_TOKEN` soit défini dans l'environnement, soit qu'une valeur soit transmise avec l'argument de ligne de commande `--db-app-token`. - -Exécute un fichier `.ts` ou `.js` pour lire ou écrire dans votre base de données. Cette commande accepte un chemin de fichier comme argument, et prend en charge l'utilisation du module `astro:db` pour écrire des requêtes sûres. Utilisez l'option `--remote` pour exécuter sur votre base de données compatible libSQL, ou ignorez l'option pour lancer l'exécution sur votre fichier de base de données local. Consultez [alimenter les données de développement](/fr/guides/astro-db/#alimenter-votre-base-de-données-pour-le-développement) pour un exemple de fichier. - -### `astro db shell --query ` - -**Options :** - -- `--query` Requête SQL brute à exécuter. -- `--remote` Exécuter cette commande sur votre base de données compatible libSQL. Omettre cette option pour exécuter la commande sur votre fichier de base de données local. Nécessite que la variable d'environnement `ASTRO_DB_REMOTE_URL` soit définie, et soit que `ASTRO_DB_APP_TOKEN` soit défini dans l'environnement, soit qu'une valeur soit transmise avec l'argument de ligne de commande `--db-app-token`. - -Exécute une requête SQL brute sur votre base de données. - -L'exemple suivant sélectionne toutes les lignes d'une table `Comment` dans une base de données distante : - -```sh -npx astro db shell --query "SELECT * FROM Comment;" --remote -``` - -## Référence des utilitaires d'Astro DB - -Les utilitaires suivants sont importés depuis le module `astro:db` : - -```ts -import { - isDbError, - getDbError -} from "astro:db"; -``` - -### `isDbError()` - -

- -**Type :** `(err: unknown) => boolean`
- -

- -Vérifie si une erreur est une exception de la base de données libSQL. Il peut s'agir d'une erreur de contrainte de clé étrangère lors de l'utilisation de références, ou de champs manquants lors de l'insertion de données. Vous pouvez combiner `isDbError()` avec un bloc try/catch pour gérer les erreurs de base de données dans votre application : - -```ts title="src/pages/api/comment/[id].ts" "idDbError" -import { db, Comment, isDbError } from 'astro:db'; -import type { APIRoute } from 'astro'; - -export const POST: APIRoute = (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - if (isDbError(e)) { - return new Response(`Impossible d'insérer un commentaire avec l'id ${id}\n\n${e.message}`, { status: 400 }); - } - return new Response("Une erreur inattendue s'est produite", { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; -``` - -### `getDbError()` - -

- -**Type :** `(err: unknown) => LibsqlError | undefined`
- -

- -Parcourt la chaîne de causes d'une erreur pour trouver l'exception sous-jacente de la base de données libSQL. Elle renvoie `LibsqlError` ou `undefined` si l'erreur ne provient pas de LibSQL. Cela est utile lorsqu'une autre erreur (par exemple, `DrizzleQueryError`) peut envelopper l'erreur de base de données. - -L'exemple suivant extrait l'erreur de base de données d'une exception interceptée et renvoie le code d'erreur et le message dans la réponse : - -```ts title="src/pages/api/comment/[id].ts" "getDbError" -import { getDbError } from 'astro:db'; - -export const POST: APIRoute = (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - const dbError = getDbError(e); - if (dbError) { - return new Response(`Erreur de base de données : ${dbError.code}\n\n${dbError.message}`, { status: 400 }); - } - return new Response("Une erreur inattendue s'est produite", { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; -``` diff --git a/src/content/docs/fr/reference/cli-reference.mdx b/src/content/docs/fr/reference/cli-reference.mdx index b61e2d66d5ddf..c6f034a6227a0 100644 --- a/src/content/docs/fr/reference/cli-reference.mdx +++ b/src/content/docs/fr/reference/cli-reference.mdx @@ -266,7 +266,6 @@ Exécuter `astro dev`, `astro build` ou `astro check` exécutera également la c Génère des types TypeScript pour tous les modules Astro. Cela configure un [fichier `.astro/types.d.ts`](/fr/guides/typescript/#configuration) pour l'inférence de type et définit des modules pour les fonctionnalités qui s'appuient sur des types générés : - Le module `astro:content` pour l'[API des collections de contenus](/fr/guides/content-collections/). -- Le module `astro:db` pour [Astro DB](/fr/guides/astro-db/). - Le module `astro:env` pour [Astro Env](/fr/guides/environment-variables/). - Le module `astro:actions` pour [Astro Actions](/fr/guides/actions/) diff --git a/src/content/docs/fr/reference/experimental-flags/advanced-routing.mdx b/src/content/docs/fr/reference/experimental-flags/advanced-routing.mdx deleted file mode 100644 index c5d7ed3b4b04f..0000000000000 --- a/src/content/docs/fr/reference/experimental-flags/advanced-routing.mdx +++ /dev/null @@ -1,529 +0,0 @@ ---- -title: Routage avancé expérimental -sidebar: - label: Routage avancé -i18nReady: false ---- - -import Since from '~/components/Since.astro' - -

- -**Type :** `boolean`
-**Par défaut :** `false`
- -

- -Active `src/app.ts` comme point d'entrée personnalisé du pipeline de requêtes, vous donnant un contrôle total sur la manière dont Astro gère les requêtes entrantes. - -Par défaut, Astro gère chaque requête avec un pipeline intégré qui exécute la normalisation des barres obliques finales, les redirections, les sessions, les actions, les middleware utilisateur, le rendu des pages, l'internationalisation (i18n) et la mise en cache dans un ordre fixe. Le routage avancé vous permet de remplacer ce pipeline par le vôtre, en composant les fonctions de gestion intégrées d'Astro avec une logique personnalisée dans l'ordre de votre choix. - -```js title="astro.config.mjs" -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - experimental: { - advancedRouting: true, - }, -}); -``` - -## Création de `src/app.ts` - -Lorsque `advancedRouting` est activé, créez un fichier `src/app.ts` (ou `.js`, `.mjs`, `.mts`) qui exporte par défaut un objet doté d'une méthode `fetch`. La méthode `fetch` reçoit un objet [Request](https://developer.mozilla.org/fr/docs/Web/API/Request) standard et doit renvoyer un objet [Response](https://developer.mozilla.org/fr/docs/Web/API/Response). - -Si aucun fichier `src/app.ts` n'existe (ou si `advancedRouting` n'est pas activée), Astro utilise son pipeline intégré, qui exécute automatiquement toutes les fonctionnalités. - -Vous pouvez éventuellement importer le type `Fetchable` depuis `astro` pour vérifier le type de votre point d'entrée : - -```ts title="src/app.ts" -import type { Fetchable } from 'astro'; - -export default { - async fetch(request: Request): Promise { - // ... - }, -} satisfies Fetchable; -``` - -### Personnalisation du fichier de point d'entrée - -Par défaut, Astro recherche `src/app.ts` comme point d'entrée du routage avancé. Transmettez un objet à `advancedRouting` avec une option `fetchFile` pour utiliser un fichier différent : - -```js title="astro.config.mjs" -export default defineConfig({ - experimental: { - advancedRouting: { - fetchFile: 'fetch.ts', - }, - }, -}); -``` - -Avec cette configuration, Astro recherchera `src/fetch.ts` au lieu de `src/app.ts`. - -Définissez `fetchFile` sur `null` pour désactiver complètement le point d'entrée. Cela est utile si vous avez déjà un fichier `src/app.ts` utilisé à d'autres fins : - -```js title="astro.config.mjs" -export default defineConfig({ - experimental: { - advancedRouting: { - fetchFile: null, - }, - }, -}); -``` - -### Utilisation de `astro()` - -La manière la plus simple de commencer est d'utiliser le gestionnaire [`astro()`](#astro), qui exécute l'intégralité du pipeline intégré d'Astro (sessions, cache, redirections, barres obliques finales, actions, middleware, pages et i18n) dans l'ordre par défaut. Cela vous permet d'ajouter une logique personnalisée avant ou après Astro sans modifier le fonctionnement du pipeline interne : - -```ts title="src/app.ts" -import { FetchState, astro } from 'astro/fetch'; - -export default { - async fetch(request: Request): Promise { - const state = new FetchState(request); - - // Prétraitement personnalisé, exécuté avant tout gestionnaire Astro - const url = new URL(request.url); - if (url.pathname.startsWith('/tableau-de-bord')) { - const cookie = request.headers.get('cookie') ?? ''; - if (!cookie.includes('session=')) { - return new Response(null, { - status: 302, - headers: { Location: '/connexion' }, - }); - } - } - - const response = await astro(state); - - // Post-traitement personnalisé, exécuté après le rendu Astro - response.headers.set('X-Powered-By', 'Astro'); - return response; - }, -}; -``` - -Pour de nombreux cas d'utilisation, tels que l'ajout de gardes d'authentification, la journalisation des requêtes et les en-têtes personnalisés, `astro()` est tout ce dont vous avez besoin. - -### Composition des gestionnaires individuels - -Lorsque vous avez besoin de plus de contrôle sur l'ordre du pipeline, ou si vous souhaitez omettre certaines fonctionnalités, vous pouvez composer des fonctions de gestion individuelles à partir de `astro/fetch` : - -```ts title="src/app.ts" -import { - FetchState, - sessions, - actions, - middleware, - pages, - i18n, -} from 'astro/fetch'; - -export default { - async fetch(request: Request): Promise { - const state = new FetchState(request); - await sessions(state); - try { - const actionResponse = await actions(state); - if (actionResponse) return actionResponse; - - const response = await middleware(state, (s) => pages(s)); - return i18n(state, response); - } finally { - await state.finalizeAll(); - } - }, -}; -``` - -Chaque fonction opère sur un [objet `FetchState`](#fetchstate) qui suit les données par requête comme la route correspondante, les cookies et la session. Vous pouvez les appeler dans n'importe quel ordre et les mélanger avec votre propre logique. - -## Ajout de logique personnalisée - -Le principal avantage du routage avancé est la possibilité d'insérer une logique personnalisée n'importe où dans le pipeline de requêtes. Vous pouvez exécuter du code avant qu'Astro ne touche à la requête, entre les étapes du pipeline ou après la production de la réponse. - -Le [gestionnaire `astro()`](#astro) est le moyen le plus simple d'ajouter un prétraitement ou un post-traitement autour de l'ensemble du pipeline. Lorsque vous devez insérer une logique *entre* des étapes spécifiques, comme exécuter du code personnalisé après les actions mais avant le rendu de la page, composez plutôt les gestionnaires individuels : - -```ts title="src/app.ts" -import { - FetchState, - actions, - middleware, - pages, - i18n, -} from 'astro/fetch'; - -export default { - async fetch(request: Request): Promise { - const state = new FetchState(request); - - const actionResponse = await actions(state); - if (actionResponse) return actionResponse; - - // Logique personnalisée entre les actions et le rendu de la page - console.log(`Rendu de ${new URL(request.url).pathname}`); - - const response = await middleware(state, (s) => pages(s)); - return i18n(state, response); - }, -}; -``` - -## Définition du type des fournisseurs personnalisés avec `App.Providers` - -Lorsque vous enregistrez des fournisseurs de contexte personnalisés avec [`state.provide()`](#stateprovide), vous pouvez déclarer leurs types en utilisant l'interface `App.Providers` afin que `Astro` et `ctx` soient entièrement typés dans vos composants et middleware : - -```ts title="src/env.d.ts" -declare namespace App { - interface Providers { - oauth: import('./lib/oauth').OAuthSession; - } -} -``` - -Après avoir déclaré un fournisseur, `ctx.oauth` (et `Astro.oauth` dans les fichiers `.astro`) sera typé automatiquement. - -## Référence des gestionnaires d'`astro/fetch` - -Toutes les fonctions de gestion sont importées depuis `astro/fetch` et opèrent sur un objet `FetchState`. - -### `FetchState` - -L'objet d'état par requête. Créez-en un au début de votre méthode `fetch` : - -```ts -import { FetchState } from 'astro/fetch'; - -const state = new FetchState(request); -``` - -`FetchState` suit la route correspondante, les cookies, les fournisseurs de session et d'autres données par requête. Toutes les fonctions de gestion nécessitent cet objet comme premier argument. - -#### Propriétés - -##### `state.request` - -**Type :** `Request` - -L'objet [Request](https://developer.mozilla.org/fr/docs/Web/API/Request) entrant. - -##### `state.url` - -**Type :** `URL` - -Une [URL](https://developer.mozilla.org/fr/docs/Web/API/URL) normalisée dérivée de la requête. - -##### `state.pathname` - -**Type :** `string` - -Le chemin de la requête, décodé et sans le préfixe de base (par exemple `/a-propos` ou `/blog/mon-article`). - -##### `state.routeData` - -**Type :** `RouteData | undefined` - -La route correspondante pour cette requête, le cas échéant. Elle est résolue automatiquement lors de la création de `FetchState`. - -##### `state.cookies` - -**Type :** `AstroCookies` - -Une instance [`AstroCookies`](/fr/reference/api-reference/#cookies) pour lire et définir des cookies sur cette requête. - -##### `state.locals` - -**Type :** `App.Locals` - -Un objet limité à la requête pour stocker des données personnalisées. Il s'agit du même objet `locals` disponible dans les [middlewares](/fr/guides/middleware/) et les [routes d'API](/fr/guides/endpoints/#points-de-terminaison-du-serveur-routes-api). - -##### `state.params` - -**Type :** `Params | undefined` - -Les paramètres de la route dérivés de la route correspondante et du chemin (par exemple `{ slug: 'mon-article' }` pour une route `[slug].astro`). - -##### `state.status` - -

- -**Type :** `number`
-**Par défaut :** `200` -

- -Le code de statut HTTP pour la réponse. Vous pouvez le définir avant le rendu pour contrôler le statut de la réponse (par exemple `state.status = 404`). - -##### `state.response` - -

- -**Type :** `Response | undefined`
-**Par défaut :** `undefined` -

- -La réponse (`Response`) produite par les gestionnaires après le rendu. Elle est définie automatiquement par [`pages()`](#pages) et [`middleware()`](#middleware), ce qui vous permet d'inspecter ou d'utiliser la réponse plus tard dans le pipeline : - -```ts -const response = await middleware(state, (s) => pages(s)); -// state.response est maintenant le même objet que response -``` - -#### Méthodes - -##### `state.rewrite()` - -

- -**Type :** (payload: RewritePayload) => Promise\ -

- -Déclenche une [réécriture](/fr/guides/routing/#réécritures) vers une autre route. Le `payload` peut être un chemin sous forme de chaîne de caractères (`'/autre-page'`), une URL ou un objet `Request` : - -```ts -const response = await state.rewrite('/autre-page'); -``` - -##### `state.provide()` - -

- -**Type :** `(key: string, provider: ContextProvider) => void` -

- -Enregistre un fournisseur de contexte sous le nom de propriété donné. La fonction `create()` du fournisseur est appelée de manière paresseuse lors du premier [`state.resolve()`](#stateresolve), et son rappel optionnel `finalize()` s'exécute lors de [`state.finalizeAll()`](#statefinalizeall) : - -```ts -state.provide('monService', { - create: () => new MonService(), - finalize: (service) => service.close(), -}); -``` - -##### `state.resolve()` - -

- -**Type :** `(key: string) => T | undefined` -

- -Renvoie la valeur d'un fournisseur précédemment enregistré, en appelant sa fonction `create` lors du premier accès. Renvoie `undefined` si aucun fournisseur n'a été enregistré pour le nom de propriété : - -```ts -const service = state.resolve('monService'); -``` - -##### `state.finalizeAll()` - -

- -**Type :** `() => Promise | void` -

- -Exécute tous les rappels `finalize` des fournisseurs enregistrés. Appelez ceci après que la réponse a été produite, généralement dans un bloc `finally`, pour persister les données de session et nettoyer les ressources : - -```ts -await sessions(state); -try { - // ...pipeline de rendu... - return response; -} finally { - await state.finalizeAll(); -} -``` - -### `astro()` - -

- -**Type :** (state: FetchState) => Promise\ -

- -Le gestionnaire tout-en-un qui exécute l'ensemble du pipeline d'Astro (sessions, cache, redirections, barre oblique finale, actions, middleware, pages et i18n) dans l'ordre par défaut. Utilisez ceci lorsque vous souhaitez ajouter une logique avant ou après Astro sans modifier l'ordre interne du pipeline : - -```ts title="src/app.ts" -import { FetchState, astro } from 'astro/fetch'; - -export default { - async fetch(request: Request): Promise { - const state = new FetchState(request); - // Prétraitement personnalisé ici... - const response = await astro(state); - // Post-traitement personnalisé ici... - return response; - }, -}; -``` - -### `pages()` - -

- -**Type :** (state: FetchState) => Promise\ -

- -Transmet la requête à la route Astro correspondante (page, point de terminaison ou solution de repli). Il s'agit du gestionnaire de rendu principal, et la plupart des pipelines personnalisés l'incluent. - -### `middleware()` - -

- -**Type :** (state: FetchState, next: (state: FetchState) => Promise\) => Promise\ -

- -Exécute la chaîne de middleware d'Astro (depuis `src/middleware.ts`). Le rappel `next` est appelé au bas de la chaîne pour produire la réponse, généralement en appelant `pages()` : - -```ts -const response = await middleware(state, (s) => pages(s)); -``` - -### `actions()` - -

- -**Type :** (state: FetchState) => Promise\ | undefined -

- -Gère les [actions d'Astro](/fr/guides/actions/) (RPC et soumissions de formulaires). Renvoie une `Response` pour les actions RPC, ou `undefined` pour les actions de formulaire et les requêtes ne constituant pas une action. Vérifiez la valeur de retour pour décider s'il faut poursuivre le rendu : - -```ts -const actionResponse = await actions(state); -if (actionResponse) return actionResponse; -// sinon, continuez le rendu de la page... -``` - -### `sessions()` - -

- -**Type :** (state: FetchState) => Promise\ | void -

- -Enregistre le fournisseur de [sessions](/fr/guides/sessions/). Les sessions sont créées de manière paresseuse lorsque votre code accède à `ctx.session` et sont persistées lorsque `state.finalizeAll()` est appelé. Appelez ceci tôt dans le pipeline, et appelez `finalizeAll()` dans un bloc `finally` : - -```ts -await sessions(state); -try { - // ...pipeline de rendu... -} finally { - await state.finalizeAll(); -} -``` - -### `i18n()` - -

- -**Type :** (state: FetchState, response: Response) => Promise\ -

- -Post-traite une réponse en fonction de votre [configuration i18n](/fr/guides/internationalization/). Gère les redirections de paramètres régionaux, les erreurs 404 pour les paramètres régionaux invalides et le routage de repli. Appelez cette fonction après le rendu : - -```ts -const response = await middleware(state, (s) => pages(s)); -return i18n(state, response); -``` - -### `redirects()` - -

- -**Type :** (state: FetchState) => Promise\ | undefined -

- -Gère les routes de redirection définies dans votre [configuration d'Astro](/fr/reference/configuration-reference/#redirects). Renvoie une réponse de redirection (`Response`) si la route correspondante est une redirection, ou `undefined` si l'appelant doit continuer le traitement. - -### `cache()` - -

- -**Type :** (state: FetchState, next: () => Promise\) => Promise\ -

- -Enveloppe un rappel de rendu avec la logique du fournisseur de [cache](/fr/reference/experimental-flags/route-caching/). Gère la mise en cache à l'exécution, les fournisseurs basés sur le CDN et le cas sans cache. - -### `trailingSlash()` - -

- -**Type :** (state: FetchState) => Response | undefined -

- -Vérifie si le chemin d'accès à la requête nécessite une normalisation des [barres obliques finales](/fr/reference/configuration-reference/#trailingslash) et renvoie une réponse de redirection (`Response`) le cas échéant. Renvoie `undefined` si aucune redirection n'est nécessaire. - -## Utilisation avec Hono - -Astro fournit également des enveloppes compatibles avec Hono pour toutes les fonctions de gestion via `astro/hono`. Si vous préférez utiliser [Hono](https://hono.dev/) comme framework de routage, vous pouvez exporter une application Hono depuis `src/app.ts` : - -```ts title="src/app.ts" -import { Hono } from 'hono'; -import { logger } from 'hono/logger'; -import { actions, middleware, pages, i18n } from 'astro/hono'; - -const app = new Hono(); - -// Middleware Hono -app.use(logger()); - -// Gestionnaires d'Astro (en tant que middleware Hono) -app.use(actions()); -app.use(middleware()); -app.use(pages()); -app.use(i18n()); - -export default app; -``` - -Le module `astro/hono` exporte les mêmes noms de gestionnaires que `astro/fetch` (`astro`, `pages`, `middleware`, `actions`, `sessions`, `redirects`, `cache`, `i18n`, `trailingSlash`), mais chacun renvoie une fonction middleware Hono. Cela vous permet de mélanger les gestionnaires d'Astro avec n'importe quel middleware Hono de l'écosystème. - -## Adaptateur Cloudflare - -L'adaptateur [`@astrojs/cloudflare`](/fr/guides/integrations-guide/cloudflare/) fournit des gestionnaires complémentaires qui appliquent une configuration spécifique à Cloudflare à votre pipeline de routage avancé. Ces gestionnaires configurent l'injection de liaison KV pour les sessions, la diffusion de ressources statiques via la liaison `ASSETS`, `Astro.locals.cfContext`, l'adresse du client à partir de l'en-tête `cf-connecting-ip`, `waitUntil` et la récupération des pages d'erreur pré-rendues. - -Vous pouvez utiliser les API `astro/fetch` et `astro/hono` depuis `src/app.ts` sur Cloudflare sans ces gestionnaires. Le point d'entrée par défaut de l'adaptateur prend en charge la configuration spécifique à Cloudflare pour vous. Ces gestionnaires complémentaires sont utiles lorsque vous avez déjà un [point d'entrée de worker personnalisé](https://developers.cloudflare.com/workers/wrangler/configuration/#inheritable-keys) (`src/worker.ts`), par exemple, pour exporter un objet durable (Durable Object), et que vous souhaitez utiliser les API de routage avancé directement depuis ce fichier. - -Lorsque vous utilisez ces gestionnaires dans votre point d'entrée de worker, ils remplacent la fonctionnalité du gestionnaire par défaut de l'adaptateur, vous ne devez donc pas utiliser les deux en même temps. Placez le gestionnaire Cloudflare avant les autres gestionnaires d'Astro afin que les liaisons et les locaux soient disponibles pour le reste du pipeline. - -### `@astrojs/cloudflare/fetch` - -

- -Pour une utilisation avec `astro/fetch`. La fonction `cf()` reçoit un objet `FetchState`, l'`env` de Cloudflare et le contexte d'exécution (`ExecutionContext`). Elle renvoie une réponse (`Response`) pour les accès aux ressources statiques, ou `undefined` lorsque la requête doit se poursuivre avec le rendu d'Astro : - -```ts title="src/worker.ts" -import { astro, FetchState } from 'astro/fetch'; -import { cf } from '@astrojs/cloudflare/fetch'; - -export default { - async fetch(request: Request, env: Env, ctx: ExecutionContext) { - const state = new FetchState(request); - const asset = await cf(state, env, ctx); - if (asset) return asset; - return astro(state); - }, -}; -``` - -### `@astrojs/cloudflare/hono` - -

- -Pour une utilisation avec `astro/hono`. La fonction `cf()` renvoie un middleware Hono qui lit automatiquement `env` et `executionCtx` depuis le contexte d'Hono : - -```ts title="src/worker.ts" -import { Hono } from 'hono'; -import { actions, middleware, pages, i18n } from 'astro/hono'; -import { cf } from '@astrojs/cloudflare/hono'; - -const app = new Hono<{ Bindings: Env }>(); - -app.use(cf()); -app.use(actions()); -app.use(middleware()); -app.use(pages()); -app.use(i18n()); - -export default app; -``` diff --git a/src/content/docs/fr/reference/experimental-flags/logger.mdx b/src/content/docs/fr/reference/experimental-flags/logger.mdx deleted file mode 100644 index fbc9ffe02be6d..0000000000000 --- a/src/content/docs/fr/reference/experimental-flags/logger.mdx +++ /dev/null @@ -1,328 +0,0 @@ ---- -title: Journaliseur expérimental -sidebar: - label: Journaliseur -i18nReady: true ---- - -import Since from '~/components/Since.astro'; - -

- -**Type :** `object`
-**Par défaut :** `undefined`
- -

- -Active un journaliseur expérimental et personnalisable qui peut être contrôlé par l'utilisateur. - -Lorsque fourni, l'utilisateur a un contrôle total sur les journaux émis par Astro. De plus, la fonctionnalité est livrée avec quelques journaliseurs intégrés qui peuvent être utilisés via les nouveaux gestionnaires de journalisation (`logHandlers`). - -L'exemple suivant active le journaliseur JSON intégré, avec une sortie formatée : - -```js title="astro.config.mjs" {5} ins="logHandlers" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.json({ pretty: true }) - } -}); -``` - -Vous pouvez également activer la journalisation JSON pour les commandes `dev`, `build` et `sync` à l'aide de l'option `--experimentalJson` : - -```shell -astro dev --experimentalJson -astro sync --experimentalJson -astro build --experimentalJson -``` - - -## Journaliseurs intégrés - -Cette fonctionnalité inclut trois enregistreurs intégrés. - -### `logHandlers.json` - -Un journaliseur qui produit des messages au format JSON. Un journal ressemblerait à ceci : -```json -{ "message": "", "label": "routeur", "level": "info", "time": "" } -``` - -#### Options du journaliseur JSON - -

-**Type :** `{ pretty: boolean; level: AstroLoggerLevel; }`
-**Par défaut :** `{ pretty: false, level: 'info' }` - -

- -Le journaliseur `json` accepte les options suivantes : - -- `pretty` : lorsque la valeur est `true`, le journal JSON est affiché sur plusieurs lignes. La valeur par défaut est `false`. -- `level` : le [niveau](#niveau-de-journalisation) des journaux qui doivent être affichés. - -```js title="astro.config.mjs" {5} ins="json" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.json({ pretty: true }) - } -}); -``` - -### `logHandlers.console` - -Un journaliseur qui affiche les messages en utilisant la `console` comme destination. En fonction du niveau du message, il utilise différents canaux : - -- Les messages d'erreur (`error`) sont affichés en utilisant `console.error()`. -- Les messages d'avertissement (`warn`) sont affichés en utilisant `console.warn()`. -- Les messages d'information (`info`) sont affichés en utilisant `console.info()`. - -#### Options du journaliseur console - -

-**Type :** `{ level: AstroLoggerLevel }`
-**Par défaut :** `{ level: 'info' }` - -

- -Le journaliseur `console` accepte les options suivantes : - -- `level` : le [niveau](#niveau-de-journalisation) des journaux qui doivent être affichés. - -```js title="astro.config.mjs" {5} ins="console" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.console({ level: 'warn' }) - } -}); -``` - -### `logHandlers.node` - -Un journaliseur qui affiche les messages dans [`process.stdout`](https://nodejs.org/api/process.html#processstdout) et [`process.stderr`](https://nodejs.org/api/process.html#processstderr). Les messages de niveau `error` sont affichés dans `stderr`, tandis que les autres sont affichés dans `stdout`. - -C'est le journaliseur par défaut d'Astro. - -#### Options du journaliseur Node - -

-**Type :** `{ level: AstroLoggerLevel }`
-**Par défaut :** `{ level: 'info' }` - -

- -Le journaliseur `node` accepte les options suivantes : - -- `level` : le [niveau](#niveau-de-journalisation) des journaux qui doivent être affichés. - -```js title="astro.config.mjs" {5} ins="node" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.node({ level: 'warn' }) - } -}); -``` - -### `logHandlers.compose` - -Une fonction particulière qui permet de configurer plusieurs journaliseurs dans un ordre arbitraire. Le même message est diffusé à tous les journaliseurs. - -L'exemple suivant compose le journaliseur console et le journaliseur JSON en utilisant le niveau de journalisation par défaut : - -```js title="astro.config.mjs" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.compose( - logHandlers.console(), - logHandlers.json() - ) - } -}); -``` - -## Journaliseurs personnalisés - -Vous pouvez créer un journaliseur personnalisé en fournissant la configuration correcte au paramètre `logger`. Il accepte un objet avec un point d'entrée (`entrypoint`) obligatoire, le module depuis lequel le journaliseur est exporté, et une configuration facultative à transmettre au journaliseur. La configuration doit être sérialisable. - -La fonction du journaliseur doit être exportée en tant que `default`. - -Lorsque vous définissez un journaliseur personnalisé, vous êtes responsable de tous les journaux, même ceux émis par Astro. - -L'exemple suivant définit un journaliseur personnalisé exporté par le package `@org/journaliseur-personnalise` et n'acceptant qu'un seul paramètre pour configurer le niveau (`level`) de journalisation : - -```js title="astro.config.mjs" -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: { - entrypoint: "@org/journaliseur-personnalise", - config: { - level: "warn" - } - } - } -}); -``` - -L'exemple suivant implémente un journaliseur minimal renvoyant un [objet `AstroLoggerDestination`](#astrologgerdestination) avec la fonction `write()` requise : - -```ts title="@org/journaliseur-personnalise/index.ts" -import type { - AstroLoggerLevel, - AstroLoggerDestination, - AstroLoggerMessage -} from "astro"; -import { matchesLevel } from "astro/logger"; - -type LoggerOptions = { - level: AstroLoggerLevel -} - -function orgLogger(options: LoggerOptions = {}): AstroLoggerDestination { - const { level = 'info' } = options; - return { - write(message: AstroLoggerMessage) { - // Utilisez cet utilitaire pour comprendre si le message doit être affiché - if (matchesLevel(message.level, level)) { - // journalisez le message quelque part en tenant compte du niveau - } - } - } -} - -export default orgLogger; -``` - -## Environnement d'exécution - -L'[objet de contexte](/fr/reference/api-reference/#lobjet-de-contexte) expose désormais un objet `logger` contenant les fonctions suivantes : - -- `error()`, qui émet un message avec le niveau `error`. -- `warn()`, qui émet un message avec le niveau `warn`. -- `info()`, qui émet un message avec le niveau `info`. - -```astro ---- -Astro.logger.error("Ceci est une erreur"); -Astro.logger.warn("Ceci est un avertissement"); -Astro.logger.info("Ceci est une information"); ---- -``` - -## Niveau de journalisation - -Un niveau est un score interne et arbitraire attribué à chaque message. Lorsqu'un journaliseur est configuré avec un certain niveau, seuls les messages ayant un niveau égal ou supérieur sont affichés. - -Il existe trois niveaux, du score le plus élevé au score le plus bas : -1. `error` -2. `warn` -3. `info` - -L'exemple suivant configure le journaliseur JSON pour n'afficher que les messages ayant le niveau `warn` ou supérieur : - -```js title="astro.config.mjs" {5} ins='level: "warn"' -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.json({ level: "warn" }) - } -}); -``` - -Le paquet `astro/logger` expose une fonction utilitaire [`matchesLevel()`](#matcheslevel) pour vérifier le niveau de journalisation. Cela peut être utile lors de la [création d'un journaliseur personnalisé](#journaliseurs-personnalisés). - -```js -import { matchesLevel } from "astro/logger"; - -matchesLevel("error", "info"); -``` - - -## Référence des types - -Les types suivants peuvent être importés depuis le module `astro`. - -### `AstroLoggerDestination` - -Ceci est l'interface que les journaliseurs personnalisés doivent implémenter. - -#### `AstroLoggerDestination.write()` - -

- -**Type :** `(message: AstroLoggerMessage) => void` -

- -Une méthode obligatoire appelée pour chaque journal et acceptant un objet [`AstroLoggerMessage`](#astrologgermessage). - -#### `AstroLoggerDestination.flush()` - -

- -**Type :** `() => Promise | void` -

- -Une fonction facultative appelée à la fin de chaque requête. Cela est utile pour les journaliseurs avancés qui doivent vider les messages de journal tout en maintenant la connexion avec la destination active. - -#### `AstroLoggerDestination.close()` - -

- -**Type :** `() => Promise | void` -

- -Une fonction facultative appelée avant l'arrêt d'un serveur. Cette fonction est généralement appelée par des adaptateurs tels que `@astrojs/node`. - -### `AstroLoggerLevel` - -Le niveau du message. Variantes disponibles : -- `'debug'` -- `'info'` -- `'warn'` -- `'error'` -- `'silent'` - -### `AstroLoggerMessage` - -

- -**Type :** `{ label: string | null; level: AstroLoggerLevel; message: string; newLine: boolean; }` -

-L'objet entrant de la fonction [`AstroLoggerDestination.write()`](#astrologgerdestinationwrite) : -- `message` : le message à journaliser. -- `level` : le niveau du message. -- `label` : une étiquette arbitraire attribuée au message du journal. -- `newLine` : indique si ce message doit ajouter une nouvelle ligne à la fin. - -## Référence des APIs - -Les APIs suivantes peuvent être importées depuis le module `astro/logger`. - -### `matchesLevel` - -

- -**Type :** `matchesLevel(messageLevel: AstroLoggerLevel, configuredLevel: AstroLoggerLevel) => boolean` -

- -Étant donné deux [niveaux de journalisation](#niveau-de-journalisation), cette fonction renvoie si le premier niveau correspond au second niveau. - -```js -import { matchesLevel } from "astro/logger"; - -matchesLevel("error", "info"); // true -matchesLevel("info", "error"); // false - -``` diff --git a/src/content/docs/fr/reference/experimental-flags/queued-rendering.mdx b/src/content/docs/fr/reference/experimental-flags/queued-rendering.mdx deleted file mode 100644 index 6a21357698d49..0000000000000 --- a/src/content/docs/fr/reference/experimental-flags/queued-rendering.mdx +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Rendu en file d'attente expérimental -sidebar: - label: Rendu en file d'attente -i18nReady: true ---- - -import Since from '~/components/Since.astro'; - -

- -**Type :** `object`
-**Par défaut :** `{ enabled: false }`
- -

- -Permet de mettre en place une infrastructure de rendu expérimentale et plus performante, reposant sur une file d'attente plutôt que sur la récursivité. - -Par défaut, Astro traite les fichiers `.astro`, `.md` et `.mdx` à l'aide d'un algorithme récursif. Il prend en entrée une série de composants sérialisés sous forme d'arbre, et pour chaque nœud de cet arbre, Astro appelle une fonction de rendu. - -Lorsque le rendu en file d'attente est activé, Astro parcourt tous les nœuds de l'arbre et génère une liste de nœuds par [recherche en profondeur](https://fr.wikipedia.org/wiki/Algorithme_de_parcours_en_profondeur). Cette liste est ensuite parcourue et rendue, sans nécessiter d'algorithme récursif. Ce rendu est plus économe en mémoire et s'avère particulièrement avantageux pour les grands projets. - -Pour activer cette fonctionnalité avec les paramètres par défaut, définissez `queuedRendering.enabled` sur `true` dans votre configuration d'Astro : - -```js title="astro.config.mjs" ins={5-7} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - queuedRendering: { - enabled: true - } - } -}); -``` - -Dans une future version majeure, Astro utilisera ce nouveau compilateur par défaut, mais vous pouvez activer ce comportement futur dès maintenant en utilisant l'option `experimental.queuedRendering`. - -## Configuration - -Le moteur de rendu en file d'attente intègre des fonctionnalités supplémentaires de bas niveau, permettant d'expérimenter d'autres optimisations. Ces optimisations ne font pas directement partie du moteur de mise en file d'attente et pourront être supprimées si elles s'avèrent inefficaces au cours de cette phase expérimentale de test. - - -### Regroupement de nœuds - -

- -**Type :** `number`
-**Par défaut :** `1000`
- -

- - -Le regroupement de nœuds est un système de mise en cache conçu pour réutiliser les nœuds de composants entre les rendus. Cette fonctionnalité est automatiquement activée avec une valeur par défaut raisonnable d'après nos premiers tests. Vous pouvez toutefois configurer la taille du groupe pour augmenter ou diminuer le nombre de nœuds combinés dans un seul groupe en fonction des besoins de votre projet. Pour désactiver complètement cette fonctionnalité, définissez `poolSize` sur `0`. - -Le regroupement de nœuds est très efficace lors du rendu de pages statiques car il permet d'économiser de la mémoire lors de la création de sites web comportant de nombreuses pages partageant les mêmes composants. - -Le regroupement de nœuds est désactivé pour les pages rendues à la demande, car ces requêtes de rendu ne partagent pas la mémoire et, par conséquent, cette stratégie ne permet pas de réaliser d'économies. - -```js title="astro.config.mjs" ins={7} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - queuedRendering: { - enabled: true, - poolSize: 3000 // utiliser un groupe de 3000 nœuds - } - } -}); -``` - -### Mise en cache du contenu - -

- -**Type :** `boolean`
-**Par défaut :** `false`
- -

- - -La mise en cache du contenu est une autre technique permettant de réutiliser des valeurs (généralement des chaînes de caractères) lors du rendu d'une page. Actuellement, cette fonctionnalité peut uniquement être activée ou désactivée sans configuration supplémentaire. Elle est désactivée par défaut, mais lorsqu'elle est activée, le moteur de mise en file d'attente expérimental choisira une taille de cache par défaut adaptée à la plupart des grandes collections de contenu. - -```js title="astro.config.mjs" ins={7} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - queuedRendering: { - enabled: true, - contentCache: true - } - } -}); -``` diff --git a/src/content/docs/fr/reference/experimental-flags/rust-compiler.mdx b/src/content/docs/fr/reference/experimental-flags/rust-compiler.mdx deleted file mode 100644 index 502d42ac1e685..0000000000000 --- a/src/content/docs/fr/reference/experimental-flags/rust-compiler.mdx +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Compilateur Rust expérimental -sidebar: - label: Compilateur Rust -i18nReady: true ---- - -import Since from '~/components/Since.astro' -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' - -

- - **Type :** `boolean`
- **Par défaut :** `false`
- -

- -Active le nouveau compilateur de fichiers Astro implémenté avec Rust. Ce compilateur est plus rapide, fournit de meilleurs messages d'erreur, et de manière générale a une meilleure prise en charge des fonctionnalités modernes de JavaScript, TypeScript et CSS. - -Dans une future version majeure, Astro utilisera ce nouveau compilateur par défaut, mais vous pouvez activer ce comportement futur dès maintenant en utilisant l'option `experimental.rustCompiler`. - -Pour faire part de vos commentaires sur le compilateur ou bien pour suivre son développement, consultez la [RFC relative au nouveau compilateur d'Astro](https://github.com/withastro/roadmap/discussions/1306) pour plus d'informations et discussions. - -## Utilisation - -Cette option expérimentale ne nécessite aucune utilisation spécifique et concerne seulement le compilateur qu'Astro utilise pour votre projet. - -Pour activer le compilateur Rust, ajoutez le code suivant à votre fichier `astro.config.mjs` : - -```js title="astro.config.mjs" ins={4-6} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - rustCompiler: true - } -}); -``` - -et installez ensuite le paquet `@astrojs/compiler-rs` dans votre projet : - - - - ```shell - npm install @astrojs/compiler-rs - ``` - - - ```shell - pnpm add @astrojs/compiler-rs - ``` - - - ```shell - yarn add @astrojs/compiler-rs - ``` - - - -### Différences attendues - -Contrairement au compilateur Astro actuel écrit en Go, ce compilateur Rust expérimental ne corrigera pas les structures HTML invalides. Par exemple, les modèles notables suivants seront laissés tels quels, et ne seront plus corrigés : - - - `

Mauvaise imbrication

` (au lieu de supprimer la balise `div` de la balise `p`) - - `

Mon paragraphe` (au lieu d'ajouter la balise `

` manquante) - -Cela signifie que si vos fichiers Astro contiennent du code HTML invalide, vous pourriez obtenir un résultat différent avec le compilateur Rust par rapport au compilateur précédent, ou rencontrer des erreurs lors de la compilation. - -## Limitations - -À l'heure actuelle, le compilateur Rust ne génère pas les métadonnées nécessaires au bon fonctionnement des audits de la barre d'outils de développement. diff --git a/src/content/docs/ja/reference/experimental-flags/queued-rendering.mdx b/src/content/docs/ja/reference/experimental-flags/queued-rendering.mdx deleted file mode 100644 index c8f9367e3dc2d..0000000000000 --- a/src/content/docs/ja/reference/experimental-flags/queued-rendering.mdx +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: 実験的なキューレンダリング -sidebar: - label: キューレンダリング -i18nReady: true ---- - -import Since from '~/components/Since.astro'; - -

- -**Type:** `object`
-**Default:** `{ enabled: false }`
- -

- -再帰ではなくキューに基づいた、より高パフォーマンスな実験的レンダリング基盤を有効にします。 - -デフォルトでは、Astroは再帰アルゴリズムを使用して`.astro`・`.md`・`.mdx`ファイルをレンダリングします。ツリー構造にシリアライズされた一連のコンポーネントを入力として受け取り、ツリーの各ノードに対してAstroはレンダリング関数を呼び出します。 - -キューレンダリングを有効にすると、Astroはツリー内のすべてのノードを走査し、[深さ優先](https://en.wikipedia.org/wiki/Depth-first_search)のノードリストを生成します。このリストは再帰アルゴリズムを使わずに順番にレンダリングされます。このレンダリング方式はメモリ効率が高く、大規模なプロジェクトでより大きな効果が期待できます。 - -デフォルト設定でこの機能を有効にするには、Astroの設定で`queuedRendering.enabled`を`true`に設定します。 - -```js title="astro.config.mjs" ins={5-7} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - queuedRendering: { - enabled: true - } - } -}); -``` - -将来のメジャーバージョンでは、Astroはデフォルトでこの新しいコンパイラーを使用するようになりますが、`experimental.queuedRendering`フラグを使用することで、いち早く将来の動作を試すことができます。 - -## 設定 - -キューレンダリングエンジンには追加の低レベル機能が用意されており、その他の最適化を実験することができます。これらの最適化はキューエンジン自体の直接的な機能ではなく、この実験フェーズのテスト中に非効率と判明した場合は削除される可能性があります。 - -### ノードプーリング - -

- -**Type:** `number`
-**Default:** `1000`
- -

- -ノードプーリングは、レンダリング間でコンポーネントノードを再利用するためのキャッシュシステムです。この機能は初期テストに基づいた合理的なデフォルト値で自動的に有効になります。ただし、プロジェクトのニーズに合わせて1つのプールに含まれるノード数を増減するため、プールのサイズを設定できます。この機能を完全に無効にするには、`poolSize`を`0`に設定します。 - -ノードプーリングは静的ページのレンダリングに非常に効果的です。同じコンポーネントを共有する多くのページを持つウェブサイトをビルドする際に、メモリを節約できます。 - -オンデマンドレンダリングのページでは、レンダリングリクエスト間でメモリを共有しないため、この戦略によるメモリ節約の効果がなく、ノードプーリングは無効になります。 - -```js title="astro.config.mjs" ins={7} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - queuedRendering: { - enabled: true, - poolSize: 3000 // 3000ノードのプールを使用する - } - } -}); -``` - -### コンテンツキャッシング - -

- -**Type:** `boolean`
-**Default:** `false`
- -

- -コンテンツキャッシングは、ページのレンダリング中に値(通常は文字列)を再利用するもう一つの技法です。現在、この機能は有効・無効の切り替えのみで、追加の設定はできません。デフォルトでは無効ですが、有効にすると実験的なキューエンジンがほとんどの大規模コンテンツコレクションに対して合理的なデフォルトキャッシュサイズを選択します。 - -```js title="astro.config.mjs" ins={7} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - queuedRendering: { - enabled: true, - contentCache: true - } - } -}); -``` diff --git a/src/content/docs/ja/reference/experimental-flags/rust-compiler.mdx b/src/content/docs/ja/reference/experimental-flags/rust-compiler.mdx deleted file mode 100644 index 80bbb666ce926..0000000000000 --- a/src/content/docs/ja/reference/experimental-flags/rust-compiler.mdx +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: 試験的なRustコンパイラー -sidebar: - label: Rustコンパイラー -i18nReady: true ---- - -import Since from '~/components/Since.astro' -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' - -

- - **Type:** `boolean`
- **Default:** `false`
- -

- -AstroファイルにRustベースの新しいコンパイラーを使用できるようにします。このコンパイラーはより高速で、エラーメッセージがわかりやすく、モダンなJavaScript・TypeScript・CSSの機能に対して全般的に優れたサポートを提供します。 - -将来のメジャーバージョンでは、Astroはデフォルトでこの新しいコンパイラーを使用するようになりますが、`experimental.rustCompiler`フラグを使用することで、いち早く将来の動作を試すことができます。 - -コンパイラーへのフィードバックや開発状況を確認するには、[Astroの新しいコンパイラーに関するRFC](https://github.com/withastro/roadmap/discussions/1306)をご参照ください。 - -## 使い方 - -この試験的なフラグは特定の使い方を必要とせず、Astroがプロジェクトに使用するコンパイラーにのみ影響します。 - -Rustコンパイラーを有効にするには、`astro.config.mjs`に以下を追加します。 - -```js title="astro.config.mjs" ins={4-6} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - rustCompiler: true - } -}); -``` - -次に、`@astrojs/compiler-rs`パッケージをプロジェクトにインストールします。 - - - - ```shell - npm install @astrojs/compiler-rs - ``` - - - ```shell - pnpm add @astrojs/compiler-rs - ``` - - - ```shell - yarn add @astrojs/compiler-rs - ``` - - - -### 動作の違いについて - -AstroのGoコンパイラーとは異なり、この試験的なRustコンパイラーは無効なHTML構造を修正しません。たとえば、以下のようなパターンはそのまま出力され、自動修正されなくなります。 - - - `

Bad nesting

`(`p`タグから`div`を除去する代わりに) - - `

My paragraph` (閉じタグ`

`を補完する代わりに) - -そのため、Astroファイルに無効なHTMLが含まれている場合、Rustコンパイラーによる出力が以前のコンパイラーと異なる場合や、ビルド時にエラーが発生する場合があります。 - -## 制限事項 - -現時点では、Rustコンパイラーはdevツールバーの監査が正しく機能するために必要なメタデータを出力しません。 diff --git a/src/content/docs/ko/guides/astro-db.mdx b/src/content/docs/ko/guides/astro-db.mdx deleted file mode 100644 index 2baf6edbea9d9..0000000000000 --- a/src/content/docs/ko/guides/astro-db.mdx +++ /dev/null @@ -1,799 +0,0 @@ ---- -title: 'Astro DB' -description: Astro 전용으로 설계된 완전 관리형 SQL 데이터베이스인 Astro DB를 사용하는 방법을 알아보세요. -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -import { Steps } from '@astrojs/starlight/components'; - -:::caution[지원 중단] -`@astrojs/db` 통합은 Astro v6.5에서 지원이 중단되었으며 더 이상 유지 관리되지 않습니다. - -이 통합을 사용 중인 프로젝트라면, Astro 프로젝트에서 데이터베이스 클라이언트(예: Drizzle, Kysely)를 직접 사용하는 것을 권장합니다. -::: - -Astro DB는 Astro 생태계를 위해 설계된 완전 관리형 SQL 데이터베이스입니다. Astro에서 로컬로 개발하여 모든 libSQL 호환 데이터베이스에 배포하세요. - -Astro DB는 데이터를 구성, 개발, 쿼리할 수 있는 완벽한 솔루션입니다. Docker나 네트워크 연결 없이도 데이터를 관리하기 위해 `astro dev`를 실행할 때마다 로컬 데이터베이스가 `.astro/content.db`에 생성됩니다. - -## 설치 - -내장된 `astro add` 명령을 사용하여 [`@astrojs/db` 통합](/ko/guides/integrations-guide/db/)을 설치합니다: - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -## 데이터베이스 정의 - -`astro add` 명령으로 `@astrojs/db`를 설치하면 프로젝트에 데이터베이스 테이블을 정의할 `db/config.ts` 파일이 자동으로 생성됩니다: - -```ts title="db/config.ts" -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: { }, -}) -``` - -### 테이블 - -Astro DB의 데이터는 SQL 테이블을 사용하여 저장됩니다. 테이블은 데이터를 행과 열로 구조화하며, 여기서 열은 각 행 값의 타입을 적용합니다. - -기존 libSQL 데이터베이스의 데이터 구조 또는 새 데이터베이스에서 수집할 데이터를 제공하여 `db/config.ts` 파일에 테이블을 정의하세요. 이렇게 하면 Astro가 프로젝트에서 해당 테이블을 쿼리하기 위한 TypeScript 인터페이스를 생성할 수 있습니다. 결과적으로 데이터에 액세스할 때 속성 자동 완성 및 타입 검사를 통해 완전한 TypeScript 지원이 제공됩니다. - -데이터베이스 테이블을 구성하려면 `astro:db`에서 `defineTable()` 및 `column` 유틸리티를 가져와 사용하세요. 그런 다음 테이블의 이름 (대소문자 구분)과 각 열의 데이터 타입을 정의합니다. - -이 예시에서는 `author` 및 `body`에 대한 필수 텍스트 열이 있는 `Comment` 테이블을 구성합니다. 그런 다음 `defineDb()` 내보내기를 통해 프로젝트에서 사용할 수 있도록 합니다. - -```ts title="db/config.ts" "Comment" -import { defineDb, defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } -}) - -export default defineDb({ - tables: { Comment }, -}) -``` - -테이블 옵션에 대한 전체 참조는 [테이블 구성 참조](/ko/guides/integrations-guide/db/#테이블-구성-참조)를 확인하세요. - -### 열 (Columns) - -Astro DB는 다음 열 타입을 지원합니다. - -```ts title="db/config.ts" "column.text()" "column.number()" "column.boolean()" "column.date()" "column.json()" -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - // 텍스트 문자열입니다. - author: column.text(), - // 정수 값입니다. - likes: column.number(), - // 참 또는 거짓 값입니다. - flagged: column.boolean(), - // JavaScript Date 객체로 쿼리되는 날짜/시간 값입니다. - published: column.date(), - // 타입이 설정되지 않은 JSON 객체입니다. - metadata: column.json(), - } -}); -``` - -자세한 내용은 [테이블 열 참조](/ko/guides/integrations-guide/db/#테이블-구성-참조)를 확인하세요. - -### 테이블 참조 - -테이블 간 관계는 데이터베이스 디자인의 일반적인 패턴입니다. 예를 들어, `Blog` 테이블은 `Comment`, `Author` 및 `Category`의 다른 테이블과 밀접하게 관련될 수 있습니다. - -테이블 간 관계를 정의하고 **참조 열 (reference columns)** 을 사용하여 데이터베이스 스키마에 저장할 수 있습니다. 관계를 구축하려면 다음이 필요합니다. - -- 참조 테이블의 **식별자 열 (identifier column)** 이 필요합니다. 이는 일반적으로 `primaryKey` 속성이 있는 `id` 열입니다. -- **참조된 `id`를 저장하기 위한 기본 테이블의 열** 이 필요합니다. 이는 관계를 설정하기 위해 `references` 속성을 사용합니다. - -이 예시에서는 `Author` 테이블의 `id` 열을 참조하는 `Comment` 테이블의 `authorId` 열을 보여줍니다. - -```ts title="db/config.ts" {3, 10} -const Author = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - } -}); - -const Comment = defineTable({ - columns: { - authorId: column.number({ references: () => Author.columns.id }), - body: column.text(), - } -}); -``` - -## 개발 모드에서 데이터베이스 시드 - -개발 모드에서 Astro는 DB 구성을 사용하여 스키마에 따라 로컬 타입을 생성합니다. 이는 개발 서버가 시작될 때마다 시드 파일에서 새로 생성되며 타입 안전성 및 자동 완성을 통해 데이터 형태를 쿼리하고 작업할 수 있습니다. - -개발 모드에서 [원격 데이터베이스에 연결](#원격-데이터베이스에-연결)하지 않으면 개발 중에 프로덕션 데이터에 액세스할 수 없습니다. 이렇게 하면 데이터를 보호하는 동시에 타입 안전성이 보장된 작동 중인 데이터베이스로 테스트하고 개발할 수 있습니다. - -테스트 및 디버깅을 위해 개발 데이터를 Astro 프로젝트에 시드하려면 `db/seed.ts` 파일을 생성합니다. `db` 객체와 `astro:db`에 정의된 테이블을 모두 가져옵니다. 각 테이블에 초기 데이터를 `insert` 합니다. 이 개발 데이터는 데이터베이스 스키마 및 프로덕션 데이터의 형식과 일치해야 합니다. - -다음 예시에서는 `Comment` 테이블과 `Author` 테이블에 대한 개발 데이터의 두 행을 정의합니다. - -```ts title="db/seed.ts" -import { db, Comment, Author } from 'astro:db'; - -export default async function() { - await db.insert(Author).values([ - { id: 1, name: "Kasim" }, - { id: 2, name: "Mina" }, - ]); - - await db.insert(Comment).values([ - { authorId: 1, body: 'Hope you like Astro DB!' }, - { authorId: 2, body: 'Enjoy!'}, - ]) -} -``` - -개발 서버는 이 파일이 변경될 때마다 자동으로 데이터베이스를 다시 시작하여 타입을 재생성하고 매번 `seed.ts`에서 이 개발 데이터를 새로 시드합니다. - -## 프로덕션용 libSQL 데이터베이스 연결 - -Astro DB는 관리형 또는 자체 호스팅에 관계없이 모든 로컬 libSQL 데이터베이스 또는 libSQL 원격 프로토콜을 노출하는 모든 서버에 연결할 수 있습니다. - -Astro DB를 libSQL 데이터베이스에 연결하려면 데이터베이스 제공업체에서 얻은 다음 환경 변수를 설정하세요: - -- `ASTRO_DB_REMOTE_URL`: 로컬 또는 원격 libSQL DB의 위치에 대한 연결 URL입니다. 여기에는 동기화 및 암호화와 같은 [URL 구성 옵션](#원격-url-구성-옵션)이 매개변수로 포함될 수 있습니다. -- `ASTRO_DB_APP_TOKEN`: libSQL 서버의 인증 토큰입니다. 이는 원격 데이터베이스에 필요하며 [파일 또는 인메모리와 같은 로컬 DB](#url-스킴-및-호스트) 데이터베이스에는 필요하지 않습니다. - -서비스에 따라 CLI 또는 웹 UI에 액세스하여 이러한 값을 검색할 수 있습니다. 다음 섹션에서는 Turso에 연결하여 이러한 값을 설정하는 방법을 예시로 보여드리지만, 어떤 제공업체를 사용하든 자유롭게 사용할 수 있습니다. - -### Turso로 시작하기 - -Turso는 Astro DB를 구동하는 SQLite의 오픈 소스 포크인 [libSQL](https://github.com/tursodatabase/libsql)을 개발한 회사입니다. 완전히 관리되는 libSQL 데이터베이스 플랫폼을 제공하며 Astro와 완벽하게 호환됩니다. - -아래 단계는 Turso CLI 설치, 로그인 (또는 가입), 새 데이터베이스 생성, 필요한 환경 변수 가져오기, 스키마를 원격 데이터베이스에 푸시하는 과정을 안내합니다. - - - -1. [Turso CLI](https://docs.turso.tech/cli/installation)를 설치합니다. - -2. Turso에 [로그인 또는 가입](https://docs.turso.tech/cli/authentication)합니다. - -3. 새 데이터베이스를 생성합니다. 이 예시에서 데이터베이스 이름은 `andromeda`입니다. - - ```sh "andromeda" - turso db create andromeda - ``` - -4. `show` 명령을 실행하여 새로 생성된 데이터베이스에 대한 정보를 확인합니다: - - ```sh "andromeda" - turso db show andromeda - ``` - - `URL` 값을 복사하여 `ASTRO_DB_REMOTE_URL`의 값으로 설정합니다. - - - ```dotenv title=".env" "libsql://andromeda-houston.turso.io" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ``` - -5. 데이터베이스에 대한 요청을 인증할 새 토큰을 생성합니다: - - ```sh "andromeda" - turso db tokens create andromeda - ``` - - 명령의 출력을 복사하여 `ASTRO_DB_APP_TOKEN`의 값으로 설정합니다. - - ```dotenv title=".env" add={2} "eyJhbGciOiJF...3ahJpTkKDw" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ASTRO_DB_APP_TOKEN=eyJhbGciOiJF...3ahJpTkKDw - ``` - -6. DB 스키마 및 메타데이터를 새 Turso 데이터베이스로 푸시합니다. - - ```sh - astro db push --remote - ``` - -7. 축하합니다, 이제 데이터베이스가 연결되었습니다! 이제 휴식을 취하세요. 👾 - - ```sh - turso relax - ``` - - - -Turso의 더 많은 기능을 살펴보려면 [Turso 문서](https://docs.turso.tech)를 확인하세요. - -### 원격 데이터베이스에 연결 - -Astro DB를 사용하면 로컬 및 원격 데이터베이스에 모두 연결할 수 있습니다. 기본적으로 Astro는 `dev` 및 `build` 명령에 로컬 데이터베이스 파일을 사용하여 테이블을 다시 생성하고 매번 개발 시드 데이터를 삽입합니다. - -호스팅된 원격 데이터베이스에 연결하려면 `--remote` 플래그를 사용합니다. 이 플래그를 사용하면 원격 데이터베이스에 대한 읽기 및 쓰기 액세스가 모두 가능하므로 프로덕션 환경에서 [사용자 데이터를 허용 및 유지](#insert)할 수 있습니다. - -`--remote` 플래그를 사용하도록 빌드 명령을 구성합니다: - -```json title="package.json" "--remote" -{ - "scripts": { - "build": "astro build --remote" - } -} -``` - -명령줄에서 직접 플래그를 사용할 수도 있습니다: - -```bash -# 원격 연결을 통한 빌드 -astro build --remote - -# 원격 연결을 통한 개발 -astro dev --remote -``` - -:::caution -개발 모드에서 `--remote`를 사용할 때는 주의하세요. 이렇게 하면 라이브 프로덕션 데이터베이스에 연결되며 모든 변경 사항 (삽입, 업데이트, 삭제)이 유지됩니다. -::: - -`--remote` 플래그는 로컬 빌드와 서버에서 모두 원격 DB에 대한 연결을 사용합니다. 로컬 개발 환경과 배포 플랫폼 모두에서 필요한 환경 변수를 설정했는지 확인하세요. 또한 Cloudflare Workers나 Deno와 같은 Node.js가 아닌 런타임 환경에서는 [웹 모드를 구성](/ko/guides/integrations-guide/db/#mode)해야 할 수도 있습니다. - -Astro DB 프로젝트를 배포할 때, 배포 플랫폼의 빌드 명령이 `package.json`에 구성된 `--remote` 플래그를 활용하도록 `npm run build` (또는 패키지 관리자에 상응하는 명령어)로 설정되어 있는지 확인하세요. - -### 원격 URL 구성 옵션 - -`ASTRO_DB_REMOTE_URL` 환경 변수는 데이터베이스의 위치와 동기화 및 암호화와 같은 기타 옵션을 구성합니다. - -#### URL 스킴 및 호스트 - -libSQL은 원격 서버의 전송 프로토콜로 HTTP와 WebSockets을 모두 지원합니다. 또한 로컬 파일이나 인메모리 DB 사용도 지원합니다. 이러한 프로토콜은 연결 URL에서 다음 URL 스킴을 사용하여 구성할 수 있습니다: - -- `memory:` 인메모리 DB를 사용합니다. 이 경우 호스트는 비어 있어야 합니다. -- `file:` 로컬 파일을 사용합니다. 호스트는 파일 경로입니다 (`file:path/to/file.db`). -- `libsql:` 라이브러리에서 선호하는 프로토콜을 통해 원격 서버를 사용합니다 (버전에 따라 다를 수 있음). 호스트는 서버의 주소 (`libsql://your.server.io`)입니다. -- `http:` HTTP를 통해 원격 서버를 사용합니다. 보안 연결을 사용하려면 `https:`를 사용할 수 있습니다. 호스트는 `libsql:`와 동일합니다. -- `ws:` WebSockets을 통해 원격 서버를 사용합니다. `wss:`를 사용하여 보안 연결을 활성화할 수 있습니다. 호스트는 `libsql:`와 동일합니다. - -libSQL 연결의 세부 정보 (예: 암호화 키, 복제, 동기화 간격)는 원격 연결 URL에서 쿼리 매개변수로 구성될 수 있습니다. - -예를 들어 암호화된 로컬 파일이 libSQL 서버에 임베디드 복제본으로 작동하도록 하려면 다음 환경 변수를 설정하면 됩니다: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io -ASTRO_DB_APP_TOKEN=token-to-your-remote-url -``` - -:::caution -데이터베이스 파일을 사용하는 것은 고급 기능이므로 배포 시 데이터베이스가 재정의되어 프로덕션 데이터가 손실되지 않도록 주의해야 합니다. - -또한 서버리스 배포에서는 파일 시스템이 유지되지 않으므로 이 방법은 작동하지 않습니다. -::: - -#### `encryptionKey` - -libSQL은 암호화된 데이터베이스를 기본적으로 지원합니다. 이 검색 매개변수를 전달하면 지정된 키를 사용하여 암호화를 활성화합니다: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file:path/to/file.db?encryptionKey=your-encryption-key -``` - -#### `syncUrl` - -임베디드 복제본은 초고속 읽기를 위해 로컬 파일이나 메모리에 데이터베이스의 전체 동기화 복사본을 저장할 수 있는 libSQL 클라이언트의 기능입니다. 쓰기는 `syncUrl`에 정의된 원격 데이터베이스로 전송되어 로컬 복사본과 동기화됩니다. - -이 속성을 사용하여 별도의 연결 URL을 전달하여 데이터베이스를 다른 데이터베이스의 임베디드 복제본으로 전환할 수 있습니다. 이 속성은 `file:` 및 `memory:` 스킴에서만 사용해야 합니다. 매개변수는 URL로 인코딩되어야 합니다. - -예를 들어 데이터베이스의 인메모리 임베디드 복제본을 `libsql://your.server.io`에 만들려면 연결 URL을 다음과 같이 설정할 수 있습니다. - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io -``` - -#### `syncInterval` - -임베디드 복제본 동기화 간격 (초)입니다. 기본적으로 시작 시와 쓰기 후에만 동기화됩니다. - -이 속성은 `syncUrl`도 설정된 경우에만 사용됩니다. 예를 들어 인메모리 임베디드 복제본이 매분 동기화되도록 설정하려면 다음 환경 변수를 설정합니다: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io&syncInterval=60 -``` - -## 데이터베이스 쿼리 - -제공된 db ORM 및 쿼리 빌더를 사용하여 프로젝트의 모든 [Astro 페이지](/ko/basics/astro-pages/#astro-페이지), [엔드포인트](/ko/guides/endpoints/), 또는 [액션](/ko/guides/actions/)에서 데이터베이스를 쿼리할 수 있습니다. - -### Drizzle ORM - -```ts -import { db } from 'astro:db'; -``` - -Astro DB에는 [Drizzle ORM](https://orm.drizzle.team/) 클라이언트가 내장되어 있습니다. 클라이언트를 사용하는 데 필요한 설정이나 수동 구성이 없습니다. Astro DB의 `db` 클라이언트는 Astro를 실행할 때 데이터베이스 (로컬 또는 원격)와 통신하도록 자동으로 구성됩니다. 존재하지 않는 열이나 테이블을 참조할 때, TypeScript 오류가 발생한 타입 안정성을 갖춘 SQL 쿼리에 대해 정확한 데이터베이스 스키마 정의를 사용합니다. - -### Select - -다음 예시에서는 `Comment` 테이블의 모든 행을 선택합니다. 그러면 페이지 템플릿에서 사용할 수 있는 `db/seed.ts` 파일에서 시드된 개발 데이터의 전체 배열이 반환됩니다. - -```astro title="src/pages/index.astro" ---- -import { db, Comment } from 'astro:db'; - -const comments = await db.select().from(Comment); ---- - -

Comments

- -{ - comments.map(({ author, body }) => ( -
-

Author: {author}

-

{body}

-
- )) -} -``` - -전체 개요는 [Drizzle `select()` API 참조](https://orm.drizzle.team/docs/select)를 확인하세요. - -### Insert - -양식 요청 처리 및 원격 호스팅 데이터베이스에 데이터 삽입과 같은 사용자 입력을 허용하려면 Astro 프로젝트에 [주문형 렌더링](/ko/guides/on-demand-rendering/)을 구성하고 배포 환경에 [SSR 어댑터를 추가](/ko/guides/on-demand-rendering/#어댑터-추가)하세요. - -이 예시에서는 구문 분석된 양식 POST 요청을 기반으로 `Comment` 테이블에 행을 삽입합니다. - -```astro ---- -// src/pages/index.astro -import { db, Comment } from 'astro:db'; - -if (Astro.request.method === 'POST') { - // 양식 데이터 구문 분석 - const formData = await Astro.request.formData(); - const author = formData.get('author'); - const body = formData.get('body'); - if (typeof author === 'string' && typeof body === 'string') { - // Comment 테이블에 양식 데이터 삽입 - await db.insert(Comment).values({ author, body }); - } -} - -// 각 요청에 대해 새로운 comments 목록을 렌더링 -const comments = await db.select().from(Comment); ---- - -
- - - - - - - -
- - -``` - -[Astro 액션](/ko/guides/actions/)을 사용하여 Astro DB 테이블에 데이터를 삽입할 수도 있습니다. 다음은 액션을 사용하여 `Comment` 테이블에 행을 삽입하는 예시입니다: - -```ts -// src/actions/index.ts -import { db, Comment } from 'astro:db'; -import { defineAction } from 'astro:actions'; -import { z } from 'astro/zod'; - -export const server = { - addComment: defineAction({ - // 액션에는 Zod의 타입 안정성이 포함되어 있으므로 - // 페이지에서 typeof {value} === 'string'인지 확인할 필요가 없습니다. - input: z.object({ - author: z.string(), - body: z.string(), - }), - handler: async (input) => { - const updatedComments = await db - .insert(Comment) - .values(input) - .returning(); // 업데이트된 comments를 반환합니다. - return updatedComments; - }, - }), -}; -``` - - - -전체 개요는 [Drizzle `insert()` API 참조](https://orm.drizzle.team/docs/insert)를 확인하세요. - - - -### Delete - -API 엔드포인트에서 데이터베이스를 쿼리할 수도 있습니다. 이 예시에서는 `id` 매개변수를 사용하여 `Comment` 테이블에서 행을 삭제합니다: - -```ts -// src/pages/api/comments/[id].ts -import type { APIRoute } from "astro"; -import { db, Comment, eq } from 'astro:db'; - -export const DELETE: APIRoute = async (ctx) => { - await db.delete(Comment).where(eq(Comment.id, ctx.params.id )); - return new Response(null, { status: 204 }); -} -``` - - - -전체 개요는 [Drizzle `delete()` API 참조](https://orm.drizzle.team/docs/delete)를 확인하세요. - - - -### 필터링 - -특정 속성으로 테이블 결과를 쿼리하려면 [부분 선택을 위한 Drizzle 옵션](https://orm.drizzle.team/docs/select#partial-select)을 사용하세요. 예를 들어, `select()` 쿼리에 [`.where()` 호출](https://orm.drizzle.team/docs/select#filtering)을 추가하고 원하는 비교를 전달합니다. - -다음 예시에서는 "Astro DB"라는 문구가 포함된 `Comment` 테이블의 모든 행을 쿼리합니다. `body`에 문구가 있는지 확인하려면 [`like()` 연산자](https://orm.drizzle.team/docs/operators#like)를 사용하세요. - -```astro title="src/pages/index.astro" ---- -import { db, Comment, like } from 'astro:db'; - -const comments = await db.select().from(Comment).where( - like(Comment.body, '%Astro DB%') -); ---- -``` - -### Drizzle 유틸리티 - -쿼리 작성을 위한 모든 Drizzle 유틸리티는 `astro:db` 모듈에서 노출됩니다. 여기에는 다음이 포함됩니다. - -- [필터 연산자](https://orm.drizzle.team/docs/operators) 예: `eq()` 및 `gt()` -- [집계 도우미](https://orm.drizzle.team/docs/select#aggregations-helpers) 예: `count()` -- [`sql` 도우미](https://orm.drizzle.team/docs/sql) - 원시 SQL 쿼리 작성 - -```ts -import { eq, gt, count, sql } from 'astro:db'; -``` - -### 관계 - -SQL join을 사용하여 여러 테이블에서 관련 데이터를 쿼리할 수 있습니다. join 쿼리를 생성하려면 `db.select()` 문을 join 연산자로 확장하세요. 각 함수는 join할 테이블과 두 테이블 사이의 행을 일치시키는 조건을 인자로 전달받습니다. - -이 예시에서는 `innerJoin()` 함수를 사용하여 `authorId` 열을 기반으로 `Comment`의 authors를 관련 `Author` 정보와 join합니다. 그러면 각 `Author` 및 `Comment` 행이 최상위 속성인 객체 배열이 반환됩니다. - -```astro title="src/pages/index.astro" ---- -import { db, eq, Comment, Author } from 'astro:db'; - -const comments = await db.select() - .from(Comment) - .innerJoin(Author, eq(Comment.authorId, Author.id)); ---- - -

Comments

- -{ - comments.map(({ Author, Comment }) => ( -
-

Author: {Author.name}

-

{Comment.body}

-
- )) -} -``` - - - -사용 가능한 모든 join 연산자 및 구성 옵션은 [Drizzle join 참조](https://orm.drizzle.team/docs/joins#join-types)를 확인하세요. - - - -### 일괄 트랜잭션 - -모든 원격 데이터베이스 쿼리는 네트워크 요청으로 이루어집니다. 많은 수의 쿼리를 수행할 때 쿼리를 단일 트랜잭션으로 함께 "일괄 처리"하거나 쿼리가 실패할 경우 자동 롤백을 수행해야 할 수도 있습니다. - -이 예시에서는 `db.batch()` 메서드를 사용하여 단일 요청에 여러 행을 시드합니다. - -```ts -// db/seed.ts -import { db, Author, Comment } from 'astro:db'; - -export default async function () { - const queries = []; - // 단일 네트워크 요청으로 원격 데이터베이스에 100개의 샘플 comments를 시드합니다. - for (let i = 0; i < 100; i++) { - queries.push(db.insert(Comment).values({ body: `Test comment ${i}` })); - } - await db.batch(queries); -} -``` - - - -자세한 내용은 [Drizzle `db.batch()`](https://orm.drizzle.team/docs/batch-api) 문서를 참조하세요. - - - -## 데이터베이스에 변경 사항 푸시하기 - -개발 중에 변경한 내용을 데이터베이스에 푸시할 수 있습니다. - -### 테이블 스키마 푸시 - -프로젝트가 성장하면서 테이블 스키마는 시간이 지남에 따라 변경될 수 있습니다. 구성 변경 사항을 로컬에서 안전하게 테스트하고 배포할 때 원격 데이터베이스로 푸시할 수 있습니다. - -`astro db push --remote` 명령을 사용하여 CLI를 통해 로컬 스키마 변경 사항을 원격 데이터베이스로 푸시할 수도 있습니다. - - - - ```sh - npm run astro db push --remote - ``` - - - ```sh - pnpm astro db push --remote - ``` - - - ```sh - yarn astro db push --remote - ``` - - - -이 명령은 데이터 손실 없이 로컬 변경이 이루어질 수 있는지 확인하고 필요한 경우 충돌을 해결하기 위해 스키마를 안전하게 변경하는 방법을 제안합니다. - -#### 주요 스키마 변경 사항 푸시 - -:::danger -__이렇게 하면 데이터베이스가 파괴됩니다__. 프로덕션 데이터가 필요하지 않은 경우에만 이 명령을 수행하세요. -::: - -원격 데이터베이스에서 호스팅되는 기존 데이터와 호환되지 않는 방식으로 테이블 스키마를 변경해야 하는 경우 프로덕션 데이터베이스를 초기화해야 합니다. - -주요 변경 사항이 포함된 테이블 스키마 업데이트를 푸시하려면 `--force-reset` 플래그를 추가하여 모든 프로덕션 데이터를 초기화하세요. - - - - ```sh - npm run astro db push --remote --force-reset - ``` - - - ```sh - pnpm astro db push --remote --force-reset - ``` - - - ```sh - yarn astro db push --remote --force-reset - ``` - - - -### 테이블 이름 변경 - -스키마를 원격 데이터베이스로 푸시한 후 테이블 이름을 변경할 수 있습니다. - -**중요한 프로덕션 데이터가 없는** 경우 `--force-reset` 플래그를 사용하여 [데이터베이스를 초기화](#주요-스키마-변경-사항-푸시)할 수 있습니다. 이 플래그는 데이터베이스의 모든 테이블을 삭제하고 현재 스키마와 정확히 일치하는 새 테이블을 생성합니다. - -프로덕션 데이터를 보존하면서 테이블 이름을 변경하려면, 기존 기능을 중단하지 않는 변경을 수행하여 로컬 스키마를 원격 데이터베이스에 안전하게 푸시해야 합니다. - -다음 예시에서는 테이블의 이름을 `Comment`에서 `Feedback`으로 변경합니다. - - - -1. 데이터베이스 구성 파일에서 이름을 바꾸려는 테이블에 `deprecated: true` 속성을 추가하세요. - - ```ts title="db/config.ts" ins={2} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -2. 새 이름으로 새 테이블 스키마 (기존 테이블의 속성과 정확히 일치)를 추가합니다. - - ```ts title="db/config.ts" ins={8-14} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -3. `astro db push --remote` 명령을 사용하여 [원격 데이터베이스로 푸시](#테이블-스키마-푸시)합니다. 그러면 새 테이블이 추가되고 이전 테이블은 더 이상 사용되지 않는 것으로 표시됩니다. -4. 이전 테이블 대신 새 테이블을 사용하도록 로컬 프로젝트 코드를 업데이트하세요. 데이터를 새 테이블로 마이그레이션해야 할 수도 있습니다. -5. 이전 테이블이 프로젝트에서 더 이상 사용되지 않는다고 확신하면 `config.ts` 파일에서 스키마를 제거할 수 있습니다. - ```ts title="db/config.ts" del={1-7} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` -6. `astro db push --remote` 명령을 사용하여 원격 데이터베이스로 다시 푸시합니다. 이전 테이블은 삭제되고 이름이 변경된 새 테이블만 남습니다. - - -### 테이블 데이터 푸시 - -시드 또는 데이터 마이그레이션을 위해 원격 데이터베이스에 데이터를 푸시해야 할 수도 있습니다. 타입 안정성을 갖춘 쿼리를 작성하려면 `astro:db` 모듈을 사용하여 `.ts` 파일을 작성할 수 있습니다. 그런 다음 `astro db execute --remote` 명령을 사용하여 원격 데이터베이스에 대해 파일을 실행합니다. - -다음 Comments는 `astro db execute db/seed.ts --remote` 명령을 사용하여 시드할 수 있습니다. - -```ts -// db/seed.ts -import { Comment } from 'astro:db'; - -export default async function () { - await db.insert(Comment).values([ - { authorId: 1, body: 'Hope you like Astro DB!' }, - { authorId: 2, body: 'Enjoy!' }, - ]) -} -``` - - - -전체 명령 목록은 [CLI 참조](/ko/guides/integrations-guide/db/#astro-db-cli-참조)를 확인하세요. - - - -## Astro DB 통합 구축 - -[Astro 통합](/ko/reference/integrations-reference/)은 추가 Astro DB 테이블 및 시드 데이터를 사용하여 사용자 프로젝트를 확장할 수 있습니다. - -추가 Astro DB 구성 및 시드 파일을 등록하려면 `astro:db:setup` 후크에서 `extendDb()` 메서드를 사용하세요. -`defineDbIntegration()` 도우미는 `astro:db:setup` 후크에 대한 TypeScript 지원 및 자동 완성 기능을 제공합니다. - -```js {8-13} -// my-integration/index.ts -import { defineDbIntegration } from '@astrojs/db/utils'; - -export default function MyIntegration() { - return defineDbIntegration({ - name: 'my-astro-db-powered-integration', - hooks: { - 'astro:db:setup': ({ extendDb }) => { - extendDb({ - configEntrypoint: '@astronaut/my-package/config', - seedEntrypoint: '@astronaut/my-package/seed', - }); - }, - // 기타 통합 후크... - }, - }); -} -``` - -통합 [config](#데이터베이스-정의) 및 [seed](#개발-모드에서-데이터베이스-시드) 파일은 해당 사용자 정의 파일과 동일한 형식을 따릅니다. - -### 타입 안정성을 갖춘 통합 작업 - -통합 작업을 하는 동안, Astro에서 생성된 (`astro:db`에서 내보낸) 테이블 타입의 이점을 활용하지 못할 수도 있습니다. -완전한 타입 안정성을 위해 `asDrizzleTable()` 유틸리티를 사용하여 데이터베이스 작업에 사용할 수 있는 테이블 참조 객체를 생성하세요. - -예를 들어, 다음 `Pets` 데이터베이스 테이블을 설정하는 통합이 있다고 가정해 보겠습니다. - -```js -// my-integration/config.ts -import { defineDb, defineTable, column } from 'astro:db'; - -export const Pets = defineTable({ - columns: { - name: column.text(), - species: column.text(), - }, -}); - -export default defineDb({ tables: { Pets } }); -``` - -시드 파일은 `Pets`를 가져오고 `asDrizzleTable()`을 사용하여 타입 검사를 통해 테이블에 행을 삽입할 수 있습니다. - -```js {2,7} /typeSafePets(?! )/ -// my-integration/seed.ts -import { asDrizzleTable } from '@astrojs/db/utils'; -import { db } from 'astro:db'; -import { Pets } from './config'; - -export default async function() { - const typeSafePets = asDrizzleTable('Pets', Pets); - - await db.insert(typeSafePets).values([ - { name: 'Palomita', species: 'cat' }, - { name: 'Pan', species: 'dog' }, - ]); -} -``` - -`asDrizzleTable('Pets', Pets)`에 의해 반환된 값은 `import { Pets } from 'astro:db'`와 동일하지만, Astro의 타입 생성을 실행할 수 없는 경우에도 사용할 수 있습니다. -데이터베이스에 쿼리하거나 삽입해야 하는 모든 통합 코드에서 이를 사용할 수 있습니다. - - - - -## Astro Studio에서 Turso로 마이그레이션 - - - -1. [Studio 대시보드](https://studio.astro.build/)에서 마이그레이션하려는 프로젝트로 이동합니다. settings 탭에서 "Export Database" 버튼을 사용해 데이터베이스 덤프를 다운로드합니다. -2. 공식 지침에 따라 [Turso CLI를 설치](https://docs.turso.tech/cli/installation)하고, Turso 계정의 [가입 또는 로그인](https://docs.turso.tech/cli/authentication)을 진행합니다. -3. `turso db create` 명령을 사용하여 Turso에서 새 데이터베이스를 생성합니다. - ```sh - turso db create [database-name] - ``` -4. Turso CLI를 사용하여 데이터베이스 URL을 가져와서 환경 변수 `ASTRO_DB_REMOTE_URL`로 사용합니다. - ```sh - turso db show [database-name] - ``` - ```dotenv - ASTRO_DB_REMOTE_URL=[your-database-url] - ``` -5. 데이터베이스에 액세스할 수 있는 토큰을 생성하고 환경 변수 `ASTRO_DB_APP_TOKEN`으로 사용합니다. - ```sh - turso db tokens create [database-name] - ``` - ```dotenv - ASTRO_DB_APP_TOKEN=[your-app-token] - ``` -6. DB 스키마와 메타데이터를 새 Turso 데이터베이스로 푸시하세요. - ```sh - astro db push --remote - ``` -7. 1단계의 데이터베이스 덤프를 새 Turso DB로 가져옵니다. - ```sh - turso db shell [database-name] < ./path/to/dump.sql - ``` -8. 프로젝트가 새 데이터베이스에 연결되었음을 확인했으면 Astro Studio에서 프로젝트를 안전하게 삭제할 수 있습니다. - - diff --git a/src/content/docs/ko/guides/integrations-guide/db.mdx b/src/content/docs/ko/guides/integrations-guide/db.mdx deleted file mode 100644 index 81aa959436f3f..0000000000000 --- a/src/content/docs/ko/guides/integrations-guide/db.mdx +++ /dev/null @@ -1,399 +0,0 @@ ---- -type: integration -title: '@astrojs/db' -description: Astro 프로젝트에서 @astrojs/db 통합을 사용하는 방법을 알아보세요. -sidebar: - label: DB -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -category: other -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; - -:::caution[지원 중단] -Astro DB 통합은 Astro v6.5에서 지원이 중단되었으며 더 이상 유지 관리되지 않습니다. - -이 통합을 사용 중인 프로젝트라면, Astro 프로젝트에서 데이터베이스 클라이언트(예: Drizzle, Kysely)를 직접 사용하는 것을 권장합니다. -::: - -Astro DB는 Astro 생태계를 위해 설계된 완전 관리형 SQL 데이터베이스입니다. Astro에서 로컬로 개발하고 모든 [libSQL 호환 데이터베이스](/ko/guides/astro-db/)에 배포하세요. - -Astro DB를 사용하면 콘텐츠를 관계형 데이터베이스로 쿼리하고 모델링할 수 있는 강력하고 타입 안정성을 갖춘 로컬에서 동작하는 도구를 갖게 됩니다. - -전체 사용법과 예시는 [Astro DB 가이드](/ko/guides/astro-db/)를 참조하세요. - -## 설치 - -Astro에는 공식 통합 설정을 자동화하는 `astro add` 명령이 포함되어 있습니다. 원하는 경우 대신 [통합을 수동으로 설치](#수동-설치)할 수 있습니다. - -새 터미널 창에서 다음 명령 중 하나를 실행합니다. - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -#### 수동 설치 - -처음부터 직접 설정하려면 `astro add`를 건너뛰고 다음 지침에 따라 Astro DB를 직접 설치하세요. - -##### 1. 패키지 관리자를 통해 npm에서 통합 설치 - - - - ```shell - npm install @astrojs/db - ``` - - - ```shell - pnpm add @astrojs/db - ``` - - - ```shell - yarn add @astrojs/db - ``` - - - -##### 2. `astro.config.mjs` 파일에 통합 추가 - - ```js title="astro.config.mjs" ins={2,6} - import { defineConfig } from 'astro/config'; - import db from '@astrojs/db'; - - export default defineConfig({ - integrations: [ - db() - ] - }); - ``` - -##### 3. 데이터베이스 구성 - -프로젝트 루트에 `db/config.ts` 파일을 생성합니다. 이 파일은 Astro가 자동으로 로드하여 데이터베이스 테이블을 구성하는 데 사용되는 특수 파일입니다. - -```ts -// db/config.ts -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: {}, -}) -``` - -## 구성 - -### `mode` - -

- -**타입:** `'node' | 'web'`
-**기본값:** `'node'`
- -

- -프로덕션 환경에서 데이터베이스에 연결할 때 사용할 드라이버를 구성합니다. - -기본적으로 Astro DB는 프로덕션 배포에 Node.js 기반 libSQL 드라이버를 사용합니다. Node.js 런타임을 사용하는 대부분의 Astro 호스팅 또는 자체 호스팅 웹사이트에는 `node` 드라이버 모드로 충분합니다. 이를 통해 `memory:`, `file:`, `ws:`, `wss:`, `libsql`, `http`, `https` 등 여러 프로토콜을 통해 데이터베이스에 연결할 수 있으며, [임베디드 레플리카](/ko/guides/astro-db/#syncurl)와 같은 고급 기능도 사용할 수 있습니다. - -Cloudflare Workers나 Deno와 같은 Node.js가 아닌 런타임의 서버리스 환경에 배포할 경우, 웹 기반 libSQL 드라이버를 사용할 수 있습니다. `web` 모드를 사용하여 배포할 경우, `libsql`, `http`, `https`를 통해 웹 기반 연결을 설정할 수 있습니다. - -Node.js 환경이 아닌 경우 웹 libSQL 드라이버 모드를 사용하려면 어댑터 구성에서 `mode` 속성을 설정해야 합니다. - -```ts title="astro.config.mjs" ins={7} -import { defineConfig } from 'astro/config'; -import db from '@astrojs/db'; - -export default defineConfig({ - integrations: [ - db({ - mode: 'web' - }) - ] -}); -``` - -## 테이블 구성 참조 - -### `columns` - -

- -**타입:** `ColumnsConfig` -

- -테이블 열은 `columns` 객체를 사용하여 구성됩니다. - -```ts -import { defineTable, column, NOW } from 'astro:db'; - -const Comment = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - author: column.text(), - content: column.text({ optional: true }), - published: column.date({ default: NOW }), - }, -}); -``` - -열은 `column` 유틸리티를 사용하여 구성됩니다. `column`은 다음 타입을 지원합니다: - -- **`column.text(...)`** - 일반 또는 서식 있는 텍스트 콘텐츠 저장 -- **`column.number(...)`** - 정수 및 부동 소수점 값 저장 -- **`column.boolean(...)`** - 참/거짓 값 저장 -- **`column.date(...)`** - 데이터 저장을 위해 ISO 문자열로 구문 분석된 `Date` 객체를 저장 -- **`column.json(...)`** - 데이터 저장을 위해 문자열로 구문 분석된 임의의 JSON Blob을 저장 - -모든 열에는 몇 가지 공유 구성 값이 있습니다. - -- `primaryKey` - `number` 또는 `text` 열을 고유 식별자로 설정합니다. -- `optional` - Astro DB는 기본적으로 모든 열에 `NOT NULL`을 사용합니다. null 값을 허용하려면 `optional`을 `true`로 설정하세요. -- `default` - 새로 삽입된 항목의 기본값을 설정합니다. 이는 에 대해 정적 값이나 타임스탬프와 같이 생성된 값을 나타내는 `sql` 문자열을 허용합니다. -- `unique` - 열을 고유한 것으로 표시합니다. 이렇게 하면 테이블의 항목 전체에서 값이 중복되는 것을 방지할 수 있습니다. -- `references` - 각 열과 관련된 테이블을 참조합니다. 이는 외래 키 제약 조건을 설정합니다. 즉, 각 열 값은 참조된 테이블에서 일치하는 값을 가져야 합니다. - -`text` 열은 문자열 리터럴 목록을 선택적으로 정의하여 타입 생성을 위한 열거형의 역할을 수행할 수 있습니다. 그러나 **런타임 유효성 검사는 수행되지 않습니다.** 값 제거, 추가 및 변경은 프로젝트 코드에서 처리해야 합니다. - -```ts title="db/config.ts" {8} -import { defineTable, column } from 'astro:db'; - -// 테이블을 정의합니다. -const UserTable = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - rank: column.text({ enum: ['user', 'mod', 'admin'] }), - }, -}); - -// 결과 타입을 정의합니다. -type UserTableInferInsert = { - id?: string; - name: string; - rank: "user" | "mod" | "admin"; -} -``` - -### `indexes` - -

- -**타입:** `{ on: string | string[]; unique?: boolean | undefined; name?: string | undefined; }[]` -

- -테이블 인덱스는 특정 열 또는 열 조합에 대한 조회 속도를 향상시키는 데 사용됩니다. `indexes` 속성은 인덱스를 생성할 열을 지정하는 구성 객체의 배열을 값으로 전달받습니다. - -```ts title="db/config.ts" {9-11} -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - authorId: column.number(), - published: column.date(), - body: column.text(), - }, - indexes: [ - { on: ["authorId", "published"], unique: true }, - ] -}); -``` - -그러면 `authorId` 및 `published` 열에 `Comment_authorId_published_idx`라는 이름의 고유 인덱스가 생성됩니다. - -각 인덱스에 대해 다음 구성 옵션을 사용할 수 있습니다. - -- `on` - 인덱싱할 단일 열 또는 열 이름 배열입니다. -- `unique` (선택 사항) - 인덱스가 생성된 열 전체에 고유한 값을 적용하려면 `true`로 설정합니다. -- `name` (선택 사항) - 고유 인덱스의 사용자 정의 이름입니다. 이는 색인화되는 테이블 및 열 이름을 기반으로 Astro에서 생성된 이름을 재정의합니다 (예: `Comment_authorId_published_idx`). 사용자 정의 이름은 전역적이므로 인덱스 이름이 테이블 간에 충돌하지 않는지 확인하세요. - -### `foreignKeys` - -

- -**타입:** `{ columns: string | string[]; references: () => Column | Column[]; }[]` -

- -:::tip - -`foreignKeys`는 여러 테이블 열을 연결하기 위한 고급 API입니다. 단일 열만 참조해야 하는 경우 [열 `references` 속성](#columns)을 사용하세요. - -::: - -외래 키는 두 테이블 간 관계를 설정하는 데 사용됩니다. `foreignKeys` 속성은 테이블 간 하나 이상의 열을 연결할 수 있는 구성 객체의 배열을 허용합니다. - -```ts title="db/config.ts" {12-20} -import { defineTable, column } from 'astro:db'; - -const Author = defineTable({ - columns: { - firstName: column.text(), - lastName: column.text(), - }, -}); - -const Comment = defineTable({ - columns: { - authorFirstName: column.text(), - authorLastName: column.text(), - body: column.text(), - }, - foreignKeys: [ - { - columns: ["authorFirstName", "authorLastName"], - references: () => [Author.columns.firstName, Author.columns.lastName], - }, - ], -}); -``` - -각 외래 키 구성 객체는 다음 속성을 허용합니다. - -- `columns` - 참조된 테이블과 관련된 단일 열 또는 열 이름의 배열입니다. -- `references` - 참조된 테이블에서 단일 열 또는 열 배열을 반환하는 함수입니다. - -## Astro DB CLI 참조 - -Astro DB에는 로컬 및 libSQL 호환 데이터베이스와 상호 작용하는 CLI 명령 세트가 포함되어 있습니다. - -이러한 명령은 GitHub CI 액션을 사용할 때 자동으로 호출되며 `astro db` CLI를 사용하여 수동으로 호출할 수 있습니다. - -### `astro db push` - -**플래그:** - -- `--db-app-token ` `ASTRO_DB_APP_TOKEN` 대신 원격 데이터베이스 앱 토큰을 직접 제공합니다. -- `--dry-run` 생성된 SQL 문을 적용하지 않고 출력합니다. -- `--force-reset` 주요 스키마 변경이 필요한 경우 모든 프로덕션 데이터를 재설정합니다. -- `--remote` 로컬 데이터베이스 파일 대신 원격 데이터베이스에 푸시합니다. `ASTRO_DB_REMOTE_URL` 환경 변수를 설정해야 하며, `ASTRO_DB_APP_TOKEN`이 환경에 설정되어 있거나 `--db-app-token` 명령줄 인수로 값이 전달되어야 합니다. - -데이터베이스 구성 변경 사항을 프로젝트 데이터베이스에 안전하게 푸시합니다. 그러면 데이터 손실 위험이 있는지 확인하고 권장되는 마이그레이션 단계를 안내합니다. `--remote`를 사용하여 원격 데이터베이스에 변경 사항을 적용하세요. 주요 스키마 변경을 수행해야 하는 경우 `--force-reset`를 사용하여 모든 프로덕션 데이터를 재설정하세요. - -### `astro db verify` - -**플래그:** - -- `--db-app-token ` `ASTRO_DB_APP_TOKEN` 대신 원격 데이터베이스 앱 토큰을 직접 제공합니다. -- `--json` `verify`에서 기계가 읽을 수 있는 JSON 결과를 출력합니다. -- `--remote` 로컬 데이터베이스 파일 대신 원격 데이터베이스와 비교합니다. `ASTRO_DB_REMOTE_URL` 환경 변수가 설정되어 있어야 하며, `ASTRO_DB_APP_TOKEN`이 환경에 설정되어 있거나 `--db-app-token` 명령줄 인수로 값이 전달되어야 합니다. - -로컬 스키마를 원격 데이터베이스와 비교하여 로컬 및 원격 데이터베이스 구성 간의 차이점을 확인합니다. 이 명령은 `astro db push`에 의해 자동으로 실행됩니다. - -`verify`는 로컬 `db/config.ts` 파일을 원격 데이터베이스와 비교하고 변경 사항이 감지되면 경고합니다. 변경 사항이 필요하거나 안전하지 않은 경우 0이 아닌 코드로 종료되므로 CI에 유용합니다. - -### `astro db execute ` - -**플래그:** - -- `--db-app-token ` `ASTRO_DB_APP_TOKEN` 대신 원격 데이터베이스 앱 토큰을 직접 제공합니다. -- `--remote` libSQL 호환 데이터베이스에 대해 실행합니다. 로컬 데이터베이스 파일에 대해서는 실행을 생략합니다. `ASTRO_DB_REMOTE_URL` 환경 변수가 설정되어 있어야 하며, `ASTRO_DB_APP_TOKEN`이 환경에 설정되어 있거나 `--db-app-token` 명령줄 인수로 값이 전달되어야 합니다. - -데이터베이스를 읽거나 쓰려면 `.ts` 또는 `.js` 파일을 실행하세요. 이는 파일 경로를 인수로 받아들이고 `astro:db` 모듈을 사용하여 타입 안정성을 갖춘 쿼리를 작성할 수 있도록 지원합니다. libSQL 호환 데이터베이스에 대해 실행하려면 `--remote` 플래그를 사용하고, 로컬 데이터베이스 파일에 대해 실행하려면 플래그를 생략하세요. [개발 데이터를 시드](/ko/guides/astro-db/#개발-모드에서-데이터베이스-시드)하는 방법에 대한 예시 파일을 참조하세요. - -### `astro db shell --query ` - -**플래그:** - -- `--query` 실행할 원시 SQL 쿼리입니다. -- `--remote` libSQL 호환 데이터베이스에 대해 실행합니다. 로컬 데이터베이스 파일에 대해서는 실행을 생략합니다. `ASTRO_DB_REMOTE_URL` 환경 변수가 설정되어 있어야 하며, `ASTRO_DB_APP_TOKEN`이 환경에 설정되어 있거나 `--db-app-token` 명령줄 인수로 값이 전달되어야 합니다. - -데이터베이스에 대해 원시 SQL 쿼리를 실행합니다. - -다음 예시는 원격 데이터베이스의 `Comment` 테이블에서 모든 행을 선택합니다. - -```sh -npx astro db shell --query "SELECT * FROM Comment;" --remote -``` - -## Astro DB 유틸리티 참조 - -다음 유틸리티는 `astro:db` 모듈에서 가져옵니다: - -```ts -import { - isDbError, - getDbError -} from "astro:db"; -``` - -### `isDbError()` - -

- -**타입:** `(err: unknown) => boolean`
- -

- -오류가 libSQL 데이터베이스 예외인지 확인합니다. 여기에는 참조 사용 시 외래 키 제약 조건 오류가 포함되거나 데이터 삽입 시 필드 누락이 포함될 수 있습니다. `isDbError()`를 try / catch 블록과 결합하여 애플리케이션의 데이터베이스 오류를 처리할 수 있습니다. - -```ts title="src/pages/api/comment/[id].ts" "idDbError" -import { db, Comment, isDbError } from 'astro:db'; -import type { APIRoute } from 'astro'; - -export const POST: APIRoute = (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - if (isDbError(e)) { - return new Response(`Cannot insert comment with id ${id}\n\n${e.message}`, { status: 400 }); - } - return new Response('An unexpected error occurred', { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; -``` - -### `getDbError()` - -

- -**타입:** `(err: unknown) => LibsqlError | undefined`
- -

- -오류의 원인을 탐색하여 기저에 있는 libSQL 데이터베이스 예외를 찾습니다. 이 함수는 `LibsqlError`를 반환하거나, 오류가 libSQL에서 발생한 것이 아니면 `undefined`를 반환합니다. 이는 다른 오류(예: `DrizzleQueryError`)가 데이터베이스 오류를 감싸고 있을 때 유용합니다. - -다음 예시는 발생한 예외에서 데이터베이스 오류를 추출하고 응답에 오류 코드와 메시지를 반환합니다. - -```ts title="src/pages/api/comment/[id].ts" "getDbError" -import { getDbError } from 'astro:db'; - -export const POST: APIRoute = (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - const dbError = getDbError(e); - if (dbError) { - return new Response(`Database error: ${dbError.code}\n\n${dbError.message}`, { status: 400 }); - } - return new Response('An unexpected error occurred', { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; -``` diff --git a/src/content/docs/ko/reference/cli-reference.mdx b/src/content/docs/ko/reference/cli-reference.mdx index eee22f90d8b9f..887919ac9c594 100644 --- a/src/content/docs/ko/reference/cli-reference.mdx +++ b/src/content/docs/ko/reference/cli-reference.mdx @@ -266,7 +266,6 @@ check 명령을 실행할 다른 루트 디렉터리를 지정합니다. 기본 모든 Astro 모듈에 대한 TypeScript 타입을 생성합니다. 이는 타입 추론을 위한 [`.astro/types.d.ts` 파일](/ko/guides/typescript/#설정)을 설정하고 생성된 타입에 의존하는 기능에 대한 모듈을 정의합니다. - `astro:content` [콘텐츠 컬렉션 API](/ko/guides/content-collections/)를 위한 모듈 -- `astro:db` [Astro DB](/ko/guides/astro-db/)를 위한 모듈 - [실험적 Astro Env](/ko/guides/environment-variables/)를 위한 `astro:env` 모듈 - [Astro Actions](/ko/guides/actions/)를 위한 `astro:actions` 모듈 diff --git a/src/content/docs/ko/reference/experimental-flags/advanced-routing.mdx b/src/content/docs/ko/reference/experimental-flags/advanced-routing.mdx deleted file mode 100644 index baa7ada2db807..0000000000000 --- a/src/content/docs/ko/reference/experimental-flags/advanced-routing.mdx +++ /dev/null @@ -1,529 +0,0 @@ ---- -title: 실험적인 고급 라우팅 -sidebar: - label: 고급 라우팅 -i18nReady: true ---- - -import Since from '~/components/Since.astro' - -

- -**타입:** `boolean`
-**기본값:** `false`
- -

- -`src/app.ts`를 사용자 정의 요청 파이프라인의 진입점으로 활성화하여, Astro가 들어오는 요청을 처리하는 방식을 완전히 제어할 수 있습니다. - -기본적으로 Astro는 트레일링 슬래시 정규화, 리다이렉트, 세션, 액션, 사용자 미들웨어, 페이지 렌더링, i18n, 캐싱을 정해진 순서대로 실행하는 내장 파이프라인으로 모든 요청을 처리합니다. 고급 라우팅을 사용하면 이 파이프라인을 직접 구현한 것으로 대체할 수 있으며, Astro의 내장 핸들러 함수를 원하는 순서로 조합하고 그 사이에 사용자 정의 로직을 추가할 수 있습니다. - -```js title="astro.config.mjs" -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - experimental: { - advancedRouting: true, - }, -}); -``` - -## `src/app.ts` 생성하기 - -`advancedRouting`이 활성화되면, `fetch` 메서드를 포함한 객체를 기본 내보내기(default export)하는 `src/app.ts`(또는 `.js`, `.mjs`, `.mts`) 파일을 생성하세요. `fetch` 메서드는 표준 [Request](https://developer.mozilla.org/ko/docs/Web/API/Request) 객체를 받고 [Response](https://developer.mozilla.org/ko/docs/Web/API/Response)를 반환해야 합니다. - -`src/app.ts` 파일이 없거나 `advancedRouting`이 활성화되지 않은 경우, Astro는 모든 기능을 자동으로 실행하는 내장 파이프라인을 사용합니다. - -`astro`에서 `Fetchable` 타입을 선택적으로 가져와 진입점의 타입을 검사할 수 있습니다: - -```ts title="src/app.ts" -import type { Fetchable } from 'astro'; - -export default { - async fetch(request: Request): Promise { - // ... - }, -} satisfies Fetchable; -``` - -### 진입점 파일 사용자 지정 - -기본적으로 Astro는 고급 라우팅 진입점으로 `src/app.ts` 파일을 사용합니다. 다른 파일을 사용하려면 `fetchFile` 옵션이 포함된 객체를 `advancedRouting`에 전달하세요: - -```js title="astro.config.mjs" -export default defineConfig({ - experimental: { - advancedRouting: { - fetchFile: 'fetch.ts', - }, - }, -}); -``` - -이 구성을 사용하면 Astro는 `src/app.ts` 대신 `src/fetch.ts` 파일을 사용합니다. - -`fetchFile`을 `null`로 설정하면 진입점을 완전히 비활성화할 수 있습니다. 이는 `src/app.ts` 파일을 이미 다른 용도로 사용하고 있는 경우에 유용합니다: - -```js title="astro.config.mjs" -export default defineConfig({ - experimental: { - advancedRouting: { - fetchFile: null, - }, - }, -}); -``` - -### `astro()` 사용하기 - -가장 쉬운 시작 방법은 [`astro()` 핸들러](#astro)를 사용하는 것입니다. 이 핸들러는 Astro의 전체 내장 파이프라인(세션, 캐시, 리다이렉트, 트레일링 슬래시, 액션, 미들웨어, 페이지, i18n)을 기본 순서대로 실행합니다. 이를 통해 내부 파이프라인의 동작 방식을 변경하지 않고도 Astro 파이프라인 실행 전후에 사용자 정의 로직을 추가할 수 있습니다: - -```ts title="src/app.ts" -import { FetchState, astro } from 'astro/fetch'; - -export default { - async fetch(request: Request): Promise { - const state = new FetchState(request); - - // Astro 핸들러 전에 실행되는 사용자 정의 전처리 로직 - const url = new URL(request.url); - if (url.pathname.startsWith('/dashboard')) { - const cookie = request.headers.get('cookie') ?? ''; - if (!cookie.includes('session=')) { - return new Response(null, { - status: 302, - headers: { Location: '/login' }, - }); - } - } - - const response = await astro(state); - - // Astro 렌더링 후에 실행되는 사용자 정의 후처리 로직 - response.headers.set('X-Powered-By', 'Astro'); - return response; - }, -}; -``` - -인증 가드 추가, 요청 로깅, 사용자 정의 헤더 추가와 같은 대부분의 사용 사례에서는 `astro()`만으로 충분합니다. - -### 개별 핸들러 조합하기 - -파이프라인 순서를 더 세밀하게 제어하거나 특정 기능을 완전히 제외하고 싶은 경우, `astro/fetch`에서 제공하는 개별 핸들러 함수를 조합할 수 있습니다: - -```ts title="src/app.ts" -import { - FetchState, - sessions, - actions, - middleware, - pages, - i18n, -} from 'astro/fetch'; - -export default { - async fetch(request: Request): Promise { - const state = new FetchState(request); - await sessions(state); - try { - const actionResponse = await actions(state); - if (actionResponse) return actionResponse; - - const response = await middleware(state, (s) => pages(s)); - return i18n(state, response); - } finally { - await state.finalizeAll(); - } - }, -}; -``` - -각 함수는 일치하는 경로, 쿠키, 세션과 같은 요청별 데이터를 추적하는 [`FetchState` 객체](#fetchstate)를 기반으로 동작합니다. 이를 원하는 순서대로 호출하고 사용자 정의 로직과 함께 사용할 수 있습니다. - -## 사용자 정의 로직 추가하기 - -고급 라우팅의 주요 이점은 요청 파이프라인의 어느 위치에든 사용자 정의 로직을 삽입할 수 있다는 점입니다. Astro가 요청을 처리하기 전, 파이프라인 단계 사이, 또는 응답이 생성된 후에 코드를 실행할 수 있습니다. - -[`astro()` 핸들러](#astro)는 전체 파이프라인 전후에 전처리 또는 후처리를 추가하는 가장 간단한 방법입니다. 액션 실행 후 페이지 렌더링 전과 같이 특정 단계 *사이*에 로직을 삽입해야 하는 경우에는 대신 개별 핸들러를 조합하세요: - -```ts title="src/app.ts" -import { - FetchState, - actions, - middleware, - pages, - i18n, -} from 'astro/fetch'; - -export default { - async fetch(request: Request): Promise { - const state = new FetchState(request); - - const actionResponse = await actions(state); - if (actionResponse) return actionResponse; - - // 액션과 페이지 렌더링 사이의 사용자 정의 로직 - console.log(`Rendering ${new URL(request.url).pathname}`); - - const response = await middleware(state, (s) => pages(s)); - return i18n(state, response); - }, -}; -``` - -## `App.Providers`를 사용하여 사용자 정의 프로바이더 타입 지정하기 - -[`state.provide()`](#stateprovide)를 사용하여 사용자 정의 컨텍스트 프로바이더를 등록할 때, `App.Providers` 인터페이스를 사용하여 해당 타입을 선언할 수 있습니다. 이를 통해 컴포넌트와 미들웨어에서 `Astro`와 `ctx`의 타입이 완벽하게 지정됩니다: - -```ts title="src/env.d.ts" -declare namespace App { - interface Providers { - oauth: import('./lib/oauth').OAuthSession; - } -} -``` - -프로바이더를 선언하면 `ctx.oauth` (및 `.astro` 파일의 `Astro.oauth`)의 타입이 자동으로 지정됩니다. - -## `astro/fetch` 핸들러 참조 - -모든 핸들러 함수는 `astro/fetch`에서 가져오며 `FetchState` 객체를 기반으로 동작합니다. - -### `FetchState` - -요청별 상태 객체입니다. `fetch` 메서드 시작 부분에서 생성하세요: - -```ts -import { FetchState } from 'astro/fetch'; - -const state = new FetchState(request); -``` - -`FetchState`는 일치하는 경로, 쿠키, 세션 프로바이더 및 기타 요청별 데이터를 추적합니다. 모든 핸들러 함수는 이를 첫 번째 인자로 사용합니다. - -#### 속성 - -##### `state.request` - -**타입:** `Request` - -수신된 [Request](https://developer.mozilla.org/ko/docs/Web/API/Request) 객체입니다. - -##### `state.url` - -**타입:** `URL` - -요청에서 파생된 정규화된 [URL](https://developer.mozilla.org/ko/docs/Web/API/URL)입니다. - -##### `state.pathname` - -**타입:** `string` - -기본 경로가 제거되고 디코딩된 요청 경로입니다 (예: `/about` 또는 `/blog/my-post`). - -##### `state.routeData` - -**타입:** `RouteData | undefined` - -이 요청과 일치하는 경로 데이터입니다(있는 경우). 이는 `FetchState`가 생성될 때 자동으로 결정됩니다. - -##### `state.cookies` - -**타입:** `AstroCookies` - -이 요청의 쿠키를 읽고 설정하기 위한 [`AstroCookies`](/ko/reference/api-reference/#cookies) 인스턴스입니다. - -##### `state.locals` - -**타입:** `App.Locals` - -사용자 정의 데이터를 저장하기 위한 요청 범위의 객체입니다. 이는 [미들웨어](/ko/guides/middleware/) 및 [API 경로](/ko/guides/endpoints/#서버-엔드포인트-api-라우트)에서 사용할 수 있는 `locals` 객체와 동일합니다. - -##### `state.params` - -**타입:** `Params | undefined` - -일치하는 경로와 요청 경로에서 파생된 경로 매개변수입니다 (예: `[slug].astro` 경로의 경우 `{ slug: 'my-post' }`). - -##### `state.status` - -

- -**타입:** `number`
-**기본값:** `200` -

- -응답의 HTTP 상태 코드입니다. 렌더링 전에 이를 설정하여 응답 상태를 제어할 수 있습니다 (예: `state.status = 404`). - -##### `state.response` - -

- -**타입:** `Response | undefined`
-**기본값:** `undefined` -

- -렌더링이 완료된 후 핸들러에 의해 생성된 `Response`입니다. 이는 [`pages()`](#pages) 및 [`middleware()`](#middleware)에 의해 자동으로 설정되어, 파이프라인의 뒷부분에서 응답을 검사하거나 사용할 수 있게 해줍니다: - -```ts -const response = await middleware(state, (s) => pages(s)); -// 이제 state.response는 response와 동일한 객체입니다 -``` - -#### 메서드 - -##### `state.rewrite()` - -

- -**타입:** (payload: RewritePayload) => Promise\ -

- -다른 경로로 [리라이트](/ko/guides/routing/#url-재작성-rewrites)를 수행합니다. `payload`는 경로 문자열(`'/other-page'`), URL 또는 `Request`가 될 수 있습니다: - -```ts -const response = await state.rewrite('/other-page'); -``` - -##### `state.provide()` - -

- -**타입:** `(key: string, provider: ContextProvider) => void` -

- -지정된 키 아래에 컨텍스트 프로바이더를 등록합니다. 프로바이더의 `create()` 함수는 [`state.resolve()`](#stateresolve)가 처음 호출될 때 지연 호출되며, 선택적인 `finalize()` 콜백은 [`state.finalizeAll()`](#statefinalizeall) 실행 중 호출됩니다: - -```ts -state.provide('myService', { - create: () => new MyService(), - finalize: (service) => service.close(), -}); -``` - -##### `state.resolve()` - -

- -**타입:** `(key: string) => T | undefined` -

- -이전에 등록된 프로바이더의 값을 반환하며, 첫 접근 시 `create` 함수를 호출합니다. 해당 키로 등록된 프로바이더가 없으면 `undefined`를 반환합니다: - -```ts -const service = state.resolve('myService'); -``` - -##### `state.finalizeAll()` - -

- -**타입:** `() => Promise | void` -

- -등록된 모든 프로바이더의 `finalize` 콜백을 실행합니다. 세션 데이터를 저장하고 리소스를 정리하기 위해 일반적으로 `finally` 블록에서 응답 생성 후 이 메서드를 호출합니다: - -```ts -await sessions(state); -try { - // ...렌더 파이프라인... - return response; -} finally { - await state.finalizeAll(); -} -``` - -### `astro()` - -

- -**타입:** (state: FetchState) => Promise\ -

- -Astro의 전체 파이프라인(세션, 캐시, 리다이렉트, 트레일링 슬래시, 액션, 미들웨어, 페이지, i18n)을 기본 순서대로 실행하는 올인원 핸들러입니다. 내부 파이프라인 순서를 변경하지 않고 Astro 파이프라인 실행 전후에 로직을 추가하고 싶을 때 사용하세요: - -```ts title="src/app.ts" -import { FetchState, astro } from 'astro/fetch'; - -export default { - async fetch(request: Request): Promise { - const state = new FetchState(request); - // 사용자 정의 전처리... - const response = await astro(state); - // 사용자 정의 후처리... - return response; - }, -}; -``` - -### `pages()` - -

- -**타입:** (state: FetchState) => Promise\ -

- -요청을 일치하는 Astro 경로(페이지, 엔드포인트 또는 폴백)로 전달합니다. 이는 핵심 렌더링 핸들러이며, 대부분의 사용자 정의 파이프라인에서 사용됩니다. - -### `middleware()` - -

- -**타입:** (state: FetchState, next: (state: FetchState) => Promise\) => Promise\ -

- -Astro의 미들웨어 체인(`src/middleware.ts`에서 정의)을 실행합니다. `next` 콜백은 체인의 마지막에서 응답을 생성하기 위해 호출되며, 일반적으로 `pages()`를 호출합니다: - -```ts -const response = await middleware(state, (s) => pages(s)); -``` - -### `actions()` - -

- -**타입:** (state: FetchState) => Promise\ | undefined -

- -[Astro 액션](/ko/guides/actions/)(RPC 및 폼 제출)을 처리합니다. RPC 액션에 대해서는 `Response`를 반환하고, 폼 액션 및 액션이 아닌 요청에 대해서는 `undefined`를 반환합니다. 반환 값을 확인하여 렌더링을 계속할지 결정하세요: - -```ts -const actionResponse = await actions(state); -if (actionResponse) return actionResponse; -// 그렇지 않으면 페이지 렌더링을 계속합니다... -``` - -### `sessions()` - -

- -**타입:** (state: FetchState) => Promise\ | void -

- -[세션](/ko/guides/sessions/) 프로바이더를 등록합니다. 세션은 코드에서 `ctx.session`에 접근할 때 지연 생성되며, `state.finalizeAll()`이 호출될 때 저장됩니다. 파이프라인 초기에 이를 호출하고, `finally` 블록에서 `finalizeAll()`을 호출하세요: - -```ts -await sessions(state); -try { - // ...렌더 파이프라인... -} finally { - await state.finalizeAll(); -} -``` - -### `i18n()` - -

- -**타입:** (state: FetchState, response: Response) => Promise\ -

- -[i18n 설정](/ko/guides/internationalization/)에 따라 응답을 후처리합니다. 로케일 리다이렉트, 유효하지 않은 로케일에 대한 404 처리 및 폴백 라우팅을 처리합니다. 렌더링 후에 이를 호출하세요: - -```ts -const response = await middleware(state, (s) => pages(s)); -return i18n(state, response); -``` - -### `redirects()` - -

- -**타입:** (state: FetchState) => Promise\ | undefined -

- -[Astro 설정](/ko/reference/configuration-reference/#redirects)에 정의된 리다이렉트 경로를 처리합니다. 일치하는 경로가 리다이렉트인 경우 리다이렉트 `Response`를 반환하고, 그렇지 않으면 호출자가 처리를 계속할 수 있도록 `undefined`를 반환합니다. - -### `cache()` - -

- -**타입:** (state: FetchState, next: () => Promise\) => Promise\ -

- -렌더링 콜백을 [캐시](/ko/reference/experimental-flags/route-caching/) 프로바이더 로직으로 래핑합니다. 런타임 캐싱, CDN 기반 프로바이더 및 캐시가 없는 경우를 처리합니다. - -### `trailingSlash()` - -

- -**타입:** (state: FetchState) => Response | undefined -

- -요청 경로에 [트레일링 슬래시](/ko/reference/configuration-reference/#trailingslash) 정규화가 필요한지 확인하고, 필요한 경우 리다이렉트 `Response`를 반환합니다. 리다이렉트가 필요하지 않으면 `undefined`를 반환합니다. - -## Hono와 함께 사용하기 - -Astro는 또한 `astro/hono`를 통해 모든 핸들러 함수에 대한 Hono 호환 래퍼를 제공합니다. [Hono](https://hono.dev/)를 라우팅 프레임워크로 사용하고 싶다면 `src/app.ts`에서 Hono 앱을 내보낼 수 있습니다: - -```ts title="src/app.ts" -import { Hono } from 'hono'; -import { logger } from 'hono/logger'; -import { actions, middleware, pages, i18n } from 'astro/hono'; - -const app = new Hono(); - -// Hono 미들웨어 -app.use(logger()); - -// Hono 미들웨어로 사용하는 Astro 핸들러 -app.use(actions()); -app.use(middleware()); -app.use(pages()); -app.use(i18n()); - -export default app; -``` - -`astro/hono` 모듈은 `astro/fetch`와 동일한 핸들러 이름(`astro`, `pages`, `middleware`, `actions`, `sessions`, `redirects`, `cache`, `i18n`, `trailingSlash`)을 내보내지만, 각각은 Hono 미들웨어 함수를 반환합니다. 이를 통해 Astro 핸들러를 Hono 생태계의 다양한 미들웨어와 함께 사용할 수 있습니다. - -## Cloudflare 어댑터 - -[`@astrojs/cloudflare`](/ko/guides/integrations-guide/cloudflare/) 어댑터는 고급 라우팅 파이프라인에 Cloudflare 관련 설정을 적용하는 보조 핸들러를 제공합니다. 이 핸들러들은 세션 KV 바인딩 주입, `ASSETS` 바인딩을 통한 정적 자산 제공, `Astro.locals.cfContext`, `cf-connecting-ip` 헤더에서 클라이언트 주소를 가져오는 기능, `waitUntil`, 그리고 사전 렌더링된 오류 페이지 로드를 구성합니다. - -Cloudflare에서는 이 핸들러 없이도 `src/app.ts`의 `astro/fetch` 및 `astro/hono` API를 사용할 수 있습니다. 어댑터의 기본 진입점이 Cloudflare 관련 설정을 자동으로 처리하기 때문입니다. 이러한 보조 핸들러는 예를 들어 Durable Object를 내보내기 위해 이미 [사용자 정의 워커 진입점](https://developers.cloudflare.com/workers/wrangler/configuration/#inheritable-keys)(`src/worker.ts`)을 사용하고 있으며, 해당 파일에서 직접 고급 라우팅 API를 사용하려는 경우에 유용합니다. - -워커 진입점에서 이 핸들러를 사용하면 어댑터의 기본 핸들러 기능을 대체하게 되므로 둘을 동시에 사용해서는 안 됩니다. 파이프라인의 나머지 부분에서 바인딩과 locals를 사용할 수 있도록 Cloudflare 핸들러를 다른 Astro 핸들러보다 먼저 배치하세요. - -### `@astrojs/cloudflare/fetch` - -

- -`astro/fetch`와 함께 사용합니다. `cf()` 함수는 `FetchState`, Cloudflare의 `env`, 그리고 `ExecutionContext`를 인자로 받습니다. 정적 자산 요청에 대해서는 `Response`를 반환하고, 요청이 Astro 렌더링으로 계속 처리되어야 하는 경우에는 `undefined`를 반환합니다. - -```ts title="src/worker.ts" -import { astro, FetchState } from 'astro/fetch'; -import { cf } from '@astrojs/cloudflare/fetch'; - -export default { - async fetch(request: Request, env: Env, ctx: ExecutionContext) { - const state = new FetchState(request); - const asset = await cf(state, env, ctx); - if (asset) return asset; - return astro(state); - }, -}; -``` - -### `@astrojs/cloudflare/hono` - -

- -`astro/hono`와 함께 사용합니다. `cf()` 함수는 Hono 컨텍스트에서 `env`와 `executionCtx`를 자동으로 읽어오는 Hono 미들웨어를 반환합니다: - -```ts title="src/worker.ts" -import { Hono } from 'hono'; -import { actions, middleware, pages, i18n } from 'astro/hono'; -import { cf } from '@astrojs/cloudflare/hono'; - -const app = new Hono<{ Bindings: Env }>(); - -app.use(cf()); -app.use(actions()); -app.use(middleware()); -app.use(pages()); -app.use(i18n()); - -export default app; -``` diff --git a/src/content/docs/ko/reference/experimental-flags/logger.mdx b/src/content/docs/ko/reference/experimental-flags/logger.mdx deleted file mode 100644 index d3930e138a7c0..0000000000000 --- a/src/content/docs/ko/reference/experimental-flags/logger.mdx +++ /dev/null @@ -1,328 +0,0 @@ ---- -title: 실험적 로거 -sidebar: - label: 로거 -i18nReady: true ---- - -import Since from '~/components/Since.astro'; - -

- -**타입:** `object`
-**기본값:** `undefined`
- -

- -사용자가 제어할 수 있는 실험적인 커스텀 로거를 활성화합니다. - -이 설정이 제공되면 사용자는 Astro에서 내보내는 로그를 완전히 제어할 수 있습니다. 또한 이 기능에는 새로운 `logHandlers`를 통해 사용할 수 있는 몇 가지 내장 로거가 포함되어 있습니다. - -다음 예시는 가독성 있는 출력 형식을 사용하는 내장 JSON 로거를 활성화합니다. - -```js title="astro.config.mjs" {5} ins="logHandlers" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.json({ pretty: true }) - } -}); -``` - -또는 `--experimentalJson` 플래그를 사용하면 `dev`, `build`, `sync` 명령어 실행 시 JSON 로깅을 사용할 수 있습니다. - -```shell -astro dev --experimentalJson -astro sync --experimentalJson -astro build --experimentalJson -``` - - -## 내장 로거 - -이 기능에는 세 가지 내장 로거가 포함되어 있습니다. - -### `logHandlers.json` - -메시지를 JSON 형식으로 출력하는 로거입니다. 로그는 다음과 같은 형태입니다. -```json -{ "message": "", "label": "router", "level": "info", "time": "" } -``` - -#### JSON 로거 옵션 - -

-**타입:** `{ pretty: boolean; level: AstroLoggerLevel; }`
-**기본값:** `{ pretty: false, level: 'info' }` - -

- -`json` 로거는 다음 옵션을 허용합니다. - -- `pretty`: `true`일 경우 JSON 로그가 여러 줄로 출력됩니다. 기본값은 `false`입니다. -- `level`: 출력할 로그의 [레벨](#로그-레벨)입니다. - -```js title="astro.config.mjs" {5} ins="json" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.json({ pretty: true }) - } -}); -``` - -### `logHandlers.console` - -`console`을 출력 대상으로 사용하는 로거입니다. 메시지 레벨에 따라 서로 다른 채널을 사용합니다. - -- `error` 메시지는 `console.error()`를 사용하여 출력됩니다. -- `warn` 메시지는 `console.warn()`을 사용하여 출력됩니다. -- `info` 메시지는 `console.info()`를 사용하여 출력됩니다. - -#### Console 로거 옵션 - -

-**타입:** `{ level: AstroLoggerLevel }`
-**기본값:** `{ level: 'info' }` - -

- -`console` 로거는 다음 옵션을 허용합니다. - -- `level`: 출력할 로그의 [레벨](#로그-레벨)입니다. - -```js title="astro.config.mjs" {5} ins="console" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.console({ level: 'warn' }) - } -}); -``` - -### `logHandlers.node` - -메시지를 [`process.stdout`](https://nodejs.org/api/process.html#processstdout) 및 [`process.stderr`](https://nodejs.org/api/process.html#processstderr)로 출력하는 로거입니다. `error` 레벨 메시지는 `stderr`로 출력되며, 나머지는 `stdout`으로 출력됩니다. - -Astro의 기본 로거입니다. - -#### Node 로거 옵션 - -

-**타입:** `{ level: AstroLoggerLevel }`
-**기본값:** `{ level: 'info' }` - -

- -`node` 로거는 다음 옵션을 허용합니다. - -- `level`: 출력할 로그의 [레벨](#로그-레벨)입니다. - -```js title="astro.config.mjs" {5} ins="node" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.node({ level: 'warn' }) - } -}); -``` - -### `logHandlers.compose` - -여러 로거를 임의의 순서로 구성할 수 있게 해주는 특별한 함수입니다. 동일한 메시지가 모든 로거에 전달됩니다. - -다음 예시는 기본 로그 레벨을 사용하여 콘솔 로거와 JSON 로거를 조합합니다. - -```js title="astro.config.mjs" -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.compose( - logHandlers.console(), - logHandlers.json() - ) - } -}); -``` - -## 커스텀 로거 - -`logger` 설정에 적절한 구성을 제공하여 커스텀 로거를 만들 수 있습니다. 이 설정은 로거가 내보내지는 모듈을 지정하는 필수 `entrypoint`와 로거에 전달할 선택적 구성을 포함한 객체를 사용합니다. 구성은 직렬화 가능해야 합니다. - -로거 함수는 `default`로 내보내야 합니다. - -커스텀 로거를 정의하면 Astro에서 출력하는 로그를 포함한 모든 로그를 직접 관리하게 됩니다. - -다음 예시는 `@org/custom-logger` 패키지에서 내보내는 커스텀 로거를 정의하며, 로깅 `level`을 구성하기 위한 하나의 매개변수만 받습니다. - -```js title="astro.config.mjs" -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: { - entrypoint: "@org/custom-logger", - config: { - level: "warn" - } - } - } -}); -``` - -다음 예시는 필수 `write()` 함수를 포함하는 [`AstroLoggerDestination` 객체](#astrologgerdestination)를 반환하는 최소한의 로거를 구현합니다. - -```ts title="@org/custom-logger/index.ts" -import type { - AstroLoggerLevel, - AstroLoggerDestination, - AstroLoggerMessage -} from "astro"; -import { matchesLevel } from "astro/logger"; - -type LoggerOptions = { - level: AstroLoggerLevel -} - -function orgLogger(options: LoggerOptions = {}): AstroLoggerDestination { - const { level = 'info' } = options; - return { - write(message: AstroLoggerMessage) { - // 이 유틸리티를 사용하여 메시지를 출력해야 하는지 확인합니다. - if (matchesLevel(message.level, level)) { - // 메시지를 적절한 위치에 기록하고 로그 레벨을 반영합니다. - } - } - } -} - -export default orgLogger; -``` - -## 런타임 - -이제 [컨텍스트 객체](/ko/reference/api-reference/#컨텍스트-객체)는 다음 함수를 포함하는 `logger` 객체를 노출합니다. - -- `error()`: `error` 레벨의 메시지를 내보냅니다. -- `warn()`: `warn` 레벨의 메시지를 내보냅니다. -- `info()`: `info` 레벨의 메시지를 내보냅니다. - -```astro ---- -Astro.logger.error("에러입니다"); -Astro.logger.warn("경고입니다"); -Astro.logger.info("정보입니다"); ---- -``` - -## 로그 레벨 - -레벨은 각 메시지에 할당되는 내부적인 점수입니다. 로거가 특정 레벨로 구성되면 해당 레벨 이상인 메시지만 출력됩니다. - -가장 높은 점수부터 가장 낮은 점수까지 세 가지 레벨이 있습니다. -1. `error` -2. `warn` -3. `info` - -다음 예시는 JSON 로거가 `warn` 레벨 이상의 메시지만 출력하도록 구성합니다. - -```js title="astro.config.mjs" {5} ins='level: "warn"' -import { defineConfig, logHandlers } from 'astro/config'; - -export default defineConfig({ - experimental: { - logger: logHandlers.json({ level: "warn" }) - } -}); -``` - -`astro/logger` 패키지는 로그 레벨을 확인하기 위해 [`matchesLevel()`](#matcheslevel) 헬퍼를 노출합니다. 이는 [커스텀 로거를 빌드할 때](#커스텀-로거) 유용할 수 있습니다. - -```js -import { matchesLevel } from "astro/logger"; - -matchesLevel("error", "info"); -``` - - -## 타입 참조 - -다음 타입은 `astro` 식별자에서 가져올 수 있습니다. - -### `AstroLoggerDestination` - -커스텀 로거가 구현해야 하는 인터페이스입니다. - -#### `AstroLoggerDestination.write()` - -

- -**타입:** `(message: AstroLoggerMessage) => void` -

- -각 로그에 대해 호출되는 필수 메서드이며 [`AstroLoggerMessage`](#astrologgermessage)를 인자로 받습니다. - -#### `AstroLoggerDestination.flush()` - -

- -**타입:** `() => Promise | void` -

- -각 요청이 끝날 때 호출되는 선택적 함수입니다. 출력 대상과의 연결을 유지하면서 로그 메시지를 플러시해야 하는 고급 로거에 유용합니다. - -#### `AstroLoggerDestination.close()` - -

- -**타입:** `() => Promise | void` -

- -서버가 종료되기 전에 호출되는 선택적 함수입니다. 이 함수는 일반적으로 `@astrojs/node`와 같은 어댑터에 의해 호출됩니다. - -### `AstroLoggerLevel` - -메시지 레벨입니다. 사용 가능한 레벨은 다음과 같습니다. -- `'debug'` -- `'info'` -- `'warn'` -- `'error'` -- `'silent'` - -### `AstroLoggerMessage` - -

- -**타입:** `{ label: string | null; level: AstroLoggerLevel; message: string; newLine: boolean; }` -

-[`AstroLoggerDestination.write()`](#astrologgerdestinationwrite) 함수로부터 들어오는 객체입니다. -- `message`: 로깅되는 메시지입니다. -- `level`: 메시지의 레벨입니다. -- `label`: 로그 메시지에 할당된 임의의 레이블입니다. -- `newLine`: 이 메시지가 후행 줄바꿈을 추가해야 하는지 여부입니다. - -## API 참조 - -다음 API는 `astro/logger` 식별자에서 가져올 수 있습니다. - -### `matchesLevel` - -

- -**타입:** `matchesLevel(messageLevel: AstroLoggerLevel, configuredLevel: AstroLoggerLevel) => boolean` -

- -두 개의 [로그 레벨](#로그-레벨)이 주어졌을 때, 첫 번째 레벨이 두 번째 레벨 이상인지 여부를 반환합니다. - -```js -import { matchesLevel } from "astro/logger"; - -matchesLevel("error", "info"); // true -matchesLevel("info", "error"); // false - -``` diff --git a/src/content/docs/ko/reference/experimental-flags/queued-rendering.mdx b/src/content/docs/ko/reference/experimental-flags/queued-rendering.mdx deleted file mode 100644 index c7850575d2946..0000000000000 --- a/src/content/docs/ko/reference/experimental-flags/queued-rendering.mdx +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: 실험적 큐 렌더링 -sidebar: - label: 큐 렌더링 -i18nReady: true ---- - -import Since from '~/components/Since.astro'; - -

- -**타입:** `object`
-**기본값:** `{ enabled: false }`
- -

- -재귀 대신 큐를 기반으로 하는 실험적이고 성능이 더 뛰어난 렌더링 인프라를 활성화합니다. - -기본적으로 Astro는 재귀 알고리즘을 사용하여 `.astro`, `.md`, `.mdx` 파일을 렌더링합니다. 이는 트리 구조로 직렬화된 일련의 컴포넌트를 입력으로 받아 트리의 각 노드에 대해 Astro가 렌더링 함수를 호출하는 방식입니다. - -큐 렌더링이 활성화되면 Astro는 트리의 모든 노드를 순회하고 [깊이 우선](https://en.wikipedia.org/wiki/Depth-first_search) 노드 목록을 생성합니다. 그런 다음 이 목록을 반복하여 렌더링하며, 재귀 알고리즘이 필요하지 않습니다. 이 방식은 메모리 효율성이 더 높으며 대규모 프로젝트에서 더 많은 이점을 제공합니다. - -기본 설정으로 이 기능을 활성화하려면 Astro 설정에서 `queuedRendering.enabled`를 `true`로 설정하세요. - -```js title="astro.config.mjs" ins={5-7} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - queuedRendering: { - enabled: true - } - } -}); -``` - -향후 메이저 버전에서 Astro는 이 새로운 컴파일러를 기본적으로 사용하게 될 것이나, `experimental.queuedRendering` 플래그를 사용하여 미래의 동작을 미리 선택할 수 있습니다. - -## 설정 - -큐 렌더링 엔진에는 다른 가능한 최적화를 실험해 볼 수 있는 추가적인 로우 레벨 기능이 포함되어 있습니다. 이러한 최적화는 큐 엔진의 직접적인 일부가 아니며, 이 실험적인 테스트 단계에서 비효율적이라고 판명되면 제거될 수 있습니다. - - -### 노드 풀링 - -

- -**타입:** `number`
-**기본값:** `1000`
- -

- - -노드 풀링은 렌더링 간에 컴포넌트 노드를 재사용하도록 설계된 캐싱 시스템입니다. 이 기능은 초기 테스트 결과에 따라 합리적인 기본값으로 자동 활성화됩니다. 그러나 프로젝트 요구 사항에 따라 단일 풀에 결합된 노드 수를 늘리거나 줄이도록 풀 크기를 구성할 수 있습니다. 이 기능을 완전히 비활성화하려면 `poolSize`를 `0`으로 설정하세요. - -노드 풀링은 동일한 컴포넌트를 공유하는 많은 페이지가 있는 웹사이트를 빌드할 때 메모리를 절약하므로 정적 페이지를 렌더링할 때 매우 효과적입니다. - -온디맨드로 렌더링되는 페이지의 경우 이러한 렌더링 요청은 메모리를 공유하지 않으므로 이 전략으로 얻을 수 있는 이점이 없기 때문에 노드 풀링이 꺼집니다. - -```js title="astro.config.mjs" ins={7} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - queuedRendering: { - enabled: true, - poolSize: 3000 // 3000개의 노드 풀 사용 - } - } -}); -``` - -### 콘텐츠 캐싱 - -

- -**타입:** `boolean`
-**기본값:** `false`
- -

- - -콘텐츠 캐싱은 페이지 렌더링 중에 값(보통 문자열)을 재사용하는 또 다른 기술입니다. 현재 이 기능은 추가 구성 없이 활성화 또는 비활성화만 가능합니다. 기본적으로 비활성화되어 있지만, 활성화되면 실험적인 큐 엔진이 대부분의 대규모 콘텐츠 컬렉션에 적합한 합리적인 기본 캐시 크기를 선택합니다. - -```js title="astro.config.mjs" ins={7} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - queuedRendering: { - enabled: true, - contentCache: true - } - } -}); -``` diff --git a/src/content/docs/ko/reference/experimental-flags/rust-compiler.mdx b/src/content/docs/ko/reference/experimental-flags/rust-compiler.mdx deleted file mode 100644 index cefc0c0bdff96..0000000000000 --- a/src/content/docs/ko/reference/experimental-flags/rust-compiler.mdx +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: 실험적 Rust 컴파일러 -sidebar: - label: Rust 컴파일러 -i18nReady: true ---- - -import Since from '~/components/Since.astro' -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' - -

- - **타입:** `boolean`
- **기본값:** `false`
- -

- -Astro 파일에 대해 새로운 Rust 기반 컴파일러 사용을 활성화합니다. 이 컴파일러는 더 빠르고, 더 나은 오류 메시지를 제공하며, 전반적으로 현대적인 JavaScript, TypeScript 및 CSS 기능을 더 잘 지원합니다. - -Astro의 향후 주요 버전에서는 이 새로운 컴파일러가 기본으로 사용될 예정이지만, `experimental.rustCompiler` 플래그를 사용하여 미래의 동작을 미리 선택할 수 있습니다. - -컴파일러에 대한 피드백을 제공하거나 개발 상황을 확인하려면 [Astro를 위한 새로운 컴파일러 RFC](https://github.com/withastro/roadmap/discussions/1306)에서 자세한 정보와 토론을 확인하세요. - -## 사용법 - -이 실험적 플래그는 특별한 사용법이 필요하지 않으며, 프로젝트에서 Astro가 사용하는 컴파일러에만 영향을 미칩니다. - -Rust 컴파일러를 활성화하려면 `astro.config.mjs`에 다음을 추가하세요: - -```js title="astro.config.mjs" ins={4-6} -import { defineConfig } from "astro/config"; - -export default defineConfig({ - experimental: { - rustCompiler: true - } -}); -``` - -그런 다음 프로젝트에 `@astrojs/compiler-rs` 패키지를 설치하세요: - - - - ```shell - npm install @astrojs/compiler-rs - ``` - - - ```shell - pnpm add @astrojs/compiler-rs - ``` - - - ```shell - yarn add @astrojs/compiler-rs - ``` - - - -### 예상되는 차이점 - -Astro의 현재 Go 컴파일러와 달리, 이 실험적인 Rust 컴파일러는 잘못된 HTML 구조를 수정하지 않습니다. 예를 들어, 다음과 같은 주요 패턴은 작성된 대로 유지되며 더 이상 수정되지 않습니다: - - - `

Bad nesting

` (`p` 태그 내부의 `div`를 제거하는 대신) - - `

My paragraph` (누락된 닫는 `

` 태그를 추가하는 대신) - -즉, Astro 파일에 잘못된 HTML이 포함되어 있으면 이전 컴파일러를 사용했을 때와 출력이 다르거나 빌드 중에 오류가 발생할 수 있습니다. - -## 제한 사항 - -현재 Rust 컴파일러는 개발 툴바 감사가 올바르게 작동하는 데 필요한 메타데이터를 출력하지 않습니다. diff --git a/src/content/docs/zh-cn/guides/astro-db.mdx b/src/content/docs/zh-cn/guides/astro-db.mdx deleted file mode 100644 index 8855f54d4af60..0000000000000 --- a/src/content/docs/zh-cn/guides/astro-db.mdx +++ /dev/null @@ -1,787 +0,0 @@ ---- -title: 'Astro DB' -description: 了解如何使用 Astro DB——一个专门为 Astro 设计的全托管 SQL 数据库。 -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; -import { Steps } from '@astrojs/starlight/components'; - -Astro DB 是一款专为 Astro 设计的全托管 SQL 数据库。在 Astro 中进行本地开发并部署到任何与 libSQL 兼容的数据库。 - -Astro DB 是一种配置、开发和查询数据的完整解决方案。每当你运行`astro dev`时,都会在`.astro/content.db`中创建一个本地数据库来管理数据,而无需 Docker 或网络连接。 - -## 安装 - -使用内置的 `astro add` 命令安装 [`@astrojs/db` 集成](/zh-cn/guides/integrations-guide/db/): - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -## 定义你的数据库 - -使用 `astro add` 命令安装 `@astrojs/db` 将自动在你的项目中创建一个 `db/config.ts` 文件,你可以在其中定义你的数据库表: - -```ts title="db/config.ts" -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: { }, -}) -``` - -### 表 - -Astro DB 中的数据是通过 SQL 表存储的。表将你的数据结构化为行和列,其中列强制每行值的类型。 - -通过提供现有 libSQL 数据库中的数据结构或将在新数据库中收集的数据,在 `db/config.ts` 文件中定义表。这将允许 Astro 为你的项目生成一个 TypeScript 接口来查询该表。这意味着当你访问数据时,将获得完整的 TypeScript 支持,包括属性自动完成和类型检查。 - -要配置数据库表,应从 `astro:db` 导入并使用 `defineTable()` 和 `column` 工具。然后,为表定义一个名称(区分大小写)以及每列的数据类型。 - -这个例子配置了一个 `Comment` 表,它有 `author` 和 `body` 的必需文本列。然后,通过 `defineDb()` 导出使其在你的项目中可用。 - -```ts title="db/config.ts" "Comment" -import { defineDb, defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } -}) - -export default defineDb({ - tables: { Comment }, -}) -``` - -查看 [表配置参考](/zh-cn/guides/integrations-guide/db/#表配置参考) 以获取完整的表选项参考。 - -### 列 - -Astro DB 支持以下列类型: - -```ts title="db/config.ts" "column.text()" "column.number()" "column.boolean()" "column.date()" "column.json()" -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - // 文本字符串。 - author: column.text(), - // 整数值。 - likes: column.number(), - // 布尔值。 - flagged: column.boolean(), - // 作为 JavaScript Date 对象查询的日期/时间值。 - published: column.date(), - // 未经类型化的 JSON 对象。 - metadata: column.json(), - } -}); -``` - -查看[表的列参考](/zh-cn/guides/integrations-guide/db/#表配置参考)以获取更多细节。 - -### 表引用 - -表之间的关系是数据库设计中的常见架构。例如,一个 `Blog` 表可能与 `Comment`、`Author` 和 `Category` 等其他几个表密切相关。 - -你可以使用**引用列**定义来这些表之间的关系并将它们保存到你的数据库中。要建立关系,你需要: - -- 在被引用的表上有一个**标识符列**。这通常是带有 `primaryKey` 属性的 `id` 列。 -- 在基础表上有一个用于**存储被引用 `id`** 的列。这将使用 `references` 属性来建立关系。 - -这个例子显示了一个 `Comment` 表的 `authorId` 列引用了 `Author` 表的 `id` 列。 - -```ts title="db/config.ts" {3, 10} -const Author = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - } -}); - -const Comment = defineTable({ - columns: { - authorId: column.number({ references: () => Author.columns.id }), - body: column.text(), - } -}); -``` - -## 为你的开发数据库填充数据 - -在开发过程中,Astro 将使用你的 DB 配置并根据你的架构生成本地类型。这些内容将在每次启动开发服务器时从你的 seed 文件重新生成,并允许你使用类型安全和自动补全来查询和处理你的数据样例。 - -你将无法在开发过程中访问生产数据,除非你在开发过程中 [连接到远程数据库](#连接到远程数据库)。这样可以保护你的数据,同时允许你使用类型安全的工作数据库进行测试和开发。 - -要为你的 Astro 项目填充开发数据进行测试和调试,你需要创建一个 `db/seed.ts` 文件。导入 `db` 对象和 `astro:db` 中定义的表。`insert`一些初始数据到每一个表中。这些开发数据应该与数据库模式和生产数据的结构相匹配。 - -以下例子为 `Comment` 表和 `Author` 表定义了两行开发数据: - -```ts title="db/seed.ts" -import { db, Comment, Author } from 'astro:db'; - -export default async function() { - await db.insert(Author).values([ - { id: 1, name: "Kasim" }, - { id: 2, name: "Mina" }, - ]); - - await db.insert(Comment).values([ - { authorId: 1, body: 'Hope you like Astro DB!' }, - { authorId: 2, body: 'Enjoy!'}, - ]) -} -``` - -你的开发服务器将在此文件更改时自动重启你的数据库,并每次重新生成类型并从 `seed.ts` 填充新的开发数据。 - -## 连接一个 libSQL 数据库用于生产 - -Astro DB 可以连接到任何本地 libSQL 数据库或任何暴露 libSQL 远程协议的托管或自托管服务器。 - -要连接 Astro DB 到 libSQL 数据库,设置以下从你的数据库提供商获取的环境变量: - -- `ASTRO_DB_REMOTE_URL`:连接到本地或远程 libSQL DB 的位置的连接 URL。这可能包括 [URL 配置选项](#远程-url-配置选项) 如 sync 和 encryption 作为参数。 -- `ASTRO_DB_APP_TOKEN`:你的 libSQL 服务器的认证 token。这对远程数据库是必须的,对 [本地 DB 如 文件或内存](#url-scheme-和-host) 数据库不是必须的。 - -根据你的服务,你可能会访问到一个 CLI 或 web UI 来获取这些值。以下部分将演示连接到 Turso 并设置这些值,但你也可以使用任何提供商。 - -### 开始使用 Turso - -Turso 是 [libSQL](https://github.com/tursodatabase/libsql) 背后的公司,libSQL 是 Astro DB 的底层数据库。他们提供了一个完全托管的 libSQL 数据库平台,并与 Astro 完全兼容。 - -以下步骤将引导你完成安装 Turso CLI、登录(或注册)、创建一个新数据库、获取所需的认证环境变量,并将模式推送到远程数据库的过程。 - - - -1. 安装 [Turso CLI](https://docs.turso.tech/cli/installation)。 - -2. [登录或注册](https://docs.turso.tech/cli/authentication) Turso。 - -3. 创建一个新数据库。在这个例子中,数据库名称为 `andromeda`。 - - ```sh "andromeda" - turso db create andromeda - ``` - -4. 运行 `show` 命令查看新创建数据库的信息: - - ```sh "andromeda" - turso db show andromeda - ``` - - 复制 `URL` 值并将其设置为 `ASTRO_DB_REMOTE_URL` 的值。 - - - ```dotenv title=".env" "libsql://andromeda-houston.turso.io" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ``` - -5. 创建一个新 token 认证请求到数据库: - - ```sh "andromeda" - turso db tokens create andromeda - ``` - - 复制命令的输出并将其设置为 `ASTRO_DB_APP_TOKEN` 的值。 - - ```dotenv title=".env" add={2} "eyJhbGciOiJF...3ahJpTkKDw" - ASTRO_DB_REMOTE_URL=libsql://andromeda-houston.turso.io - ASTRO_DB_APP_TOKEN=eyJhbGciOiJF...3ahJpTkKDw - ``` - -6. 将你的 DB schema 和 metadata 推送到新的 Turso 数据库。 - - ```sh - astro db push --remote - ``` - -7. 恭喜,现在你已经连接了一个数据库!给自己一个奖励。 👾 - - ```sh - turso relax - ``` - - - -要探索更多 Turso 的功能,请查看 [Turso 文档](https://docs.turso.tech)。 - -### 连接到远程数据库 - -Astro DB 允许你连接到本地和远程数据库。默认情况下,Astro 使用一个本地数据库文件用于 `dev` 和 `build` 命令,每次重新创建表并插入开发 seed 数据。 - -要连接到一个托管的远程数据库,使用 `--remote` 标志。这个标志允许你访问远程数据库,允许你 [接受和持久化用户数据](#插入) 在生产环境中。 - -配置你的 build 命令使用 `--remote` 标志: - -```json title="package.json" "--remote" -{ - "scripts": { - "build": "astro build --remote" - } -} -``` - -你也可以直接在命令行中使用该标志: - -```bash -# 使用远程连接构建 -astro build --remote - -# 使用远程连接开发 -astro dev --remote -``` - -:::caution -在开发过程中使用 `--remote` 时请小心。这会连接到你的生产数据库,所有更改(插入、更新、删除)都会被持久化。 -::: - -`--remote` 标志在本地构建期间和服务器上都使用远程数据库连接。确保在本地开发环境和部署平台中都设置了必要的环境变量。此外,你可能还需要为非 Node.js 运行时(如 Cloudflare Workers 或 Deno)[配置 web 模式](/zh-cn/guides/integrations-guide/db/#mode)。 - -当你部署你的 Astro DB 项目时,确保你的部署平台的 build 命令设置为 `npm run build`(或你包管理器的等效命令)以使用在 `package.json` 中配置的 `--remote` 标志。 - -### 远程 URL 配置选项 - -`ASTRO_DB_REMOTE_URL` 环境变量配置了数据库的位置以及同步和加密等其他选项。 - -#### URL scheme 和 host - -libSQL 支持 HTTP 和 WebSockets 作为远程服务器的传输协议。它还支持使用本地文件或内存数据库。可以使用以下 URL 方案在连接 URL 中进行配置: - -- `memory:` 将使用内存数据库。在这种情况下,主机必须为空。 -- `file:` 将使用本地文件。主机是文件的路径 (`file:path/to/file.db`). -- `libsql:` 将通过 libSQL 库首选的协议使用远程服务器(这可能因版本而异)。主机是服务器的地址 (`libsql://your.server.io`). -- `http:` 通过 HTTP 使用远程服务器。`https:` 可以用来启用安全连接。主机与 `libsql:` 相同。 -- `ws:` 通过 WebSockets 使用远程服务器。`wss:` 可以用来启用安全连接。主机与 `libsql:` 相同。 - -libSQL 连接的详细信息(例如加密密钥、复制、同步间隔)可以在远程连接 URL 中作为查询参数进行配置。 - -例如,要将一个加密的本地文件设置为 libSQL 服务器的嵌入式副本,可以设置以下环境变量: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file://local-copy.db?encryptionKey=your-encryption-key&syncInterval=60&syncUrl=libsql%3A%2F%2Fyour.server.io -ASTRO_DB_APP_TOKEN=token-to-your-remote-url -``` - -:::caution -使用数据库文件是一个高级特性,在部署时应该小心,以防止覆盖你的数据库并丢失你的生产数据。 - -此外,这种方法在无服务器部署中将无法工作,因为这些环境中没有持久化的文件系统。 -::: - -#### `encryptionKey` - -libSQL 对加密数据库有原生支持。传递这个搜索参数将使用给定的密钥启用加密: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=file:path/to/file.db?encryptionKey=your-encryption-key -``` - -#### `syncUrl` - -嵌入式副本是 libSQL 客户端的一个特性,它会在本地文件或内存中创建一个完整同步的副本,以实现超快的读取。写入发送到在 `syncUrl` 上定义的远程数据库,并与本地副本同步。 - -使用此属性传递一个单独的连接 URL 将数据库转换为另一个数据库的嵌入式副本。这应该仅与 `file:` 和 `memory:` 方案一起使用。该参数必须进行 URL 编码。 - -例如,要将一个数据库设置为 `libsql://your.server.io` 的内存嵌入式副本,可以设置连接 URL 如下: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io -``` - -#### `syncInterval` - -嵌入式副本之间同步的间隔时间,单位为秒。默认情况下,它仅在启动时和写入后同步。 - -此属性仅在设置 `syncUrl` 时使用。例如,要将内存嵌入式副本设置为每分钟同步,请设置以下环境变量: - -```dotenv title=".env" -ASTRO_DB_REMOTE_URL=memory:?syncUrl=libsql%3A%2F%2Fyour.server.io&syncInterval=60 -``` - -## 查询你的数据库 - -你可以从项目中的任何 [Astro 页面](/zh-cn/basics/astro-pages/#astro-页面),[端点](/zh-cn/guides/endpoints/) 或 [action](/zh-cn/guides/actions/) 使用提供的 `db` ORM 和查询构建器来查询你的数据库。 - -### Drizzle ORM - -```ts -import { db } from 'astro:db'; -``` - -Astro DB 包含一个内置的 [Drizzle ORM](https://orm.drizzle.team/) 客户端。使用该客户端无需设置或手动配置。当你运行 Astro 时,Astro DB 的 `db` 客户端会自动配置以与你的数据库(本地或远程)进行通信。它使用你明确的数据库架构定义进行类型安全的 SQL 查询,当你引用不存在的列或表时,会出现 TypeScript 错误。 - -### 查询 - -以下例子选择了 `Comment` 表的所有行。这将返回来自 `db/seed.ts` 全量的填充的开发数据数组,然后可以在你的页面模板中使用它们: - -```astro title="src/pages/index.astro" ---- -import { db, Comment } from 'astro:db'; - -const comments = await db.select().from(Comment); ---- - -

Comments

- -{ - comments.map(({ author, body }) => ( -
-

Author: {author}

-

{body}

-
- )) -} -``` - -查看 [Drizzle `select()` API 参考](https://orm.drizzle.team/docs/select) 以获取完整概述。 - -### 插入 - -要接受用户输入,如处理表单请求并将数据插入到你的远程托管数据库,需要为你的 Astro 项目配置 [按需渲染](/zh-cn/guides/on-demand-rendering/) 并为你的部署环境 [添加一个适配器](/zh-cn/guides/on-demand-rendering/#添加适配器)。 - -这个例子基于解析后表单的 POST 请求向 `Comment` 表插入一行: - -```astro ---- -// src/pages/index.astro -import { db, Comment } from 'astro:db'; - -if (Astro.request.method === 'POST') { - // 解析表单数据 - const formData = await Astro.request.formData(); - const author = formData.get('author'); - const body = formData.get('body'); - if (typeof author === 'string' && typeof body === 'string') { - // 将表单数据插入到 Comment 表中 - await db.insert(Comment).values({ author, body }); - } -} - -// 在每次请求上渲染新的评论列表 -const comments = await db.select().from(Comment); ---- - -
- - - - - - - -
- - -``` - -你也可以使用 [Astro actions](/zh-cn/guides/actions/) 向 Astro DB 表中插入数据。以下例子使用一个 action 向 `Comment` 表中插入一行: - -```ts -// src/actions/index.ts -import { db, Comment } from 'astro:db'; -import { defineAction } from 'astro:actions'; -import { z } from 'astro/zod'; -export const server = { - addComment: defineAction({ - // Actions 用 Zod 保证类型安全,不需要再 - // 在页面中检查 typeof {value} === 'string' - input: z.object({ - author: z.string(), - body: z.string(), - }), - handler: async (input) => { - const updatedComments = await db - .insert(Comment) - .values(input) - .returning(); // 返回更新后的评论 - return updatedComments; - }, - }), -}; -``` - - - -查看 [Drizzle `insert()` API 参考](https://orm.drizzle.team/docs/insert) 以获取完整概述。 - - - -### 删除 - -你也可以从 API 端点查询你的数据库。这个例子通过 `id` 参数删除 `Comment` 表中的一行: - -```ts -// src/pages/api/comments/[id].ts -import type { APIRoute } from "astro"; -import { db, Comment, eq } from 'astro:db'; -export const DELETE: APIRoute = async (ctx) => { - await db.delete(Comment).where(eq(Comment.id, ctx.params.id )); - return new Response(null, { status: 204 }); -} -``` - - -查看 [Drizzle `delete()` API 参考](https://orm.drizzle.team/docs/delete) 以获取完整概述。 - - -### 过滤 - -要通过特定属性查询表结果,请使用 [Drizzle 的部分查询选项](https://orm.drizzle.team/docs/select#partial-select)。例如,向你的 `select()` 查询添加 [一个 `.where()` 调用](https://orm.drizzle.team/docs/select#filtering),并传递你想做的比较操作。 - -以下例子查询了 `Comment` 表中包含 "Astro DB" 短语的所有行。使用 [`like()` 操作符](https://orm.drizzle.team/docs/operators#like) 检查 `body` 中是否存在短语: - -```astro title="src/pages/index.astro" ---- -import { db, Comment, like } from 'astro:db'; - -const comments = await db.select().from(Comment).where( - like(Comment.body, '%Astro DB%') -); ---- -``` - -### Drizzle 辅助工具 - -所有用于构建查询的 Drizzle 辅助工具都从 `astro:db` 模块中暴露出来。这包括: - -- [过滤操作符](https://orm.drizzle.team/docs/operators) 如 `eq()` 和 `gt()` -- [聚合辅助工具](https://orm.drizzle.team/docs/select#aggregations-helpers) 如 `count()` -- 用于编写原始 SQL 查询语句的 [`sql` 辅助工具](https://orm.drizzle.team/docs/sql) - -```ts -import { eq, gt, count, sql } from 'astro:db'; -``` - -### 关系 - -你可以使用 SQL 连接从多个表查询关联的数据。要创建一个连接查询,请使用连接操作符扩展你的 `db.select()` 语句。每个函数都接受一个要连接的表和一个条件来匹配两个表之间的行。 - -这个例子使用了 `innerJoin()` 函数将 `Comment` 的作者与他们相关的 `Author` 信息连接起来,基于 `authorId` 列。这将返回一个对象数组,每个 `Author` 和 `Comment` 行作为顶级属性: - -```astro title="src/pages/index.astro" ---- -import { db, eq, Comment, Author } from 'astro:db'; - -const comments = await db.select() - .from(Comment) - .innerJoin(Author, eq(Comment.authorId, Author.id)); ---- - -

Comments

- -{ - comments.map(({ Author, Comment }) => ( -
-

Author: {Author.name}

-

{Comment.body}

-
- )) -} -``` - - - -查看 [Drizzle 连接参考](https://orm.drizzle.team/docs/joins#join-types) 以获取所有可用的连接操作符和配置选项。 - - - -### 批处理事务 - -所有远程数据库查询都作为网络请求进行。当进行大量查询,或者如果任何查询失败需要自动回滚时,你可能需要将查询批量处理为单个事务。 - -这个例子使用 `db.batch()` 方法在单个请求中填充多行: - -```ts -// db/seed.ts -import { db, Author, Comment } from 'astro:db'; - -export default async function () { - const queries = []; - // 使用单个网络请求将 100 个样本数据填充到你的远程数据库中。 - for (let i = 0; i < 100; i++) { - queries.push(db.insert(Comment).values({ body: `Test comment ${i}` })); - } - await db.batch(queries); -} -``` - - - -查看 [Drizzle `db.batch()`](https://orm.drizzle.team/docs/batch-api) 文档以获取更多详细信息。 - - - -## 将更改推送到你的数据库 - -你可以将开发期间所做的更改推送到你的数据库。 - -### 推送表架构 - -你的表架构可能会随着项目的增长而变化。你可以在本地安全地测试配置更改,并在部署时推送到你的远程数据库。 - -你可以通过 CLI 使用 `astro db push --remote` 命令将本地架构更改推送到远程数据库: - - - - ```sh - npm run astro db push --remote - ``` - - - ```sh - pnpm astro db push --remote - ``` - - - ```sh - yarn astro db push --remote - ``` - - - -此命令将验证你的本地更改是否可以在不丢失数据的情况下进行,并在必要时,建议如何安全地修改你的架构以解决冲突。 - -#### 推送破坏性架构更改 - -:::danger -__这将销毁你的数据库__。仅在你不需要生产数据时执行此命令。 -::: - -如果必须以与现有数据不兼容的方式更改表架构,则需要重置生产数据库。 - -要推送包含破坏性更改的表架构更新,请添加 `--force-reset` 标志以重置所有生产数据: - - - - ```sh - npm run astro db push --remote --force-reset - ``` - - - ```sh - pnpm astro db push --remote --force-reset - ``` - - - ```sh - yarn astro db push --remote --force-reset - ``` - - - -### 重命名表 - -在将架构推送到远程数据库后,可以重命名表。 - -如果 **没有重要的生产数据**,则可以使用 `--force-reset` 标志 [重置你的数据库](#推送破坏性架构更改)。此标志将删除数据库中的所有表并创建新的表,以匹配当前的架构。 - -为了在保留你的生产数据的同时重命名一个表,你必须执行一系列非破坏性更改,以安全地将本地架构推送到远程数据库。 - -以下示例将表从 `Comment` 重命名为 `Feedback`: - - - -1. 在你的数据库配置文件中,为你想要重命名的表添加 `deprecated: true` 属性: - - ```ts title="db/config.ts" ins={2} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -2. 添加一个新的表架构(完全匹配现有表的属性)并使用新名称: - - ```ts title="db/config.ts" ins={8-14} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` - -3. 使用 `astro db push --remote`[将架构推送到远程数据库](#推送表架构) 。这将添加新表并将旧表标记为已弃用。 -4. 更新你的本地项目代码以使用新表而不是旧表。你可能还需要将数据迁移到新表。 -5. 一旦你确信旧表在你的项目中不再使用,你可以从 `config.ts` 中删除旧表的架构: - ```ts title="db/config.ts" del={1-7} - const Comment = defineTable({ - deprecated: true, - columns: { - author: column.text(), - body: column.text(), - } - }); - - const Feedback = defineTable({ - columns: { - author: column.text(), - body: column.text(), - } - }); - ``` -6. 再次使用 `astro db push --remote`推送到远程数据库。旧表将被删除,只留下新的、重命名的表。 - - -### 推送表数据 - -你可能需要将数据推送到远程数据库以进行填充或数据迁移。你可以编写一个 `.ts` 文件并使用 `astro:db` 模块来编写类型安全的查询。然后,使用命令 `astro db execute --remote` 对远程数据库执行该文件: - -以下评论可以使用命令 `astro db execute db/seed.ts --remote` 进行填充: - -```ts -// db/seed.ts -import { Comment } from 'astro:db'; - -export default async function () { - await db.insert(Comment).values([ - { authorId: 1, body: 'Hope you like Astro DB!' }, - { authorId: 2, body: 'Enjoy!' }, - ]) -} -``` - - - -查看 [CLI 参考](/zh-cn/guides/integrations-guide/db/#astro-db-cli-参考) 以获取完整的命令列表。 - - - -## 构建 Astro DB 集成 - -[Astro 集成](/zh-cn/reference/integrations-reference/) 可以通过额外的 Astro DB 表和填充数据来扩展用户项目。 - -在 `astro:db:setup` 钩子中使用 `extendDb()` 方法注册额外的 Astro DB 配置和填充文件。 -`defineDbIntegration()` 辅助函数为 `astro:db:setup` 钩子提供 TypeScript 支持和自动补全。 - -```js {8-13} -// my-integration/index.ts -import { defineDbIntegration } from '@astrojs/db/utils'; - -export default function MyIntegration() { - return defineDbIntegration({ - name: 'my-astro-db-powered-integration', - hooks: { - 'astro:db:setup': ({ extendDb }) => { - extendDb({ - configEntrypoint: '@astronaut/my-package/config', - seedEntrypoint: '@astronaut/my-package/seed', - }); - }, - // 其他集成钩子... - }, - }); -} -``` - -集成的 [配置](#定义你的数据库) 和 [填充](#为你的开发数据库填充数据) 文件遵循与其用户定义的等效项相同的格式。 - -### 在集成中进行类型安全操作 - -在进行集成工作时,你可能无法从 `astro:db` 导出的 Astro 生成的表类型中获益。 -为了完全的类型安全,使用 `asDrizzleTable()` 辅助工具创建一个可以用于数据库操作的表引用对象。 - -例如,给定一个集成设置以下 `Pets` 数据库表: - -```js -// my-integration/config.ts -import { defineDb, defineTable, column } from 'astro:db'; - -export const Pets = defineTable({ - columns: { - name: column.text(), - species: column.text(), - }, -}); - -export default defineDb({ tables: { Pets } }); -``` - -填充文件可以导入 `Pets` 并使用 `asDrizzleTable()` 向你的表插入具有类型检查的行: - -```js {2,7} /typeSafePets(?! )/ -// my-integration/seed.ts -import { asDrizzleTable } from '@astrojs/db/utils'; -import { db } from 'astro:db'; -import { Pets } from './config'; - -export default async function() { - const typeSafePets = asDrizzleTable('Pets', Pets); - - await db.insert(typeSafePets).values([ - { name: 'Palomita', species: 'cat' }, - { name: 'Pan', species: 'dog' }, - ]); -} -``` - -`asDrizzleTable('Pets', Pets)` 返回的值等同于 `import { Pets } from 'astro:db'`,但即使 Astro 的类型生成无法运行时也可用。 -你可以在任何需要查询或插入数据库的集成代码中使用它。 - - -## 从 Astro Studio 迁移到 Turso - - - -1. 在 [Studio 仪表板](https://studio.astro.build/) 中,导航到你要迁移的项目。在设置选项卡中,使用 “Export Database(导出数据库)” 按钮下载数据库的转储。 -2. 按照官方说明 [安装 Turso CLI](https://docs.turso.tech/cli/installation) 并 [注册或登录](https://docs.turso.tech/cli/authentication) 你的 Turso 帐户。 -3. 使用 `turso db create` 命令在 Turso 上创建一个新数据库。 - ```sh - turso db create [database-name] - ``` -4. 使用 Turso CLI 获取数据库 URL,并将其配置为环境变量 `ASTRO_DB_REMOTE_URL`。 - ```sh - turso db show [database-name] - ``` - ```dotenv - ASTRO_DB_REMOTE_URL=[your-database-url] - ``` -5. 创建一个令牌来访问你的数据库,并将其配置为环境变量 `ASTRO_DB_APP_TOKEN`。 - ```sh - turso db tokens create [database-name] - ``` - ```dotenv - ASTRO_DB_APP_TOKEN=[your-app-token] - ``` -6. 将你的 DB 架构和元数据推送到新的 Turso 数据库。 - ```sh - astro db push --remote - ``` -7. 将步骤 1 中的数据库转储导入到新的 Turso DB 中。 - ```sh - turso db shell [database-name] < ./path/to/dump.sql - ``` -8. 确认你的项目连接到新数据库后,你就可以安全地从 Astro Studio 中删除该项目了。 - - diff --git a/src/content/docs/zh-cn/guides/integrations-guide/db.mdx b/src/content/docs/zh-cn/guides/integrations-guide/db.mdx deleted file mode 100644 index ab3d06b95e765..0000000000000 --- a/src/content/docs/zh-cn/guides/integrations-guide/db.mdx +++ /dev/null @@ -1,331 +0,0 @@ ---- -type: integration -title: '@astrojs/db' -description: 了解如何在你的 Astro 项目中使用 @astrojs/db 集成。 -sidebar: - label: DB -githubIntegrationURL: 'https://github.com/withastro/astro/tree/main/packages/db/' -category: other -i18nReady: true ---- -import { FileTree } from '@astrojs/starlight/components'; -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -import ReadMore from '~/components/ReadMore.astro'; -import Since from '~/components/Since.astro'; - -Astro DB 是一个为 Astro 生态设计的全托管 SQL 数据库:你可以在本地使用 Astro 进行开发,并部署到任何 [libSQL 兼容的数据库](/zh-cn/guides/astro-db/)。 - -有了 Astro DB,你就拥有了一个强大的、本地的、类型安全的工具,可以像关系数据库查询和构建内容。 - -查看 [Astro DB 指南](/zh-cn/guides/astro-db/) 以获取完整的使用方法和示例。 - -## 安装 - -Astro 包含了一个 `astro add` 命令,用于自动设置官方集成。如果你愿意,你也可以选择[手动安装集成](#手动安装)。 - -在新的终端窗口中运行以下之一的命令。 - - - - ```sh - npx astro add db - ``` - - - ```sh - pnpm astro add db - ``` - - - ```sh - yarn astro add db - ``` - - - -#### 手动安装 - -如果你更喜欢自己从头开始设置,可以跳过 `astro add`,并按照以下说明自行安装 Astro DB。 - -##### 1. 通过包管理器从 npm 安装集成 - - - - ```shell - npm install @astrojs/db - ``` - - - ```shell - pnpm add @astrojs/db - ``` - - - ```shell - yarn add @astrojs/db - ``` - - - -##### 2. 将集成添加到 `astro.config.mjs` - - ```js title="astro.config.mjs" ins={2,6} - import { defineConfig } from 'astro/config'; - import db from '@astrojs/db'; - - export default defineConfig({ - integrations: [ - db() - ] - }); - ``` - -##### 3. 配置你的数据库 - -在项目的根目录下创建一个 `db/config.ts` 文件。这是一个特殊的文件,Astro 会自动加载并用它来配置你的数据库表。 - -```ts -// db/config.ts -import { defineDb } from 'astro:db'; - -export default defineDb({ - tables: {}, -}) -``` - -## 配置 - -### `mode` - -

- -**类型:** `'node' | 'web'`
-**默认值:** `'node'`
- -

- -配置用于在生产环境中连接到数据库的驱动程序。 - -默认情况下,Astro DB 在生产部署中使用基于 Node.js 的 libSQL 驱动程序。`node` 驱动程序模式足以满足大多数使用 Node.js 运行时的 Astro 托管或自托管网站的需求。这使你能够通过 `memory:`、`file:`、`ws:`、`wss:`、`libsql`、`http` 和 `https` 等多种协议连接到你的数据库,并且支持[嵌入式副本](/zh-cn/guides/astro-db/#syncurl)等高级功能。 - -当在非 Node.js 运行时(例如 Cloudflare Workers 或 Deno)的无服务器环境中部署时,可以使用基于 Web 的 libSQL 驱动程序。使用 `web` 模式部署时,你将能够通过 `libsql`、`http` 或 `https` 建立基于 Web 的连接。 - -要在非 Node.js 环境中使用 web libSQL 驱动模式,请在适配器的配置中设置 `mode` 属性: - -```ts title="astro.config.mjs" ins={7} -import { defineConfig } from 'astro/config'; -import db from '@astrojs/db'; - -export default defineConfig({ - integrations: [ - db({ - mode: 'web' - }) - ] -}); -``` - -## 表配置参考 - -### `columns` -

- -**类型:** `ColumnsConfig` -

-表的列是使用 `columns` 对象配置: - -```ts -import { defineTable, column, NOW } from 'astro:db'; - -const Comment = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - author: column.text(), - content: column.text({ optional: true }), - published: column.date({ default: NOW }), - }, -}); -``` - -列是使用 `column` 辅助工具进行配置的。`column` 支持以下类型: - -- **`column.text(...)`** - 存储纯文本或富文本内容 -- **`column.number(...)`** - 存储整数和浮点值 -- **`column.boolean(...)`** - 存储 true / false 值 -- **`column.date(...)`** - 存储 `Date` 对象,解析为 ISO 字符串用于数据存储 -- **`column.json(...)`** - 存储任意 JSON blobs,解析为字符串化的 JSON 用于数据存储 - -所有列都有一些共享的配置值: - -- `primaryKey` - 将 `number` 或 `text` 列设置为唯一标识符。 -- `optional` - Astro DB 默认对所有列使用 `NOT NULL`。将 `optional` 设置为 `true` 以允许 null 值。 -- `default` - 设置新插入条目的默认值。这可以接受静态值或生成值(如时间戳)的 `sql` 字符串。 -- `unique` - 将列标记为唯一。这将防止表中条目的值重复。 -- `references` - 通过列引用相关表。这会建立一个外键约束,意味着每个列值必须在引用的表中有一个匹配的值。 - -`text` 列可以选择性地定义字符串字面量列表以用作生成枚举类型。但是,**这不会在运行时执行任何校验**。删除、添加和更改这些值都应该由你的项目代码来处理。 - -```ts title="db/config.ts" {8} -import { defineTable, column } from 'astro:db'; - -// 表定义 -const UserTable = defineTable({ - columns: { - id: column.number({ primaryKey: true }), - name: column.text(), - rank: column.text({ enum: ['user', 'mod', 'admin'] }), - }, -}); - -// 生成的类型定义 -type UserTableInferInsert = { - id?: string; - name: string; - rank: "user" | "mod" | "admin"; -} -``` - -### `indexes` - -

- -**类型:** `{ on: string | string[]; unique?: boolean | undefined; name?: string | undefined; }[]` -

- -表索引用于提高在特定列或列组合上的查找速度。`indexes` 属性接受一个配置对象数组,用于指定要索引的列: - -```ts title="db/config.ts" {9-11} -import { defineTable, column } from 'astro:db'; - -const Comment = defineTable({ - columns: { - authorId: column.number(), - published: column.date(), - body: column.text(), - }, - indexes: [ - { on: ["authorId", "published"], unique: true }, - ] -}); -``` - -这将在 `authorId` 和 `published` 列上生成一个名为 `Comment_authorId_published_idx` 的唯一索引。 - -每个索引都有以下配置选项: - -- `on` - 要索引的单个列或列名数组。 -- `unique` (可选) - 设置为 `true` 以在索引列上强制唯一值。 -- `name` (可选) - 为唯一索引指定一个自定义名称。这将覆盖 Astro 根据被索引的表和列名生成的名称(例如 `Comment_authorId_published_idx`)。自定义名称是全局的,因此请确保索引名称在不同的表之间不会冲突。 - -### `foreignKeys` - -

- -**类型:** `{ columns: string | string[]; references: () => Column | Column[]; }[]` -

- -:::tip - -`foreignKeys` 是一个用于关联多个表列的高级 API。如果你只需要引用一个单独的列,试试使用[列 `references` 属性。](#columns) - -::: - -外键用于建立两个表之间的关系。`foreignKeys` 属性接受一个配置对象数组,可以在表之间关联一个或多个列: - -```ts title="db/config.ts" {12-20} -import { defineTable, column } from 'astro:db'; - -const Author = defineTable({ - columns: { - firstName: column.text(), - lastName: column.text(), - }, -}); - -const Comment = defineTable({ - columns: { - authorFirstName: column.text(), - authorLastName: column.text(), - body: column.text(), - }, - foreignKeys: [ - { - columns: ["authorFirstName", "authorLastName"], - references: () => [Author.columns.firstName, Author.columns.lastName], - }, - ], -}); -``` - -每个外键配置对象接受以下属性: - -- `columns`: - 要与引用表关联的单个列名或者列名数组。 -- `references`: - 返回引用表的单列或者列数组的函数。 - -## Astro DB CLI 参考 - -Astro DB 包含一组 CLI 命令,用于与你的本地和 libSQL 兼容数据库进行交互。 - -当使用 GitHub CI 流水线时,这些命令会被自动调用,你也可以使用 `astro db` CLI 手动调用它们。 - -### `astro db push` - -**标志:** - -- `--force-reset` 如果需要进行破坏性的模式更改,则重置所有生产数据。 - -安全地将数据库配置更改推送到你的项目数据库。这将检查任何数据丢失的风险,并指导你进行任何推荐的迁移步骤。如果必须进行破坏性的模式更改,使用 `--force-reset` 标志重置所有生产数据。 - -### `astro db verify` - -检查你的本地和远程数据库配置之间的任何差异。这是由 `astro db push` 自动运行的。`verify` 将比较你的本地 `db/config.ts` 文件与远程数据库,并在检测到更改时发出警告。 - -### `astro db execute ` - -**标志:** - -- `--remote` 在你的 libSQL 兼容数据库上运行。省略则在你的开发服务器上运行。 - -执行一个 `.ts` 或 `.js` 文件以读取或写入你的数据库。这接受一个文件路径作为参数,并支持使用 `astro:db` 模块编写类型安全的查询。使用 `--remote` 标志在你的 libSQL 兼容数据库上运行,或省略该标志在你的开发服务器上运行。参见如何[填充开发数据](/zh-cn/guides/astro-db/#为你的开发数据库填充数据)以获取一个示例文件。 - -### `astro db shell --query ` - -**标志:** - -- `--query` 要执行的原始 SQL 查询语句。 -- `--remote` 在你的 libSQL 兼容数据库上运行。省略则在你的开发服务器上运行。 - -对你的数据库执行原始 SQL 查询。使用 `--remote` 标志在你的 libSQL 兼容数据库上运行,或省略该标志在你的开发服务器上运行。 - -## Astro DB 工具函数参考 - -### `isDbError()` - - -

- -**类型:** `(err: unknown) => boolean`
- -

- -`isDbError()` 函数用于检查一个错误是否是 libSQL 数据库异常。这可能包括在使用引用时的外键约束错误,或在插入数据时缺少字段。你可以将 `isDbError()` 与 try / catch 块结合使用,来处理应用程序中的数据库错误: - -```ts title="src/pages/api/comment/[id].ts" "idDbError" -import { db, Comment, isDbError } from 'astro:db'; -import type { APIRoute } from 'astro'; - -export const POST: APIRoute = async (ctx) => { - try { - await db.insert(Comment).values({ - id: ctx.params.id, - content: 'Hello, world!' - }); - } catch (e) { - if (isDbError(e)) { - return new Response(`无法插入 id 为 ${ctx.params.id} 的评论\n\n${e.message}`, { status: 400 }); - } - return new Response('发生了意外错误', { status: 500 }); - } - - return new Response(null, { status: 201 }); -}; diff --git a/src/content/docs/zh-cn/reference/cli-reference.mdx b/src/content/docs/zh-cn/reference/cli-reference.mdx index 451e8d5bc5b9c..79c08efc55eb0 100644 --- a/src/content/docs/zh-cn/reference/cli-reference.mdx +++ b/src/content/docs/zh-cn/reference/cli-reference.mdx @@ -267,7 +267,6 @@ Flags 为所有 Astro 模块生成 TypeScript 类型。这会为类型推断设置一个[`.astro/types.d.ts`文件](/zh-cn/guides/typescript/#设置),并为依赖于生成类型的特性定义模块: - `astro:content` 模块用于 [内容集合 API](/zh-cn/guides/content-collections/)。 -- `astro:db` 模块用于 [Astro DB](/zh-cn/guides/astro-db/)。 - `astro:env` 模块用于 [Astro Env](/zh-cn/guides/environment-variables/)。 - `astro:actions` 模块用于 [Astro Actions](/zh-cn/guides/actions/)。 diff --git a/worker.js b/worker.js index a03133631f157..392bed56e0a3a 100644 --- a/worker.js +++ b/worker.js @@ -84,6 +84,7 @@ const rules = [ '/:lang/reference/experimental-flags/static-import-meta-env/', '/:lang/guides/environment-variables/', ], + ['/:lang/reference/experimental-flags/advanced-routing/', '/:lang/guides/routing/'], // Very old docs site redirects ['/reference/renderer-reference', '/en/reference/renderer-reference/'], @@ -99,6 +100,7 @@ const rules = [ ['/lighthouse/*', '/en/guides/migrate-to-astro/'], ['/en/guides/debugging', '/en/guides/troubleshooting/'], ['/en/quick-started', '/en/installation/'], + ['/:lang/guides/astro-db/', '/:lang/guides/integrations-guide/db/'], // Redirect root to English homepage ['/', '/en/getting-started/'], diff --git a/wrangler.jsonc b/wrangler.jsonc index df65c429cfbcd..42768caae454c 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -1,12 +1,11 @@ { "$schema": "node_modules/wrangler/config-schema.json", - "name": "docs", + "name": "docs-v7", "main": "worker.js", - "compatibility_date": "2026-05-06", + "compatibility_date": "2026-06-12", "assets": { "directory": "./dist", "binding": "ASSETS", - "not_found_handling": "none", - }, - "preview_urls": true, + "not_found_handling": "none" + } }