feat: fetchable dev environments
This PR changes the dev, preview, build analysis and prerender to run inside of the configured Vite SSR environment. This required the following fundamental changes:
1. Avoiding Node.js imports in the runtime
- Some of our utilities had to be moved to a separate file to avoid importing Node.js modules. Others had to be recreated to avoid adding another dependency if we want the same functionality in a Node-agnostic environment.
node:fsis a requirement but we import it in the main process instead and communicate the results back to the Vite SSR environment.- We can't use
AsyncLocalStorage.enterWithbecause it's a Node.js-only experimental API
2. Replacing Vite's ssrLoadModule
The Vite docs recommendation is to create a ModuleRunner or the RunnableDevEnvironment instance to achieve a similar functionality but these don't work with Cloudflare's environment. There's also no strict contract for environments to make these available to us so they can't be relied on. We solve this in two different ways:
- We use Vite's
import.meta.hot.onin the SSR environment to listen for events from the main process, compute the result, and send it back. - Instead of importing the
Serverclass from the build output in the main process, we spin up a Vite development server with the build output but proxy theServerclass by intercepting module resolution with Vite'sresolveIdhook. Starting a dev server and sending a request or HMR event seems to be the only way to run a module in the environment.
3. Communication between the main process (where Vite runs) and the SSR environment (where user code runs)
The two points before this makes this a requirement. Now we'll detail the different types of communication that exist as a result:
One way communication
- Main process to SSR environment. e.g., when we detect a server asset import from a Vite hook, we can update the server manifest in the environment using
environments.ssr.hot.send. This helps us retain synchronous access to the filesystem from a non-Node environment such as checking if a filename exists as a key in the server assets map. We can also construct virtual modules with serialised data that the can be imported and accessed in the environment. - SSR environment to main process. e.g., when an error occurs on the server, we use
import.meta.hot.sendso that the main process can then create a Vite error overlay in the browser. This replaces ourloudSsrLoadModuleutility.
Two way communication
- Main process to SSR environment and back to the main process. Previously we could just run
ssrLoadModuleto run some code in Vite's pipeline and get a result back. Now, we have to ensure the SSR environment has animport.meta.hot.onevent listener attached, emit an event, compute in the environment, and receive the results back in the main process throughenvironments.ssr.hot.onandPromise.withResolversto await the result. This is used for retrieving remote function info, etc. Alternatively, we can also proxy theServerclass during analysis and prerendering to respond with our environment computed result as mentioned earlier. - SSR environment to main process and back to the environment. This requires the operation to be asynchronous if it wasn't already. We also can't re-use the two-way
import.meta.hotapproach above because Cloudflare's workerd doesn't like responding to requests from a context created byimport.meta.hot.on. Therefore, we usefetchto send a request to the running Vite dev server, configure the Vite dev server using theconfigureServerhook to intercept the request viavite.middlewares.use, and respond with the computed result. This is primarily used for getting CSS to inline to avoid FOUC during dev, finding out which param matchers exist from the filesystem, or even checking if a feature should be allowed by theadapter.supportsfunction which we can't serialise.
Most of the import.meta.hot and fetch style communication requires serialising and deserialising data using devalue.
Future PRs
- adapter-static environment that uses
sirvon the build output instead of running the SSR server - adapter-node environment that allows using a custom entry point similar to after building
- adapter-netlify environment to run things in serverless/edge mode?
Please don't delete this checklist! Before submitting the PR, please make sure you do the following:
- [x] It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
- [x] This message body should clearly illustrate what problems it solves.
- [ ] Ideally, include a test that fails without this PR but passes with it.
Tests
- [x] Run the tests with
pnpm testand lint the project withpnpm lintandpnpm check
Changesets
- [x] If your PR makes a change that should be noted in one or more packages' changelogs, generate a changeset by running
pnpm changesetand following the prompts. Changesets that add features should beminorand those that fix bugs should bepatch. Please prefix changeset messages withfeat:,fix:, orchore:.
Edits
- [x] Please ensure that 'Allow edits from maintainers' is checked. PRs without this option may be closed.
🦋 Changeset detected
Latest commit: 9629cfc2ca30288b45d9f7c72e93096244b766a1
The changes in this PR will be included in the next version bump.
This PR includes changesets to release 1 package
| Name | Type |
|---|---|
| @sveltejs/kit | Major |
Not sure what this means? Click here to learn what changesets are.
Click here if you're a maintainer who wants to add another changeset to this PR
Preview: https://svelte-dev-git-preview-kit-15574-svelte.vercel.app/
/autofix
/autofix
Looking pretty good! Occurs to me we should probably try and merge main into version-3 before merging this, just to keep the merge conflicts slightly less unmanageable...
- Instead of importing the
Serverclass from the build output in the main process, we spin up a Vite development server with the build output but proxy theServerclass by intercepting module resolution with Vite'sresolveIdhook. Starting a dev server and sending a request or HMR event seems to be the only way to run a module in the environment.
Interested how you landed on this. Did you try the approach of building a separate environment for the analysis/prerender phases and running it using the preview server rather than the dev server?
- Instead of importing the
Serverclass from the build output in the main process, we spin up a Vite development server with the build output but proxy theServerclass by intercepting module resolution with Vite'sresolveIdhook. Starting a dev server and sending a request or HMR event seems to be the only way to run a module in the environment.Interested how you landed on this. Did you try the approach of building a separate environment for the analysis/prerender phases and running it using the preview server rather than the dev server?
I did try creating a separate environment but it was a little easier at the time to reuse the ssr environment namespace without having to worry about copying over the ssr environment config settings. Maybe I’ll try to revisit this to get the Cloudflare prerender worker working
I also wasn’t sure how to create a Vite preview server since the Vite createServer function errors when not using the 'serve' command as an option. I just found the preview function so I think we’ll use that instead 🤦🏻♂️ https://vite.dev/guide/api-javascript#preview this whole time I was looking for something like createPreviewServer
- Instead of importing the
Serverclass from the build output in the main process, we spin up a Vite development server with the build output but proxy theServerclass by intercepting module resolution with Vite'sresolveIdhook. Starting a dev server and sending a request or HMR event seems to be the only way to run a module in the environment.Interested how you landed on this. Did you try the approach of building a separate environment for the analysis/prerender phases and running it using the preview server rather than the dev server?
I did try creating a separate environment but it was a little easier at the time to reuse the ssr environment namespace without having to worry about copying over the ssr environment config settings. Maybe I’ll try to revisit this to get the Cloudflare prerender worker working
I also wasn’t sure how to create a Vite preview server since the Vite
createServerfunction errors when not using the 'serve' command as an option. I just found thepreviewfunction so I think we’ll use that instead 🤦🏻♂️ https://vite.dev/guide/api-javascript#preview this whole time I was looking for something likecreatePreviewServer
Don't worry about changing if the approach you've gone with works, of course. My main concern about using the dev server for pre-rendering is that the asset paths might not match up with production but you may solved that. If you did want to run the preview server before building the ssr environment then that might require some changes on the Cloudflare side so just let me know if you go down that route.
Recapping discussion elsewhere: since it's now necessary to pass the adapter to the sveltekit Vite plugin, we should remove config.kit.adapter from svelte.config.js (with a helpful error)
Interested how you landed on this. Did you try the approach of building a separate environment for the analysis/prerender phases and running it using the preview server rather than the dev server?
Seems like we can't use the Vite preview server for this because it doesn't provide access to the environment hmr API
I wonder if we should break this PR into smaller chunks so that it's a bit more reviewable — at the moment it's quite overwhelming. Started here: #15837
Yeah, agreed. Merging the stacked PR was my mistake because that made this PR include all the changed files from that. I'll try to split the rest into something like:
- Avoiding node dependencies on utils that run in the dev environment
- https://github.com/sveltejs/kit/pull/15846
- https://github.com/sveltejs/kit/pull/15848
- Remove emulate https://github.com/sveltejs/kit/pull/15845
- Vite dev (maybe this can be split into even smaller parts)
- Analyser
- Prerenderer
EDIT: the PR is already looking smaller and will be smaller once the PRs above are merged. Going to hold off on splitting it up more for the moment
The recent on main and version-3 are proving rather difficult to merge into this branch. The nub of the problem is that dynamic environment variables need to be set before anything gets imported from $app/env/*, and there are some brain-bending circular dependencies involved. Trying to figure it out
Alright, rewinding the merge, since I fucked things up beyond repair. Sorry 😬 Will see if I can get it right on the second attempt, though I'm a little worried that the new explicit env stuff is going to pose a real challenge
I’ll take a look too if you haven’t had another go at it already
It's all working now, just needed to point to __SERVER__/env.js. One of those obvious-in-hindsight things that takes several hours of headbashing to realise
Heads up for when this rebases. The eager import('/@vite/client') added in render.js is gated on esm-env DEV, the same pattern that caused #16008. Verified here, a NODE_ENV=staging build puts @vite/client in the prerendered output. #16023 swaps that for an import.meta.hot guard in the generated app.js.