fix: only reference env.js/env.script.js if dynamic public env vars are in use, and emit them as prerender output#16024
Conversation
…rs are in use, and emit them as prerender output
🦋 Changeset detectedLatest commit: 40b364d The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
… doesn't use them
teemingc
left a comment
There was a problem hiding this comment.
Can we separate the two changes into two PRs?
…e client doesn't use them" This reverts commit 3175412.
|
Sure, reverted the second commit so this PR is now just the env.js/env.script.js fix. The SSR omission gates on the broadened |
…ndleStrategy: 'inline'` (#16025) With `bundleStrategy: 'inline'`, the bundle and stylesheet are written to `_app/immutable` even though their content is inlined into the page, so the build ships a full copy of the app that nothing ever loads. In the default template that roughly doubles the output size, and a service worker will happily precache the dead files too. This deletes both files (and the bundle sourcemap if present) once their content has been captured for inlining, and filters anything that no longer exists out of the `$service-worker` build list. `version.json` stays, since the version checker can still fetch it at runtime. Of the unused files listed in the issue, `env.js` no longer reproduces on current main, so these two were the ones left. I went with deleting the files after the build rather than suppressing their emission inside it, since `find_deps` and the manifest plumbing still need the entries to exist, but open to a different route if preferred. The `options-3` app now has a service worker and a stylesheet, and its build-mode tests assert the inlined files are gone from `_app/immutable` (including sourcemaps), the service worker build list is clean, and `version.json` survives. The emitted-files assertions fail on main. Found this one while working on #16024 and digging through how the client build decides what to emit. Fixes #13700 --- ### 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. - [x] Ideally, include a test that fails without this PR but passes with it. ### Tests - [x] Run the tests with `pnpm test` and lint the project with `pnpm lint` and `pnpm 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 changeset` and following the prompts. Changesets that add features should be `minor` and those that fix bugs should be `patch`. Please prefix changeset messages with `feat:`, `fix:`, or `chore:`. ### Edits - [x] Please ensure that 'Allow edits from maintainers' is checked. PRs without this option may be closed.
teemingc
left a comment
There was a problem hiding this comment.
Thank you. This was a great catch. I just deduped some of the tests and moved them into an existing test suite. Also made it so that env.script.js is only generated if there are public dynamic env variables declared.
quick follow-up to #16024 — the flag is guaranteed to be `true` at this point
This PR contains the following updates: | Package | Change | [Age](https://docs.renovatebot.com/merge-confidence/) | [Confidence](https://docs.renovatebot.com/merge-confidence/) | |---|---|---|---| | [@sveltejs/kit](https://svelte.dev) ([source](https://github.com/sveltejs/kit/tree/HEAD/packages/kit)) | [`2.65.1` → `2.66.0`](https://renovatebot.com/diffs/npm/@sveltejs%2fkit/2.65.1/2.66.0) |  |  | --- ### Release Notes <details> <summary>sveltejs/kit (@​sveltejs/kit)</summary> ### [`v2.66.0`](https://github.com/sveltejs/kit/blob/HEAD/packages/kit/CHANGELOG.md#2660) [Compare Source](https://github.com/sveltejs/kit/compare/@sveltejs/kit@2.65.2...@sveltejs/kit@2.66.0) ##### Minor Changes - feat: precompress prerendered `.md` and `.mdx` files ([#​15893](sveltejs/kit#15893)) - feat: warn the user when they forget to make boolean inputs optional in their form schemas ([#​15804](sveltejs/kit#15804)) ##### Patch Changes - fix: blur active element before component update during navigation so that blur/focusout handlers fire while old component data is still valid ([#​15452](sveltejs/kit#15452)) - fix: ensure `base` is available from `$service-worker` during development ([#​15882](sveltejs/kit#15882)) - fix: use correct relative asset paths when rendering an error page for a missing `__data.json` request ([#​15884](sveltejs/kit#15884)) - fix: preserve active `for await` consumers across `query.live` reconnects ([#​16022](sveltejs/kit#16022)) - fix: settle `query.live` reconnect promise on all exit paths, preventing `invalidateAll()` from deadlocking when a live query is offline or interrupted ([#​16022](sveltejs/kit#16022)) - fix: preserve last value when a `query.live` stream completes without yielding on reconnect ([#​16022](sveltejs/kit#16022)) - fix: remove `types: ['node']` from generated tsconfig to avoid errors when `@types/node` is not installed ([#​15709](sveltejs/kit#15709)) - fix: prefer pages over endpoints when prerendering ([#​16076](sveltejs/kit#16076)) - fix: restore snapshots after afterNavigate callbacks ([#​16066](sveltejs/kit#16066)) - fix: support `ws:`/`wss:` and `trusted-types-eval` for CSP sources ([#​15938](sveltejs/kit#15938)) - fix: omit empty `file` inputs from remote form data ([#​15898](sveltejs/kit#15898)) - fix: fail early if a route with `+page` and `+server` is marked as prerenderable ([#​16075](sveltejs/kit#16075)) - fix: wait a tick before resetting forms ([#​15805](sveltejs/kit#15805)) - fix: `preflight` schemas apply correctly when chained before `for` ([#​15863](sveltejs/kit#15863)) - fix: blank page in SPA mode when root layout `load()` throws ([#​15798](sveltejs/kit#15798)) - fix: pass all unknown options from the `sveltekit` Vite plugin through to `vite-plugin-svelte` ([#​16010](sveltejs/kit#16010)) ### [`v2.65.2`](https://github.com/sveltejs/kit/blob/HEAD/packages/kit/CHANGELOG.md#2652) [Compare Source](https://github.com/sveltejs/kit/compare/@sveltejs/kit@2.65.1...@sveltejs/kit@2.65.2) ##### Patch Changes - fix: throw an error when prerendering a root +server.js that returns a non-HTML response ([#​15994](sveltejs/kit#15994)) - fix: decode base64-serialized fetch bodies before caching them for client-side replay ([#​16034](sveltejs/kit#16034)) - fix: correctly access explicit dynamic public environment variables from prerendered pages and service workers ([#​16024](sveltejs/kit#16024)) - fix: allow `preloadCode` to be called during initial page load ([#​16028](sveltejs/kit#16028)) - fix: send `cache-control: private, no-store` on remote function responses so personalized query results can never be cached by shared caches ([#​16020](sveltejs/kit#16020)) - fix: preserve the HTTP status and error body when a remote function request fails in transport (e.g. a 401/403 from a `handle` hook), instead of reporting a generic 500 ([#​16021](sveltejs/kit#16021)) - fix: avoid loading universal nodes during build analysis when the app uses a hash router ([#​16042](sveltejs/kit#16042)) - fix: correctly serve client entry during development when using the pnpm global virtual store ([#​16045](sveltejs/kit#16045)) - fix: normalize path separators when comparing config ([#​16037](sveltejs/kit#16037)) - fix: ensure `building` resolves correctly to allow avoiding build-time explicit environment variable validation ([#​16058](sveltejs/kit#16058)) - fix: prevent unhandled promise rejections when remote function failures are consumed via `current`/`error` instead of `await` ([#​16018](sveltejs/kit#16018)) </details> --- ### Configuration 📅 **Schedule**: (UTC) - Branch creation - At any time (no schedule defined) - Automerge - At any time (no schedule defined) 🚦 **Automerge**: Disabled because a matching PR was automerged previously. ♻ **Rebasing**: Whenever PR is behind base branch, or you tick the rebase/retry checkbox. 🔕 **Ignore**: Close this PR and you won't be reminded about this update again. --- - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box --- This PR has been generated by [Mend Renovate](https://github.com/renovatebot/renovate). <!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4yMjAuMCIsInVwZGF0ZWRJblZlciI6IjQzLjIyMC4wIiwidGFyZ2V0QnJhbmNoIjoiZGV2ZWxvcCIsImxhYmVscyI6W119--> Reviewed-on: https://codeberg.org/huskas-2189/Bookmark/pulls/126
With
experimental.explicitEnvironmentVariablesenabled, every prerendered page boots throughimport("/_app/env.js")and a service worker that imports$app/env/publiccallsimportScripts('/_app/env.script.js'), but adapter-static never writes either file. Static hosts answer the missing module with fallback HTML and hydration dies on a MIME error before any user code runs.The renderer and
generateEnvModule()disagree about when runtime env is needed.render_responsedefers env loading whenever the flag is set, even if every public variable isstatic: trueand nothing can ever readenv.js. MeanwhilegenerateEnvModule()only writes the file whenclient.uses_env_dynamic_publicis set, which is always false under explicit env vars because$env/dynamic/publicis disabled, so its explicit-env branch was unreachable.This PR makes both sides read the same bit.
uses_env_dynamic_publicis now also true when the client bundle contains$app/env/publicand at least one public variable is dynamic. Static-only apps get fully inlined env and noenv.jsimport, and pages that do defer pick up a previously missingmodulepreload. For the genuinely dynamic casegenerateEnvModule()now emitsenv.js, plusenv.script.jswhen the app has a service worker, since non-module workers load dynamic vars viaimportScripts. The service worker build also drops theimportScriptsprelude when all public vars are static, resolving the TODO from #15934.Two new
test/prerenderingapps cover both directions.explicit-env-staticasserts prerendered HTML inlines the values and references noenv.js, and that the service worker doesn't callimportScripts.explicit-env-dynamicasserts the deferral stays and thatenv.js/env.script.jsare emitted with only the dynamic values. Four of the eight assertions fail on main.Hopefully this continues my redemption arc after #16008 😅
Fixes #15985
Please don't delete this checklist! Before submitting the PR, please make sure you do the following:
Tests
pnpm testand lint the project withpnpm lintandpnpm checkChangesets
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