diff options
360 files changed, 2615 insertions, 5793 deletions
diff --git a/.changeset/chatty-teachers-sit.md b/.changeset/chatty-teachers-sit.md new file mode 100644 index 000000000..9e4fd89b4 --- /dev/null +++ b/.changeset/chatty-teachers-sit.md @@ -0,0 +1,5 @@ +--- +"astro": major +--- + +The lowest version of Node supported by Astro is now Node v18.17.1 and higher. diff --git a/.changeset/config.json b/.changeset/config.json index 030941db2..7920f52b8 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -4,7 +4,7 @@ "commit": false, "linked": [], "access": "public", - "baseBranch": "main", + "baseBranch": "next", "updateInternalDependencies": "patch", "___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH": { "onlyUpdatePeerDependentsWhenOutOfRange": true diff --git a/.changeset/many-garlics-lick.md b/.changeset/many-garlics-lick.md new file mode 100644 index 000000000..12ac2dd7c --- /dev/null +++ b/.changeset/many-garlics-lick.md @@ -0,0 +1,14 @@ +--- +'astro': major +--- + +Removes internal JSX handling and moves the responsibility to the `@astrojs/mdx` package directly. The following exports are also now removed: + +- `astro/jsx/babel.js` +- `astro/jsx/component.js` +- `astro/jsx/index.js` +- `astro/jsx/renderer.js` +- `astro/jsx/server.js` +- `astro/jsx/transform-options.js` + +If your project includes `.mdx` files, you must upgrade `@astrojs/mdx` to the latest version so that it doesn't rely on these entrypoints to handle your JSX. diff --git a/.changeset/perfect-fans-fly.md b/.changeset/perfect-fans-fly.md new file mode 100644 index 000000000..cdecf6fb1 --- /dev/null +++ b/.changeset/perfect-fans-fly.md @@ -0,0 +1,7 @@ +--- +'@astrojs/mdx': minor +--- + +Updates adapter server entrypoint to use `@astrojs/mdx/server.js` + +This is an internal change. Handling JSX in your `.mdx` files has been moved from Astro internals and is now the responsibility of this integration. You should not notice a change in your project, and no update to your code is required. diff --git a/.changeset/poor-frogs-dream.md b/.changeset/poor-frogs-dream.md new file mode 100644 index 000000000..fdb3daa85 --- /dev/null +++ b/.changeset/poor-frogs-dream.md @@ -0,0 +1,7 @@ +--- +'astro': major +--- + +Refactor the exported types from the `astro` module. There should normally be no breaking changes, but if you relied on some previously deprecated types, these might now have been fully removed. + +In most cases, updating your code to move away from previously deprecated APIs in previous versions of Astro should be enough to fix any issues. diff --git a/.changeset/pre.json b/.changeset/pre.json new file mode 100644 index 000000000..50eeffb37 --- /dev/null +++ b/.changeset/pre.json @@ -0,0 +1,46 @@ +{ + "mode": "pre", + "tag": "alpha", + "initialVersions": { + "astro": "4.13.1", + "@astrojs/prism": "3.1.0", + "@astrojs/rss": "4.0.7", + "create-astro": "4.8.1", + "@astrojs/db": "0.12.0", + "@astrojs/alpinejs": "0.4.0", + "@astrojs/cloudflare": "0.0.0", + "@astrojs/lit": "4.3.0", + "@astrojs/markdoc": "0.11.3", + "@astrojs/mdx": "3.1.3", + "@astrojs/netlify": "0.0.0", + "@astrojs/node": "8.3.2", + "@astrojs/partytown": "2.1.1", + "@astrojs/preact": "3.5.1", + "@astrojs/react": "3.6.1", + "@astrojs/sitemap": "3.1.6", + "@astrojs/solid-js": "4.4.0", + "@astrojs/svelte": "5.7.0", + "@astrojs/tailwind": "5.1.0", + "@astrojs/vercel": "7.7.2", + "@astrojs/vue": "4.5.0", + "@astrojs/web-vitals": "1.0.0", + "@astrojs/internal-helpers": "0.4.1", + "@astrojs/markdown-remark": "5.2.0", + "@astrojs/studio": "0.1.1", + "@astrojs/telemetry": "3.1.0", + "@astrojs/underscore-redirects": "0.3.4", + "@astrojs/upgrade": "0.3.1" + }, + "changesets": [ + "chatty-teachers-sit", + "mighty-trees-teach", + "new-pillows-kick", + "poor-frogs-dream", + "quick-ads-exercise", + "small-ties-sort", + "smart-comics-doubt", + "spicy-houses-fry", + "ten-students-repair", + "weak-dancers-beam" + ] +} diff --git a/.changeset/quick-ads-exercise.md b/.changeset/quick-ads-exercise.md new file mode 100644 index 000000000..dd4285a4c --- /dev/null +++ b/.changeset/quick-ads-exercise.md @@ -0,0 +1,10 @@ +--- +'@astrojs/markdown-remark': major +--- + +Renames the following CSS variables theme color token names to better align with the Shiki v1 defaults: + +- `--astro-code-color-text` => `--astro-code-foreground` +- `--astro-code-color-background` => `--astro-code-background` + +You can perform a global find and replace in your project to migrate to the new token names. diff --git a/.changeset/small-ties-sort.md b/.changeset/small-ties-sort.md new file mode 100644 index 000000000..e3f3d67eb --- /dev/null +++ b/.changeset/small-ties-sort.md @@ -0,0 +1,50 @@ +--- +'astro': major +--- + +Fixes attribute rendering for non-[boolean HTML attributes](https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML) with boolean values to match proper attribute handling in browsers. + +Previously, non-boolean attributes may not have included their values when rendered to HTML. In Astro v5.0, the values are now explicitly rendered as `="true"` or `="false"` + +In the following `.astro` examples, only `allowfullscreen` is a boolean attribute: + +```astro +<!-- src/pages/index.astro --> +<!-- `allowfullscreen` is a boolean attribute --> +<p allowfullscreen={true}></p> +<p allowfullscreen={false}></p> + +<!-- `inherit` is *not* a boolean attribute --> +<p inherit={true}></p> +<p inherit={false}></p> + +<!-- `data-*` attributes are not boolean attributes --> +<p data-light={true}></p> +<p data-light={false}></p> +``` + +Astro v5.0 now preserves the full data attribute with its value when rendering the HTML of non-boolean attributes: + +```diff + <p allowfullscreen></p> + <p></p> + + <p inherit="true"></p> +- <p inherit></p> ++ <p inherit="false"></p> + +- <p data-light></p> ++ <p data-light="true"></p> +- <p></p> ++ <p data-light="false"></p> +``` + +If you rely on attribute values, for example to locate elements or to conditionally render, update your code to match the new non-boolean attribute values: + +```diff +- el.getAttribute('inherit') === '' ++ el.getAttribute('inherit') === 'false' + +- el.hasAttribute('data-light') ++ el.dataset.light === 'true' +``` diff --git a/.changeset/ten-students-repair.md b/.changeset/ten-students-repair.md new file mode 100644 index 000000000..bffa74548 --- /dev/null +++ b/.changeset/ten-students-repair.md @@ -0,0 +1,14 @@ +--- +'@astrojs/vercel': major +'astro': major +--- + +Remove support for functionPerRoute + +This change removes support for the `functionPerRoute` option both in Astro and `@astrojs/vercel`. + +This option made it so that each route got built as separate entrypoints so that they could be loaded as separate functions. The hope was that by doing this it would decrease the size of each function. However in practice routes use most of the same code, and increases in function size limitations made the potential upsides less important. + +Additionally there are downsides to functionPerRoute, such as hitting limits on the number of functions per project. The feature also never worked with some Astro features like i18n domains and request rewriting. + +Given this, the feature has been removed from Astro. diff --git a/.github/labeler.yml b/.github/labeler.yml index c1025ad11..b0d27800b 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -40,5 +40,5 @@ - packages/integrations/vue/** 'docs pr': -- packages/astro/src/@types/astro.ts +- packages/astro/src/types/public/** - packages/astro/src/core/errors/errors-data.ts diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index c1b491990..2ce9ac1db 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -11,7 +11,7 @@ on: - "examples/**" - ".github/workflows/check.yml" - "scripts/smoke/check.js" - - "packages/astro/src/@types/astro.ts" + - "packages/astro/src/types/public/**" - "pnpm-lock.yaml" - "packages/astro/types.d.ts" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 79962c07e..d71c17afe 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -207,6 +207,7 @@ jobs: uses: actions/checkout@v4 with: repository: withastro/docs + ref: 5.0.0-beta path: smoke/docs - name: Install dependencies @@ -229,7 +230,7 @@ jobs: filters: | docs: - 'packages/integrations/*/README.md' - - 'packages/astro/src/@types/astro.ts' + - "packages/astro/src/types/public/**" - 'packages/astro/src/core/errors/errors-data.ts' - name: Build autogenerated docs pages from current astro branch diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2f2e63786..6a657068d 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -289,7 +289,7 @@ Server-side rendering (SSR) can be complicated. The Astro package (`packages/ast - `components/`: Built-in components to use in your project (e.g. `import Code from 'astro/components/Code.astro'`) - `src/`: Astro source - - `@types/`: TypeScript types. These are centralized to cut down on circular dependencies + - `types/`: TypeScript types. These are centralized to cut down on circular dependencies - `cli/`: Code that powers the `astro` CLI command - `core/`: Code that executes **in the top-level scope** (in Node). Within, you’ll find code that powers the `astro build` and `astro dev` commands, as well as top-level SSR code. - `runtime/`: Code that executes **in different scopes** (i.e. not in a pure Node context). You’ll have to think about code differently here. @@ -369,20 +369,22 @@ Full documentation: https://github.com/changesets/changesets/blob/main/docs/prer ### Entering prerelease mode -If you have gotten permission from the core contributors, you can enter into prerelease mode by following the following steps: +If you have gotten permission from the core contributors, you can enter into prerelease mode with the following steps: - Run: `pnpm exec changeset pre enter next` in the project root +- Update `.changeset/config.json` with `"baseBranch": "next"` (for easier changesets creation) - Create a new PR from the changes created by this command -- Review, approve, and more the PR to enter prerelease mode. +- Review, approve, and merge the PR to enter prerelease mode. - If successful, The "[ci] release" PR (if one exists) will now say "[ci] release (next)". ### Exiting prerelease mode -Exiting prerelease mode should happen once an experimental release is ready to go from `npm install astro@next` to `npm install astro`. Only a core contributor run these steps. These steps should be run before +Exiting prerelease mode should happen once an experimental release is ready to go from `npm install astro@next` to `npm install astro`. Only a core contributor can run these steps: - Run: `pnpm exec changeset pre exit` in the project root +- Update `.changeset/config.json` with `"baseBranch": "main"` - Create a new PR from the changes created by this command. -- Review, approve, and more the PR to enter prerelease mode. +- Review, approve, and merge the PR to enter prerelease mode. - If successful, The "[ci] release (next)" PR (if one exists) will now say "[ci] release". ### Releasing `astro@latest` while in prerelease mode diff --git a/examples/basics/package.json b/examples/basics/package.json index be4bf81ad..3390c8634 100644 --- a/examples/basics/package.json +++ b/examples/basics/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.2" + "astro": "^5.0.0-alpha.0" } } diff --git a/examples/blog/package.json b/examples/blog/package.json index 2b248d3a8..e3c9c3bb9 100644 --- a/examples/blog/package.json +++ b/examples/blog/package.json @@ -11,9 +11,9 @@ "astro": "astro" }, "dependencies": { - "@astrojs/mdx": "^3.1.3", + "@astrojs/mdx": "^4.0.0-alpha.0", "@astrojs/rss": "^4.0.7", "@astrojs/sitemap": "^3.1.6", - "astro": "^4.14.2" + "astro": "^5.0.0-alpha.0" } } diff --git a/examples/component/package.json b/examples/component/package.json index 3d2e2bead..9ef977a49 100644 --- a/examples/component/package.json +++ b/examples/component/package.json @@ -15,7 +15,7 @@ ], "scripts": {}, "devDependencies": { - "astro": "^4.14.2" + "astro": "^5.0.0-alpha.0" }, "peerDependencies": { "astro": "^4.0.0" diff --git a/examples/container-with-vitest/package.json b/examples/container-with-vitest/package.json index 1c6732340..b062065f6 100644 --- a/examples/container-with-vitest/package.json +++ b/examples/container-with-vitest/package.json @@ -12,7 +12,7 @@ "test": "vitest run" }, "dependencies": { - "astro": "^4.14.2", + "astro": "^5.0.0-alpha.0", "@astrojs/react": "^3.6.2", "react": "^18.3.1", "react-dom": "^18.3.1", diff --git a/examples/framework-alpine/package.json b/examples/framework-alpine/package.json index 03cfff656..3d494a88f 100644 --- a/examples/framework-alpine/package.json +++ b/examples/framework-alpine/package.json @@ -14,6 +14,6 @@ "@astrojs/alpinejs": "^0.4.0", "@types/alpinejs": "^3.13.10", "alpinejs": "^3.14.1", - "astro": "^4.14.2" + "astro": "^5.0.0-alpha.0" } } diff --git a/examples/framework-lit/.codesandbox/Dockerfile b/examples/framework-lit/.codesandbox/Dockerfile deleted file mode 100644 index c3b5c81a1..000000000 --- a/examples/framework-lit/.codesandbox/Dockerfile +++ /dev/null @@ -1 +0,0 @@ -FROM node:18-bullseye diff --git a/examples/framework-lit/.gitignore b/examples/framework-lit/.gitignore deleted file mode 100644 index 16d54bb13..000000000 --- a/examples/framework-lit/.gitignore +++ /dev/null @@ -1,24 +0,0 @@ -# build output -dist/ -# generated types -.astro/ - -# dependencies -node_modules/ - -# logs -npm-debug.log* -yarn-debug.log* -yarn-error.log* -pnpm-debug.log* - - -# environment variables -.env -.env.production - -# macOS-specific files -.DS_Store - -# jetbrains setting folder -.idea/ diff --git a/examples/framework-lit/.npmrc b/examples/framework-lit/.npmrc deleted file mode 100644 index b417e450e..000000000 --- a/examples/framework-lit/.npmrc +++ /dev/null @@ -1 +0,0 @@ -public-hoist-pattern[]=*lit* diff --git a/examples/framework-lit/.vscode/extensions.json b/examples/framework-lit/.vscode/extensions.json deleted file mode 100644 index 22a15055d..000000000 --- a/examples/framework-lit/.vscode/extensions.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "recommendations": ["astro-build.astro-vscode"], - "unwantedRecommendations": [] -} diff --git a/examples/framework-lit/.vscode/launch.json b/examples/framework-lit/.vscode/launch.json deleted file mode 100644 index d64220976..000000000 --- a/examples/framework-lit/.vscode/launch.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "command": "./node_modules/.bin/astro dev", - "name": "Development server", - "request": "launch", - "type": "node-terminal" - } - ] -} diff --git a/examples/framework-lit/README.md b/examples/framework-lit/README.md deleted file mode 100644 index 714d179da..000000000 --- a/examples/framework-lit/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# Astro + Lit Example - -```sh -npm create astro@latest -- --template framework-lit -``` - -[](https://stackblitz.com/github/withastro/astro/tree/latest/examples/framework-lit) -[](https://codesandbox.io/p/sandbox/github/withastro/astro/tree/latest/examples/framework-lit) -[](https://codespaces.new/withastro/astro?devcontainer_path=.devcontainer/framework-lit/devcontainer.json) - -This example showcases Astro working with [Lit](https://lit.dev/). diff --git a/examples/framework-lit/astro.config.mjs b/examples/framework-lit/astro.config.mjs deleted file mode 100644 index 99733e933..000000000 --- a/examples/framework-lit/astro.config.mjs +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from 'astro/config'; -import lit from '@astrojs/lit'; - -// https://astro.build/config -export default defineConfig({ - // Enable Lit to support LitHTML components and templates. - integrations: [lit()], -}); diff --git a/examples/framework-lit/package.json b/examples/framework-lit/package.json deleted file mode 100644 index cdb7d272a..000000000 --- a/examples/framework-lit/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "@example/framework-lit", - "type": "module", - "version": "0.0.1", - "private": true, - "scripts": { - "dev": "astro dev", - "start": "astro dev", - "build": "astro build", - "preview": "astro preview", - "astro": "astro" - }, - "dependencies": { - "@astrojs/lit": "^4.3.0", - "@webcomponents/template-shadowroot": "^0.2.1", - "astro": "^4.14.2", - "lit": "^3.2.0" - } -} diff --git a/examples/framework-lit/public/assets/logo.svg b/examples/framework-lit/public/assets/logo.svg deleted file mode 100644 index d751556b2..000000000 --- a/examples/framework-lit/public/assets/logo.svg +++ /dev/null @@ -1,12 +0,0 @@ -<svg width="193" height="256" fill="none" xmlns="http://www.w3.org/2000/svg"> - <style> - #flame { fill: #FF5D01; } - #a { fill: #000014; } - @media (prefers-color-scheme: dark) { - #a { fill: #fff; } - } - </style> - - <path id="a" fill-rule="evenodd" clip-rule="evenodd" d="M131.496 18.929c1.943 2.413 2.935 5.67 4.917 12.181l43.309 142.27a180.277 180.277 0 00-51.778-17.53L99.746 60.56a3.67 3.67 0 00-7.042.01l-27.857 95.232a180.224 180.224 0 00-52.01 17.557l43.52-142.281c1.989-6.502 2.983-9.752 4.927-12.16a15.999 15.999 0 016.484-4.798c2.872-1.154 6.271-1.154 13.07-1.154h31.085c6.807 0 10.211 0 13.085 1.157a16 16 0 016.488 4.806z" fill="url(#paint0_linear)"/> - <path id="flame" fill-rule="evenodd" clip-rule="evenodd" d="M136.678 180.151c-7.14 6.105-21.39 10.268-37.804 10.268-20.147 0-37.033-6.272-41.513-14.707-1.602 4.835-1.962 10.367-1.962 13.902 0 0-1.055 17.355 11.016 29.426 0-6.268 5.081-11.349 11.349-11.349 10.743 0 10.731 9.373 10.721 16.977v.679c0 11.542 7.054 21.436 17.086 25.606a23.27 23.27 0 01-2.339-10.2c0-11.008 6.463-15.107 13.973-19.87 5.977-3.79 12.616-8.001 17.192-16.449a31.013 31.013 0 003.744-14.82c0-3.299-.513-6.479-1.463-9.463z" /> -</svg> diff --git a/examples/framework-lit/public/favicon.svg b/examples/framework-lit/public/favicon.svg deleted file mode 100644 index f157bd1c5..000000000 --- a/examples/framework-lit/public/favicon.svg +++ /dev/null @@ -1,9 +0,0 @@ -<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 128 128"> - <path d="M50.4 78.5a75.1 75.1 0 0 0-28.5 6.9l24.2-65.7c.7-2 1.9-3.2 3.4-3.2h29c1.5 0 2.7 1.2 3.4 3.2l24.2 65.7s-11.6-7-28.5-7L67 45.5c-.4-1.7-1.6-2.8-2.9-2.8-1.3 0-2.5 1.1-2.9 2.7L50.4 78.5Zm-1.1 28.2Zm-4.2-20.2c-2 6.6-.6 15.8 4.2 20.2a17.5 17.5 0 0 1 .2-.7 5.5 5.5 0 0 1 5.7-4.5c2.8.1 4.3 1.5 4.7 4.7.2 1.1.2 2.3.2 3.5v.4c0 2.7.7 5.2 2.2 7.4a13 13 0 0 0 5.7 4.9v-.3l-.2-.3c-1.8-5.6-.5-9.5 4.4-12.8l1.5-1a73 73 0 0 0 3.2-2.2 16 16 0 0 0 6.8-11.4c.3-2 .1-4-.6-6l-.8.6-1.6 1a37 37 0 0 1-22.4 2.7c-5-.7-9.7-2-13.2-6.2Z" /> - <style> - path { fill: #000; } - @media (prefers-color-scheme: dark) { - path { fill: #FFF; } - } - </style> -</svg> diff --git a/examples/framework-lit/src/components/Lorem.astro b/examples/framework-lit/src/components/Lorem.astro deleted file mode 100644 index d742ef6a5..000000000 --- a/examples/framework-lit/src/components/Lorem.astro +++ /dev/null @@ -1,106 +0,0 @@ -<p> - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi quam arcu, rhoncus et dui at, - volutpat viverra augue. Suspendisse placerat libero tellus, ut consequat ligula rutrum id. - Vestibulum lectus libero, viverra in lacus eget, porttitor tincidunt leo. Integer sit amet turpis - et felis fringilla lacinia in id nibh. Proin vitae dapibus odio. Mauris ornare eget urna id - volutpat. Duis tellus nisi, hendrerit id sodales in, rutrum a quam. Proin tempor velit turpis, et - tempor lacus sagittis in. Sed congue mauris quis nibh posuere, nec semper lacus auctor. Morbi sit - amet enim sit amet arcu ullamcorper sollicitudin. Donec dignissim posuere tincidunt. Donec - ultrices quam nec orci venenatis suscipit. Maecenas sapien quam, pretium sit amet ullamcorper at, - vulputate sit amet urna. Suspendisse potenti. Integer in sapien turpis. Nulla accumsan viverra - diam, quis convallis magna finibus eget. Integer sed eros bibendum, consequat velit sit amet, - tincidunt orci. Mauris varius id metus in fringilla. Vestibulum dignissim massa eget erat luctus, - ac congue mauris pellentesque. In et tempor dolor. Cras blandit congue lorem at facilisis. Aenean - vel lacinia quam. Pellentesque luctus metus ut scelerisque efficitur. Mauris laoreet sodales - libero eget luctus. Proin at congue dui, a cursus risus. Pellentesque lorem sem, rhoncus fermentum - arcu ut, euismod fermentum ligula. Nullam eu orci posuere, laoreet leo in, commodo dolor. Fusce at - felis elementum, commodo justo at, placerat justo. Nam feugiat scelerisque arcu, ut fermentum - tellus elementum in. Sed ut vulputate ante. Morbi cursus arcu quis odio convallis egestas. Donec - vulputate vestibulum dolor eget tristique. Nullam tempor semper augue, vitae lobortis neque tempor - ac. Pellentesque massa leo, congue id ligula auctor, sollicitudin pharetra lorem. Curabitur a - lacus porttitor, venenatis est quis, mattis velit. Fusce hendrerit lobortis mi ac efficitur. - Mauris ornare, lorem sed varius faucibus, nisi dui pretium urna, sit amet lacinia nibh ligula in - ipsum. Phasellus gravida, metus eget ornare ultrices, dolor ipsum consectetur erat, ac aliquet - eros metus sed lectus. Nullam eleifend posuere rhoncus. Curabitur semper ligula vel ante posuere, - at blandit orci accumsan. Vivamus accumsan metus in lorem laoreet, a luctus arcu tempus. Donec - posuere sollicitudin nulla at vulputate. Nulla condimentum imperdiet purus, et lobortis ligula - iaculis in. Donec suscipit viverra neque, ut elementum eros lacinia ut. Fusce at odio enim. Donec - rutrum lectus sit amet est auctor, ac rhoncus lorem imperdiet. Curabitur commodo ex est, non - tempus massa pulvinar nec. Sed fermentum, lectus eget ultricies luctus, enim sem sodales quam, sed - laoreet tortor sem feugiat nisi. Morbi molestie vehicula viverra. Integer accumsan mi in orci - ultrices posuere. Integer mi quam, faucibus et aliquet imperdiet, ornare ac ex. Nunc mattis - molestie nisi, eu venenatis nibh vehicula at. Aliquam ut elit consectetur, finibus lorem sed, - condimentum sapien. Praesent fermentum iaculis orci, vitae tincidunt est viverra nec. Morbi semper - turpis sed lectus ornare tristique. Sed congue dui ex. Maecenas orci ligula, imperdiet sit amet - accumsan et, finibus a velit. Ut vitae blandit eros. Nam gravida nec ipsum non volutpat. Integer - quam metus, porttitor id ante sed, rutrum porta quam. Aenean at mattis ante. Morbi id libero eget - risus sagittis gravida. Proin consequat sapien a dignissim posuere. Ut luctus sed metus ut - elementum. Mauris tincidunt condimentum risus at bibendum. Aenean a sapien justo. Morbi vel neque - in eros venenatis scelerisque vitae nec justo. Vestibulum lacinia, dui eu sollicitudin ornare, est - elit vestibulum arcu, nec ultrices augue turpis in massa. Duis commodo lectus sed est posuere, et - mollis nisi dapibus. Sed id ultrices arcu. Praesent tempor sodales aliquet. Donec suscipit ipsum - eu odio cursus, quis sodales metus sodales. Nunc vestibulum massa at felis ullamcorper cursus. - Pellentesque facilisis ante ut lectus vulputate vestibulum. Nullam pharetra felis ac lacus - sodales, vel suscipit metus faucibus. Donec facilisis imperdiet risus, in volutpat odio tincidunt - a. Aliquam vitae leo lorem. Proin scelerisque efficitur velit, vel cursus ipsum accumsan id. Morbi - nibh nulla, pretium quis venenatis et, pharetra et sapien. Cras lobortis, massa sit amet blandit - pulvinar, mi magna condimentum ex, quis commodo ipsum est quis metus. Maecenas pulvinar, leo sit - amet congue pulvinar, neque magna ultrices mi, et rhoncus massa sapien quis libero. Etiam a nunc - et ipsum faucibus pretium. Nulla facilisi. Nunc nec dolor velit. In semper semper mi non - condimentum. Pellentesque vehicula volutpat odio, a semper sem porta a. In sit amet lectus rutrum, - sollicitudin augue auctor, maximus quam. Mauris congue, nisl non fermentum iaculis, leo erat - interdum lorem, quis bibendum arcu eros et elit. Fusce tortor ante, gravida a arcu in, lacinia - finibus ante. Phasellus facilisis lectus vitae sapien feugiat laoreet. Curabitur ultricies libero - sit amet condimentum suscipit. Duis at vestibulum mi. Suspendisse at neque augue. Duis ornare a - mauris id efficitur. Suspendisse in dui nec dolor dignissim venenatis. Curabitur a magna turpis. - Aliquam at commodo tellus. In id sem interdum, suscipit felis at, mattis velit. Proin accumsan - sodales felis a lacinia. Curabitur at magna a massa varius maximus. Vestibulum in auctor ante. - Donec aliquam tortor sed nulla rutrum, et egestas mi efficitur. Sed viverra quam tellus, quis - vulputate felis ultrices sed. Mauris sagittis, neque quis laoreet gravida, nisi est ultrices mi, - at tempus nunc justo non dui. Suspendisse porttitor tortor nulla, eget luctus quam finibus id. - Proin sodales eros mollis tellus euismod luctus a eu mi. Quisque consectetur iaculis nibh, at - mollis tellus volutpat eu. Aenean a nulla vel lectus rhoncus aliquam. Donec vitae lacinia neque. - Donec non lectus eget sem finibus ultrices vel nec felis. Proin fringilla mi a leo rhoncus aliquam - sit amet quis augue. Duis congue ligula at est suscipit fringilla. Proin aliquam erat ut consequat - dapibus. Suspendisse non nisi orci. Donec ac erat vel libero egestas laoreet. Nullam felis odio, - tincidunt eget eleifend a, porttitor eu nisi. Suspendisse tristique eros at dolor scelerisque - hendrerit. Etiam id dignissim lectus. Fusce lacinia metus eu risus placerat, et eleifend nunc - ultrices. Ut gravida a dui sed volutpat. Sed semper quis erat sed ornare. Pellentesque sapien sem, - fermentum vel nunc at, auctor posuere nisl. Maecenas aliquet lobortis leo. Vivamus tellus urna, - dignissim consectetur sapien vitae, hendrerit varius sem. Nunc dictum tristique fermentum. Duis eu - suscipit odio. Curabitur quis egestas neque. Fusce eu fringilla orci, vitae euismod sapien. Donec - sit amet iaculis urna. Phasellus maximus nisl in libero bibendum volutpat. Nulla at vehicula - lorem. Phasellus varius, elit ac suscipit pretium, turpis ipsum porttitor lectus, vitae - ullamcorper orci velit ut ligula. Proin mollis, orci vel commodo auctor, sapien ipsum vulputate - enim, sit amet aliquam nulla sapien ut sapien. Proin tincidunt ex non massa aliquet, quis aliquam - nulla egestas. Maecenas mollis turpis dapibus, dignissim lectus tincidunt, egestas ligula. - Suspendisse in lobortis purus. Sed tellus tellus, mollis eget tempor sed, interdum ut lectus. - Nulla sed ex efficitur, porta dui cursus, tristique elit. Maecenas tincidunt tortor vitae massa - laoreet ultricies. Mauris ac elit vitae orci eleifend ornare non eu ligula. Curabitur venenatis - nulla ut neque tristique, non tincidunt justo pretium. Suspendisse mattis semper dui, eget - vestibulum risus elementum sed. In consequat nisi sit amet nulla euismod, at convallis tortor - tincidunt. Aliquam hendrerit venenatis risus in interdum. Duis ullamcorper imperdiet elit sit amet - blandit. Mauris placerat lacinia velit id pharetra. Nam nec iaculis dui. Etiam odio mi, fringilla - in rutrum in, viverra quis tellus. Aliquam egestas mauris id nisi facilisis, in laoreet nibh - malesuada. Ut eu dui laoreet, venenatis tellus ac, feugiat mauris. Nunc in velit laoreet, - venenatis tellus quis, blandit dolor. Nulla ultrices et neque id placerat. Nulla eu interdum - nulla. Aliquam molestie enim quis rutrum finibus. Nulla bibendum orci vel scelerisque posuere. - Praesent quis magna molestie, luctus tortor tincidunt, gravida neque. Quisque et ligula eget magna - viverra interdum at a sapien. Mauris ornare efficitur nunc sed vulputate. Praesent laoreet mollis - tincidunt. Vestibulum id arcu vulputate, eleifend enim vel, accumsan turpis. Morbi faucibus - convallis tellus, semper laoreet justo lacinia nec. Sed sodales ligula consectetur dui rhoncus, et - convallis metus accumsan. Sed ullamcorper non ex sit amet ultricies. Donec finibus nulla nec - blandit porttitor. Etiam aliquam quis leo a imperdiet. Cras at lobortis est. In convallis semper - enim, ac porta ligula fringilla at. Donec augue est, facilisis et odio sit amet, viverra - ullamcorper nisl. Ut porta velit nec sem lacinia, sit amet mollis magna auctor. Nulla lobortis - lacinia mauris nec sagittis. Suspendisse rutrum ex vel nisi interdum hendrerit et ut purus. Sed - consectetur sodales nibh eget tempus. Aenean egestas luctus viverra. Integer fermentum tincidunt - tellus, nec rhoncus velit hendrerit vitae. Proin quis neque porttitor, scelerisque risus gravida, - volutpat sem. Fusce nec ex rhoncus, tempor libero nec, pellentesque ex. Integer quis iaculis - purus. Nullam vitae imperdiet orci. Sed sit amet eros condimentum, scelerisque turpis facilisis, - dignissim ante. Proin quis tristique lacus, sed sagittis nisl. Cras pharetra ultrices purus, sed - ullamcorper nisi fringilla eu. Praesent risus turpis, auctor in fringilla a, fringilla eu dolor. - Phasellus auctor tristique enim, eleifend molestie diam venenatis ut. Mauris dapibus, enim eget - pharetra semper, nulla dui porttitor mi, auctor hendrerit augue nulla quis urna. Aliquam in cursus - justo. -</p> diff --git a/examples/framework-lit/src/components/calc-add.js b/examples/framework-lit/src/components/calc-add.js deleted file mode 100644 index b0b3978bf..000000000 --- a/examples/framework-lit/src/components/calc-add.js +++ /dev/null @@ -1,17 +0,0 @@ -import { LitElement, html } from 'lit'; - -export class CalcAdd extends LitElement { - static get properties() { - return { - num: { - type: Number, - }, - }; - } - - render() { - return html` <div>Number: ${this.num}</div> `; - } -} - -customElements.define('calc-add', CalcAdd); diff --git a/examples/framework-lit/src/components/my-counter.js b/examples/framework-lit/src/components/my-counter.js deleted file mode 100644 index adc9e4a3d..000000000 --- a/examples/framework-lit/src/components/my-counter.js +++ /dev/null @@ -1,32 +0,0 @@ -import { LitElement, html } from 'lit'; - -export class MyCounter extends LitElement { - static get properties() { - return { - count: { - type: Number, - }, - }; - } - - constructor() { - super(); - this.count = 0; - } - - increment() { - this.count++; - } - - render() { - return html` - <div> - <p>Count: ${this.count}</p> - - <button type="button" @click=${this.increment}>Increment</button> - </div> - `; - } -} - -customElements.define('my-counter', MyCounter); diff --git a/examples/framework-lit/src/env.d.ts b/examples/framework-lit/src/env.d.ts deleted file mode 100644 index e16c13c69..000000000 --- a/examples/framework-lit/src/env.d.ts +++ /dev/null @@ -1 +0,0 @@ -/// <reference path="../.astro/types.d.ts" /> diff --git a/examples/framework-lit/src/pages/index.astro b/examples/framework-lit/src/pages/index.astro deleted file mode 100644 index 5fa6fed67..000000000 --- a/examples/framework-lit/src/pages/index.astro +++ /dev/null @@ -1,35 +0,0 @@ ---- -import Lorem from '../components/Lorem.astro'; -import { CalcAdd } from '../components/calc-add.js'; -import { MyCounter } from '../components/my-counter.js'; - -// Full Astro Component Syntax: -// https://docs.astro.build/basics/astro-components/ ---- - -<!doctype html> -<html lang="en"> - <head> - <meta charset="utf-8" /> - <meta name="viewport" content="width=device-width" /> - <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> - <title>Demo</title> - </head> - <body> - <h1>Test app</h1> - <MyCounter client:load /> - <Lorem /> - - { - ( - /** - * Our editor tooling does not currently properly typecheck attributes on imported Lit components. As such, without a - * pragma directive telling TypeScript to ignore the error, the line below will result in an error in the editor. - * Nonetheless, this code works in Astro itself! - */ - // @ts-expect-error - <CalcAdd num={0} /> - ) - } - </body> -</html> diff --git a/examples/framework-lit/tsconfig.json b/examples/framework-lit/tsconfig.json deleted file mode 100644 index d78f81ec4..000000000 --- a/examples/framework-lit/tsconfig.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "astro/tsconfigs/base" -} diff --git a/examples/framework-multiple/package.json b/examples/framework-multiple/package.json index 043cee15e..ec4d835ec 100644 --- a/examples/framework-multiple/package.json +++ b/examples/framework-multiple/package.json @@ -14,11 +14,11 @@ "@astrojs/preact": "^3.5.1", "@astrojs/react": "^3.6.2", "@astrojs/solid-js": "^4.4.1", - "@astrojs/svelte": "^5.7.0", - "@astrojs/vue": "^4.5.0", + "@astrojs/svelte": "^6.0.0-alpha.0", + "@astrojs/vue": "^5.0.0-alpha.0", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", - "astro": "^4.14.2", + "astro": "^5.0.0-alpha.0", "preact": "^10.23.2", "react": "^18.3.1", "react-dom": "^18.3.1", diff --git a/examples/framework-preact/package.json b/examples/framework-preact/package.json index cb70d3a9f..c2635c093 100644 --- a/examples/framework-preact/package.json +++ b/examples/framework-preact/package.json @@ -13,7 +13,7 @@ "dependencies": { "@astrojs/preact": "^3.5.1", "@preact/signals": "^1.3.0", - "astro": "^4.14.2", + "astro": "^5.0.0-alpha.0", "preact": "^10.23.2" } } diff --git a/examples/framework-react/package.json b/examples/framework-react/package.json index 4fbde09c6..f1585c4c1 100644 --- a/examples/framework-react/package.json +++ b/examples/framework-react/package.json @@ -14,7 +14,7 @@ "@astrojs/react": "^3.6.2", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", - "astro": "^4.14.2", + "astro": "^5.0.0-alpha.0", "react": "^18.3.1", "react-dom": "^18.3.1" } diff --git a/examples/framework-solid/package.json b/examples/framework-solid/package.json index 6d234f05c..05e6ec738 100644 --- a/examples/framework-solid/package.json +++ b/examples/framework-solid/package.json @@ -12,7 +12,7 @@ }, "dependencies": { "@astrojs/solid-js": "^4.4.1", - "astro": "^4.14.2", + "astro": "^5.0.0-alpha.0", "solid-js": "^1.8.21" } } diff --git a/examples/framework-svelte/package.json b/examples/framework-svelte/package.json index 42a99cd24..1cec15cbc 100644 --- a/examples/framework-svelte/package.json +++ b/examples/framework-svelte/package.json @@ -11,8 +11,8 @@ "astro": "astro" }, "dependencies": { - "@astrojs/svelte": "^5.7.0", - "astro": "^4.14.2", + "@astrojs/svelte": "^6.0.0-alpha.0", + "astro": "^5.0.0-alpha.0", "svelte": "^4.2.18" } } diff --git a/examples/framework-vue/package.json b/examples/framework-vue/package.json index 2e9653a88..ad8546684 100644 --- a/examples/framework-vue/package.json +++ b/examples/framework-vue/package.json @@ -11,8 +11,8 @@ "astro": "astro" }, "dependencies": { - "@astrojs/vue": "^4.5.0", - "astro": "^4.14.2", + "@astrojs/vue": "^5.0.0-alpha.0", + "astro": "^5.0.0-alpha.0", "vue": "^3.4.38" } } diff --git a/examples/hackernews/package.json b/examples/hackernews/package.json index bc5ee46b2..4b6a2af10 100644 --- a/examples/hackernews/package.json +++ b/examples/hackernews/package.json @@ -11,7 +11,7 @@ "astro": "astro" }, "dependencies": { - "@astrojs/node": "^8.3.3", - "astro": "^4.14.2" + "@astrojs/node": "^9.0.0-alpha.0", + "astro": "^5.0.0-alpha.0" } } diff --git a/examples/integration/index.ts b/examples/integration/index.ts index 8b34afd23..1fafd4e15 100644 --- a/examples/integration/index.ts +++ b/examples/integration/index.ts @@ -11,8 +11,8 @@ export default function createIntegration(): AstroIntegration { // https://github.com/withastro/astro/blob/main/packages/integrations/react/src/index.ts }, 'astro:build:setup': () => { - // See the @astrojs/lit integration for an example - // https://github.com/withastro/astro/blob/main/packages/integrations/lit/src/index.ts + // See the @astrojs/react integration for an example + // https://github.com/withastro/astro/blob/main/packages/integrations/react/src/index.ts }, 'astro:build:done': () => { // See the @astrojs/partytown integration for an example diff --git a/examples/integration/package.json b/examples/integration/package.json index d8225462a..2b5f62ef3 100644 --- a/examples/integration/package.json +++ b/examples/integration/package.json @@ -15,7 +15,7 @@ ], "scripts": {}, "devDependencies": { - "astro": "^4.14.2" + "astro": "^5.0.0-alpha.0" }, "peerDependencies": { "astro": "^4.0.0" diff --git a/examples/middleware/package.json b/examples/middleware/package.json index db80ba2fe..4c7fa55de 100644 --- a/examples/middleware/package.json +++ b/examples/middleware/package.json @@ -12,8 +12,8 @@ "server": "node dist/server/entry.mjs" }, "dependencies": { - "@astrojs/node": "^8.3.3", - "astro": "^4.14.2", + "@astrojs/node": "^9.0.0-alpha.0", + "astro": "^5.0.0-alpha.0", "html-minifier": "^4.0.0" }, "devDependencies": { diff --git a/examples/minimal/package.json b/examples/minimal/package.json index 129a0e1c6..d18bbd27a 100644 --- a/examples/minimal/package.json +++ b/examples/minimal/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.2" + "astro": "^5.0.0-alpha.0" } } diff --git a/examples/non-html-pages/package.json b/examples/non-html-pages/package.json index 14750d841..f5e09395a 100644 --- a/examples/non-html-pages/package.json +++ b/examples/non-html-pages/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.2" + "astro": "^5.0.0-alpha.0" } } diff --git a/examples/portfolio/package.json b/examples/portfolio/package.json index 22e75e141..b0620901e 100644 --- a/examples/portfolio/package.json +++ b/examples/portfolio/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.2" + "astro": "^5.0.0-alpha.0" } } diff --git a/examples/server-islands/package.json b/examples/server-islands/package.json index adf39cd38..96ac136ab 100644 --- a/examples/server-islands/package.json +++ b/examples/server-islands/package.json @@ -10,14 +10,14 @@ "astro": "astro" }, "devDependencies": { - "@astrojs/node": "^8.3.3", + "@astrojs/node": "^9.0.0-alpha.0", "@astrojs/react": "^3.6.2", - "@astrojs/tailwind": "^5.1.0", + "@astrojs/tailwind": "^6.0.0-alpha.0", "@fortawesome/fontawesome-free": "^6.6.0", "@tailwindcss/forms": "^0.5.7", "@types/react": "^18.3.3", "@types/react-dom": "^18.3.0", - "astro": "^4.14.2", + "astro": "^5.0.0-alpha.0", "postcss": "^8.4.41", "react": "^18.3.1", "react-dom": "^18.3.1", diff --git a/examples/ssr/package.json b/examples/ssr/package.json index d35df0ec4..cb9e2a4cb 100644 --- a/examples/ssr/package.json +++ b/examples/ssr/package.json @@ -12,9 +12,9 @@ "server": "node dist/server/entry.mjs" }, "dependencies": { - "@astrojs/node": "^8.3.3", - "@astrojs/svelte": "^5.7.0", - "astro": "^4.14.2", + "@astrojs/node": "^9.0.0-alpha.0", + "@astrojs/svelte": "^6.0.0-alpha.0", + "astro": "^5.0.0-alpha.0", "svelte": "^4.2.18" } } diff --git a/examples/starlog/package.json b/examples/starlog/package.json index 905df4a69..9e03a65ad 100644 --- a/examples/starlog/package.json +++ b/examples/starlog/package.json @@ -10,7 +10,7 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.2", + "astro": "^5.0.0-alpha.0", "sass": "^1.77.8", "sharp": "^0.33.3" } diff --git a/examples/toolbar-app/package.json b/examples/toolbar-app/package.json index d08c29bca..fb8551ae6 100644 --- a/examples/toolbar-app/package.json +++ b/examples/toolbar-app/package.json @@ -15,6 +15,6 @@ "./app": "./dist/app.js" }, "devDependencies": { - "astro": "^4.14.2" + "astro": "^5.0.0-alpha.0" } } diff --git a/examples/view-transitions/package.json b/examples/view-transitions/package.json index 7448b9ec0..f568ec7a1 100644 --- a/examples/view-transitions/package.json +++ b/examples/view-transitions/package.json @@ -10,8 +10,8 @@ "astro": "astro" }, "devDependencies": { - "@astrojs/tailwind": "^5.1.0", - "@astrojs/node": "^8.3.3", - "astro": "^4.14.2" + "@astrojs/tailwind": "^6.0.0-alpha.0", + "@astrojs/node": "^9.0.0-alpha.0", + "astro": "^5.0.0-alpha.0" } } diff --git a/examples/with-markdoc/package.json b/examples/with-markdoc/package.json index 1af3bc63c..23a78a6ac 100644 --- a/examples/with-markdoc/package.json +++ b/examples/with-markdoc/package.json @@ -11,7 +11,7 @@ "astro": "astro" }, "dependencies": { - "@astrojs/markdoc": "^0.11.3", - "astro": "^4.14.2" + "@astrojs/markdoc": "^1.0.0-alpha.0", + "astro": "^5.0.0-alpha.0" } } diff --git a/examples/with-markdown-plugins/package.json b/examples/with-markdown-plugins/package.json index 61f125345..f44497713 100644 --- a/examples/with-markdown-plugins/package.json +++ b/examples/with-markdown-plugins/package.json @@ -11,8 +11,8 @@ "astro": "astro" }, "dependencies": { - "@astrojs/markdown-remark": "^5.2.0", - "astro": "^4.14.2", + "@astrojs/markdown-remark": "^6.0.0-alpha.0", + "astro": "^5.0.0-alpha.0", "hast-util-select": "^6.0.2", "rehype-autolink-headings": "^7.1.0", "rehype-slug": "^6.0.0", diff --git a/examples/with-markdown-shiki/package.json b/examples/with-markdown-shiki/package.json index e1486a376..1e5a875cc 100644 --- a/examples/with-markdown-shiki/package.json +++ b/examples/with-markdown-shiki/package.json @@ -11,6 +11,6 @@ "astro": "astro" }, "dependencies": { - "astro": "^4.14.2" + "astro": "^5.0.0-alpha.0" } } diff --git a/examples/with-mdx/package.json b/examples/with-mdx/package.json index e83c26abc..d5d61d16d 100644 --- a/examples/with-mdx/package.json +++ b/examples/with-mdx/package.json @@ -11,9 +11,9 @@ "astro": "astro" }, "dependencies": { - "@astrojs/mdx": "^3.1.3", + "@astrojs/mdx": "^4.0.0-alpha.0", "@astrojs/preact": "^3.5.1", - "astro": "^4.14.2", + "astro": "^5.0.0-alpha.0", "preact": "^10.23.2" } } diff --git a/examples/with-nanostores/package.json b/examples/with-nanostores/package.json index 709d6388c..db6080d09 100644 --- a/examples/with-nanostores/package.json +++ b/examples/with-nanostores/package.json @@ -13,7 +13,7 @@ "dependencies": { "@astrojs/preact": "^3.5.1", "@nanostores/preact": "^0.5.2", - "astro": "^4.14.2", + "astro": "^5.0.0-alpha.0", "nanostores": "^0.11.2", "preact": "^10.23.2" } diff --git a/examples/with-tailwindcss/package.json b/examples/with-tailwindcss/package.json index cd5e7b994..5fc07f1de 100644 --- a/examples/with-tailwindcss/package.json +++ b/examples/with-tailwindcss/package.json @@ -11,10 +11,10 @@ "astro": "astro" }, "dependencies": { - "@astrojs/mdx": "^3.1.3", - "@astrojs/tailwind": "^5.1.0", + "@astrojs/mdx": "^4.0.0-alpha.0", + "@astrojs/tailwind": "^6.0.0-alpha.0", "@types/canvas-confetti": "^1.6.4", - "astro": "^4.14.2", + "astro": "^5.0.0-alpha.0", "autoprefixer": "^10.4.20", "canvas-confetti": "^1.9.3", "postcss": "^8.4.41", diff --git a/examples/with-vitest/package.json b/examples/with-vitest/package.json index 88956a94e..40ea3ea32 100644 --- a/examples/with-vitest/package.json +++ b/examples/with-vitest/package.json @@ -12,7 +12,7 @@ "test": "vitest" }, "dependencies": { - "astro": "^4.14.2", + "astro": "^5.0.0-alpha.0", "vitest": "^2.0.5" } } diff --git a/packages/astro/CHANGELOG.md b/packages/astro/CHANGELOG.md index 5c93709a4..1a9256585 100644 --- a/packages/astro/CHANGELOG.md +++ b/packages/astro/CHANGELOG.md @@ -1,5 +1,80 @@ # astro +## 5.0.0-alpha.0 + +### Major Changes + +- [#10742](https://github.com/withastro/astro/pull/10742) [`b6fbdaa`](https://github.com/withastro/astro/commit/b6fbdaa94a9ecec706a99e1938fbf5cd028c72e0) Thanks [@ematipico](https://github.com/ematipico)! - The lowest version of Node supported by Astro is now Node v18.17.1 and higher. + +- [#11715](https://github.com/withastro/astro/pull/11715) [`d74617c`](https://github.com/withastro/astro/commit/d74617cbd3278feba05909ec83db2d73d57a153e) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Refactor the exported types from the `astro` module. There should normally be no breaking changes, but if you relied on some previously deprecated types, these might now have been fully removed. + + In most cases, updating your code to move away from previously deprecated APIs in previous versions of Astro should be enough to fix any issues. + +- [#11660](https://github.com/withastro/astro/pull/11660) [`e90f559`](https://github.com/withastro/astro/commit/e90f5593d23043579611452a84b9e18ad2407ef9) Thanks [@bluwy](https://github.com/bluwy)! - Fixes attribute rendering for non-[boolean HTML attributes](https://developer.mozilla.org/en-US/docs/Glossary/Boolean/HTML) with boolean values to match proper attribute handling in browsers. + + Previously, non-boolean attributes may not have included their values when rendered to HTML. In Astro v5.0, the values are now explicitly rendered as `="true"` or `="false"` + + In the following `.astro` examples, only `allowfullscreen` is a boolean attribute: + + ```astro + <!-- src/pages/index.astro --><!-- `allowfullscreen` is a boolean attribute --> + <p allowfullscreen={true}></p> + <p allowfullscreen={false}></p> + + <!-- `inherit` is *not* a boolean attribute --> + <p inherit={true}></p> + <p inherit={false}></p> + + <!-- `data-*` attributes are not boolean attributes --> + <p data-light={true}></p> + <p data-light={false}></p> + ``` + + Astro v5.0 now preserves the full data attribute with its value when rendering the HTML of non-boolean attributes: + + ```diff + <p allowfullscreen></p> + <p></p> + + <p inherit="true"></p> + - <p inherit></p> + + <p inherit="false"></p> + + - <p data-light></p> + + <p data-light="true"></p> + - <p></p> + + <p data-light="false"></p> + ``` + + If you rely on attribute values, for example to locate elements or to conditionally render, update your code to match the new non-boolean attribute values: + + ```diff + - el.getAttribute('inherit') === '' + + el.getAttribute('inherit') === 'false' + + - el.hasAttribute('data-light') + + el.dataset.light === 'true' + ``` + +- [#11714](https://github.com/withastro/astro/pull/11714) [`8a53517`](https://github.com/withastro/astro/commit/8a5351737d6a14fc55f1dafad8f3b04079e81af6) Thanks [@matthewp](https://github.com/matthewp)! - Remove support for functionPerRoute + + This change removes support for the `functionPerRoute` option both in Astro and `@astrojs/vercel`. + + This option made it so that each route got built as separate entrypoints so that they could be loaded as separate functions. The hope was that by doing this it would decrease the size of each function. However in practice routes use most of the same code, and increases in function size limitations made the potential upsides less important. + + Additionally there are downsides to functionPerRoute, such as hitting limits on the number of functions per project. The feature also never worked with some Astro features like i18n domains and request rewriting. + + Given this, the feature has been removed from Astro. + +### Patch Changes + +- [#11745](https://github.com/withastro/astro/pull/11745) [`89bab1e`](https://github.com/withastro/astro/commit/89bab1e70786123fbe933a9d7a1b80c9334dcc5f) Thanks [@bluwy](https://github.com/bluwy)! - Prints prerender dynamic value usage warning only if it's used + +- [#11730](https://github.com/withastro/astro/pull/11730) [`2df49a6`](https://github.com/withastro/astro/commit/2df49a6fb4f6d92fe45f7429430abe63defeacd6) Thanks [@florian-lefebvre](https://github.com/florian-lefebvre)! - Simplifies path operations of `astro sync` + +- Updated dependencies [[`83a2a64`](https://github.com/withastro/astro/commit/83a2a648418ad30f4eb781d1c1b5f2d8a8ac846e)]: + - @astrojs/markdown-remark@6.0.0-alpha.0 + ## 4.14.2 ### Patch Changes diff --git a/packages/astro/astro-jsx.d.ts b/packages/astro/astro-jsx.d.ts index b26507d1d..128709dfc 100644 --- a/packages/astro/astro-jsx.d.ts +++ b/packages/astro/astro-jsx.d.ts @@ -17,23 +17,21 @@ declare namespace astroHTML.JSX { children: {}; } - interface IntrinsicAttributes - extends AstroBuiltinProps, - AstroBuiltinAttributes, - AstroClientDirectives { + interface IntrinsicAttributes extends AstroComponentDirectives, AstroBuiltinAttributes { slot?: string | undefined | null; children?: Children; } - type AstroBuiltinProps = import('./dist/@types/astro.js').AstroBuiltinProps; - type AstroClientDirectives = import('./dist/@types/astro.js').AstroClientDirectives; - type AstroBuiltinAttributes = import('./dist/@types/astro.js').AstroBuiltinAttributes; - type AstroDefineVarsAttribute = import('./dist/@types/astro.js').AstroDefineVarsAttribute; - type AstroScriptAttributes = import('./dist/@types/astro.js').AstroScriptAttributes & + type AstroComponentDirectives = + import('./dist/types/public/elements.js').AstroComponentDirectives; + type AstroBuiltinAttributes = import('./dist/types/public/elements.js').AstroBuiltinAttributes; + type AstroDefineVarsAttribute = + import('./dist/types/public/elements.js').AstroDefineVarsAttribute; + type AstroScriptAttributes = import('./dist/types/public/elements.js').AstroScriptAttributes & AstroDefineVarsAttribute; - type AstroStyleAttributes = import('./dist/@types/astro.js').AstroStyleAttributes & + type AstroStyleAttributes = import('./dist/types/public/elements.js').AstroStyleAttributes & AstroDefineVarsAttribute; - type AstroSlotAttributes = import('./dist/@types/astro.js').AstroSlotAttributes; + type AstroSlotAttributes = import('./dist/types/public/elements.js').AstroSlotAttributes; // This is an unfortunate use of `any`, but unfortunately we can't make a type that works for every framework // without importing every single framework's types (which comes with its own set of problems). diff --git a/packages/astro/astro.js b/packages/astro/astro.js index 2000ca566..a02e60b76 100755 --- a/packages/astro/astro.js +++ b/packages/astro/astro.js @@ -12,7 +12,7 @@ const CI_INSTRUCTIONS = { }; // Hardcode supported Node.js version so we don't have to read differently in CJS & ESM. -const engines = '>=18.14.1'; +const engines = '>=18.17.1'; const skipSemverCheckIfAbove = 19; /** `astro *` */ diff --git a/packages/astro/client.d.ts b/packages/astro/client.d.ts index ed5c1b894..796bf3f33 100644 --- a/packages/astro/client.d.ts +++ b/packages/astro/client.d.ts @@ -2,12 +2,6 @@ /// <reference path="./types/content.d.ts" /> /// <reference path="./types/actions.d.ts" /> -// eslint-disable-next-line @typescript-eslint/no-namespace -declare namespace App { - // eslint-disable-next-line @typescript-eslint/no-empty-interface - export interface Locals {} -} - interface ImportMetaEnv { /** * The prefix for Astro-generated asset links if the build.assetsPrefix config option is set. This can be used to create asset links not handled by Astro. @@ -52,7 +46,7 @@ declare module 'astro:assets' { getImage: ( options: import('./dist/assets/types.js').UnresolvedImageTransform, ) => Promise<import('./dist/assets/types.js').GetImageResult>; - imageConfig: import('./dist/@types/astro.js').AstroConfig['image']; + imageConfig: import('./dist/types/public/config.js').AstroConfig['image']; getConfiguredImageService: typeof import('./dist/assets/index.js').getConfiguredImageService; inferRemoteSize: typeof import('./dist/assets/utils/index.js').inferRemoteSize; Image: typeof import('./components/Image.astro').default; @@ -172,7 +166,7 @@ declare module 'astro:components' { export * from 'astro/components'; } -type MD = import('./dist/@types/astro.js').MarkdownInstance<Record<string, any>>; +type MD = import('./dist/types/public/content.js').MarkdownInstance<Record<string, any>>; interface ExportedMarkdownModuleEntities { frontmatter: MD['frontmatter']; file: MD['file']; @@ -191,7 +185,6 @@ declare module '*.md' { file, url, getHeadings, - getHeaders, Content, rawContent, compiledContent, @@ -206,7 +199,6 @@ declare module '*.markdown' { file, url, getHeadings, - getHeaders, Content, rawContent, compiledContent, @@ -221,7 +213,6 @@ declare module '*.mkdn' { file, url, getHeadings, - getHeaders, Content, rawContent, compiledContent, @@ -236,7 +227,6 @@ declare module '*.mkd' { file, url, getHeadings, - getHeaders, Content, rawContent, compiledContent, @@ -251,7 +241,6 @@ declare module '*.mdwn' { file, url, getHeadings, - getHeaders, Content, rawContent, compiledContent, @@ -266,7 +255,6 @@ declare module '*.mdown' { file, url, getHeadings, - getHeaders, Content, rawContent, compiledContent, @@ -275,7 +263,7 @@ declare module '*.mdown' { } declare module '*.mdx' { - type MDX = import('./dist/@types/astro.js').MDXInstance<Record<string, any>>; + type MDX = import('./dist/types/public/content.js').MDXInstance<Record<string, any>>; export const frontmatter: MDX['frontmatter']; export const file: MDX['file']; @@ -288,7 +276,7 @@ declare module '*.mdx' { } declare module 'astro:ssr-manifest' { - export const manifest: import('./dist/@types/astro.js').SSRManifest; + export const manifest: import('./dist/types/public/internal.js').SSRManifest; } // Everything below are Vite's types (apart from image types, which are in `client.d.ts`) diff --git a/packages/astro/components/Picture.astro b/packages/astro/components/Picture.astro index c85548404..73459db04 100644 --- a/packages/astro/components/Picture.astro +++ b/packages/astro/components/Picture.astro @@ -1,9 +1,9 @@ --- import { type LocalImageProps, type RemoteImageProps, getImage } from 'astro:assets'; import * as mime from 'mrmime'; -import type { GetImageResult, ImageOutputFormat } from '../dist/@types/astro'; import { isESMImportedImage, resolveSrc } from '../dist/assets/utils/imageKind'; import { AstroError, AstroErrorData } from '../dist/core/errors/index.js'; +import type { GetImageResult, ImageOutputFormat } from '../dist/types/public/index.js'; import type { HTMLAttributes } from '../types'; type Props = (LocalImageProps | RemoteImageProps) & { diff --git a/packages/astro/config.d.ts b/packages/astro/config.d.ts index 68743b35d..a6f1191e0 100644 --- a/packages/astro/config.d.ts +++ b/packages/astro/config.d.ts @@ -1,8 +1,8 @@ type ViteUserConfig = import('vite').UserConfig; type ViteUserConfigFn = import('vite').UserConfigFn; -type AstroUserConfig = import('./dist/@types/astro.js').AstroUserConfig; -type AstroInlineConfig = import('./dist/@types/astro.js').AstroInlineConfig; -type ImageServiceConfig = import('./dist/@types/astro.js').ImageServiceConfig; +type AstroUserConfig = import('./dist/types/public/config.js').AstroUserConfig; +type AstroInlineConfig = import('./dist/types/public/config.js').AstroInlineConfig; +type ImageServiceConfig = import('./dist/types/public/config.js').ImageServiceConfig; type SharpImageServiceConfig = import('./dist/assets/services/sharp.js').SharpImageServiceConfig; type EnvField = typeof import('./dist/env/config.js').envField; @@ -45,4 +45,4 @@ export function passthroughImageService(): ImageServiceConfig; /** * Return a valid env field to use in this Astro config for `experimental.env.schema`. */ -export const envField: EnvField; +export declare const envField: EnvField; diff --git a/packages/astro/e2e/fixtures/lit-component/astro.config.mjs b/packages/astro/e2e/fixtures/lit-component/astro.config.mjs deleted file mode 100644 index 24de2f1b5..000000000 --- a/packages/astro/e2e/fixtures/lit-component/astro.config.mjs +++ /dev/null @@ -1,10 +0,0 @@ -import lit from '@astrojs/lit'; -import { defineConfig } from 'astro/config'; - -// https://astro.build/config -export default defineConfig({ - integrations: [lit()], - devToolbar: { - enabled: false, - } -}); diff --git a/packages/astro/e2e/fixtures/lit-component/package.json b/packages/astro/e2e/fixtures/lit-component/package.json deleted file mode 100644 index 0db0d4111..000000000 --- a/packages/astro/e2e/fixtures/lit-component/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@e2e/lit-component", - "version": "0.0.0", - "private": true, - "dependencies": { - "@astrojs/lit": "workspace:*", - "@webcomponents/template-shadowroot": "^0.2.1", - "astro": "workspace:*", - "lit": "^3.2.0" - } -} diff --git a/packages/astro/e2e/fixtures/lit-component/src/components/ClientOnlyComponent.js b/packages/astro/e2e/fixtures/lit-component/src/components/ClientOnlyComponent.js deleted file mode 100644 index 0fd16b50a..000000000 --- a/packages/astro/e2e/fixtures/lit-component/src/components/ClientOnlyComponent.js +++ /dev/null @@ -1,9 +0,0 @@ -import { LitElement, html } from 'lit'; - -export default class ClientOnlyComponent extends LitElement { - render() { - return html`<slot><div class="defaultContent"> Shadow dom default content should not be visible</div></slot><slot name="foo"></slot><slot name="bar"></slot></div>`; - } -} - -customElements.define('client-only-component', ClientOnlyComponent); diff --git a/packages/astro/e2e/fixtures/lit-component/src/components/Counter.js b/packages/astro/e2e/fixtures/lit-component/src/components/Counter.js deleted file mode 100644 index 1ccd020ed..000000000 --- a/packages/astro/e2e/fixtures/lit-component/src/components/Counter.js +++ /dev/null @@ -1,38 +0,0 @@ -import { LitElement, html } from 'lit'; - -export default class Counter extends LitElement { - static get properties() { - return { - count: { - type: Number, - }, - }; - } - - constructor() { - super(); - this.count = 0; - } - - increment() { - this.count++; - } - - render() { - return html` - <div> - <p>Count: ${this.count}</p> - - <button type="button" @click=${this.increment}>Increment</button> - - <slot /> - </div> - `; - } -} - -// Since this fixture is ran in both dev and build, this could register twice. Wrap with a try..catch for now. -try { - customElements.define('my-counter', Counter); -} catch {} - diff --git a/packages/astro/e2e/fixtures/lit-component/src/components/NonDeferredCounter.js b/packages/astro/e2e/fixtures/lit-component/src/components/NonDeferredCounter.js deleted file mode 100644 index 409d3e9a5..000000000 --- a/packages/astro/e2e/fixtures/lit-component/src/components/NonDeferredCounter.js +++ /dev/null @@ -1,38 +0,0 @@ -import { LitElement, html } from 'lit'; - -export default class NonDeferredCounter extends LitElement { - static get properties() { - return { - count: { - type: Number, - // All set properties are reflected to attributes so its hydration is - // not deferred. - reflect: true, - }, - }; - } - - constructor() { - super(); - this.count = 0; - } - - increment() { - this.count++; - } - - render() { - return html` - <div> - <p>Count: ${this.count}</p> - - <button type="button" @click=${this.increment}>Increment</button> - </div> - `; - } -} - -// Since this fixture is ran in both dev and build, this could register twice. Wrap with a try..catch for now. -try { - customElements.define('non-deferred-counter', NonDeferredCounter); -} catch {} diff --git a/packages/astro/e2e/fixtures/lit-component/src/pages/index.astro b/packages/astro/e2e/fixtures/lit-component/src/pages/index.astro deleted file mode 100644 index 1d9511057..000000000 --- a/packages/astro/e2e/fixtures/lit-component/src/pages/index.astro +++ /dev/null @@ -1,38 +0,0 @@ ---- -import ClientOnlyComponent from '../components/ClientOnlyComponent.js'; -import MyCounter from '../components/Counter.js'; -import NonDeferredCounter from '../components/NonDeferredCounter.js'; - -const someProps = { - count: 10, -}; ---- - -<html> - <head> - <!-- Head Stuff --> - </head> - <body> - <MyCounter id="client-idle" {...someProps} client:idle> - <h1>Hello, client:idle!</h1> - </MyCounter> - - <NonDeferredCounter id="non-deferred" client:idle {...someProps}> - </NonDeferredCounter> - - <MyCounter id="client-load" {...someProps} client:load> - <h1>Hello, client:load!</h1> - </MyCounter> - - <MyCounter id="client-visible" {...someProps} client:visible> - <h1>Hello, client:visible!</h1> - </MyCounter> - - <ClientOnlyComponent id="client-only" client:only="lit"> - Frame<span class="default">work </span> - <span slot="foo" class="foo1">client:only</span> - <span slot="foo" class="foo2"> component</span> - <span slot="quux"> Should not be visible</span> - </ClientOnlyComponent> - </body> -</html> diff --git a/packages/astro/e2e/fixtures/lit-component/src/pages/media.astro b/packages/astro/e2e/fixtures/lit-component/src/pages/media.astro deleted file mode 100644 index 69e1d7005..000000000 --- a/packages/astro/e2e/fixtures/lit-component/src/pages/media.astro +++ /dev/null @@ -1,18 +0,0 @@ ---- -import MyCounter from '../components/Counter.js'; - -const someProps = { - count: 10, -}; ---- - -<html> - <head> - <!-- Head Stuff --> - </head> - <body> - <MyCounter id="client-media" {...someProps} client:media="(max-width: 50em)"> - <h1>Hello, client:media!</h1> - </MyCounter> - </body> -</html> diff --git a/packages/astro/e2e/fixtures/lit-component/src/pages/solo.astro b/packages/astro/e2e/fixtures/lit-component/src/pages/solo.astro deleted file mode 100644 index c9dfe0ba0..000000000 --- a/packages/astro/e2e/fixtures/lit-component/src/pages/solo.astro +++ /dev/null @@ -1,18 +0,0 @@ ---- -import MyCounter from '../components/Counter.js'; - -const someProps = { - count: 10, -}; ---- - -<html> - <head> - <!-- Head Stuff --> - </head> - <body> - <MyCounter {...someProps} client:idle> - <h1>Hello, client:idle!</h1> - </MyCounter> - </body> -</html> diff --git a/packages/astro/e2e/fixtures/multiple-frameworks/package.json b/packages/astro/e2e/fixtures/multiple-frameworks/package.json index c7438fd98..810e503f7 100644 --- a/packages/astro/e2e/fixtures/multiple-frameworks/package.json +++ b/packages/astro/e2e/fixtures/multiple-frameworks/package.json @@ -3,7 +3,6 @@ "version": "0.0.0", "private": true, "devDependencies": { - "@astrojs/lit": "workspace:*", "@astrojs/preact": "workspace:*", "@astrojs/react": "workspace:*", "@astrojs/solid-js": "workspace:*", diff --git a/packages/astro/e2e/fixtures/multiple-frameworks/src/components/LitCounter.js b/packages/astro/e2e/fixtures/multiple-frameworks/src/components/LitCounter.js deleted file mode 100644 index 883a7581d..000000000 --- a/packages/astro/e2e/fixtures/multiple-frameworks/src/components/LitCounter.js +++ /dev/null @@ -1,33 +0,0 @@ -import { LitElement, html } from 'lit'; - -export const tagName = 'my-counter'; - -class Counter extends LitElement { - static get properties() { - return { - count: { - type: Number, - }, - }; - } - - constructor() { - super(); - this.count = 0; - } - - increment() { - this.count++; - } - - render() { - return html` - <div> - <p>Count: ${this.count}</p> - <button type="button" @click=${this.increment}>Increment</button> - </div> - `; - } -} - -customElements.define(tagName, Counter); diff --git a/packages/astro/e2e/lit-component.test.js b/packages/astro/e2e/lit-component.test.js deleted file mode 100644 index d68f5f7b8..000000000 --- a/packages/astro/e2e/lit-component.test.js +++ /dev/null @@ -1,183 +0,0 @@ -import { expect } from '@playwright/test'; -import { testFactory, waitForHydrate } from './test-utils.js'; - -const test = testFactory({ - root: './fixtures/lit-component/', -}); - -// TODO: configure playwright to handle web component APIs -// https://github.com/microsoft/playwright/issues/14241 -test.describe('Lit components', () => { - test.describe('Development', () => { - let devServer; - - test.beforeAll(async ({ astro }) => { - devServer = await astro.startDevServer(); - }); - - test.afterAll(async () => { - await devServer.stop(); - }); - - test('client:idle', async ({ page, astro }) => { - await page.goto(astro.resolveUrl('/')); - - const counter = page.locator('#client-idle'); - await expect(counter, 'component is visible').toBeVisible(); - await expect(counter).toHaveCount(1); - - const count = counter.locator('p'); - await expect(count, 'initial count is 10').toHaveText('Count: 10'); - - await waitForHydrate(page, counter); - - const inc = counter.locator('button'); - await inc.click(); - - await expect(count, 'count incremented by 1').toHaveText('Count: 11'); - }); - - test('non-deferred attribute serialization', async ({ page, astro }) => { - await page.goto(astro.resolveUrl('/')); - - const counter = page.locator('#non-deferred'); - const count = counter.locator('p'); - await expect(count, 'initial count is 10').toHaveText('Count: 10'); - - await waitForHydrate(page, counter); - - const inc = counter.locator('button'); - await inc.click(); - - await expect(count, 'count incremented by 1').toHaveText('Count: 11'); - }); - - test('client:load', async ({ page, astro }) => { - await page.goto(astro.resolveUrl('/')); - - const counter = page.locator('#client-load'); - await expect(counter, 'component is visible').toBeVisible(); - - const count = counter.locator('p'); - await expect(count, 'initial count is 10').toHaveText('Count: 10'); - - await waitForHydrate(page, counter); - - const inc = counter.locator('button'); - await inc.click(); - - await expect(count, 'count incremented by 1').toHaveText('Count: 11'); - }); - - test('client:visible', async ({ page, astro }) => { - await page.goto(astro.resolveUrl('/')); - - // Make sure the component is on screen to trigger hydration - const counter = page.locator('#client-visible'); - await counter.scrollIntoViewIfNeeded(); - await expect(counter, 'component is visible').toBeVisible(); - - const count = counter.locator('p'); - await expect(count, 'initial count is 10').toHaveText('Count: 10'); - - await waitForHydrate(page, counter); - - const inc = counter.locator('button'); - await inc.click(); - - await expect(count, 'count incremented by 1').toHaveText('Count: 11'); - }); - - test('client:media', async ({ page, astro }) => { - await page.goto(astro.resolveUrl('/media')); - - const counter = page.locator('#client-media'); - await expect(counter, 'component is visible').toBeVisible(); - - const count = counter.locator('p'); - await expect(count, 'initial count is 10').toHaveText('Count: 10'); - - const inc = counter.locator('button'); - await inc.click(); - - await expect(count, 'component not hydrated yet').toHaveText('Count: 10'); - - // Reset the viewport to hydrate the component (max-width: 50rem) - await page.setViewportSize({ width: 414, height: 1124 }); - await waitForHydrate(page, counter); - - await inc.click(); - await expect(count, 'count incremented by 1').toHaveText('Count: 11'); - }); - - test('client:only', async ({ page, astro }) => { - await page.goto(astro.resolveUrl('/')); - - const label = page.locator('#client-only'); - await expect(label, 'component is visible').toBeVisible(); - - // Light DOM reconstructed correctly (slots are rendered alphabetically) and shadow dom content rendered - await expect(label, 'slotted text is in DOM').toHaveText( - 'Framework client:only component Should not be visible Shadow dom default content should not be visible', - ); - - // Projected content should be visible - await expect( - page.locator('#client-only .default'), - 'slotted element is visible', - ).toBeVisible(); - await expect(page.locator('#client-only .foo1'), 'slotted element is visible').toBeVisible(); - await expect(page.locator('#client-only .foo2'), 'slotted element is visible').toBeVisible(); - - // Non-projected content should not be visible - await expect( - page.locator('#client-only [slot="quux"]'), - 'element without slot is not visible', - ).toBeHidden(); - - // Default slot content should not be visible - await expect( - page.locator('#client-only .defaultContent'), - 'element without slot is not visible', - ).toBeHidden(); - }); - - test.skip('HMR', async ({ page, astro }) => { - await page.goto(astro.resolveUrl('/')); - - const counter = page.locator('#client-idle'); - const label = counter.locator('h1'); - - await astro.editFile('./src/pages/index.astro', (original) => - original.replace('Hello, client:idle!', 'Hello, updated client:idle!'), - ); - - await expect(label, 'slot text updated').toHaveText('Hello, updated client:idle!'); - await expect(counter, 'component styles persisted').toHaveCSS('display', 'grid'); - }); - }); - - test.describe('Production', () => { - let previewServer; - - test.beforeAll(async ({ astro }) => { - // Playwright's Node version doesn't have these functions, so stub them. - process.stdout.clearLine = () => {}; - process.stdout.cursorTo = () => {}; - await astro.build(); - previewServer = await astro.preview(); - }); - - test.afterAll(async () => { - await previewServer.stop(); - }); - - test('Only one component in prod', async ({ page, astro }) => { - await page.goto(astro.resolveUrl('/solo')); - - const counter = page.locator('my-counter'); - await expect(counter, 'component is visible').toBeVisible(); - await expect(counter, 'there is only one counter').toHaveCount(1); - }); - }); -}); diff --git a/packages/astro/env.d.ts b/packages/astro/env.d.ts index 876a29c60..d2a788db3 100644 --- a/packages/astro/env.d.ts +++ b/packages/astro/env.d.ts @@ -4,7 +4,7 @@ // As such, if the typings you're trying to add should be available inside ex: React components, they should instead // be inside `client.d.ts` -type Astro = import('./dist/@types/astro.js').AstroGlobal; +type Astro = import('./dist/types/public/context.js').AstroGlobal; // We have to duplicate the description here because editors won't show the JSDoc comment from the imported type // However, they will for its properties, ex: Astro.request will show the AstroGlobal.request description diff --git a/packages/astro/index.d.ts b/packages/astro/index.d.ts index a9e679be1..7b7a236e7 100644 --- a/packages/astro/index.d.ts +++ b/packages/astro/index.d.ts @@ -1,2 +1,2 @@ -export type * from './dist/@types/astro.js'; +export type * from './dist/types/public/index.js'; export * from './dist/core/index.js'; diff --git a/packages/astro/package.json b/packages/astro/package.json index 479024de2..9e4e48538 100644 --- a/packages/astro/package.json +++ b/packages/astro/package.json @@ -1,6 +1,6 @@ { "name": "astro", - "version": "4.14.2", + "version": "5.0.0-alpha.0", "description": "Astro is a modern site builder with web best practices, performance, and DX front-of-mind.", "type": "module", "author": "withastro", @@ -39,7 +39,7 @@ "./astro-jsx": "./astro-jsx.d.ts", "./tsconfigs/*.json": "./tsconfigs/*", "./tsconfigs/*": "./tsconfigs/*.json", - "./jsx/*": "./dist/jsx/*", + "./jsx/rehype.js": "./dist/jsx/rehype.js", "./jsx-runtime": { "types": "./jsx-runtime.d.ts", "default": "./dist/jsx-runtime/index.js" diff --git a/packages/astro/src/@types/README.md b/packages/astro/src/@types/README.md deleted file mode 100644 index 397329eaf..000000000 --- a/packages/astro/src/@types/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# `@types/` - -TypeScript definitions and types for untyped modules. - -[See CONTRIBUTING.md](../../../../CONTRIBUTING.md) for a code overview. diff --git a/packages/astro/src/@types/app.d.ts b/packages/astro/src/@types/app.d.ts deleted file mode 100644 index 1c0908bb8..000000000 --- a/packages/astro/src/@types/app.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * Shared interfaces throughout the application that can be overridden by the user. - */ -declare namespace App { - /** - * Used by middlewares to store information, that can be read by the user via the global `Astro.locals` - */ - interface Locals {} -} diff --git a/packages/astro/src/actions/index.ts b/packages/astro/src/actions/index.ts index 2423b7017..61f5a00cc 100644 --- a/packages/astro/src/actions/index.ts +++ b/packages/astro/src/actions/index.ts @@ -1,9 +1,10 @@ import fsMod from 'node:fs'; import type { Plugin as VitePlugin } from 'vite'; -import type { AstroIntegration, AstroSettings } from '../@types/astro.js'; import { ActionsWithoutServerOutputError } from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/errors.js'; import { isServerLikeOutput, viteID } from '../core/util.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroIntegration } from '../types/public/integrations.js'; import { ACTIONS_TYPES_FILE, NOOP_ACTIONS, diff --git a/packages/astro/src/actions/runtime/middleware.ts b/packages/astro/src/actions/runtime/middleware.ts index f3f01800a..b6f3221b5 100644 --- a/packages/astro/src/actions/runtime/middleware.ts +++ b/packages/astro/src/actions/runtime/middleware.ts @@ -1,8 +1,9 @@ import { yellow } from 'kleur/colors'; -import type { APIContext, MiddlewareNext } from '../../@types/astro.js'; import { ActionQueryStringInvalidError } from '../../core/errors/errors-data.js'; import { AstroError } from '../../core/errors/errors.js'; import { defineMiddleware } from '../../core/middleware/index.js'; +import type { MiddlewareNext } from '../../types/public/common.js'; +import type { APIContext } from '../../types/public/context.js'; import { ACTION_QUERY_PARAMS } from '../consts.js'; import { formContentTypes, hasContentType } from './utils.js'; import { getAction } from './virtual/get-action.js'; diff --git a/packages/astro/src/actions/runtime/route.ts b/packages/astro/src/actions/runtime/route.ts index e4e2ad1ce..7279a093d 100644 --- a/packages/astro/src/actions/runtime/route.ts +++ b/packages/astro/src/actions/runtime/route.ts @@ -1,4 +1,4 @@ -import type { APIRoute } from '../../@types/astro.js'; +import type { APIRoute } from '../../types/public/common.js'; import { formContentTypes, hasContentType } from './utils.js'; import { getAction } from './virtual/get-action.js'; import { serializeActionResult } from './virtual/shared.js'; diff --git a/packages/astro/src/actions/runtime/utils.ts b/packages/astro/src/actions/runtime/utils.ts index 776171aa2..199809d4e 100644 --- a/packages/astro/src/actions/runtime/utils.ts +++ b/packages/astro/src/actions/runtime/utils.ts @@ -1,4 +1,4 @@ -import type { APIContext } from '../../@types/astro.js'; +import type { APIContext } from '../../types/public/context.js'; export const formContentTypes = ['application/x-www-form-urlencoded', 'multipart/form-data']; diff --git a/packages/astro/src/actions/utils.ts b/packages/astro/src/actions/utils.ts index 5cf786266..f1cab8e43 100644 --- a/packages/astro/src/actions/utils.ts +++ b/packages/astro/src/actions/utils.ts @@ -1,6 +1,6 @@ -import type { APIContext } from '../@types/astro.js'; +import type { APIContext } from '../types/public/context.js'; import type { Locals } from './runtime/middleware.js'; -import { type ActionAPIContext } from './runtime/utils.js'; +import type { ActionAPIContext } from './runtime/utils.js'; import { deserializeActionResult, getActionQueryString } from './runtime/virtual/shared.js'; export function hasActionPayload(locals: APIContext['locals']): locals is Locals { diff --git a/packages/astro/src/assets/build/generate.ts b/packages/astro/src/assets/build/generate.ts index fcc19f4f5..1c4866592 100644 --- a/packages/astro/src/assets/build/generate.ts +++ b/packages/astro/src/assets/build/generate.ts @@ -2,7 +2,6 @@ import fs, { readFileSync } from 'node:fs'; import { basename } from 'node:path/posix'; import { dim, green } from 'kleur/colors'; import type PQueue from 'p-queue'; -import type { AstroConfig } from '../../@types/astro.js'; import { getOutDirWithinCwd } from '../../core/build/common.js'; import type { BuildPipeline } from '../../core/build/pipeline.js'; import { getTimeStat } from '../../core/build/util.js'; @@ -12,6 +11,7 @@ import type { Logger } from '../../core/logger/core.js'; import { isRemotePath, removeLeadingForwardSlash } from '../../core/path.js'; import { isServerLikeOutput } from '../../core/util.js'; import type { MapValue } from '../../type-utils.js'; +import type { AstroConfig } from '../../types/public/config.js'; import { getConfiguredImageService } from '../internal.js'; import type { LocalImageService } from '../services/service.js'; import type { AssetsGlobalStaticImagesList, ImageMetadata, ImageTransform } from '../types.js'; diff --git a/packages/astro/src/assets/endpoint/config.ts b/packages/astro/src/assets/endpoint/config.ts index 07cfe8fae..ff9dcc79a 100644 --- a/packages/astro/src/assets/endpoint/config.ts +++ b/packages/astro/src/assets/endpoint/config.ts @@ -1,4 +1,4 @@ -import type { AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; export function injectImageEndpoint(settings: AstroSettings, mode: 'dev' | 'build') { const endpointEntrypoint = diff --git a/packages/astro/src/assets/endpoint/generic.ts b/packages/astro/src/assets/endpoint/generic.ts index 5238f3721..d453787fd 100644 --- a/packages/astro/src/assets/endpoint/generic.ts +++ b/packages/astro/src/assets/endpoint/generic.ts @@ -2,7 +2,7 @@ import { imageConfig } from 'astro:assets'; import { isRemotePath } from '@astrojs/internal-helpers/path'; import * as mime from 'mrmime'; -import type { APIRoute } from '../../@types/astro.js'; +import type { APIRoute } from '../../types/public/common.js'; import { getConfiguredImageService } from '../internal.js'; import { etag } from '../utils/etag.js'; import { isRemoteAllowed } from '../utils/remotePattern.js'; diff --git a/packages/astro/src/assets/endpoint/node.ts b/packages/astro/src/assets/endpoint/node.ts index cb3ae7806..04275652c 100644 --- a/packages/astro/src/assets/endpoint/node.ts +++ b/packages/astro/src/assets/endpoint/node.ts @@ -7,7 +7,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; import { assetsDir, imageConfig, outDir } from 'astro:assets'; import { isRemotePath, removeQueryString } from '@astrojs/internal-helpers/path'; import * as mime from 'mrmime'; -import type { APIRoute } from '../../@types/astro.js'; +import type { APIRoute } from '../../types/public/common.js'; import { getConfiguredImageService } from '../internal.js'; import { etag } from '../utils/etag.js'; import { isRemoteAllowed } from '../utils/remotePattern.js'; diff --git a/packages/astro/src/assets/internal.ts b/packages/astro/src/assets/internal.ts index 38afbf19f..9a5926e8d 100644 --- a/packages/astro/src/assets/internal.ts +++ b/packages/astro/src/assets/internal.ts @@ -1,5 +1,5 @@ -import type { AstroConfig } from '../@types/astro.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; +import type { AstroConfig } from '../types/public/config.js'; import { DEFAULT_HASH_PROPS } from './consts.js'; import { type ImageService, isLocalService } from './services/service.js'; import { diff --git a/packages/astro/src/assets/services/service.ts b/packages/astro/src/assets/services/service.ts index 9cd6d0ecb..f798e1dfd 100644 --- a/packages/astro/src/assets/services/service.ts +++ b/packages/astro/src/assets/services/service.ts @@ -1,6 +1,6 @@ -import type { AstroConfig } from '../../@types/astro.js'; import { AstroError, AstroErrorData } from '../../core/errors/index.js'; import { isRemotePath, joinPaths } from '../../core/path.js'; +import type { AstroConfig } from '../../types/public/config.js'; import { DEFAULT_HASH_PROPS, DEFAULT_OUTPUT_FORMAT, VALID_SUPPORTED_FORMATS } from '../consts.js'; import type { ImageOutputFormat, ImageTransform, UnresolvedSrcSetValue } from '../types.js'; import { isESMImportedImage } from '../utils/imageKind.js'; diff --git a/packages/astro/src/assets/utils/remotePattern.ts b/packages/astro/src/assets/utils/remotePattern.ts index 5feefb89f..d3e832573 100644 --- a/packages/astro/src/assets/utils/remotePattern.ts +++ b/packages/astro/src/assets/utils/remotePattern.ts @@ -1,5 +1,5 @@ import { isRemotePath } from '@astrojs/internal-helpers/path'; -import type { AstroConfig } from '../../@types/astro.js'; +import type { AstroConfig } from '../../types/public/config.js'; export type RemotePattern = { hostname?: string; diff --git a/packages/astro/src/assets/vite-plugin-assets.ts b/packages/astro/src/assets/vite-plugin-assets.ts index 4c9314e85..57bbf847a 100644 --- a/packages/astro/src/assets/vite-plugin-assets.ts +++ b/packages/astro/src/assets/vite-plugin-assets.ts @@ -2,7 +2,6 @@ import { extname } from 'node:path'; import MagicString from 'magic-string'; import type * as vite from 'vite'; import { normalizePath } from 'vite'; -import type { AstroPluginOptions, AstroSettings, ImageTransform } from '../@types/astro.js'; import { extendManualChunks } from '../core/build/plugins/util.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import { @@ -13,7 +12,9 @@ import { removeQueryString, } from '../core/path.js'; import { isServerLikeOutput } from '../core/util.js'; +import type { AstroPluginOptions, AstroSettings } from '../types/astro.js'; import { VALID_INPUT_FORMATS, VIRTUAL_MODULE_ID, VIRTUAL_SERVICE_ID } from './consts.js'; +import type { ImageTransform } from './types.js'; import { getAssetsPrefix } from './utils/getAssetsPrefix.js'; import { isESMImportedImage } from './utils/imageKind.js'; import { emitESMImage } from './utils/node/emitAsset.js'; diff --git a/packages/astro/src/cli/db/index.ts b/packages/astro/src/cli/db/index.ts index ae97e498f..0dda4f30b 100644 --- a/packages/astro/src/cli/db/index.ts +++ b/packages/astro/src/cli/db/index.ts @@ -1,7 +1,7 @@ import type { Arguments } from 'yargs-parser'; -import type { AstroConfig } from '../../@types/astro.js'; import { resolveConfig } from '../../core/config/config.js'; import { apply as applyPolyfill } from '../../core/polyfill.js'; +import type { AstroConfig } from '../../types/public/config.js'; import { createLoggerFromFlags, flagsToAstroInlineConfig } from '../flags.js'; import { getPackage } from '../install-package.js'; diff --git a/packages/astro/src/cli/flags.ts b/packages/astro/src/cli/flags.ts index 9d57c0316..e890b242c 100644 --- a/packages/astro/src/cli/flags.ts +++ b/packages/astro/src/cli/flags.ts @@ -1,7 +1,7 @@ import type { Arguments } from 'yargs-parser'; -import type { AstroInlineConfig } from '../@types/astro.js'; import { type LogOptions, Logger } from '../core/logger/core.js'; import { nodeLogDestination } from '../core/logger/node.js'; +import type { AstroInlineConfig } from '../types/public/config.js'; // Alias for now, but allows easier migration to node's `parseArgs` in the future. export type Flags = Arguments; diff --git a/packages/astro/src/cli/info/index.ts b/packages/astro/src/cli/info/index.ts index 3fa91802f..9f25a2535 100644 --- a/packages/astro/src/cli/info/index.ts +++ b/packages/astro/src/cli/info/index.ts @@ -3,10 +3,10 @@ import { arch, platform } from 'node:os'; /* eslint-disable no-console */ import * as colors from 'kleur/colors'; import prompts from 'prompts'; -import type { AstroConfig, AstroUserConfig } from '../../@types/astro.js'; import { resolveConfig } from '../../core/config/index.js'; import { ASTRO_VERSION } from '../../core/constants.js'; import { apply as applyPolyfill } from '../../core/polyfill.js'; +import type { AstroConfig, AstroUserConfig } from '../../types/public/config.js'; import { type Flags, flagsToAstroInlineConfig } from '../flags.js'; interface InfoOptions { diff --git a/packages/astro/src/cli/preferences/index.ts b/packages/astro/src/cli/preferences/index.ts index 3811e7f48..bd60343c2 100644 --- a/packages/astro/src/cli/preferences/index.ts +++ b/packages/astro/src/cli/preferences/index.ts @@ -1,5 +1,5 @@ /* eslint-disable no-console */ -import type { AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; import { fileURLToPath } from 'node:url'; import { bgGreen, black, bold, dim, yellow } from 'kleur/colors'; diff --git a/packages/astro/src/config/index.ts b/packages/astro/src/config/index.ts index 3c5faf2fa..b31105ec7 100644 --- a/packages/astro/src/config/index.ts +++ b/packages/astro/src/config/index.ts @@ -1,6 +1,6 @@ import type { UserConfig as ViteUserConfig } from 'vite'; -import type { AstroInlineConfig, AstroUserConfig } from '../@types/astro.js'; import { Logger } from '../core/logger/core.js'; +import type { AstroInlineConfig, AstroUserConfig } from '../types/public/config.js'; export function defineConfig(config: AstroUserConfig) { return config; diff --git a/packages/astro/src/config/vite-plugin-content-listen.ts b/packages/astro/src/config/vite-plugin-content-listen.ts index 1b65c5bfb..6c0408001 100644 --- a/packages/astro/src/config/vite-plugin-content-listen.ts +++ b/packages/astro/src/config/vite-plugin-content-listen.ts @@ -1,8 +1,8 @@ import type fsMod from 'node:fs'; import type { Plugin, ViteDevServer } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; import { attachContentServerListeners } from '../content/server-listeners.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; /** * Listen for Astro content directory changes and generate types. diff --git a/packages/astro/src/container/index.ts b/packages/astro/src/container/index.ts index f0c600a40..8a8c83e07 100644 --- a/packages/astro/src/container/index.ts +++ b/packages/astro/src/container/index.ts @@ -1,19 +1,4 @@ import { posix } from 'node:path'; -import type { - AstroConfig, - AstroUserConfig, - ComponentInstance, - ContainerImportRendererFn, - MiddlewareHandler, - NamedSSRLoadedRendererValue, - Props, - RouteData, - RouteType, - SSRLoadedRenderer, - SSRLoadedRendererValue, - SSRManifest, - SSRResult, -} from '../@types/astro.js'; import { getDefaultClientDirectives } from '../core/client-directive/index.js'; import { ASTRO_CONFIG_DEFAULTS } from '../core/config/schema.js'; import { validateConfig } from '../core/config/validate.js'; @@ -25,8 +10,32 @@ import { RenderContext } from '../core/render-context.js'; import { getParts, validateSegment } from '../core/routing/manifest/create.js'; import { getPattern } from '../core/routing/manifest/pattern.js'; import type { AstroComponentFactory } from '../runtime/server/index.js'; +import type { ComponentInstance } from '../types/astro.js'; +import type { MiddlewareHandler, Props } from '../types/public/common.js'; +import type { AstroConfig, AstroUserConfig } from '../types/public/config.js'; +import type { + NamedSSRLoadedRendererValue, + RouteData, + RouteType, + SSRLoadedRenderer, + SSRLoadedRendererValue, + SSRManifest, + SSRResult, +} from '../types/public/internal.js'; import { ContainerPipeline } from './pipeline.js'; +/** Public type, used for integrations to define a renderer for the container API */ +export type ContainerRenderer = { + /** + * The name of the renderer. + */ + name: string; + /** + * The entrypoint that is used to render a component on the server + */ + serverEntrypoint: string; +}; + /** * Options to be passed when rendering a route */ @@ -103,6 +112,10 @@ export type AddClientRenderer = { entrypoint: string; }; +type ContainerImportRendererFn = ( + containerRenderer: ContainerRenderer, +) => Promise<SSRLoadedRenderer>; + function createManifest( manifest?: AstroContainerManifest, renderers?: SSRLoadedRenderer[], diff --git a/packages/astro/src/container/pipeline.ts b/packages/astro/src/container/pipeline.ts index ff2718b8f..73caa4ecd 100644 --- a/packages/astro/src/container/pipeline.ts +++ b/packages/astro/src/container/pipeline.ts @@ -1,10 +1,3 @@ -import type { - ComponentInstance, - RewritePayload, - RouteData, - SSRElement, - SSRResult, -} from '../@types/astro.js'; import { type HeadElements, Pipeline } from '../core/base-pipeline.js'; import type { SinglePageBuiltModule } from '../core/build/types.js'; import { @@ -12,6 +5,9 @@ import { createStylesheetElementSet, } from '../core/render/ssr-element.js'; import { findRouteToRewrite } from '../core/routing/rewrite.js'; +import type { ComponentInstance } from '../types/astro.js'; +import type { RewritePayload } from '../types/public/common.js'; +import type { RouteData, SSRElement, SSRResult } from '../types/public/internal.js'; export class ContainerPipeline extends Pipeline { /** diff --git a/packages/astro/src/content/content-layer.ts b/packages/astro/src/content/content-layer.ts index 4861f3f61..c0ccf27c6 100644 --- a/packages/astro/src/content/content-layer.ts +++ b/packages/astro/src/content/content-layer.ts @@ -3,9 +3,9 @@ import { isAbsolute } from 'node:path'; import { fileURLToPath } from 'node:url'; import type { FSWatcher } from 'vite'; import xxhash from 'xxhash-wasm'; -import type { AstroSettings } from '../@types/astro.js'; import { AstroUserError } from '../core/errors/errors.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; import { ASSET_IMPORTS_FILE, CONTENT_LAYER_TYPE, diff --git a/packages/astro/src/content/loaders/glob.ts b/packages/astro/src/content/loaders/glob.ts index 4a4ecbcac..27af34196 100644 --- a/packages/astro/src/content/loaders/glob.ts +++ b/packages/astro/src/content/loaders/glob.ts @@ -4,7 +4,7 @@ import fastGlob from 'fast-glob'; import { bold, green } from 'kleur/colors'; import micromatch from 'micromatch'; import pLimit from 'p-limit'; -import type { ContentEntryRenderFuction, ContentEntryType } from '../../@types/astro.js'; +import type { ContentEntryRenderFunction, ContentEntryType } from '../../types/public/content.js'; import type { RenderedContent } from '../data-store.js'; import { getContentEntryIdAndSlug, getEntryConfigByExtMap, posixRelative } from '../utils.js'; import type { Loader } from './types.js'; @@ -69,7 +69,7 @@ export function glob(globOptions: GlobOptions): Loader { load: async ({ settings, logger, watcher, parseData, store, generateDigest }) => { const renderFunctionByContentType = new WeakMap< ContentEntryType, - ContentEntryRenderFuction + ContentEntryRenderFunction >(); const untouchedEntries = new Set(store.keys()); @@ -131,7 +131,7 @@ export function glob(globOptions: GlobOptions): Loader { if (entryType.getRenderFunction) { let render = renderFunctionByContentType.get(entryType); if (!render) { - render = await entryType.getRenderFunction(settings); + render = await entryType.getRenderFunction(settings.config); // Cache the render function for this content type, so it can re-use parsers and other expensive setup renderFunctionByContentType.set(entryType, render); } diff --git a/packages/astro/src/content/loaders/types.ts b/packages/astro/src/content/loaders/types.ts index 26be0495a..5edfb5ef7 100644 --- a/packages/astro/src/content/loaders/types.ts +++ b/packages/astro/src/content/loaders/types.ts @@ -1,6 +1,7 @@ import type { FSWatcher } from 'vite'; import type { ZodSchema } from 'zod'; -import type { AstroIntegrationLogger, AstroSettings } from '../../@types/astro.js'; +import type { AstroIntegrationLogger } from '../../core/logger/core.js'; +import type { AstroSettings } from '../../types/astro.js'; import type { MetaStore, ScopedDataStore } from '../mutable-data-store.js'; export interface ParseDataOptions<TData extends Record<string, unknown>> { diff --git a/packages/astro/src/content/runtime.ts b/packages/astro/src/content/runtime.ts index b462e2e23..489625532 100644 --- a/packages/astro/src/content/runtime.ts +++ b/packages/astro/src/content/runtime.ts @@ -2,7 +2,7 @@ import type { MarkdownHeading } from '@astrojs/markdown-remark'; import { Traverse } from 'neotraverse/modern'; import pLimit from 'p-limit'; import { ZodIssueCode, z } from 'zod'; -import type { GetImageResult, ImageMetadata } from '../@types/astro.js'; +import type { GetImageResult, ImageMetadata } from '../assets/types.js'; import { imageSrcToImportId } from '../assets/utils/resolveImports.js'; import { AstroError, AstroErrorData, AstroUserError } from '../core/errors/index.js'; import { prependForwardSlash } from '../core/path.js'; diff --git a/packages/astro/src/content/server-listeners.ts b/packages/astro/src/content/server-listeners.ts index 5d7868d58..28f5b16a8 100644 --- a/packages/astro/src/content/server-listeners.ts +++ b/packages/astro/src/content/server-listeners.ts @@ -3,10 +3,10 @@ import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { bold, cyan, underline } from 'kleur/colors'; import type { ViteDevServer } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; import { loadTSConfig } from '../core/config/tsconfig.js'; import type { Logger } from '../core/logger/core.js'; import { appendForwardSlash } from '../core/path.js'; +import type { AstroSettings } from '../types/astro.js'; import { createContentTypesGenerator } from './types-generator.js'; import { type ContentPaths, getContentPaths, globalContentConfigObserver } from './utils.js'; diff --git a/packages/astro/src/content/types-generator.ts b/packages/astro/src/content/types-generator.ts index faf02d95d..9923a0c34 100644 --- a/packages/astro/src/content/types-generator.ts +++ b/packages/astro/src/content/types-generator.ts @@ -7,11 +7,12 @@ import { type ViteDevServer, normalizePath } from 'vite'; import { type ZodSchema, z } from 'zod'; import { zodToJsonSchema } from 'zod-to-json-schema'; import { printNode, zodToTs } from 'zod-to-ts'; -import type { AstroSettings, ContentEntryType } from '../@types/astro.js'; import { AstroError } from '../core/errors/errors.js'; import { AstroErrorData } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import { isRelativePath } from '../core/path.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { ContentEntryType } from '../types/public/content.js'; import { CONTENT_LAYER_TYPE, CONTENT_TYPES_FILE, VIRTUAL_MODULE_ID } from './consts.js'; import { type CollectionConfig, diff --git a/packages/astro/src/content/utils.ts b/packages/astro/src/content/utils.ts index 6d0627247..27b0e1915 100644 --- a/packages/astro/src/content/utils.ts +++ b/packages/astro/src/content/utils.ts @@ -7,15 +7,12 @@ import type { PluginContext } from 'rollup'; import { type ViteDevServer, normalizePath } from 'vite'; import xxhash from 'xxhash-wasm'; import { z } from 'zod'; -import type { - AstroConfig, - AstroSettings, - ContentEntryType, - DataEntryType, -} from '../@types/astro.js'; import { AstroError, AstroErrorData, MarkdownError, errorMap } from '../core/errors/index.js'; import { isYAMLException } from '../core/errors/utils.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroConfig } from '../types/public/config.js'; +import type { ContentEntryType, DataEntryType } from '../types/public/content.js'; import { CONTENT_FLAGS, CONTENT_LAYER_TYPE, diff --git a/packages/astro/src/content/vite-plugin-content-assets.ts b/packages/astro/src/content/vite-plugin-content-assets.ts index b810b8f71..059cd92fa 100644 --- a/packages/astro/src/content/vite-plugin-content-assets.ts +++ b/packages/astro/src/content/vite-plugin-content-assets.ts @@ -1,7 +1,6 @@ import { extname } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import type { Plugin } from 'vite'; -import type { AstroSettings, SSRElement } from '../@types/astro.js'; import { getAssetsPrefix } from '../assets/utils/getAssetsPrefix.js'; import type { BuildInternals } from '../core/build/internal.js'; import type { AstroBuildPlugin } from '../core/build/plugin.js'; @@ -9,6 +8,8 @@ import type { StaticBuildOptions } from '../core/build/types.js'; import type { ModuleLoader } from '../core/module-loader/loader.js'; import { createViteLoader } from '../core/module-loader/vite.js'; import { joinPaths, prependForwardSlash } from '../core/path.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { SSRElement } from '../types/public/internal.js'; import { getStylesForURL } from '../vite-plugin-astro-server/css.js'; import { getScriptsForURL } from '../vite-plugin-astro-server/scripts.js'; import { diff --git a/packages/astro/src/content/vite-plugin-content-imports.ts b/packages/astro/src/content/vite-plugin-content-imports.ts index 5a944716c..62f129052 100644 --- a/packages/astro/src/content/vite-plugin-content-imports.ts +++ b/packages/astro/src/content/vite-plugin-content-imports.ts @@ -4,19 +4,19 @@ import { pathToFileURL } from 'node:url'; import * as devalue from 'devalue'; import type { PluginContext } from 'rollup'; import type { Plugin } from 'vite'; -import type { - AstroConfig, - AstroSettings, - ContentEntryModule, - ContentEntryType, - DataEntryModule, - DataEntryType, -} from '../@types/astro.js'; import { getProxyCode } from '../assets/utils/proxy.js'; import { AstroError } from '../core/errors/errors.js'; import { AstroErrorData } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import { isServerLikeOutput } from '../core/util.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroConfig } from '../types/public/config.js'; +import type { + ContentEntryModule, + ContentEntryType, + DataEntryModule, + DataEntryType, +} from '../types/public/content.js'; import { CONTENT_FLAG, DATA_FLAG } from './consts.js'; import { type ContentConfig, diff --git a/packages/astro/src/content/vite-plugin-content-virtual-mod.ts b/packages/astro/src/content/vite-plugin-content-virtual-mod.ts index 64e5d98ee..832ca0b17 100644 --- a/packages/astro/src/content/vite-plugin-content-virtual-mod.ts +++ b/packages/astro/src/content/vite-plugin-content-virtual-mod.ts @@ -5,12 +5,12 @@ import { dataToEsm } from '@rollup/pluginutils'; import glob from 'fast-glob'; import pLimit from 'p-limit'; import type { Plugin } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; import { encodeName } from '../core/build/util.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import { appendForwardSlash, removeFileExtension } from '../core/path.js'; import { isServerLikeOutput } from '../core/util.js'; import { rootRelativePath } from '../core/viteUtils.js'; +import type { AstroSettings } from '../types/astro.js'; import type { AstroPluginMetadata } from '../vite-plugin-astro/index.js'; import { createDefaultAstroMetadata } from '../vite-plugin-astro/metadata.js'; import { diff --git a/packages/astro/src/core/app/index.ts b/packages/astro/src/core/app/index.ts index 8041dda3c..3ffa5f144 100644 --- a/packages/astro/src/core/app/index.ts +++ b/packages/astro/src/core/app/index.ts @@ -1,5 +1,6 @@ -import type { ManifestData, RouteData, SSRManifest } from '../../@types/astro.js'; import { normalizeTheLocale } from '../../i18n/index.js'; +import type { ManifestData } from '../../types/astro.js'; +import type { RouteData, SSRManifest } from '../../types/public/internal.js'; import { REROUTABLE_STATUS_CODES, REROUTE_DIRECTIVE_HEADER, diff --git a/packages/astro/src/core/app/middlewares.ts b/packages/astro/src/core/app/middlewares.ts index 095158b42..a60b6baf4 100644 --- a/packages/astro/src/core/app/middlewares.ts +++ b/packages/astro/src/core/app/middlewares.ts @@ -1,4 +1,4 @@ -import type { MiddlewareHandler } from '../../@types/astro.js'; +import type { MiddlewareHandler } from '../../types/public/common.js'; import { defineMiddleware } from '../middleware/index.js'; /** diff --git a/packages/astro/src/core/app/node.ts b/packages/astro/src/core/app/node.ts index f9afa6189..86f0f5f65 100644 --- a/packages/astro/src/core/app/node.ts +++ b/packages/astro/src/core/app/node.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import type { IncomingMessage, ServerResponse } from 'node:http'; -import type { RouteData } from '../../@types/astro.js'; +import type { RouteData } from '../../types/public/internal.js'; import { deserializeManifest } from './common.js'; import { createOutgoingHttpHeaders } from './createOutgoingHttpHeaders.js'; import { App } from './index.js'; diff --git a/packages/astro/src/core/app/pipeline.ts b/packages/astro/src/core/app/pipeline.ts index b784ba916..d42472f50 100644 --- a/packages/astro/src/core/app/pipeline.ts +++ b/packages/astro/src/core/app/pipeline.ts @@ -1,11 +1,6 @@ -import type { - ComponentInstance, - ManifestData, - RewritePayload, - RouteData, - SSRElement, - SSRResult, -} from '../../@types/astro.js'; +import type { ComponentInstance, ManifestData } from '../../types/astro.js'; +import type { RewritePayload } from '../../types/public/common.js'; +import type { RouteData, SSRElement, SSRResult } from '../../types/public/internal.js'; import { Pipeline } from '../base-pipeline.js'; import type { SinglePageBuiltModule } from '../build/types.js'; import { RedirectSinglePageBuiltModule } from '../redirects/component.js'; diff --git a/packages/astro/src/core/app/types.ts b/packages/astro/src/core/app/types.ts index 00e37dacd..29cb00ed4 100644 --- a/packages/astro/src/core/app/types.ts +++ b/packages/astro/src/core/app/types.ts @@ -1,14 +1,13 @@ +import type { RoutingStrategies } from '../../i18n/utils.js'; +import type { ComponentInstance, SerializedRouteData } from '../../types/astro.js'; +import type { MiddlewareHandler } from '../../types/public/common.js'; +import type { Locales } from '../../types/public/config.js'; import type { - ComponentInstance, - Locales, - MiddlewareHandler, RouteData, SSRComponentMetadata, SSRLoadedRenderer, SSRResult, - SerializedRouteData, -} from '../../@types/astro.js'; -import type { RoutingStrategies } from '../../i18n/utils.js'; +} from '../../types/public/internal.js'; import type { SinglePageBuiltModule } from '../build/types.js'; export type ComponentPath = string; @@ -82,6 +81,7 @@ export type SSRManifestI18n = { domainLookupTable: Record<string, string>; }; +/** Public type exposed through the `astro:build:ssr` integration hook */ export type SerializedSSRManifest = Omit< SSRManifest, | 'middleware' diff --git a/packages/astro/src/core/base-pipeline.ts b/packages/astro/src/core/base-pipeline.ts index 01e18bfa0..562b65174 100644 --- a/packages/astro/src/core/base-pipeline.ts +++ b/packages/astro/src/core/base-pipeline.ts @@ -1,15 +1,14 @@ +import { setGetEnv } from '../env/runtime.js'; +import { createI18nMiddleware } from '../i18n/middleware.js'; +import type { ComponentInstance } from '../types/astro.js'; +import type { MiddlewareHandler, RewritePayload } from '../types/public/common.js'; +import type { RuntimeMode } from '../types/public/config.js'; import type { - ComponentInstance, - MiddlewareHandler, - RewritePayload, RouteData, - RuntimeMode, SSRLoadedRenderer, SSRManifest, SSRResult, -} from '../@types/astro.js'; -import { setGetEnv } from '../env/runtime.js'; -import { createI18nMiddleware } from '../i18n/middleware.js'; +} from '../types/public/internal.js'; import { AstroError } from './errors/errors.js'; import { AstroErrorData } from './errors/index.js'; import type { Logger } from './logger/core.js'; diff --git a/packages/astro/src/core/build/common.ts b/packages/astro/src/core/build/common.ts index a479aed39..f9ed45836 100644 --- a/packages/astro/src/core/build/common.ts +++ b/packages/astro/src/core/build/common.ts @@ -1,7 +1,8 @@ import npath from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import type { AstroConfig, RouteData } from '../../@types/astro.js'; import { appendForwardSlash } from '../../core/path.js'; +import type { AstroConfig } from '../../types/public/config.js'; +import type { RouteData } from '../../types/public/internal.js'; const STATUS_CODE_PAGES = new Set(['/404', '/500']); const FALLBACK_OUT_DIR_NAME = './.astro/'; diff --git a/packages/astro/src/core/build/css-asset-name.ts b/packages/astro/src/core/build/css-asset-name.ts index fbee7f2e2..57277c989 100644 --- a/packages/astro/src/core/build/css-asset-name.ts +++ b/packages/astro/src/core/build/css-asset-name.ts @@ -4,7 +4,7 @@ import crypto from 'node:crypto'; import npath from 'node:path'; import { fileURLToPath } from 'node:url'; import { normalizePath } from 'vite'; -import type { AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; import { viteID } from '../util.js'; import { getTopLevelPageModuleInfos } from './graph.js'; diff --git a/packages/astro/src/core/build/generate.ts b/packages/astro/src/core/build/generate.ts index fae7896b9..e58f56100 100644 --- a/packages/astro/src/core/build/generate.ts +++ b/packages/astro/src/core/build/generate.ts @@ -2,18 +2,6 @@ import fs from 'node:fs'; import os from 'node:os'; import { bgGreen, black, blue, bold, dim, green, magenta, red } from 'kleur/colors'; import PQueue from 'p-queue'; -import type { - AstroConfig, - AstroSettings, - ComponentInstance, - GetStaticPathsItem, - MiddlewareHandler, - RouteData, - RouteType, - SSRError, - SSRLoadedRenderer, - SSRManifest, -} from '../../@types/astro.js'; import { generateImagesForPath, getStaticImageList, @@ -29,7 +17,16 @@ import { import { toRoutingStrategy } from '../../i18n/utils.js'; import { runHookBuildGenerated } from '../../integrations/hooks.js'; import { getOutputDirectory } from '../../prerender/utils.js'; -import type { SSRManifestI18n } from '../app/types.js'; +import type { AstroSettings, ComponentInstance } from '../../types/astro.js'; +import type { GetStaticPathsItem, MiddlewareHandler } from '../../types/public/common.js'; +import type { AstroConfig } from '../../types/public/config.js'; +import type { + RouteData, + RouteType, + SSRError, + SSRLoadedRenderer, +} from '../../types/public/internal.js'; +import type { SSRManifest, SSRManifestI18n } from '../app/types.js'; import { NoPrerenderedRoutesWithDomains } from '../errors/errors-data.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import { getRedirectLocationOrThrow, routeIsRedirect } from '../redirects/index.js'; @@ -39,7 +36,7 @@ import { createRequest } from '../request.js'; import { matchRoute } from '../routing/match.js'; import { stringifyParams } from '../routing/params.js'; import { getOutputFilename, isServerLikeOutput } from '../util.js'; -import { getOutDirWithinCwd, getOutFile, getOutFolder } from './common.js'; +import { getOutFile, getOutFolder } from './common.js'; import { cssOrder, mergeInlineCss } from './internal.js'; import { BuildPipeline } from './pipeline.js'; import type { @@ -50,10 +47,6 @@ import type { } from './types.js'; import { getTimeStat, shouldAppendForwardSlash } from './util.js'; -function createEntryURL(filePath: string, outFolder: URL) { - return new URL('./' + filePath + `?time=${Date.now()}`, outFolder); -} - export async function generatePages(options: StaticBuildOptions, internals: BuildInternals) { const generatePagesTimer = performance.now(); const ssr = isServerLikeOutput(options.settings.config); @@ -83,10 +76,6 @@ export async function generatePages(options: StaticBuildOptions, internals: Buil const pipeline = BuildPipeline.create({ internals, manifest, options }); const { config, logger } = pipeline; - const outFolder = ssr - ? options.settings.config.build.server - : getOutDirWithinCwd(options.settings.config.outDir); - // HACK! `astro:assets` relies on a global to know if its running in dev, prod, ssr, ssg, full moon // If we don't delete it here, it's technically not impossible (albeit improbable) for it to leak if (ssr && !hasPrerenderedPages(internals)) { @@ -110,22 +99,9 @@ export async function generatePages(options: StaticBuildOptions, internals: Buil } const ssrEntryPage = await pipeline.retrieveSsrEntry(pageData.route, filePath); - if (options.settings.adapter?.adapterFeatures?.functionPerRoute) { - // forcing to use undefined, so we fail in an expected way if the module is not even there. - // @ts-expect-error When building for `functionPerRoute`, the module exports a `pageModule` function instead - const ssrEntry = ssrEntryPage?.pageModule; - if (ssrEntry) { - await generatePage(pageData, ssrEntry, builtPaths, pipeline); - } else { - const ssrEntryURLPage = createEntryURL(filePath, outFolder); - throw new Error( - `Unable to find the manifest for the module ${ssrEntryURLPage.toString()}. This is unexpected and likely a bug in Astro, please report.`, - ); - } - } else { - const ssrEntry = ssrEntryPage as SinglePageBuiltModule; - await generatePage(pageData, ssrEntry, builtPaths, pipeline); - } + + const ssrEntry = ssrEntryPage as SinglePageBuiltModule; + await generatePage(pageData, ssrEntry, builtPaths, pipeline); } } } else { diff --git a/packages/astro/src/core/build/index.ts b/packages/astro/src/core/build/index.ts index 72df05b89..74a648304 100644 --- a/packages/astro/src/core/build/index.ts +++ b/packages/astro/src/core/build/index.ts @@ -3,13 +3,6 @@ import { performance } from 'node:perf_hooks'; import { fileURLToPath } from 'node:url'; import { blue, bold, green } from 'kleur/colors'; import type * as vite from 'vite'; -import type { - AstroConfig, - AstroInlineConfig, - AstroSettings, - ManifestData, - RuntimeMode, -} from '../../@types/astro.js'; import { injectImageEndpoint } from '../../assets/endpoint/config.js'; import { telemetry } from '../../events/index.js'; import { eventCliSession } from '../../events/session.js'; @@ -19,6 +12,8 @@ import { runHookConfigDone, runHookConfigSetup, } from '../../integrations/hooks.js'; +import type { AstroSettings, ManifestData } from '../../types/astro.js'; +import type { AstroConfig, AstroInlineConfig, RuntimeMode } from '../../types/public/config.js'; import { resolveConfig } from '../config/config.js'; import { createNodeLogger } from '../config/logging.js'; import { createSettings } from '../config/settings.js'; diff --git a/packages/astro/src/core/build/internal.ts b/packages/astro/src/core/build/internal.ts index 5c28a4d40..8c2d92824 100644 --- a/packages/astro/src/core/build/internal.ts +++ b/packages/astro/src/core/build/internal.ts @@ -1,5 +1,5 @@ import type { Rollup } from 'vite'; -import type { RouteData, SSRResult } from '../../@types/astro.js'; +import type { RouteData, SSRResult } from '../../types/public/internal.js'; import { prependForwardSlash, removeFileExtension } from '../path.js'; import { viteID } from '../util.js'; import { makePageDataKey } from './plugins/util.js'; diff --git a/packages/astro/src/core/build/page-data.ts b/packages/astro/src/core/build/page-data.ts index 210b31a0e..06ed629f2 100644 --- a/packages/astro/src/core/build/page-data.ts +++ b/packages/astro/src/core/build/page-data.ts @@ -1,4 +1,4 @@ -import type { AstroSettings, ManifestData } from '../../@types/astro.js'; +import type { AstroSettings, ManifestData } from '../../types/astro.js'; import type { Logger } from '../logger/core.js'; import type { AllPagesData } from './types.js'; diff --git a/packages/astro/src/core/build/pipeline.ts b/packages/astro/src/core/build/pipeline.ts index 4e0d94c57..ae00da5a0 100644 --- a/packages/astro/src/core/build/pipeline.ts +++ b/packages/astro/src/core/build/pipeline.ts @@ -1,11 +1,7 @@ -import type { - ComponentInstance, - RewritePayload, - RouteData, - SSRLoadedRenderer, - SSRResult, -} from '../../@types/astro.js'; import { getOutputDirectory } from '../../prerender/utils.js'; +import type { ComponentInstance } from '../../types/astro.js'; +import type { RewritePayload } from '../../types/public/common.js'; +import type { RouteData, SSRLoadedRenderer, SSRResult } from '../../types/public/internal.js'; import { BEFORE_HYDRATION_SCRIPT_ID, PAGE_SCRIPT_ID } from '../../vite-plugin-scripts/index.js'; import type { SSRManifest } from '../app/types.js'; import { routeIsFallback, routeIsRedirect } from '../redirects/helpers.js'; @@ -22,7 +18,6 @@ import { isServerLikeOutput } from '../util.js'; import { getOutDirWithinCwd } from './common.js'; import { type BuildInternals, cssOrder, getPageData, mergeInlineCss } from './internal.js'; import { ASTRO_PAGE_MODULE_ID, ASTRO_PAGE_RESOLVED_MODULE_ID } from './plugins/plugin-pages.js'; -import { RESOLVED_SPLIT_MODULE_ID } from './plugins/plugin-ssr.js'; import { getPagesFromVirtualModulePageName, getVirtualModulePageName } from './plugins/util.js'; import type { PageBuildData, SinglePageBuiltModule, StaticBuildOptions } from './types.js'; import { i18nHasFallback } from './util.js'; @@ -203,32 +198,16 @@ export class BuildPipeline extends Pipeline { const pages = new Map<PageBuildData, string>(); for (const [virtualModulePageName, filePath] of this.internals.entrySpecifierToBundleMap) { - // virtual pages can be emitted with different prefixes: - // - the classic way are pages emitted with prefix ASTRO_PAGE_RESOLVED_MODULE_ID -> plugin-pages - // - pages emitted using `functionPerRoute`, in this case pages are emitted with prefix RESOLVED_SPLIT_MODULE_ID - if ( - virtualModulePageName.includes(ASTRO_PAGE_RESOLVED_MODULE_ID) || - virtualModulePageName.includes(RESOLVED_SPLIT_MODULE_ID) - ) { + // virtual pages are emitted with the 'plugin-pages' prefix + if (virtualModulePageName.includes(ASTRO_PAGE_RESOLVED_MODULE_ID)) { let pageDatas: PageBuildData[] = []; - if (virtualModulePageName.includes(ASTRO_PAGE_RESOLVED_MODULE_ID)) { - pageDatas.push( - ...getPagesFromVirtualModulePageName( - this.internals, - ASTRO_PAGE_RESOLVED_MODULE_ID, - virtualModulePageName, - ), - ); - } - if (virtualModulePageName.includes(RESOLVED_SPLIT_MODULE_ID)) { - pageDatas.push( - ...getPagesFromVirtualModulePageName( - this.internals, - RESOLVED_SPLIT_MODULE_ID, - virtualModulePageName, - ), - ); - } + pageDatas.push( + ...getPagesFromVirtualModulePageName( + this.internals, + ASTRO_PAGE_RESOLVED_MODULE_ID, + virtualModulePageName, + ), + ); for (const pageData of pageDatas) { pages.set(pageData, filePath); } @@ -310,9 +289,9 @@ export class BuildPipeline extends Pipeline { } let entry; if (routeIsRedirect(route)) { - entry = await this.#getEntryForRedirectRoute(route, this.internals, this.outFolder); + entry = await this.#getEntryForRedirectRoute(route, this.outFolder); } else if (routeIsFallback(route)) { - entry = await this.#getEntryForFallbackRoute(route, this.internals, this.outFolder); + entry = await this.#getEntryForFallbackRoute(route, this.outFolder); } else { const ssrEntryURLPage = createEntryURL(filePath, this.outFolder); entry = await import(ssrEntryURLPage.toString()); @@ -323,7 +302,6 @@ export class BuildPipeline extends Pipeline { async #getEntryForFallbackRoute( route: RouteData, - internals: BuildInternals, outFolder: URL, ): Promise<SinglePageBuiltModule> { if (route.type !== 'fallback') { @@ -343,7 +321,6 @@ export class BuildPipeline extends Pipeline { async #getEntryForRedirectRoute( route: RouteData, - internals: BuildInternals, outFolder: URL, ): Promise<SinglePageBuiltModule> { if (route.type !== 'redirect') { diff --git a/packages/astro/src/core/build/plugins/README.md b/packages/astro/src/core/build/plugins/README.md index 2949233e6..667ec4a86 100644 --- a/packages/astro/src/core/build/plugins/README.md +++ b/packages/astro/src/core/build/plugins/README.md @@ -21,7 +21,7 @@ The emitted file has content similar to: ```js const renderers = [ Object.assign( - { name: 'astro:jsx', serverEntrypoint: 'astro/jsx/server.js', jsxImportSource: 'astro' }, + { name: 'astro:framework', serverEntrypoint: '@astrojs/framework/server.js' }, { ssr: server_default }, ), ]; diff --git a/packages/astro/src/core/build/plugins/index.ts b/packages/astro/src/core/build/plugins/index.ts index 1ccb7c6c3..809e5d42b 100644 --- a/packages/astro/src/core/build/plugins/index.ts +++ b/packages/astro/src/core/build/plugins/index.ts @@ -14,7 +14,7 @@ import { pluginPages } from './plugin-pages.js'; import { pluginPrerender } from './plugin-prerender.js'; import { pluginRenderers } from './plugin-renderers.js'; import { pluginScripts } from './plugin-scripts.js'; -import { pluginSSR, pluginSSRSplit } from './plugin-ssr.js'; +import { pluginSSR } from './plugin-ssr.js'; export function registerAllPlugins({ internals, options, register }: AstroBuildPluginContainer) { register(pluginComponentEntry(internals)); @@ -35,6 +35,5 @@ export function registerAllPlugins({ internals, options, register }: AstroBuildP register(pluginHoistedScripts(options, internals)); } register(pluginSSR(options, internals)); - register(pluginSSRSplit(options, internals)); register(pluginChunks()); } diff --git a/packages/astro/src/core/build/plugins/plugin-content.ts b/packages/astro/src/core/build/plugins/plugin-content.ts index 9c6d5add0..5fe0b6792 100644 --- a/packages/astro/src/core/build/plugins/plugin-content.ts +++ b/packages/astro/src/core/build/plugins/plugin-content.ts @@ -4,13 +4,13 @@ import { fileURLToPath } from 'node:url'; import glob from 'fast-glob'; import pLimit from 'p-limit'; import { type Plugin as VitePlugin, normalizePath } from 'vite'; -import type { AstroConfig } from '../../../@types/astro.js'; import { CONTENT_RENDER_FLAG, PROPAGATED_ASSET_FLAG } from '../../../content/consts.js'; import { type ContentLookupMap, hasContentFlag } from '../../../content/utils.js'; import { generateContentEntryFile, generateLookupMap, } from '../../../content/vite-plugin-content-virtual-mod.js'; +import type { AstroConfig } from '../../../types/public/config.js'; import { configPaths } from '../../config/index.js'; import { emptyDir } from '../../fs/index.js'; import { diff --git a/packages/astro/src/core/build/plugins/plugin-hoisted-scripts.ts b/packages/astro/src/core/build/plugins/plugin-hoisted-scripts.ts index 7c3784909..2992c0f2d 100644 --- a/packages/astro/src/core/build/plugins/plugin-hoisted-scripts.ts +++ b/packages/astro/src/core/build/plugins/plugin-hoisted-scripts.ts @@ -1,5 +1,5 @@ import type { BuildOptions, Rollup, Plugin as VitePlugin } from 'vite'; -import type { AstroSettings } from '../../../@types/astro.js'; +import type { AstroSettings } from '../../../types/astro.js'; import { viteID } from '../../util.js'; import type { BuildInternals } from '../internal.js'; import { getPageDataByViteID } from '../internal.js'; diff --git a/packages/astro/src/core/build/plugins/plugin-prerender.ts b/packages/astro/src/core/build/plugins/plugin-prerender.ts index 25b951794..c7552db9b 100644 --- a/packages/astro/src/core/build/plugins/plugin-prerender.ts +++ b/packages/astro/src/core/build/plugins/plugin-prerender.ts @@ -54,21 +54,6 @@ function getNonPrerenderOnlyChunks(bundle: Rollup.OutputBundle, internals: Build continue; } } - // Ideally we should record entries when `functionPerRoute` is enabled, but this breaks some tests - // that expect the entrypoint to still exist even if it should be unused. - // TODO: Revisit this so we can delete additional unused chunks - // else if (chunk.facadeModuleId?.startsWith(RESOLVED_SPLIT_MODULE_ID)) { - // const pageDatas = getPagesFromVirtualModulePageName( - // internals, - // RESOLVED_SPLIT_MODULE_ID, - // chunk.facadeModuleId - // ); - // const prerender = pageDatas.every((pageData) => pageData.route.prerender); - // if (prerender) { - // prerenderOnlyEntryChunks.add(chunk); - // continue; - // } - // } nonPrerenderOnlyEntryChunks.add(chunk); } diff --git a/packages/astro/src/core/build/plugins/plugin-ssr.ts b/packages/astro/src/core/build/plugins/plugin-ssr.ts index e9eda1dc9..992dc6561 100644 --- a/packages/astro/src/core/build/plugins/plugin-ssr.ts +++ b/packages/astro/src/core/build/plugins/plugin-ssr.ts @@ -1,8 +1,6 @@ -import { join } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; import type { Plugin as VitePlugin } from 'vite'; -import type { AstroAdapter, AstroSettings } from '../../../@types/astro.js'; -import { isFunctionPerRouteEnabled } from '../../../integrations/hooks.js'; +import type { AstroSettings } from '../../../types/astro.js'; +import type { AstroAdapter } from '../../../types/public/integrations.js'; import { routeIsRedirect } from '../../redirects/index.js'; import { VIRTUAL_ISLAND_MAP_ID } from '../../server-islands/vite-plugin-server-islands.js'; import { isServerLikeOutput } from '../../util.js'; @@ -14,7 +12,7 @@ import { SSR_MANIFEST_VIRTUAL_MODULE_ID } from './plugin-manifest.js'; import { MIDDLEWARE_MODULE_ID } from './plugin-middleware.js'; import { ASTRO_PAGE_MODULE_ID } from './plugin-pages.js'; import { RENDERERS_MODULE_ID } from './plugin-renderers.js'; -import { getComponentFromVirtualModulePageName, getVirtualModulePageName } from './util.js'; +import { getVirtualModulePageName } from './util.js'; export const SSR_VIRTUAL_MODULE_ID = '@astrojs-ssr-virtual-entry'; export const RESOLVED_SSR_VIRTUAL_MODULE_ID = '\0' + SSR_VIRTUAL_MODULE_ID; @@ -134,16 +132,12 @@ export function pluginSSR( internals: BuildInternals, ): AstroBuildPlugin { const ssr = isServerLikeOutput(options.settings.config); - const functionPerRouteEnabled = isFunctionPerRouteEnabled(options.settings.adapter); return { targets: ['server'], hooks: { 'build:before': () => { const adapter = options.settings.adapter!; - let ssrPlugin = - ssr && functionPerRouteEnabled === false - ? vitePluginSSR(internals, adapter, options) - : undefined; + const ssrPlugin = ssr && vitePluginSSR(internals, adapter, options); const vitePlugin = [vitePluginAdapter(adapter)]; if (ssrPlugin) { vitePlugin.unshift(ssrPlugin); @@ -159,10 +153,6 @@ export function pluginSSR( return; } - if (functionPerRouteEnabled) { - return; - } - if (!internals.ssrEntryChunk) { throw new Error(`Did not generate an entry chunk for SSR`); } @@ -173,111 +163,8 @@ export function pluginSSR( }; } -export const SPLIT_MODULE_ID = '@astro-page-split:'; -export const RESOLVED_SPLIT_MODULE_ID = '\0@astro-page-split:'; - -function vitePluginSSRSplit( - internals: BuildInternals, - adapter: AstroAdapter, - options: StaticBuildOptions, -): VitePlugin { - return { - name: '@astrojs/vite-plugin-astro-ssr-split', - enforce: 'post', - options(opts) { - const inputs = new Set<string>(); - - for (const pageData of Object.values(options.allPages)) { - if (routeIsRedirect(pageData.route)) { - continue; - } - inputs.add(getVirtualModulePageName(SPLIT_MODULE_ID, pageData.component)); - } - - return addRollupInput(opts, Array.from(inputs)); - }, - resolveId(id) { - if (id.startsWith(SPLIT_MODULE_ID)) { - return '\0' + id; - } - }, - async load(id) { - if (id.startsWith(RESOLVED_SPLIT_MODULE_ID)) { - const imports: string[] = []; - const contents: string[] = []; - const exports: string[] = []; - const componentPath = getComponentFromVirtualModulePageName(RESOLVED_SPLIT_MODULE_ID, id); - const virtualModuleName = getVirtualModulePageName(ASTRO_PAGE_MODULE_ID, componentPath); - let module = await this.resolve(virtualModuleName); - if (module) { - // we need to use the non-resolved ID in order to resolve correctly the virtual module - imports.push(`import * as pageModule from "${virtualModuleName}";`); - } - const middleware = await this.resolve(MIDDLEWARE_MODULE_ID); - const ssrCode = generateSSRCode(options.settings, adapter, middleware!.id); - imports.push(...ssrCode.imports); - contents.push(...ssrCode.contents); - - exports.push('export { pageModule }'); - - return [...imports, ...contents, ...exports].join('\n'); - } - }, - async generateBundle(_opts, bundle) { - // Add assets from this SSR chunk as well. - for (const [, chunk] of Object.entries(bundle)) { - if (chunk.type === 'asset') { - internals.staticFiles.add(chunk.fileName); - } - } - - for (const [, chunk] of Object.entries(bundle)) { - if (chunk.type === 'asset') { - continue; - } - for (const moduleKey of Object.keys(chunk.modules)) { - if (moduleKey.startsWith(RESOLVED_SPLIT_MODULE_ID)) { - storeEntryPoint(moduleKey, options, internals, chunk.fileName); - } - } - } - }, - }; -} - -export function pluginSSRSplit( - options: StaticBuildOptions, - internals: BuildInternals, -): AstroBuildPlugin { - const ssr = isServerLikeOutput(options.settings.config); - const functionPerRouteEnabled = isFunctionPerRouteEnabled(options.settings.adapter); - - return { - targets: ['server'], - hooks: { - 'build:before': () => { - const adapter = options.settings.adapter!; - let ssrPlugin = - ssr && functionPerRouteEnabled - ? vitePluginSSRSplit(internals, adapter, options) - : undefined; - const vitePlugin = [vitePluginAdapter(adapter)]; - if (ssrPlugin) { - vitePlugin.unshift(ssrPlugin); - } - - return { - enforce: 'after-user-plugins', - vitePlugin, - }; - }, - }, - }; -} - function generateSSRCode(settings: AstroSettings, adapter: AstroAdapter, middlewareId: string) { const edgeMiddleware = adapter?.adapterFeatures?.edgeMiddleware ?? false; - const pageMap = isFunctionPerRouteEnabled(adapter) ? 'pageModule' : 'pageMap'; const imports = [ `import { renderers } from '${RENDERERS_MODULE_ID}';`, @@ -293,7 +180,7 @@ function generateSSRCode(settings: AstroSettings, adapter: AstroAdapter, middlew settings.config.experimental.serverIslands ? '' : `const serverIslandMap = new Map()`, edgeMiddleware ? `const middleware = (_, next) => next()` : '', `const _manifest = Object.assign(defaultManifest, {`, - ` ${pageMap},`, + ` pageMap,`, ` serverIslandMap,`, ` renderers,`, ` middleware`, @@ -324,25 +211,3 @@ if (_start in serverEntrypointModule) { contents, }; } - -/** - * Because we delete the bundle from rollup at the end of this function, - * we can't use `writeBundle` hook to get the final file name of the entry point written on disk. - * We use this hook instead. - * - * We retrieve all the {@link RouteData} that have the same component as the one we are processing. - */ -function storeEntryPoint( - moduleKey: string, - options: StaticBuildOptions, - internals: BuildInternals, - fileName: string, -) { - const componentPath = getComponentFromVirtualModulePageName(RESOLVED_SPLIT_MODULE_ID, moduleKey); - for (const pageData of Object.values(options.allPages)) { - if (componentPath == pageData.component) { - const publicPath = fileURLToPath(options.settings.config.build.server); - internals.entryPoints.set(pageData.route, pathToFileURL(join(publicPath, fileName))); - } - } -} diff --git a/packages/astro/src/core/build/static-build.ts b/packages/astro/src/core/build/static-build.ts index 7e2272dde..725f919ba 100644 --- a/packages/astro/src/core/build/static-build.ts +++ b/packages/astro/src/core/build/static-build.ts @@ -1,11 +1,10 @@ import fs from 'node:fs'; -import path, { extname } from 'node:path'; +import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { teardown } from '@astrojs/compiler'; import glob from 'fast-glob'; import { bgGreen, bgMagenta, black, green } from 'kleur/colors'; import * as vite from 'vite'; -import type { RouteData } from '../../@types/astro.js'; import { PROPAGATED_ASSET_FLAG } from '../../content/consts.js'; import { getSymlinkedContentCollections, @@ -22,6 +21,7 @@ import { appendForwardSlash, prependForwardSlash, removeFileExtension } from '.. import { isModeServerWithNoAdapter, isServerLikeOutput } from '../../core/util.js'; import { runHookBuildSetup } from '../../integrations/hooks.js'; import { getOutputDirectory } from '../../prerender/utils.js'; +import type { RouteData } from '../../types/public/internal.js'; import { PAGE_SCRIPT_ID } from '../../vite-plugin-scripts/index.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; @@ -36,7 +36,7 @@ import { copyContentToCache } from './plugins/plugin-content.js'; import { RESOLVED_SSR_MANIFEST_VIRTUAL_MODULE_ID } from './plugins/plugin-manifest.js'; import { ASTRO_PAGE_RESOLVED_MODULE_ID } from './plugins/plugin-pages.js'; import { RESOLVED_RENDERERS_MODULE_ID } from './plugins/plugin-renderers.js'; -import { RESOLVED_SPLIT_MODULE_ID, RESOLVED_SSR_VIRTUAL_MODULE_ID } from './plugins/plugin-ssr.js'; +import { RESOLVED_SSR_VIRTUAL_MODULE_ID } from './plugins/plugin-ssr.js'; import { ASTRO_PAGE_EXTENSION_POST_PATTERN } from './plugins/util.js'; import type { StaticBuildOptions } from './types.js'; import { encodeName, getTimeStat, viteBuildReturnToRollupOutputs } from './util.js'; @@ -247,8 +247,6 @@ async function ssrBuild( chunkInfo.facadeModuleId, routes, ); - } else if (chunkInfo.facadeModuleId?.startsWith(RESOLVED_SPLIT_MODULE_ID)) { - return makeSplitEntryPointFileName(chunkInfo.facadeModuleId, routes); } else if (chunkInfo.facadeModuleId === RESOLVED_SSR_VIRTUAL_MODULE_ID) { return opts.settings.config.build.serverEntry; } else if (chunkInfo.facadeModuleId === RESOLVED_RENDERERS_MODULE_ID) { @@ -540,34 +538,3 @@ export function makeAstroPageEntryPointFileName( .replaceAll(/[[\]]/g, '_') .replaceAll('...', '---')}.astro.mjs`; } - -/** - * The `facadeModuleId` has a shape like: \0@astro-serverless-page:src/pages/index@_@astro. - * - * 1. We call `makeAstroPageEntryPointFileName` which normalise its name, making it like a file path - * 2. We split the file path using the file system separator and attempt to retrieve the last entry - * 3. The last entry should be the file - * 4. We prepend the file name with `entry.` - * 5. We built the file path again, using the new en3built in the previous step - * - * @param facadeModuleId - * @param opts - */ -export function makeSplitEntryPointFileName(facadeModuleId: string, routes: RouteData[]) { - const filePath = `${makeAstroPageEntryPointFileName( - RESOLVED_SPLIT_MODULE_ID, - facadeModuleId, - routes, - )}`; - - const pathComponents = filePath.split(path.sep); - const lastPathComponent = pathComponents.pop(); - if (lastPathComponent) { - const extension = extname(lastPathComponent); - if (extension.length > 0) { - const newFileName = `entry.${lastPathComponent}`; - return [...pathComponents, newFileName].join(path.sep); - } - } - return filePath; -} diff --git a/packages/astro/src/core/build/types.ts b/packages/astro/src/core/build/types.ts index 572140ef6..f06f42501 100644 --- a/packages/astro/src/core/build/types.ts +++ b/packages/astro/src/core/build/types.ts @@ -1,14 +1,9 @@ import type * as vite from 'vite'; import type { InlineConfig } from 'vite'; -import type { - AstroSettings, - ComponentInstance, - ManifestData, - MiddlewareHandler, - RouteData, - RuntimeMode, - SSRLoadedRenderer, -} from '../../@types/astro.js'; +import type { AstroSettings, ComponentInstance, ManifestData } from '../../types/astro.js'; +import type { MiddlewareHandler } from '../../types/public/common.js'; +import type { RuntimeMode } from '../../types/public/config.js'; +import type { RouteData, SSRLoadedRenderer } from '../../types/public/internal.js'; import type { Logger } from '../logger/core.js'; export type ComponentPath = string; @@ -20,6 +15,7 @@ export type StylesheetAsset = export type HoistedScriptAsset = { type: 'inline' | 'external'; value: string }; +/** Public type exposed through the `astro:build:setup` integration hook */ export interface PageBuildData { key: string; component: ComponentPath; diff --git a/packages/astro/src/core/build/util.ts b/packages/astro/src/core/build/util.ts index 9dc61f06f..b6b313254 100644 --- a/packages/astro/src/core/build/util.ts +++ b/packages/astro/src/core/build/util.ts @@ -1,5 +1,5 @@ import type { Rollup } from 'vite'; -import type { AstroConfig } from '../../@types/astro.js'; +import type { AstroConfig } from '../../types/public/config.js'; import type { ViteBuildReturn } from './types.js'; export function getTimeStat(timeStart: number, timeEnd: number) { diff --git a/packages/astro/src/core/compile/compile.ts b/packages/astro/src/core/compile/compile.ts index c3e6e4bb8..6e49f5850 100644 --- a/packages/astro/src/core/compile/compile.ts +++ b/packages/astro/src/core/compile/compile.ts @@ -1,11 +1,11 @@ import type { TransformResult } from '@astrojs/compiler'; import type { ResolvedConfig } from 'vite'; -import type { AstroConfig } from '../../@types/astro.js'; import { fileURLToPath } from 'node:url'; import { transform } from '@astrojs/compiler'; import { normalizePath } from 'vite'; import type { AstroPreferences } from '../../preferences/index.js'; +import type { AstroConfig } from '../../types/public/config.js'; import type { AstroError } from '../errors/errors.js'; import { AggregateError, CompilerError } from '../errors/errors.js'; import { AstroErrorData } from '../errors/index.js'; diff --git a/packages/astro/src/core/config/config.ts b/packages/astro/src/core/config/config.ts index c10066ce3..3e19db801 100644 --- a/packages/astro/src/core/config/config.ts +++ b/packages/astro/src/core/config/config.ts @@ -3,13 +3,13 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import * as colors from 'kleur/colors'; import { ZodError } from 'zod'; +import { eventConfigError, telemetry } from '../../events/index.js'; import type { AstroConfig, AstroInlineConfig, AstroInlineOnlyConfig, AstroUserConfig, -} from '../../@types/astro.js'; -import { eventConfigError, telemetry } from '../../events/index.js'; +} from '../../types/public/config.js'; import { trackAstroConfigZodError } from '../errors/errors.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import { formatConfigErrorMessage } from '../messages.js'; diff --git a/packages/astro/src/core/config/logging.ts b/packages/astro/src/core/config/logging.ts index 004283f85..bd72f8b5e 100644 --- a/packages/astro/src/core/config/logging.ts +++ b/packages/astro/src/core/config/logging.ts @@ -1,4 +1,4 @@ -import type { AstroInlineConfig } from '../../@types/astro.js'; +import type { AstroInlineConfig } from '../../types/public/config.js'; import { Logger } from '../logger/core.js'; import { nodeLogDestination } from '../logger/node.js'; diff --git a/packages/astro/src/core/config/schema.ts b/packages/astro/src/core/config/schema.ts index f49b4708e..9db111718 100644 --- a/packages/astro/src/core/config/schema.ts +++ b/packages/astro/src/core/config/schema.ts @@ -6,13 +6,13 @@ import type { } from '@astrojs/markdown-remark'; import { markdownConfigDefaults } from '@astrojs/markdown-remark'; import { type BuiltinTheme, bundledThemes } from 'shiki'; -import type { AstroUserConfig, ViteUserConfig } from '../../@types/astro.js'; import type { OutgoingHttpHeaders } from 'node:http'; import path from 'node:path'; import { pathToFileURL } from 'node:url'; import { z } from 'zod'; import { EnvSchema } from '../../env/schema.js'; +import type { AstroUserConfig, ViteUserConfig } from '../../types/public/config.js'; import { appendForwardSlash, prependForwardSlash, removeTrailingForwardSlash } from '../path.js'; // The below types are required boilerplate to workaround a Zod issue since v3.21.2. Since that version, diff --git a/packages/astro/src/core/config/settings.ts b/packages/astro/src/core/config/settings.ts index 6c878d7f3..902ff7d03 100644 --- a/packages/astro/src/core/config/settings.ts +++ b/packages/astro/src/core/config/settings.ts @@ -1,9 +1,10 @@ import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import yaml from 'js-yaml'; -import type { AstroConfig, AstroSettings } from '../../@types/astro.js'; import { getContentPaths } from '../../content/index.js'; import createPreferences from '../../preferences/index.js'; +import type { AstroSettings } from '../../types/astro.js'; +import type { AstroConfig } from '../../types/public/config.js'; import { markdownContentEntryType } from '../../vite-plugin-markdown/content-entry-type.js'; import { getDefaultClientDirectives } from '../client-directive/index.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; diff --git a/packages/astro/src/core/config/validate.ts b/packages/astro/src/core/config/validate.ts index 4f4497b78..75a64f1f7 100644 --- a/packages/astro/src/core/config/validate.ts +++ b/packages/astro/src/core/config/validate.ts @@ -1,4 +1,4 @@ -import type { AstroConfig } from '../../@types/astro.js'; +import type { AstroConfig } from '../../types/public/config.js'; import { createRelativeSchema } from './schema.js'; /** Turn raw config values into normalized values */ diff --git a/packages/astro/src/core/create-vite.ts b/packages/astro/src/core/create-vite.ts index 23a4068a8..d01eedb0d 100644 --- a/packages/astro/src/core/create-vite.ts +++ b/packages/astro/src/core/create-vite.ts @@ -3,7 +3,6 @@ import { fileURLToPath } from 'node:url'; import glob from 'fast-glob'; import * as vite from 'vite'; import { crawlFrameworkPkgs } from 'vitefu'; -import type { AstroSettings } from '../@types/astro.js'; import { getAssetsPrefix } from '../assets/utils/getAssetsPrefix.js'; import astroAssetsPlugin from '../assets/vite-plugin-assets.js'; import astroContainer from '../container/vite-plugin-container.js'; @@ -17,6 +16,7 @@ import astroInternationalization from '../i18n/vite-plugin-i18n.js'; import astroPrefetch from '../prefetch/vite-plugin-prefetch.js'; import astroDevToolbar from '../toolbar/vite-plugin-dev-toolbar.js'; import astroTransitions from '../transitions/vite-plugin-transitions.js'; +import type { AstroSettings } from '../types/astro.js'; import astroPostprocessVitePlugin from '../vite-plugin-astro-postprocess/index.js'; import { vitePluginAstroServer } from '../vite-plugin-astro-server/index.js'; import astroVitePlugin from '../vite-plugin-astro/index.js'; @@ -28,7 +28,6 @@ import htmlVitePlugin from '../vite-plugin-html/index.js'; import astroIntegrationsContainerPlugin from '../vite-plugin-integrations-container/index.js'; import astroLoadFallbackPlugin from '../vite-plugin-load-fallback/index.js'; import markdownVitePlugin from '../vite-plugin-markdown/index.js'; -import mdxVitePlugin from '../vite-plugin-mdx/index.js'; import astroScannerPlugin from '../vite-plugin-scanner/index.js'; import astroScriptsPlugin from '../vite-plugin-scripts/index.js'; import astroScriptsPageSSRPlugin from '../vite-plugin-scripts/page-ssr.js'; @@ -136,7 +135,6 @@ export async function createVite( astroEnv({ settings, mode, fs, sync }), markdownVitePlugin({ settings, logger }), htmlVitePlugin(), - mdxVitePlugin(), astroPostprocessVitePlugin(), astroIntegrationsContainerPlugin({ settings, logger }), astroScriptsPageSSRPlugin({ settings }), @@ -185,7 +183,7 @@ export async function createVite( { // Typings are imported from 'astro' (e.g. import { Type } from 'astro') find: /^astro$/, - replacement: fileURLToPath(new URL('../@types/astro.js', import.meta.url)), + replacement: fileURLToPath(new URL('../types/public/index.js', import.meta.url)), }, { find: 'astro:middleware', diff --git a/packages/astro/src/core/dev/container.ts b/packages/astro/src/core/dev/container.ts index 159d5e447..f89e33197 100644 --- a/packages/astro/src/core/dev/container.ts +++ b/packages/astro/src/core/dev/container.ts @@ -1,6 +1,6 @@ import type * as http from 'node:http'; import type { AddressInfo } from 'node:net'; -import type { AstroInlineConfig, AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; import nodeFs from 'node:fs'; import * as vite from 'vite'; @@ -11,6 +11,7 @@ import { runHookServerDone, runHookServerStart, } from '../../integrations/hooks.js'; +import type { AstroInlineConfig } from '../../types/public/config.js'; import { createVite } from '../create-vite.js'; import type { Logger } from '../logger/core.js'; import { apply as applyPolyfill } from '../polyfill.js'; diff --git a/packages/astro/src/core/dev/dev.ts b/packages/astro/src/core/dev/dev.ts index 12b6d3b55..73ec0fa71 100644 --- a/packages/astro/src/core/dev/dev.ts +++ b/packages/astro/src/core/dev/dev.ts @@ -5,13 +5,13 @@ import { performance } from 'node:perf_hooks'; import { green } from 'kleur/colors'; import { gt, major, minor, patch } from 'semver'; import type * as vite from 'vite'; -import type { AstroInlineConfig } from '../../@types/astro.js'; import { DATA_STORE_FILE } from '../../content/consts.js'; import { globalContentLayer } from '../../content/content-layer.js'; import { attachContentServerListeners } from '../../content/index.js'; import { MutableDataStore } from '../../content/mutable-data-store.js'; import { globalContentConfigObserver } from '../../content/utils.js'; import { telemetry } from '../../events/index.js'; +import type { AstroInlineConfig } from '../../types/public/config.js'; import * as msg from '../messages.js'; import { ensureProcessNodeEnv } from '../util.js'; import { startContainer } from './container.js'; diff --git a/packages/astro/src/core/dev/restart.ts b/packages/astro/src/core/dev/restart.ts index ee0ba995c..8fb6e46a3 100644 --- a/packages/astro/src/core/dev/restart.ts +++ b/packages/astro/src/core/dev/restart.ts @@ -1,9 +1,10 @@ import type nodeFs from 'node:fs'; import { fileURLToPath } from 'node:url'; import * as vite from 'vite'; -import type { AstroInlineConfig, AstroSettings } from '../../@types/astro.js'; import { globalContentLayer } from '../../content/content-layer.js'; import { eventCliSession, telemetry } from '../../events/index.js'; +import type { AstroSettings } from '../../types/astro.js'; +import type { AstroInlineConfig } from '../../types/public/config.js'; import { createNodeLogger, createSettings, resolveConfig } from '../config/index.js'; import { collectErrorMetadata } from '../errors/dev/utils.js'; import { isAstroConfigZodError } from '../errors/errors.js'; diff --git a/packages/astro/src/core/errors/dev/utils.ts b/packages/astro/src/core/errors/dev/utils.ts index 341c815a6..c082a8193 100644 --- a/packages/astro/src/core/errors/dev/utils.ts +++ b/packages/astro/src/core/errors/dev/utils.ts @@ -6,7 +6,7 @@ import { bold, underline } from 'kleur/colors'; import stripAnsi from 'strip-ansi'; import type { ESBuildTransformResult } from 'vite'; import { normalizePath } from 'vite'; -import type { SSRError } from '../../../@types/astro.js'; +import type { SSRError } from '../../../types/public/internal.js'; import { removeLeadingForwardSlashWindows } from '../../path.js'; import { AggregateError, type ErrorWithMetadata } from '../errors.js'; import { AstroErrorData } from '../index.js'; diff --git a/packages/astro/src/core/errors/dev/vite.ts b/packages/astro/src/core/errors/dev/vite.ts index 56688877a..c944ad78d 100644 --- a/packages/astro/src/core/errors/dev/vite.ts +++ b/packages/astro/src/core/errors/dev/vite.ts @@ -3,11 +3,11 @@ import { fileURLToPath } from 'node:url'; import { codeToHtml, createCssVariablesTheme } from 'shiki'; import type { ShikiTransformer } from 'shiki'; import type { ErrorPayload } from 'vite'; +import type { SSRLoadedRenderer } from '../../../types/public/internal.js'; import type { ModuleLoader } from '../../module-loader/index.js'; import { FailedToLoadModuleSSR, InvalidGlob, MdxIntegrationMissingError } from '../errors-data.js'; import { AstroError, type ErrorWithMetadata } from '../errors.js'; import { createSafeError } from '../utils.js'; -import type { SSRLoadedRenderer } from './../../../@types/astro.js'; import { getDocsForError, renderErrorMarkdown } from './utils.js'; export function enhanceViteSSRError({ diff --git a/packages/astro/src/core/errors/errors-data.ts b/packages/astro/src/core/errors/errors-data.ts index 24b9ad687..e083ba2f5 100644 --- a/packages/astro/src/core/errors/errors-data.ts +++ b/packages/astro/src/core/errors/errors-data.ts @@ -1,5 +1,5 @@ // BEFORE ADDING AN ERROR: Please look at the README.md in this folder for general guidelines on writing error messages -// Additionally, this code, much like `@types/astro.ts`, is used to generate documentation, so make sure to pass +// Additionally, this code, much like `types/public/config.ts`, is used to generate documentation, so make sure to pass // your changes by our wonderful docs team before merging! import type { ZodError } from 'zod'; diff --git a/packages/astro/src/core/errors/utils.ts b/packages/astro/src/core/errors/utils.ts index 05dd49071..6754656b9 100644 --- a/packages/astro/src/core/errors/utils.ts +++ b/packages/astro/src/core/errors/utils.ts @@ -1,6 +1,6 @@ import type { YAMLException } from 'js-yaml'; import type { ErrorPayload as ViteErrorPayload } from 'vite'; -import type { SSRError } from '../../@types/astro.js'; +import type { SSRError } from '../../types/public/internal.js'; /** * Get the line and character based on the offset diff --git a/packages/astro/src/core/index.ts b/packages/astro/src/core/index.ts index bdd7c7f05..14a8c2f99 100644 --- a/packages/astro/src/core/index.ts +++ b/packages/astro/src/core/index.ts @@ -1,6 +1,6 @@ // This is the main entrypoint when importing the `astro` package. -import type { AstroInlineConfig } from '../@types/astro.js'; +import type { AstroInlineConfig } from '../types/public/config.js'; import { default as _build } from './build/index.js'; import { default as _sync } from './sync/index.js'; diff --git a/packages/astro/src/core/middleware/callMiddleware.ts b/packages/astro/src/core/middleware/callMiddleware.ts index 3bdc6052d..4cc7b6586 100644 --- a/packages/astro/src/core/middleware/callMiddleware.ts +++ b/packages/astro/src/core/middleware/callMiddleware.ts @@ -1,9 +1,9 @@ import type { - APIContext, MiddlewareHandler, MiddlewareNext, RewritePayload, -} from '../../@types/astro.js'; +} from '../../types/public/common.js'; +import type { APIContext } from '../../types/public/context.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; /** diff --git a/packages/astro/src/core/middleware/index.ts b/packages/astro/src/core/middleware/index.ts index 56ce0b76c..31988ae02 100644 --- a/packages/astro/src/core/middleware/index.ts +++ b/packages/astro/src/core/middleware/index.ts @@ -1,10 +1,11 @@ -import type { APIContext, MiddlewareHandler, Params, RewritePayload } from '../../@types/astro.js'; import { createCallAction, createGetActionResult } from '../../actions/utils.js'; import { computeCurrentLocale, computePreferredLocale, computePreferredLocaleList, } from '../../i18n/utils.js'; +import type { MiddlewareHandler, Params, RewritePayload } from '../../types/public/common.js'; +import type { APIContext } from '../../types/public/context.js'; import { ASTRO_VERSION, clientAddressSymbol, clientLocalsSymbol } from '../constants.js'; import { AstroCookies } from '../cookies/index.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; diff --git a/packages/astro/src/core/middleware/sequence.ts b/packages/astro/src/core/middleware/sequence.ts index ee08381e6..aefa66a92 100644 --- a/packages/astro/src/core/middleware/sequence.ts +++ b/packages/astro/src/core/middleware/sequence.ts @@ -1,4 +1,5 @@ -import type { APIContext, MiddlewareHandler, RewritePayload } from '../../@types/astro.js'; +import type { MiddlewareHandler, RewritePayload } from '../../types/public/common.js'; +import type { APIContext } from '../../types/public/context.js'; import { AstroCookies } from '../cookies/cookies.js'; import { defineMiddleware } from './index.js'; diff --git a/packages/astro/src/core/middleware/vite-plugin.ts b/packages/astro/src/core/middleware/vite-plugin.ts index bb7b54e72..8a76bed92 100644 --- a/packages/astro/src/core/middleware/vite-plugin.ts +++ b/packages/astro/src/core/middleware/vite-plugin.ts @@ -1,7 +1,7 @@ import type { Plugin as VitePlugin } from 'vite'; import { normalizePath } from 'vite'; -import type { AstroSettings } from '../../@types/astro.js'; import { getOutputDirectory } from '../../prerender/utils.js'; +import type { AstroSettings } from '../../types/astro.js'; import { addRollupInput } from '../build/add-rollup-input.js'; import type { BuildInternals } from '../build/internal.js'; import type { StaticBuildOptions } from '../build/types.js'; diff --git a/packages/astro/src/core/module-loader/loader.ts b/packages/astro/src/core/module-loader/loader.ts index 976354448..9973ae657 100644 --- a/packages/astro/src/core/module-loader/loader.ts +++ b/packages/astro/src/core/module-loader/loader.ts @@ -1,6 +1,6 @@ import { EventEmitter } from 'node:events'; import type * as fs from 'node:fs'; -import type { TypedEventEmitter } from '../../@types/typed-emitter.js'; +import type { TypedEventEmitter } from '../../types/typed-emitter.js'; // This is a generic interface for a module loader. In the astro cli this is // fulfilled by Vite, see vite.ts diff --git a/packages/astro/src/core/preview/index.ts b/packages/astro/src/core/preview/index.ts index b46cf1bec..a8a533fe8 100644 --- a/packages/astro/src/core/preview/index.ts +++ b/packages/astro/src/core/preview/index.ts @@ -1,11 +1,12 @@ import fs from 'node:fs'; import { createRequire } from 'node:module'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import type { AstroInlineConfig, PreviewModule, PreviewServer } from '../../@types/astro.js'; import { AstroIntegrationLogger } from '../../core/logger/core.js'; import { telemetry } from '../../events/index.js'; import { eventCliSession } from '../../events/session.js'; import { runHookConfigDone, runHookConfigSetup } from '../../integrations/hooks.js'; +import type { AstroInlineConfig } from '../../types/public/config.js'; +import type { PreviewModule, PreviewServer } from '../../types/public/preview.js'; import { resolveConfig } from '../config/config.js'; import { createNodeLogger } from '../config/logging.js'; import { createSettings } from '../config/settings.js'; diff --git a/packages/astro/src/core/preview/static-preview-server.ts b/packages/astro/src/core/preview/static-preview-server.ts index 0afa34b60..855506ef9 100644 --- a/packages/astro/src/core/preview/static-preview-server.ts +++ b/packages/astro/src/core/preview/static-preview-server.ts @@ -2,7 +2,7 @@ import type http from 'node:http'; import { performance } from 'node:perf_hooks'; import { fileURLToPath } from 'node:url'; import { type PreviewServer as VitePreviewServer, preview } from 'vite'; -import type { AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; import type { Logger } from '../logger/core.js'; import * as msg from '../messages.js'; import { getResolvedHostForHttpServer } from './util.js'; diff --git a/packages/astro/src/core/preview/vite-plugin-astro-preview.ts b/packages/astro/src/core/preview/vite-plugin-astro-preview.ts index a425807dc..fd9bbae66 100644 --- a/packages/astro/src/core/preview/vite-plugin-astro-preview.ts +++ b/packages/astro/src/core/preview/vite-plugin-astro-preview.ts @@ -2,8 +2,8 @@ import fs from 'node:fs'; import type { IncomingMessage, ServerResponse } from 'node:http'; import { fileURLToPath } from 'node:url'; import type { Connect, Plugin } from 'vite'; -import type { AstroSettings } from '../../@types/astro.js'; import { notFoundTemplate, subpathNotUsedTemplate } from '../../template/4xx.js'; +import type { AstroSettings } from '../../types/astro.js'; import { cleanUrl } from '../../vite-plugin-utils/index.js'; import { stripBase } from './util.js'; diff --git a/packages/astro/src/core/redirects/component.ts b/packages/astro/src/core/redirects/component.ts index 00b8d176c..12b37ae00 100644 --- a/packages/astro/src/core/redirects/component.ts +++ b/packages/astro/src/core/redirects/component.ts @@ -1,4 +1,4 @@ -import type { ComponentInstance } from '../../@types/astro.js'; +import type { ComponentInstance } from '../../types/astro.js'; import type { SinglePageBuiltModule } from '../build/types.js'; // A stub of a component instance for a given route diff --git a/packages/astro/src/core/redirects/helpers.ts b/packages/astro/src/core/redirects/helpers.ts index 80f18ae0f..a2dc42df9 100644 --- a/packages/astro/src/core/redirects/helpers.ts +++ b/packages/astro/src/core/redirects/helpers.ts @@ -1,4 +1,8 @@ -import type { RedirectRouteData, RouteData } from '../../@types/astro.js'; +import type { RouteData } from '../../types/public/internal.js'; + +type RedirectRouteData = RouteData & { + redirect: string; +}; export function routeIsRedirect(route: RouteData | undefined): route is RedirectRouteData { return route?.type === 'redirect'; diff --git a/packages/astro/src/core/render-context.ts b/packages/astro/src/core/render-context.ts index a19d11080..ab0554d0c 100644 --- a/packages/astro/src/core/render-context.ts +++ b/packages/astro/src/core/render-context.ts @@ -1,14 +1,3 @@ -import type { - APIContext, - AstroGlobal, - AstroGlobalPartial, - ComponentInstance, - MiddlewareHandler, - Props, - RewritePayload, - RouteData, - SSRResult, -} from '../@types/astro.js'; import type { ActionAPIContext } from '../actions/runtime/utils.js'; import { deserializeActionResult } from '../actions/runtime/virtual/shared.js'; import { createCallAction, createGetActionResult, hasActionPayload } from '../actions/utils.js'; @@ -19,6 +8,10 @@ import { } from '../i18n/utils.js'; import { renderEndpoint } from '../runtime/server/endpoint.js'; import { renderPage } from '../runtime/server/index.js'; +import type { ComponentInstance } from '../types/astro.js'; +import type { MiddlewareHandler, Props, RewritePayload } from '../types/public/common.js'; +import type { APIContext, AstroGlobal, AstroGlobalPartial } from '../types/public/context.js'; +import type { RouteData, SSRResult } from '../types/public/internal.js'; import { ASTRO_VERSION, REROUTE_DIRECTIVE_HEADER, diff --git a/packages/astro/src/core/render/index.ts b/packages/astro/src/core/render/index.ts index db14701b0..b56a2eaf2 100644 --- a/packages/astro/src/core/render/index.ts +++ b/packages/astro/src/core/render/index.ts @@ -1,4 +1,5 @@ -import type { ComponentInstance, RouteData } from '../../@types/astro.js'; +import type { ComponentInstance } from '../../types/astro.js'; +import type { RouteData } from '../../types/public/internal.js'; import type { Pipeline } from '../base-pipeline.js'; export { Pipeline } from '../base-pipeline.js'; export { getParams, getProps } from './params-and-props.js'; diff --git a/packages/astro/src/core/render/paginate.ts b/packages/astro/src/core/render/paginate.ts index e962d98d3..c462cd4b8 100644 --- a/packages/astro/src/core/render/paginate.ts +++ b/packages/astro/src/core/render/paginate.ts @@ -4,8 +4,8 @@ import type { PaginateOptions, Params, Props, - RouteData, -} from '../../@types/astro.js'; +} from '../../types/public/common.js'; +import type { RouteData } from '../../types/public/internal.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; export function generatePaginateFunction( diff --git a/packages/astro/src/core/render/params-and-props.ts b/packages/astro/src/core/render/params-and-props.ts index cf7d02d48..a45fb16a8 100644 --- a/packages/astro/src/core/render/params-and-props.ts +++ b/packages/astro/src/core/render/params-and-props.ts @@ -1,4 +1,6 @@ -import type { ComponentInstance, Params, Props, RouteData } from '../../@types/astro.js'; +import type { ComponentInstance } from '../../types/astro.js'; +import type { Params, Props } from '../../types/public/common.js'; +import type { RouteData } from '../../types/public/internal.js'; import { DEFAULT_404_COMPONENT } from '../constants.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; diff --git a/packages/astro/src/core/render/renderer.ts b/packages/astro/src/core/render/renderer.ts index 42cc8fd05..8daec8d53 100644 --- a/packages/astro/src/core/render/renderer.ts +++ b/packages/astro/src/core/render/renderer.ts @@ -1,4 +1,5 @@ -import type { AstroRenderer, SSRLoadedRenderer } from '../../@types/astro.js'; +import type { AstroRenderer } from '../../types/public/integrations.js'; +import type { SSRLoadedRenderer } from '../../types/public/internal.js'; import type { ModuleLoader } from '../module-loader/index.js'; export async function loadRenderer( diff --git a/packages/astro/src/core/render/route-cache.ts b/packages/astro/src/core/render/route-cache.ts index 399795675..3329c42cd 100644 --- a/packages/astro/src/core/render/route-cache.ts +++ b/packages/astro/src/core/render/route-cache.ts @@ -1,13 +1,13 @@ +import type { ComponentInstance } from '../../types/astro.js'; import type { - ComponentInstance, GetStaticPathsItem, GetStaticPathsResult, GetStaticPathsResultKeyed, PaginateFunction, Params, - RouteData, - RuntimeMode, -} from '../../@types/astro.js'; +} from '../../types/public/common.js'; +import type { RuntimeMode } from '../../types/public/config.js'; +import type { RouteData } from '../../types/public/internal.js'; import type { Logger } from '../logger/core.js'; import { stringifyParams } from '../routing/params.js'; diff --git a/packages/astro/src/core/render/slots.ts b/packages/astro/src/core/render/slots.ts index ab87204e4..1c767083d 100644 --- a/packages/astro/src/core/render/slots.ts +++ b/packages/astro/src/core/render/slots.ts @@ -1,8 +1,8 @@ -import type { SSRResult } from '../../@types/astro.js'; import { type ComponentSlots, renderSlotToString } from '../../runtime/server/index.js'; import { renderJSX } from '../../runtime/server/jsx.js'; import { chunkToString } from '../../runtime/server/render/index.js'; import { isRenderInstruction } from '../../runtime/server/render/instruction.js'; +import type { SSRResult } from '../../types/public/internal.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; diff --git a/packages/astro/src/core/render/ssr-element.ts b/packages/astro/src/core/render/ssr-element.ts index 7c766ee20..827c8fddf 100644 --- a/packages/astro/src/core/render/ssr-element.ts +++ b/packages/astro/src/core/render/ssr-element.ts @@ -1,7 +1,7 @@ -import type { AssetsPrefix, SSRElement } from '../../@types/astro.js'; import { getAssetsPrefix } from '../../assets/utils/getAssetsPrefix.js'; import { fileExtension, joinPaths, prependForwardSlash, slash } from '../../core/path.js'; -import type { StylesheetAsset } from '../app/types.js'; +import type { SSRElement } from '../../types/public/internal.js'; +import type { AssetsPrefix, StylesheetAsset } from '../app/types.js'; export function createAssetLink(href: string, base?: string, assetsPrefix?: AssetsPrefix): string { if (assetsPrefix) { diff --git a/packages/astro/src/core/routing/astro-designed-error-pages.ts b/packages/astro/src/core/routing/astro-designed-error-pages.ts index 4e4b41b70..2c1c1f77c 100644 --- a/packages/astro/src/core/routing/astro-designed-error-pages.ts +++ b/packages/astro/src/core/routing/astro-designed-error-pages.ts @@ -1,5 +1,6 @@ -import type { ComponentInstance, ManifestData, RouteData } from '../../@types/astro.js'; import notFoundTemplate from '../../template/4xx.js'; +import type { ComponentInstance, ManifestData } from '../../types/astro.js'; +import type { RouteData } from '../../types/public/internal.js'; import { DEFAULT_404_COMPONENT, DEFAULT_500_COMPONENT } from '../constants.js'; export const DEFAULT_404_ROUTE: RouteData = { diff --git a/packages/astro/src/core/routing/default.ts b/packages/astro/src/core/routing/default.ts index dd3c8cc53..8bcd473d0 100644 --- a/packages/astro/src/core/routing/default.ts +++ b/packages/astro/src/core/routing/default.ts @@ -1,4 +1,5 @@ -import type { ComponentInstance, ManifestData, SSRManifest } from '../../@types/astro.js'; +import type { ComponentInstance, ManifestData } from '../../types/astro.js'; +import type { SSRManifest } from '../app/types.js'; import { DEFAULT_404_COMPONENT } from '../constants.js'; import { SERVER_ISLAND_COMPONENT, diff --git a/packages/astro/src/core/routing/manifest/create.ts b/packages/astro/src/core/routing/manifest/create.ts index df548ec82..14980f63e 100644 --- a/packages/astro/src/core/routing/manifest/create.ts +++ b/packages/astro/src/core/routing/manifest/create.ts @@ -1,11 +1,4 @@ -import type { - AstroConfig, - AstroSettings, - ManifestData, - RouteData, - RoutePart, - RoutePriorityOverride, -} from '../../../@types/astro.js'; +import type { AstroSettings, ManifestData } from '../../../types/astro.js'; import type { Logger } from '../../logger/core.js'; import nodeFs from 'node:fs'; @@ -15,6 +8,9 @@ import { fileURLToPath } from 'node:url'; import { bold } from 'kleur/colors'; import { toRoutingStrategy } from '../../../i18n/utils.js'; import { getPrerenderDefault } from '../../../prerender/utils.js'; +import type { AstroConfig } from '../../../types/public/config.js'; +import type { RoutePriorityOverride } from '../../../types/public/integrations.js'; +import type { RouteData, RoutePart } from '../../../types/public/internal.js'; import { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from '../../constants.js'; import { MissingIndexForInternationalization } from '../../errors/errors-data.js'; import { AstroError } from '../../errors/index.js'; diff --git a/packages/astro/src/core/routing/manifest/generator.ts b/packages/astro/src/core/routing/manifest/generator.ts index 4ab635ec6..e3565864d 100644 --- a/packages/astro/src/core/routing/manifest/generator.ts +++ b/packages/astro/src/core/routing/manifest/generator.ts @@ -1,6 +1,6 @@ -import type { AstroConfig, RoutePart } from '../../../@types/astro.js'; - import { compile } from 'path-to-regexp'; +import type { AstroConfig } from '../../../types/public/config.js'; +import type { RoutePart } from '../../../types/public/internal.js'; /** * Sanitizes the parameters object by normalizing string values and replacing certain characters with their URL-encoded equivalents. diff --git a/packages/astro/src/core/routing/manifest/pattern.ts b/packages/astro/src/core/routing/manifest/pattern.ts index 65f223aa0..8a9a9d27f 100644 --- a/packages/astro/src/core/routing/manifest/pattern.ts +++ b/packages/astro/src/core/routing/manifest/pattern.ts @@ -1,4 +1,5 @@ -import type { AstroConfig, RoutePart } from '../../../@types/astro.js'; +import type { AstroConfig } from '../../../types/public/config.js'; +import type { RoutePart } from '../../../types/public/internal.js'; export function getPattern( segments: RoutePart[][], diff --git a/packages/astro/src/core/routing/manifest/serialization.ts b/packages/astro/src/core/routing/manifest/serialization.ts index 852aa703b..c0cf600f0 100644 --- a/packages/astro/src/core/routing/manifest/serialization.ts +++ b/packages/astro/src/core/routing/manifest/serialization.ts @@ -1,4 +1,6 @@ -import type { AstroConfig, RouteData, SerializedRouteData } from '../../../@types/astro.js'; +import type { SerializedRouteData } from '../../../types/astro.js'; +import type { AstroConfig } from '../../../types/public/config.js'; +import type { RouteData } from '../../../types/public/internal.js'; import { getRouteGenerator } from './generator.js'; diff --git a/packages/astro/src/core/routing/match.ts b/packages/astro/src/core/routing/match.ts index 40a8b95fb..403b3fb95 100644 --- a/packages/astro/src/core/routing/match.ts +++ b/packages/astro/src/core/routing/match.ts @@ -1,4 +1,5 @@ -import type { ManifestData, RouteData } from '../../@types/astro.js'; +import type { ManifestData } from '../../types/astro.js'; +import type { RouteData } from '../../types/public/internal.js'; /** Find matching route from pathname */ export function matchRoute(pathname: string, manifest: ManifestData): RouteData | undefined { diff --git a/packages/astro/src/core/routing/params.ts b/packages/astro/src/core/routing/params.ts index 43cd24cc1..802c39cc5 100644 --- a/packages/astro/src/core/routing/params.ts +++ b/packages/astro/src/core/routing/params.ts @@ -1,4 +1,5 @@ -import type { GetStaticPathsItem, Params, RouteData } from '../../@types/astro.js'; +import type { GetStaticPathsItem, Params } from '../../types/public/common.js'; +import type { RouteData } from '../../types/public/internal.js'; import { trimSlashes } from '../path.js'; import { validateGetStaticPathsParameter } from './validation.js'; diff --git a/packages/astro/src/core/routing/priority.ts b/packages/astro/src/core/routing/priority.ts index 408268397..dc1c665c6 100644 --- a/packages/astro/src/core/routing/priority.ts +++ b/packages/astro/src/core/routing/priority.ts @@ -1,4 +1,4 @@ -import type { RouteData } from '../../@types/astro.js'; +import type { RouteData } from '../../types/public/internal.js'; /** * Comparator for sorting routes in resolution order. diff --git a/packages/astro/src/core/routing/rewrite.ts b/packages/astro/src/core/routing/rewrite.ts index f30caed08..a6fce3354 100644 --- a/packages/astro/src/core/routing/rewrite.ts +++ b/packages/astro/src/core/routing/rewrite.ts @@ -1,4 +1,6 @@ -import type { AstroConfig, RewritePayload, RouteData } from '../../@types/astro.js'; +import type { RewritePayload } from '../../types/public/common.js'; +import type { AstroConfig } from '../../types/public/config.js'; +import type { RouteData } from '../../types/public/internal.js'; import { shouldAppendForwardSlash } from '../build/util.js'; import { appendForwardSlash, removeTrailingForwardSlash } from '../path.js'; import { DEFAULT_404_ROUTE } from './astro-designed-error-pages.js'; diff --git a/packages/astro/src/core/routing/validation.ts b/packages/astro/src/core/routing/validation.ts index 1f11f55e6..a2f9a25ba 100644 --- a/packages/astro/src/core/routing/validation.ts +++ b/packages/astro/src/core/routing/validation.ts @@ -1,4 +1,6 @@ -import type { ComponentInstance, GetStaticPathsResult, RouteData } from '../../@types/astro.js'; +import type { ComponentInstance } from '../../types/astro.js'; +import type { GetStaticPathsResult } from '../../types/public/common.js'; +import type { RouteData } from '../../types/public/internal.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; diff --git a/packages/astro/src/core/server-islands/endpoint.ts b/packages/astro/src/core/server-islands/endpoint.ts index 368a1b9b1..73ed57177 100644 --- a/packages/astro/src/core/server-islands/endpoint.ts +++ b/packages/astro/src/core/server-islands/endpoint.ts @@ -1,9 +1,3 @@ -import type { - ComponentInstance, - ManifestData, - RouteData, - SSRManifest, -} from '../../@types/astro.js'; import { type AstroComponentFactory, type ComponentSlots, @@ -11,6 +5,8 @@ import { renderTemplate, } from '../../runtime/server/index.js'; import { createSlotValueFromString } from '../../runtime/server/render/slot.js'; +import type { ComponentInstance, ManifestData } from '../../types/astro.js'; +import type { RouteData, SSRManifest } from '../../types/public/internal.js'; import { decryptString } from '../encryption.js'; import { getPattern } from '../routing/manifest/pattern.js'; diff --git a/packages/astro/src/core/server-islands/vite-plugin-server-islands.ts b/packages/astro/src/core/server-islands/vite-plugin-server-islands.ts index 573ae9cf9..8bc79e087 100644 --- a/packages/astro/src/core/server-islands/vite-plugin-server-islands.ts +++ b/packages/astro/src/core/server-islands/vite-plugin-server-islands.ts @@ -1,5 +1,5 @@ import type { ConfigEnv, ViteDevServer, Plugin as VitePlugin } from 'vite'; -import type { AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; import type { AstroPluginMetadata } from '../../vite-plugin-astro/index.js'; export const VIRTUAL_ISLAND_MAP_ID = '@astro-server-islands'; diff --git a/packages/astro/src/core/sync/index.ts b/packages/astro/src/core/sync/index.ts index 3df81846e..805a955bb 100644 --- a/packages/astro/src/core/sync/index.ts +++ b/packages/astro/src/core/sync/index.ts @@ -3,7 +3,6 @@ import { performance } from 'node:perf_hooks'; import { fileURLToPath } from 'node:url'; import { dim } from 'kleur/colors'; import { type HMRPayload, createServer } from 'vite'; -import type { AstroConfig, AstroInlineConfig, AstroSettings } from '../../@types/astro.js'; import { CONTENT_TYPES_FILE, DATA_STORE_FILE } from '../../content/consts.js'; import { globalContentLayer } from '../../content/content-layer.js'; import { createContentTypesGenerator } from '../../content/index.js'; @@ -13,6 +12,8 @@ import { syncAstroEnv } from '../../env/sync.js'; import { telemetry } from '../../events/index.js'; import { eventCliSession } from '../../events/session.js'; import { runHookConfigDone, runHookConfigSetup } from '../../integrations/hooks.js'; +import type { AstroSettings } from '../../types/astro.js'; +import type { AstroConfig, AstroInlineConfig } from '../../types/public/config.js'; import { getTimeStat } from '../build/util.js'; import { resolveConfig } from '../config/config.js'; import { createNodeLogger } from '../config/logging.js'; diff --git a/packages/astro/src/core/sync/write-files.ts b/packages/astro/src/core/sync/write-files.ts index 91084c36f..1f7d1d304 100644 --- a/packages/astro/src/core/sync/write-files.ts +++ b/packages/astro/src/core/sync/write-files.ts @@ -3,7 +3,7 @@ import { dirname, relative } from 'node:path'; import { fileURLToPath } from 'node:url'; import { bold } from 'kleur/colors'; import { normalizePath } from 'vite'; -import type { AstroSettings } from '../../@types/astro.js'; +import type { AstroSettings } from '../../types/astro.js'; import { AstroError, AstroErrorData } from '../errors/index.js'; import type { Logger } from '../logger/core.js'; import { REFERENCE_FILE } from './constants.js'; diff --git a/packages/astro/src/core/util.ts b/packages/astro/src/core/util.ts index 654d19829..497d54610 100644 --- a/packages/astro/src/core/util.ts +++ b/packages/astro/src/core/util.ts @@ -1,7 +1,9 @@ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; -import type { AstroConfig, AstroSettings, RouteType } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroConfig } from '../types/public/config.js'; +import type { RouteType } from '../types/public/internal.js'; import { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from './constants.js'; import { removeTrailingForwardSlash, slash } from './path.js'; diff --git a/packages/astro/src/env/sync.ts b/packages/astro/src/env/sync.ts index 27436f967..90a29685d 100644 --- a/packages/astro/src/env/sync.ts +++ b/packages/astro/src/env/sync.ts @@ -1,5 +1,5 @@ import fsMod from 'node:fs'; -import type { AstroSettings } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; import { TYPES_TEMPLATE_URL } from './constants.js'; import { getEnvFieldType } from './validators.js'; diff --git a/packages/astro/src/env/vite-plugin-env.ts b/packages/astro/src/env/vite-plugin-env.ts index 9ae24a90b..b6d3194a6 100644 --- a/packages/astro/src/env/vite-plugin-env.ts +++ b/packages/astro/src/env/vite-plugin-env.ts @@ -1,8 +1,8 @@ import type fsMod from 'node:fs'; import { fileURLToPath } from 'node:url'; import { type Plugin, loadEnv } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; +import type { AstroSettings } from '../types/astro.js'; import { MODULE_TEMPLATE_URL, VIRTUAL_MODULES_IDS, diff --git a/packages/astro/src/events/session.ts b/packages/astro/src/events/session.ts index 18049ac04..6e919f127 100644 --- a/packages/astro/src/events/session.ts +++ b/packages/astro/src/events/session.ts @@ -1,5 +1,6 @@ -import type { AstroIntegration, AstroUserConfig } from '../@types/astro.js'; import { AstroConfigSchema } from '../core/config/schema.js'; +import type { AstroUserConfig } from '../types/public/config.js'; +import type { AstroIntegration } from '../types/public/integrations.js'; const EVENT_SESSION = 'ASTRO_CLI_SESSION_STARTED'; diff --git a/packages/astro/src/i18n/index.ts b/packages/astro/src/i18n/index.ts index aa38b63bb..c7e676f75 100644 --- a/packages/astro/src/i18n/index.ts +++ b/packages/astro/src/i18n/index.ts @@ -1,15 +1,11 @@ import { appendForwardSlash, joinPaths } from '@astrojs/internal-helpers/path'; -import type { - APIContext, - AstroConfig, - Locales, - SSRManifest, - ValidRedirectStatus, -} from '../@types/astro.js'; +import type { SSRManifest } from '../core/app/types.js'; import { shouldAppendForwardSlash } from '../core/build/util.js'; import { REROUTE_DIRECTIVE_HEADER } from '../core/constants.js'; import { MissingLocale, i18nNoLocaleFoundInPath } from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/index.js'; +import type { AstroConfig, Locales, ValidRedirectStatus } from '../types/public/config.js'; +import type { APIContext } from '../types/public/context.js'; import { createI18nMiddleware } from './middleware.js'; import type { RoutingStrategies } from './utils.js'; diff --git a/packages/astro/src/i18n/middleware.ts b/packages/astro/src/i18n/middleware.ts index 097332805..7c2fc1406 100644 --- a/packages/astro/src/i18n/middleware.ts +++ b/packages/astro/src/i18n/middleware.ts @@ -1,6 +1,7 @@ -import type { APIContext, MiddlewareHandler, SSRManifest } from '../@types/astro.js'; -import type { SSRManifestI18n } from '../core/app/types.js'; +import type { SSRManifest, SSRManifestI18n } from '../core/app/types.js'; import { ROUTE_TYPE_HEADER } from '../core/constants.js'; +import type { MiddlewareHandler } from '../types/public/common.js'; +import type { APIContext } from '../types/public/context.js'; import { type MiddlewarePayload, normalizeTheLocale, diff --git a/packages/astro/src/i18n/utils.ts b/packages/astro/src/i18n/utils.ts index 052fe01fc..98a44a19c 100644 --- a/packages/astro/src/i18n/utils.ts +++ b/packages/astro/src/i18n/utils.ts @@ -1,4 +1,4 @@ -import type { AstroConfig, Locales } from '../@types/astro.js'; +import type { AstroConfig, Locales } from '../types/public/config.js'; import { normalizeTheLocale, toCodes } from './index.js'; type BrowserLocale = { diff --git a/packages/astro/src/i18n/vite-plugin-i18n.ts b/packages/astro/src/i18n/vite-plugin-i18n.ts index 7aa4d327b..5ee79a883 100644 --- a/packages/astro/src/i18n/vite-plugin-i18n.ts +++ b/packages/astro/src/i18n/vite-plugin-i18n.ts @@ -1,7 +1,8 @@ import type * as vite from 'vite'; -import type { AstroConfig, AstroSettings } from '../@types/astro.js'; import { AstroError } from '../core/errors/errors.js'; import { AstroErrorData } from '../core/errors/index.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroConfig } from '../types/public/config.js'; const virtualModuleId = 'astro:i18n'; diff --git a/packages/astro/src/integrations/features-validation.ts b/packages/astro/src/integrations/features-validation.ts index e0613c6e8..3d1191953 100644 --- a/packages/astro/src/integrations/features-validation.ts +++ b/packages/astro/src/integrations/features-validation.ts @@ -1,11 +1,11 @@ +import type { Logger } from '../core/logger/core.js'; +import type { AstroConfig } from '../types/public/config.js'; import type { + AdapterSupportsKind, + AstroAdapterFeatureMap, AstroAdapterFeatures, AstroAssetsFeature, - AstroConfig, - AstroFeatureMap, - SupportsKind, -} from '../@types/astro.js'; -import type { Logger } from '../core/logger/core.js'; +} from '../types/public/integrations.js'; const STABLE = 'stable'; const DEPRECATED = 'deprecated'; @@ -19,7 +19,7 @@ const UNSUPPORTED_ASSETS_FEATURE: AstroAssetsFeature = { }; type ValidationResult = { - [Property in keyof AstroFeatureMap]: boolean; + [Property in keyof AstroAdapterFeatureMap]: boolean; }; /** @@ -31,7 +31,7 @@ type ValidationResult = { */ export function validateSupportedFeatures( adapterName: string, - featureMap: AstroFeatureMap, + featureMap: AstroAdapterFeatureMap, config: AstroConfig, adapterFeatures: AstroAdapterFeatures | undefined, logger: Logger, @@ -81,12 +81,6 @@ export function validateSupportedFeatures( return config?.output === 'server' && !config?.site; }, ); - if (adapterFeatures?.functionPerRoute) { - logger.error( - 'config', - 'The Astro feature `i18nDomains` is incompatible with the Adapter feature `functionPerRoute`', - ); - } } validationResult.envGetSecret = validateSupportKind( @@ -101,7 +95,7 @@ export function validateSupportedFeatures( } function validateSupportKind( - supportKind: SupportsKind, + supportKind: AdapterSupportsKind, adapterName: string, logger: Logger, featureName: string, diff --git a/packages/astro/src/integrations/hooks.ts b/packages/astro/src/integrations/hooks.ts index aa62572ee..1dc681db6 100644 --- a/packages/astro/src/integrations/hooks.ts +++ b/packages/astro/src/integrations/hooks.ts @@ -3,24 +3,22 @@ import type { AddressInfo } from 'node:net'; import { fileURLToPath } from 'node:url'; import { bold } from 'kleur/colors'; import type { InlineConfig, ViteDevServer } from 'vite'; -import type { - AstroAdapter, - AstroConfig, - AstroIntegration, - AstroRenderer, - AstroSettings, - ContentEntryType, - DataEntryType, - HookParameters, - RouteData, - RouteOptions, -} from '../@types/astro.js'; import type { SerializedSSRManifest } from '../core/app/types.js'; import type { PageBuildData } from '../core/build/types.js'; import { buildClientDirectiveEntrypoint } from '../core/client-directive/index.js'; import { mergeConfig } from '../core/config/index.js'; import type { AstroIntegrationLogger, Logger } from '../core/logger/core.js'; import { isServerLikeOutput } from '../core/util.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroConfig } from '../types/public/config.js'; +import type { ContentEntryType, DataEntryType } from '../types/public/content.js'; +import type { + AstroIntegration, + AstroRenderer, + HookParameters, + RouteOptions, +} from '../types/public/integrations.js'; +import type { RouteData } from '../types/public/internal.js'; import { validateSupportedFeatures } from './features-validation.js'; async function withTakingALongTimeMsg<T>({ @@ -198,10 +196,6 @@ export async function runHookConfigSetup({ addWatchFile: (path) => { updatedSettings.watchFiles.push(path instanceof URL ? fileURLToPath(path) : path); }, - addDevOverlayPlugin: (entrypoint) => { - // TODO add a deprecation warning in Astro 5. - hooks.addDevToolbarApp(entrypoint); - }, addDevToolbarApp: (entrypoint) => { updatedSettings.devToolbarApps.push(entrypoint); }, @@ -626,11 +620,3 @@ export async function runHookRouteSetup({ ); } } - -export function isFunctionPerRouteEnabled(adapter: AstroAdapter | undefined): boolean { - if (adapter?.adapterFeatures?.functionPerRoute === true) { - return true; - } else { - return false; - } -} diff --git a/packages/astro/src/jsx/babel.ts b/packages/astro/src/jsx/babel.ts deleted file mode 100644 index 648831481..000000000 --- a/packages/astro/src/jsx/babel.ts +++ /dev/null @@ -1,326 +0,0 @@ -import type { PluginObj } from '@babel/core'; -import * as t from '@babel/types'; -import { AstroError } from '../core/errors/errors.js'; -import { AstroErrorData } from '../core/errors/index.js'; -import { resolvePath } from '../core/viteUtils.js'; -import { createDefaultAstroMetadata } from '../vite-plugin-astro/metadata.js'; -import type { PluginMetadata } from '../vite-plugin-astro/types.js'; - -const ClientOnlyPlaceholder = 'astro-client-only'; - -function isComponent(tagName: string) { - return ( - (tagName[0] && tagName[0].toLowerCase() !== tagName[0]) || - tagName.includes('.') || - /[^a-zA-Z]/.test(tagName[0]) - ); -} - -function hasClientDirective(node: t.JSXElement) { - for (const attr of node.openingElement.attributes) { - if (attr.type === 'JSXAttribute' && attr.name.type === 'JSXNamespacedName') { - return attr.name.namespace.name === 'client'; - } - } - return false; -} - -function isClientOnlyComponent(node: t.JSXElement) { - for (const attr of node.openingElement.attributes) { - if (attr.type === 'JSXAttribute' && attr.name.type === 'JSXNamespacedName') { - return jsxAttributeToString(attr) === 'client:only'; - } - } - return false; -} - -function getTagName(tag: t.JSXElement) { - const jsxName = tag.openingElement.name; - return jsxElementNameToString(jsxName); -} - -function jsxElementNameToString(node: t.JSXOpeningElement['name']): string { - if (t.isJSXMemberExpression(node)) { - return `${jsxElementNameToString(node.object)}.${node.property.name}`; - } - if (t.isJSXIdentifier(node) || t.isIdentifier(node)) { - return node.name; - } - return `${node.namespace.name}:${node.name.name}`; -} - -function jsxAttributeToString(attr: t.JSXAttribute): string { - if (t.isJSXNamespacedName(attr.name)) { - return `${attr.name.namespace.name}:${attr.name.name.name}`; - } - return `${attr.name.name}`; -} - -function addClientMetadata( - node: t.JSXElement, - meta: { resolvedPath: string; path: string; name: string }, -) { - const existingAttributes = node.openingElement.attributes.map((attr) => - t.isJSXAttribute(attr) ? jsxAttributeToString(attr) : null, - ); - if (!existingAttributes.find((attr) => attr === 'client:component-path')) { - const componentPath = t.jsxAttribute( - t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-path')), - t.stringLiteral(meta.resolvedPath), - ); - node.openingElement.attributes.push(componentPath); - } - if (!existingAttributes.find((attr) => attr === 'client:component-export')) { - if (meta.name === '*') { - meta.name = getTagName(node).split('.').slice(1).join('.')!; - } - const componentExport = t.jsxAttribute( - t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-export')), - t.stringLiteral(meta.name), - ); - node.openingElement.attributes.push(componentExport); - } - if (!existingAttributes.find((attr) => attr === 'client:component-hydration')) { - const staticMarker = t.jsxAttribute( - t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-hydration')), - ); - node.openingElement.attributes.push(staticMarker); - } -} - -function addClientOnlyMetadata( - node: t.JSXElement, - meta: { resolvedPath: string; path: string; name: string }, -) { - const tagName = getTagName(node); - node.openingElement = t.jsxOpeningElement( - t.jsxIdentifier(ClientOnlyPlaceholder), - node.openingElement.attributes, - ); - if (node.closingElement) { - node.closingElement = t.jsxClosingElement(t.jsxIdentifier(ClientOnlyPlaceholder)); - } - const existingAttributes = node.openingElement.attributes.map((attr) => - t.isJSXAttribute(attr) ? jsxAttributeToString(attr) : null, - ); - if (!existingAttributes.find((attr) => attr === 'client:display-name')) { - const displayName = t.jsxAttribute( - t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('display-name')), - t.stringLiteral(tagName), - ); - node.openingElement.attributes.push(displayName); - } - if (!existingAttributes.find((attr) => attr === 'client:component-path')) { - const componentPath = t.jsxAttribute( - t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-path')), - t.stringLiteral(meta.resolvedPath), - ); - node.openingElement.attributes.push(componentPath); - } - if (!existingAttributes.find((attr) => attr === 'client:component-export')) { - if (meta.name === '*') { - meta.name = getTagName(node).split('.').at(1)!; - } - const componentExport = t.jsxAttribute( - t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-export')), - t.stringLiteral(meta.name), - ); - node.openingElement.attributes.push(componentExport); - } - if (!existingAttributes.find((attr) => attr === 'client:component-hydration')) { - const staticMarker = t.jsxAttribute( - t.jsxNamespacedName(t.jsxIdentifier('client'), t.jsxIdentifier('component-hydration')), - ); - node.openingElement.attributes.push(staticMarker); - } -} - -/** - * @deprecated This plugin is no longer used. Remove in Astro 5.0 - */ -export default function astroJSX(): PluginObj { - return { - visitor: { - Program: { - enter(path, state) { - if (!(state.file.metadata as PluginMetadata).astro) { - (state.file.metadata as PluginMetadata).astro = createDefaultAstroMetadata(); - } - path.node.body.splice( - 0, - 0, - t.importDeclaration( - [t.importSpecifier(t.identifier('Fragment'), t.identifier('Fragment'))], - t.stringLiteral('astro/jsx-runtime'), - ), - ); - }, - }, - ImportDeclaration(path, state) { - const source = path.node.source.value; - if (source.startsWith('astro/jsx-runtime')) return; - const specs = path.node.specifiers.map((spec) => { - if (t.isImportDefaultSpecifier(spec)) - return { local: spec.local.name, imported: 'default' }; - if (t.isImportNamespaceSpecifier(spec)) return { local: spec.local.name, imported: '*' }; - if (t.isIdentifier(spec.imported)) - return { local: spec.local.name, imported: spec.imported.name }; - return { local: spec.local.name, imported: spec.imported.value }; - }); - const imports = state.get('imports') ?? new Map(); - for (const spec of specs) { - if (imports.has(source)) { - const existing = imports.get(source); - existing.add(spec); - imports.set(source, existing); - } else { - imports.set(source, new Set([spec])); - } - } - state.set('imports', imports); - }, - JSXMemberExpression(path, state) { - const node = path.node; - // Skip automatic `_components` in MDX files - if ( - state.filename?.endsWith('.mdx') && - t.isJSXIdentifier(node.object) && - node.object.name === '_components' - ) { - return; - } - const parent = path.findParent((n) => t.isJSXElement(n.node))!; - const parentNode = parent.node as t.JSXElement; - const tagName = getTagName(parentNode); - if (!isComponent(tagName)) return; - if (!hasClientDirective(parentNode)) return; - const isClientOnly = isClientOnlyComponent(parentNode); - if (tagName === ClientOnlyPlaceholder) return; - - const imports = state.get('imports') ?? new Map(); - const namespace = tagName.split('.'); - for (const [source, specs] of imports) { - for (const { imported, local } of specs) { - const reference = path.referencesImport(source, imported); - if (reference) { - path.setData('import', { name: imported, path: source }); - break; - } - if (namespace.at(0) === local) { - const name = imported === '*' ? imported : tagName; - path.setData('import', { name, path: source }); - break; - } - } - } - - const meta = path.getData('import'); - if (meta) { - const resolvedPath = resolvePath(meta.path, state.filename!); - - if (isClientOnly) { - (state.file.metadata as PluginMetadata).astro.clientOnlyComponents.push({ - exportName: meta.name, - localName: '', - specifier: tagName, - resolvedPath, - }); - - meta.resolvedPath = resolvedPath; - addClientOnlyMetadata(parentNode, meta); - } else { - (state.file.metadata as PluginMetadata).astro.hydratedComponents.push({ - exportName: '*', - localName: '', - specifier: tagName, - resolvedPath, - }); - - meta.resolvedPath = resolvedPath; - addClientMetadata(parentNode, meta); - } - } else { - throw new Error( - `Unable to match <${getTagName( - parentNode, - )}> with client:* directive to an import statement!`, - ); - } - }, - JSXIdentifier(path, state) { - const isAttr = path.findParent((n) => t.isJSXAttribute(n.node)); - if (isAttr) return; - const parent = path.findParent((n) => t.isJSXElement(n.node))!; - const parentNode = parent.node as t.JSXElement; - const tagName = getTagName(parentNode); - if (!isComponent(tagName)) return; - if (!hasClientDirective(parentNode)) return; - const isClientOnly = isClientOnlyComponent(parentNode); - if (tagName === ClientOnlyPlaceholder) return; - - const imports = state.get('imports') ?? new Map(); - const namespace = tagName.split('.'); - for (const [source, specs] of imports) { - for (const { imported, local } of specs) { - const reference = path.referencesImport(source, imported); - if (reference) { - path.setData('import', { name: imported, path: source }); - break; - } - if (namespace.at(0) === local) { - path.setData('import', { name: imported, path: source }); - break; - } - } - } - - const meta = path.getData('import'); - if (meta) { - // If JSX is importing an Astro component, e.g. using MDX for templating, - // check Astro node's props and make sure they are valid for an Astro component - if (meta.path.endsWith('.astro')) { - const displayName = getTagName(parentNode); - for (const attr of parentNode.openingElement.attributes) { - if (t.isJSXAttribute(attr)) { - const name = jsxAttributeToString(attr); - if (name.startsWith('client:')) { - // eslint-disable-next-line - console.warn( - `You are attempting to render <${displayName} ${name} />, but ${displayName} is an Astro component. Astro components do not render in the client and should not have a hydration directive. Please use a framework component for client rendering.`, - ); - } - } - } - } - const resolvedPath = resolvePath(meta.path, state.filename!); - if (isClientOnly) { - (state.file.metadata as PluginMetadata).astro.clientOnlyComponents.push({ - exportName: meta.name, - localName: '', - specifier: meta.name, - resolvedPath, - }); - - meta.resolvedPath = resolvedPath; - addClientOnlyMetadata(parentNode, meta); - } else { - (state.file.metadata as PluginMetadata).astro.hydratedComponents.push({ - exportName: meta.name, - localName: '', - specifier: meta.name, - resolvedPath, - }); - - meta.resolvedPath = resolvedPath; - addClientMetadata(parentNode, meta); - } - } else { - throw new AstroError({ - ...AstroErrorData.NoMatchingImport, - message: AstroErrorData.NoMatchingImport.message(getTagName(parentNode)), - }); - } - }, - }, - }; -} diff --git a/packages/astro/src/jsx/component.ts b/packages/astro/src/jsx/component.ts deleted file mode 100644 index e0ce37ef2..000000000 --- a/packages/astro/src/jsx/component.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { __astro_tag_component__ } from '../runtime/server/index.js'; -import renderer from './renderer.js'; - -const ASTRO_JSX_RENDERER_NAME = renderer.name; - -export function createAstroJSXComponent(factory: (...args: any[]) => any) { - __astro_tag_component__(factory, ASTRO_JSX_RENDERER_NAME); - return factory; -} diff --git a/packages/astro/src/jsx/index.ts b/packages/astro/src/jsx/index.ts deleted file mode 100644 index 2d5904e04..000000000 --- a/packages/astro/src/jsx/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { createAstroJSXComponent } from './component.js'; -export { default as renderer } from './renderer.js'; diff --git a/packages/astro/src/jsx/renderer.ts b/packages/astro/src/jsx/renderer.ts deleted file mode 100644 index 413257faa..000000000 --- a/packages/astro/src/jsx/renderer.ts +++ /dev/null @@ -1,11 +0,0 @@ -import type { AstroRenderer } from '../@types/astro.js'; -import { jsxTransformOptions } from './transform-options.js'; - -const renderer: AstroRenderer = { - name: 'astro:jsx', - serverEntrypoint: 'astro/jsx/server.js', - jsxImportSource: 'astro', - jsxTransformOptions, -}; - -export default renderer; diff --git a/packages/astro/src/jsx/transform-options.ts b/packages/astro/src/jsx/transform-options.ts deleted file mode 100644 index ca1d50a6a..000000000 --- a/packages/astro/src/jsx/transform-options.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { JSXTransformConfig } from '../@types/astro.js'; - -/** - * @deprecated This function is no longer used. Remove in Astro 5.0 - */ -export async function jsxTransformOptions(): Promise<JSXTransformConfig> { - // @ts-expect-error types not found - const plugin = await import('@babel/plugin-transform-react-jsx'); - const jsx = plugin.default?.default ?? plugin.default; - const { default: astroJSX } = await import('./babel.js'); - return { - plugins: [ - astroJSX(), - jsx({}, { throwIfNamespace: false, runtime: 'automatic', importSource: 'astro' }), - ], - }; -} diff --git a/packages/astro/src/preferences/index.ts b/packages/astro/src/preferences/index.ts index 2b92c5fb6..7c8779b43 100644 --- a/packages/astro/src/preferences/index.ts +++ b/packages/astro/src/preferences/index.ts @@ -1,11 +1,10 @@ -import type { AstroConfig } from '../@types/astro.js'; - import os from 'node:os'; import path from 'node:path'; import process from 'node:process'; import { fileURLToPath } from 'node:url'; import dget from 'dlv'; +import type { AstroConfig } from '../types/public/config.js'; import { DEFAULT_PREFERENCES, type Preferences, type PublicPreferences } from './defaults.js'; import { PreferenceStore } from './store.js'; diff --git a/packages/astro/src/prefetch/vite-plugin-prefetch.ts b/packages/astro/src/prefetch/vite-plugin-prefetch.ts index d64c6d500..560895b15 100644 --- a/packages/astro/src/prefetch/vite-plugin-prefetch.ts +++ b/packages/astro/src/prefetch/vite-plugin-prefetch.ts @@ -1,5 +1,5 @@ import type * as vite from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; const virtualModuleId = 'astro:prefetch'; const resolvedVirtualModuleId = '\0' + virtualModuleId; diff --git a/packages/astro/src/prerender/routing.ts b/packages/astro/src/prerender/routing.ts index cbdddff5c..888b012e0 100644 --- a/packages/astro/src/prerender/routing.ts +++ b/packages/astro/src/prerender/routing.ts @@ -1,6 +1,7 @@ -import type { AstroSettings, ComponentInstance, RouteData } from '../@types/astro.js'; import { RedirectComponentInstance, routeIsRedirect } from '../core/redirects/index.js'; import { routeComparator } from '../core/routing/priority.js'; +import type { AstroSettings, ComponentInstance } from '../types/astro.js'; +import type { RouteData } from '../types/public/internal.js'; import type { DevPipeline } from '../vite-plugin-astro-server/pipeline.js'; import { getPrerenderStatus } from './metadata.js'; diff --git a/packages/astro/src/prerender/utils.ts b/packages/astro/src/prerender/utils.ts index 4097b66b1..e34e0d5fd 100644 --- a/packages/astro/src/prerender/utils.ts +++ b/packages/astro/src/prerender/utils.ts @@ -1,6 +1,6 @@ -import type { AstroConfig } from '../@types/astro.js'; import { getOutDirWithinCwd } from '../core/build/common.js'; import { isServerLikeOutput } from '../core/util.js'; +import type { AstroConfig } from '../types/public/config.js'; export function getPrerenderDefault(config: AstroConfig) { return config.output !== 'server'; diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/astro.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/astro.ts index e63667a12..12ab602a2 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/astro.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/astro.ts @@ -1,4 +1,4 @@ -import type { DevToolbarApp, DevToolbarMetadata } from '../../../../@types/astro.js'; +import type { DevToolbarApp, DevToolbarMetadata } from '../../../../types/public/toolbar.js'; import { type Icon, isDefinedIcon } from '../ui-library/icons.js'; import { colorForIntegration, iconForIntegration } from './utils/icons.js'; import { diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/index.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/index.ts index 6a6aba42d..cc58411cf 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/index.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/index.ts @@ -1,4 +1,4 @@ -import type { DevToolbarApp } from '../../../../../@types/astro.js'; +import type { DevToolbarApp } from '../../../../../types/public/toolbar.js'; import { settings } from '../../settings.js'; import type { DevToolbarHighlight } from '../../ui-library/highlight.js'; import { positionHighlight } from '../utils/highlight.js'; diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.ts index 38559e0f9..34adf4f01 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/audit/ui/audit-ui.ts @@ -1,5 +1,5 @@ import { escape as escapeHTML } from 'html-escaper'; -import type { DevToolbarMetadata } from '../../../../../../@types/astro.js'; +import type { DevToolbarMetadata } from '../../../../../../types/public/toolbar.js'; import { attachTooltipToHighlight, createHighlight, diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/settings.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/settings.ts index 7ee42da84..192e4509b 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/settings.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/settings.ts @@ -1,4 +1,4 @@ -import type { DevToolbarApp } from '../../../../@types/astro.js'; +import type { DevToolbarApp } from '../../../../types/public/toolbar.js'; import { type Settings, settings } from '../settings.js'; import { isValidPlacement, placements } from '../ui-library/window.js'; import { diff --git a/packages/astro/src/runtime/client/dev-toolbar/apps/xray.ts b/packages/astro/src/runtime/client/dev-toolbar/apps/xray.ts index 2e56b0f24..fafc8e26d 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/apps/xray.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/apps/xray.ts @@ -1,5 +1,5 @@ import { escape as escapeHTML } from 'html-escaper'; -import type { DevToolbarApp, DevToolbarMetadata } from '../../../../@types/astro.js'; +import type { DevToolbarApp, DevToolbarMetadata } from '../../../../types/public/toolbar.js'; import type { DevToolbarHighlight } from '../ui-library/highlight.js'; import { attachTooltipToHighlight, diff --git a/packages/astro/src/runtime/client/dev-toolbar/entrypoint.ts b/packages/astro/src/runtime/client/dev-toolbar/entrypoint.ts index 9731f3597..86c616bec 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/entrypoint.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/entrypoint.ts @@ -1,6 +1,6 @@ // @ts-expect-error - This module is private and untyped import { loadDevToolbarApps } from 'astro:toolbar:internal'; -import type { ResolvedDevToolbarApp as DevToolbarAppDefinition } from '../../../@types/astro.js'; +import type { ResolvedDevToolbarApp as DevToolbarAppDefinition } from '../../../types/public/toolbar.js'; import { ToolbarAppEventTarget } from './helpers.js'; import { settings } from './settings.js'; import type { AstroDevToolbar, DevToolbarApp } from './toolbar.js'; diff --git a/packages/astro/src/runtime/client/dev-toolbar/toolbar.ts b/packages/astro/src/runtime/client/dev-toolbar/toolbar.ts index 08ea61cac..e24698d43 100644 --- a/packages/astro/src/runtime/client/dev-toolbar/toolbar.ts +++ b/packages/astro/src/runtime/client/dev-toolbar/toolbar.ts @@ -1,5 +1,5 @@ /* eslint-disable no-console */ -import type { ResolvedDevToolbarApp as DevToolbarAppDefinition } from '../../../@types/astro.js'; +import type { ResolvedDevToolbarApp as DevToolbarAppDefinition } from '../../../types/public/toolbar.js'; import { type ToolbarAppEventTarget, serverHelpers } from './helpers.js'; import { settings } from './settings.js'; import { type Icon, getIconElement, isDefinedIcon } from './ui-library/icons.js'; diff --git a/packages/astro/src/runtime/client/idle.ts b/packages/astro/src/runtime/client/idle.ts index 990d5da6e..e32b1a42f 100644 --- a/packages/astro/src/runtime/client/idle.ts +++ b/packages/astro/src/runtime/client/idle.ts @@ -1,4 +1,4 @@ -import type { ClientDirective } from '../../@types/astro.js'; +import type { ClientDirective } from '../../types/public/integrations.js'; const idleDirective: ClientDirective = (load) => { const cb = async () => { diff --git a/packages/astro/src/runtime/client/load.ts b/packages/astro/src/runtime/client/load.ts index b603eecb3..98521181c 100644 --- a/packages/astro/src/runtime/client/load.ts +++ b/packages/astro/src/runtime/client/load.ts @@ -1,4 +1,4 @@ -import type { ClientDirective } from '../../@types/astro.js'; +import type { ClientDirective } from '../../types/public/integrations.js'; const loadDirective: ClientDirective = async (load) => { const hydrate = await load(); diff --git a/packages/astro/src/runtime/client/media.ts b/packages/astro/src/runtime/client/media.ts index f894af311..0c6e497e3 100644 --- a/packages/astro/src/runtime/client/media.ts +++ b/packages/astro/src/runtime/client/media.ts @@ -1,4 +1,4 @@ -import type { ClientDirective } from '../../@types/astro.js'; +import type { ClientDirective } from '../../types/public/integrations.js'; /** * Hydrate this component when a matching media query is found diff --git a/packages/astro/src/runtime/client/only.ts b/packages/astro/src/runtime/client/only.ts index 8e072b7a3..c5fc488d4 100644 --- a/packages/astro/src/runtime/client/only.ts +++ b/packages/astro/src/runtime/client/only.ts @@ -1,4 +1,4 @@ -import type { ClientDirective } from '../../@types/astro.js'; +import type { ClientDirective } from '../../types/public/integrations.js'; /** * Hydrate this component only on the client diff --git a/packages/astro/src/runtime/client/visible.ts b/packages/astro/src/runtime/client/visible.ts index 9be4d9b31..c7d858ffb 100644 --- a/packages/astro/src/runtime/client/visible.ts +++ b/packages/astro/src/runtime/client/visible.ts @@ -1,4 +1,5 @@ -import type { ClientDirective, ClientVisibleOptions } from '../../@types/astro.js'; +import type { ClientVisibleOptions } from '../../types/public/elements.js'; +import type { ClientDirective } from '../../types/public/integrations.js'; /** * Hydrate this component when one of it's children becomes visible diff --git a/packages/astro/src/runtime/server/astro-component.ts b/packages/astro/src/runtime/server/astro-component.ts index 928d23ad8..20649b64d 100644 --- a/packages/astro/src/runtime/server/astro-component.ts +++ b/packages/astro/src/runtime/server/astro-component.ts @@ -1,5 +1,5 @@ -import type { PropagationHint } from '../../@types/astro.js'; import { AstroError, AstroErrorData } from '../../core/errors/index.js'; +import type { PropagationHint } from '../../types/public/internal.js'; import type { AstroComponentFactory } from './render/index.js'; function validateArgs(args: unknown[]): args is Parameters<AstroComponentFactory> { diff --git a/packages/astro/src/runtime/server/astro-global.ts b/packages/astro/src/runtime/server/astro-global.ts index 5948c8ff3..74b32e331 100644 --- a/packages/astro/src/runtime/server/astro-global.ts +++ b/packages/astro/src/runtime/server/astro-global.ts @@ -1,6 +1,6 @@ -import type { AstroGlobalPartial } from '../../@types/astro.js'; import { ASTRO_VERSION } from '../../core/constants.js'; import { AstroError, AstroErrorData } from '../../core/errors/index.js'; +import type { AstroGlobalPartial } from '../../types/public/context.js'; /** Create the Astro.glob() runtime function. */ function createAstroGlobFn() { diff --git a/packages/astro/src/runtime/server/endpoint.ts b/packages/astro/src/runtime/server/endpoint.ts index 900d604fd..674d62093 100644 --- a/packages/astro/src/runtime/server/endpoint.ts +++ b/packages/astro/src/runtime/server/endpoint.ts @@ -1,13 +1,16 @@ import { bold } from 'kleur/colors'; -import type { APIContext, EndpointHandler } from '../../@types/astro.js'; import { REROUTABLE_STATUS_CODES, REROUTE_DIRECTIVE_HEADER } from '../../core/constants.js'; import { EndpointDidNotReturnAResponse } from '../../core/errors/errors-data.js'; import { AstroError } from '../../core/errors/errors.js'; import type { Logger } from '../../core/logger/core.js'; +import type { APIRoute } from '../../types/public/common.js'; +import type { APIContext } from '../../types/public/context.js'; /** Renders an endpoint request to completion, returning the body. */ export async function renderEndpoint( - mod: EndpointHandler, + mod: { + [method: string]: APIRoute; + }, context: APIContext, ssr: boolean, logger: Logger, diff --git a/packages/astro/src/runtime/server/hydration.ts b/packages/astro/src/runtime/server/hydration.ts index ab6396566..982ff9977 100644 --- a/packages/astro/src/runtime/server/hydration.ts +++ b/packages/astro/src/runtime/server/hydration.ts @@ -1,10 +1,10 @@ +import { AstroError, AstroErrorData } from '../../core/errors/index.js'; import type { AstroComponentMetadata, SSRElement, SSRLoadedRenderer, SSRResult, -} from '../../@types/astro.js'; -import { AstroError, AstroErrorData } from '../../core/errors/index.js'; +} from '../../types/public/internal.js'; import { escapeHTML } from './escape.js'; import { serializeProps } from './serialize.js'; diff --git a/packages/astro/src/runtime/server/index.ts b/packages/astro/src/runtime/server/index.ts index e2b49c231..508ece984 100644 --- a/packages/astro/src/runtime/server/index.ts +++ b/packages/astro/src/runtime/server/index.ts @@ -57,7 +57,7 @@ export function mergeSlots(...slotted: unknown[]) { return slots; } -/** @internal Associate JSX components with a specific renderer (see /src/vite-plugin-jsx/tag.ts) */ +/** @internal Associate JSX components with a specific renderer (see /packages/integrations/mdx/src/vite-plugin-mdx-postprocess.ts) */ export function __astro_tag_component__(Component: unknown, rendererName: string) { if (!Component) return; if (typeof Component !== 'function') return; diff --git a/packages/astro/src/runtime/server/jsx.ts b/packages/astro/src/runtime/server/jsx.ts index 2491ab589..7280e216c 100644 --- a/packages/astro/src/runtime/server/jsx.ts +++ b/packages/astro/src/runtime/server/jsx.ts @@ -1,5 +1,5 @@ -import type { SSRResult } from '../../@types/astro.js'; import { AstroJSX, type AstroVNode, isVNode } from '../../jsx-runtime/index.js'; +import type { SSRResult } from '../../types/public/internal.js'; import { HTMLString, escapeHTML, diff --git a/packages/astro/src/runtime/server/render/astro/factory.ts b/packages/astro/src/runtime/server/render/astro/factory.ts index db319eb1a..dab33a031 100644 --- a/packages/astro/src/runtime/server/render/astro/factory.ts +++ b/packages/astro/src/runtime/server/render/astro/factory.ts @@ -1,4 +1,4 @@ -import type { PropagationHint, SSRResult } from '../../../../@types/astro.js'; +import type { PropagationHint, SSRResult } from '../../../../types/public/internal.js'; import type { HeadAndContent } from './head-and-content.js'; import type { RenderTemplateResult } from './render-template.js'; diff --git a/packages/astro/src/runtime/server/render/astro/instance.ts b/packages/astro/src/runtime/server/render/astro/instance.ts index 3246a7e1b..029231a28 100644 --- a/packages/astro/src/runtime/server/render/astro/instance.ts +++ b/packages/astro/src/runtime/server/render/astro/instance.ts @@ -1,7 +1,7 @@ -import type { SSRResult } from '../../../../@types/astro.js'; import type { ComponentSlots } from '../slot.js'; import type { AstroComponentFactory } from './factory.js'; +import type { SSRResult } from '../../../../types/public/internal.js'; import { isPromise } from '../../util.js'; import { renderChild } from '../any.js'; import type { RenderDestination } from '../common.js'; diff --git a/packages/astro/src/runtime/server/render/astro/render.ts b/packages/astro/src/runtime/server/render/astro/render.ts index 41845b7b9..adc335495 100644 --- a/packages/astro/src/runtime/server/render/astro/render.ts +++ b/packages/astro/src/runtime/server/render/astro/render.ts @@ -1,5 +1,5 @@ -import type { RouteData, SSRResult } from '../../../../@types/astro.js'; import { AstroError, AstroErrorData } from '../../../../core/errors/index.js'; +import type { RouteData, SSRResult } from '../../../../types/public/internal.js'; import { type RenderDestination, chunkToByteArray, chunkToString, encoder } from '../common.js'; import { promiseWithResolvers } from '../util.js'; import type { AstroComponentFactory } from './factory.js'; diff --git a/packages/astro/src/runtime/server/render/common.ts b/packages/astro/src/runtime/server/render/common.ts index 0845bdd65..77f05dfcc 100644 --- a/packages/astro/src/runtime/server/render/common.ts +++ b/packages/astro/src/runtime/server/render/common.ts @@ -1,6 +1,6 @@ -import type { SSRResult } from '../../../@types/astro.js'; import type { RenderInstruction } from './instruction.js'; +import type { SSRResult } from '../../../types/public/internal.js'; import type { HTMLBytes, HTMLString } from '../escape.js'; import { markHTMLString } from '../escape.js'; import { diff --git a/packages/astro/src/runtime/server/render/component.ts b/packages/astro/src/runtime/server/render/component.ts index 449f58fbc..017594e75 100644 --- a/packages/astro/src/runtime/server/render/component.ts +++ b/packages/astro/src/runtime/server/render/component.ts @@ -1,9 +1,3 @@ -import type { - AstroComponentMetadata, - RouteData, - SSRLoadedRenderer, - SSRResult, -} from '../../../@types/astro.js'; import { createRenderInstruction } from './instruction.js'; import { clsx } from 'clsx'; @@ -17,6 +11,12 @@ import { type AstroComponentFactory, isAstroComponentFactory } from './astro/fac import { renderTemplate } from './astro/index.js'; import { createAstroComponentInstance } from './astro/instance.js'; +import type { + AstroComponentMetadata, + RouteData, + SSRLoadedRenderer, + SSRResult, +} from '../../../types/public/internal.js'; import { Fragment, type RenderDestination, @@ -32,7 +32,7 @@ import { formatList, internalSpreadAttributes, renderElement, voidElementNames } const needsHeadRenderingSymbol = Symbol.for('astro.needsHeadRendering'); const rendererAliases = new Map([['solid', 'solid-js']]); -const clientOnlyValues = new Set(['solid-js', 'react', 'preact', 'vue', 'svelte', 'lit']); +const clientOnlyValues = new Set(['solid-js', 'react', 'preact', 'vue', 'svelte']); function guessRenderers(componentUrl?: string): string[] { const extname = componentUrl?.split('.').pop(); @@ -51,7 +51,6 @@ function guessRenderers(componentUrl?: string): string[] { '@astrojs/solid-js', '@astrojs/vue', '@astrojs/svelte', - '@astrojs/lit', ]; } } @@ -285,24 +284,6 @@ If you're still stuck, please open an issue on GitHub or join us at https://astr } } - // HACK! The lit renderer doesn't include a clientEntrypoint for custom elements, allow it - // to render here until we find a better way to recognize when a client entrypoint isn't required. - if ( - renderer && - !renderer.clientEntrypoint && - renderer.name !== '@astrojs/lit' && - metadata.hydrate - ) { - throw new AstroError({ - ...AstroErrorData.NoClientEntrypoint, - message: AstroErrorData.NoClientEntrypoint.message( - displayName, - metadata.hydrate, - renderer.name, - ), - }); - } - // This is a custom element without a renderer. Because of that, render it // as a string and the user is responsible for adding a script tag for the component definition. if (!html && typeof Component === 'string') { diff --git a/packages/astro/src/runtime/server/render/dom.ts b/packages/astro/src/runtime/server/render/dom.ts index e2b194df3..f92b4889a 100644 --- a/packages/astro/src/runtime/server/render/dom.ts +++ b/packages/astro/src/runtime/server/render/dom.ts @@ -1,5 +1,4 @@ -import type { SSRResult } from '../../../@types/astro.js'; - +import type { SSRResult } from '../../../types/public/internal.js'; import { markHTMLString } from '../escape.js'; import { renderSlotToString } from './slot.js'; import { toAttributeString } from './util.js'; diff --git a/packages/astro/src/runtime/server/render/head.ts b/packages/astro/src/runtime/server/render/head.ts index 49dd5abed..01f11f21e 100644 --- a/packages/astro/src/runtime/server/render/head.ts +++ b/packages/astro/src/runtime/server/render/head.ts @@ -1,5 +1,4 @@ -import type { SSRResult } from '../../../@types/astro.js'; - +import type { SSRResult } from '../../../types/public/internal.js'; import { markHTMLString } from '../escape.js'; import type { MaybeRenderHeadInstruction, RenderHeadInstruction } from './instruction.js'; import { createRenderInstruction } from './instruction.js'; diff --git a/packages/astro/src/runtime/server/render/page.ts b/packages/astro/src/runtime/server/render/page.ts index 35a7ec789..0e0bcf295 100644 --- a/packages/astro/src/runtime/server/render/page.ts +++ b/packages/astro/src/runtime/server/render/page.ts @@ -1,7 +1,7 @@ -import type { RouteData, SSRResult } from '../../../@types/astro.js'; import { type NonAstroPageComponent, renderComponentToString } from './component.js'; import type { AstroComponentFactory } from './index.js'; +import type { RouteData, SSRResult } from '../../../types/public/internal.js'; import { isAstroComponentFactory } from './astro/index.js'; import { renderToAsyncIterable, renderToReadableStream, renderToString } from './astro/render.js'; import { encoder } from './common.js'; diff --git a/packages/astro/src/runtime/server/render/script.ts b/packages/astro/src/runtime/server/render/script.ts index 1b9c5ce1b..6d9283790 100644 --- a/packages/astro/src/runtime/server/render/script.ts +++ b/packages/astro/src/runtime/server/render/script.ts @@ -1,4 +1,4 @@ -import type { SSRResult } from '../../../@types/astro.js'; +import type { SSRResult } from '../../../types/public/internal.js'; import { markHTMLString } from '../escape.js'; /** diff --git a/packages/astro/src/runtime/server/render/server-islands.ts b/packages/astro/src/runtime/server/render/server-islands.ts index 0a0721134..fce702364 100644 --- a/packages/astro/src/runtime/server/render/server-islands.ts +++ b/packages/astro/src/runtime/server/render/server-islands.ts @@ -1,5 +1,5 @@ -import type { SSRResult } from '../../../@types/astro.js'; import { encryptString } from '../../../core/encryption.js'; +import type { SSRResult } from '../../../types/public/internal.js'; import { renderChild } from './any.js'; import type { RenderInstance } from './common.js'; import { type ComponentSlots, renderSlotToString } from './slot.js'; diff --git a/packages/astro/src/runtime/server/render/slot.ts b/packages/astro/src/runtime/server/render/slot.ts index d02a32d82..0df374406 100644 --- a/packages/astro/src/runtime/server/render/slot.ts +++ b/packages/astro/src/runtime/server/render/slot.ts @@ -1,7 +1,7 @@ -import type { SSRResult } from '../../../@types/astro.js'; import { renderTemplate } from './astro/render-template.js'; import type { RenderInstruction } from './instruction.js'; +import type { SSRResult } from '../../../types/public/internal.js'; import { HTMLString, markHTMLString, unescapeHTML } from '../escape.js'; import { renderChild } from './any.js'; import { type RenderDestination, type RenderInstance, chunkToString } from './common.js'; diff --git a/packages/astro/src/runtime/server/render/tags.ts b/packages/astro/src/runtime/server/render/tags.ts index 093c51a3c..baba11a5b 100644 --- a/packages/astro/src/runtime/server/render/tags.ts +++ b/packages/astro/src/runtime/server/render/tags.ts @@ -1,5 +1,5 @@ -import type { SSRElement, SSRResult } from '../../../@types/astro.js'; import type { StylesheetAsset } from '../../../core/app/types.js'; +import type { SSRElement, SSRResult } from '../../../types/public/internal.js'; import { renderElement } from './util.js'; export function renderScriptElement({ props, children }: SSRElement) { diff --git a/packages/astro/src/runtime/server/render/util.ts b/packages/astro/src/runtime/server/render/util.ts index 5dc821aa5..19ac2f2b1 100644 --- a/packages/astro/src/runtime/server/render/util.ts +++ b/packages/astro/src/runtime/server/render/util.ts @@ -1,16 +1,13 @@ -import type { SSRElement } from '../../../@types/astro.js'; import type { RenderDestination, RenderDestinationChunk, RenderFunction } from './common.js'; import { clsx } from 'clsx'; +import type { SSRElement } from '../../../types/public/internal.js'; import { HTMLString, markHTMLString } from '../escape.js'; export const voidElementNames = /^(area|base|br|col|command|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i; const htmlBooleanAttributes = /^(?:allowfullscreen|async|autofocus|autoplay|controls|default|defer|disabled|disablepictureinpicture|disableremoteplayback|formnovalidate|hidden|loop|nomodule|novalidate|open|playsinline|readonly|required|reversed|scoped|seamless|itemscope)$/i; -const htmlEnumAttributes = /^(?:contenteditable|draggable|spellcheck|value)$/i; -// Note: SVG is case-sensitive! -const svgEnumAttributes = /^(?:autoReverse|externalResourcesRequired|focusable|preserveAlpha)$/i; const AMPERSAND_REGEX = /&/g; const DOUBLE_QUOTE_REGEX = /"/g; @@ -67,13 +64,6 @@ export function addAttribute(value: any, key: string, shouldEscape = true) { return ''; } - if (value === false) { - if (htmlEnumAttributes.test(key) || svgEnumAttributes.test(key)) { - return markHTMLString(` ${key}="false"`); - } - return ''; - } - // compiler directives cannot be applied dynamically, log a warning and ignore. if (STATIC_DIRECTIVES.has(key)) { // eslint-disable-next-line no-console @@ -115,11 +105,16 @@ Make sure to use the static attribute syntax (\`${key}={value}\`) instead of the } // Boolean values only need the key - if (value === true && (key.startsWith('data-') || htmlBooleanAttributes.test(key))) { + if (htmlBooleanAttributes.test(key)) { + return markHTMLString(value ? ` ${key}` : ''); + } + + // Other attributes with an empty string value can omit rendering the value + if (value === '') { return markHTMLString(` ${key}`); - } else { - return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`); } + + return markHTMLString(` ${key}="${toAttributeString(value, shouldEscape)}"`); } // Adds support for `<Component {...value} /> diff --git a/packages/astro/src/runtime/server/scripts.ts b/packages/astro/src/runtime/server/scripts.ts index 84f2dcd52..ca9cad1fb 100644 --- a/packages/astro/src/runtime/server/scripts.ts +++ b/packages/astro/src/runtime/server/scripts.ts @@ -1,4 +1,4 @@ -import type { SSRResult } from '../../@types/astro.js'; +import type { SSRResult } from '../../types/public/internal.js'; import islandScriptDev from './astro-island.prebuilt-dev.js'; import islandScript from './astro-island.prebuilt.js'; diff --git a/packages/astro/src/runtime/server/serialize.ts b/packages/astro/src/runtime/server/serialize.ts index 522b05256..6afe91917 100644 --- a/packages/astro/src/runtime/server/serialize.ts +++ b/packages/astro/src/runtime/server/serialize.ts @@ -1,5 +1,5 @@ -import type { AstroComponentMetadata } from '../../@types/astro.js'; import type { ValueOf } from '../../type-utils.js'; +import type { AstroComponentMetadata } from '../../types/public/internal.js'; const PROP_TYPE = { Value: 0, diff --git a/packages/astro/src/runtime/server/transition.ts b/packages/astro/src/runtime/server/transition.ts index 8887d3dae..4baae442a 100644 --- a/packages/astro/src/runtime/server/transition.ts +++ b/packages/astro/src/runtime/server/transition.ts @@ -1,12 +1,12 @@ import cssesc from 'cssesc'; +import { fade, slide } from '../../transitions/index.js'; +import type { SSRResult } from '../../types/public/internal.js'; import type { - SSRResult, TransitionAnimation, TransitionAnimationPair, TransitionAnimationValue, TransitionDirectionalAnimations, -} from '../../@types/astro.js'; -import { fade, slide } from '../../transitions/index.js'; +} from '../../types/public/view-transitions.js'; import { markHTMLString } from './escape.js'; const transitionNameMap = new WeakMap<SSRResult, number>(); diff --git a/packages/astro/src/toolbar/index.ts b/packages/astro/src/toolbar/index.ts index bd05e4417..78d7158b2 100644 --- a/packages/astro/src/toolbar/index.ts +++ b/packages/astro/src/toolbar/index.ts @@ -1,4 +1,4 @@ -import type { DevToolbarApp } from '../@types/astro.js'; +import type { DevToolbarApp } from '../types/public/toolbar.js'; export function defineToolbarApp(app: DevToolbarApp) { return app; diff --git a/packages/astro/src/toolbar/vite-plugin-dev-toolbar.ts b/packages/astro/src/toolbar/vite-plugin-dev-toolbar.ts index 32c91752f..d4d0510e6 100644 --- a/packages/astro/src/toolbar/vite-plugin-dev-toolbar.ts +++ b/packages/astro/src/toolbar/vite-plugin-dev-toolbar.ts @@ -1,7 +1,7 @@ import type * as vite from 'vite'; -import type { AstroPluginOptions } from '../@types/astro.js'; import { telemetry } from '../events/index.js'; import { eventAppToggled } from '../events/toolbar.js'; +import type { AstroPluginOptions } from '../types/astro.js'; const PRIVATE_VIRTUAL_MODULE_ID = 'astro:toolbar:internal'; const resolvedPrivateVirtualModuleId = '\0' + PRIVATE_VIRTUAL_MODULE_ID; diff --git a/packages/astro/src/transitions/index.ts b/packages/astro/src/transitions/index.ts index d87052f2d..05bfb0972 100644 --- a/packages/astro/src/transitions/index.ts +++ b/packages/astro/src/transitions/index.ts @@ -1,4 +1,8 @@ -import type { TransitionAnimationPair, TransitionDirectionalAnimations } from '../@types/astro.js'; +import type { + TransitionAnimationPair, + TransitionDirectionalAnimations, +} from '../types/public/view-transitions.js'; + export { createAnimationScope } from '../runtime/server/transition.js'; const EASE_IN_OUT_QUART = 'cubic-bezier(0.76, 0, 0.24, 1)'; diff --git a/packages/astro/src/transitions/vite-plugin-transitions.ts b/packages/astro/src/transitions/vite-plugin-transitions.ts index d88c96f89..56f086a06 100644 --- a/packages/astro/src/transitions/vite-plugin-transitions.ts +++ b/packages/astro/src/transitions/vite-plugin-transitions.ts @@ -1,5 +1,5 @@ import type * as vite from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; const virtualModuleId = 'astro:transitions'; const resolvedVirtualModuleId = '\0' + virtualModuleId; diff --git a/packages/astro/src/types/README.md b/packages/astro/src/types/README.md new file mode 100644 index 000000000..103312106 --- /dev/null +++ b/packages/astro/src/types/README.md @@ -0,0 +1,5 @@ +# `types/` + +In this folder rest the types that are used throughout Astro. Typically folders for corresponding features will have a corresponding `types.ts` file in their folder. For example, the `src/assets/types.ts` contain the types for `astro:assets`. However this folder can be useful for types that are used across multiple features, or generally don't fit in any other folder. + +This folder additionally contain a `public` folder, which contains types that are exposed to users one way or another. Remember that these types are part of the public API, and as such follow the same semver contract as the rest of Astro. diff --git a/packages/astro/src/types/astro.ts b/packages/astro/src/types/astro.ts new file mode 100644 index 000000000..1d48536d0 --- /dev/null +++ b/packages/astro/src/types/astro.ts @@ -0,0 +1,88 @@ +import type { SSRManifest } from '../core/app/types.js'; +import type { AstroTimer } from '../core/config/timer.js'; +import type { TSConfig } from '../core/config/tsconfig.js'; +import type { Logger } from '../core/logger/core.js'; +import type { AstroPreferences } from '../preferences/index.js'; +import type { AstroComponentFactory } from '../runtime/server/index.js'; +import type { GetStaticPathsOptions, GetStaticPathsResult } from './public/common.js'; +import type { AstroConfig } from './public/config.js'; +import type { ContentEntryType, DataEntryType } from './public/content.js'; +import type { + AstroAdapter, + AstroRenderer, + InjectedRoute, + InjectedScriptStage, + InjectedType, + ResolvedInjectedRoute, +} from './public/integrations.js'; +import type { RouteData } from './public/internal.js'; +import type { DevToolbarAppEntry } from './public/toolbar.js'; + +export type SerializedRouteData = Omit< + RouteData, + 'generate' | 'pattern' | 'redirectRoute' | 'fallbackRoutes' +> & { + generate: undefined; + pattern: string; + redirectRoute: SerializedRouteData | undefined; + fallbackRoutes: SerializedRouteData[]; + _meta: { + trailingSlash: AstroConfig['trailingSlash']; + }; +}; + +export interface AstroSettings { + config: AstroConfig; + adapter: AstroAdapter | undefined; + preferences: AstroPreferences; + injectedRoutes: InjectedRoute[]; + resolvedInjectedRoutes: ResolvedInjectedRoute[]; + pageExtensions: string[]; + contentEntryTypes: ContentEntryType[]; + dataEntryTypes: DataEntryType[]; + renderers: AstroRenderer[]; + scripts: { + stage: InjectedScriptStage; + content: string; + }[]; + /** + * Map of directive name (e.g. `load`) to the directive script code + */ + clientDirectives: Map<string, string>; + devToolbarApps: (DevToolbarAppEntry | string)[]; + middlewares: { pre: string[]; post: string[] }; + tsConfig: TSConfig | undefined; + tsConfigPath: string | undefined; + watchFiles: string[]; + timer: AstroTimer; + dotAstroDir: URL; + /** + * Latest version of Astro, will be undefined if: + * - unable to check + * - the user has disabled the check + * - the check has not completed yet + * - the user is on the latest version already + */ + latestAstroVersion: string | undefined; + serverIslandMap: NonNullable<SSRManifest['serverIslandMap']>; + serverIslandNameMap: NonNullable<SSRManifest['serverIslandNameMap']>; + injectedTypes: Array<InjectedType>; +} + +/** Generic interface for a component (Astro, Svelte, React, etc.) */ +export interface ComponentInstance { + default: AstroComponentFactory; + css?: string[]; + partial?: boolean; + prerender?: boolean; + getStaticPaths?: (options: GetStaticPathsOptions) => GetStaticPathsResult; +} + +export interface ManifestData { + routes: RouteData[]; +} + +export interface AstroPluginOptions { + settings: AstroSettings; + logger: Logger; +} diff --git a/packages/astro/src/types/public/common.ts b/packages/astro/src/types/public/common.ts new file mode 100644 index 000000000..4bb94f5ca --- /dev/null +++ b/packages/astro/src/types/public/common.ts @@ -0,0 +1,176 @@ +import type { OmitIndexSignature, Simplify } from '../../type-utils.js'; +import type { APIContext } from './context.js'; + +/** + * getStaticPaths() options + * + * [Astro Reference](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + */ +export interface GetStaticPathsOptions { + paginate: PaginateFunction; +} + +export type GetStaticPathsItem = { + params: { [K in keyof Params]: Params[K] | number }; + props?: Props; +}; +export type GetStaticPathsResult = GetStaticPathsItem[]; +export type GetStaticPathsResultKeyed = GetStaticPathsResult & { + keyed: Map<string, GetStaticPathsItem>; +}; + +/** + * Return an array of pages to generate for a [dynamic route](https://docs.astro.build/en/guides/routing/#dynamic-routes). (**SSG Only**) + * + * [Astro Reference](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + */ +export type GetStaticPaths = ( + options: GetStaticPathsOptions, +) => Promise<GetStaticPathsResult> | GetStaticPathsResult; + +/** + * paginate() Options + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#paginate) + */ +export interface PaginateOptions<PaginateProps extends Props, PaginateParams extends Params> { + /** the number of items per-page (default: `10`) */ + pageSize?: number; + /** key: value object of page params (ex: `{ tag: 'javascript' }`) */ + params?: PaginateParams; + /** object of props to forward to `page` result */ + props?: PaginateProps; +} + +/** + * Represents a single page of data in a paginated collection + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#the-pagination-page-prop) + */ +export interface Page<T = any> { + /** result */ + data: T[]; + /** metadata */ + /** the count of the first item on the page, starting from 0 */ + start: number; + /** the count of the last item on the page, starting from 0 */ + end: number; + /** total number of results */ + total: number; + /** the current page number, starting from 1 */ + currentPage: number; + /** number of items per page (default: 10) */ + size: number; + /** number of last page */ + lastPage: number; + url: { + /** url of the current page */ + current: string; + /** url of the previous page (if there is one) */ + prev: string | undefined; + /** url of the next page (if there is one) */ + next: string | undefined; + /** url of the first page (if the current page is not the first page) */ + first: string | undefined; + /** url of the next page (if the current page in not the last page) */ + last: string | undefined; + }; +} + +export type PaginateFunction = < + PaginateData, + AdditionalPaginateProps extends Props, + AdditionalPaginateParams extends Params, +>( + data: PaginateData[], + args?: PaginateOptions<AdditionalPaginateProps, AdditionalPaginateParams>, +) => { + params: Simplify< + { + page: string | undefined; + } & OmitIndexSignature<AdditionalPaginateParams> + >; + props: Simplify< + { + page: Page<PaginateData>; + } & OmitIndexSignature<AdditionalPaginateProps> + >; +}[]; + +export type APIRoute< + Props extends Record<string, any> = Record<string, any>, + APIParams extends Record<string, string | undefined> = Record<string, string | undefined>, +> = (context: APIContext<Props, APIParams>) => Response | Promise<Response>; + +export type RewritePayload = string | URL | Request; + +export type MiddlewareNext = (rewritePayload?: RewritePayload) => Promise<Response>; +export type MiddlewareHandler = ( + context: APIContext, + next: MiddlewareNext, +) => Promise<Response> | Response | Promise<void> | void; + +/** + * Infers the shape of the `params` property returned by `getStaticPaths()`. + * + * @example + * ```ts + * import type { GetStaticPaths } from 'astro'; + * + * export const getStaticPaths = (() => { + * return results.map((entry) => ({ + * params: { slug: entry.slug }, + * })); + * }) satisfies GetStaticPaths; + * + * type Params = InferGetStaticParamsType<typeof getStaticPaths>; + * // ^? { slug: string; } + * + * const { slug } = Astro.params as Params; + * ``` + */ +export type InferGetStaticParamsType<T> = T extends ( + opts?: GetStaticPathsOptions, +) => infer R | Promise<infer R> + ? R extends Array<infer U> + ? U extends { params: infer P } + ? P + : never + : never + : never; + +/** + * Infers the shape of the `props` property returned by `getStaticPaths()`. + * + * @example + * ```ts + * import type { GetStaticPaths } from 'astro'; + * + * export const getStaticPaths = (() => { + * return results.map((entry) => ({ + * params: { slug: entry.slug }, + * props: { + * propA: true, + * propB: 42 + * }, + * })); + * }) satisfies GetStaticPaths; + * + * type Props = InferGetStaticPropsType<typeof getStaticPaths>; + * // ^? { propA: boolean; propB: number; } + * + * const { propA, propB } = Astro.props; + * ``` + */ +export type InferGetStaticPropsType<T> = T extends ( + opts: GetStaticPathsOptions, +) => infer R | Promise<infer R> + ? R extends Array<infer U> + ? U extends { props: infer P } + ? P + : never + : never + : never; + +export type Params = Record<string, string | undefined>; +export type Props = Record<string, unknown>; diff --git a/packages/astro/src/@types/astro.ts b/packages/astro/src/types/public/config.ts index c584e5657..353e24115 100644 --- a/packages/astro/src/@types/astro.ts +++ b/packages/astro/src/types/public/config.ts @@ -1,408 +1,38 @@ import type { OutgoingHttpHeaders } from 'node:http'; -import type { AddressInfo } from 'node:net'; import type { - MarkdownHeading, - MarkdownVFile, RehypePlugins, RemarkPlugins, RemarkRehype, ShikiConfig, } from '@astrojs/markdown-remark'; -import type * as babel from '@babel/core'; -import type * as rollup from 'rollup'; -import type * as vite from 'vite'; -import type { - ActionAccept, - ActionClient, - ActionInputSchema, - ActionReturnType, -} from '../actions/runtime/virtual/server.js'; -import type { RemotePattern } from '../assets/utils/remotePattern.js'; -import type { DataEntry, RenderedContent } from '../content/data-store.js'; -import type { AssetsPrefix, SSRManifest, SerializedSSRManifest } from '../core/app/types.js'; -import type { PageBuildData } from '../core/build/types.js'; -import type { AstroConfigType } from '../core/config/index.js'; -import type { AstroTimer } from '../core/config/timer.js'; -import type { TSConfig } from '../core/config/tsconfig.js'; -import type { AstroCookies } from '../core/cookies/index.js'; -import type { AstroIntegrationLogger, Logger, LoggerLevel } from '../core/logger/core.js'; -import type { EnvSchema } from '../env/schema.js'; -import type { getToolbarServerCommunicationHelpers } from '../integrations/hooks.js'; -import type { AstroPreferences } from '../preferences/index.js'; -import type { - ToolbarAppEventTarget, - ToolbarServerHelpers, -} from '../runtime/client/dev-toolbar/helpers.js'; -import type { AstroDevToolbar, DevToolbarCanvas } from '../runtime/client/dev-toolbar/toolbar.js'; -import type { Icon } from '../runtime/client/dev-toolbar/ui-library/icons.js'; -import type { - DevToolbarBadge, - DevToolbarButton, - DevToolbarCard, - DevToolbarHighlight, - DevToolbarIcon, - DevToolbarRadioCheckbox, - DevToolbarSelect, - DevToolbarToggle, - DevToolbarTooltip, - DevToolbarWindow, -} from '../runtime/client/dev-toolbar/ui-library/index.js'; -import type { AstroComponentFactory, AstroComponentInstance } from '../runtime/server/index.js'; -import type { - TransitionBeforePreparationEvent, - TransitionBeforeSwapEvent, -} from '../transitions/events.js'; -import type { DeepPartial, OmitIndexSignature, Simplify } from '../type-utils.js'; -import type { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from './../core/constants.js'; - -export type { AstroIntegrationLogger, ToolbarServerHelpers }; +import type { UserConfig as OriginalViteUserConfig, SSROptions as ViteSSROptions } from 'vite'; +import type { RemotePattern } from '../../assets/utils/remotePattern.js'; +import type { AssetsPrefix } from '../../core/app/types.js'; +import type { AstroConfigType } from '../../core/config/schema.js'; +import type { Logger, LoggerLevel } from '../../core/logger/core.js'; +import type { EnvSchema } from '../../env/schema.js'; +import type { AstroIntegration, RoutePriorityOverride } from './integrations.js'; -export type { - MarkdownHeading, - RehypePlugins, - RemarkPlugins, - ShikiConfig, -} from '@astrojs/markdown-remark'; -export type { - ExternalImageService, - ImageService, - LocalImageService, -} from '../assets/services/service.js'; -export type { - GetImageResult, - ImageInputFormat, - ImageMetadata, - ImageOutputFormat, - ImageQuality, - ImageQualityPreset, - ImageTransform, - UnresolvedImageTransform, -} from '../assets/types.js'; -export type { RemotePattern } from '../assets/utils/remotePattern.js'; -export type { AssetsPrefix, SSRManifest } from '../core/app/types.js'; -export type { - AstroCookieGetOptions, - AstroCookieSetOptions, - AstroCookies, -} from '../core/cookies/index.js'; - -export interface AstroBuiltinProps { - 'client:load'?: boolean; - 'client:idle'?: boolean; - 'client:media'?: string; - 'client:visible'?: ClientVisibleOptions | boolean; - 'client:only'?: boolean | string; - 'server:defer'?: boolean; -} - -export type ClientVisibleOptions = Pick<IntersectionObserverInit, 'rootMargin'>; - -export interface TransitionAnimation { - name: string; // The name of the keyframe - delay?: number | string; - duration?: number | string; - easing?: string; - fillMode?: string; - direction?: string; -} - -export interface TransitionAnimationPair { - old: TransitionAnimation | TransitionAnimation[]; - new: TransitionAnimation | TransitionAnimation[]; -} - -export interface TransitionDirectionalAnimations { - forwards: TransitionAnimationPair; - backwards: TransitionAnimationPair; -} - -export type TransitionAnimationValue = - | 'initial' - | 'slide' - | 'fade' - | 'none' - | TransitionDirectionalAnimations; - -// Allow users to extend this for astro-jsx.d.ts - -// eslint-disable-next-line @typescript-eslint/no-empty-object-type -export interface AstroClientDirectives {} - -export interface AstroBuiltinAttributes { - 'class:list'?: - | Record<string, boolean> - | Record<any, any> - | Iterable<string> - | Iterable<any> - | string; - 'set:html'?: any; - 'set:text'?: any; - 'is:raw'?: boolean; - 'transition:animate'?: TransitionAnimationValue; - 'transition:name'?: string; - 'transition:persist'?: boolean | string; -} - -export interface AstroDefineVarsAttribute { - 'define:vars'?: any; -} - -export interface AstroStyleAttributes { - 'is:global'?: boolean; - 'is:inline'?: boolean; -} - -export interface AstroScriptAttributes { - 'is:inline'?: boolean; -} - -export interface AstroSlotAttributes { - 'is:inline'?: boolean; -} - -export interface AstroComponentMetadata { - displayName: string; - hydrate?: 'load' | 'idle' | 'visible' | 'media' | 'only'; - hydrateArgs?: any; - componentUrl?: string; - componentExport?: { value: string; namespace?: boolean }; - astroStaticSlot: true; -} +export type Locales = (string | { codes: string[]; path: string })[]; -/** The flags supported by the Astro CLI */ -export interface CLIFlags { - root?: string; - site?: string; - base?: string; - host?: string | boolean; - port?: number; - config?: string; - open?: string | boolean; +export interface ImageServiceConfig<T extends Record<string, any> = Record<string, any>> { + entrypoint: 'astro/assets/services/sharp' | 'astro/assets/services/squoosh' | (string & {}); + config?: T; } -/** - * Astro global available in all contexts in .astro files - * - * [Astro reference](https://docs.astro.build/reference/api-reference/#astro-global) - */ -export interface AstroGlobal< - Props extends Record<string, any> = Record<string, any>, - Self = AstroComponentFactory, - Params extends Record<string, string | undefined> = Record<string, string | undefined>, -> extends AstroGlobalPartial, - AstroSharedContext<Props, Params> { - /** - * A full URL object of the request URL. - * Equivalent to: `new URL(Astro.request.url)` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#url) - */ - url: AstroSharedContext['url']; - /** Parameters passed to a dynamic page generated using [getStaticPaths](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - * - * Example usage: - * ```astro - * --- - * export async function getStaticPaths() { - * return [ - * { params: { id: '1' } }, - * ]; - * } - * - * const { id } = Astro.params; - * --- - * <h1>{id}</h1> - * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroparams) - */ - params: AstroSharedContext<Props, Params>['params']; - /** List of props passed to this component - * - * A common way to get specific props is through [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), ex: - * ```typescript - * const { name } = Astro.props - * ``` - * - * [Astro reference](https://docs.astro.build/en/basics/astro-components/#component-props) - */ - props: AstroSharedContext<Props, Params>['props']; - /** Information about the current request. This is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object - * - * For example, to get a URL object of the current URL, you can use: - * ```typescript - * const url = new URL(Astro.request.url); - * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrorequest) - */ - request: Request; - /** Information about the outgoing response. This is a standard [ResponseInit](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#init) object - * - * For example, to change the status code you can set a different status on this object: - * ```typescript - * Astro.response.status = 404; - * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroresponse) - */ - response: ResponseInit & { - readonly headers: Headers; - }; - /** - * Get an action result on the server when using a form POST. - * Expects the action function as a parameter. - * Returns a type-safe result with the action data when - * a matching POST request is received - * and `undefined` otherwise. - * - * Example usage: - * - * ```typescript - * import { actions } from 'astro:actions'; - * - * const result = await Astro.getActionResult(actions.myAction); - * ``` - */ - getActionResult: AstroSharedContext['getActionResult']; - /** - * Call an Action directly from an Astro page or API endpoint. - * Expects the action function as the first parameter, - * and the type-safe action input as the second parameter. - * Returns a Promise with the action result. - * - * Example usage: - * - * ```typescript - * import { actions } from 'astro:actions'; - * - * const result = await Astro.callAction(actions.getPost, { postId: 'test' }); - * ``` - */ - callAction: AstroSharedContext['callAction']; - /** Redirect to another page - * - * Example usage: - * ```typescript - * if(!isLoggedIn) { - * return Astro.redirect('/login'); - * } - * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroredirect) - */ - redirect: AstroSharedContext['redirect']; - /** - * It rewrites to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted - * by the rewritten URL passed as argument. - * - * ## Example - * - * ```js - * if (pageIsNotEnabled) { - * return Astro.rewrite('/fallback-page') - * } - * ``` - */ - rewrite: AstroSharedContext['rewrite']; - /** - * The <Astro.self /> element allows a component to reference itself recursively. - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroself) - */ - self: Self; - /** Utility functions for modifying an Astro component’s slotted children - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroslots) - */ - slots: Record<string, true | undefined> & { - /** - * Check whether content for this slot name exists - * - * Example usage: - * ```typescript - * if (Astro.slots.has('default')) { - * // Do something... - * } - * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroslots) - */ - has(slotName: string): boolean; - /** - * Asynchronously renders this slot and returns a string - * - * Example usage: - * ```astro - * --- - * let html: string = ''; - * if (Astro.slots.has('default')) { - * html = await Astro.slots.render('default') - * } - * --- - * <Fragment set:html={html} /> - * ``` - * - * A second parameter can be used to pass arguments to a slotted callback - * - * Example usage: - * ```astro - * --- - * html = await Astro.slots.render('default', ["Hello", "World"]) - * --- - * ``` - * Each item in the array will be passed as an argument that you can use like so: - * ```astro - * <Component> - * {(hello, world) => <div>{hello}, {world}!</div>} - * </Component> - * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroslots) - */ - render(slotName: string, args?: any[]): Promise<string>; - }; -} +export type RuntimeMode = 'development' | 'production'; -/** Union type of supported markdown file extensions */ -type MarkdowFileExtension = (typeof SUPPORTED_MARKDOWN_FILE_EXTENSIONS)[number]; +export type ValidRedirectStatus = 300 | 301 | 302 | 303 | 304 | 307 | 308; -export interface AstroGlobalPartial { - /** - * Fetch local files into your static site setup - * - * Example usage: - * ```typescript - * const posts = await Astro.glob('../pages/post/*.md'); - * ``` - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroglob) - */ - glob(globStr: `${any}.astro`): Promise<AstroInstance[]>; - glob<T extends Record<string, any>>( - globStr: `${any}${MarkdowFileExtension}`, - ): Promise<MarkdownInstance<T>[]>; - glob<T extends Record<string, any>>(globStr: `${any}.mdx`): Promise<MDXInstance<T>[]>; - glob<T extends Record<string, any>>(globStr: string): Promise<T[]>; - /** - * Returns a [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object built from the [site](https://docs.astro.build/en/reference/configuration-reference/#site) config option - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrosite) - */ - site: URL | undefined; - /** - * Returns a string with the current version of Astro. - * - * Useful for using `<meta name="generator" content={Astro.generator} />` or crediting Astro in a site footer. - * - * [HTML Specification for `generator`](https://html.spec.whatwg.org/multipage/semantics.html#meta-generator) - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrogenerator) - */ - generator: string; -} +export type RedirectConfig = + | string + | { + status: ValidRedirectStatus; + destination: string; + priority?: RoutePriorityOverride; + }; -type ServerConfig = { +export type ServerConfig = { /** * @name server.host * @type {string | boolean} @@ -456,14 +86,17 @@ type ServerConfig = { open?: string | boolean; }; -export interface ViteUserConfig extends vite.UserConfig { - ssr?: vite.SSROptions; +export interface ViteUserConfig extends OriginalViteUserConfig { + ssr?: ViteSSROptions; } -export interface ImageServiceConfig<T extends Record<string, any> = Record<string, any>> { - entrypoint: 'astro/assets/services/sharp' | 'astro/assets/services/squoosh' | (string & {}); - config?: T; -} +// NOTE(fks): We choose to keep our hand-generated AstroUserConfig interface so that +// we can add JSDoc-style documentation and link to the definition file in our repo. +// However, Zod comes with the ability to auto-generate AstroConfig from the schema +// above. If we ever get to the point where we no longer need the dedicated type, +// consider replacing it with the following lines: +// export interface AstroUserConfig extends z.input<typeof AstroConfigSchema> { +// } /** * Astro User Config @@ -2411,58 +2044,6 @@ export interface AstroUserConfig { }; } -// NOTE(fks): We choose to keep our hand-generated AstroUserConfig interface so that -// we can add JSDoc-style documentation and link to the definition file in our repo. -// However, Zod comes with the ability to auto-generate AstroConfig from the schema -// above. If we ever get to the point where we no longer need the dedicated -// @types/config.ts file, consider replacing it with the following lines: -// -// export interface AstroUserConfig extends z.input<typeof AstroConfigSchema> { -// } - -/** - * IDs for different stages of JS script injection: - * - "before-hydration": Imported client-side, before the hydration script runs. Processed & resolved by Vite. - * - "head-inline": Injected into a script tag in the `<head>` of every page. Not processed or resolved by Vite. - * - "page": Injected into the JavaScript bundle of every page. Processed & resolved by Vite. - * - "page-ssr": Injected into the frontmatter of every Astro page. Processed & resolved by Vite. - */ -export type InjectedScriptStage = 'before-hydration' | 'head-inline' | 'page' | 'page-ssr'; - -/** - * IDs for different priorities of injected routes and redirects: - * - "normal": Merge with discovered file-based project routes, behaving the same as if the route - * was defined as a file in the project. - * - "legacy": Use the old ordering of routes. Inject routes will override any file-based project route, - * and redirects will be overridden by any project route on conflict. - */ -export type RoutePriorityOverride = 'normal' | 'legacy'; - -export interface InjectedRoute { - pattern: string; - entrypoint: string; - prerender?: boolean; -} - -export interface ResolvedInjectedRoute extends InjectedRoute { - resolvedEntryPoint?: URL; -} - -export interface RouteOptions { - /** - * The path to this route relative to the project root. The slash is normalized as forward slash - * across all OS. - * @example "src/pages/blog/[...slug].astro" - */ - readonly component: string; - /** - * Whether this route should be prerendered. If the route has an explicit `prerender` export, - * the value will be passed here. Otherwise, it's undefined and will fallback to a prerender - * default depending on the `output` option. - */ - prerender?: boolean; -} - /** * Resolved Astro Config * Config with user settings along with all defaults filled in. @@ -2514,1230 +2095,10 @@ export interface AstroInlineOnlyConfig { logger?: Logger; } -export type ContentEntryModule = { - id: string; - collection: string; - slug: string; - body: string; - data: Record<string, unknown>; - _internal: { - rawData: string; - filePath: string; - }; -}; - -export type DataEntryModule = { - id: string; - collection: string; - data: Record<string, unknown>; - _internal: { - rawData: string; - filePath: string; - }; -}; - -export type ContentEntryRenderFuction = (entry: DataEntry) => Promise<RenderedContent>; - -export interface ContentEntryType { - extensions: string[]; - getEntryInfo(params: { - fileUrl: URL; - contents: string; - }): GetContentEntryInfoReturnType | Promise<GetContentEntryInfoReturnType>; - getRenderModule?( - this: rollup.PluginContext, - params: { - contents: string; - fileUrl: URL; - viteId: string; - }, - ): rollup.LoadResult | Promise<rollup.LoadResult>; - contentModuleTypes?: string; - getRenderFunction?(settings: AstroSettings): Promise<ContentEntryRenderFuction>; - - /** - * Handle asset propagation for rendered content to avoid bleed. - * Ex. MDX content can import styles and scripts, so `handlePropagation` should be true. - * @default true - */ - handlePropagation?: boolean; -} - -type GetContentEntryInfoReturnType = { - data: Record<string, unknown>; - /** - * Used for error hints to point to correct line and location - * Should be the untouched data as read from the file, - * including newlines - */ - rawData: string; - body: string; - slug: string; -}; - -export interface DataEntryType { - extensions: string[]; - getEntryInfo(params: { - fileUrl: URL; - contents: string; - }): GetDataEntryInfoReturnType | Promise<GetDataEntryInfoReturnType>; -} - -export type GetDataEntryInfoReturnType = { data: Record<string, unknown>; rawData?: string }; - -export interface AstroAdapterFeatures { - /** - * Creates an edge function that will communiate with the Astro middleware - */ - edgeMiddleware: boolean; - /** - * SSR only. Each route becomes its own function/file. - */ - functionPerRoute: boolean; -} - -export interface InjectedType { - filename: string; - content: string; -} - -export interface AstroSettings { - config: AstroConfig; - adapter: AstroAdapter | undefined; - preferences: AstroPreferences; - injectedRoutes: InjectedRoute[]; - resolvedInjectedRoutes: ResolvedInjectedRoute[]; - pageExtensions: string[]; - contentEntryTypes: ContentEntryType[]; - dataEntryTypes: DataEntryType[]; - renderers: AstroRenderer[]; - scripts: { - stage: InjectedScriptStage; - content: string; - }[]; - /** - * Map of directive name (e.g. `load`) to the directive script code - */ - clientDirectives: Map<string, string>; - devToolbarApps: (DevToolbarAppEntry | string)[]; - middlewares: { pre: string[]; post: string[] }; - tsConfig: TSConfig | undefined; - tsConfigPath: string | undefined; - watchFiles: string[]; - timer: AstroTimer; - dotAstroDir: URL; - /** - * Latest version of Astro, will be undefined if: - * - unable to check - * - the user has disabled the check - * - the check has not completed yet - * - the user is on the latest version already - */ - latestAstroVersion: string | undefined; - serverIslandMap: NonNullable<SSRManifest['serverIslandMap']>; - serverIslandNameMap: NonNullable<SSRManifest['serverIslandNameMap']>; - injectedTypes: Array<InjectedType>; -} - -export type AsyncRendererComponentFn<U> = ( - Component: any, - props: any, - slots: Record<string, string>, - metadata?: AstroComponentMetadata, -) => Promise<U>; - -/** Generic interface for a component (Astro, Svelte, React, etc.) */ -export interface ComponentInstance { - default: AstroComponentFactory; - css?: string[]; - partial?: boolean; - prerender?: boolean; - getStaticPaths?: (options: GetStaticPathsOptions) => GetStaticPathsResult; -} - -export interface AstroInstance { - file: string; - url: string | undefined; - default: AstroComponentFactory; -} - -export interface MarkdownInstance<T extends Record<string, any>> { - frontmatter: T; - /** Absolute file path (e.g. `/home/user/projects/.../file.md`) */ - file: string; - /** Browser URL for files under `/src/pages` (e.g. `/en/guides/markdown-content`) */ - url: string | undefined; - /** Component to render content in `.astro` files. Usage: `<Content />` */ - Content: AstroComponentFactory; - /** raw Markdown file content, excluding layout HTML and YAML frontmatter */ - rawContent(): string; - /** Markdown file compiled to HTML, excluding layout HTML */ - compiledContent(): string; - /** List of headings (h1 -> h6) with associated metadata */ - getHeadings(): MarkdownHeading[]; - default: AstroComponentFactory; -} - -type MD = MarkdownInstance<Record<string, any>>; - -export type MDXInstance<T extends Record<string, any>> = Omit< - MarkdownInstance<T>, - 'rawContent' | 'compiledContent' ->; - -export interface MarkdownLayoutProps<T extends Record<string, any>> { - frontmatter: { - file: MarkdownInstance<T>['file']; - url: MarkdownInstance<T>['url']; - } & T; - file: MarkdownInstance<T>['file']; - url: MarkdownInstance<T>['url']; - headings: MarkdownHeading[]; - rawContent: MarkdownInstance<T>['rawContent']; - compiledContent: MarkdownInstance<T>['compiledContent']; -} - -export type MDXLayoutProps<T extends Record<string, any>> = Omit< - MarkdownLayoutProps<T>, - 'rawContent' | 'compiledContent' ->; - -export type GetHydrateCallback = () => Promise<() => void | Promise<void>>; - -/** - * getStaticPaths() options - * - * [Astro Reference](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - */ -export interface GetStaticPathsOptions { - paginate: PaginateFunction; -} - -export type GetStaticPathsItem = { - params: { [K in keyof Params]: Params[K] | number }; - props?: Props; -}; -export type GetStaticPathsResult = GetStaticPathsItem[]; -export type GetStaticPathsResultKeyed = GetStaticPathsResult & { - keyed: Map<string, GetStaticPathsItem>; -}; - -/** - * Return an array of pages to generate for a [dynamic route](https://docs.astro.build/en/guides/routing/#dynamic-routes). (**SSG Only**) - * - * [Astro Reference](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) - */ -export type GetStaticPaths = ( - options: GetStaticPathsOptions, -) => Promise<GetStaticPathsResult> | GetStaticPathsResult; - -/** - * Infers the shape of the `params` property returned by `getStaticPaths()`. - * - * @example - * ```ts - * import type { GetStaticPaths } from 'astro'; - * - * export const getStaticPaths = (() => { - * return results.map((entry) => ({ - * params: { slug: entry.slug }, - * })); - * }) satisfies GetStaticPaths; - * - * type Params = InferGetStaticParamsType<typeof getStaticPaths>; - * // ^? { slug: string; } - * - * const { slug } = Astro.params as Params; - * ``` - */ -export type InferGetStaticParamsType<T> = T extends ( - opts?: GetStaticPathsOptions, -) => infer R | Promise<infer R> - ? R extends Array<infer U> - ? U extends { params: infer P } - ? P - : never - : never - : never; - -/** - * Infers the shape of the `props` property returned by `getStaticPaths()`. - * - * @example - * ```ts - * import type { GetStaticPaths } from 'astro'; - * - * export const getStaticPaths = (() => { - * return results.map((entry) => ({ - * params: { slug: entry.slug }, - * props: { - * propA: true, - * propB: 42 - * }, - * })); - * }) satisfies GetStaticPaths; - * - * type Props = InferGetStaticPropsType<typeof getStaticPaths>; - * // ^? { propA: boolean; propB: number; } - * - * const { propA, propB } = Astro.props; - * ``` - */ -export type InferGetStaticPropsType<T> = T extends ( - opts: GetStaticPathsOptions, -) => infer R | Promise<infer R> - ? R extends Array<infer U> - ? U extends { props: infer P } - ? P - : never - : never - : never; - -export interface HydrateOptions { - name: string; - value?: string; -} - -export type JSXTransformConfig = Pick< - babel.TransformOptions, - 'presets' | 'plugins' | 'inputSourceMap' ->; - -export type JSXTransformFn = (options: { - mode: string; - ssr: boolean; -}) => Promise<JSXTransformConfig>; - -export interface ManifestData { - routes: RouteData[]; -} - -/** @deprecated Type is no longer used by exported APIs */ -export interface MarkdownMetadata { - headings: MarkdownHeading[]; - source: string; - html: string; -} - -/** @deprecated Type is no longer used by exported APIs */ -export interface MarkdownRenderingResult { - metadata: MarkdownMetadata; - vfile: MarkdownVFile; - code: string; -} - -/** @deprecated Type is no longer used by exported APIs */ -export interface MarkdownParserResponse extends MarkdownRenderingResult { - frontmatter: MD['frontmatter']; -} - -/** - * The `content` prop given to a Layout - * - * [Astro reference](https://docs.astro.build/en/guides/markdown-content/#markdown-layouts) - */ -export type MarkdownContent<T extends Record<string, any> = Record<string, any>> = T & { - astro: MarkdownMetadata; - url: string | undefined; - file: string; -}; - -/** - * paginate() Options - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#paginate) - */ -export interface PaginateOptions<PaginateProps extends Props, PaginateParams extends Params> { - /** the number of items per-page (default: `10`) */ - pageSize?: number; - /** key: value object of page params (ex: `{ tag: 'javascript' }`) */ - params?: PaginateParams; - /** object of props to forward to `page` result */ - props?: PaginateProps; -} - -/** - * Represents a single page of data in a paginated collection - * - * [Astro reference](https://docs.astro.build/en/reference/api-reference/#the-pagination-page-prop) - */ -export interface Page<T = any> { - /** result */ - data: T[]; - /** metadata */ - /** the count of the first item on the page, starting from 0 */ - start: number; - /** the count of the last item on the page, starting from 0 */ - end: number; - /** total number of results */ - total: number; - /** the current page number, starting from 1 */ - currentPage: number; - /** number of items per page (default: 10) */ - size: number; - /** number of last page */ - lastPage: number; - url: { - /** url of the current page */ - current: string; - /** url of the previous page (if there is one) */ - prev: string | undefined; - /** url of the next page (if there is one) */ - next: string | undefined; - /** url of the first page (if the current page is not the first page) */ - first: string | undefined; - /** url of the next page (if the current page in not the last page) */ - last: string | undefined; - }; -} - -export type PaginateFunction = < - PaginateData, - AdditionalPaginateProps extends Props, - AdditionalPaginateParams extends Params, ->( - data: PaginateData[], - args?: PaginateOptions<AdditionalPaginateProps, AdditionalPaginateParams>, -) => { - params: Simplify< - { - page: string | undefined; - } & OmitIndexSignature<AdditionalPaginateParams> - >; - props: Simplify< - { - page: Page<PaginateData>; - } & OmitIndexSignature<AdditionalPaginateProps> - >; -}[]; - -export type Params = Record<string, string | undefined>; - -export type SupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated'; - -export type AstroFeatureMap = { - /** - * The adapter is able serve static pages - */ - staticOutput?: SupportsKind; - /** - * The adapter is able to serve pages that are static or rendered via server - */ - hybridOutput?: SupportsKind; - /** - * The adapter is able to serve SSR pages - */ - serverOutput?: SupportsKind; - /** - * The adapter can emit static assets - */ - assets?: AstroAssetsFeature; - - /** - * List of features that orbit around the i18n routing - */ - i18nDomains?: SupportsKind; - - /** - * The adapter is able to support `getSecret` exported from `astro:env/server` - */ - envGetSecret?: SupportsKind; -}; - -export interface AstroAssetsFeature { - supportKind?: SupportsKind; - /** - * Whether if this adapter deploys files in an environment that is compatible with the library `sharp` - */ - isSharpCompatible?: boolean; - /** - * Whether if this adapter deploys files in an environment that is compatible with the library `squoosh` - */ - isSquooshCompatible?: boolean; -} - -export interface AstroInternationalizationFeature { - /** - * The adapter should be able to create the proper redirects - */ - domains?: SupportsKind; -} - -export type Locales = (string | { codes: string[]; path: string })[]; - -export interface AstroAdapter { - name: string; - serverEntrypoint?: string; - previewEntrypoint?: string; - exports?: string[]; - args?: any; - adapterFeatures?: AstroAdapterFeatures; - /** - * List of features supported by an adapter. - * - * If the adapter is not able to handle certain configurations, Astro will throw an error. - */ - supportedAstroFeatures: AstroFeatureMap; -} - -export type ValidRedirectStatus = 300 | 301 | 302 | 303 | 304 | 307 | 308; - -// Shared types between `Astro` global and API context object -interface AstroSharedContext< - Props extends Record<string, any> = Record<string, any>, - RouteParams extends Record<string, string | undefined> = Record<string, string | undefined>, -> { - /** - * The address (usually IP address) of the user. - * - * Throws an error if used within a static site, or within a prerendered page. - */ - clientAddress: string; - /** - * Utility for getting and setting the values of cookies. - */ - cookies: AstroCookies; - /** - * Information about the current request. This is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object - */ - request: Request; - /** - * A full URL object of the request URL. - */ - url: URL; - /** - * Get action result on the server when using a form POST. - */ - getActionResult: < - TAccept extends ActionAccept, - TInputSchema extends ActionInputSchema<TAccept>, - TAction extends ActionClient<unknown, TAccept, TInputSchema>, - >( - action: TAction, - ) => ActionReturnType<TAction> | undefined; - /** - * Call action handler from the server. - */ - callAction: < - TAccept extends ActionAccept, - TInputSchema extends ActionInputSchema<TAccept>, - TOutput, - TAction extends - | ActionClient<TOutput, TAccept, TInputSchema> - | ActionClient<TOutput, TAccept, TInputSchema>['orThrow'], - >( - action: TAction, - input: Parameters<TAction>[0], - ) => Promise<ActionReturnType<TAction>>; - /** - * Route parameters for this request if this is a dynamic route. - */ - params: RouteParams; - /** - * List of props returned for this path by `getStaticPaths` (**Static Only**). - */ - props: Props; - /** - * Redirect to another page (**SSR Only**). - */ - redirect(path: string, status?: ValidRedirectStatus): Response; - - /** - * It rewrites to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted - * by the rerouted URL passed as argument. - * - * ## Example - * - * ```js - * if (pageIsNotEnabled) { - * return Astro.rewrite('/fallback-page') - * } - * ``` - */ - rewrite(rewritePayload: RewritePayload): Promise<Response>; - - /** - * Object accessed via Astro middleware - */ - locals: App.Locals; - - /** - * The current locale that is computed from the `Accept-Language` header of the browser (**SSR Only**). - */ - preferredLocale: string | undefined; - - /** - * The list of locales computed from the `Accept-Language` header of the browser, sorted by quality value (**SSR Only**). - */ - - preferredLocaleList: string[] | undefined; - - /** - * The current locale computed from the URL of the request. It matches the locales in `i18n.locales`, and returns `undefined` otherwise. - */ - currentLocale: string | undefined; -} - -/** - * The `APIContext` is the object made available to endpoints and middleware. - * It is a subset of the `Astro` global object available in pages. - * - * [Reference](https://docs.astro.build/en/reference/api-reference/#endpoint-context) - */ -export interface APIContext< - Props extends Record<string, any> = Record<string, any>, - APIParams extends Record<string, string | undefined> = Record<string, string | undefined>, -> extends AstroSharedContext<Props, Params> { - /** - * The site provided in the astro config, parsed as an instance of `URL`, without base. - * `undefined` if the site is not provided in the config. - */ - site: URL | undefined; - /** - * A human-readable string representing the Astro version used to create the project. - * For example, `"Astro v1.1.1"`. - */ - generator: string; - /** - * The url of the current request, parsed as an instance of `URL`. - * - * Equivalent to: - * ```ts - * new URL(context.request.url) - * ``` - */ - url: AstroSharedContext['url']; - /** - * Parameters matching the page’s dynamic route pattern. - * In static builds, this will be the `params` generated by `getStaticPaths`. - * In SSR builds, this can be any path segments matching the dynamic route pattern. - * - * Example usage: - * ```ts - * import type { APIContext } from "astro" - * - * export function getStaticPaths() { - * return [ - * { params: { id: '0' }, props: { name: 'Sarah' } }, - * { params: { id: '1' }, props: { name: 'Chris' } }, - * { params: { id: '2' }, props: { name: 'Fuzzy' } }, - * ]; - * } - * - * export async function GET({ params }: APIContext) { - * return new Response(`Hello user ${params.id}!`) - * } - * ``` - * - * [Reference](https://docs.astro.build/en/reference/api-reference/#contextparams) - */ - params: AstroSharedContext<Props, APIParams>['params']; - /** - * List of props passed from `getStaticPaths`. Only available to static builds. - * - * Example usage: - * ```ts - * import type { APIContext } from "astro" - * - * export function getStaticPaths() { - * return [ - * { params: { id: '0' }, props: { name: 'Sarah' } }, - * { params: { id: '1' }, props: { name: 'Chris' } }, - * { params: { id: '2' }, props: { name: 'Fuzzy' } }, - * ]; - * } - * - * export function GET({ props }: APIContext): Response { - * return new Response(`Hello ${props.name}!`); - * } - * ``` - * - * [Reference](https://docs.astro.build/en/reference/api-reference/#contextprops) - */ - props: AstroSharedContext<Props, APIParams>['props']; - /** - * Create a response that redirects to another page. - * - * Example usage: - * ```ts - * // src/pages/secret.ts - * export function GET({ redirect }) { - * return redirect('/login'); - * } - * ``` - * - * [Reference](https://docs.astro.build/en/guides/api-reference/#contextredirect) - */ - redirect: AstroSharedContext['redirect']; - - /** - * It reroutes to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted - * by the rerouted URL passed as argument. - * - * ## Example - * - * ```ts - * // src/pages/secret.ts - * export function GET(ctx) { - * return ctx.rewrite(new URL("../"), ctx.url); - * } - * ``` - */ - rewrite: AstroSharedContext['rewrite']; - - /** - * An object that middlewares can use to store extra information related to the request. - * - * It will be made available to pages as `Astro.locals`, and to endpoints as `context.locals`. - * - * Example usage: - * - * ```ts - * // src/middleware.ts - * import { defineMiddleware } from "astro:middleware"; - * - * export const onRequest = defineMiddleware((context, next) => { - * context.locals.greeting = "Hello!"; - * return next(); - * }); - * ``` - * Inside a `.astro` file: - * ```astro - * --- - * // src/pages/index.astro - * const greeting = Astro.locals.greeting; - * --- - * <h1>{greeting}</h1> - * ``` - * - * [Reference](https://docs.astro.build/en/reference/api-reference/#contextlocals) - */ - locals: App.Locals; - - /** - * Available only when `i18n` configured and in SSR. - * - * It represents the preferred locale of the user. It's computed by checking the supported locales in `i18n.locales` - * and locales supported by the users's browser via the header `Accept-Language` - * - * For example, given `i18n.locales` equals to `['fr', 'de']`, and the `Accept-Language` value equals to `en, de;q=0.2, fr;q=0.6`, the - * `Astro.preferredLanguage` will be `fr` because `en` is not supported, its [quality value] is the highest. - * - * [quality value]: https://developer.mozilla.org/en-US/docs/Glossary/Quality_values - */ - preferredLocale: string | undefined; - - /** - * Available only when `i18n` configured and in SSR. - * - * It represents the list of the preferred locales that are supported by the application. The list is sorted via [quality value]. - * - * For example, given `i18n.locales` equals to `['fr', 'pt', 'de']`, and the `Accept-Language` value equals to `en, de;q=0.2, fr;q=0.6`, the - * `Astro.preferredLocaleList` will be equal to `['fs', 'de']` because `en` isn't supported, and `pt` isn't part of the locales contained in the - * header. - * - * When the `Accept-Header` is `*`, the original `i18n.locales` are returned. The value `*` means no preferences, so Astro returns all the supported locales. - * - * [quality value]: https://developer.mozilla.org/en-US/docs/Glossary/Quality_values - */ - preferredLocaleList: string[] | undefined; - - /** - * The current locale computed from the URL of the request. It matches the locales in `i18n.locales`, and returns `undefined` otherwise. - */ - currentLocale: string | undefined; -} - -export type APIRoute< - Props extends Record<string, any> = Record<string, any>, - APIParams extends Record<string, string | undefined> = Record<string, string | undefined>, -> = (context: APIContext<Props, APIParams>) => Response | Promise<Response>; - -export interface EndpointHandler { - [method: string]: APIRoute; -} - -export type Props = Record<string, unknown>; - -export interface AstroRenderer { - /** Name of the renderer. */ - name: string; - /** Import entrypoint for the client/browser renderer. */ - clientEntrypoint?: string; - /** Import entrypoint for the server/build/ssr renderer. */ - serverEntrypoint: string; - /** @deprecated Vite plugins should transform the JSX instead */ - jsxImportSource?: string; - /** @deprecated Vite plugins should transform the JSX instead */ - jsxTransformOptions?: JSXTransformFn; -} - -export interface NamedSSRLoadedRendererValue extends SSRLoadedRendererValue { - name: string; -} - -export interface SSRLoadedRendererValue { - name?: string; - check: AsyncRendererComponentFn<boolean>; - renderToStaticMarkup: AsyncRendererComponentFn<{ - html: string; - attrs?: Record<string, string>; - }>; - supportsAstroStaticSlot?: boolean; - /** - * If provided, Astro will call this function and inject the returned - * script in the HTML before the first component handled by this renderer. - * - * This feature is needed by some renderers (in particular, by Solid). The - * Solid official hydration script sets up a page-level data structure. - * It is mainly used to transfer data between the server side render phase - * and the browser application state. Solid Components rendered later in - * the HTML may inject tiny scripts into the HTML that call into this - * page-level data structure. - */ - renderHydrationScript?: () => string; -} - -export interface SSRLoadedRenderer extends Pick<AstroRenderer, 'name' | 'clientEntrypoint'> { - ssr: SSRLoadedRendererValue; -} - -export type HookParameters< - Hook extends keyof AstroIntegration['hooks'], - Fn = AstroIntegration['hooks'][Hook], -> = Fn extends (...args: any) => any ? Parameters<Fn>[0] : never; - +// HACK! astro:db augment this type that is used in the config declare global { - // eslint-disable-next-line @typescript-eslint/no-namespace - namespace Astro { - export interface IntegrationHooks { - 'astro:config:setup': (options: { - config: AstroConfig; - command: 'dev' | 'build' | 'preview'; - isRestart: boolean; - updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig; - addRenderer: (renderer: AstroRenderer) => void; - addWatchFile: (path: URL | string) => void; - injectScript: (stage: InjectedScriptStage, content: string) => void; - injectRoute: (injectRoute: InjectedRoute) => void; - addClientDirective: (directive: ClientDirectiveConfig) => void; - /** - * @deprecated Use `addDevToolbarApp` instead. - * TODO: Fully remove in Astro 5.0 - */ - addDevOverlayPlugin: (entrypoint: string) => void; - // TODO: Deprecate the `string` overload once a few apps have been migrated to the new API. - addDevToolbarApp: (entrypoint: DevToolbarAppEntry | string) => void; - addMiddleware: (mid: AstroIntegrationMiddleware) => void; - logger: AstroIntegrationLogger; - // TODO: Add support for `injectElement()` for full HTML element injection, not just scripts. - // This may require some refactoring of `scripts`, `styles`, and `links` into something - // more generalized. Consider the SSR use-case as well. - // injectElement: (stage: vite.HtmlTagDescriptor, element: string) => void; - }) => void | Promise<void>; - 'astro:config:done': (options: { - config: AstroConfig; - setAdapter: (adapter: AstroAdapter) => void; - injectTypes: (injectedType: InjectedType) => URL; - logger: AstroIntegrationLogger; - }) => void | Promise<void>; - 'astro:server:setup': (options: { - server: vite.ViteDevServer; - logger: AstroIntegrationLogger; - toolbar: ReturnType<typeof getToolbarServerCommunicationHelpers>; - }) => void | Promise<void>; - 'astro:server:start': (options: { - address: AddressInfo; - logger: AstroIntegrationLogger; - }) => void | Promise<void>; - 'astro:server:done': (options: { logger: AstroIntegrationLogger }) => void | Promise<void>; - 'astro:build:ssr': (options: { - manifest: SerializedSSRManifest; - /** - * This maps a {@link RouteData} to an {@link URL}, this URL represents - * the physical file you should import. - */ - entryPoints: Map<RouteData, URL>; - /** - * File path of the emitted middleware - */ - middlewareEntryPoint: URL | undefined; - logger: AstroIntegrationLogger; - }) => void | Promise<void>; - 'astro:build:start': (options: { logger: AstroIntegrationLogger }) => void | Promise<void>; - 'astro:build:setup': (options: { - vite: vite.InlineConfig; - pages: Map<string, PageBuildData>; - target: 'client' | 'server'; - updateConfig: (newConfig: vite.InlineConfig) => void; - logger: AstroIntegrationLogger; - }) => void | Promise<void>; - 'astro:build:generated': (options: { - dir: URL; - logger: AstroIntegrationLogger; - }) => void | Promise<void>; - 'astro:build:done': (options: { - pages: { pathname: string }[]; - dir: URL; - routes: RouteData[]; - logger: AstroIntegrationLogger; - cacheManifest: boolean; - }) => void | Promise<void>; - 'astro:route:setup': (options: { - route: RouteOptions; - logger: AstroIntegrationLogger; - }) => void | Promise<void>; - } - } -} - -export interface AstroIntegration { - /** The name of the integration. */ - name: string; - /** The different hooks available to extend. */ - hooks: { - [K in keyof Astro.IntegrationHooks]?: Astro.IntegrationHooks[K]; - } & Partial<Record<string, unknown>>; -} - -export type RewritePayload = string | URL | Request; - -export type MiddlewareNext = (rewritePayload?: RewritePayload) => Promise<Response>; -export type MiddlewareHandler = ( - context: APIContext, - next: MiddlewareNext, -) => Promise<Response> | Response | Promise<void> | void; - -// NOTE: when updating this file with other functions, -// remember to update `plugin-page.ts` too, to add that function as a no-op function. -export type AstroMiddlewareInstance = { - onRequest?: MiddlewareHandler; -}; - -export type AstroIntegrationMiddleware = { - order: 'pre' | 'post'; - entrypoint: string; -}; - -export interface AstroPluginOptions { - settings: AstroSettings; - logger: Logger; -} - -/** - * - page: a route that lives in the file system, usually an Astro component - * - endpoint: a route that lives in the file system, usually a JS file that exposes endpoints methods - * - redirect: a route points to another route that lives in the file system - * - fallback: a route that doesn't exist in the file system that needs to be handled with other means, usually the middleware - */ -export type RouteType = 'page' | 'endpoint' | 'redirect' | 'fallback'; - -export interface RoutePart { - content: string; - dynamic: boolean; - spread: boolean; -} - -type RedirectConfig = - | string - | { - status: ValidRedirectStatus; - destination: string; - priority?: RoutePriorityOverride; - }; - -export interface RouteData { - route: string; - component: string; - generate: (data?: any) => string; - params: string[]; - pathname?: string; - // expose the real path name on SSG - distURL?: URL; - pattern: RegExp; - segments: RoutePart[][]; - type: RouteType; - prerender: boolean; - redirect?: RedirectConfig; - redirectRoute?: RouteData; - fallbackRoutes: RouteData[]; - isIndex: boolean; -} - -export type RedirectRouteData = RouteData & { - redirect: string; -}; - -export type SerializedRouteData = Omit< - RouteData, - 'generate' | 'pattern' | 'redirectRoute' | 'fallbackRoutes' -> & { - generate: undefined; - pattern: string; - redirectRoute: SerializedRouteData | undefined; - fallbackRoutes: SerializedRouteData[]; - _meta: { - trailingSlash: AstroConfig['trailingSlash']; - }; -}; - -export type RuntimeMode = 'development' | 'production'; - -export type SSRError = Error & vite.ErrorPayload['err']; - -export interface SSRElement { - props: Record<string, any>; - children: string; -} - -/** - * A hint on whether the Astro runtime needs to wait on a component to render head - * content. The meanings: - * - * - __none__ (default) The component does not propagation head content. - * - __self__ The component appends head content. - * - __in-tree__ Another component within this component's dependency tree appends head content. - * - * These are used within the runtime to know whether or not a component should be waited on. - */ -export type PropagationHint = 'none' | 'self' | 'in-tree'; - -export type SSRComponentMetadata = { - propagation: PropagationHint; - containsHead: boolean; -}; - -export interface SSRResult { - /** - * Whether the page has failed with a non-recoverable error, or the client disconnected. - */ - cancelled: boolean; - base: string; - styles: Set<SSRElement>; - scripts: Set<SSRElement>; - links: Set<SSRElement>; - componentMetadata: Map<string, SSRComponentMetadata>; - inlinedScripts: Map<string, string>; - createAstro( - Astro: AstroGlobalPartial, - props: Record<string, any>, - slots: Record<string, any> | null, - ): AstroGlobal; - params: Params; - resolve: (s: string) => Promise<string>; - response: AstroGlobal['response']; - request: AstroGlobal['request']; - actionResult?: ReturnType<AstroGlobal['getActionResult']>; - renderers: SSRLoadedRenderer[]; - /** - * Map of directive name (e.g. `load`) to the directive script code - */ - clientDirectives: Map<string, string>; - compressHTML: boolean; - partial: boolean; - /** - * Only used for logging - */ - pathname: string; - cookies: AstroCookies | undefined; - serverIslandNameMap: Map<string, string>; - trailingSlash: AstroConfig['trailingSlash']; - key: Promise<CryptoKey>; - _metadata: SSRMetadata; -} - -/** - * Ephemeral and mutable state during rendering that doesn't rely - * on external configuration - */ -export interface SSRMetadata { - hasHydrationScript: boolean; - /** - * Names of renderers that have injected their hydration scripts - * into the current page. For example, Solid SSR needs a hydration - * script in the page HTML before the first Solid component. - */ - rendererSpecificHydrationScripts: Set<string>; - /** - * Used by `renderScript` to track script ids that have been rendered, - * so we only render each once. - */ - renderedScripts: Set<string>; - hasDirectives: Set<string>; - hasRenderedHead: boolean; - headInTree: boolean; - extraHead: string[]; - propagators: Set<AstroComponentInstance>; -} - -/* Preview server stuff */ -export interface PreviewServer { - host?: string; - port: number; - closed(): Promise<void>; - stop(): Promise<void>; -} - -export interface PreviewServerParams { - outDir: URL; - client: URL; - serverEntrypoint: URL; - host: string | undefined; - port: number; - base: string; - logger: AstroIntegrationLogger; - headers?: OutgoingHttpHeaders; -} - -export type CreatePreviewServer = ( - params: PreviewServerParams, -) => PreviewServer | Promise<PreviewServer>; - -export interface PreviewModule { - default: CreatePreviewServer; -} - -/* Client Directives */ -type DirectiveHydrate = () => Promise<void>; -type DirectiveLoad = () => Promise<DirectiveHydrate>; - -type DirectiveOptions = { - /** - * The component displayName - */ - name: string; - /** - * The attribute value provided - */ - value: string; -}; - -export type ClientDirective = ( - load: DirectiveLoad, - options: DirectiveOptions, - el: HTMLElement, -) => void; - -export interface ClientDirectiveConfig { - name: string; - entrypoint: string; -} - -type DevToolbarAppMeta = { - id: string; - name: string; - icon?: Icon; -}; - -// The param passed to `addDevToolbarApp` in the integration -export type DevToolbarAppEntry = DevToolbarAppMeta & { - entrypoint: string; -}; - -// Public API for the dev toolbar -export type DevToolbarApp = { - /** - * @deprecated The `id`, `name`, and `icon` properties should now be defined when using `addDevToolbarApp`. - * - * Ex: `addDevToolbarApp({ id: 'my-app', name: 'My App', icon: '🚀', entrypoint: '/path/to/app' })` - * - * In the future, putting these properties directly on the app object will be removed. - */ - id?: string; - /** - * @deprecated The `id`, `name`, and `icon` properties should now be defined when using `addDevToolbarApp`. - * - * Ex: `addDevToolbarApp({ id: 'my-app', name: 'My App', icon: '🚀', entrypoint: '/path/to/app' })` - * - * In the future, putting these properties directly on the app object will be removed. - */ - name?: string; - /** - * @deprecated The `id`, `name`, and `icon` properties should now be defined when using `addDevToolbarApp`. - * - * Ex: `addDevToolbarApp({ id: 'my-app', name: 'My App', icon: '🚀', entrypoint: '/path/to/app' })` - * - * In the future, putting these properties directly on the app object will be removed. - */ - icon?: Icon; - init?( - canvas: ShadowRoot, - app: ToolbarAppEventTarget, - server: ToolbarServerHelpers, - ): void | Promise<void>; - beforeTogglingOff?(canvas: ShadowRoot): boolean | Promise<boolean>; -}; - -// An app that has been loaded and as such contain all of its properties -export type ResolvedDevToolbarApp = DevToolbarAppMeta & Omit<DevToolbarApp, 'id' | 'name' | 'icon'>; - -// TODO: Remove in Astro 5.0 -export type DevOverlayPlugin = DevToolbarApp; - -export type DevToolbarMetadata = Window & - typeof globalThis & { - __astro_dev_toolbar__: { - root: string; - version: string; - latestAstroVersion: AstroSettings['latestAstroVersion']; - debugInfo: string; - }; - }; - -declare global { - interface HTMLElementTagNameMap { - 'astro-dev-toolbar': AstroDevToolbar; - 'astro-dev-toolbar-window': DevToolbarWindow; - 'astro-dev-toolbar-app-canvas': DevToolbarCanvas; - 'astro-dev-toolbar-tooltip': DevToolbarTooltip; - 'astro-dev-toolbar-highlight': DevToolbarHighlight; - 'astro-dev-toolbar-toggle': DevToolbarToggle; - 'astro-dev-toolbar-badge': DevToolbarBadge; - 'astro-dev-toolbar-button': DevToolbarButton; - 'astro-dev-toolbar-icon': DevToolbarIcon; - 'astro-dev-toolbar-card': DevToolbarCard; - 'astro-dev-toolbar-select': DevToolbarSelect; - 'astro-dev-toolbar-radio-checkbox': DevToolbarRadioCheckbox; - - // Deprecated names - // TODO: Remove in Astro 5.0 - 'astro-dev-overlay': AstroDevToolbar; - 'astro-dev-overlay-window': DevToolbarWindow; - 'astro-dev-overlay-plugin-canvas': DevToolbarCanvas; - 'astro-dev-overlay-tooltip': DevToolbarTooltip; - 'astro-dev-overlay-highlight': DevToolbarHighlight; - 'astro-dev-overlay-toggle': DevToolbarToggle; - 'astro-dev-overlay-badge': DevToolbarBadge; - 'astro-dev-overlay-button': DevToolbarButton; - 'astro-dev-overlay-icon': DevToolbarIcon; - 'astro-dev-overlay-card': DevToolbarCard; - } // eslint-disable-next-line @typescript-eslint/no-namespace namespace Config { type Database = Record<string, any>; } - - interface DocumentEventMap { - 'astro:before-preparation': TransitionBeforePreparationEvent; - 'astro:after-preparation': Event; - 'astro:before-swap': TransitionBeforeSwapEvent; - 'astro:after-swap': Event; - 'astro:page-load': Event; - } } - -// Container types -export type ContainerImportRendererFn = ( - containerRenderer: ContainerRenderer, -) => Promise<SSRLoadedRenderer>; - -export type ContainerRenderer = { - /** - * The name of the renderer. - */ - name: string; - /** - * The entrypoint that is used to render a component on the server - */ - serverEntrypoint: string; -}; diff --git a/packages/astro/src/types/public/content.ts b/packages/astro/src/types/public/content.ts new file mode 100644 index 000000000..ac58c918f --- /dev/null +++ b/packages/astro/src/types/public/content.ts @@ -0,0 +1,121 @@ +import type { MarkdownHeading } from '@astrojs/markdown-remark'; +import type * as rollup from 'rollup'; +import type { DataEntry, RenderedContent } from '../../content/data-store.js'; +import type { AstroComponentFactory } from '../../runtime/server/index.js'; +import type { AstroConfig } from './config.js'; + +export interface AstroInstance { + file: string; + url: string | undefined; + default: AstroComponentFactory; +} + +export interface MarkdownInstance<T extends Record<string, any>> { + frontmatter: T; + /** Absolute file path (e.g. `/home/user/projects/.../file.md`) */ + file: string; + /** Browser URL for files under `/src/pages` (e.g. `/en/guides/markdown-content`) */ + url: string | undefined; + /** Component to render content in `.astro` files. Usage: `<Content />` */ + Content: AstroComponentFactory; + /** raw Markdown file content, excluding layout HTML and YAML frontmatter */ + rawContent(): string; + /** Markdown file compiled to HTML, excluding layout HTML */ + compiledContent(): string; + /** List of headings (h1 -> h6) with associated metadata */ + getHeadings(): MarkdownHeading[]; + default: AstroComponentFactory; +} + +export type MDXInstance<T extends Record<string, any>> = Omit< + MarkdownInstance<T>, + 'rawContent' | 'compiledContent' +>; + +export interface MarkdownLayoutProps<T extends Record<string, any>> { + frontmatter: { + file: MarkdownInstance<T>['file']; + url: MarkdownInstance<T>['url']; + } & T; + file: MarkdownInstance<T>['file']; + url: MarkdownInstance<T>['url']; + headings: MarkdownHeading[]; + rawContent: MarkdownInstance<T>['rawContent']; + compiledContent: MarkdownInstance<T>['compiledContent']; +} + +export type MDXLayoutProps<T extends Record<string, any>> = Omit< + MarkdownLayoutProps<T>, + 'rawContent' | 'compiledContent' +>; + +export type ContentEntryModule = { + id: string; + collection: string; + slug: string; + body: string; + data: Record<string, unknown>; + _internal: { + rawData: string; + filePath: string; + }; +}; + +export type DataEntryModule = { + id: string; + collection: string; + data: Record<string, unknown>; + _internal: { + rawData: string; + filePath: string; + }; +}; + +export type ContentEntryRenderFunction = (entry: DataEntry) => Promise<RenderedContent>; + +export interface ContentEntryType { + extensions: string[]; + getEntryInfo(params: { + fileUrl: URL; + contents: string; + }): GetContentEntryInfoReturnType | Promise<GetContentEntryInfoReturnType>; + getRenderModule?( + this: rollup.PluginContext, + params: { + contents: string; + fileUrl: URL; + viteId: string; + }, + ): rollup.LoadResult | Promise<rollup.LoadResult>; + contentModuleTypes?: string; + getRenderFunction?(config: AstroConfig): Promise<ContentEntryRenderFunction>; + + /** + * Handle asset propagation for rendered content to avoid bleed. + * Ex. MDX content can import styles and scripts, so `handlePropagation` should be true. + * @default true + */ + handlePropagation?: boolean; +} + +type GetContentEntryInfoReturnType = { + data: Record<string, unknown>; + /** + * Used for error hints to point to correct line and location + * Should be the untouched data as read from the file, + * including newlines + */ + rawData: string; + body: string; + slug: string; +}; + +export interface DataEntryType { + extensions: string[]; + getEntryInfo(params: { + fileUrl: URL; + contents: string; + }): GetDataEntryInfoReturnType | Promise<GetDataEntryInfoReturnType>; +} + +export type GetDataEntryInfoReturnType = { data: Record<string, unknown>; rawData?: string }; diff --git a/packages/astro/src/types/public/context.ts b/packages/astro/src/types/public/context.ts new file mode 100644 index 000000000..5f05b7a66 --- /dev/null +++ b/packages/astro/src/types/public/context.ts @@ -0,0 +1,501 @@ +import type { + ActionAccept, + ActionClient, + ActionInputSchema, + ActionReturnType, +} from '../../actions/runtime/virtual/server.js'; +import type { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from '../../core/constants.js'; +import type { AstroCookies } from '../../core/cookies/cookies.js'; +import type { AstroComponentFactory } from '../../runtime/server/index.js'; +import type { Params, RewritePayload } from './common.js'; +import type { ValidRedirectStatus } from './config.js'; +import type { AstroInstance, MDXInstance, MarkdownInstance } from './content.js'; + +/** + * Astro global available in all contexts in .astro files + * + * [Astro reference](https://docs.astro.build/reference/api-reference/#astro-global) + */ +export interface AstroGlobal< + Props extends Record<string, any> = Record<string, any>, + Self = AstroComponentFactory, + // eslint-disable-next-line @typescript-eslint/no-shadow + Params extends Record<string, string | undefined> = Record<string, string | undefined>, +> extends AstroGlobalPartial, + AstroSharedContext<Props, Params> { + /** + * A full URL object of the request URL. + * Equivalent to: `new URL(Astro.request.url)` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#url) + */ + url: AstroSharedContext['url']; + /** Parameters passed to a dynamic page generated using [getStaticPaths](https://docs.astro.build/en/reference/api-reference/#getstaticpaths) + * + * Example usage: + * ```astro + * --- + * export async function getStaticPaths() { + * return [ + * { params: { id: '1' } }, + * ]; + * } + * + * const { id } = Astro.params; + * --- + * <h1>{id}</h1> + * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroparams) + */ + params: AstroSharedContext<Props, Params>['params']; + /** List of props passed to this component + * + * A common way to get specific props is through [destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment), ex: + * ```typescript + * const { name } = Astro.props + * ``` + * + * [Astro reference](https://docs.astro.build/en/basics/astro-components/#component-props) + */ + props: AstroSharedContext<Props, Params>['props']; + /** Information about the current request. This is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object + * + * For example, to get a URL object of the current URL, you can use: + * ```typescript + * const url = new URL(Astro.request.url); + * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrorequest) + */ + request: Request; + /** Information about the outgoing response. This is a standard [ResponseInit](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#init) object + * + * For example, to change the status code you can set a different status on this object: + * ```typescript + * Astro.response.status = 404; + * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroresponse) + */ + response: ResponseInit & { + readonly headers: Headers; + }; + /** + * Get an action result on the server when using a form POST. + * Expects the action function as a parameter. + * Returns a type-safe result with the action data when + * a matching POST request is received + * and `undefined` otherwise. + * + * Example usage: + * + * ```typescript + * import { actions } from 'astro:actions'; + * + * const result = await Astro.getActionResult(actions.myAction); + * ``` + */ + getActionResult: AstroSharedContext['getActionResult']; + /** + * Call an Action directly from an Astro page or API endpoint. + * Expects the action function as the first parameter, + * and the type-safe action input as the second parameter. + * Returns a Promise with the action result. + * + * Example usage: + * + * ```typescript + * import { actions } from 'astro:actions'; + * + * const result = await Astro.callAction(actions.getPost, { postId: 'test' }); + * ``` + */ + callAction: AstroSharedContext['callAction']; + /** Redirect to another page + * + * Example usage: + * ```typescript + * if(!isLoggedIn) { + * return Astro.redirect('/login'); + * } + * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroredirect) + */ + redirect: AstroSharedContext['redirect']; + /** + * It rewrites to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted + * by the rewritten URL passed as argument. + * + * ## Example + * + * ```js + * if (pageIsNotEnabled) { + * return Astro.rewrite('/fallback-page') + * } + * ``` + */ + rewrite: AstroSharedContext['rewrite']; + /** + * The <Astro.self /> element allows a component to reference itself recursively. + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroself) + */ + self: Self; + /** Utility functions for modifying an Astro component’s slotted children + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroslots) + */ + slots: Record<string, true | undefined> & { + /** + * Check whether content for this slot name exists + * + * Example usage: + * ```typescript + * if (Astro.slots.has('default')) { + * // Do something... + * } + * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroslots) + */ + has(slotName: string): boolean; + /** + * Asynchronously renders this slot and returns a string + * + * Example usage: + * ```astro + * --- + * let html: string = ''; + * if (Astro.slots.has('default')) { + * html = await Astro.slots.render('default') + * } + * --- + * <Fragment set:html={html} /> + * ``` + * + * A second parameter can be used to pass arguments to a slotted callback + * + * Example usage: + * ```astro + * --- + * html = await Astro.slots.render('default', ["Hello", "World"]) + * --- + * ``` + * Each item in the array will be passed as an argument that you can use like so: + * ```astro + * <Component> + * {(hello, world) => <div>{hello}, {world}!</div>} + * </Component> + * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroslots) + */ + render(slotName: string, args?: any[]): Promise<string>; + }; +} + +/** Union type of supported markdown file extensions */ +type MarkdownFileExtension = (typeof SUPPORTED_MARKDOWN_FILE_EXTENSIONS)[number]; + +export interface AstroGlobalPartial { + /** + * Fetch local files into your static site setup + * + * Example usage: + * ```typescript + * const posts = await Astro.glob('../pages/post/*.md'); + * ``` + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astroglob) + */ + glob(globStr: `${any}.astro`): Promise<AstroInstance[]>; + glob<T extends Record<string, any>>( + globStr: `${any}${MarkdownFileExtension}`, + ): Promise<MarkdownInstance<T>[]>; + glob<T extends Record<string, any>>(globStr: `${any}.mdx`): Promise<MDXInstance<T>[]>; + glob<T extends Record<string, any>>(globStr: string): Promise<T[]>; + /** + * Returns a [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) object built from the [site](https://docs.astro.build/en/reference/configuration-reference/#site) config option + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrosite) + */ + site: URL | undefined; + /** + * Returns a string with the current version of Astro. + * + * Useful for using `<meta name="generator" content={Astro.generator} />` or crediting Astro in a site footer. + * + * [HTML Specification for `generator`](https://html.spec.whatwg.org/multipage/semantics.html#meta-generator) + * + * [Astro reference](https://docs.astro.build/en/reference/api-reference/#astrogenerator) + */ + generator: string; +} + +// Shared types between `Astro` global and API context object +interface AstroSharedContext< + Props extends Record<string, any> = Record<string, any>, + RouteParams extends Record<string, string | undefined> = Record<string, string | undefined>, +> { + /** + * The address (usually IP address) of the user. + * + * Throws an error if used within a static site, or within a prerendered page. + */ + clientAddress: string; + /** + * Utility for getting and setting the values of cookies. + */ + cookies: AstroCookies; + /** + * Information about the current request. This is a standard [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object + */ + request: Request; + /** + * A full URL object of the request URL. + */ + url: URL; + /** + * Get action result on the server when using a form POST. + */ + getActionResult: < + TAccept extends ActionAccept, + TInputSchema extends ActionInputSchema<TAccept>, + TAction extends ActionClient<unknown, TAccept, TInputSchema>, + >( + action: TAction, + ) => ActionReturnType<TAction> | undefined; + /** + * Call action handler from the server. + */ + callAction: < + TAccept extends ActionAccept, + TInputSchema extends ActionInputSchema<TAccept>, + TOutput, + TAction extends + | ActionClient<TOutput, TAccept, TInputSchema> + | ActionClient<TOutput, TAccept, TInputSchema>['orThrow'], + >( + action: TAction, + input: Parameters<TAction>[0], + ) => Promise<ActionReturnType<TAction>>; + /** + * Route parameters for this request if this is a dynamic route. + */ + params: RouteParams; + /** + * List of props returned for this path by `getStaticPaths` (**Static Only**). + */ + props: Props; + /** + * Redirect to another page (**SSR Only**). + */ + redirect(path: string, status?: ValidRedirectStatus): Response; + + /** + * It rewrites to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted + * by the rerouted URL passed as argument. + * + * ## Example + * + * ```js + * if (pageIsNotEnabled) { + * return Astro.rewrite('/fallback-page') + * } + * ``` + */ + rewrite(rewritePayload: RewritePayload): Promise<Response>; + + /** + * Object accessed via Astro middleware + */ + locals: App.Locals; + + /** + * The current locale that is computed from the `Accept-Language` header of the browser (**SSR Only**). + */ + preferredLocale: string | undefined; + + /** + * The list of locales computed from the `Accept-Language` header of the browser, sorted by quality value (**SSR Only**). + */ + + preferredLocaleList: string[] | undefined; + + /** + * The current locale computed from the URL of the request. It matches the locales in `i18n.locales`, and returns `undefined` otherwise. + */ + currentLocale: string | undefined; +} + +/** + * The `APIContext` is the object made available to endpoints and middleware. + * It is a subset of the `Astro` global object available in pages. + * + * [Reference](https://docs.astro.build/en/reference/api-reference/#endpoint-context) + */ +export interface APIContext< + Props extends Record<string, any> = Record<string, any>, + APIParams extends Record<string, string | undefined> = Record<string, string | undefined>, +> extends AstroSharedContext<Props, Params> { + /** + * The site provided in the astro config, parsed as an instance of `URL`, without base. + * `undefined` if the site is not provided in the config. + */ + site: URL | undefined; + /** + * A human-readable string representing the Astro version used to create the project. + * For example, `"Astro v1.1.1"`. + */ + generator: string; + /** + * The url of the current request, parsed as an instance of `URL`. + * + * Equivalent to: + * ```ts + * new URL(context.request.url) + * ``` + */ + url: AstroSharedContext['url']; + /** + * Parameters matching the page’s dynamic route pattern. + * In static builds, this will be the `params` generated by `getStaticPaths`. + * In SSR builds, this can be any path segments matching the dynamic route pattern. + * + * Example usage: + * ```ts + * import type { APIContext } from "astro" + * + * export function getStaticPaths() { + * return [ + * { params: { id: '0' }, props: { name: 'Sarah' } }, + * { params: { id: '1' }, props: { name: 'Chris' } }, + * { params: { id: '2' }, props: { name: 'Fuzzy' } }, + * ]; + * } + * + * export async function GET({ params }: APIContext) { + * return new Response(`Hello user ${params.id}!`) + * } + * ``` + * + * [Reference](https://docs.astro.build/en/reference/api-reference/#contextparams) + */ + params: AstroSharedContext<Props, APIParams>['params']; + /** + * List of props passed from `getStaticPaths`. Only available to static builds. + * + * Example usage: + * ```ts + * import type { APIContext } from "astro" + * + * export function getStaticPaths() { + * return [ + * { params: { id: '0' }, props: { name: 'Sarah' } }, + * { params: { id: '1' }, props: { name: 'Chris' } }, + * { params: { id: '2' }, props: { name: 'Fuzzy' } }, + * ]; + * } + * + * export function GET({ props }: APIContext): Response { + * return new Response(`Hello ${props.name}!`); + * } + * ``` + * + * [Reference](https://docs.astro.build/en/reference/api-reference/#contextprops) + */ + props: AstroSharedContext<Props, APIParams>['props']; + /** + * Create a response that redirects to another page. + * + * Example usage: + * ```ts + * // src/pages/secret.ts + * export function GET({ redirect }) { + * return redirect('/login'); + * } + * ``` + * + * [Reference](https://docs.astro.build/en/guides/api-reference/#contextredirect) + */ + redirect: AstroSharedContext['redirect']; + + /** + * It reroutes to another page. As opposed to redirects, the URL won't change, and Astro will render the HTML emitted + * by the rerouted URL passed as argument. + * + * ## Example + * + * ```ts + * // src/pages/secret.ts + * export function GET(ctx) { + * return ctx.rewrite(new URL("../"), ctx.url); + * } + * ``` + */ + rewrite: AstroSharedContext['rewrite']; + + /** + * An object that middlewares can use to store extra information related to the request. + * + * It will be made available to pages as `Astro.locals`, and to endpoints as `context.locals`. + * + * Example usage: + * + * ```ts + * // src/middleware.ts + * import { defineMiddleware } from "astro:middleware"; + * + * export const onRequest = defineMiddleware((context, next) => { + * context.locals.greeting = "Hello!"; + * return next(); + * }); + * ``` + * Inside a `.astro` file: + * ```astro + * --- + * // src/pages/index.astro + * const greeting = Astro.locals.greeting; + * --- + * <h1>{greeting}</h1> + * ``` + * + * [Reference](https://docs.astro.build/en/reference/api-reference/#contextlocals) + */ + locals: App.Locals; + + /** + * Available only when `i18n` configured and in SSR. + * + * It represents the preferred locale of the user. It's computed by checking the supported locales in `i18n.locales` + * and locales supported by the users's browser via the header `Accept-Language` + * + * For example, given `i18n.locales` equals to `['fr', 'de']`, and the `Accept-Language` value equals to `en, de;q=0.2, fr;q=0.6`, the + * `Astro.preferredLanguage` will be `fr` because `en` is not supported, its [quality value] is the highest. + * + * [quality value]: https://developer.mozilla.org/en-US/docs/Glossary/Quality_values + */ + preferredLocale: string | undefined; + + /** + * Available only when `i18n` configured and in SSR. + * + * It represents the list of the preferred locales that are supported by the application. The list is sorted via [quality value]. + * + * For example, given `i18n.locales` equals to `['fr', 'pt', 'de']`, and the `Accept-Language` value equals to `en, de;q=0.2, fr;q=0.6`, the + * `Astro.preferredLocaleList` will be equal to `['fs', 'de']` because `en` isn't supported, and `pt` isn't part of the locales contained in the + * header. + * + * When the `Accept-Header` is `*`, the original `i18n.locales` are returned. The value `*` means no preferences, so Astro returns all the supported locales. + * + * [quality value]: https://developer.mozilla.org/en-US/docs/Glossary/Quality_values + */ + preferredLocaleList: string[] | undefined; + + /** + * The current locale computed from the URL of the request. It matches the locales in `i18n.locales`, and returns `undefined` otherwise. + */ + currentLocale: string | undefined; +} diff --git a/packages/astro/src/types/public/elements.ts b/packages/astro/src/types/public/elements.ts new file mode 100644 index 000000000..83301f7b8 --- /dev/null +++ b/packages/astro/src/types/public/elements.ts @@ -0,0 +1,47 @@ +import type { TransitionAnimationValue } from './view-transitions.js'; + +export interface AstroComponentDirectives extends Astro.ClientDirectives { + 'server:defer'?: boolean; +} + +export interface AstroClientDirectives { + 'client:load'?: boolean; + 'client:idle'?: boolean; + 'client:media'?: string; + 'client:visible'?: ClientVisibleOptions | boolean; + 'client:only'?: boolean | string; +} + +export type ClientVisibleOptions = Pick<IntersectionObserverInit, 'rootMargin'>; + +export interface AstroBuiltinAttributes { + 'class:list'?: + | Record<string, boolean> + | Record<any, any> + | Iterable<string> + | Iterable<any> + | string; + 'set:html'?: any; + 'set:text'?: any; + 'is:raw'?: boolean; + 'transition:animate'?: TransitionAnimationValue; + 'transition:name'?: string; + 'transition:persist'?: boolean | string; +} + +export interface AstroDefineVarsAttribute { + 'define:vars'?: any; +} + +export interface AstroStyleAttributes { + 'is:global'?: boolean; + 'is:inline'?: boolean; +} + +export interface AstroScriptAttributes { + 'is:inline'?: boolean; +} + +export interface AstroSlotAttributes { + 'is:inline'?: boolean; +} diff --git a/packages/astro/src/types/public/extendables.ts b/packages/astro/src/types/public/extendables.ts new file mode 100644 index 000000000..1592eda19 --- /dev/null +++ b/packages/astro/src/types/public/extendables.ts @@ -0,0 +1,21 @@ +/* eslint-disable @typescript-eslint/no-namespace */ +/* eslint-disable @typescript-eslint/no-empty-object-type */ +import type { AstroClientDirectives } from './elements.js'; +import type { BaseIntegrationHooks } from './integrations.js'; + +// The interfaces in this file can be extended by users +declare global { + namespace App { + /** + * Used by middlewares to store information, that can be read by the user via the global `Astro.locals` + */ + export interface Locals {} + } + + namespace Astro { + export interface IntegrationHooks extends BaseIntegrationHooks {} + export interface ClientDirectives extends AstroClientDirectives {} + } +} + +export {}; diff --git a/packages/astro/src/types/public/index.ts b/packages/astro/src/types/public/index.ts new file mode 100644 index 000000000..5df509013 --- /dev/null +++ b/packages/astro/src/types/public/index.ts @@ -0,0 +1,44 @@ +export type * from './config.js'; +export type * from './elements.js'; +export type * from './extendables.js'; +export type * from './toolbar.js'; +export type * from './view-transitions.js'; +export type * from './integrations.js'; +export type * from './internal.js'; +export type * from './context.js'; +export type * from './preview.js'; +export type * from './content.js'; +export type * from './common.js'; + +export type { AstroIntegrationLogger } from '../../core/logger/core.js'; +export type { ToolbarServerHelpers } from '../../runtime/client/dev-toolbar/helpers.js'; + +export type { + MarkdownHeading, + RehypePlugins, + RemarkPlugins, + ShikiConfig, +} from '@astrojs/markdown-remark'; +export type { + ExternalImageService, + ImageService, + LocalImageService, +} from '../../assets/services/service.js'; +export type { + GetImageResult, + ImageInputFormat, + ImageMetadata, + ImageOutputFormat, + ImageQuality, + ImageQualityPreset, + ImageTransform, + UnresolvedImageTransform, +} from '../../assets/types.js'; +export type { RemotePattern } from '../../assets/utils/remotePattern.js'; +export type { AssetsPrefix, SSRManifest } from '../../core/app/types.js'; +export type { + AstroCookieGetOptions, + AstroCookieSetOptions, + AstroCookies, +} from '../../core/cookies/index.js'; +export type { ContainerRenderer } from '../../container/index.js'; diff --git a/packages/astro/src/types/public/integrations.ts b/packages/astro/src/types/public/integrations.ts new file mode 100644 index 000000000..7b3cb4b65 --- /dev/null +++ b/packages/astro/src/types/public/integrations.ts @@ -0,0 +1,254 @@ +import type { AddressInfo } from 'node:net'; +import type { ViteDevServer, InlineConfig as ViteInlineConfig } from 'vite'; +import type { SerializedSSRManifest } from '../../core/app/types.js'; +import type { PageBuildData } from '../../core/build/types.js'; +import type { AstroIntegrationLogger } from '../../core/logger/core.js'; +import type { getToolbarServerCommunicationHelpers } from '../../integrations/hooks.js'; +import type { DeepPartial } from '../../type-utils.js'; +import type { AstroConfig } from './config.js'; +import type { RouteData } from './internal.js'; +import type { DevToolbarAppEntry } from './toolbar.js'; + +export interface RouteOptions { + /** + * The path to this route relative to the project root. The slash is normalized as forward slash + * across all OS. + * @example "src/pages/blog/[...slug].astro" + */ + readonly component: string; + /** + * Whether this route should be prerendered. If the route has an explicit `prerender` export, + * the value will be passed here. Otherwise, it's undefined and will fallback to a prerender + * default depending on the `output` option. + */ + prerender?: boolean; +} + +/* Client Directives */ +type DirectiveHydrate = () => Promise<void>; +type DirectiveLoad = () => Promise<DirectiveHydrate>; + +type DirectiveOptions = { + /** + * The component displayName + */ + name: string; + /** + * The attribute value provided + */ + value: string; +}; + +export type ClientDirective = ( + load: DirectiveLoad, + options: DirectiveOptions, + el: HTMLElement, +) => void; + +export interface ClientDirectiveConfig { + name: string; + entrypoint: string; +} + +export interface AstroRenderer { + /** Name of the renderer. */ + name: string; + /** Import entrypoint for the client/browser renderer. */ + clientEntrypoint?: string; + /** Import entrypoint for the server/build/ssr renderer. */ + serverEntrypoint: string; +} + +export type AdapterSupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated'; + +export interface AstroAdapterFeatures { + /** + * Creates an edge function that will communiate with the Astro middleware + */ + edgeMiddleware: boolean; +} + +export interface AstroAdapter { + name: string; + serverEntrypoint?: string; + previewEntrypoint?: string; + exports?: string[]; + args?: any; + adapterFeatures?: AstroAdapterFeatures; + /** + * List of features supported by an adapter. + * + * If the adapter is not able to handle certain configurations, Astro will throw an error. + */ + supportedAstroFeatures: AstroAdapterFeatureMap; +} + +export type AstroAdapterFeatureMap = { + /** + * The adapter is able serve static pages + */ + staticOutput?: AdapterSupportsKind; + /** + * The adapter is able to serve pages that are static or rendered via server + */ + hybridOutput?: AdapterSupportsKind; + /** + * The adapter is able to serve SSR pages + */ + serverOutput?: AdapterSupportsKind; + /** + * The adapter can emit static assets + */ + assets?: AstroAssetsFeature; + + /** + * List of features that orbit around the i18n routing + */ + i18nDomains?: AdapterSupportsKind; + + /** + * The adapter is able to support `getSecret` exported from `astro:env/server` + */ + envGetSecret?: AdapterSupportsKind; +}; + +export interface AstroAssetsFeature { + supportKind?: AdapterSupportsKind; + /** + * Whether if this adapter deploys files in an environment that is compatible with the library `sharp` + */ + isSharpCompatible?: boolean; + /** + * Whether if this adapter deploys files in an environment that is compatible with the library `squoosh` + */ + isSquooshCompatible?: boolean; +} + +export interface AstroInternationalizationFeature { + /** + * The adapter should be able to create the proper redirects + */ + domains?: AdapterSupportsKind; +} + +/** + * IDs for different stages of JS script injection: + * - "before-hydration": Imported client-side, before the hydration script runs. Processed & resolved by Vite. + * - "head-inline": Injected into a script tag in the `<head>` of every page. Not processed or resolved by Vite. + * - "page": Injected into the JavaScript bundle of every page. Processed & resolved by Vite. + * - "page-ssr": Injected into the frontmatter of every Astro page. Processed & resolved by Vite. + */ +export type InjectedScriptStage = 'before-hydration' | 'head-inline' | 'page' | 'page-ssr'; + +/** + * IDs for different priorities of injected routes and redirects: + * - "normal": Merge with discovered file-based project routes, behaving the same as if the route + * was defined as a file in the project. + * - "legacy": Use the old ordering of routes. Inject routes will override any file-based project route, + * and redirects will be overridden by any project route on conflict. + */ +export type RoutePriorityOverride = 'normal' | 'legacy'; + +export interface InjectedRoute { + pattern: string; + entrypoint: string; + prerender?: boolean; +} + +export interface ResolvedInjectedRoute extends InjectedRoute { + resolvedEntryPoint?: URL; +} + +export interface InjectedType { + filename: string; + content: string; +} + +export type AstroIntegrationMiddleware = { + order: 'pre' | 'post'; + entrypoint: string; +}; + +export type HookParameters< + Hook extends keyof AstroIntegration['hooks'], + Fn = AstroIntegration['hooks'][Hook], +> = Fn extends (...args: any) => any ? Parameters<Fn>[0] : never; + +export interface BaseIntegrationHooks { + 'astro:config:setup': (options: { + config: AstroConfig; + command: 'dev' | 'build' | 'preview'; + isRestart: boolean; + updateConfig: (newConfig: DeepPartial<AstroConfig>) => AstroConfig; + addRenderer: (renderer: AstroRenderer) => void; + addWatchFile: (path: URL | string) => void; + injectScript: (stage: InjectedScriptStage, content: string) => void; + injectRoute: (injectRoute: InjectedRoute) => void; + addClientDirective: (directive: ClientDirectiveConfig) => void; + // TODO: Deprecate the `string` overload once a few apps have been migrated to the new API. + addDevToolbarApp: (entrypoint: DevToolbarAppEntry | string) => void; + addMiddleware: (mid: AstroIntegrationMiddleware) => void; + logger: AstroIntegrationLogger; + }) => void | Promise<void>; + 'astro:config:done': (options: { + config: AstroConfig; + setAdapter: (adapter: AstroAdapter) => void; + injectTypes: (injectedType: InjectedType) => URL; + logger: AstroIntegrationLogger; + }) => void | Promise<void>; + 'astro:server:setup': (options: { + server: ViteDevServer; + logger: AstroIntegrationLogger; + toolbar: ReturnType<typeof getToolbarServerCommunicationHelpers>; + }) => void | Promise<void>; + 'astro:server:start': (options: { + address: AddressInfo; + logger: AstroIntegrationLogger; + }) => void | Promise<void>; + 'astro:server:done': (options: { logger: AstroIntegrationLogger }) => void | Promise<void>; + 'astro:build:ssr': (options: { + manifest: SerializedSSRManifest; + /** + * This maps a {@link RouteData} to an {@link URL}, this URL represents + * the physical file you should import. + */ + entryPoints: Map<RouteData, URL>; + /** + * File path of the emitted middleware + */ + middlewareEntryPoint: URL | undefined; + logger: AstroIntegrationLogger; + }) => void | Promise<void>; + 'astro:build:start': (options: { logger: AstroIntegrationLogger }) => void | Promise<void>; + 'astro:build:setup': (options: { + vite: ViteInlineConfig; + pages: Map<string, PageBuildData>; + target: 'client' | 'server'; + updateConfig: (newConfig: ViteInlineConfig) => void; + logger: AstroIntegrationLogger; + }) => void | Promise<void>; + 'astro:build:generated': (options: { + dir: URL; + logger: AstroIntegrationLogger; + }) => void | Promise<void>; + 'astro:build:done': (options: { + pages: { pathname: string }[]; + dir: URL; + routes: RouteData[]; + logger: AstroIntegrationLogger; + cacheManifest: boolean; + }) => void | Promise<void>; + 'astro:route:setup': (options: { + route: RouteOptions; + logger: AstroIntegrationLogger; + }) => void | Promise<void>; +} + +export interface AstroIntegration { + /** The name of the integration. */ + name: string; + /** The different hooks available to extend. */ + hooks: { + [K in keyof Astro.IntegrationHooks]?: Astro.IntegrationHooks[K]; + } & Partial<Record<string, unknown>>; +} diff --git a/packages/astro/src/types/public/internal.ts b/packages/astro/src/types/public/internal.ts new file mode 100644 index 000000000..bee15c6f7 --- /dev/null +++ b/packages/astro/src/types/public/internal.ts @@ -0,0 +1,202 @@ +// TODO: Should the types here really be public? + +import type { ErrorPayload as ViteErrorPayload } from 'vite'; +import type { AstroCookies } from '../../core/cookies/cookies.js'; +import type { AstroComponentInstance } from '../../runtime/server/index.js'; +import type { Params } from './common.js'; +import type { AstroConfig, RedirectConfig } from './config.js'; +import type { AstroGlobal, AstroGlobalPartial } from './context.js'; +import type { AstroRenderer } from './integrations.js'; + +export type { SSRManifest } from '../../core/app/types.js'; + +export interface NamedSSRLoadedRendererValue extends SSRLoadedRendererValue { + name: string; +} + +export interface SSRLoadedRendererValue { + name?: string; + check: AsyncRendererComponentFn<boolean>; + renderToStaticMarkup: AsyncRendererComponentFn<{ + html: string; + attrs?: Record<string, string>; + }>; + supportsAstroStaticSlot?: boolean; + /** + * If provided, Astro will call this function and inject the returned + * script in the HTML before the first component handled by this renderer. + * + * This feature is needed by some renderers (in particular, by Solid). The + * Solid official hydration script sets up a page-level data structure. + * It is mainly used to transfer data between the server side render phase + * and the browser application state. Solid Components rendered later in + * the HTML may inject tiny scripts into the HTML that call into this + * page-level data structure. + */ + renderHydrationScript?: () => string; +} + +export interface RouteData { + route: string; + component: string; + generate: (data?: any) => string; + params: string[]; + pathname?: string; + // expose the real path name on SSG + distURL?: URL; + pattern: RegExp; + segments: RoutePart[][]; + type: RouteType; + prerender: boolean; + redirect?: RedirectConfig; + redirectRoute?: RouteData; + fallbackRoutes: RouteData[]; + isIndex: boolean; +} + +/** + * - page: a route that lives in the file system, usually an Astro component + * - endpoint: a route that lives in the file system, usually a JS file that exposes endpoints methods + * - redirect: a route points to another route that lives in the file system + * - fallback: a route that doesn't exist in the file system that needs to be handled with other means, usually the middleware + */ +export type RouteType = 'page' | 'endpoint' | 'redirect' | 'fallback'; + +export interface RoutePart { + content: string; + dynamic: boolean; + spread: boolean; +} + +export interface AstroComponentMetadata { + displayName: string; + hydrate?: 'load' | 'idle' | 'visible' | 'media' | 'only'; + hydrateArgs?: any; + componentUrl?: string; + componentExport?: { value: string; namespace?: boolean }; + astroStaticSlot: true; +} + +export type AsyncRendererComponentFn<U> = ( + Component: any, + props: any, + slots: Record<string, string>, + metadata?: AstroComponentMetadata, +) => Promise<U>; + +export interface NamedSSRLoadedRendererValue extends SSRLoadedRendererValue { + name: string; +} + +export interface SSRLoadedRendererValue { + name?: string; + check: AsyncRendererComponentFn<boolean>; + renderToStaticMarkup: AsyncRendererComponentFn<{ + html: string; + attrs?: Record<string, string>; + }>; + supportsAstroStaticSlot?: boolean; + /** + * If provided, Astro will call this function and inject the returned + * script in the HTML before the first component handled by this renderer. + * + * This feature is needed by some renderers (in particular, by Solid). The + * Solid official hydration script sets up a page-level data structure. + * It is mainly used to transfer data between the server side render phase + * and the browser application state. Solid Components rendered later in + * the HTML may inject tiny scripts into the HTML that call into this + * page-level data structure. + */ + renderHydrationScript?: () => string; +} + +export interface SSRLoadedRenderer extends Pick<AstroRenderer, 'name' | 'clientEntrypoint'> { + ssr: SSRLoadedRendererValue; +} + +export interface SSRElement { + props: Record<string, any>; + children: string; +} + +export interface SSRResult { + /** + * Whether the page has failed with a non-recoverable error, or the client disconnected. + */ + cancelled: boolean; + base: string; + styles: Set<SSRElement>; + scripts: Set<SSRElement>; + links: Set<SSRElement>; + componentMetadata: Map<string, SSRComponentMetadata>; + inlinedScripts: Map<string, string>; + createAstro( + Astro: AstroGlobalPartial, + props: Record<string, any>, + slots: Record<string, any> | null, + ): AstroGlobal; + params: Params; + resolve: (s: string) => Promise<string>; + response: AstroGlobal['response']; + request: AstroGlobal['request']; + actionResult?: ReturnType<AstroGlobal['getActionResult']>; + renderers: SSRLoadedRenderer[]; + /** + * Map of directive name (e.g. `load`) to the directive script code + */ + clientDirectives: Map<string, string>; + compressHTML: boolean; + partial: boolean; + /** + * Only used for logging + */ + pathname: string; + cookies: AstroCookies | undefined; + serverIslandNameMap: Map<string, string>; + trailingSlash: AstroConfig['trailingSlash']; + key: Promise<CryptoKey>; + _metadata: SSRMetadata; +} + +/** + * A hint on whether the Astro runtime needs to wait on a component to render head + * content. The meanings: + * + * - __none__ (default) The component does not propagation head content. + * - __self__ The component appends head content. + * - __in-tree__ Another component within this component's dependency tree appends head content. + * + * These are used within the runtime to know whether or not a component should be waited on. + */ +export type PropagationHint = 'none' | 'self' | 'in-tree'; + +export type SSRComponentMetadata = { + propagation: PropagationHint; + containsHead: boolean; +}; + +/** + * Ephemeral and mutable state during rendering that doesn't rely + * on external configuration + */ +export interface SSRMetadata { + hasHydrationScript: boolean; + /** + * Names of renderers that have injected their hydration scripts + * into the current page. For example, Solid SSR needs a hydration + * script in the page HTML before the first Solid component. + */ + rendererSpecificHydrationScripts: Set<string>; + /** + * Used by `renderScript` to track script ids that have been rendered, + * so we only render each once. + */ + renderedScripts: Set<string>; + hasDirectives: Set<string>; + hasRenderedHead: boolean; + headInTree: boolean; + extraHead: string[]; + propagators: Set<AstroComponentInstance>; +} + +export type SSRError = Error & ViteErrorPayload['err']; diff --git a/packages/astro/src/types/public/preview.ts b/packages/astro/src/types/public/preview.ts new file mode 100644 index 000000000..e2794303f --- /dev/null +++ b/packages/astro/src/types/public/preview.ts @@ -0,0 +1,28 @@ +import type { OutgoingHttpHeaders } from 'node:http'; +import type { AstroIntegrationLogger } from '../../core/logger/core.js'; + +export interface PreviewServer { + host?: string; + port: number; + closed(): Promise<void>; + stop(): Promise<void>; +} + +export interface PreviewServerParams { + outDir: URL; + client: URL; + serverEntrypoint: URL; + host: string | undefined; + port: number; + base: string; + logger: AstroIntegrationLogger; + headers?: OutgoingHttpHeaders; +} + +export type CreatePreviewServer = ( + params: PreviewServerParams, +) => PreviewServer | Promise<PreviewServer>; + +export interface PreviewModule { + default: CreatePreviewServer; +} diff --git a/packages/astro/src/types/public/toolbar.ts b/packages/astro/src/types/public/toolbar.ts new file mode 100644 index 000000000..7beaab3bb --- /dev/null +++ b/packages/astro/src/types/public/toolbar.ts @@ -0,0 +1,96 @@ +import type { + ToolbarAppEventTarget, + ToolbarServerHelpers, +} from '../../runtime/client/dev-toolbar/helpers.js'; +import type { + AstroDevToolbar, + DevToolbarCanvas, +} from '../../runtime/client/dev-toolbar/toolbar.js'; +import type { Icon } from '../../runtime/client/dev-toolbar/ui-library/icons.js'; +import type { + DevToolbarBadge, + DevToolbarButton, + DevToolbarCard, + DevToolbarHighlight, + DevToolbarIcon, + DevToolbarRadioCheckbox, + DevToolbarSelect, + DevToolbarToggle, + DevToolbarTooltip, + DevToolbarWindow, +} from '../../runtime/client/dev-toolbar/ui-library/index.js'; + +declare global { + interface HTMLElementTagNameMap { + 'astro-dev-toolbar': AstroDevToolbar; + 'astro-dev-toolbar-window': DevToolbarWindow; + 'astro-dev-toolbar-app-canvas': DevToolbarCanvas; + 'astro-dev-toolbar-tooltip': DevToolbarTooltip; + 'astro-dev-toolbar-highlight': DevToolbarHighlight; + 'astro-dev-toolbar-toggle': DevToolbarToggle; + 'astro-dev-toolbar-badge': DevToolbarBadge; + 'astro-dev-toolbar-button': DevToolbarButton; + 'astro-dev-toolbar-icon': DevToolbarIcon; + 'astro-dev-toolbar-card': DevToolbarCard; + 'astro-dev-toolbar-select': DevToolbarSelect; + 'astro-dev-toolbar-radio-checkbox': DevToolbarRadioCheckbox; + } +} + +type DevToolbarAppMeta = { + id: string; + name: string; + icon?: Icon; +}; + +// The param passed to `addDevToolbarApp` in the integration +export type DevToolbarAppEntry = DevToolbarAppMeta & { + entrypoint: string; +}; + +// Public API for the dev toolbar +export type DevToolbarApp = { + /** + * @deprecated The `id`, `name`, and `icon` properties should now be defined when using `addDevToolbarApp`. + * + * Ex: `addDevToolbarApp({ id: 'my-app', name: 'My App', icon: '🚀', entrypoint: '/path/to/app' })` + * + * In the future, putting these properties directly on the app object will be removed. + */ + id?: string; + /** + * @deprecated The `id`, `name`, and `icon` properties should now be defined when using `addDevToolbarApp`. + * + * Ex: `addDevToolbarApp({ id: 'my-app', name: 'My App', icon: '🚀', entrypoint: '/path/to/app' })` + * + * In the future, putting these properties directly on the app object will be removed. + */ + name?: string; + /** + * @deprecated The `id`, `name`, and `icon` properties should now be defined when using `addDevToolbarApp`. + * + * Ex: `addDevToolbarApp({ id: 'my-app', name: 'My App', icon: '🚀', entrypoint: '/path/to/app' })` + * + * In the future, putting these properties directly on the app object will be removed. + */ + icon?: Icon; + init?( + canvas: ShadowRoot, + app: ToolbarAppEventTarget, + server: ToolbarServerHelpers, + ): void | Promise<void>; + beforeTogglingOff?(canvas: ShadowRoot): boolean | Promise<boolean>; +}; + +// An app that has been loaded and as such contain all of its properties +export type ResolvedDevToolbarApp = DevToolbarAppMeta & Omit<DevToolbarApp, 'id' | 'name' | 'icon'>; + +export type DevToolbarMetadata = Window & + typeof globalThis & { + __astro_dev_toolbar__: { + root: string; + version: string; + latestAstroVersion: string | undefined; + debugInfo: string; + }; + }; diff --git a/packages/astro/src/types/public/view-transitions.ts b/packages/astro/src/types/public/view-transitions.ts new file mode 100644 index 000000000..1acd5003b --- /dev/null +++ b/packages/astro/src/types/public/view-transitions.ts @@ -0,0 +1,40 @@ +import type { + TransitionBeforePreparationEvent, + TransitionBeforeSwapEvent, +} from '../../transitions/events.js'; + +export interface TransitionAnimation { + name: string; // The name of the keyframe + delay?: number | string; + duration?: number | string; + easing?: string; + fillMode?: string; + direction?: string; +} + +export interface TransitionAnimationPair { + old: TransitionAnimation | TransitionAnimation[]; + new: TransitionAnimation | TransitionAnimation[]; +} + +export interface TransitionDirectionalAnimations { + forwards: TransitionAnimationPair; + backwards: TransitionAnimationPair; +} + +export type TransitionAnimationValue = + | 'initial' + | 'slide' + | 'fade' + | 'none' + | TransitionDirectionalAnimations; + +declare global { + interface DocumentEventMap { + 'astro:before-preparation': TransitionBeforePreparationEvent; + 'astro:after-preparation': Event; + 'astro:before-swap': TransitionBeforeSwapEvent; + 'astro:after-swap': Event; + 'astro:page-load': Event; + } +} diff --git a/packages/astro/src/@types/typed-emitter.ts b/packages/astro/src/types/typed-emitter.ts index 43139bd4e..43139bd4e 100644 --- a/packages/astro/src/@types/typed-emitter.ts +++ b/packages/astro/src/types/typed-emitter.ts diff --git a/packages/astro/src/virtual-modules/container.ts b/packages/astro/src/virtual-modules/container.ts index 420b3e3e2..3efc626d9 100644 --- a/packages/astro/src/virtual-modules/container.ts +++ b/packages/astro/src/virtual-modules/container.ts @@ -1,4 +1,5 @@ -import type { AstroRenderer, SSRLoadedRenderer } from '../@types/astro.js'; +import type { AstroRenderer } from '../types/public/integrations.js'; +import type { SSRLoadedRenderer } from '../types/public/internal.js'; /** * Use this function to provide renderers to the `AstroContainer`: diff --git a/packages/astro/src/virtual-modules/i18n.ts b/packages/astro/src/virtual-modules/i18n.ts index aacdd80a9..927d479aa 100644 --- a/packages/astro/src/virtual-modules/i18n.ts +++ b/packages/astro/src/virtual-modules/i18n.ts @@ -1,9 +1,3 @@ -import type { - APIContext, - AstroConfig, - MiddlewareHandler, - ValidRedirectStatus, -} from '../@types/astro.js'; import type { SSRManifest } from '../core/app/types.js'; import { IncorrectStrategyForI18n } from '../core/errors/errors-data.js'; import { AstroError } from '../core/errors/index.js'; @@ -11,6 +5,9 @@ import * as I18nInternals from '../i18n/index.js'; import type { RedirectToFallback } from '../i18n/index.js'; import { toRoutingStrategy } from '../i18n/utils.js'; import type { I18nInternalConfig } from '../i18n/vite-plugin-i18n.js'; +import type { MiddlewareHandler } from '../types/public/common.js'; +import type { AstroConfig, ValidRedirectStatus } from '../types/public/config.js'; +import type { APIContext } from '../types/public/context.js'; export { normalizeTheLocale, toCodes, toPaths } from '../i18n/index.js'; diff --git a/packages/astro/src/vite-plugin-astro-server/base.ts b/packages/astro/src/vite-plugin-astro-server/base.ts index bea642f6f..562b89ba2 100644 --- a/packages/astro/src/vite-plugin-astro-server/base.ts +++ b/packages/astro/src/vite-plugin-astro-server/base.ts @@ -1,5 +1,5 @@ import type * as vite from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; import * as fs from 'node:fs'; import path from 'node:path'; diff --git a/packages/astro/src/vite-plugin-astro-server/error.ts b/packages/astro/src/vite-plugin-astro-server/error.ts index 24db9dc49..25a237cc2 100644 --- a/packages/astro/src/vite-plugin-astro-server/error.ts +++ b/packages/astro/src/vite-plugin-astro-server/error.ts @@ -1,10 +1,10 @@ -import type { AstroConfig } from '../@types/astro.js'; import type { ModuleLoader } from '../core/module-loader/index.js'; import type { DevPipeline } from './pipeline.js'; import { collectErrorMetadata } from '../core/errors/dev/index.js'; import { createSafeError } from '../core/errors/index.js'; import { formatErrorMessage } from '../core/messages.js'; +import type { AstroConfig } from '../types/public/config.js'; export function recordServerError( loader: ModuleLoader, diff --git a/packages/astro/src/vite-plugin-astro-server/metadata.ts b/packages/astro/src/vite-plugin-astro-server/metadata.ts index 793ee5669..7f358ade0 100644 --- a/packages/astro/src/vite-plugin-astro-server/metadata.ts +++ b/packages/astro/src/vite-plugin-astro-server/metadata.ts @@ -1,6 +1,6 @@ -import type { SSRComponentMetadata, SSRResult } from '../@types/astro.js'; import type { ModuleInfo, ModuleLoader } from '../core/module-loader/index.js'; import { viteID } from '../core/util.js'; +import type { SSRComponentMetadata, SSRResult } from '../types/public/internal.js'; import { getAstroMetadata } from '../vite-plugin-astro/index.js'; import { crawlGraph } from './vite.js'; diff --git a/packages/astro/src/vite-plugin-astro-server/pipeline.ts b/packages/astro/src/vite-plugin-astro-server/pipeline.ts index 4386eb154..5a672279e 100644 --- a/packages/astro/src/vite-plugin-astro-server/pipeline.ts +++ b/packages/astro/src/vite-plugin-astro-server/pipeline.ts @@ -1,15 +1,4 @@ import { fileURLToPath } from 'node:url'; -import type { - AstroSettings, - ComponentInstance, - DevToolbarMetadata, - ManifestData, - RewritePayload, - RouteData, - SSRElement, - SSRLoadedRenderer, - SSRManifest, -} from '../@types/astro.js'; import { getInfoOutput } from '../cli/info/index.js'; import { type HeadElements } from '../core/base-pipeline.js'; import { ASTRO_VERSION } from '../core/constants.js'; @@ -22,6 +11,15 @@ import { createDefaultRoutes } from '../core/routing/default.js'; import { findRouteToRewrite } from '../core/routing/rewrite.js'; import { isPage, isServerLikeOutput, viteID } from '../core/util.js'; import { resolveIdToUrl } from '../core/viteUtils.js'; +import type { AstroSettings, ComponentInstance, ManifestData } from '../types/astro.js'; +import type { RewritePayload } from '../types/public/common.js'; +import type { + RouteData, + SSRElement, + SSRLoadedRenderer, + SSRManifest, +} from '../types/public/internal.js'; +import type { DevToolbarMetadata } from '../types/public/toolbar.js'; import { PAGE_SCRIPT_ID } from '../vite-plugin-scripts/index.js'; import { getStylesForURL } from './css.js'; import { getComponentMetadata } from './metadata.js'; diff --git a/packages/astro/src/vite-plugin-astro-server/plugin.ts b/packages/astro/src/vite-plugin-astro-server/plugin.ts index 2458b5b8d..3015f1003 100644 --- a/packages/astro/src/vite-plugin-astro-server/plugin.ts +++ b/packages/astro/src/vite-plugin-astro-server/plugin.ts @@ -2,8 +2,7 @@ import { AsyncLocalStorage } from 'node:async_hooks'; import type fs from 'node:fs'; import { IncomingMessage } from 'node:http'; import type * as vite from 'vite'; -import type { AstroSettings, ManifestData, SSRManifest } from '../@types/astro.js'; -import type { SSRManifestI18n } from '../core/app/types.js'; +import type { SSRManifest, SSRManifestI18n } from '../core/app/types.js'; import { createKey } from '../core/encryption.js'; import { getViteErrorPayload } from '../core/errors/dev/index.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; @@ -13,6 +12,7 @@ import { createViteLoader } from '../core/module-loader/index.js'; import { injectDefaultRoutes } from '../core/routing/default.js'; import { createRouteManifest } from '../core/routing/index.js'; import { toRoutingStrategy } from '../i18n/utils.js'; +import type { AstroSettings, ManifestData } from '../types/astro.js'; import { baseMiddleware } from './base.js'; import { createController } from './controller.js'; import { recordServerError } from './error.js'; diff --git a/packages/astro/src/vite-plugin-astro-server/request.ts b/packages/astro/src/vite-plugin-astro-server/request.ts index b231bfde3..98cf2b502 100644 --- a/packages/astro/src/vite-plugin-astro-server/request.ts +++ b/packages/astro/src/vite-plugin-astro-server/request.ts @@ -1,6 +1,6 @@ import type http from 'node:http'; -import type { ManifestData } from '../@types/astro.js'; import { removeTrailingForwardSlash } from '../core/path.js'; +import type { ManifestData } from '../types/astro.js'; import type { DevServerController } from './controller.js'; import { runWithErrorHandling } from './controller.js'; import { recordServerError } from './error.js'; diff --git a/packages/astro/src/vite-plugin-astro-server/route.ts b/packages/astro/src/vite-plugin-astro-server/route.ts index aa70d5324..c59af5c80 100644 --- a/packages/astro/src/vite-plugin-astro-server/route.ts +++ b/packages/astro/src/vite-plugin-astro-server/route.ts @@ -1,5 +1,4 @@ import type http from 'node:http'; -import type { ComponentInstance, ManifestData, RouteData } from '../@types/astro.js'; import { REROUTE_DIRECTIVE_HEADER, REWRITE_DIRECTIVE_HEADER_KEY, @@ -13,6 +12,8 @@ import { type SSROptions, getProps } from '../core/render/index.js'; import { createRequest } from '../core/request.js'; import { matchAllRoutes } from '../core/routing/index.js'; import { getSortedPreloadedMatches } from '../prerender/routing.js'; +import type { ComponentInstance, ManifestData } from '../types/astro.js'; +import type { RouteData } from '../types/public/internal.js'; import type { DevPipeline } from './pipeline.js'; import { writeSSRResult, writeWebResponse } from './response.js'; diff --git a/packages/astro/src/vite-plugin-astro-server/scripts.ts b/packages/astro/src/vite-plugin-astro-server/scripts.ts index e21d44116..95763ab34 100644 --- a/packages/astro/src/vite-plugin-astro-server/scripts.ts +++ b/packages/astro/src/vite-plugin-astro-server/scripts.ts @@ -1,8 +1,8 @@ -import type { SSRElement } from '../@types/astro.js'; import type { ModuleInfo, ModuleLoader } from '../core/module-loader/index.js'; import { createModuleScriptElementWithSrc } from '../core/render/ssr-element.js'; import { viteID } from '../core/util.js'; import { rootRelativePath } from '../core/viteUtils.js'; +import type { SSRElement } from '../types/public/internal.js'; import type { PluginMetadata as AstroPluginMetadata } from '../vite-plugin-astro/types.js'; import { crawlGraph } from './vite.js'; diff --git a/packages/astro/src/vite-plugin-astro/compile.ts b/packages/astro/src/vite-plugin-astro/compile.ts index 8dfb68a16..78d6c416f 100644 --- a/packages/astro/src/vite-plugin-astro/compile.ts +++ b/packages/astro/src/vite-plugin-astro/compile.ts @@ -1,7 +1,7 @@ import { type ESBuildTransformResult, transformWithEsbuild } from 'vite'; -import type { AstroConfig } from '../@types/astro.js'; import { type CompileProps, type CompileResult, compile } from '../core/compile/index.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroConfig } from '../types/public/config.js'; import { getFileInfo } from '../vite-plugin-utils/index.js'; import type { CompileMetadata } from './types.js'; import { frontmatterRE } from './utils.js'; diff --git a/packages/astro/src/vite-plugin-astro/index.ts b/packages/astro/src/vite-plugin-astro/index.ts index d5968a905..b7dd0a2b6 100644 --- a/packages/astro/src/vite-plugin-astro/index.ts +++ b/packages/astro/src/vite-plugin-astro/index.ts @@ -1,7 +1,7 @@ import type { SourceDescription } from 'rollup'; import type * as vite from 'vite'; -import type { AstroConfig, AstroSettings } from '../@types/astro.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; import type { PluginCssMetadata as AstroPluginCssMetadata, PluginMetadata as AstroPluginMetadata, @@ -9,6 +9,7 @@ import type { } from './types.js'; import { normalizePath } from 'vite'; +import type { AstroConfig } from '../types/public/config.js'; import { hasSpecialQueries, normalizeFilename } from '../vite-plugin-utils/index.js'; import { type CompileAstroResult, compileAstro } from './compile.js'; import { handleHotUpdate } from './hmr.js'; diff --git a/packages/astro/src/vite-plugin-astro/types.ts b/packages/astro/src/vite-plugin-astro/types.ts index ee5003941..195745443 100644 --- a/packages/astro/src/vite-plugin-astro/types.ts +++ b/packages/astro/src/vite-plugin-astro/types.ts @@ -1,6 +1,6 @@ import type { HoistedScript, TransformResult } from '@astrojs/compiler'; -import type { PropagationHint } from '../@types/astro.js'; import type { CompileCssResult } from '../core/compile/types.js'; +import type { PropagationHint } from '../types/public/internal.js'; export interface PageOptions { prerender?: boolean; diff --git a/packages/astro/src/vite-plugin-config-alias/index.ts b/packages/astro/src/vite-plugin-config-alias/index.ts index cb9bdc48c..9b102c564 100644 --- a/packages/astro/src/vite-plugin-config-alias/index.ts +++ b/packages/astro/src/vite-plugin-config-alias/index.ts @@ -1,7 +1,7 @@ import path from 'node:path'; import type { CompilerOptions } from 'typescript'; import { type ResolvedConfig, type Plugin as VitePlugin, normalizePath } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; type Alias = { find: RegExp; diff --git a/packages/astro/src/vite-plugin-env/index.ts b/packages/astro/src/vite-plugin-env/index.ts index 79bdad4cf..0408e645d 100644 --- a/packages/astro/src/vite-plugin-env/index.ts +++ b/packages/astro/src/vite-plugin-env/index.ts @@ -4,8 +4,9 @@ import { bold } from 'kleur/colors'; import MagicString from 'magic-string'; import type * as vite from 'vite'; import { loadEnv } from 'vite'; -import type { AstroConfig, AstroSettings } from '../@types/astro.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { AstroConfig } from '../types/public/config.js'; interface EnvPluginOptions { settings: AstroSettings; diff --git a/packages/astro/src/vite-plugin-head/index.ts b/packages/astro/src/vite-plugin-head/index.ts index a7e35dedb..c9ec2460d 100644 --- a/packages/astro/src/vite-plugin-head/index.ts +++ b/packages/astro/src/vite-plugin-head/index.ts @@ -1,11 +1,11 @@ import type { ModuleInfo } from 'rollup'; import type * as vite from 'vite'; -import type { SSRComponentMetadata, SSRResult } from '../@types/astro.js'; import type { AstroBuildPlugin } from '../core/build/plugin.js'; import type { PluginMetadata } from '../vite-plugin-astro/types.js'; import { getParentModuleInfos, getTopLevelPageModuleInfos } from '../core/build/graph.js'; import type { BuildInternals } from '../core/build/internal.js'; +import type { SSRComponentMetadata, SSRResult } from '../types/public/internal.js'; import { getAstroMetadata } from '../vite-plugin-astro/index.js'; // Detect this in comments, both in .astro components and in js/ts files. diff --git a/packages/astro/src/vite-plugin-integrations-container/index.ts b/packages/astro/src/vite-plugin-integrations-container/index.ts index 49122b24f..22623284e 100644 --- a/packages/astro/src/vite-plugin-integrations-container/index.ts +++ b/packages/astro/src/vite-plugin-integrations-container/index.ts @@ -1,10 +1,11 @@ import type { PluginContext } from 'rollup'; import type { Plugin as VitePlugin } from 'vite'; -import type { AstroSettings, InjectedRoute, ResolvedInjectedRoute } from '../@types/astro.js'; import type { Logger } from '../core/logger/core.js'; +import type { AstroSettings } from '../types/astro.js'; import { normalizePath } from 'vite'; import { runHookServerSetup } from '../integrations/hooks.js'; +import type { InjectedRoute, ResolvedInjectedRoute } from '../types/public/integrations.js'; /** Connect Astro integrations into Vite, as needed. */ export default function astroIntegrationsContainerPlugin({ diff --git a/packages/astro/src/vite-plugin-markdown/content-entry-type.ts b/packages/astro/src/vite-plugin-markdown/content-entry-type.ts index 9b78d8f35..48a45294e 100644 --- a/packages/astro/src/vite-plugin-markdown/content-entry-type.ts +++ b/packages/astro/src/vite-plugin-markdown/content-entry-type.ts @@ -1,7 +1,7 @@ import { fileURLToPath, pathToFileURL } from 'node:url'; import { createMarkdownProcessor } from '@astrojs/markdown-remark'; -import type { ContentEntryType } from '../@types/astro.js'; import { safeParseFrontmatter } from '../content/utils.js'; +import type { ContentEntryType } from '../types/public/content.js'; export const markdownContentEntryType: ContentEntryType = { extensions: ['.md'], @@ -17,8 +17,8 @@ export const markdownContentEntryType: ContentEntryType = { // We need to handle propagation for Markdown because they support layouts which will bring in styles. handlePropagation: true, - async getRenderFunction(settings) { - const processor = await createMarkdownProcessor(settings.config.markdown); + async getRenderFunction(config) { + const processor = await createMarkdownProcessor(config.markdown); return async function renderToString(entry) { if (!entry.body) { return { diff --git a/packages/astro/src/vite-plugin-markdown/index.ts b/packages/astro/src/vite-plugin-markdown/index.ts index 37af2dc50..694b96448 100644 --- a/packages/astro/src/vite-plugin-markdown/index.ts +++ b/packages/astro/src/vite-plugin-markdown/index.ts @@ -7,12 +7,12 @@ import { } from '@astrojs/markdown-remark'; import type { Plugin } from 'vite'; import { normalizePath } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; import { safeParseFrontmatter } from '../content/utils.js'; import { AstroError, AstroErrorData } from '../core/errors/index.js'; import type { Logger } from '../core/logger/core.js'; import { isMarkdownFile } from '../core/util.js'; import { shorthash } from '../runtime/server/shorthash.js'; +import type { AstroSettings } from '../types/astro.js'; import { createDefaultAstroMetadata } from '../vite-plugin-astro/metadata.js'; import { getFileInfo } from '../vite-plugin-utils/index.js'; import { type MarkdownImagePath, getMarkdownCodeForImages } from './images.js'; diff --git a/packages/astro/src/vite-plugin-mdx/README.md b/packages/astro/src/vite-plugin-mdx/README.md deleted file mode 100644 index fc962ad4e..000000000 --- a/packages/astro/src/vite-plugin-mdx/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# vite-plugin-mdx - -Handles transforming MDX via the `astro:jsx` renderer. diff --git a/packages/astro/src/vite-plugin-mdx/index.ts b/packages/astro/src/vite-plugin-mdx/index.ts deleted file mode 100644 index 1c85d9226..000000000 --- a/packages/astro/src/vite-plugin-mdx/index.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { type Plugin, transformWithEsbuild } from 'vite'; -import { CONTENT_FLAG, PROPAGATED_ASSET_FLAG } from '../content/index.js'; -import { astroEntryPrefix } from '../core/build/plugins/plugin-component-entry.js'; -import { removeQueryString } from '../core/path.js'; -import { transformJSX } from './transform-jsx.js'; - -// Format inspired by https://github.com/vitejs/vite/blob/main/packages/vite/src/node/constants.ts#L54 -const SPECIAL_QUERY_REGEX = new RegExp( - `[?&](?:worker|sharedworker|raw|url|${CONTENT_FLAG}|${PROPAGATED_ASSET_FLAG})\\b`, -); - -/** - * @deprecated This plugin is no longer used. Remove in Astro 5.0 - */ -export default function mdxVitePlugin(): Plugin { - return { - name: 'astro:jsx', - enforce: 'pre', // run transforms before other plugins - async transform(code, id, opts) { - // Skip special queries and astro entries. We skip astro entries here as we know it doesn't contain - // JSX code, and also because we can't detect the import source to apply JSX transforms. - if (SPECIAL_QUERY_REGEX.test(id) || id.startsWith(astroEntryPrefix)) { - return null; - } - id = removeQueryString(id); - // Shortcut: only use Astro renderer for MD and MDX files - if (!id.endsWith('.mdx')) { - return null; - } - const { code: jsxCode } = await transformWithEsbuild(code, id, { - loader: 'jsx', - jsx: 'preserve', - sourcemap: 'inline', - tsconfigRaw: { - compilerOptions: { - // Ensure client:only imports are treeshaken - verbatimModuleSyntax: false, - importsNotUsedAsValues: 'remove', - }, - }, - }); - return await transformJSX(jsxCode, id, opts?.ssr); - }, - }; -} diff --git a/packages/astro/src/vite-plugin-mdx/tag.ts b/packages/astro/src/vite-plugin-mdx/tag.ts deleted file mode 100644 index a65f99806..000000000 --- a/packages/astro/src/vite-plugin-mdx/tag.ts +++ /dev/null @@ -1,113 +0,0 @@ -import type { PluginObj } from '@babel/core'; -import * as t from '@babel/types'; -import astroJsxRenderer from '../jsx/renderer.js'; - -const rendererName = astroJsxRenderer.name; - -/** - * This plugin handles every file that runs through our JSX plugin. - * Since we statically match every JSX file to an Astro renderer based on import scanning, - * it would be helpful to embed some of that metadata at runtime. - * - * This plugin crawls each export in the file and "tags" each export with a given `rendererName`. - * This allows us to automatically match a component to a renderer and skip the usual `check()` calls. - * - * @deprecated This plugin is no longer used. Remove in Astro 5.0 - */ -export const tagExportsPlugin: PluginObj = { - visitor: { - Program: { - // Inject `import { __astro_tag_component__ } from 'astro/runtime/server/index.js'` - enter(path) { - path.node.body.splice( - 0, - 0, - t.importDeclaration( - [ - t.importSpecifier( - t.identifier('__astro_tag_component__'), - t.identifier('__astro_tag_component__'), - ), - ], - t.stringLiteral('astro/runtime/server/index.js'), - ), - ); - }, - // For each export we found, inject `__astro_tag_component__(exportName, rendererName)` - exit(path, state) { - const exportedIds = state.get('astro:tags'); - if (exportedIds) { - for (const id of exportedIds) { - path.node.body.push( - t.expressionStatement( - t.callExpression(t.identifier('__astro_tag_component__'), [ - t.identifier(id), - t.stringLiteral(rendererName), - ]), - ), - ); - } - } - }, - }, - ExportDeclaration: { - /** - * For default anonymous function export, we need to give them a unique name - * @param path - * @returns - */ - enter(path) { - const node = path.node; - if (!t.isExportDefaultDeclaration(node)) return; - - if (t.isArrowFunctionExpression(node.declaration) || t.isCallExpression(node.declaration)) { - const varName = t.isArrowFunctionExpression(node.declaration) - ? '_arrow_function' - : '_hoc_function'; - const uidIdentifier = path.scope.generateUidIdentifier(varName); - path.insertBefore( - t.variableDeclaration('const', [t.variableDeclarator(uidIdentifier, node.declaration)]), - ); - node.declaration = uidIdentifier; - } else if (t.isFunctionDeclaration(node.declaration) && !node.declaration.id?.name) { - const uidIdentifier = path.scope.generateUidIdentifier('_function'); - node.declaration.id = uidIdentifier; - } - }, - exit(path, state) { - const node = path.node; - if (node.exportKind === 'type') return; - if (t.isExportAllDeclaration(node)) return; - const addTag = (id: string) => { - const tags = state.get('astro:tags') ?? []; - state.set('astro:tags', [...tags, id]); - }; - if (t.isExportNamedDeclaration(node) || t.isExportDefaultDeclaration(node)) { - if (t.isIdentifier(node.declaration)) { - addTag(node.declaration.name); - } else if (t.isFunctionDeclaration(node.declaration) && node.declaration.id?.name) { - addTag(node.declaration.id.name); - } else if (t.isVariableDeclaration(node.declaration)) { - node.declaration.declarations?.forEach((declaration) => { - if (t.isArrowFunctionExpression(declaration.init) && t.isIdentifier(declaration.id)) { - addTag(declaration.id.name); - } - }); - } else if (t.isObjectExpression(node.declaration)) { - node.declaration.properties?.forEach((property) => { - if (t.isProperty(property) && t.isIdentifier(property.key)) { - addTag(property.key.name); - } - }); - } else if (t.isExportNamedDeclaration(node) && !node.source) { - node.specifiers.forEach((specifier) => { - if (t.isExportSpecifier(specifier) && t.isIdentifier(specifier.exported)) { - addTag(specifier.local.name); - } - }); - } - } - }, - }, - }, -}; diff --git a/packages/astro/src/vite-plugin-mdx/transform-jsx.ts b/packages/astro/src/vite-plugin-mdx/transform-jsx.ts deleted file mode 100644 index c3bb8ed76..000000000 --- a/packages/astro/src/vite-plugin-mdx/transform-jsx.ts +++ /dev/null @@ -1,72 +0,0 @@ -import babel from '@babel/core'; -import type { TransformResult } from 'rollup'; -import type { JSXTransformConfig } from '../@types/astro.js'; -import { jsxTransformOptions } from '../jsx/transform-options.js'; -import type { PluginMetadata } from '../vite-plugin-astro/types.js'; -import { tagExportsPlugin } from './tag.js'; - -/** - * @deprecated This function is no longer used. Remove in Astro 5.0 - */ -export async function transformJSX( - code: string, - id: string, - ssr?: boolean, -): Promise<TransformResult> { - const options = await getJsxTransformOptions(); - const plugins = ssr ? [...(options.plugins ?? []), tagExportsPlugin] : options.plugins; - - const result = await babel.transformAsync(code, { - presets: options.presets, - plugins, - cwd: process.cwd(), - filename: id, - ast: false, - compact: false, - sourceMaps: true, - configFile: false, - babelrc: false, - browserslistConfigFile: false, - inputSourceMap: options.inputSourceMap, - }); - - // TODO: Be more strict about bad return values here. - // Should we throw an error instead? Should we never return `{code: ""}`? - if (!result) return null; - - const { astro } = result.metadata as unknown as PluginMetadata; - return { - code: result.code || '', - map: result.map, - meta: { - astro, - vite: { - // Setting this vite metadata to `ts` causes Vite to resolve .js - // extensions to .ts files. - lang: 'ts', - }, - }, - }; -} - -let cachedJsxTransformOptions: Promise<JSXTransformConfig> | JSXTransformConfig | undefined; - -/** - * Get the `jsxTransformOptions` with caching - */ -async function getJsxTransformOptions(): Promise<JSXTransformConfig> { - if (cachedJsxTransformOptions) { - return cachedJsxTransformOptions; - } - - const options = jsxTransformOptions(); - - // Cache the promise - cachedJsxTransformOptions = options; - // After the promise is resolved, cache the final resolved options - options.then((resolvedOptions) => { - cachedJsxTransformOptions = resolvedOptions; - }); - - return options; -} diff --git a/packages/astro/src/vite-plugin-scanner/index.ts b/packages/astro/src/vite-plugin-scanner/index.ts index 842857777..2633743ae 100644 --- a/packages/astro/src/vite-plugin-scanner/index.ts +++ b/packages/astro/src/vite-plugin-scanner/index.ts @@ -2,12 +2,13 @@ import { extname } from 'node:path'; import { bold } from 'kleur/colors'; import type { Plugin as VitePlugin } from 'vite'; import { normalizePath } from 'vite'; -import type { AstroSettings, RouteOptions } from '../@types/astro.js'; import { type Logger } from '../core/logger/core.js'; import { isEndpoint, isPage, isServerLikeOutput } from '../core/util.js'; import { rootRelativePath } from '../core/viteUtils.js'; import { runHookRouteSetup } from '../integrations/hooks.js'; import { getPrerenderDefault } from '../prerender/utils.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { RouteOptions } from '../types/public/integrations.js'; import type { PageOptions } from '../vite-plugin-astro/types.js'; import { scan } from './scan.js'; diff --git a/packages/astro/src/vite-plugin-scanner/scan.ts b/packages/astro/src/vite-plugin-scanner/scan.ts index 52b2d6bd8..35e3de20a 100644 --- a/packages/astro/src/vite-plugin-scanner/scan.ts +++ b/packages/astro/src/vite-plugin-scanner/scan.ts @@ -1,4 +1,4 @@ -import type { AstroSettings } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; import type { PageOptions } from '../vite-plugin-astro/types.js'; import * as eslexer from 'es-module-lexer'; diff --git a/packages/astro/src/vite-plugin-scripts/index.ts b/packages/astro/src/vite-plugin-scripts/index.ts index 9b2848923..f87f6a381 100644 --- a/packages/astro/src/vite-plugin-scripts/index.ts +++ b/packages/astro/src/vite-plugin-scripts/index.ts @@ -1,5 +1,6 @@ import type { ConfigEnv, Plugin as VitePlugin } from 'vite'; -import type { AstroSettings, InjectedScriptStage } from '../@types/astro.js'; +import type { AstroSettings } from '../types/astro.js'; +import type { InjectedScriptStage } from '../types/public/integrations.js'; // NOTE: We can't use the virtual "\0" ID convention because we need to // inject these as ESM imports into actual code, where they would not diff --git a/packages/astro/src/vite-plugin-scripts/page-ssr.ts b/packages/astro/src/vite-plugin-scripts/page-ssr.ts index 00e907b03..05d8be18d 100644 --- a/packages/astro/src/vite-plugin-scripts/page-ssr.ts +++ b/packages/astro/src/vite-plugin-scripts/page-ssr.ts @@ -1,7 +1,7 @@ import MagicString from 'magic-string'; import { type Plugin as VitePlugin, normalizePath } from 'vite'; -import type { AstroSettings } from '../@types/astro.js'; import { isPage } from '../core/util.js'; +import type { AstroSettings } from '../types/astro.js'; import { PAGE_SSR_SCRIPT_ID } from './index.js'; export default function astroScriptsPostPlugin({ diff --git a/packages/astro/src/vite-plugin-utils/index.ts b/packages/astro/src/vite-plugin-utils/index.ts index a0133104c..2e7948bdd 100644 --- a/packages/astro/src/vite-plugin-utils/index.ts +++ b/packages/astro/src/vite-plugin-utils/index.ts @@ -1,12 +1,12 @@ import { fileURLToPath } from 'node:url'; import ancestor from 'common-ancestor-path'; -import type { AstroConfig } from '../@types/astro.js'; import { appendExtension, appendForwardSlash, removeLeadingForwardSlashWindows, } from '../core/path.js'; import { viteID } from '../core/util.js'; +import type { AstroConfig } from '../types/public/config.js'; export function getFileInfo(id: string, config: AstroConfig) { const sitePathname = appendForwardSlash( diff --git a/packages/astro/templates/actions.mjs b/packages/astro/templates/actions.mjs index 587f6ed9b..823699e15 100644 --- a/packages/astro/templates/actions.mjs +++ b/packages/astro/templates/actions.mjs @@ -55,7 +55,7 @@ function toActionProxy(actionCallback = {}, aggregatedPath = '') { /** * @param {*} param argument passed to the action when called server or client-side. * @param {string} path Built path to call action by path name. - * @param {import('../dist/@types/astro.d.ts').APIContext | undefined} context Injected API context when calling actions from the server. + * @param {import('../dist/types/public/context.js').APIContext | undefined} context Injected API context when calling actions from the server. * Usage: `actions.[name](param)`. * @returns {Promise<import('../dist/actions/runtime/virtual/shared.js').SafeResult<any, any>>} */ diff --git a/packages/astro/test/astro-attrs.test.js b/packages/astro/test/astro-attrs.test.js index 2e020f8ea..287298c93 100644 --- a/packages/astro/test/astro-attrs.test.js +++ b/packages/astro/test/astro-attrs.test.js @@ -16,21 +16,41 @@ describe('Attributes', async () => { const $ = cheerio.load(html); const attrs = { - 'false-str': { attribute: 'attr', value: 'false' }, - 'true-str': { attribute: 'attr', value: 'true' }, - false: { attribute: 'attr', value: undefined }, - true: { attribute: 'attr', value: 'true' }, - empty: { attribute: 'attr', value: '' }, + 'boolean-attr-true': { attribute: 'allowfullscreen', value: '' }, + 'boolean-attr-false': { attribute: 'allowfullscreen', value: undefined }, + 'boolean-attr-string-truthy': { attribute: 'allowfullscreen', value: '' }, + 'boolean-attr-string-falsy': { attribute: 'allowfullscreen', value: undefined }, + 'boolean-attr-number-truthy': { attribute: 'allowfullscreen', value: '' }, + 'boolean-attr-number-falsy': { attribute: 'allowfullscreen', value: undefined }, + 'data-attr-true': { attribute: 'data-foobar', value: 'true' }, + 'data-attr-false': { attribute: 'data-foobar', value: 'false' }, + 'data-attr-string-truthy': { attribute: 'data-foobar', value: 'foo' }, + 'data-attr-string-falsy': { attribute: 'data-foobar', value: '' }, + 'data-attr-number-truthy': { attribute: 'data-foobar', value: '1' }, + 'data-attr-number-falsy': { attribute: 'data-foobar', value: '0' }, + 'normal-attr-true': { attribute: 'foobar', value: 'true' }, + 'normal-attr-false': { attribute: 'foobar', value: 'false' }, + 'normal-attr-string-truthy': { attribute: 'foobar', value: 'foo' }, + 'normal-attr-string-falsy': { attribute: 'foobar', value: '' }, + 'normal-attr-number-truthy': { attribute: 'foobar', value: '1' }, + 'normal-attr-number-falsy': { attribute: 'foobar', value: '0' }, null: { attribute: 'attr', value: undefined }, undefined: { attribute: 'attr', value: undefined }, - 'html-boolean': { attribute: 'async', value: 'async' }, - 'html-boolean-true': { attribute: 'async', value: 'async' }, - 'html-boolean-false': { attribute: 'async', value: undefined }, 'html-enum': { attribute: 'draggable', value: 'true' }, 'html-enum-true': { attribute: 'draggable', value: 'true' }, 'html-enum-false': { attribute: 'draggable', value: 'false' }, }; + assert.ok(!/allowfullscreen=/.test(html), 'boolean attributes should not have values'); + assert.ok( + !/id="data-attr-string-falsy"\s+data-foobar=/.test(html), + "data attributes should not have values if it's an empty string", + ); + assert.ok( + !/id="normal-attr-string-falsy"\s+data-foobar=/.test(html), + "normal attributes should not have values if it's an empty string", + ); + // cheerio will unescape the values, so checking that the url rendered unescaped to begin with has to be done manually assert.equal( html.includes('https://example.com/api/og?title=hello&description=somedescription'), @@ -46,7 +66,7 @@ describe('Attributes', async () => { for (const id of Object.keys(attrs)) { const { attribute, value } = attrs[id]; const attr = $(`#${id}`).attr(attribute); - assert.equal(attr, value); + assert.equal(attr, value, `Expected ${attribute} to be ${value} for #${id}`); } }); diff --git a/packages/astro/test/astro-component-code.test.js b/packages/astro/test/astro-component-code.test.js index 6124e6054..b6f08ac57 100644 --- a/packages/astro/test/astro-component-code.test.js +++ b/packages/astro/test/astro-component-code.test.js @@ -88,12 +88,12 @@ describe('<Code>', () => { .map((i, f) => (f.attribs ? f.attribs.style : 'no style found')) .toArray(), [ - 'background-color:var(--astro-code-color-background);color:var(--astro-code-color-text); overflow-x: auto;', + 'background-color:var(--astro-code-background);color:var(--astro-code-foreground); overflow-x: auto;', 'color:var(--astro-code-token-constant)', 'color:var(--astro-code-token-function)', - 'color:var(--astro-code-color-text)', + 'color:var(--astro-code-foreground)', 'color:var(--astro-code-token-string-expression)', - 'color:var(--astro-code-color-text)', + 'color:var(--astro-code-foreground)', ], ); }); diff --git a/packages/astro/test/core-image-unconventional-settings.test.js b/packages/astro/test/core-image-unconventional-settings.test.js index edbfab6f6..b5d5fc664 100644 --- a/packages/astro/test/core-image-unconventional-settings.test.js +++ b/packages/astro/test/core-image-unconventional-settings.test.js @@ -6,7 +6,7 @@ import { testImageService } from './test-image-service.js'; import { loadFixture } from './test-utils.js'; /** - ** @typedef {import('../src/@types/astro').AstroInlineConfig & { root?: string | URL }} AstroInlineConfig + ** @typedef {import('../src/types/public/config.js').AstroInlineConfig & { root?: string | URL }} AstroInlineConfig */ /** @type {AstroInlineConfig} */ diff --git a/packages/astro/test/fixtures/astro-attrs/src/pages/index.astro b/packages/astro/test/fixtures/astro-attrs/src/pages/index.astro index 7ac96635f..8f2576650 100644 --- a/packages/astro/test/fixtures/astro-attrs/src/pages/index.astro +++ b/packages/astro/test/fixtures/astro-attrs/src/pages/index.astro @@ -1,19 +1,30 @@ -<span id="false-str" attr="false" /> -<span id="true-str" attr="true" /> -<span id="true" attr={true} /> -<span id="false" attr={false} /> -<span id="empty" attr="" /> +<span id="boolean-attr-true" allowfullscreen={true} /> +<span id="boolean-attr-false" allowfullscreen={false} /> +<span id="boolean-attr-string-truthy" allowfullscreen={'foo'} /> +<span id="boolean-attr-string-falsy" allowfullscreen={''} /> +<span id="boolean-attr-number-truthy" allowfullscreen={1} /> +<span id="boolean-attr-number-falsy" allowfullscreen={0} /> + +<span id="data-attr-true" data-foobar={true} /> +<span id="data-attr-false" data-foobar={false} /> +<span id="data-attr-string-truthy" data-foobar={'foo'} /> +<span id="data-attr-string-falsy" data-foobar={''} /> +<span id="data-attr-number-truthy" data-foobar={1} /> +<span id="data-attr-number-falsy" data-foobar={0} /> + +<span id="normal-attr-true" foobar={true} /> +<span id="normal-attr-false" foobar={false} /> +<span id="normal-attr-string-truthy" foobar={'foo'} /> +<span id="normal-attr-string-falsy" foobar={''} /> +<span id="normal-attr-number-truthy" foobar={1} /> +<span id="normal-attr-number-falsy" foobar={0} /> + <span id="null" attr={null} /> <span id="undefined" attr={undefined} /> + <span id="url" attr={"https://example.com/api/og?title=hello&description=somedescription"}/> <span id="code" attr={"cmd: echo \"foo\" && echo \"bar\" > /tmp/hello.txt"} /> -<!-- - Per HTML spec, some attributes should be treated as booleans - These should always render <span async /> or <span /> (without a string value) ---> -<span id='html-boolean' async /> -<span id='html-boolean-true' async={true} /> -<span id='html-boolean-false' async={false} /> + <!-- Other attributes should be treated as string enums These should always render <span draggable="true" /> or <span draggable="false" /> diff --git a/packages/astro/test/fixtures/core-image-ssr/src/pages/api.ts b/packages/astro/test/fixtures/core-image-ssr/src/pages/api.ts index 261fb6bb7..25777dce8 100644 --- a/packages/astro/test/fixtures/core-image-ssr/src/pages/api.ts +++ b/packages/astro/test/fixtures/core-image-ssr/src/pages/api.ts @@ -1,4 +1,4 @@ -import type { APIRoute } from "../../../../../src/@types/astro"; +import type { APIRoute } from "astro" export const GET = (async ({ params, request }) => { const url = new URL(request.url); diff --git a/packages/astro/test/fixtures/jsx/astro.config.mjs b/packages/astro/test/fixtures/jsx/astro.config.mjs index 3bcbe0d8f..661b716f5 100644 --- a/packages/astro/test/fixtures/jsx/astro.config.mjs +++ b/packages/astro/test/fixtures/jsx/astro.config.mjs @@ -5,7 +5,6 @@ import solid from '@astrojs/solid-js'; import svelte from '@astrojs/svelte'; import vue from '@astrojs/vue'; import { defineConfig } from 'astro/config'; -import renderer from 'astro/jsx/renderer.js'; export default defineConfig({ @@ -22,13 +21,5 @@ export default defineConfig({ mdx(), svelte(), vue(), - { - name: '@astrojs/test-jsx', - hooks: { - 'astro:config:setup': ({ addRenderer }) => { - addRenderer(renderer); - } - } - }, ] }) diff --git a/packages/astro/test/fixtures/lit-element/astro.config.mjs b/packages/astro/test/fixtures/lit-element/astro.config.mjs deleted file mode 100644 index 0ddc1e5d0..000000000 --- a/packages/astro/test/fixtures/lit-element/astro.config.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import lit from '@astrojs/lit'; -import { defineConfig } from 'astro/config'; - -// https://astro.build/config -export default defineConfig({ - integrations: [lit()], -});
\ No newline at end of file diff --git a/packages/astro/test/fixtures/lit-element/package.json b/packages/astro/test/fixtures/lit-element/package.json deleted file mode 100644 index fdfb79ab7..000000000 --- a/packages/astro/test/fixtures/lit-element/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "@test/lit-element", - "version": "0.0.0", - "private": true, - "dependencies": { - "@astrojs/lit": "workspace:*", - "@webcomponents/template-shadowroot": "^0.2.1", - "astro": "workspace:*", - "lit": "^3.2.0" - } -} diff --git a/packages/astro/test/fixtures/lit-element/src/components/my-element.ts b/packages/astro/test/fixtures/lit-element/src/components/my-element.ts deleted file mode 100644 index b4c98b010..000000000 --- a/packages/astro/test/fixtures/lit-element/src/components/my-element.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { LitElement, html } from 'lit'; -import { customElement, property } from 'lit/decorators.js'; - -@customElement('my-element') -export class MyElement extends LitElement { - @property({ type: Boolean }) - bool = 0; - - static properties = { - str: {type: String, attribute: 'str-attr'}, - obj: {type: Object}, - reflectedBool: {type: Boolean, reflect: true}, - reflectedStr: {type: String, reflect: true, attribute: 'reflected-str'}, - reflectedStrProp: {type: String, reflect: true, attribute: 'reflected-str-prop'}, - } - - constructor() { - super(); - this.bool = true; - this.str = 'not initialized'; - this.obj = {data: null}; - // not a reactive property - this.foo = 'not initialized'; - // reflected props - this.reflectedBool = true; - this.reflectedStr = 'default reflected string'; - } - render() { - return html` - <div>Testing...</div> - <div id="bool">${this.bool ? 'A' : 'B'}</div> - <div id="str">${this.str}</div> - <div id="data">data: ${this.obj.data}</div> - - <!-- Slots --> - <div id="default"><slot /></div> - <div id="named"><slot name="named" /></div> - `; - } -} diff --git a/packages/astro/test/fixtures/lit-element/src/components/non-deferred-element.ts b/packages/astro/test/fixtures/lit-element/src/components/non-deferred-element.ts deleted file mode 100644 index f5c36a7d3..000000000 --- a/packages/astro/test/fixtures/lit-element/src/components/non-deferred-element.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { LitElement, html } from 'lit'; -import { customElement, property } from 'lit/decorators.js'; - -@customElement('non-deferred-counter') -export class NonDeferredCounter extends LitElement { - // All set properties are reflected to attributes so its hydration is not - // hydration-deferred should always be set. - @property({ type: Number, reflect: true }) count = 0; - - increment() { - this.count++; - } - - render() { - return html` - <div> - <p>Count: ${this.count}</p> - - <button type="button" @click=${this.increment}>Increment</button> - </div> - `; - } -} diff --git a/packages/astro/test/fixtures/lit-element/src/pages/[page].astro b/packages/astro/test/fixtures/lit-element/src/pages/[page].astro deleted file mode 100644 index 52a791272..000000000 --- a/packages/astro/test/fixtures/lit-element/src/pages/[page].astro +++ /dev/null @@ -1,30 +0,0 @@ ---- -import {MyElement} from '../components/my-element.js'; -export async function getStaticPaths() { - return [ - { - params: { page: 1 }, - }, - { - params: { page: 2 }, - }, - { - params: { page: 3 } - } - ] -}; - -const { page } = Astro.params ---- - -<html lang="en"> - <head> - <meta charset="utf-8" /> - <meta name="viewport" content="width=device-width" /> - <title>Posts Page {page}</title> - </head> - <body> - <h1>Welcome to page {page}</h1> - <MyElement /> - </body> -</html> diff --git a/packages/astro/test/fixtures/lit-element/src/pages/index.astro b/packages/astro/test/fixtures/lit-element/src/pages/index.astro deleted file mode 100644 index 394885fca..000000000 --- a/packages/astro/test/fixtures/lit-element/src/pages/index.astro +++ /dev/null @@ -1,25 +0,0 @@ ---- -import {MyElement} from '../components/my-element.js'; -import {NonDeferredCounter} from '../components/non-deferred-element.js'; ---- - -<html> -<head> - <title>LitElements</title> -</head> -<body> - <MyElement - id="default" - foo="bar" - str-attr={'initialized'} - bool={false} - obj={{data: 1}} - reflectedStrProp={'initialized reflected'}> - </MyElement> - <NonDeferredCounter - id="non-deferred" - count={10} - foo="bar"> - </NonDeferredCounter> -</body> -</html> diff --git a/packages/astro/test/fixtures/lit-element/src/pages/slots.astro b/packages/astro/test/fixtures/lit-element/src/pages/slots.astro deleted file mode 100644 index 6ef0cd183..000000000 --- a/packages/astro/test/fixtures/lit-element/src/pages/slots.astro +++ /dev/null @@ -1,39 +0,0 @@ ---- -import {MyElement} from '../components/my-element.js'; ---- - -<html> -<head> - <title>LitElement | Slot</title> -</head> -<body> - <MyElement id="root"> - <div class="default">my-element default 1</div> - <div class="default">my-element default 2</div> - - <h1 slot="named">my-element named 1</h1> - <h2 slot="named">my-element named 2</h2> - - <ul slot="named" id="list"> - <li>Custom elements</li> - <li>Shadow DOM</li> - <li>HTML templates</li> - </ul> - - <my-element id="slotted" slot="named"> - <h3 class="default">slotted my-element default</h3> - - <div slot="named">slotted my-element named 1</div> - <div slot="named">slotted my-element named 2</div> - - <MyElement id="slotted-slotted" slot="named"> - <h4 class="default">slotted slotted my-element default 1</h4> - <h5 class="default">slotted slotted my-element default 2</h5> - - <div slot="named">slotted slotted my-element named 1</div> - <div slot="named">slotted slotted my-element named 2</div> - </MyElement> - </my-element> - </MyElement> -</body> -</html> diff --git a/packages/astro/test/fixtures/lit-element/src/skipped-pages/ctr.astro b/packages/astro/test/fixtures/lit-element/src/skipped-pages/ctr.astro deleted file mode 100644 index d41e9645f..000000000 --- a/packages/astro/test/fixtures/lit-element/src/skipped-pages/ctr.astro +++ /dev/null @@ -1,12 +0,0 @@ ---- -import { MyElement } from '../components/my-element.js'; ---- - -<html> -<head> - <title>LitElements</title> -</head> -<body> - <MyElement foo="bar" /> -</body> -</html> diff --git a/packages/astro/test/fixtures/lit-element/tsconfig.json b/packages/astro/test/fixtures/lit-element/tsconfig.json deleted file mode 100644 index 504cd646e..000000000 --- a/packages/astro/test/fixtures/lit-element/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "compilerOptions": { - "experimentalDecorators": true - } -} diff --git a/packages/astro/test/fixtures/ssr-prerender-chunks/deps/test-adapter/index.js b/packages/astro/test/fixtures/ssr-prerender-chunks/deps/test-adapter/index.js index 82b7b64b1..06eb02e2c 100644 --- a/packages/astro/test/fixtures/ssr-prerender-chunks/deps/test-adapter/index.js +++ b/packages/astro/test/fixtures/ssr-prerender-chunks/deps/test-adapter/index.js @@ -1,6 +1,6 @@ /** * - * @returns {import('../src/@types/astro').AstroIntegration} + * @returns {import('../../../../../src/types/public/integrations.js').AstroIntegration} */ export default function () { return { @@ -82,4 +82,4 @@ export default function () { }, }, }; -}
\ No newline at end of file +} diff --git a/packages/astro/test/lit-element.test.js b/packages/astro/test/lit-element.test.js deleted file mode 100644 index 0522b8c71..000000000 --- a/packages/astro/test/lit-element.test.js +++ /dev/null @@ -1,154 +0,0 @@ -import assert from 'node:assert/strict'; -import { before, describe, it } from 'node:test'; -import * as cheerio from 'cheerio'; -import { loadFixture } from './test-utils.js'; - -describe( - 'LitElement test', - { timeout: 300000, skip: 'This goes in conflict with ssr-lit test file' }, - () => { - let fixture; - - const NODE_VERSION = parseFloat(process.versions.node); - const stripExpressionMarkers = (html) => html.replace(/<!--\/?lit-part-->/g, ''); - - before(async () => { - // @lit-labs/ssr/ requires Node 13.9 or higher - if (NODE_VERSION < 13.9) { - return; - } - fixture = await loadFixture({ - root: './fixtures/lit-element/', - }); - await fixture.build(); - }); - - it('Renders a custom element by Constructor', async () => { - // @lit-labs/ssr/ requires Node 13.9 or higher - if (NODE_VERSION < 13.9) { - return; - } - const html = await fixture.readFile('/index.html'); - const $ = cheerio.load(html); - - // test 1: attributes rendered – non reactive properties - assert.equal($('#default').attr('foo'), 'bar'); - - // test 2: shadow rendered - assert.equal($('#default').html().includes('<div>Testing...</div>'), true); - - // test 3: string reactive property set - assert.equal( - stripExpressionMarkers($('#default').html()).includes(`<div id="str">initialized</div>`), - true, - ); - - // test 4: boolean reactive property correctly set - // <my-element bool="false"> Lit will equate to true because it uses - // this.hasAttribute to determine its value - assert.equal( - stripExpressionMarkers($('#default').html()).includes(`<div id="bool">B</div>`), - true, - ); - - // test 5: object reactive property set - // by default objects will be stringified to [object Object] - assert.equal( - stripExpressionMarkers($('#default').html()).includes(`<div id="data">data: 1</div>`), - true, - ); - - // test 6: reactive properties are not rendered as attributes - assert.equal($('#default').attr('obj'), undefined); - assert.equal($('#default').attr('bool'), undefined); - assert.equal($('#default').attr('str'), undefined); - - // test 7: reflected reactive props are rendered as attributes - assert.equal($('#default').attr('reflectedbool'), ''); - assert.equal($('#default').attr('reflected-str'), 'default reflected string'); - assert.equal($('#default').attr('reflected-str-prop'), 'initialized reflected'); - }); - - it('Sets defer-hydration on element only when necessary', async () => { - // @lit-labs/ssr/ requires Node 13.9 or higher - if (NODE_VERSION < 13.9) { - return; - } - const html = await fixture.readFile('/index.html'); - const $ = cheerio.load(html); - - // test 1: reflected reactive props are rendered as attributes - assert.equal($('#non-deferred').attr('count'), '10'); - - // test 2: non-reactive props are set as attributes - assert.equal($('#non-deferred').attr('foo'), 'bar'); - - // test 3: components with only reflected reactive props set are not - // deferred because their state can be completely serialized via attributes - assert.equal($('#non-deferred').attr('defer-hydration'), undefined); - - // test 4: components with non-reflected reactive props set are deferred because - // their state needs to be synced with the server on the client. - assert.equal($('#default').attr('defer-hydration'), ''); - }); - - it('Correctly passes child slots', async () => { - // @lit-labs/ssr/ requires Node 13.9 or higher - if (NODE_VERSION < 13.9) { - return; - } - const html = await fixture.readFile('/slots/index.html'); - const $ = cheerio.load(html); - - const $rootMyElement = $('#root'); - const $slottedMyElement = $('#slotted'); - const $slottedSlottedMyElement = $('#slotted-slotted'); - - assert.equal($('#default').length, 3); - - // Root my-element - assert.equal($rootMyElement.children('.default').length, 2); - assert.equal($rootMyElement.children('.default').eq(1).text(), 'my-element default 2'); - - assert.equal($rootMyElement.children('[slot="named"]').length, 4); - assert.equal($rootMyElement.children('[slot="named"]').eq(1).text(), 'my-element named 2'); - assert.equal($rootMyElement.children('[slot="named"]').eq(2).attr('id'), 'list'); - assert.equal($rootMyElement.children('[slot="named"]').eq(3).attr('id'), 'slotted'); - - // Slotted my-element first level - assert.equal($slottedMyElement.children('.default').length, 1); - assert.equal( - $slottedMyElement.children('.default').eq(0).text(), - 'slotted my-element default', - ); - - assert.equal($slottedMyElement.children('[slot="named"]').length, 3); - assert.equal( - $slottedMyElement.children('[slot="named"]').eq(1).text(), - 'slotted my-element named 2', - ); - assert.equal( - $slottedMyElement.children('[slot="named"]').eq(2).attr('id'), - 'slotted-slotted', - ); - - // Slotted my-element second level - assert.equal($slottedSlottedMyElement.children('.default').length, 2); - assert.equal( - $slottedSlottedMyElement.children('.default').eq(1).text(), - 'slotted slotted my-element default 2', - ); - - assert.equal($slottedSlottedMyElement.children('[slot="named"]').length, 2); - assert.equal( - $slottedSlottedMyElement.children('[slot="named"]').eq(1).text(), - 'slotted slotted my-element named 2', - ); - }); - - it('Is able to build when behind getStaticPaths', async () => { - const dynamicPage = await fixture.readFile('/1/index.html'); - assert.equal(dynamicPage.length > 0, true); - }); - }, -); diff --git a/packages/astro/test/middleware.test.js b/packages/astro/test/middleware.test.js index 612937d80..f7fbc3501 100644 --- a/packages/astro/test/middleware.test.js +++ b/packages/astro/test/middleware.test.js @@ -340,40 +340,3 @@ describe('Middleware with tailwind', () => { assert.equal(bundledCSS.includes('--tw-content'), true); }); }); - -// `loadTestAdapterApp()` does not understand how to load the page with `functionPerRoute` -// since there's no `entry.mjs`. Skip for now. -describe( - 'Middleware supports functionPerRoute feature', - { - skip: "`loadTestAdapterApp()` does not understand how to load the page with `functionPerRoute` since there's no `entry.mjs`", - }, - () => { - /** @type {import('./test-utils').Fixture} */ - let fixture; - - before(async () => { - fixture = await loadFixture({ - root: './fixtures/middleware space/', - output: 'server', - adapter: testAdapter({ - extendAdapter: { - adapterFeatures: { - functionPerRoute: true, - }, - }, - }), - }); - await fixture.build(); - }); - - it('should not render locals data because the page does not export it', async () => { - const app = await fixture.loadTestAdapterApp(); - const request = new Request('http://example.com/'); - const response = await app.render(request); - const html = await response.text(); - const $ = cheerio.load(html); - assert.equal($('p').html(), 'bar'); - }); - }, -); diff --git a/packages/astro/test/ssr-lit.test.js b/packages/astro/test/ssr-lit.test.js deleted file mode 100644 index 40057cf21..000000000 --- a/packages/astro/test/ssr-lit.test.js +++ /dev/null @@ -1,33 +0,0 @@ -import assert from 'node:assert/strict'; -import { before, describe, it } from 'node:test'; -import { load as cheerioLoad } from 'cheerio'; -import testAdapter from './test-adapter.js'; -import { loadFixture } from './test-utils.js'; - -describe('Lit integration in SSR', () => { - /** @type {import('./test-utils').Fixture} */ - let fixture; - - before(async () => { - fixture = await loadFixture({ - root: './fixtures/lit-element/', - output: 'server', - adapter: testAdapter(), - }); - await fixture.build(); - }); - - async function fetchHTML(path) { - const app = await fixture.loadTestAdapterApp(); - const request = new Request('http://example.com' + path); - const response = await app.render(request); - const html = await response.text(); - return html; - } - - it('Is able to load', async () => { - const html = await fetchHTML('/'); - const $ = cheerioLoad(html); - assert.equal($('#str').text(), 'initialized'); - }); -}); diff --git a/packages/astro/test/ssr-split-manifest.test.js b/packages/astro/test/ssr-split-manifest.test.js deleted file mode 100644 index af0234c6a..000000000 --- a/packages/astro/test/ssr-split-manifest.test.js +++ /dev/null @@ -1,117 +0,0 @@ -import assert from 'node:assert/strict'; -import { existsSync, readFileSync } from 'node:fs'; -import { before, describe, it } from 'node:test'; -import { fileURLToPath } from 'node:url'; -import * as cheerio from 'cheerio'; -import testAdapter from './test-adapter.js'; -import { loadFixture } from './test-utils.js'; - -describe('astro:ssr-manifest, split', () => { - /** @type {import('./test-utils').Fixture} */ - let fixture; - let entryPoints; - let currentRoutes; - - before(async () => { - fixture = await loadFixture({ - root: './fixtures/ssr-split-manifest/', - output: 'server', - adapter: testAdapter({ - setEntryPoints(entries) { - if (entries) { - entryPoints = entries; - } - }, - setRoutes(routes) { - currentRoutes = routes; - }, - extendAdapter: { - adapterFeatures: { - functionPerRoute: true, - }, - }, - }), - // test suite was authored when inlineStylesheets defaulted to never - build: { inlineStylesheets: 'never' }, - }); - await fixture.build(); - }); - - it('should be able to render a specific entry point', async () => { - const pagePath = 'src/pages/index.astro'; - const app = await fixture.loadEntryPoint(pagePath, currentRoutes); - const request = new Request('http://example.com/'); - const response = await app.render(request); - const html = await response.text(); - - const $ = cheerio.load(html); - assert.match( - $('#assets').text(), - /\["\/_astro\/index\.([\w-]{8})\.css","\/prerender\/index\.html"\]/, - ); - }); - - it('should give access to entry points that exists on file system', async () => { - // number of the pages inside src/ - assert.equal(entryPoints.size, 6); - for (const fileUrl of entryPoints.values()) { - let filePath = fileURLToPath(fileUrl); - assert.equal(existsSync(filePath), true); - } - }); - - it('should correctly emit the the pre render page', async () => { - const indexUrl = new URL( - './fixtures/ssr-split-manifest/dist/client/prerender/index.html', - import.meta.url, - ); - const text = readFileSync(indexUrl, { - encoding: 'utf8', - }); - assert.equal(text.includes('<title>Pre render me</title>'), true); - }); - - it('should emit an entry point to request the pre-rendered page', async () => { - const pagePath = 'src/pages/prerender.astro'; - const app = await fixture.loadEntryPoint(pagePath, currentRoutes); - const request = new Request('http://example.com/'); - const response = await app.render(request); - const html = await response.text(); - assert.equal(html.includes('<title>Pre render me</title>'), true); - }); - - describe('when function per route is enabled', async () => { - before(async () => { - fixture = await loadFixture({ - root: './fixtures/ssr-split-manifest/', - output: 'server', - adapter: testAdapter({ - setEntryPoints(entries) { - if (entries) { - entryPoints = entries; - } - }, - setRoutes(routes) { - currentRoutes = routes; - }, - extendAdapter: { - adapterFeatures: { - functionPerRoute: true, - }, - }, - }), - // test suite was authored when inlineStylesheets defaulted to never - build: { inlineStylesheets: 'never' }, - }); - await fixture.build(); - }); - it('should correctly build, and not create a "uses" entry point', async () => { - const pagePath = 'src/pages/index.astro'; - const app = await fixture.loadEntryPoint(pagePath, currentRoutes); - const request = new Request('http://example.com/'); - const response = await app.render(request); - const html = await response.text(); - assert.equal(html.includes('<title>Testing</title>'), true); - }); - }); -}); diff --git a/packages/astro/test/test-adapter.js b/packages/astro/test/test-adapter.js index fc5249561..4a2ac65d0 100644 --- a/packages/astro/test/test-adapter.js +++ b/packages/astro/test/test-adapter.js @@ -1,11 +1,11 @@ import { viteID } from '../dist/core/util.js'; /** - * @typedef {import('../src/@types/astro.js').AstroAdapter} AstroAdapter - * @typedef {import('../src/@types/astro.js').AstroIntegration} AstroIntegration - * @typedef {import('../src/@types/astro.js').HookParameters<"astro:build:ssr">['entryPoints']} EntryPoints - * @typedef {import('../src/@types/astro.js').HookParameters<"astro:build:ssr">['middlewareEntryPoint']} MiddlewareEntryPoint - * @typedef {import('../src/@types/astro.js').HookParameters<"astro:build:done">['routes']} Routes + * @typedef {import('../src/types/public/integrations.js').AstroAdapter} AstroAdapter + * @typedef {import('../src/types/public/integrations.js').AstroIntegration} AstroIntegration + * @typedef {import('../src/types/public/integrations.js').HookParameters<"astro:build:ssr">['entryPoints']} EntryPoints + * @typedef {import('../src/types/public/integrations.js').HookParameters<"astro:build:ssr">['middlewareEntryPoint']} MiddlewareEntryPoint + * @typedef {import('../src/types/public/integrations.js').HookParameters<"astro:build:done">['routes']} Routes */ /** diff --git a/packages/astro/test/test-image-service.js b/packages/astro/test/test-image-service.js index 35a5fa2c8..de076425c 100644 --- a/packages/astro/test/test-image-service.js +++ b/packages/astro/test/test-image-service.js @@ -12,7 +12,7 @@ export function testImageService(config = {}) { }; } -/** @type {import("../dist/@types/astro").LocalImageService} */ +/** @type {import("../dist/types/public/index.js").LocalImageService} */ export default { ...baseService, propertiesToHash: [...baseService.propertiesToHash, 'data-custom'], diff --git a/packages/astro/test/test-utils.js b/packages/astro/test/test-utils.js index 95edeebd2..facaaef00 100644 --- a/packages/astro/test/test-utils.js +++ b/packages/astro/test/test-utils.js @@ -10,9 +10,6 @@ import { check } from '../dist/cli/check/index.js'; import { globalContentLayer } from '../dist/content/content-layer.js'; import { globalContentConfigObserver } from '../dist/content/utils.js'; import build from '../dist/core/build/index.js'; -import { RESOLVED_SPLIT_MODULE_ID } from '../dist/core/build/plugins/plugin-ssr.js'; -import { getVirtualModulePageName } from '../dist/core/build/plugins/util.js'; -import { makeSplitEntryPointFileName } from '../dist/core/build/static-build.js'; import { mergeConfig, resolveConfig } from '../dist/core/config/index.js'; import { dev, preview } from '../dist/core/index.js'; import { nodeLogDestination } from '../dist/core/logger/node.js'; @@ -23,8 +20,8 @@ process.env.ASTRO_TELEMETRY_DISABLED = true; /** * @typedef {import('../src/core/dev/dev').DevServer} DevServer - * @typedef {import('../src/@types/astro').AstroInlineConfig & { root?: string | URL }} AstroInlineConfig - * @typedef {import('../src/@types/astro').AstroConfig} AstroConfig + * @typedef {import('../src/types/public/config.js').AstroInlineConfig & { root?: string | URL }} AstroInlineConfig + * @typedef {import('../src/types/public/config.js').AstroConfig} AstroConfig * @typedef {import('../src/core/preview/index').PreviewServer} PreviewServer * @typedef {import('../src/core/app/index').App} App * @typedef {import('../src/cli/check/index').AstroChecker} AstroChecker @@ -262,15 +259,6 @@ export async function loadFixture(inlineConfig) { app.manifest = manifest; return app; }, - loadEntryPoint: async (pagePath, routes, streaming) => { - const virtualModule = getVirtualModulePageName(RESOLVED_SPLIT_MODULE_ID, pagePath); - const filePath = makeSplitEntryPointFileName(virtualModule, routes); - const url = new URL(`./server/${filePath}?id=${fixtureId}`, config.outDir); - const { createApp, manifest } = await import(url); - const app = createApp(streaming); - app.manifest = manifest; - return app; - }, editFile: async (filePath, newContentsOrCallback) => { const fileUrl = new URL(filePath.replace(/^\//, ''), config.root); const contents = await fs.promises.readFile(fileUrl, 'utf-8'); diff --git a/packages/astro/test/types/call-action.ts b/packages/astro/test/types/call-action.ts index 916105585..6d4019d38 100644 --- a/packages/astro/test/types/call-action.ts +++ b/packages/astro/test/types/call-action.ts @@ -1,7 +1,7 @@ import { describe, it } from 'node:test'; import { expectTypeOf } from 'expect-type'; -import type { APIContext } from '../../dist/@types/astro.js'; import { type ActionReturnType, defineAction } from '../../dist/actions/runtime/virtual/server.js'; +import type { APIContext } from '../../dist/types/public/context.js'; import { z } from '../../zod.mjs'; describe('Astro.callAction', () => { diff --git a/packages/astro/test/units/render/jsx.test.js b/packages/astro/test/units/render/jsx.test.js deleted file mode 100644 index ba03a6f55..000000000 --- a/packages/astro/test/units/render/jsx.test.js +++ /dev/null @@ -1,142 +0,0 @@ -import * as assert from 'node:assert/strict'; -import { before, describe, it } from 'node:test'; -import { RenderContext } from '../../../dist/core/render-context.js'; -import { loadRenderer } from '../../../dist/core/render/index.js'; -import { jsx } from '../../../dist/jsx-runtime/index.js'; -import { createAstroJSXComponent, renderer as jsxRenderer } from '../../../dist/jsx/index.js'; -import { - createComponent, - render, - renderComponent, - renderSlot, -} from '../../../dist/runtime/server/index.js'; -import { createBasicPipeline } from '../test-utils.js'; - -const createAstroModule = (AstroComponent) => ({ default: AstroComponent }); -const loadJSXRenderer = () => loadRenderer(jsxRenderer, { import: (s) => import(s) }); - -// NOTE: This test may be testing an outdated JSX setup -describe('core/render', () => { - describe('Astro JSX components', () => { - let pipeline; - before(async () => { - pipeline = createBasicPipeline({ - renderers: [await loadJSXRenderer()], - }); - }); - - it('Can render slots', async () => { - const Wrapper = createComponent((result, _props, slots = {}) => { - return render`<div>${renderSlot(result, slots['myslot'])}</div>`; - }); - - const Page = createAstroJSXComponent(() => { - return jsx(Wrapper, { - children: [ - jsx('p', { - slot: 'myslot', - className: 'n', - children: 'works', - }), - ], - }); - }); - - const mod = createAstroModule(Page); - const request = new Request('http://example.com/'); - const routeData = { - type: 'page', - pathname: '/index', - component: 'src/pages/index.mdx', - params: {}, - }; - const renderContext = RenderContext.create({ pipeline, request, routeData }); - const response = await renderContext.render(mod); - - assert.equal(response.status, 200); - - const html = await response.text(); - assert.equal(html.includes('<div><p class="n">works</p></div>'), true); - }); - - it('Can render slots with a dash in the name', async () => { - const Wrapper = createComponent((result, _props, slots = {}) => { - return render`<div>${renderSlot(result, slots['my-slot'])}</div>`; - }); - - const Page = createAstroJSXComponent(() => { - return jsx('main', { - children: [ - jsx(Wrapper, { - // Children as an array - children: [ - jsx('p', { - slot: 'my-slot', - className: 'n', - children: 'works', - }), - ], - }), - jsx(Wrapper, { - // Children as a VNode - children: jsx('p', { - slot: 'my-slot', - className: 'p', - children: 'works', - }), - }), - ], - }); - }); - - const mod = createAstroModule(Page); - const request = new Request('http://example.com/'); - const routeData = { - type: 'page', - pathname: '/index', - component: 'src/pages/index.mdx', - params: {}, - }; - const renderContext = RenderContext.create({ pipeline, request, routeData }); - const response = await renderContext.render(mod); - - assert.equal(response.status, 200); - - const html = await response.text(); - assert.equal( - html.includes( - '<main><div><p class="n">works</p></div><div><p class="p">works</p></div></main>', - ), - true, - ); - }); - - it('Errors in JSX components are raised', async () => { - const Component = createAstroJSXComponent(() => { - throw new Error('uh oh'); - }); - - const Page = createComponent((result) => { - return render`<div>${renderComponent(result, 'Component', Component, {})}</div>`; - }); - - const mod = createAstroModule(Page); - const request = new Request('http://example.com/'); - const routeData = { - type: 'page', - pathname: '/index', - component: 'src/pages/index.mdx', - params: {}, - }; - const renderContext = RenderContext.create({ pipeline, request, routeData }); - const response = await renderContext.render(mod); - - try { - await response.text(); - assert.equal(false, true, 'should not have been successful'); - } catch (err) { - assert.equal(err.message, 'uh oh'); - } - }); - }); -}); diff --git a/packages/astro/test/units/test-utils.js b/packages/astro/test/units/test-utils.js index bab850b68..a104ef2a4 100644 --- a/packages/astro/test/units/test-utils.js +++ b/packages/astro/test/units/test-utils.js @@ -211,8 +211,8 @@ export function createBasicPipeline(options = {}) { } /** - * @param {import('../../src/@types/astro.js').AstroInlineConfig} inlineConfig - * @returns {Promise<import('../../src/@types/astro.js').AstroSettings>} + * @param {import('../../src/types/public/config.js').AstroInlineConfig} inlineConfig + * @returns {Promise<import('../../src/types/astro.js').AstroSettings>} */ export async function createBasicSettings(inlineConfig = {}) { if (!inlineConfig.root) { @@ -225,7 +225,7 @@ export async function createBasicSettings(inlineConfig = {}) { /** * @typedef {{ * fs?: typeof realFS, - * inlineConfig?: import('../../src/@types/astro.js').AstroInlineConfig, + * inlineConfig?: import('../../src/types/public/config.js').AstroInlineConfig, * logging?: import('../../src/core/logger/core').LogOptions, * }} RunInContainerOptions */ diff --git a/packages/astro/types.d.ts b/packages/astro/types.d.ts index b04f062fd..cc0f1c3d2 100644 --- a/packages/astro/types.d.ts +++ b/packages/astro/types.d.ts @@ -1,6 +1,6 @@ import './astro-jsx'; -import type { AstroBuiltinAttributes } from './dist/@types/astro.js'; import type { OmitIndexSignature, Simplify } from './dist/type-utils.js'; +import type { AstroBuiltinAttributes } from './dist/types/public/elements.js'; /** Any supported HTML or SVG element name, as defined by the HTML specification */ export type HTMLTag = keyof astroHTML.JSX.DefinedIntrinsicElements; diff --git a/packages/create-astro/CHANGELOG.md b/packages/create-astro/CHANGELOG.md index 19ae5f93f..e658c7850 100644 --- a/packages/create-astro/CHANGELOG.md +++ b/packages/create-astro/CHANGELOG.md @@ -1,5 +1,11 @@ # create-astro +## 4.8.4-alpha.0 + +### Patch Changes + +- [#11766](https://github.com/withastro/astro/pull/11766) [`d12dcbf`](https://github.com/withastro/astro/commit/d12dcbff606dd8330075ba77d73ed3cbc79d7421) Thanks [@bluwy](https://github.com/bluwy)! - Fixes initial git commit when initializing git + ## 4.8.3 ### Patch Changes diff --git a/packages/create-astro/package.json b/packages/create-astro/package.json index e22a738fa..2d2b79d79 100644 --- a/packages/create-astro/package.json +++ b/packages/create-astro/package.json @@ -1,6 +1,6 @@ { "name": "create-astro", - "version": "4.8.3", + "version": "4.8.4-alpha.0", "type": "module", "author": "withastro", "license": "MIT", diff --git a/packages/integrations/lit/.gitignore b/packages/integrations/lit/.gitignore deleted file mode 100644 index 40b878db5..000000000 --- a/packages/integrations/lit/.gitignore +++ /dev/null @@ -1 +0,0 @@ -node_modules/
\ No newline at end of file diff --git a/packages/integrations/lit/CHANGELOG.md b/packages/integrations/lit/CHANGELOG.md deleted file mode 100644 index 0aa8f4f71..000000000 --- a/packages/integrations/lit/CHANGELOG.md +++ /dev/null @@ -1,306 +0,0 @@ -# @astrojs/lit - -## 4.3.0 - -### Minor Changes - -- [#11234](https://github.com/withastro/astro/pull/11234) [`4385bf7`](https://github.com/withastro/astro/commit/4385bf7a4dc9c65bff53a30c660f7a909fcabfc9) Thanks [@ematipico](https://github.com/ematipico)! - Adds a new function called `addServerRenderer` to the Container API. Use this function to manually store renderers inside the instance of your container. - - This new function should be preferred when using the Container API in environments like on-demand pages: - - ```ts - import type { APIRoute } from 'astro'; - import { experimental_AstroContainer } from 'astro/container'; - import reactRenderer from '@astrojs/react/server.js'; - import vueRenderer from '@astrojs/vue/server.js'; - import ReactComponent from '../components/button.jsx'; - import VueComponent from '../components/button.vue'; - - // MDX runtime is contained inside the Astro core - import mdxRenderer from 'astro/jsx/server.js'; - - // In case you need to import a custom renderer - import customRenderer from '../renderers/customRenderer.js'; - - export const GET: APIRoute = async (ctx) => { - const container = await experimental_AstroContainer.create(); - container.addServerRenderer({ renderer: reactRenderer }); - container.addServerRenderer({ renderer: vueRenderer }); - container.addServerRenderer({ renderer: customRenderer }); - // You can pass a custom name too - container.addServerRenderer({ - name: 'customRenderer', - renderer: customRenderer, - }); - const vueComponent = await container.renderToString(VueComponent); - return await container.renderToResponse(Component); - }; - ``` - -## 4.2.0 - -### Minor Changes - -- [#11144](https://github.com/withastro/astro/pull/11144) [`803dd80`](https://github.com/withastro/astro/commit/803dd8061df02138b4928442bcb76e77dcf6f5e7) Thanks [@ematipico](https://github.com/ematipico)! - The integration now exposes a function called `getContainerRenderer`, that can be used inside the Container APIs to load the relative renderer. - - ```js - import { experimental_AstroContainer as AstroContainer } from 'astro/container'; - import ReactWrapper from '../src/components/ReactWrapper.astro'; - import { loadRenderers } from 'astro:container'; - import { getContainerRenderer } from '@astrojs/react'; - - test('ReactWrapper with react renderer', async () => { - const renderers = await loadRenderers([getContainerRenderer()]); - const container = await AstroContainer.create({ - renderers, - }); - const result = await container.renderToString(ReactWrapper); - - expect(result).toContain('Counter'); - expect(result).toContain('Count: <!-- -->5'); - }); - ``` - -## 4.1.0 - -### Minor Changes - -- [#11164](https://github.com/withastro/astro/pull/11164) [`cf9b2ff`](https://github.com/withastro/astro/commit/cf9b2ff7967c4287ab26ec65fc4bb2eed525a235) Thanks [@scottnath](https://github.com/scottnath)! - Removes deprecated `template` attribute and replaces deprecated domparser function - -## 4.0.1 - -### Patch Changes - -- [#9479](https://github.com/withastro/astro/pull/9479) [`1baf0b0d3cbd0564954c2366a7278794fad6726e`](https://github.com/withastro/astro/commit/1baf0b0d3cbd0564954c2366a7278794fad6726e) Thanks [@sarah11918](https://github.com/sarah11918)! - Updates README - -## 4.0.0 - -### Major Changes - -- [#8822](https://github.com/withastro/astro/pull/8822) [`b0a71946f`](https://github.com/withastro/astro/commit/b0a71946f4320d4e76f31e990fe5821f823f0e12) Thanks [@Geoffrey-Pliez](https://github.com/Geoffrey-Pliez)! - Upgrade to Lit 3.0 - -## 3.0.3 - -### Patch Changes - -- [#9018](https://github.com/withastro/astro/pull/9018) [`23c9a30ad`](https://github.com/withastro/astro/commit/23c9a30ad859398d62a013d639b5b2716b583331) Thanks [@augustjk](https://github.com/augustjk)! - Fix hydration ordering of nested custom elements. Child components will now wait for their parents to hydrate before hydrating themselves. - -## 3.0.2 - -### Patch Changes - -- [#8826](https://github.com/withastro/astro/pull/8826) [`754c40f6e`](https://github.com/withastro/astro/commit/754c40f6ed941a61362d221915568c04ae85d6ad) Thanks [@lilnasy](https://github.com/lilnasy)! - Fixed an issue where an incompatible version of lit was installed. - -## 3.0.1 - -### Patch Changes - -- [#8737](https://github.com/withastro/astro/pull/8737) [`6f60da805`](https://github.com/withastro/astro/commit/6f60da805e0014bc50dd07bef972e91c73560c3c) Thanks [@ematipico](https://github.com/ematipico)! - Add provenance statement when publishing the library from CI - -## 3.0.0 - -### Major Changes - -- [#8188](https://github.com/withastro/astro/pull/8188) [`d0679a666`](https://github.com/withastro/astro/commit/d0679a666f37da0fca396d42b9b32bbb25d29312) Thanks [@ematipico](https://github.com/ematipico)! - Remove support for Node 16. The lowest supported version by Astro and all integrations is now v18.14.1. As a reminder, Node 16 will be deprecated on the 11th September 2023. - -- [#8179](https://github.com/withastro/astro/pull/8179) [`6011d52d3`](https://github.com/withastro/astro/commit/6011d52d38e43c3e3d52bc3bc41a60e36061b7b7) Thanks [@matthewp](https://github.com/matthewp)! - Astro 3.0 Release Candidate - -## 3.0.0-rc.1 - -### Major Changes - -- [#8179](https://github.com/withastro/astro/pull/8179) [`6011d52d3`](https://github.com/withastro/astro/commit/6011d52d38e43c3e3d52bc3bc41a60e36061b7b7) Thanks [@matthewp](https://github.com/matthewp)! - Astro 3.0 Release Candidate - -## 3.0.0-beta.0 - -### Major Changes - -- [`1eae2e3f7`](https://github.com/withastro/astro/commit/1eae2e3f7d693c9dfe91c8ccfbe606d32bf2fb81) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Remove support for Node 16. The lowest supported version by Astro and all integrations is now v18.14.1. As a reminder, Node 16 will be deprecated on the 11th September 2023. - -## 2.1.1 - -### Patch Changes - -- [#7985](https://github.com/withastro/astro/pull/7985) [`ec06dd9bb`](https://github.com/withastro/astro/commit/ec06dd9bbb29cc38e891517fbf884cb7083b3240) Thanks [@delucis](https://github.com/delucis)! - Fix formatting in Lit README - -## 2.1.0 - -### Minor Changes - -- [#7373](https://github.com/withastro/astro/pull/7373) [`0986a44dd`](https://github.com/withastro/astro/commit/0986a44ddd2b48edbe318f6fceb7f4ce4670ce05) Thanks [@matthewp](https://github.com/matthewp)! - Upgrade lit dependencies - -## 2.0.2 - -### Patch Changes - -- [#7104](https://github.com/withastro/astro/pull/7104) [`826e02890`](https://github.com/withastro/astro/commit/826e0289005f645b902375b98d5549c6a95ccafa) Thanks [@bluwy](https://github.com/bluwy)! - Specify `"files"` field to only publish necessary files - -## 2.0.1 - -### Patch Changes - -- [#6752](https://github.com/withastro/astro/pull/6752) [`c7eb0d431`](https://github.com/withastro/astro/commit/c7eb0d431032edc5d4af72726d84e1c52ef36575) Thanks [@augustjk](https://github.com/augustjk)! - Provide `renderInfo` when rendering Lit components. Fixes issue with rendering nested components. - -## 2.0.0 - -### Major Changes - -- [#6681](https://github.com/withastro/astro/pull/6681) [`4b077318f`](https://github.com/withastro/astro/commit/4b077318fbc21c4350cc21c380d96b54d302759c) Thanks [@e111077](https://github.com/e111077)! - Update to use `@lit-labs/ssr@^3` - **[BREAKING]** DOM shim required for Lit SSR has been greatly reduced. `window`, `document`, and other objects are no longer available in global. Most SSR-ready component code should not be affected but, if so, they can be fixed with optional chaining or by using the `isServer` environment checker from the `lit` package. See [lit.dev docs on authoring components for SSR].(https://lit.dev/docs/ssr/authoring/#browser-only-code) - **[BREAKING]** Adds compatibility with `lit@2.7.0` hydration behavior. Do not update if you're using `lit@2.6.1` or lower. - Includes support for template[shadowrootmode] support. - -## 1.3.0 - -### Minor Changes - -- [#6213](https://github.com/withastro/astro/pull/6213) [`afbbc4d5b`](https://github.com/withastro/astro/commit/afbbc4d5bfafc1779bac00b41c2a1cb1c90f2808) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Updated compilation settings to disable downlevelling for Node 14 - -## 1.2.1 - -### Patch Changes - -- [#6351](https://github.com/withastro/astro/pull/6351) [`26bf12ef3`](https://github.com/withastro/astro/commit/26bf12ef3c7ab874a23ac753f841f7bb329c9361) Thanks [@hrmcdonald](https://github.com/hrmcdonald)! - Render DSD attributes based on `shadowRootOptions` - -## 1.2.0 - -### Minor Changes - -- [#6111](https://github.com/withastro/astro/pull/6111) [`ec38a8921`](https://github.com/withastro/astro/commit/ec38a8921f02a275949abcababe1b8afdf8184a2) Thanks [@e111077](https://github.com/e111077)! - Implement client:only functionality in Lit and add lit to the client:only warning - -## 1.1.2 - -### Patch Changes - -- [#6080](https://github.com/withastro/astro/pull/6080) [`0db220415`](https://github.com/withastro/astro/commit/0db22041531d981a813a07f4c4e00cfb7ebddd51) Thanks [@e111077](https://github.com/e111077)! - Fixes Lit hydration not having the same reactive values as server (losing state upon hydration) - -- [#6055](https://github.com/withastro/astro/pull/6055) [`2567aa48b`](https://github.com/withastro/astro/commit/2567aa48bba8751cf7e10429555f1e85830c9169) Thanks [@e111077](https://github.com/e111077)! - Add forwards compatibility for streaming Declarative Shadow DOM - -## 1.1.1 - -### Patch Changes - -- [#5478](https://github.com/withastro/astro/pull/5478) [`1c7eef308`](https://github.com/withastro/astro/commit/1c7eef308e808aa5ed4662b53e67ec8d1b814d1f) Thanks [@nemo0](https://github.com/nemo0)! - Update READMEs for consistency - -## 1.1.0 - -### Minor Changes - -- [#5782](https://github.com/withastro/astro/pull/5782) [`1f92d64ea`](https://github.com/withastro/astro/commit/1f92d64ea35c03fec43aff64eaf704dc5a9eb30a) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Only shim fetch if not already present - -- [#5791](https://github.com/withastro/astro/pull/5791) [`f7aa1ec25`](https://github.com/withastro/astro/commit/f7aa1ec25d1584f7abd421903fbef66b1c050e2a) Thanks [@ba55ie](https://github.com/ba55ie)! - Fix Lit slotted content - -## 1.0.2 - -### Patch Changes - -- [#5782](https://github.com/withastro/astro/pull/5782) [`1f92d64ea`](https://github.com/withastro/astro/commit/1f92d64ea35c03fec43aff64eaf704dc5a9eb30a) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Only shim fetch if not already present - -- [#5776](https://github.com/withastro/astro/pull/5776) [`6a31433ed`](https://github.com/withastro/astro/commit/6a31433ed79c7f84fd3ce602005b42ad95007d84) & [#5791](https://github.com/withastro/astro/pull/5791) [`f7aa1ec25`](https://github.com/withastro/astro/commit/f7aa1ec25d1584f7abd421903fbef66b1c050e2a) Thanks [@ba55ie](https://github.com/ba55ie)! - Fix Lit slotted content - -## 1.0.2-beta.0 - -<details> -<summary>See changes in 1.0.2-beta.0</summary> - -### Patch Changes - -- [#5782](https://github.com/withastro/astro/pull/5782) [`1f92d64ea`](https://github.com/withastro/astro/commit/1f92d64ea35c03fec43aff64eaf704dc5a9eb30a) Thanks [@Princesseuh](https://github.com/Princesseuh)! - Only shim fetch if not already present - -- [#5791](https://github.com/withastro/astro/pull/5791) [`f7aa1ec25`](https://github.com/withastro/astro/commit/f7aa1ec25d1584f7abd421903fbef66b1c050e2a) Thanks [@ba55ie](https://github.com/ba55ie)! - Fix Lit slotted content - -</details> - -## 1.0.1 - -### Patch Changes - -- [#4503](https://github.com/withastro/astro/pull/4503) [`1222ab954`](https://github.com/withastro/astro/commit/1222ab9540d17e4e7e811240b8a2a039acc333cb) Thanks [@matthewp](https://github.com/matthewp)! - Allow using Lit's decorators - -## 1.0.0 - -### Major Changes - -- [`04ad44563`](https://github.com/withastro/astro/commit/04ad445632c67bdd60c1704e1e0dcbcaa27b9308) - > Astro v1.0 is out! Read the [official announcement post](https://astro.build/blog/astro-1/). - - **No breaking changes**. This package is now officially stable and compatible with `astro@1.0.0`! - -## 0.3.2 - -### Patch Changes - -- [#4009](https://github.com/withastro/astro/pull/4009) [`01ba07d8f`](https://github.com/withastro/astro/commit/01ba07d8fa7eb67530b47b8530d65906f1aebf6e) Thanks [@matthewp](https://github.com/matthewp)! - Fixes Lit compat with Vite 3.0.1 - -## 0.3.1 - -### Patch Changes - -- [#3854](https://github.com/withastro/astro/pull/3854) [`b012ee55`](https://github.com/withastro/astro/commit/b012ee55b107dea0730286263b27d83e530fad5d) Thanks [@bholmesdev](https://github.com/bholmesdev)! - [astro add] Support adapters and third party packages - -## 0.3.0 - -### Minor Changes - -- [#3652](https://github.com/withastro/astro/pull/3652) [`7373d61c`](https://github.com/withastro/astro/commit/7373d61cdcaedd64bf5fd60521b157cfa4343558) Thanks [@natemoo-re](https://github.com/natemoo-re)! - Adds support for passing named slots from `.astro` => Lit components. - - All slots are treated as Light DOM content. - -## 0.2.0 - -### Minor Changes - -- [#3625](https://github.com/withastro/astro/pull/3625) [`f5afaf24`](https://github.com/withastro/astro/commit/f5afaf24984ee7d4d6e908a7eeed17f5ca18c61e) Thanks [@matthewp](https://github.com/matthewp)! - Conform to Constructor based rendering - - This changes `@astrojs/lit` to conform to the way rendering happens in all other frameworks. Instead of using the tag name `<my-element client:load>` you use the imported constructor function, `<MyElement client:load>` like you would do with any other framework. - - Support for `tag-name` syntax had to be removed due to the fact that it was a runtime feature that was not statically analyzable. To improve build performance, we have removed all runtime based component discovery. Using the imported Constructor name allows Astro to discover what components need to be built and bundled for production without ever running your file. - -## 0.1.5 - -### Patch Changes - -- [#3511](https://github.com/withastro/astro/pull/3511) [`2fedb974`](https://github.com/withastro/astro/commit/2fedb974899b37a8d9ddabc476764a6d35d1e446) Thanks [@natemoo-re](https://github.com/natemoo-re)! - Patch Lit's server shim to allow for `sass` compatibility - -## 0.1.4 - -### Patch Changes - -- [#3484](https://github.com/withastro/astro/pull/3484) [`55820fa7`](https://github.com/withastro/astro/commit/55820fa784d6d4f66a45092321a47c8ce9de5546) Thanks [@matthewp](https://github.com/matthewp)! - Wait for DOMCOntentLoaded to polyfill in Lit - -## 0.1.3 - -### Patch Changes - -- [#3375](https://github.com/withastro/astro/pull/3375) [`fe61e469`](https://github.com/withastro/astro/commit/fe61e469b243c27781112499f151782baf9004a4) Thanks [@jdvivar](https://github.com/jdvivar)! - Added tests and fix a small edge case for when you call render with no props/attrs - -## 0.1.2 - -### Patch Changes - -- [#3164](https://github.com/withastro/astro/pull/3164) [`e85b16e2`](https://github.com/withastro/astro/commit/e85b16e2b3d846333f542139c82640de19bfd2f5) Thanks [@matthewp](https://github.com/matthewp)! - Fixes lit when running in SSR - -## 0.1.1 - -### Patch Changes - -- [`815d62f1`](https://github.com/withastro/astro/commit/815d62f151a36fef7d09590d4962ca71bda61b32) Thanks [@FredKSchott](https://github.com/FredKSchott)! - no changes. - -## 0.1.0 - -### Minor Changes - -- [#2979](https://github.com/withastro/astro/pull/2979) [`9d7a4b59`](https://github.com/withastro/astro/commit/9d7a4b59b53f8cb274266f5036d1cef841750252) Thanks [@FredKSchott](https://github.com/FredKSchott)! - Welcome to the Astro v1.0.0 Beta! Read the [official announcement](https://astro.build/blog/astro-1-beta-release/) for more details. - -## 0.0.2 - -### Patch Changes - -- [#2885](https://github.com/withastro/astro/pull/2885) [`6b004363`](https://github.com/withastro/astro/commit/6b004363f99f27e581d1e2d53a2ebff39d7afb8a) Thanks [@bholmesdev](https://github.com/bholmesdev)! - Add README across Astro built-in integrations - -* [#2847](https://github.com/withastro/astro/pull/2847) [`3b621f7a`](https://github.com/withastro/astro/commit/3b621f7a613b45983b090794fa7c015f23ed6140) Thanks [@tony-sull](https://github.com/tony-sull)! - Adds keywords to the official integrations to support discoverability on Astro's Integrations site - -## 0.0.2-next.0 - -### Patch Changes - -- [#2847](https://github.com/withastro/astro/pull/2847) [`3b621f7a`](https://github.com/withastro/astro/commit/3b621f7a613b45983b090794fa7c015f23ed6140) Thanks [@tony-sull](https://github.com/tony-sull)! - Adds keywords to the official integrations to support discoverability on Astro's Integrations site diff --git a/packages/integrations/lit/README.md b/packages/integrations/lit/README.md deleted file mode 100644 index 5d0acb5ed..000000000 --- a/packages/integrations/lit/README.md +++ /dev/null @@ -1,38 +0,0 @@ -# @astrojs/lit 🔥 - -This **[Astro integration][astro-integration]** enables server-side rendering and client-side hydration for your [Lit](https://lit.dev/) custom elements. - -## Documentation - -Read the [`@astrojs/lit` docs][docs] - -## Support - -- Get help in the [Astro Discord][discord]. Post questions in our `#support` forum, or visit our dedicated `#dev` channel to discuss current development and more! - -- Check our [Astro Integration Documentation][astro-integration] for more on integrations. - -- Submit bug reports and feature requests as [GitHub issues][issues]. - -## Contributing - -This package is maintained by Astro's Core team. You're welcome to submit an issue or PR! These links will help you get started: - -- [Contributor Manual][contributing] -- [Code of Conduct][coc] -- [Community Guide][community] - -## License - -MIT - -Copyright (c) 2023–present [Astro][astro] - -[astro]: https://astro.build/ -[docs]: https://docs.astro.build/en/guides/integrations-guide/lit/ -[contributing]: https://github.com/withastro/astro/blob/main/CONTRIBUTING.md -[coc]: https://github.com/withastro/.github/blob/main/CODE_OF_CONDUCT.md -[community]: https://github.com/withastro/.github/blob/main/COMMUNITY_GUIDE.md -[discord]: https://astro.build/chat/ -[issues]: https://github.com/withastro/astro/issues -[astro-integration]: https://docs.astro.build/en/guides/integrations-guide/ diff --git a/packages/integrations/lit/client-shim.js b/packages/integrations/lit/client-shim.js deleted file mode 100644 index c28ee5edf..000000000 --- a/packages/integrations/lit/client-shim.js +++ /dev/null @@ -1,16 +0,0 @@ -async function polyfill() { - const { hydrateShadowRoots } = await import( - '@webcomponents/template-shadowroot/template-shadowroot.js' - ); - window.addEventListener('DOMContentLoaded', () => hydrateShadowRoots(document.body), { - once: true, - }); -} - -const polyfillCheckEl = Document.parseHTMLUnsafe( - `<p><template shadowrootmode="open"></template></p>`, -).querySelector('p'); - -if (!polyfillCheckEl?.shadowRoot) { - polyfill(); -} diff --git a/packages/integrations/lit/client-shim.min.js b/packages/integrations/lit/client-shim.min.js deleted file mode 100644 index 0ec44c3fa..000000000 --- a/packages/integrations/lit/client-shim.min.js +++ /dev/null @@ -1,85 +0,0 @@ -/** @license Copyright 2020 Google LLC (BSD-3-Clause) */ -/** Bundled JS generated from "@astrojs/lit/client-shim.js" */ -var N = Object.defineProperty; -var i = (t, n) => () => (t && (n = t((t = 0))), n); -var b = (t, n) => { - for (var a in n) N(t, a, { get: n[a], enumerable: !0 }); -}; -function s() { - if (d === void 0) { - let t = document.createElement('div'); - (t.innerHTML = '<div><template shadowrootmode="open"></template></div>'), - (d = !!t.firstElementChild.shadowRoot); - } - return d; -} -var d, - m = i(() => {}); -var p, - c, - f, - u = i(() => { - (p = (t) => t.parentElement === null), - (c = (t) => t.tagName === 'TEMPLATE'), - (f = (t) => t.nodeType === Node.ELEMENT_NODE); - }); -var h, - E = i(() => { - m(); - u(); - h = (t) => { - var n; - if (s()) return; - let a = [], - e = t.firstElementChild; - for (; e !== t && e !== null; ) - if (c(e)) a.push(e), (e = e.content); - else if (e.firstElementChild !== null) e = e.firstElementChild; - else if (f(e) && e.nextElementSibling !== null) e = e.nextElementSibling; - else { - let o; - for (; e !== t && e !== null; ) - if (p(e)) { - o = a.pop(); - let r = o.parentElement, - l = o.getAttribute('shadowroot'); - if (((e = o), l === 'open' || l === 'closed')) { - let y = o.hasAttribute('shadowrootdelegatesfocus'); - try { - r.attachShadow({ mode: l, delegatesFocus: y }).append(o.content); - } catch {} - } else o = void 0; - } else { - let r = e.nextElementSibling; - if (r != null) { - (e = r), o !== void 0 && o.parentElement.removeChild(o); - break; - } - let l = - (n = e.parentElement) === null || n === void 0 ? void 0 : n.nextElementSibling; - if (l != null) { - (e = l), o !== void 0 && o.parentElement.removeChild(o); - break; - } - (e = e.parentElement), o !== void 0 && (o.parentElement.removeChild(o), (o = void 0)); - } - } - }; - }); -var w = i(() => { - E(); -}); -var v = {}; -b(v, { hasNativeDeclarativeShadowRoots: () => s, hydrateShadowRoots: () => h }); -var S = i(() => { - m(); - w(); -}); -async function g() { - let { hydrateShadowRoots: t } = await Promise.resolve().then(() => (S(), v)); - window.addEventListener('DOMContentLoaded', () => t(document.body), { once: true }); -} -var x = Document.parseHTMLUnsafe( - '<p><template shadowrootmode="open"></template></p>', -).querySelector('p'); -(!x || !x.shadowRoot) && g(); diff --git a/packages/integrations/lit/hydration-support.js b/packages/integrations/lit/hydration-support.js deleted file mode 100644 index 0f367ae0b..000000000 --- a/packages/integrations/lit/hydration-support.js +++ /dev/null @@ -1,2 +0,0 @@ -// @ts-check -import '@lit-labs/ssr-client/lit-element-hydrate-support.js'; diff --git a/packages/integrations/lit/package.json b/packages/integrations/lit/package.json deleted file mode 100644 index 6f6bcacb3..000000000 --- a/packages/integrations/lit/package.json +++ /dev/null @@ -1,73 +0,0 @@ -{ - "name": "@astrojs/lit", - "version": "4.3.0", - "description": "Use Lit components within Astro", - "type": "module", - "types": "./dist/index.d.ts", - "author": "withastro", - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/withastro/astro.git", - "directory": "packages/integrations/lit" - }, - "keywords": [ - "astro-integration", - "astro-component", - "renderer", - "lit" - ], - "bugs": "https://github.com/withastro/astro/issues", - "homepage": "https://docs.astro.build/en/guides/integrations-guide/lit/", - "exports": { - ".": "./dist/index.js", - "./server.js": { - "default": "./server.js", - "types": "./server.d.ts" - }, - "./client-shim.js": "./client-shim.js", - "./dist/client.js": "./dist/client.js", - "./hydration-support.js": "./hydration-support.js", - "./package.json": "./package.json" - }, - "files": [ - "dist", - "client-shim.js", - "client-shim.min.js", - "hydration-support.js", - "server.js", - "server.d.ts", - "server-shim.js" - ], - "scripts": { - "build": "astro-scripts build \"src/**/*.ts\" && tsc", - "build:ci": "astro-scripts build \"src/**/*.ts\"", - "dev": "astro-scripts dev \"src/**/*.ts\"", - "test": "astro-scripts test \"test/**/*.test.js\"" - }, - "dependencies": { - "@lit-labs/ssr": "^3.2.2", - "@lit-labs/ssr-client": "^1.1.7", - "@lit-labs/ssr-dom-shim": "^1.2.1", - "parse5": "^7.1.2" - }, - "overrides": { - "@lit-labs/ssr": { - "@lit-labs/ssr-client": "1.1.7" - } - }, - "devDependencies": { - "astro": "workspace:*", - "astro-scripts": "workspace:*", - "cheerio": "1.0.0", - "lit": "^3.2.0", - "sass": "^1.77.8" - }, - "peerDependencies": { - "@webcomponents/template-shadowroot": "^0.2.1", - "lit": "^3.1.0" - }, - "publishConfig": { - "provenance": true - } -} diff --git a/packages/integrations/lit/server-shim.js b/packages/integrations/lit/server-shim.js deleted file mode 100644 index d777382f2..000000000 --- a/packages/integrations/lit/server-shim.js +++ /dev/null @@ -1,35 +0,0 @@ -import { customElements as litCE, HTMLElement as litShimHTMLElement } from '@lit-labs/ssr-dom-shim'; - -// Something at build time injects document.currentScript = undefined instead of -// document.currentScript = null. This causes Sass build to fail because it -// seems to be expecting `=== null`. This set to `undefined` doesn't seem to be -// caused by Lit and only happens at build / test time, but not in dev or -// preview time. -if (globalThis.document) { - document.currentScript = null; -} - -if (globalThis.HTMLElement) { - // Seems Astro's Element shim does nothing when `.setAttribute` is called - // and subsequently `.getAttribute` is called. Causes Lit to not SSR attrs - globalThis.HTMLElement = litShimHTMLElement; -} - -// Astro seems to have a DOM shim and the only real difference that we need out -// of the Lit DOM shim is that the Lit DOM shim reads -// `HTMLElement.observedAttributes` which is meant to trigger -// `ReactiveElement.finalize()`. So this is the only thing we will re-shim since -// Lit will try to respect other global DOM shims. -globalThis.customElements = litCE; - -const litCeDefine = customElements.define; - -// We need to patch customElements.define to keep track of the tagName on the -// class itself so that we can transform JSX custom element class definition to -// a DSD string on the server, because there is no way to get the tagName from a -// CE class otherwise. Not an issue on client:only because the browser supports -// appending a class instance directly to the DOM. -customElements.define = function (tagName, Ctr) { - Ctr[Symbol.for('tagName')] = tagName; - return litCeDefine.call(this, tagName, Ctr); -}; diff --git a/packages/integrations/lit/server.d.ts b/packages/integrations/lit/server.d.ts deleted file mode 100644 index bb2f29556..000000000 --- a/packages/integrations/lit/server.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { NamedSSRLoadedRendererValue } from 'astro'; -export default NamedSSRLoadedRendererValue; diff --git a/packages/integrations/lit/server.js b/packages/integrations/lit/server.js deleted file mode 100644 index d1da3c6c9..000000000 --- a/packages/integrations/lit/server.js +++ /dev/null @@ -1,118 +0,0 @@ -// Separate import from the rest so it doesn't get re-organized after other imports -import './server-shim.js'; - -import { LitElementRenderer } from '@lit-labs/ssr/lib/lit-element-renderer.js'; -import * as parse5 from 'parse5'; - -function isCustomElementTag(name) { - return typeof name === 'string' && name.includes('-'); -} - -function getCustomElementConstructor(name) { - if (typeof customElements !== 'undefined' && isCustomElementTag(name)) { - return customElements.get(name) || null; - } else if (typeof name === 'function') { - return name; - } - return null; -} - -async function isLitElement(Component) { - const Ctr = getCustomElementConstructor(Component); - return !!Ctr?._$litElement$; -} - -async function check(Component) { - // Lit doesn't support getting a tagName from a Constructor at this time. - // So this must be a string at the moment. - return !!(await isLitElement(Component)); -} - -function* render(Component, attrs, slots) { - let tagName = Component; - if (typeof tagName !== 'string') { - tagName = Component[Symbol.for('tagName')]; - } - const instance = new LitElementRenderer(tagName); - - // LitElementRenderer creates a new element instance, so copy over. - const Ctr = getCustomElementConstructor(tagName); - let shouldDeferHydration = false; - - if (attrs) { - for (let [name, value] of Object.entries(attrs)) { - const isReactiveProperty = name in Ctr.prototype; - const isReflectedReactiveProperty = Ctr.elementProperties.get(name)?.reflect; - - // Only defer hydration if we are setting a reactive property that cannot - // be reflected / serialized as a property. - shouldDeferHydration ||= isReactiveProperty && !isReflectedReactiveProperty; - - if (isReactiveProperty) { - instance.setProperty(name, value); - } else { - instance.setAttribute(name, value); - } - } - } - - instance.connectedCallback(); - - yield `<${tagName}${shouldDeferHydration ? ' defer-hydration' : ''}`; - yield* instance.renderAttributes(); - yield `>`; - const shadowContents = instance.renderShadow({ - elementRenderers: [LitElementRenderer], - customElementInstanceStack: [instance], - customElementHostStack: [instance], - deferHydration: false, - }); - if (shadowContents !== undefined) { - const { mode = 'open', delegatesFocus } = instance.shadowRootOptions ?? {}; - // `delegatesFocus` is intentionally allowed to coerce to boolean to - // match web platform behavior. - const delegatesfocusAttr = delegatesFocus ? ' shadowrootdelegatesfocus' : ''; - yield `<template shadowroot="${mode}" shadowrootmode="${mode}"${delegatesfocusAttr}>`; - yield* shadowContents; - yield '</template>'; - } - if (slots) { - for (let [slot, value = ''] of Object.entries(slots)) { - if (slot !== 'default' && value) { - // Parse the value as a concatenated string - const fragment = parse5.parseFragment(`${value}`); - - // Add the missing slot attribute to child Element nodes - for (const node of fragment.childNodes) { - if (node.tagName && !node.attrs.some(({ name }) => name === 'slot')) { - node.attrs.push({ name: 'slot', value: slot }); - } - } - - value = parse5.serialize(fragment); - } - - yield value; - } - } - yield `</${tagName}>`; -} - -async function renderToStaticMarkup(Component, props, slots) { - let tagName = Component; - - let out = ''; - for (let chunk of render(tagName, props, slots)) { - out += chunk; - } - - return { - html: out, - }; -} - -export default { - name: '@astrojs/lit', - check, - renderToStaticMarkup, -}; diff --git a/packages/integrations/lit/src/client.ts b/packages/integrations/lit/src/client.ts deleted file mode 100644 index 9a573d8ee..000000000 --- a/packages/integrations/lit/src/client.ts +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Adds the appropriate slot attribute to each top-level node in the given HTML - * string. - * - * @example - * addSlotAttrsToHtmlString('foo', '<div>bar</div><div>baz</div>'); - * // '<div slot="foo">bar</div><div slot="foo">baz</div>' - * - * @param slotName Name of slot to apply to HTML string. - * @param html Stringified HTML that should be projected into the given slotname. - * @returns A stringified HTML string with the slot attribute applied to each top-level node. - */ -const addSlotAttrsToHtmlString = (slotName: string, html: string) => { - const templ = document.createElement('template'); - templ.innerHTML = html; - Array.from(templ.content.children).forEach((node) => { - node.setAttribute('slot', slotName); - }); - return templ.innerHTML; -}; - -export default (element: HTMLElement) => - async ( - Component: any, - props: Record<string, any>, - { default: defaultChildren, ...slotted }: { default: string; [slotName: string]: string }, - ) => { - // Get the LitElement element instance. - let component = element.children[0]; - // Check if hydration model is client:only - const isClientOnly = element.getAttribute('client') === 'only'; - - // We need to attach the element and it's children to the DOM since it's not - // SSR'd. - if (isClientOnly) { - component = new Component(); - - const otherSlottedChildren = Object.entries(slotted) - .map(([slotName, htmlStr]) => addSlotAttrsToHtmlString(slotName, htmlStr)) - .join(''); - - // defaultChildren can actually be undefined, but TS will complain if we - // type it as so, make sure we don't render undefined. - component.innerHTML = `${defaultChildren ?? ''}${otherSlottedChildren}`; - element.appendChild(component); - - // Set props bound to non-reactive properties as attributes. - for (let [name, value] of Object.entries(props)) { - if (!(name in Component.prototype)) { - component.setAttribute(name, value); - } - } - } - - // If there is no deferral of hydration, then all reactive properties are - // already serialized as reflected attributes, or no reactive props were set - // Alternatively, if hydration is client:only proceed to set props. - if (!component || !(component.hasAttribute('defer-hydration') || isClientOnly)) { - return; - } - - // Set properties on the LitElement instance for resuming hydration. - for (let [name, value] of Object.entries(props)) { - // Check if reactive property or class property. - if (name in Component.prototype) { - (component as any)[name] = value; - } - } - - // Tell LitElement to resume hydration. - component.removeAttribute('defer-hydration'); - }; diff --git a/packages/integrations/lit/src/index.ts b/packages/integrations/lit/src/index.ts deleted file mode 100644 index 94a6d683a..000000000 --- a/packages/integrations/lit/src/index.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { readFileSync } from 'node:fs'; -import type { AstroIntegration, ContainerRenderer } from 'astro'; - -function getViteConfiguration() { - return { - optimizeDeps: { - include: [ - '@astrojs/lit/dist/client.js', - '@astrojs/lit/client-shim.js', - '@astrojs/lit/hydration-support.js', - '@webcomponents/template-shadowroot/template-shadowroot.js', - '@lit-labs/ssr-client/lit-element-hydrate-support.js', - ], - exclude: ['@astrojs/lit/server.js'], - }, - ssr: { - external: ['lit-element', '@lit-labs/ssr', '@astrojs/lit', 'lit/decorators.js'], - }, - }; -} - -export function getContainerRenderer(): ContainerRenderer { - return { - name: '@astrojs/lit', - serverEntrypoint: '@astrojs/lit/server.js', - }; -} - -export default function (): AstroIntegration { - return { - name: '@astrojs/lit', - hooks: { - 'astro:config:setup': ({ updateConfig, addRenderer, injectScript }) => { - // Inject the necessary polyfills on every page (inlined for speed). - injectScript( - 'head-inline', - readFileSync(new URL('../client-shim.min.js', import.meta.url), { encoding: 'utf-8' }), - ); - // Inject the hydration code, before a component is hydrated. - injectScript('before-hydration', `import '@astrojs/lit/hydration-support.js';`); - // Add the lit renderer so that Astro can understand lit components. - addRenderer({ - name: '@astrojs/lit', - serverEntrypoint: '@astrojs/lit/server.js', - clientEntrypoint: '@astrojs/lit/dist/client.js', - }); - // Update the vite configuration. - updateConfig({ - vite: getViteConfiguration(), - }); - }, - 'astro:build:setup': ({ vite, target }) => { - if (target === 'server') { - if (!vite.ssr) { - vite.ssr = {}; - } - if (!vite.ssr.noExternal) { - vite.ssr.noExternal = []; - } - if (Array.isArray(vite.ssr.noExternal)) { - vite.ssr.noExternal.push('lit'); - } - } - }, - }, - }; -} diff --git a/packages/integrations/lit/test/sass.test.js b/packages/integrations/lit/test/sass.test.js deleted file mode 100644 index a6cbfae8b..000000000 --- a/packages/integrations/lit/test/sass.test.js +++ /dev/null @@ -1,15 +0,0 @@ -import * as assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; - -describe('check', () => { - it('should be able to load sass', async () => { - let error = null; - try { - await import(new URL('../server-shim.js', import.meta.url)); - await import('sass'); - } catch (e) { - error = e; - } - assert.equal(error, null); - }); -}); diff --git a/packages/integrations/lit/test/server.test.js b/packages/integrations/lit/test/server.test.js deleted file mode 100644 index bcecef2f6..000000000 --- a/packages/integrations/lit/test/server.test.js +++ /dev/null @@ -1,134 +0,0 @@ -import * as assert from 'node:assert/strict'; -import { describe, it } from 'node:test'; -import * as cheerio from 'cheerio'; -import { LitElement, html } from 'lit'; -// Must come after lit import because @lit/reactive-element defines -// globalThis.customElements which the server shim expects to be defined. -import server from '../server.js'; - -const { check, renderToStaticMarkup } = server; - -describe('check', () => { - it('should be false with no component', async () => { - assert.equal(await check(), false); - }); - - it('should be false with a registered non-lit component', async () => { - const tagName = 'non-lit-component'; - // Lit no longer shims HTMLElement globally, so we need to do it ourselves. - if (!globalThis.HTMLElement) { - globalThis.HTMLElement = class {}; - } - customElements.define(tagName, class TestComponent extends HTMLElement {}); - assert.equal(await check(tagName), false); - }); - - it('should be true with a registered lit component', async () => { - const tagName = 'lit-component'; - customElements.define(tagName, class extends LitElement {}); - assert.equal(await check(tagName), true); - }); -}); - -describe('renderToStaticMarkup', () => { - it('should throw error if trying to render an unregistered component', async () => { - const tagName = 'non-registrered-component'; - try { - await renderToStaticMarkup(tagName); - } catch (e) { - assert.equal(e instanceof TypeError, true); - } - }); - - it('should render empty component with default markup', async () => { - const tagName = 'nothing-component'; - customElements.define(tagName, class extends LitElement {}); - const render = await renderToStaticMarkup(tagName); - assert.deepEqual(render, { - html: `<${tagName}><template shadowroot="open" shadowrootmode="open"><!--lit-part--><!--/lit-part--></template></${tagName}>`, - }); - }); - - it('should render component with default markup', async () => { - const tagName = 'simple-component'; - customElements.define( - tagName, - class extends LitElement { - render() { - return html`<p>hola</p>`; - } - }, - ); - const render = await renderToStaticMarkup(tagName); - const $ = cheerio.load(render.html); - assert.equal($(`${tagName} template`).html().includes('<p>hola</p>'), true); - }); - - it('should render component with properties and attributes', async () => { - const tagName = 'props-and-attrs-component'; - const attr1 = 'test'; - const prop1 = 'Daniel'; - customElements.define( - tagName, - class extends LitElement { - static properties = { - prop1: { type: String }, - }; - - constructor() { - super(); - this.prop1 = 'someone'; - } - - render() { - return html`<p>Hello ${this.prop1}</p>`; - } - }, - ); - const render = await renderToStaticMarkup(tagName, { prop1, attr1 }); - const $ = cheerio.load(render.html); - assert.equal($(tagName).attr('attr1'), attr1); - assert.equal($(`${tagName} template`).text().includes(`Hello ${prop1}`), true); - }); - - it('should render nested components', async () => { - const tagName = 'parent-component'; - const childTagName = 'child-component'; - customElements.define( - childTagName, - class extends LitElement { - render() { - return html`<p>child</p>`; - } - }, - ); - customElements.define( - tagName, - class extends LitElement { - render() { - return html`<child-component></child-component>`; - } - }, - ); - const render = await renderToStaticMarkup(tagName); - const $ = cheerio.load(render.html); - assert.equal($(`${tagName} template`).text().includes('child'), true); - // Child component should have `defer-hydration` attribute so it'll only - // hydrate after the parent hydrates - assert.equal($(childTagName).attr('defer-hydration'), ''); - }); - - it('should render DSD attributes based on shadowRootOptions', async () => { - const tagName = 'shadow-root-options-component'; - customElements.define( - tagName, - class extends LitElement { - static shadowRootOptions = { ...LitElement.shadowRootOptions, delegatesFocus: true }; - }, - ); - const render = await renderToStaticMarkup(tagName); - assert.deepEqual(render, { - html: `<${tagName}><template shadowroot=\"open\" shadowrootmode=\"open\" shadowrootdelegatesfocus><!--lit-part--><!--/lit-part--></template></${tagName}>`, - }); - }); -}); diff --git a/packages/integrations/lit/tsconfig.json b/packages/integrations/lit/tsconfig.json deleted file mode 100644 index 1504b4b6d..000000000 --- a/packages/integrations/lit/tsconfig.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "../../../tsconfig.base.json", - "include": ["src"], - "compilerOptions": { - "outDir": "./dist" - } -} diff --git a/packages/integrations/markdoc/CHANGELOG.md b/packages/integrations/markdoc/CHANGELOG.md index 0884b81ba..a968e5911 100644 --- a/packages/integrations/markdoc/CHANGELOG.md +++ b/packages/integrations/markdoc/CHANGELOG.md @@ -1,5 +1,13 @@ # @astrojs/markdoc +## 1.0.0-alpha.0 + +### Patch Changes + +- Updated dependencies [[`b6fbdaa`](https://github.com/withastro/astro/commit/b6fbdaa94a9ecec706a99e1938fbf5cd028c72e0), [`89bab1e`](https://github.com/withastro/astro/commit/89bab1e70786123fbe933a9d7a1b80c9334dcc5f), [`d74617c`](https://github.com/withastro/astro/commit/d74617cbd3278feba05909ec83db2d73d57a153e), [`83a2a64`](https://github.com/withastro/astro/commit/83a2a648418ad30f4eb781d1c1b5f2d8a8ac846e), [`e90f559`](https://github.com/withastro/astro/commit/e90f5593d23043579611452a84b9e18ad2407ef9), [`2df49a6`](https://github.com/withastro/astro/commit/2df49a6fb4f6d92fe45f7429430abe63defeacd6), [`8a53517`](https://github.com/withastro/astro/commit/8a5351737d6a14fc55f1dafad8f3b04079e81af6)]: + - astro@5.0.0-alpha.0 + - @astrojs/markdown-remark@6.0.0-alpha.0 + ## 0.11.3 ### Patch Changes diff --git a/packages/integrations/markdoc/package.json b/packages/integrations/markdoc/package.json index 2314f81b9..71cce6fd0 100644 --- a/packages/integrations/markdoc/package.json +++ b/packages/integrations/markdoc/package.json @@ -1,7 +1,7 @@ { "name": "@astrojs/markdoc", "description": "Add support for Markdoc in your Astro site", - "version": "0.11.3", + "version": "1.0.0-alpha.0", "type": "module", "types": "./dist/index.d.ts", "author": "withastro", @@ -72,7 +72,7 @@ "htmlparser2": "^9.1.0" }, "peerDependencies": { - "astro": "^3.0.0 || ^4.0.0" + "astro": "^5.0.0-alpha.0" }, "devDependencies": { "@types/markdown-it": "^14.1.2", diff --git a/packages/integrations/mdx/CHANGELOG.md b/packages/integrations/mdx/CHANGELOG.md index ff85f8485..10c30fbf9 100644 --- a/packages/integrations/mdx/CHANGELOG.md +++ b/packages/integrations/mdx/CHANGELOG.md @@ -1,5 +1,15 @@ # @astrojs/mdx +## 4.0.0-alpha.0 + +### Patch Changes + +- [#11717](https://github.com/withastro/astro/pull/11717) [`423614e`](https://github.com/withastro/astro/commit/423614ebb6ddb76cc8d11f3e3b6ae111a4a82662) Thanks [@bluwy](https://github.com/bluwy)! - Fixes stack trace location when failed to parse an MDX file with frontmatter + +- Updated dependencies [[`b6fbdaa`](https://github.com/withastro/astro/commit/b6fbdaa94a9ecec706a99e1938fbf5cd028c72e0), [`89bab1e`](https://github.com/withastro/astro/commit/89bab1e70786123fbe933a9d7a1b80c9334dcc5f), [`d74617c`](https://github.com/withastro/astro/commit/d74617cbd3278feba05909ec83db2d73d57a153e), [`83a2a64`](https://github.com/withastro/astro/commit/83a2a648418ad30f4eb781d1c1b5f2d8a8ac846e), [`e90f559`](https://github.com/withastro/astro/commit/e90f5593d23043579611452a84b9e18ad2407ef9), [`2df49a6`](https://github.com/withastro/astro/commit/2df49a6fb4f6d92fe45f7429430abe63defeacd6), [`8a53517`](https://github.com/withastro/astro/commit/8a5351737d6a14fc55f1dafad8f3b04079e81af6)]: + - astro@5.0.0-alpha.0 + - @astrojs/markdown-remark@6.0.0-alpha.0 + ## 3.1.3 ### Patch Changes diff --git a/packages/integrations/mdx/package.json b/packages/integrations/mdx/package.json index 773b3bf62..61dc87170 100644 --- a/packages/integrations/mdx/package.json +++ b/packages/integrations/mdx/package.json @@ -1,7 +1,7 @@ { "name": "@astrojs/mdx", "description": "Add support for MDX pages in your Astro site", - "version": "3.1.3", + "version": "4.0.0-alpha.0", "type": "module", "types": "./dist/index.d.ts", "author": "withastro", @@ -20,6 +20,7 @@ "homepage": "https://docs.astro.build/en/guides/integrations-guide/mdx/", "exports": { ".": "./dist/index.js", + "./server.js": "./dist/server.js", "./package.json": "./package.json" }, "files": [ @@ -49,7 +50,7 @@ "vfile": "^6.0.2" }, "peerDependencies": { - "astro": "^4.8.0" + "astro": "^5.0.0-alpha.0" }, "devDependencies": { "@types/estree": "^1.0.5", diff --git a/packages/integrations/mdx/src/index.ts b/packages/integrations/mdx/src/index.ts index de29003ff..3ebfc5f31 100644 --- a/packages/integrations/mdx/src/index.ts +++ b/packages/integrations/mdx/src/index.ts @@ -8,7 +8,6 @@ import type { ContentEntryType, HookParameters, } from 'astro'; -import astroJSXRenderer from 'astro/jsx/renderer.js'; import type { Options as RemarkRehypeOptions } from 'remark-rehype'; import type { PluggableList } from 'unified'; import type { OptimizeOptions } from './rehype-optimize-static.js'; @@ -37,7 +36,7 @@ type SetupHookParams = HookParameters<'astro:config:setup'> & { export function getContainerRenderer(): ContainerRenderer { return { name: 'astro:jsx', - serverEntrypoint: 'astro/jsx/server.js', + serverEntrypoint: '@astrojs/mdx/server.js', }; } @@ -53,7 +52,10 @@ export default function mdx(partialMdxOptions: Partial<MdxOptions> = {}): AstroI const { updateConfig, config, addPageExtension, addContentEntryType, addRenderer } = params as SetupHookParams; - addRenderer(astroJSXRenderer); + addRenderer({ + name: 'astro:jsx', + serverEntrypoint: '@astrojs/mdx/server.js', + }); addPageExtension('.mdx'); addContentEntryType({ extensions: ['.mdx'], diff --git a/packages/astro/src/jsx/server.ts b/packages/integrations/mdx/src/server.ts index 73b584bae..79934eb32 100644 --- a/packages/astro/src/jsx/server.ts +++ b/packages/integrations/mdx/src/server.ts @@ -1,7 +1,7 @@ -import type { NamedSSRLoadedRendererValue } from '../@types/astro.js'; -import { AstroError, AstroUserError } from '../core/errors/errors.js'; -import { AstroJSX, jsx } from '../jsx-runtime/index.js'; -import { renderJSX } from '../runtime/server/jsx.js'; +import type { NamedSSRLoadedRendererValue } from 'astro'; +import { AstroError } from 'astro/errors'; +import { AstroJSX, jsx } from 'astro/jsx-runtime'; +import { renderJSX } from 'astro/runtime/server/index.js'; const slotName = (str: string) => str.trim().replace(/[-_]([a-z])/g, (_, w) => w.toUpperCase()); @@ -53,15 +53,14 @@ function throwEnhancedErrorIfMdxComponent(error: Error, Component: any) { // if the exception is from an mdx component // throw an error if (Component[Symbol.for('mdx-component')]) { - // if it's an AstroUserError, we don't need to re-throw, keep the original hint - if (AstroUserError.is(error)) return; - throw new AstroError({ - message: error.message, - title: error.name, - hint: `This issue often occurs when your MDX component encounters runtime errors.`, - name: error.name, - stack: error.stack, - }); + // if it's an existing AstroError, we don't need to re-throw, keep the original hint + if (AstroError.is(error)) return; + // Mimic the fields of the internal `AstroError` class (not from `astro/errors`) to + // provide better title and hint for the error overlay + (error as any).title = error.name; + (error as any).hint = + `This issue often occurs when your MDX component encounters runtime errors.`; + throw error; } } diff --git a/packages/integrations/mdx/test/mdx-vite-env-vars.test.js b/packages/integrations/mdx/test/mdx-vite-env-vars.test.js index 80a9b1cec..213386ceb 100644 --- a/packages/integrations/mdx/test/mdx-vite-env-vars.test.js +++ b/packages/integrations/mdx/test/mdx-vite-env-vars.test.js @@ -57,8 +57,8 @@ describe('MDX - Vite env vars', () => { const dataAttrDump = document.querySelector('[data-env-dump]'); assert.notEqual(dataAttrDump, null); - assert.notEqual(dataAttrDump.getAttribute('data-env-prod'), null); - assert.equal(dataAttrDump.getAttribute('data-env-dev'), null); + assert.equal(dataAttrDump.getAttribute('data-env-prod'), 'true'); + assert.equal(dataAttrDump.getAttribute('data-env-dev'), 'false'); assert.equal(dataAttrDump.getAttribute('data-env-base-url'), '/'); assert.equal(dataAttrDump.getAttribute('data-env-mode'), 'production'); }); diff --git a/packages/integrations/node/CHANGELOG.md b/packages/integrations/node/CHANGELOG.md index 738cfc367..15ee56a01 100644 --- a/packages/integrations/node/CHANGELOG.md +++ b/packages/integrations/node/CHANGELOG.md @@ -1,5 +1,12 @@ # @astrojs/node +## 9.0.0-alpha.0 + +### Patch Changes + +- Updated dependencies [[`b6fbdaa`](https://github.com/withastro/astro/commit/b6fbdaa94a9ecec706a99e1938fbf5cd028c72e0), [`89bab1e`](https://github.com/withastro/astro/commit/89bab1e70786123fbe933a9d7a1b80c9334dcc5f), [`d74617c`](https://github.com/withastro/astro/commit/d74617cbd3278feba05909ec83db2d73d57a153e), [`e90f559`](https://github.com/withastro/astro/commit/e90f5593d23043579611452a84b9e18ad2407ef9), [`2df49a6`](https://github.com/withastro/astro/commit/2df49a6fb4f6d92fe45f7429430abe63defeacd6), [`8a53517`](https://github.com/withastro/astro/commit/8a5351737d6a14fc55f1dafad8f3b04079e81af6)]: + - astro@5.0.0-alpha.0 + ## 8.3.3 ### Patch Changes diff --git a/packages/integrations/node/package.json b/packages/integrations/node/package.json index a87f26133..0df2ba55a 100644 --- a/packages/integrations/node/package.json +++ b/packages/integrations/node/package.json @@ -1,7 +1,7 @@ { "name": "@astrojs/node", "description": "Deploy your site to a Node.js server", - "version": "8.3.3", + "version": "9.0.0-alpha.0", "type": "module", "types": "./dist/index.d.ts", "author": "withastro", @@ -37,7 +37,7 @@ "server-destroy": "^1.0.1" }, "peerDependencies": { - "astro": "^4.2.0" + "astro": "^5.0.0-alpha.0" }, "devDependencies": { "@types/node": "^18.17.8", diff --git a/packages/integrations/node/test/api-route.test.js b/packages/integrations/node/test/api-route.test.js index 804a5ccf4..9743ce42d 100644 --- a/packages/integrations/node/test/api-route.test.js +++ b/packages/integrations/node/test/api-route.test.js @@ -7,7 +7,7 @@ import { createRequestAndResponse, loadFixture } from './test-utils.js'; describe('API routes', () => { /** @type {import('./test-utils').Fixture} */ let fixture; - /** @type {import('astro/src/@types/astro.js').PreviewServer} */ + /** @type {import('../../../astro/src/types/public/preview.js').PreviewServer} */ let previewServer; /** @type {URL} */ let baseUri; diff --git a/packages/integrations/svelte/CHANGELOG.md b/packages/integrations/svelte/CHANGELOG.md index 44c3295eb..a498778af 100644 --- a/packages/integrations/svelte/CHANGELOG.md +++ b/packages/integrations/svelte/CHANGELOG.md @@ -1,5 +1,12 @@ # @astrojs/svelte +## 6.0.0-alpha.0 + +### Patch Changes + +- Updated dependencies [[`b6fbdaa`](https://github.com/withastro/astro/commit/b6fbdaa94a9ecec706a99e1938fbf5cd028c72e0), [`89bab1e`](https://github.com/withastro/astro/commit/89bab1e70786123fbe933a9d7a1b80c9334dcc5f), [`d74617c`](https://github.com/withastro/astro/commit/d74617cbd3278feba05909ec83db2d73d57a153e), [`e90f559`](https://github.com/withastro/astro/commit/e90f5593d23043579611452a84b9e18ad2407ef9), [`2df49a6`](https://github.com/withastro/astro/commit/2df49a6fb4f6d92fe45f7429430abe63defeacd6), [`8a53517`](https://github.com/withastro/astro/commit/8a5351737d6a14fc55f1dafad8f3b04079e81af6)]: + - astro@5.0.0-alpha.0 + ## 5.7.0 ### Minor Changes diff --git a/packages/integrations/svelte/package.json b/packages/integrations/svelte/package.json index 5354279cb..0c0ccdba8 100644 --- a/packages/integrations/svelte/package.json +++ b/packages/integrations/svelte/package.json @@ -1,6 +1,6 @@ { "name": "@astrojs/svelte", - "version": "5.7.0", + "version": "6.0.0-alpha.0", "description": "Use Svelte components within Astro", "type": "module", "types": "./dist/index.d.ts", @@ -60,7 +60,7 @@ "vite": "^5.4.1" }, "peerDependencies": { - "astro": "^4.0.0", + "astro": "^5.0.0-alpha.0", "svelte": "^4.0.0 || ^5.0.0-next.190", "typescript": "^5.3.3" }, diff --git a/packages/integrations/tailwind/CHANGELOG.md b/packages/integrations/tailwind/CHANGELOG.md index f796b1083..cc632bfc2 100644 --- a/packages/integrations/tailwind/CHANGELOG.md +++ b/packages/integrations/tailwind/CHANGELOG.md @@ -1,5 +1,12 @@ # @astrojs/tailwind +## 6.0.0-alpha.0 + +### Patch Changes + +- Updated dependencies [[`b6fbdaa`](https://github.com/withastro/astro/commit/b6fbdaa94a9ecec706a99e1938fbf5cd028c72e0), [`89bab1e`](https://github.com/withastro/astro/commit/89bab1e70786123fbe933a9d7a1b80c9334dcc5f), [`d74617c`](https://github.com/withastro/astro/commit/d74617cbd3278feba05909ec83db2d73d57a153e), [`e90f559`](https://github.com/withastro/astro/commit/e90f5593d23043579611452a84b9e18ad2407ef9), [`2df49a6`](https://github.com/withastro/astro/commit/2df49a6fb4f6d92fe45f7429430abe63defeacd6), [`8a53517`](https://github.com/withastro/astro/commit/8a5351737d6a14fc55f1dafad8f3b04079e81af6)]: + - astro@5.0.0-alpha.0 + ## 5.1.0 ### Minor Changes diff --git a/packages/integrations/tailwind/package.json b/packages/integrations/tailwind/package.json index 6001780a1..236134069 100644 --- a/packages/integrations/tailwind/package.json +++ b/packages/integrations/tailwind/package.json @@ -1,7 +1,7 @@ { "name": "@astrojs/tailwind", "description": "Use Tailwind CSS to style your Astro site", - "version": "5.1.0", + "version": "6.0.0-alpha.0", "type": "module", "types": "./dist/index.d.ts", "author": "withastro", @@ -44,7 +44,7 @@ "vite": "^5.4.1" }, "peerDependencies": { - "astro": "^3.0.0 || ^4.0.0", + "astro": "^5.0.0-alpha.0", "tailwindcss": "^3.0.24" }, "publishConfig": { diff --git a/packages/integrations/vercel/CHANGELOG.md b/packages/integrations/vercel/CHANGELOG.md index 2fda03d95..f05d7e730 100644 --- a/packages/integrations/vercel/CHANGELOG.md +++ b/packages/integrations/vercel/CHANGELOG.md @@ -1,5 +1,43 @@ # @astrojs/vercel +## 8.0.0-alpha.0 + +### Major Changes + +- [#11714](https://github.com/withastro/astro/pull/11714) [`8a53517`](https://github.com/withastro/astro/commit/8a5351737d6a14fc55f1dafad8f3b04079e81af6) Thanks [@matthewp](https://github.com/matthewp)! - Remove support for functionPerRoute + + This change removes support for the `functionPerRoute` option both in Astro and `@astrojs/vercel`. + + This option made it so that each route got built as separate entrypoints so that they could be loaded as separate functions. The hope was that by doing this it would decrease the size of each function. However in practice routes use most of the same code, and increases in function size limitations made the potential upsides less important. + + Additionally there are downsides to functionPerRoute, such as hitting limits on the number of functions per project. The feature also never worked with some Astro features like i18n domains and request rewriting. + + Given this, the feature has been removed from Astro. + +### Minor Changes + +- [#11728](https://github.com/withastro/astro/pull/11728) [`5ea02b1`](https://github.com/withastro/astro/commit/5ea02b12fdb9b8ca45b1229bb9d04bc3d1270e0f) Thanks [@matthewp](https://github.com/matthewp)! - Deprecates the `functionPerRoute` option + + This option is now deprecated, and will be removed entirely in Astro v5.0. We suggest removing this option from your configuration as soon as you are able to: + + ```diff + import { defineConfig } from 'astro/config'; + import vercel from '@astrojs/vercel/serverless'; + + export default defineConfig({ + // ... + output: 'server', + adapter: vercel({ + - functionPerRoute: true, + }), + }); + ``` + +### Patch Changes + +- Updated dependencies [[`b6fbdaa`](https://github.com/withastro/astro/commit/b6fbdaa94a9ecec706a99e1938fbf5cd028c72e0), [`89bab1e`](https://github.com/withastro/astro/commit/89bab1e70786123fbe933a9d7a1b80c9334dcc5f), [`d74617c`](https://github.com/withastro/astro/commit/d74617cbd3278feba05909ec83db2d73d57a153e), [`e90f559`](https://github.com/withastro/astro/commit/e90f5593d23043579611452a84b9e18ad2407ef9), [`2df49a6`](https://github.com/withastro/astro/commit/2df49a6fb4f6d92fe45f7429430abe63defeacd6), [`8a53517`](https://github.com/withastro/astro/commit/8a5351737d6a14fc55f1dafad8f3b04079e81af6)]: + - astro@5.0.0-alpha.0 + ## 7.7.2 ### Patch Changes diff --git a/packages/integrations/vercel/package.json b/packages/integrations/vercel/package.json index 70fe485b2..d28fc46e9 100644 --- a/packages/integrations/vercel/package.json +++ b/packages/integrations/vercel/package.json @@ -1,7 +1,7 @@ { "name": "@astrojs/vercel", "description": "Deploy your site to Vercel", - "version": "7.7.2", + "version": "8.0.0-alpha.0", "type": "module", "author": "withastro", "license": "MIT", @@ -60,7 +60,7 @@ "web-vitals": "^3.5.2" }, "peerDependencies": { - "astro": "^4.2.0" + "astro": "^5.0.0-alpha.0" }, "devDependencies": { "astro": "workspace:*", diff --git a/packages/integrations/vercel/src/serverless/adapter.ts b/packages/integrations/vercel/src/serverless/adapter.ts index 364d2c861..cd14e25b3 100644 --- a/packages/integrations/vercel/src/serverless/adapter.ts +++ b/packages/integrations/vercel/src/serverless/adapter.ts @@ -70,12 +70,10 @@ const SUPPORTED_NODE_VERSIONS: Record< function getAdapter({ edgeMiddleware, - functionPerRoute, middlewareSecret, skewProtection, }: { edgeMiddleware: boolean; - functionPerRoute: boolean; middlewareSecret: string; skewProtection: boolean; }): AstroAdapter { @@ -86,7 +84,6 @@ function getAdapter({ args: { middlewareSecret, skewProtection }, adapterFeatures: { edgeMiddleware, - functionPerRoute, }, supportedAstroFeatures: { hybridOutput: 'stable', @@ -134,12 +131,6 @@ export interface VercelServerlessConfig { /** Whether to create the Vercel Edge middleware from an Astro middleware in your code base. */ edgeMiddleware?: boolean; - /** - * Whether to split builds into a separate function for each route. - * @deprecated `functionPerRoute` is deprecated and will be removed in the next major release of the adapter. - */ - functionPerRoute?: boolean; - /** The maximum duration (in seconds) that Serverless Functions can run before timing out. See the [Vercel documentation](https://vercel.com/docs/functions/serverless-functions/runtimes#maxduration) for the default and maximum limit for your account plan. */ maxDuration?: number; @@ -186,7 +177,6 @@ export default function vercelServerless({ imageService, imagesConfig, devImageService = 'sharp', - functionPerRoute = false, edgeMiddleware = false, maxDuration, isr = false, @@ -281,24 +271,8 @@ export default function vercelServerless({ ), }); }, - 'astro:config:done': ({ setAdapter, config, logger }) => { - if (functionPerRoute === true) { - logger.warn( - `\n` + - `\tVercel's hosting plans might have limits to the number of functions you can create.\n` + - `\tMake sure to check your plan carefully to avoid incurring additional costs.\n` + - `\tYou can set functionPerRoute: false to prevent surpassing the limit.\n`, - ); - - logger.warn( - `\n` + - `\t\`functionPerRoute\` is deprecated and will be removed in a future version of the adapter.\n`, - ); - } - - setAdapter( - getAdapter({ functionPerRoute, edgeMiddleware, middlewareSecret, skewProtection }), - ); + 'astro:config:done': ({ setAdapter, config }) => { + setAdapter(getAdapter({ edgeMiddleware, middlewareSecret, skewProtection })); _config = config; _buildTempFolder = config.build.server; diff --git a/packages/integrations/vercel/src/static/adapter.ts b/packages/integrations/vercel/src/static/adapter.ts index efe3d2da5..4e1b19d8f 100644 --- a/packages/integrations/vercel/src/static/adapter.ts +++ b/packages/integrations/vercel/src/static/adapter.ts @@ -36,7 +36,6 @@ function getAdapter(): AstroAdapter { }, adapterFeatures: { edgeMiddleware: false, - functionPerRoute: false, }, }; } diff --git a/packages/integrations/vercel/test/fixtures/basic/astro.config.mjs b/packages/integrations/vercel/test/fixtures/basic/astro.config.mjs index 942139f3d..2fba43b6e 100644 --- a/packages/integrations/vercel/test/fixtures/basic/astro.config.mjs +++ b/packages/integrations/vercel/test/fixtures/basic/astro.config.mjs @@ -2,7 +2,5 @@ import vercel from '@astrojs/vercel/serverless'; import { defineConfig } from 'astro/config'; export default defineConfig({ - adapter: vercel({ - functionPerRoute: true - }) + adapter: vercel({}) }); diff --git a/packages/integrations/vercel/test/fixtures/functionPerRoute/astro.config.mjs b/packages/integrations/vercel/test/fixtures/functionPerRoute/astro.config.mjs deleted file mode 100644 index eb2c7699e..000000000 --- a/packages/integrations/vercel/test/fixtures/functionPerRoute/astro.config.mjs +++ /dev/null @@ -1,9 +0,0 @@ -import vercel from '@astrojs/vercel/serverless'; -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - adapter: vercel({ - functionPerRoute: true - }), - output: "server" -}); diff --git a/packages/integrations/vercel/test/fixtures/functionPerRoute/package.json b/packages/integrations/vercel/test/fixtures/functionPerRoute/package.json deleted file mode 100644 index e33f178bb..000000000 --- a/packages/integrations/vercel/test/fixtures/functionPerRoute/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "@test/astro-vercel-function-per-route", - "version": "0.0.0", - "private": true, - "dependencies": { - "@astrojs/vercel": "workspace:*", - "astro": "workspace:*" - } -} diff --git a/packages/integrations/vercel/test/fixtures/functionPerRoute/src/pages/one.astro b/packages/integrations/vercel/test/fixtures/functionPerRoute/src/pages/one.astro deleted file mode 100644 index 0c7fb90a7..000000000 --- a/packages/integrations/vercel/test/fixtures/functionPerRoute/src/pages/one.astro +++ /dev/null @@ -1,8 +0,0 @@ -<html> - <head> - <title>One</title> - </head> - <body> - <h1>One</h1> - </body> -</html> diff --git a/packages/integrations/vercel/test/fixtures/functionPerRoute/src/pages/prerender.astro b/packages/integrations/vercel/test/fixtures/functionPerRoute/src/pages/prerender.astro deleted file mode 100644 index c61b83a97..000000000 --- a/packages/integrations/vercel/test/fixtures/functionPerRoute/src/pages/prerender.astro +++ /dev/null @@ -1,12 +0,0 @@ ---- -export const prerender = true; ---- - -<html> - <head> - <title>Prerendered Page</title> - </head> - <body> - <h1>Prerendered Page</h1> - </body> -</html> diff --git a/packages/integrations/vercel/test/fixtures/functionPerRoute/src/pages/two.astro b/packages/integrations/vercel/test/fixtures/functionPerRoute/src/pages/two.astro deleted file mode 100644 index e7ba9910e..000000000 --- a/packages/integrations/vercel/test/fixtures/functionPerRoute/src/pages/two.astro +++ /dev/null @@ -1,8 +0,0 @@ -<html> - <head> - <title>Two</title> - </head> - <body> - <h1>Two</h1> - </body> -</html> diff --git a/packages/integrations/vercel/test/fixtures/serverless-with-dynamic-routes/astro.config.mjs b/packages/integrations/vercel/test/fixtures/serverless-with-dynamic-routes/astro.config.mjs index 3132bfc53..4d8f76288 100644 --- a/packages/integrations/vercel/test/fixtures/serverless-with-dynamic-routes/astro.config.mjs +++ b/packages/integrations/vercel/test/fixtures/serverless-with-dynamic-routes/astro.config.mjs @@ -5,7 +5,6 @@ export default defineConfig({ adapter: vercel({ // Pass some value to make sure it doesn't error out includeFiles: ['included.js'], - functionPerRoute: true, }), output: 'server' }); diff --git a/packages/integrations/vercel/test/serverless-with-dynamic-routes.test.js b/packages/integrations/vercel/test/serverless-with-dynamic-routes.test.js index 3f9613834..7eac7e875 100644 --- a/packages/integrations/vercel/test/serverless-with-dynamic-routes.test.js +++ b/packages/integrations/vercel/test/serverless-with-dynamic-routes.test.js @@ -17,11 +17,6 @@ describe('Serverless with dynamic routes', () => { it('build successful', async () => { assert.ok(await fixture.readFile('../.vercel/output/static/index.html')); - assert.ok( - await fixture.readFile('../.vercel/output/functions/[id]/index.astro.func/.vc-config.json'), - ); - assert.ok( - await fixture.readFile('../.vercel/output/functions/api/[id].js.func/.vc-config.json'), - ); + assert.ok(await fixture.readFile('../.vercel/output/functions/_render.func/.vc-config.json')); }); }); diff --git a/packages/integrations/vercel/test/split.test.js b/packages/integrations/vercel/test/split.test.js deleted file mode 100644 index 4105db7fc..000000000 --- a/packages/integrations/vercel/test/split.test.js +++ /dev/null @@ -1,32 +0,0 @@ -import assert from 'node:assert/strict'; -import { before, describe, it } from 'node:test'; -import { loadFixture } from './test-utils.js'; - -describe('build: split', () => { - /** @type {import('./test-utils').Fixture} */ - let fixture; - - before(async () => { - fixture = await loadFixture({ - root: './fixtures/functionPerRoute/', - output: 'server', - }); - await fixture.build(); - }); - - it('creates separate functions for non-prerendered pages', async () => { - const files = await fixture.readdir('../.vercel/output/functions/'); - assert.equal(files.length, 3); - assert.equal(files.includes('prerender.astro.func'), false); - }); - - it('creates the route definitions in the config.json', async () => { - const json = await fixture.readFile('../.vercel/output/config.json'); - const config = JSON.parse(json); - assert.equal(config.routes.length, 5); - assert.equal( - config.routes.some((route) => route.dest === 'prerender.astro'), - false, - ); - }); -}); diff --git a/packages/integrations/vue/CHANGELOG.md b/packages/integrations/vue/CHANGELOG.md index fd9c71e04..88ff9204e 100644 --- a/packages/integrations/vue/CHANGELOG.md +++ b/packages/integrations/vue/CHANGELOG.md @@ -1,5 +1,12 @@ # @astrojs/vue +## 5.0.0-alpha.0 + +### Patch Changes + +- Updated dependencies [[`b6fbdaa`](https://github.com/withastro/astro/commit/b6fbdaa94a9ecec706a99e1938fbf5cd028c72e0), [`89bab1e`](https://github.com/withastro/astro/commit/89bab1e70786123fbe933a9d7a1b80c9334dcc5f), [`d74617c`](https://github.com/withastro/astro/commit/d74617cbd3278feba05909ec83db2d73d57a153e), [`e90f559`](https://github.com/withastro/astro/commit/e90f5593d23043579611452a84b9e18ad2407ef9), [`2df49a6`](https://github.com/withastro/astro/commit/2df49a6fb4f6d92fe45f7429430abe63defeacd6), [`8a53517`](https://github.com/withastro/astro/commit/8a5351737d6a14fc55f1dafad8f3b04079e81af6)]: + - astro@5.0.0-alpha.0 + ## 4.5.0 ### Minor Changes diff --git a/packages/integrations/vue/package.json b/packages/integrations/vue/package.json index ae7467ac2..d66c36aad 100644 --- a/packages/integrations/vue/package.json +++ b/packages/integrations/vue/package.json @@ -1,6 +1,6 @@ { "name": "@astrojs/vue", - "version": "4.5.0", + "version": "5.0.0-alpha.0", "description": "Use Vue components within Astro", "type": "module", "types": "./dist/index.d.ts", @@ -58,7 +58,7 @@ "vue": "^3.4.38" }, "peerDependencies": { - "astro": "^4.0.0", + "astro": "^5.0.0-alpha.0", "vue": "^3.2.30" }, "engines": { diff --git a/packages/markdown/remark/CHANGELOG.md b/packages/markdown/remark/CHANGELOG.md index 73bab0b25..0f0ef4bb8 100644 --- a/packages/markdown/remark/CHANGELOG.md +++ b/packages/markdown/remark/CHANGELOG.md @@ -1,5 +1,16 @@ # @astrojs/markdown-remark +## 6.0.0-alpha.0 + +### Major Changes + +- [#11661](https://github.com/withastro/astro/pull/11661) [`83a2a64`](https://github.com/withastro/astro/commit/83a2a648418ad30f4eb781d1c1b5f2d8a8ac846e) Thanks [@bluwy](https://github.com/bluwy)! - Renames the following CSS variables theme color token names to better align with the Shiki v1 defaults: + + - `--astro-code-color-text` => `--astro-code-foreground` + - `--astro-code-color-background` => `--astro-code-background` + + You can perform a global find and replace in your project to migrate to the new token names. + ## 5.2.0 ### Minor Changes diff --git a/packages/markdown/remark/package.json b/packages/markdown/remark/package.json index 2bb99500f..82d928b85 100644 --- a/packages/markdown/remark/package.json +++ b/packages/markdown/remark/package.json @@ -1,6 +1,6 @@ { "name": "@astrojs/markdown-remark", - "version": "5.2.0", + "version": "6.0.0-alpha.0", "type": "module", "author": "withastro", "license": "MIT", diff --git a/packages/markdown/remark/src/shiki.ts b/packages/markdown/remark/src/shiki.ts index 0028ec927..011431e50 100644 --- a/packages/markdown/remark/src/shiki.ts +++ b/packages/markdown/remark/src/shiki.ts @@ -5,7 +5,6 @@ import { getHighlighter, isSpecialLang, } from 'shiki'; -import { visit } from 'unist-util-visit'; import type { ShikiConfig } from './types.js'; export interface ShikiHighlighter { @@ -23,16 +22,6 @@ export interface ShikiHighlighter { ): Promise<string>; } -// TODO: Remove this special replacement in Astro 5 -const ASTRO_COLOR_REPLACEMENTS: Record<string, string> = { - '--astro-code-foreground': '--astro-code-color-text', - '--astro-code-background': '--astro-code-color-background', -}; -const COLOR_REPLACEMENT_REGEX = new RegExp( - `${Object.keys(ASTRO_COLOR_REPLACEMENTS).join('|')}`, - 'g', -); - let _cssVariablesTheme: ReturnType<typeof createCssVariablesTheme>; const cssVariablesTheme = () => _cssVariablesTheme ?? @@ -145,21 +134,6 @@ export async function createShikiHighlighter({ return node.children[0] as typeof node; } }, - root(node) { - if (Object.values(themes).length) { - return; - } - - const themeName = typeof theme === 'string' ? theme : theme.name; - if (themeName === 'css-variables') { - // Replace special color tokens to CSS variables - visit(node as any, 'element', (child) => { - if (child.properties?.style) { - child.properties.style = replaceCssVariables(child.properties.style); - } - }); - } - }, }, ...transformers, ], @@ -171,7 +145,3 @@ export async function createShikiHighlighter({ function normalizePropAsString(value: Properties[string]): string | null { return Array.isArray(value) ? value.join(' ') : (value as string | null); } - -function replaceCssVariables(str: string) { - return str.replace(COLOR_REPLACEMENT_REGEX, (match) => ASTRO_COLOR_REPLACEMENTS[match] || match); -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 633acc7af..4563fdae5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -116,13 +116,13 @@ importers: examples/basics: dependencies: astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro examples/blog: dependencies: '@astrojs/mdx': - specifier: ^3.1.3 + specifier: ^4.0.0-alpha.0 version: link:../../packages/integrations/mdx '@astrojs/rss': specifier: ^4.0.7 @@ -131,13 +131,13 @@ importers: specifier: ^3.1.6 version: link:../../packages/integrations/sitemap astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro examples/component: devDependencies: astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro examples/container-with-vitest: @@ -146,7 +146,7 @@ importers: specifier: ^3.6.2 version: link:../../packages/integrations/react astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro react: specifier: ^18.3.1 @@ -177,24 +177,9 @@ importers: specifier: ^3.14.1 version: 3.14.1 astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro - examples/framework-lit: - dependencies: - '@astrojs/lit': - specifier: ^4.3.0 - version: link:../../packages/integrations/lit - '@webcomponents/template-shadowroot': - specifier: ^0.2.1 - version: 0.2.1 - astro: - specifier: ^4.14.2 - version: link:../../packages/astro - lit: - specifier: ^3.2.0 - version: 3.2.0 - examples/framework-multiple: dependencies: '@astrojs/preact': @@ -207,10 +192,10 @@ importers: specifier: ^4.4.1 version: link:../../packages/integrations/solid '@astrojs/svelte': - specifier: ^5.7.0 + specifier: ^6.0.0-alpha.0 version: link:../../packages/integrations/svelte '@astrojs/vue': - specifier: ^4.5.0 + specifier: ^5.0.0-alpha.0 version: link:../../packages/integrations/vue '@types/react': specifier: ^18.3.3 @@ -219,7 +204,7 @@ importers: specifier: ^18.3.0 version: 18.3.0 astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro preact: specifier: ^10.23.2 @@ -249,7 +234,7 @@ importers: specifier: ^1.3.0 version: 1.3.0(preact@10.23.2) astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro preact: specifier: ^10.23.2 @@ -267,7 +252,7 @@ importers: specifier: ^18.3.0 version: 18.3.0 astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro react: specifier: ^18.3.1 @@ -282,7 +267,7 @@ importers: specifier: ^4.4.1 version: link:../../packages/integrations/solid astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro solid-js: specifier: ^1.8.21 @@ -291,10 +276,10 @@ importers: examples/framework-svelte: dependencies: '@astrojs/svelte': - specifier: ^5.7.0 + specifier: ^6.0.0-alpha.0 version: link:../../packages/integrations/svelte astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro svelte: specifier: ^4.2.18 @@ -303,10 +288,10 @@ importers: examples/framework-vue: dependencies: '@astrojs/vue': - specifier: ^4.5.0 + specifier: ^5.0.0-alpha.0 version: link:../../packages/integrations/vue astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro vue: specifier: ^3.4.38 @@ -315,25 +300,25 @@ importers: examples/hackernews: dependencies: '@astrojs/node': - specifier: ^8.3.3 + specifier: ^9.0.0-alpha.0 version: link:../../packages/integrations/node astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro examples/integration: devDependencies: astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro examples/middleware: dependencies: '@astrojs/node': - specifier: ^8.3.3 + specifier: ^9.0.0-alpha.0 version: link:../../packages/integrations/node astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro html-minifier: specifier: ^4.0.0 @@ -346,31 +331,31 @@ importers: examples/minimal: dependencies: astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro examples/non-html-pages: dependencies: astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro examples/portfolio: dependencies: astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro examples/server-islands: devDependencies: '@astrojs/node': - specifier: ^8.3.3 + specifier: ^9.0.0-alpha.0 version: link:../../packages/integrations/node '@astrojs/react': specifier: ^3.6.2 version: link:../../packages/integrations/react '@astrojs/tailwind': - specifier: ^5.1.0 + specifier: ^6.0.0-alpha.0 version: link:../../packages/integrations/tailwind '@fortawesome/fontawesome-free': specifier: ^6.6.0 @@ -385,7 +370,7 @@ importers: specifier: ^18.3.0 version: 18.3.0 astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro postcss: specifier: ^8.4.41 @@ -403,13 +388,13 @@ importers: examples/ssr: dependencies: '@astrojs/node': - specifier: ^8.3.3 + specifier: ^9.0.0-alpha.0 version: link:../../packages/integrations/node '@astrojs/svelte': - specifier: ^5.7.0 + specifier: ^6.0.0-alpha.0 version: link:../../packages/integrations/svelte astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro svelte: specifier: ^4.2.18 @@ -418,7 +403,7 @@ importers: examples/starlog: dependencies: astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro sass: specifier: ^1.77.8 @@ -430,37 +415,37 @@ importers: examples/toolbar-app: devDependencies: astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro examples/view-transitions: devDependencies: '@astrojs/node': - specifier: ^8.3.3 + specifier: ^9.0.0-alpha.0 version: link:../../packages/integrations/node '@astrojs/tailwind': - specifier: ^5.1.0 + specifier: ^6.0.0-alpha.0 version: link:../../packages/integrations/tailwind astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro examples/with-markdoc: dependencies: '@astrojs/markdoc': - specifier: ^0.11.3 + specifier: ^1.0.0-alpha.0 version: link:../../packages/integrations/markdoc astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro examples/with-markdown-plugins: dependencies: '@astrojs/markdown-remark': - specifier: ^5.2.0 + specifier: ^6.0.0-alpha.0 version: link:../../packages/markdown/remark astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro hast-util-select: specifier: ^6.0.2 @@ -481,19 +466,19 @@ importers: examples/with-markdown-shiki: dependencies: astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro examples/with-mdx: dependencies: '@astrojs/mdx': - specifier: ^3.1.3 + specifier: ^4.0.0-alpha.0 version: link:../../packages/integrations/mdx '@astrojs/preact': specifier: ^3.5.1 version: link:../../packages/integrations/preact astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro preact: specifier: ^10.23.2 @@ -508,7 +493,7 @@ importers: specifier: ^0.5.2 version: 0.5.2(nanostores@0.11.2)(preact@10.23.2) astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro nanostores: specifier: ^0.11.2 @@ -520,16 +505,16 @@ importers: examples/with-tailwindcss: dependencies: '@astrojs/mdx': - specifier: ^3.1.3 + specifier: ^4.0.0-alpha.0 version: link:../../packages/integrations/mdx '@astrojs/tailwind': - specifier: ^5.1.0 + specifier: ^6.0.0-alpha.0 version: link:../../packages/integrations/tailwind '@types/canvas-confetti': specifier: ^1.6.4 version: 1.6.4 astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro autoprefixer: specifier: ^10.4.20 @@ -547,7 +532,7 @@ importers: examples/with-vitest: dependencies: astro: - specifier: ^4.14.2 + specifier: ^5.0.0-alpha.0 version: link:../../packages/astro vitest: specifier: ^2.0.5 @@ -1176,21 +1161,6 @@ importers: specifier: workspace:* version: link:../../.. - packages/astro/e2e/fixtures/lit-component: - dependencies: - '@astrojs/lit': - specifier: workspace:* - version: link:../../../../integrations/lit - '@webcomponents/template-shadowroot': - specifier: ^0.2.1 - version: 0.2.1 - astro: - specifier: workspace:* - version: link:../../.. - lit: - specifier: ^3.2.0 - version: 3.2.0 - packages/astro/e2e/fixtures/multiple-frameworks: dependencies: '@webcomponents/template-shadowroot': @@ -1218,9 +1188,6 @@ importers: specifier: ^3.4.38 version: 3.4.38(typescript@5.5.4) devDependencies: - '@astrojs/lit': - specifier: workspace:* - version: link:../../../../integrations/lit '@astrojs/preact': specifier: workspace:* version: link:../../../../integrations/preact @@ -3367,21 +3334,6 @@ importers: specifier: workspace:* version: link:../../.. - packages/astro/test/fixtures/lit-element: - dependencies: - '@astrojs/lit': - specifier: workspace:* - version: link:../../../../integrations/lit - '@webcomponents/template-shadowroot': - specifier: ^0.2.1 - version: 0.2.1 - astro: - specifier: workspace:* - version: link:../../.. - lit: - specifier: ^3.2.0 - version: 3.2.0 - packages/astro/test/fixtures/markdown: dependencies: '@astrojs/preact': @@ -4544,37 +4496,6 @@ importers: packages/integrations/cloudflare: {} - packages/integrations/lit: - dependencies: - '@lit-labs/ssr': - specifier: ^3.2.2 - version: 3.2.2 - '@lit-labs/ssr-client': - specifier: ^1.1.7 - version: 1.1.7 - '@lit-labs/ssr-dom-shim': - specifier: ^1.2.1 - version: 1.2.1 - parse5: - specifier: ^7.1.2 - version: 7.1.2 - devDependencies: - astro: - specifier: workspace:* - version: link:../../astro - astro-scripts: - specifier: workspace:* - version: link:../../../scripts - cheerio: - specifier: 1.0.0 - version: 1.0.0 - lit: - specifier: ^3.2.0 - version: 3.2.0 - sass: - specifier: ^1.77.8 - version: 1.77.8 - packages/integrations/markdoc: dependencies: '@astrojs/internal-helpers': @@ -5464,15 +5385,6 @@ importers: specifier: workspace:* version: link:../../../../../astro - packages/integrations/vercel/test/fixtures/functionPerRoute: - dependencies: - '@astrojs/vercel': - specifier: workspace:* - version: link:../../.. - astro: - specifier: workspace:* - version: link:../../../../../astro - packages/integrations/vercel/test/fixtures/image: dependencies: '@astrojs/vercel': @@ -7092,16 +7004,9 @@ packages: cpu: [x64] os: [win32] - '@lit-labs/ssr-client@1.1.7': - resolution: {integrity: sha512-VvqhY/iif3FHrlhkzEPsuX/7h/NqnfxLwVf0p8ghNIlKegRyRqgeaJevZ57s/u/LiFyKgqksRP5n+LmNvpxN+A==} - '@lit-labs/ssr-dom-shim@1.2.1': resolution: {integrity: sha512-wx4aBmgeGvFmOKucFKY+8VFJSYZxs9poN3SDNQFF6lT6NrQUnHiPB2PWz2sc4ieEcAaYYzN+1uWahEeTq2aRIQ==} - '@lit-labs/ssr@3.2.2': - resolution: {integrity: sha512-He5TzeNPM9ECmVpgXRYmVlz0UA5YnzHlT43kyLi2Lu6mUidskqJVonk9W5K699+2DKhoXp8Ra4EJmHR6KrcW1Q==} - engines: {node: '>=13.9.0'} - '@lit/reactive-element@2.0.4': resolution: {integrity: sha512-GFn91inaUa2oHLak8awSIigYz0cU0Payr1rcFsrkf5OJ5eSPxElyZfKh0f2p9FsTiZWXQdWGJeXZICEfXXYSXQ==} @@ -7155,9 +7060,6 @@ packages: '@oslojs/encoding@0.4.1': resolution: {integrity: sha512-hkjo6MuIK/kQR5CrGNdAPZhS01ZCXuWDRJ187zh6qqF2+yMHZpD9fAYpX8q2bOO6Ryhl3XpCT6kUX76N8hhm4Q==} - '@parse5/tools@0.3.0': - resolution: {integrity: sha512-zxRyTHkqb7WQMV8kTNBKWb1BeOFUKXBXTBWuxg9H9hfvQB3IwP6Iw2U75Ia5eyRxPNltmY7E8YAlz6zWwUnjKg==} - '@pkgjs/parseargs@0.11.0': resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} engines: {node: '>=14'} @@ -7459,9 +7361,6 @@ packages: '@types/node@12.20.55': resolution: {integrity: sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ==} - '@types/node@16.18.96': - resolution: {integrity: sha512-84iSqGXoO+Ha16j8pRZ/L90vDMKX04QTYMTfYeE1WrjWaZXuchBehGUZEpNgx7JnmlrIHdnABmpjrQjhCnNldQ==} - '@types/node@17.0.45': resolution: {integrity: sha512-w+tIMs3rq2afQdsPJlODhoUEKzFP1ayaoyl1CcnwtIlsVe7K7bA1NGm4s3PraqTLlXnbIN84zuBlxBWo1u9BLw==} @@ -8555,10 +8454,6 @@ packages: encoding-sniffer@0.2.0: resolution: {integrity: sha512-ju7Wq1kg04I3HtiYIOrUrdfdDvkyO9s5XM8QAj/bN61Yo/Vb4vgJxy5vi4Yxk01gWHbrofpPtpxM8bKger9jhg==} - enhanced-resolve@5.16.0: - resolution: {integrity: sha512-O+QWCviPNSSLAD9Ucn8Awv+poAkqn3T1XY5/N7kR7rQO9yfSGWkYZDwpJ+iKF7B8rxaQKWngSqACpgzeapSyoA==} - engines: {node: '>=10.13.0'} - enquirer@2.4.1: resolution: {integrity: sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ==} engines: {node: '>=8.6'} @@ -10943,10 +10838,6 @@ packages: engines: {node: '>=14.0.0'} hasBin: true - tapable@2.2.1: - resolution: {integrity: sha512-GNzQvQTOIP6RyTfE2Qxb8ZVlNmw0n88vp1szwWRimP02mnTsx3Wtn5qRdqY9w2XduFNUgvOwhNnQsjwCp+kqaQ==} - engines: {node: '>=6'} - tar@6.2.1: resolution: {integrity: sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==} engines: {node: '>=10'} @@ -12849,28 +12740,8 @@ snapshots: '@libsql/win32-x64-msvc@0.4.1': optional: true - '@lit-labs/ssr-client@1.1.7': - dependencies: - '@lit/reactive-element': 2.0.4 - lit: 3.2.0 - lit-html: 3.2.0 - '@lit-labs/ssr-dom-shim@1.2.1': {} - '@lit-labs/ssr@3.2.2': - dependencies: - '@lit-labs/ssr-client': 1.1.7 - '@lit-labs/ssr-dom-shim': 1.2.1 - '@lit/reactive-element': 2.0.4 - '@parse5/tools': 0.3.0 - '@types/node': 16.18.96 - enhanced-resolve: 5.16.0 - lit: 3.2.0 - lit-element: 4.1.0 - lit-html: 3.2.0 - node-fetch: 3.3.2 - parse5: 7.1.2 - '@lit/reactive-element@2.0.4': dependencies: '@lit-labs/ssr-dom-shim': 1.2.1 @@ -12961,10 +12832,6 @@ snapshots: '@oslojs/encoding@0.4.1': {} - '@parse5/tools@0.3.0': - dependencies: - parse5: 7.1.2 - '@pkgjs/parseargs@0.11.0': optional: true @@ -13264,8 +13131,6 @@ snapshots: '@types/node@12.20.55': {} - '@types/node@16.18.96': {} - '@types/node@17.0.45': {} '@types/node@18.19.31': @@ -14398,11 +14263,6 @@ snapshots: iconv-lite: 0.6.3 whatwg-encoding: 3.1.1 - enhanced-resolve@5.16.0: - dependencies: - graceful-fs: 4.2.11 - tapable: 2.2.1 - enquirer@2.4.1: dependencies: ansi-colors: 4.1.3 @@ -17467,8 +17327,6 @@ snapshots: transitivePeerDependencies: - ts-node - tapable@2.2.1: {} - tar@6.2.1: dependencies: chownr: 2.0.0 |