This PR adds a vite plugin for Fresh. This enables:
- HMR (only for islands for now)
- self-contained output bundles for both server and client
- smarter chunking
It uses vite's new Environment API under the hood.
Adds support for passing `URL` values to Islands.
```tsx
// routes/index.html
export default function Page() {
return <MyIsland url={new URL("https://fresh.deno.dev")} />;
}
```
Also updates documentation with some missing serialization features
(`undefined`, `Map`, `Set`, and `-0`).
---------
Co-authored-by: Marvin Hagemeister <hello@marvinh.dev>
Allow `ctx.render()` to bypass app wrapper and layouts.
- I originally intended this as a solution for middleware (`app.use()`)
to have the same capability as routes (`app.route()`) to solve the
`devErrorOverlay()` including wrappers.
- The docs mention it's possible to "opt-out" during `ctx.render()`
> Every
[ctx.render()](https://fresh.deno.dev/docs/canary/concepts/context#render-1)
call will include the app wrapper component by default, unless opted
out.
> \- https://fresh.deno.dev/docs/canary/advanced/app-wrapper
I don't need this myself currently, but it seemed a bit weird that
middleware was not able to bypass app wrapper or layouts, because it's
not possible to pass a `RouteConfig`. If this API is not something you
want to support, I could remove the code changes in favor of just
updating docs (above) and adding the tests.
### Open questions
Should it not be possible for "index" to use a layout? E.g. calls to
`/foo` should include the layout:
```ts
const app = new App()
.layout("/foo", ({ Component }) => (<>foo/<Component /></>))
.get("/foo", (ctx) => ctx.render(<>index</>));
// Should this not be "foo/index"? Currently renders "index"
```
Currently, I ignored the test for this, since it was not what I
expected. I tried to simulate the following folder layout, but with
imperative code:
```
<root>/routes
└── /foo
├── _layout.tsx
└── index.tsx
```
Encountered this issue in #3167, but already fixed in #3165. I noticed
`/_frsh/error_overlay` was using `_app`/`_layout`, which seemed
unnecessary.
Since this was already fixed in #3165, I just added a test to check that
this is not a regression in the future.
---------
Co-authored-by: Marvin Hagemeister <marvin@deno.com>
This adds a new `sourceMap` option on the `Builder` configuration. This
can be used to optionally specify how production source maps should be
generated.
See https://esbuild.github.io/api/#source-maps for more information.
No need to detect them at runtime when we can do this during build. This
saves us from having to load `@std/media-types` during production which
is quite a heavy library due to the amount of file types out there.
We can improve cold start times by only loading route modules when the particular pattern matches. This PR introduces the concept of lazy middlewares, routes and handlers to do that.
This fixes a bunch of long standing issues in our tracker where a build
wouldn't finish because of importing user code. It's common for backend
apps to spawn some open ended tasks like subscribing to Deno KV or other
things. This addresses another problem of having to set up ENV vars just
for the build, even though they are technically not required to build
islands.
This also gives a roughly ~30% performance boost on cold starts (at
least on `deno.com`). Unfortunately, this does require some breaking
changes. But I believe the performance improvements + removing the
footgun of loading user code during build is well worth it. This work is
also a precursor in case we want to exploring moving to vite at some
point in the future.
## Breaking changes
1. Build options have moved to the builder.
```diff
// main.ts
- const app = new App({ build: { outDir: "dist/" } })
+ const app = new App()
// dev.ts
- const builder = new Builder();
+ const builder = new Builder({ outDir: "dist/" });
```
2. Another breaking change is how file based routes are loaded. Since
they're prepared and loaded by the builder the API changed.
```diff
// main.ts
const app = new App()
.use(staticFiles())
- await fsRoutes(app, {
- loadIsland: (path) => import(`./islands/${path}`),
- loadRoute: (path) => import(`./routes/${path}`),
- });
+ app.fsRoutes()
```
You can optionally change the `islandDir` or `routeDir` by passing that
to the `Builder`:
```ts
// dev.ts
const builder = new Builder({
islandDir: "/path/to/islands",
routeDir: "/path/to/routes"
});
```
3. Import `app` lazily in `dev.ts`. Passing `app` to `builder.build()`
is not necessary anymore.
```diff
- import { app } from "./main.ts";
const builder = new Builder({ target: "safari12" });
if (Deno.args.includes("build")) {
- await builder.build(app);
+ await builder.build();
} else {
- await builder.listen(app);
+ await builder.listen(() => import("./main.ts"));
}
```
4. The production run command has changed. It's now using `deno serve`
```diff
// deno.json
{
"tasks": {
"dev": "deno run -A --watch=static/,routes/ dev.ts",
"dev": "deno run -A dev.ts build",
- "start": "deno run -A main.ts",
+ "start": "deno serve -A _fresh/server.js",
}
}
```
Remove this bit in `main.ts`:
```diff
// main.ts
- if (import.meta.main) {
- await app.listen()
- }
```
Fixes https://github.com/denoland/fresh/issues/2240
Fixes https://github.com/denoland/fresh/issues/2640
Fixes https://github.com/denoland/fresh/issues/2592
Fixes https://github.com/denoland/fresh/issues/1843
Fixes some regressions found after merging
https://github.com/denoland/fresh/pull/3086
- Missing 404 middlewares when mounting sub-apps
- revert more staticFiles logic to always require the middleware like
before
This pull request includes a small but important change to the
`withTmpDir` function in `src/test_utils.ts`. The change adds error
handling to ensure that a `PermissionDenied` error during directory
removal does not interrupt the execution.
The Fresh partials popstate handler causes page reloads when user code
makes use of navigation history state. This can lead to a loss of user
data in a browsing context.
To fix this behavior, FreshHistoryState now has a flag which validates
partials functionality/explicitly opts-in to any partial related
location management.
When binding to `0.0.0.0` or `::`, show localhost equivalent URL for
convenience
Closes#3076
output from fresh www
```
deno task start
Task start deno run -A --watch=static/,routes/,../src,../docs dev.ts
Watcher Process started.
🍋 Fresh ready
Local: http://0.0.0.0:8000/ (http://localhost:8000/)
GA4_MEASUREMENT_ID environment variable not set. Google Analytics reporting disabled.
```
In Fresh 1, define apps used `RouteContext`, which align with
`PageProps` in Fresh 2, rather than `FreshContext`. E.g. before this PR,
one would get a type error if they tried to use `ctx.Component` within
`defineApp()` and now they shouldn't.
Move to the new esbuild plugin that leverages `@deno/loader` under the
hood. This is based on the exact same rust crates that Deno itself uses
to do resolution, instead of doing it's own resolution.
- `fresh/compat - defineFn mixed return types` - Tests all supported
return types (Response, VNode, null) with both sync and async handlers,
including FreshContext parameter usage
- `fresh/compat - multiple compat imports` - Tests importing multiple
compat functions simultaneously
close#3025
--patch-1
try to use deno/std Api to replace
--patch-2
make it simple and clean
--patch-3
Convert update_test.ts to .tsx for JSX support
Use static imports instead of dynamic imports for better performance
Switch from @std/assert to @std/expect for consistency
Use ReturnType<> for automatic type inference instead of manual type
definitions
Sincerely grateful to @iuioiua for the guidance and patience.
---------
Co-authored-by: 李嘉图·M·路 <146103794+Ricardo-M-Zheng@users.noreply.github.com>
Co-authored-by: Asher Gomez <ashersaupingomez@gmail.com>
## Why was this PR initiated?
I opened an issue and held discussions about officially providing
middleware in Fresh by porting middleware from Hono.
https://github.com/denoland/fresh/issues/3011
## What does this PR do?
I introduced the CORS middleware bundled with Fresh by porting the CORS
middleware from Hono.
I appreciate your review.
---------
Co-authored-by: Marvin Hagemeister <marvin@deno.com>
Addresses a gap between [Fresh
v1](https://github.com/denoland/fresh/blob/1.x/src/server/types.ts#L192)
and Fresh v2, by adding `ctx.isPartial` to `FreshContext`.
The same route (e.g. `GET /api/autocomplete`) can be called from both an
Island or a Partial. Returning JSON or HTML depending on the destination
of the code.
Or is the intent that endpoints returning partials and data should be
separated, and this pattern is not to be encouraged in Fresh v2? My use
case in Fresh v1 was an `/routes/api/cart.tsx`, which can either just
toggle a product from the cart (via cookie), but also update UI elements
(e.g. cart icon) based on if called from partial or not.

~~Makes it easier to upgrade from 1.x .~~
Initially, I assumed it would be just an alias to `RouteConfig`, but
upon closer inspection that has some additional properties that make no
sense for a layout.
Replaces the patterns below with consistent `AsyncDisposable` and `await
using` resource management for automatic cleanup.
- `await withTmpDir(async (dir) => { ... })` with `finally`
- Makes code a bit flatter, and reduces callback-hell a bit
- `await Deno.makeTempDir()` + `Deno.remove()`
- `await Deno.makeTempDir()`
Helps be more consistent in removing temporary folders. Among others,
ensures temp folders are removed in the tests below:
- `src/build_cache_test.ts`
- `src/dev/builder_test.ts`
- `src/dev/dev_build_cache_test.ts`
## TODO's
The `Deno.makeTempDir()` method is still used by `buildProd` as well,
but this method is used in the top module scope, where it does not work
correctly with `Deno.test` (it runs before the test methods). I removed
this part from the PR and leave this for later to avoid making the PR
too big.
-
https://github.com/csvn/fresh/blob/test%2Fdisposable-tmp-dirs/tests/test_utils.tsx/#L64
-
https://github.com/csvn/fresh/blob/test%2Fdisposable-tmp-dirs/www/main_test.ts/#L7