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
Adds support for [Automatic Workspace
Detection](https://chromium.googlesource.com/devtools/devtools-frontend/+/main/docs/ecosystem/automatic_workspace_folders.md).
- Avoids 404's or middleware logging when this feature is active (e.g.
Chrome/Edge with DevTools open)
- Generates the same UUID based on root folder path (without writing
anything to disk)
- The middleware is lazy and does nothing until the path is opened for
`com.chrome.devtools.json`
This PR adds general support for an `exclude` option to file
transformers. This allows plugin to skip processing excluded files. The
exclude array can be a `string`, a `RegExp` or a glob pattern.
Fixes https://github.com/denoland/fresh/issues/2937
Related to #2953.
I found it confusing that there were unsupported route configurations,
that fails silently without any errors or wanings. Though I think it is
a good idea to not throw for this, as that would be worse DX. But
logging a warning if the developer is migrating from Fresh v1, or if the
developer is using code that will not work (e.g. copy pasting a handler
from a route to `_middleware`), I think it's helpful where reasonable to
help guide a bit more.
Does a small refactor first to hopefully improve typing to be more
correct for `InternalRoute.handlers`, then adds warnings for the
following:
- `_middleware` using Object form (`GET`, `POST` handlers) of the
handler format
- Helps find issues when moving handler from route to middleware
- `_layout` using `handlers`
- E.g. if developer moves a route to a layout
- ~~`_404`, `_500` or `_error` using Object handler form (`GET`, `POST`
handlers), which is not yet supported (See #2953)~~
- No longer necessary as it is fixed by #2955
JSR is a bit over-eager with inserting JSX comments and inserts both
`@jsx classic` and `@jsxImportSource` which are ignored in combination
Fixes https://github.com/denoland/fresh/issues/2942
This PR adds a unit test for the issue in #2910. I have not found a
solution yet, since I'm not very familiar with the `fsRoutes` code, and
what it is doing. But a thought a unit test with the failing code could
help to find a bug fix.
**Edit:** I managed to fix the failing test by removing a couple of
lines, but I'm not too familiar with the code so I'm not sure if it's
correct. It seems to pass all the tests still...
Closes#2910