Compare commits
11
Commits
216d54a0ae
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6e37c2aea7 | ||
|
|
7595cf396f | ||
|
|
0b6be21d14 | ||
|
|
8c552d05d1 | ||
|
|
3866b47741 | ||
|
|
8400c019e0 | ||
|
|
0e6aa1d232 | ||
|
|
dd635e0fbe | ||
|
|
cc42b17dfb | ||
|
|
dda4a30f9c | ||
|
|
8aa05e104d |
@@ -11,6 +11,8 @@
|
||||
"jsr:@deno/graph@~0.82.3": "0.82.3",
|
||||
"jsr:@deno/loader@0.4": "0.4.0",
|
||||
"jsr:@deno/loader@~0.3.10": "0.3.14",
|
||||
"jsr:@fresh/build-id@1": "1.0.1",
|
||||
"jsr:@fresh/core@2.3.3": "2.3.3",
|
||||
"jsr:@marvinh-test/fresh-island@^0.0.3": "0.0.3",
|
||||
"jsr:@marvinh-test/import-json@^0.0.1": "0.0.1",
|
||||
"jsr:@matmen/imagescript@^1.3.0": "1.3.1",
|
||||
@@ -71,12 +73,12 @@
|
||||
"jsr:@zip-js/zip-js@^2.7.52": "2.8.24",
|
||||
"npm:@babel/core@^7.28.0": "7.28.5",
|
||||
"npm:@babel/preset-react@^7.27.1": "7.28.5_@babel+core@7.28.5",
|
||||
"npm:@docsearch/js@^3.5.2": "3.9.0_@algolia+client-search@5.50.0_search-insights@2.17.3",
|
||||
"npm:@docsearch/js@^3.5.2": "3.9.0_preact-render-to-string@6.6.7__preact@10.29.8",
|
||||
"npm:@opentelemetry/api@^1.9.0": "1.9.1",
|
||||
"npm:@preact/signals@2": "2.9.0_preact@10.29.1",
|
||||
"npm:@preact/signals@^2.2.1": "2.9.0_preact@10.29.1",
|
||||
"npm:@preact/signals@^2.5.1": "2.9.0_preact@10.29.1",
|
||||
"npm:@prefresh/vite@^2.4.8": "2.4.11_preact@10.29.1_vite@7.3.1",
|
||||
"npm:@preact/signals@2": "2.9.0_preact@10.29.8_preact-render-to-string@6.6.7__preact@10.29.8",
|
||||
"npm:@preact/signals@^2.2.1": "2.9.0_preact@10.29.8_preact-render-to-string@6.6.7__preact@10.29.8",
|
||||
"npm:@preact/signals@^2.5.1": "2.9.0_preact@10.29.8_preact-render-to-string@6.6.7__preact@10.29.8",
|
||||
"npm:@prefresh/vite@^2.4.8": "2.4.11_preact@10.29.8_vite@7.3.1_preact-render-to-string@6.6.7__preact@10.29.8",
|
||||
"npm:@radix-ui/themes@^3.2.1": "3.2.1_react@19.1.1_react-dom@19.1.1",
|
||||
"npm:@remix-run/node-fetch-server@0.12": "0.12.0",
|
||||
"npm:@supabase/postgrest-js@^1.21.4": "1.21.4",
|
||||
@@ -106,13 +108,13 @@
|
||||
"npm:pg@^8.16.3": "8.16.3",
|
||||
"npm:postcss@8.5.6": "8.5.6",
|
||||
"npm:postcss@^8.5.6": "8.5.6",
|
||||
"npm:preact-render-to-string@^6.6.3": "6.6.7_preact@10.29.1",
|
||||
"npm:preact-render-to-string@^6.6.5": "6.6.7_preact@10.29.1",
|
||||
"npm:preact@^10.22.0": "10.29.1",
|
||||
"npm:preact@^10.26.9": "10.29.1",
|
||||
"npm:preact@^10.27.0": "10.29.1",
|
||||
"npm:preact@^10.28.2": "10.29.1",
|
||||
"npm:preact@^10.29.1": "10.29.1",
|
||||
"npm:preact-render-to-string@^6.6.3": "6.6.7_preact@10.29.8",
|
||||
"npm:preact-render-to-string@^6.6.5": "6.6.7_preact@10.29.8",
|
||||
"npm:preact@^10.22.0": "10.29.8_preact-render-to-string@6.6.7",
|
||||
"npm:preact@^10.26.9": "10.29.8_preact-render-to-string@6.6.7",
|
||||
"npm:preact@^10.27.0": "10.29.8_preact-render-to-string@6.6.7",
|
||||
"npm:preact@^10.28.2": "10.29.8_preact-render-to-string@6.6.7",
|
||||
"npm:preact@^10.29.8": "10.29.8_preact-render-to-string@6.6.7",
|
||||
"npm:prismjs@^1.29.0": "1.30.0",
|
||||
"npm:qs@^6.14.0": "6.14.0",
|
||||
"npm:redis@^5.8.2": "5.9.0_@redis+client@5.9.0",
|
||||
@@ -194,6 +196,24 @@
|
||||
"@deno/loader@0.4.0": {
|
||||
"integrity": "6c1b18cfa18592740613ce79e15625c24268d60dbfc54bebfb5153bf512c536b"
|
||||
},
|
||||
"@fresh/build-id@1.0.1": {
|
||||
"integrity": "12a2ec25fd52ae9ec68c26848a5696cd1c9b537f7c983c7e56e4fb1e7e816c20",
|
||||
"dependencies": [
|
||||
"jsr:@std/encoding@^1.0.10"
|
||||
]
|
||||
},
|
||||
"@fresh/core@2.3.3": {
|
||||
"integrity": "6c2aad199976644352c89a1d601f3ef331b1d24cdadb53ed469324a303598383",
|
||||
"dependencies": [
|
||||
"jsr:@fresh/build-id",
|
||||
"jsr:@std/fmt@^1.0.8",
|
||||
"jsr:@std/fs@^1.0.19",
|
||||
"jsr:@std/html@^1.0.5",
|
||||
"jsr:@std/http@^1.0.21",
|
||||
"jsr:@std/net",
|
||||
"jsr:@std/path@^1.1.2"
|
||||
]
|
||||
},
|
||||
"@marvinh-test/fresh-island@0.0.3": {
|
||||
"integrity": "6d06b6009b7dfba9bba28e941e03e6ff652c4ef4f2fbfdf4b78741abd6c6c1c6",
|
||||
"dependencies": [
|
||||
@@ -1337,7 +1357,7 @@
|
||||
"@docsearch/css@3.9.0": {
|
||||
"integrity": "sha512-cQbnVbq0rrBwNAKegIac/t6a8nWoUAn8frnkLFW6YARaRmAQr5/Eoe6Ln2fqkUCZ40KpdrKbpSAmgrkviOxuWA=="
|
||||
},
|
||||
"@docsearch/js@3.9.0_@algolia+client-search@5.50.0_search-insights@2.17.3": {
|
||||
"@docsearch/js@3.9.0_preact-render-to-string@6.6.7__preact@10.29.8": {
|
||||
"integrity": "sha512-4bKHcye6EkLgRE8ze0vcdshmEqxeiJM77M0JXjef7lrYZfSlMunrDOCqyLjiZyo1+c0BhUqA2QpFartIjuHIjw==",
|
||||
"dependencies": [
|
||||
"@docsearch/react",
|
||||
@@ -1721,7 +1741,7 @@
|
||||
"@preact/signals-core@1.14.0": {
|
||||
"integrity": "sha512-AowtCcCU/33lFlh1zRFf/u+12rfrhtNakj7UpaGEsmMwUKpKWMVvcktOGcwBBNiB4lWrZWc01LhiyyzVklJyaQ=="
|
||||
},
|
||||
"@preact/signals@2.9.0_preact@10.29.1": {
|
||||
"@preact/signals@2.9.0_preact@10.29.8_preact-render-to-string@6.6.7__preact@10.29.8": {
|
||||
"integrity": "sha512-hYrY0KyUqkDgOl1qba/JGn6y81pXnurn21PMaxfcMwdncdZ3M/oVdmpTvEnsGjh48dIwDVc7bjWHqIsngSjYug==",
|
||||
"dependencies": [
|
||||
"@preact/signals-core",
|
||||
@@ -1731,7 +1751,7 @@
|
||||
"@prefresh/babel-plugin@0.5.2": {
|
||||
"integrity": "sha512-AOl4HG6dAxWkJ5ndPHBgBa49oo/9bOiJuRDKHLSTyH+Fd9x00shTXpdiTj1W41l6oQIwUOAgJeHMn4QwIDpHkA=="
|
||||
},
|
||||
"@prefresh/core@1.5.8_preact@10.29.1": {
|
||||
"@prefresh/core@1.5.8_preact@10.29.8_preact-render-to-string@6.6.7__preact@10.29.8": {
|
||||
"integrity": "sha512-T7HMpakS1iPVCFZvfDLMGyrWAcO3toUN9/RkJUqqoRr/vNhQrZgHjidfhq3awDzAQtw1emDWH8dsOeu0DWqtgA==",
|
||||
"dependencies": [
|
||||
"preact"
|
||||
@@ -1740,7 +1760,7 @@
|
||||
"@prefresh/utils@1.2.1": {
|
||||
"integrity": "sha512-vq/sIuN5nYfYzvyayXI4C2QkprfNaHUQ9ZX+3xLD8nL3rWyzpxOm1+K7RtMbhd+66QcaISViK7amjnheQ/4WZw=="
|
||||
},
|
||||
"@prefresh/vite@2.4.11_preact@10.29.1_vite@7.3.1": {
|
||||
"@prefresh/vite@2.4.11_preact@10.29.8_vite@7.3.1_preact-render-to-string@6.6.7__preact@10.29.8": {
|
||||
"integrity": "sha512-/XjURQqdRiCG3NpMmWqE9kJwrg9IchIOWHzulCfqg2sRe/8oQ1g5De7xrk9lbqPIQLn7ntBkKdqWXIj4E9YXyg==",
|
||||
"dependencies": [
|
||||
"@babel/core",
|
||||
@@ -4807,14 +4827,20 @@
|
||||
"xtend"
|
||||
]
|
||||
},
|
||||
"preact-render-to-string@6.6.7_preact@10.29.1": {
|
||||
"preact-render-to-string@6.6.7_preact@10.29.8": {
|
||||
"integrity": "sha512-3XdbsX3+vn9dQW+jJI/FsI9rlkgl6dbeUpqLsChak6jp3j3auFqBCkno7VChbMFs5Q8ylBj6DrUkKRwtVN3nvw==",
|
||||
"dependencies": [
|
||||
"preact"
|
||||
]
|
||||
},
|
||||
"preact@10.29.1": {
|
||||
"integrity": "sha512-gQCLc/vWroE8lIpleXtdJhTFDogTdZG9AjMUpVkDf2iTCNwYNWA+u16dL41TqUDJO4gm2IgrcMv3uTpjd4Pwmg=="
|
||||
"preact@10.29.8_preact-render-to-string@6.6.7": {
|
||||
"integrity": "sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==",
|
||||
"dependencies": [
|
||||
"preact-render-to-string"
|
||||
],
|
||||
"optionalPeers": [
|
||||
"preact-render-to-string"
|
||||
]
|
||||
},
|
||||
"pretty-bytes@5.6.0": {
|
||||
"integrity": "sha512-FFw039TmrBqFK8ma/7OL3sDz/VytdtJr044/QUJtH0wK9lb9jLq9tJyIxUwtQJHwar2BqtiA4iCWSwo9JLkzFg=="
|
||||
@@ -6065,7 +6091,7 @@
|
||||
"npm:@types/node@^24.2.1",
|
||||
"npm:esbuild-wasm@~0.25.11",
|
||||
"npm:preact-render-to-string@^6.6.3",
|
||||
"npm:preact@^10.29.1"
|
||||
"npm:preact@^10.29.8"
|
||||
]
|
||||
},
|
||||
"packages/plugin-tailwindcss-v3": {
|
||||
|
||||
@@ -102,6 +102,12 @@ export default define.page<typeof handler>(function Upload(props) {
|
||||
});
|
||||
```
|
||||
|
||||
## Other HTTP methods
|
||||
|
||||
Browsers can only submit forms as `GET` or `POST`. To submit a form as `DELETE`,
|
||||
`PATCH` or `PUT` and update part of the page with the response, use
|
||||
[Partials](/docs/advanced/partials#using-other-http-methods).
|
||||
|
||||
## A note of caution
|
||||
|
||||
These examples are simplified to demonstrate how Deno and Fresh handle HTTP
|
||||
|
||||
@@ -145,6 +145,201 @@ two links and _only_ load the content rendered by our optimized partial route.
|
||||
> Currently, `f-partial` is scoped to `<a>`, `<button>` and `<form>` elements.
|
||||
> This might be extended to more elements in the future.
|
||||
|
||||
## Submitting forms
|
||||
|
||||
Forms inside an `f-client-nav` element can be submitted as a partial request.
|
||||
For `GET` and `POST` forms, this happens when the form opts in through one of
|
||||
these attributes:
|
||||
|
||||
- an `action` attribute on the `<form>`
|
||||
- an `f-partial` attribute on the `<form>`
|
||||
- a `formaction` or `f-partial` attribute on the submit button
|
||||
|
||||
A `GET` form sends its fields as URL search parameters. Every other method sends
|
||||
them as a `multipart/form-data` request body. If the submit button has a `name`,
|
||||
its value is included too.
|
||||
|
||||
A `GET` or `POST` form without any of these attributes is submitted the normal
|
||||
way, with a full page load. Forms with `method="dialog"` are never intercepted.
|
||||
|
||||
### Using other HTTP methods
|
||||
|
||||
Browsers can only submit forms as `GET` or `POST`. Fresh lets forms inside
|
||||
`f-client-nav` use any other method too, like `DELETE`, `PATCH` or `PUT`. You
|
||||
set it with the `method` attribute on the form or the `formmethod` attribute on
|
||||
a submit button, and Fresh sends the request with `fetch()`.
|
||||
|
||||
```tsx routes/index.tsx
|
||||
import { Partial } from "sweet/runtime";
|
||||
import { define } from "../utils.ts";
|
||||
|
||||
export const handler = define.handlers({
|
||||
POST(ctx) {
|
||||
return ctx.render(<Partial name="body">post!</Partial>);
|
||||
},
|
||||
DELETE(ctx) {
|
||||
return ctx.render(<Partial name="body">delete!</Partial>);
|
||||
},
|
||||
PATCH(ctx) {
|
||||
return ctx.render(<Partial name="body">patch!</Partial>);
|
||||
},
|
||||
});
|
||||
|
||||
export default define.page(function Home() {
|
||||
return (
|
||||
<div f-client-nav>
|
||||
<form action="/">
|
||||
<button type="submit" formmethod="POST">post</button>
|
||||
<button type="submit" formmethod="DELETE">delete</button>
|
||||
<button type="submit" formmethod="PATCH">patch</button>
|
||||
</form>
|
||||
<Partial name="body">nothing submitted yet</Partial>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
A form that uses another method is always submitted as a partial request. It
|
||||
doesn't need an `action` or `f-partial` attribute. Without them, the request
|
||||
goes to the current page. You can write the method in any case: Fresh converts
|
||||
it to uppercase, so `formmethod="patch"` reaches your `PATCH` handler.
|
||||
|
||||
The `POST` button above only submits as a partial because the form has an
|
||||
`action` attribute. Without it, `POST` would cause a full page load, while the
|
||||
`DELETE` and `PATCH` buttons would still work as partials.
|
||||
|
||||
Keep the following in mind when using other methods:
|
||||
|
||||
- **The URL doesn't change:** Unlike `GET` and `POST`, these methods leave the
|
||||
URL in the address bar as it is. See
|
||||
[Controlling the URL](#controlling-the-url).
|
||||
- **Redirects:** To redirect after a `DELETE`, `PATCH` or `PUT`, respond with
|
||||
status `303 See Other`. With a `301` or `302`, `fetch()` sends the request to
|
||||
the new URL again with the same method. The partials from the redirect target
|
||||
are applied, but the URL only changes to it if you set `f-update-url="true"`.
|
||||
- **Without JavaScript:** If JavaScript isn't loaded, the browser doesn't
|
||||
recognize the method and submits the form as a `GET` request instead, with the
|
||||
fields in the URL. If a form has to work without JavaScript, use `POST`.
|
||||
- **CSRF protection:** The [CSRF middleware](/docs/plugins/csrf) treats these
|
||||
methods like `POST`, so they get the same checks.
|
||||
|
||||
### Controlling the URL
|
||||
|
||||
When a `GET` or `POST` form is submitted as a partial, Fresh replaces the URL in
|
||||
the address bar with the form's action URL, or with the URL it was redirected
|
||||
to. Other methods leave the URL as it is, so a `DELETE` to `/items/1` doesn't
|
||||
leave `/items/1` in the address bar.
|
||||
|
||||
To change this, set `f-update-url` on the form or on the submit button. The
|
||||
button's value wins if both have one.
|
||||
|
||||
- `f-update-url="true"` updates the URL, for any method
|
||||
- `f-update-url="false"` leaves the URL as it is, for any method
|
||||
|
||||
```tsx
|
||||
<form action="/search" f-update-url="false">
|
||||
<input name="q" />
|
||||
<button type="submit">Search</button>
|
||||
</form>;
|
||||
```
|
||||
|
||||
> [info]: Use the strings `"true"` and `"false"`. Preact leaves the attribute
|
||||
> out when you pass the boolean `{false}`, so Fresh falls back to the default.
|
||||
|
||||
### Sending requests from buttons
|
||||
|
||||
A `<button>` with an `f-partial` attribute also triggers a partial request on
|
||||
its own. This applies to buttons outside a form and to buttons with
|
||||
`type="button"`. Submit buttons inside a form submit the form instead, as
|
||||
described above. By default, the button sends a `GET` request to the `f-partial`
|
||||
URL and applies the partials in the response. Unlike links, buttons don't change
|
||||
the URL in the address bar.
|
||||
|
||||
To use another method, add an `f-method` attribute. This is handy for actions
|
||||
like deleting an item from a list, where wrapping each button in a `<form>`
|
||||
would be awkward.
|
||||
|
||||
```tsx routes/todos.tsx
|
||||
import { Partial } from "sweet/runtime";
|
||||
import { define } from "../utils.ts";
|
||||
|
||||
export const handler = define.handlers({
|
||||
async DELETE(ctx) {
|
||||
const form = await ctx.req.formData();
|
||||
await deleteTodo(String(form.get("id")));
|
||||
return ctx.render(<TodoList todos={await getTodos()} />);
|
||||
},
|
||||
});
|
||||
|
||||
function TodoList(props: { todos: Todo[] }) {
|
||||
return (
|
||||
<Partial name="todos">
|
||||
<ul>
|
||||
{props.todos.map((todo) => (
|
||||
<li key={todo.id}>
|
||||
{todo.title}
|
||||
<button
|
||||
type="button"
|
||||
f-partial="/todos"
|
||||
f-method="DELETE"
|
||||
name="id"
|
||||
value={todo.id}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Partial>
|
||||
);
|
||||
}
|
||||
|
||||
export default define.page(async () => {
|
||||
const todos = await getTodos();
|
||||
return (
|
||||
<div f-client-nav>
|
||||
<TodoList todos={todos} />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
```
|
||||
|
||||
When `f-method` is set to something other than `GET`, the request body is
|
||||
`multipart/form-data` and contains:
|
||||
|
||||
- the button's own `name` and `value`, if it has a `name`
|
||||
- every field of the surrounding form, if the button is a `type="button"` inside
|
||||
a `<form>`
|
||||
|
||||
A `GET` button doesn't send any data. Like with forms, you can write the method
|
||||
in any case.
|
||||
|
||||
To ask for confirmation first, call `preventDefault()` on the click event in an
|
||||
island. Fresh won't send the request when the event was cancelled.
|
||||
|
||||
```tsx islands/DeleteButton.tsx
|
||||
export function DeleteButton(props: { id: string }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
f-partial="/todos"
|
||||
f-method="DELETE"
|
||||
name="id"
|
||||
value={props.id}
|
||||
onClick={(e) => {
|
||||
if (!confirm("Delete this todo?")) e.preventDefault();
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
[Loading indicators](#loading-indicators) work on these buttons too, and the
|
||||
same advice about redirects applies. Buttons with `f-partial` rely on
|
||||
JavaScript, so they do nothing if JavaScript isn't loaded.
|
||||
|
||||
## Sending multiple Partials at the same time
|
||||
|
||||
A neat aspect of partials in Fresh is that a response can return as many
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@paulaboks/sweet",
|
||||
"version": "2.3.3",
|
||||
"version": "2.3.7",
|
||||
"license": "MIT",
|
||||
"exports": {
|
||||
".": "./src/mod.ts",
|
||||
@@ -27,7 +27,7 @@
|
||||
"@std/uuid": "jsr:@std/uuid@^1.0.9",
|
||||
"@types/node": "npm:@types/node@^24.2.1",
|
||||
"esbuild-wasm": "npm:esbuild-wasm@^0.25.11",
|
||||
"preact": "npm:preact@^10.29.1",
|
||||
"preact": "npm:preact@^10.29.8",
|
||||
"preact-render-to-string": "npm:preact-render-to-string@^6.6.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from "./context.ts";
|
||||
import { mergePath, type Method, UrlPatternRouter } from "./router.ts";
|
||||
import type { FreshConfig, ResolvedFreshConfig } from "./config.ts";
|
||||
import type { BuildCache } from "./build_cache.ts";
|
||||
import { type BuildCache, MockBuildCache } from "./build_cache.ts";
|
||||
import { HttpError } from "./error.ts";
|
||||
import { STATUS_TEXT } from "@std/http/status";
|
||||
import type { LayoutConfig, MaybeLazy, Route, RouteConfig } from "./types.ts";
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
newNotFoundCmd,
|
||||
newRouteCmd,
|
||||
} from "./commands.ts";
|
||||
import { MockBuildCache } from "./test_utils.ts";
|
||||
|
||||
// TODO: Completed type clashes in older Deno versions
|
||||
// deno-lint-ignore no-explicit-any
|
||||
|
||||
@@ -102,6 +102,32 @@ export class ProdBuildCache<State> implements BuildCache<State> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Fallback build cache for when there's no build output (and for tests). */
|
||||
export class MockBuildCache<State> implements BuildCache<State> {
|
||||
#files: FsRouteFile<State>[];
|
||||
root = "";
|
||||
clientEntry = "";
|
||||
islandRegistry: ServerIslandRegistry = new Map();
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(files: FsRouteFile<State>[], mode: "development" | "production") {
|
||||
this.features.errorOverlay = mode === "development";
|
||||
this.#files = files;
|
||||
}
|
||||
|
||||
getEntryAssets(): string[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
getFsRoutes(): Command<State>[] {
|
||||
return fsItemsToCommands(this.#files);
|
||||
}
|
||||
|
||||
readFile(_pathname: string): Promise<StaticFile | null> {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
}
|
||||
|
||||
export class IslandPreparer {
|
||||
#namer = new UniqueNamer();
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import * as pathWin32 from "@std/path/windows";
|
||||
import { encodeHex } from "@std/encoding/hex";
|
||||
import { fsAdapter } from "../fs.ts";
|
||||
import type { FileTransformer } from "./file_transformer.ts";
|
||||
import { assertInDir, pathToSpec } from "../utils.ts";
|
||||
import { assertInDir, pathToSpec, toPosix } from "../utils.ts";
|
||||
import type { ResolvedBuildConfig } from "./builder.ts";
|
||||
import { fsItemsToCommands, type FsRouteFile } from "../fs_routes.ts";
|
||||
import type { Command } from "../commands.ts";
|
||||
@@ -17,13 +17,6 @@ import { contentType as getStdContentType } from "@std/media-types/content-type"
|
||||
|
||||
const WINDOWS_SEPARATOR = pathWin32.SEPARATOR;
|
||||
|
||||
/** Normalize a path to use forward slashes so that generated files
|
||||
* are portable across operating systems (e.g. build on Windows,
|
||||
* deploy on Linux). */
|
||||
export function toPosix(p: string): string {
|
||||
return p.replaceAll(WINDOWS_SEPARATOR, "/");
|
||||
}
|
||||
|
||||
export interface MemoryFile {
|
||||
hash: string | null;
|
||||
contentType: string;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { type FsAdapter, fsAdapter } from "../fs.ts";
|
||||
import type { WalkEntry } from "@std/fs/walk";
|
||||
import { type FsRouteFileNoMod, toPosix } from "./dev_build_cache.ts";
|
||||
import type { FsRouteFileNoMod } from "./dev_build_cache.ts";
|
||||
import { toPosix } from "../utils.ts";
|
||||
import * as path from "@std/path";
|
||||
import { pathToPattern } from "../router.ts";
|
||||
import { CommandType } from "../commands.ts";
|
||||
|
||||
@@ -7,10 +7,9 @@ export {
|
||||
type IslandModChunk,
|
||||
type PendingStaticFile,
|
||||
prepareStaticFile,
|
||||
toPosix,
|
||||
writeCompiledEntry,
|
||||
} from "./dev/dev_build_cache.ts";
|
||||
export { specToName } from "./dev/builder.ts";
|
||||
export { pathToSpec, UniqueNamer } from "./utils.ts";
|
||||
export { pathToSpec, toPosix, UniqueNamer } from "./utils.ts";
|
||||
export { updateCheck } from "./dev/update_check.ts";
|
||||
export { TEST_FILE_PATTERN, UPDATE_INTERVAL } from "./constants.ts";
|
||||
|
||||
@@ -99,12 +99,25 @@ export function csp<State>(options: CSPOptions = {}): Middleware<State> {
|
||||
? "Content-Security-Policy-Report-Only"
|
||||
: "Content-Security-Policy";
|
||||
|
||||
// Upgrading requests only makes sense when the page itself was served over
|
||||
// HTTPS. On plain HTTP (e.g. local dev) it breaks things like partial
|
||||
// redirects by upgrading them to an https:// URL the server doesn't serve.
|
||||
// Behind a TLS-terminating proxy, enable `trustProxy` so the protocol is
|
||||
// detected correctly.
|
||||
const insecureMerged = merged.filter((d) =>
|
||||
d !== "upgrade-insecure-requests"
|
||||
);
|
||||
|
||||
if (!useNonce) {
|
||||
// Static CSP — no per-request nonce
|
||||
const cspString = merged.join("; ");
|
||||
const insecureCspString = insecureMerged.join("; ");
|
||||
return async (ctx) => {
|
||||
const res = await ctx.next();
|
||||
res.headers.set(headerName, cspString);
|
||||
res.headers.set(
|
||||
headerName,
|
||||
ctx.url.protocol === "https:" ? cspString : insecureCspString,
|
||||
);
|
||||
if (reportTo) {
|
||||
res.headers.set("Reporting-Endpoints", `csp-endpoint="${reportTo}"`);
|
||||
}
|
||||
@@ -117,10 +130,11 @@ export function csp<State>(options: CSPOptions = {}): Middleware<State> {
|
||||
const res = await ctx.next();
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const nonce = (res as any)[NONCE_SYMBOL] as string | undefined;
|
||||
const base = ctx.url.protocol === "https:" ? merged : insecureMerged;
|
||||
|
||||
let directives: string[];
|
||||
if (nonce) {
|
||||
directives = merged.map((d) => {
|
||||
directives = base.map((d) => {
|
||||
const spaceIdx = d.indexOf(" ");
|
||||
const name = spaceIdx === -1 ? d : d.slice(0, spaceIdx);
|
||||
if (INLINE_DIRECTIVES.has(name) && d.includes("'unsafe-inline'")) {
|
||||
@@ -129,7 +143,7 @@ export function csp<State>(options: CSPOptions = {}): Middleware<State> {
|
||||
return d;
|
||||
});
|
||||
} else {
|
||||
directives = merged;
|
||||
directives = base;
|
||||
}
|
||||
|
||||
res.headers.set(headerName, directives.join("; "));
|
||||
|
||||
@@ -17,6 +17,47 @@ Deno.test("CSP - GET default", async () => {
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("CSP - omits upgrade-insecure-requests over http", async () => {
|
||||
const handler = new App()
|
||||
.use(csp())
|
||||
.get("/", () => new Response("ok"))
|
||||
.handler();
|
||||
const res = await handler(new Request("http://localhost/"));
|
||||
const header = res.headers.get("Content-Security-Policy")!;
|
||||
expect(header).toContain("default-src 'self'");
|
||||
expect(header).not.toContain("upgrade-insecure-requests");
|
||||
});
|
||||
|
||||
Deno.test("CSP - useNonce omits upgrade-insecure-requests over http", async () => {
|
||||
const handler = new App()
|
||||
.use(csp({ useNonce: true }))
|
||||
.get("/", () => new Response("ok"))
|
||||
.handler();
|
||||
const resHttp = await handler(new Request("http://localhost/"));
|
||||
expect(resHttp.headers.get("Content-Security-Policy")).not.toContain(
|
||||
"upgrade-insecure-requests",
|
||||
);
|
||||
const resHttps = await handler(new Request("https://localhost/"));
|
||||
expect(resHttps.headers.get("Content-Security-Policy")).toContain(
|
||||
"upgrade-insecure-requests",
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("CSP - keeps upgrade-insecure-requests with trusted x-forwarded-proto https", async () => {
|
||||
const handler = new App({ trustProxy: true })
|
||||
.use(csp())
|
||||
.get("/", () => new Response("ok"))
|
||||
.handler();
|
||||
const res = await handler(
|
||||
new Request("http://localhost/", {
|
||||
headers: { "x-forwarded-proto": "https" },
|
||||
}),
|
||||
);
|
||||
expect(res.headers.get("Content-Security-Policy")).toContain(
|
||||
"upgrade-insecure-requests",
|
||||
);
|
||||
});
|
||||
|
||||
Deno.test("CSP - GET with override options", async () => {
|
||||
const handler = new App()
|
||||
.use(csp({
|
||||
|
||||
@@ -25,6 +25,8 @@ import { parse } from "../../jsonify/parse.ts";
|
||||
import { INTERNAL_PREFIX, PARTIAL_SEARCH_PARAM } from "../../constants.ts";
|
||||
|
||||
export const PARTIAL_ATTR = "f-partial";
|
||||
export const METHOD_ATTR = "f-method";
|
||||
export const UPDATE_URL_ATTR = "f-update-url";
|
||||
|
||||
class NoPartialsError extends Error {}
|
||||
|
||||
@@ -112,6 +114,12 @@ function maybeReplaceHistory(nextUrl: URL) {
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeMethod(raw: string | null | undefined): string {
|
||||
const method = (raw || "get").toUpperCase();
|
||||
// Browsers submit invalid methods like HEAD as GET
|
||||
return method === "HEAD" ? "GET" : method;
|
||||
}
|
||||
|
||||
document.addEventListener("click", async (e) => {
|
||||
let el = e.target;
|
||||
if (el && (el instanceof HTMLElement || el instanceof SVGElement)) {
|
||||
@@ -178,20 +186,38 @@ document.addEventListener("click", async (e) => {
|
||||
}
|
||||
} else if (
|
||||
el && el instanceof HTMLButtonElement &&
|
||||
(el.type !== "submit" || el.form === null)
|
||||
(el.type !== "submit" || el.form === null) &&
|
||||
!e.defaultPrevented
|
||||
) {
|
||||
const partial = el.getAttribute(PARTIAL_ATTR);
|
||||
if (partial === null || !checkClientNavEnabled(el)) return;
|
||||
|
||||
// Check if the user opted out of client side navigation.
|
||||
if (partial === null || !checkClientNavEnabled(el)) {
|
||||
return;
|
||||
const method = normalizeMethod(el.getAttribute(METHOD_ATTR));
|
||||
const partialUrl = new URL(partial, location.href);
|
||||
|
||||
let init: RequestInit | undefined;
|
||||
if (method !== "GET") {
|
||||
const body = el.form ? new FormData(el.form) : new FormData();
|
||||
if (el.name) {
|
||||
body.append(el.name, el.value);
|
||||
}
|
||||
init = { method, body };
|
||||
}
|
||||
|
||||
const partialUrl = new URL(
|
||||
partial,
|
||||
location.href,
|
||||
);
|
||||
await fetchPartials(partialUrl, partialUrl, false);
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const indicator = (el as any)._freshIndicator;
|
||||
if (indicator !== undefined) {
|
||||
indicator.value = true;
|
||||
}
|
||||
try {
|
||||
await withViewTransition(() =>
|
||||
fetchPartials(partialUrl, partialUrl, false, init)
|
||||
);
|
||||
} finally {
|
||||
if (indicator !== undefined) {
|
||||
indicator.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -262,14 +288,18 @@ document.addEventListener("submit", async (e) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const lowerMethod =
|
||||
e.submitter?.getAttribute("formmethod")?.toLowerCase() ??
|
||||
el.method.toLowerCase();
|
||||
if (lowerMethod !== "get" && lowerMethod !== "post") {
|
||||
const method = normalizeMethod(
|
||||
e.submitter?.getAttribute("formmethod") || el.getAttribute("method"),
|
||||
);
|
||||
|
||||
if (method === "DIALOG") {
|
||||
return;
|
||||
}
|
||||
|
||||
const hasExplicitPartial = e.submitter?.hasAttribute(PARTIAL_ATTR) ||
|
||||
const isCustomMethod = method !== "GET" && method !== "POST";
|
||||
|
||||
const hasExplicitPartial = isCustomMethod ||
|
||||
e.submitter?.hasAttribute(PARTIAL_ATTR) ||
|
||||
e.submitter?.hasAttribute("formaction") ||
|
||||
el.hasAttribute(PARTIAL_ATTR) ||
|
||||
el.hasAttribute("action");
|
||||
@@ -300,18 +330,28 @@ document.addEventListener("submit", async (e) => {
|
||||
let init: RequestInit | undefined;
|
||||
|
||||
// GET method appends form data via url search params
|
||||
if (lowerMethod === "get") {
|
||||
if (method === "GET") {
|
||||
// TODO: Looks like constructor type for URLSearchParam is wrong
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const qs = new URLSearchParams(new FormData(el, e.submitter) as any);
|
||||
qs.forEach((value, key) => partialUrl.searchParams.append(key, value));
|
||||
} else {
|
||||
init = { body: new FormData(el, e.submitter), method: lowerMethod };
|
||||
init = {
|
||||
body: new FormData(el, e.submitter),
|
||||
method,
|
||||
};
|
||||
}
|
||||
|
||||
// GET and POST update the URL by default, other methods don't
|
||||
const updateUrl = e.submitter?.getAttribute(UPDATE_URL_ATTR) ??
|
||||
el.getAttribute(UPDATE_URL_ATTR);
|
||||
const shouldNavigate = updateUrl === null
|
||||
? !isCustomMethod
|
||||
: updateUrl !== "false";
|
||||
|
||||
try {
|
||||
await withViewTransition(async () => {
|
||||
await fetchPartials(actionUrl, partialUrl, true, init);
|
||||
await fetchPartials(actionUrl, partialUrl, shouldNavigate, init);
|
||||
});
|
||||
} finally {
|
||||
if (indicator !== undefined) {
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import { Context, type ServerIslandRegistry } from "./context.ts";
|
||||
import { Context } from "./context.ts";
|
||||
import type { FsAdapter } from "./fs.ts";
|
||||
import type { BuildCache, StaticFile } from "./build_cache.ts";
|
||||
import { type BuildCache, MockBuildCache } from "./build_cache.ts";
|
||||
import type { ResolvedFreshConfig } from "./config.ts";
|
||||
import type { WalkEntry } from "@std/fs/walk";
|
||||
import { DEFAULT_CONN_INFO } from "./app.ts";
|
||||
import type { Command } from "./commands.ts";
|
||||
import { fsItemsToCommands, type FsRouteFile } from "./fs_routes.ts";
|
||||
import * as path from "@std/path";
|
||||
import { toPosix } from "./dev/dev_build_cache.ts";
|
||||
import { toPosix } from "./utils.ts";
|
||||
|
||||
const STUB = {} as unknown as Deno.ServeHandlerInfo;
|
||||
|
||||
@@ -162,30 +160,7 @@ export async function withTmpDir(
|
||||
};
|
||||
}
|
||||
|
||||
export class MockBuildCache<State> implements BuildCache<State> {
|
||||
#files: FsRouteFile<State>[];
|
||||
root = "";
|
||||
clientEntry = "";
|
||||
islandRegistry: ServerIslandRegistry = new Map();
|
||||
features = { errorOverlay: false };
|
||||
|
||||
constructor(files: FsRouteFile<State>[], mode: "development" | "production") {
|
||||
this.features.errorOverlay = mode === "development";
|
||||
this.#files = files;
|
||||
}
|
||||
|
||||
getEntryAssets(): string[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
getFsRoutes(): Command<State>[] {
|
||||
return fsItemsToCommands(this.#files);
|
||||
}
|
||||
|
||||
readFile(_pathname: string): Promise<StaticFile | null> {
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
}
|
||||
export { MockBuildCache };
|
||||
|
||||
/**
|
||||
* Wrapper around `Deno.test` for integration tests that disables sanitizers.
|
||||
|
||||
@@ -2,6 +2,13 @@ import * as path from "@std/path";
|
||||
import type { Lazy, MaybeLazy } from "./types.ts";
|
||||
import { pathToFileUrl, relativeUrl } from "./file_url.ts";
|
||||
|
||||
/** Normalize a path to use forward slashes so that generated files
|
||||
* are portable across operating systems (e.g. build on Windows,
|
||||
* deploy on Linux). */
|
||||
export function toPosix(p: string): string {
|
||||
return p.replaceAll("\\", "/");
|
||||
}
|
||||
|
||||
export function assertInDir(
|
||||
filePath: string,
|
||||
dir: string,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { App, staticFiles } from "sweet";
|
||||
import { App, type Context, staticFiles } from "sweet";
|
||||
import { Partial } from "sweet/runtime";
|
||||
import {
|
||||
ALL_ISLAND_DIR,
|
||||
@@ -1955,6 +1955,545 @@ Deno.test({
|
||||
},
|
||||
});
|
||||
|
||||
async function renderMethodPartial(ctx: Context<unknown>) {
|
||||
const data = await ctx.req.formData();
|
||||
const name = data.get("name");
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<Partial name="foo">
|
||||
<p class={`done-${ctx.req.method}-${name}`}>done</p>
|
||||
</Partial>
|
||||
</Doc>,
|
||||
);
|
||||
}
|
||||
|
||||
Deno.test({
|
||||
name: "partials - submit form with formmethod DELETE, PATCH and PUT",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.delete("/", renderMethodPartial)
|
||||
.patch("/", renderMethodPartial)
|
||||
.put("/", renderMethodPartial)
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<form>
|
||||
<input name="name" value="foo" />
|
||||
<SelfCounter />
|
||||
<button type="submit" class="delete" formmethod="DELETE">
|
||||
delete
|
||||
</button>
|
||||
<button type="submit" class="patch" formmethod="PATCH">
|
||||
patch
|
||||
</button>
|
||||
<button type="submit" class="put" formmethod="put">
|
||||
put
|
||||
</button>
|
||||
</form>
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".ready").wait();
|
||||
|
||||
await page.locator(".increment").click();
|
||||
await waitForText(page, ".output", "1");
|
||||
|
||||
await page.locator(".delete").click();
|
||||
await page.locator(".done-DELETE-foo").wait();
|
||||
|
||||
await page.locator(".patch").click();
|
||||
await page.locator(".done-PATCH-foo").wait();
|
||||
|
||||
await page.locator(".put").click();
|
||||
await page.locator(".done-PUT-foo").wait();
|
||||
|
||||
// Island state survives, so no full page reload happened
|
||||
await waitForText(page, ".output", "1");
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - submit form with custom method on form element",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.patch("/", renderMethodPartial)
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<form method="patch">
|
||||
<input name="name" value="foo" />
|
||||
<SelfCounter />
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
<button type="submit" class="update">update</button>
|
||||
</form>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".ready").wait();
|
||||
|
||||
await page.locator(".increment").click();
|
||||
await waitForText(page, ".output", "1");
|
||||
|
||||
await page.locator(".update").click();
|
||||
await page.locator(".done-PATCH-foo").wait();
|
||||
await waitForText(page, ".output", "1");
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - form without method inside f-client-nav not intercepted",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.get("/", (ctx) => {
|
||||
if (ctx.url.searchParams.has("name")) {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<p class="submitted">form submitted normally</p>
|
||||
</Doc>,
|
||||
);
|
||||
}
|
||||
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<form>
|
||||
<input name="name" value="foo" />
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
<button type="submit" class="update">update</button>
|
||||
</form>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".init").wait();
|
||||
|
||||
await Promise.all([
|
||||
page.waitForNavigation(),
|
||||
page.locator(".update").click(),
|
||||
]);
|
||||
await page.locator(".submitted").wait();
|
||||
|
||||
const search = await page.evaluate(() => window.location.search);
|
||||
expect(search).toEqual("?name=foo");
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - submit form DELETE with 303 redirect",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.get("/done", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<Partial name="foo">
|
||||
<h1 class="done">deleted</h1>
|
||||
</Partial>
|
||||
</Doc>,
|
||||
);
|
||||
})
|
||||
.delete("/", () => {
|
||||
return new Response(null, {
|
||||
status: 303,
|
||||
headers: { Location: "/done" },
|
||||
});
|
||||
})
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<form>
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
<button
|
||||
type="submit"
|
||||
class="update"
|
||||
formmethod="DELETE"
|
||||
f-update-url="true"
|
||||
>
|
||||
delete
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".init").wait();
|
||||
|
||||
await page.locator(".update").click();
|
||||
await page.locator(".done").wait();
|
||||
|
||||
const pathname = await page.evaluate(() => window.location.pathname);
|
||||
expect(pathname).toEqual("/done");
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - submit form f-update-url",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.delete("/items/1", renderMethodPartial)
|
||||
.post("/partial", renderMethodPartial)
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<form>
|
||||
<input name="name" value="foo" />
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
<button
|
||||
type="submit"
|
||||
class="delete"
|
||||
formaction="/items/1"
|
||||
formmethod="DELETE"
|
||||
>
|
||||
delete
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
class="post"
|
||||
formaction="/partial"
|
||||
formmethod="POST"
|
||||
f-update-url="false"
|
||||
>
|
||||
post
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".init").wait();
|
||||
|
||||
// Custom methods leave the URL alone by default
|
||||
await page.locator(".delete").click();
|
||||
await page.locator(".done-DELETE-foo").wait();
|
||||
let pathname = await page.evaluate(() => window.location.pathname);
|
||||
expect(pathname).toEqual("/");
|
||||
|
||||
// f-update-url="false" opts POST out of updating the URL
|
||||
await page.locator(".post").click();
|
||||
await page.locator(".done-POST-foo").wait();
|
||||
pathname = await page.evaluate(() => window.location.pathname);
|
||||
expect(pathname).toEqual("/");
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - submit form with formmethod HEAD is sent as GET",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.get("/partial", (ctx) => {
|
||||
const name = ctx.url.searchParams.get("name");
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<Partial name="foo">
|
||||
<p class={`done-${ctx.req.method}-${name}`}>done</p>
|
||||
</Partial>
|
||||
</Doc>,
|
||||
);
|
||||
})
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<form action="/partial">
|
||||
<input name="name" value="foo" />
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
<button type="submit" class="update" formmethod="head">
|
||||
update
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".init").wait();
|
||||
|
||||
await page.locator(".update").click();
|
||||
await page.locator(".done-GET-foo").wait();
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - button f-method outside form",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.delete("/partial", renderMethodPartial)
|
||||
.patch("/partial", renderMethodPartial)
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<SelfCounter />
|
||||
<button
|
||||
type="button"
|
||||
class="delete"
|
||||
f-partial="/partial"
|
||||
f-method="DELETE"
|
||||
name="name"
|
||||
value="foo"
|
||||
>
|
||||
delete
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="patch"
|
||||
f-partial="/partial"
|
||||
f-method="patch"
|
||||
name="name"
|
||||
value="bar"
|
||||
>
|
||||
patch
|
||||
</button>
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".ready").wait();
|
||||
|
||||
await page.locator(".increment").click();
|
||||
await waitForText(page, ".output", "1");
|
||||
|
||||
await page.locator(".delete").click();
|
||||
await page.locator(".done-DELETE-foo").wait();
|
||||
|
||||
await page.locator(".patch").click();
|
||||
await page.locator(".done-PATCH-bar").wait();
|
||||
|
||||
// Island state survives and the URL is left alone
|
||||
await waitForText(page, ".output", "1");
|
||||
const pathname = await page.evaluate(() => window.location.pathname);
|
||||
expect(pathname).toEqual("/");
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - button f-method inside form sends form fields",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.put("/partial", async (ctx) => {
|
||||
const data = await ctx.req.formData();
|
||||
const name = data.get("name");
|
||||
const extra = data.get("extra");
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<Partial name="foo">
|
||||
<p class={`done-${ctx.req.method}-${name}-${extra}`}>done</p>
|
||||
</Partial>
|
||||
</Doc>,
|
||||
);
|
||||
})
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<form>
|
||||
<input name="name" value="foo" />
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
<button
|
||||
type="button"
|
||||
class="update"
|
||||
f-partial="/partial"
|
||||
f-method="PUT"
|
||||
name="extra"
|
||||
value="bar"
|
||||
>
|
||||
update
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".init").wait();
|
||||
|
||||
await page.locator(".update").click();
|
||||
await page.locator(".done-PUT-foo-bar").wait();
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - button f-method cancelled with preventDefault",
|
||||
fn: async () => {
|
||||
let deleteCalls = 0;
|
||||
const app = testApp()
|
||||
.delete("/partial", (ctx) => {
|
||||
deleteCalls++;
|
||||
return renderMethodPartial(ctx);
|
||||
})
|
||||
.get("/other", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<Partial name="foo">
|
||||
<p class="other">other</p>
|
||||
</Partial>
|
||||
</Doc>,
|
||||
);
|
||||
})
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<button
|
||||
type="button"
|
||||
class="delete"
|
||||
f-partial="/partial"
|
||||
f-method="DELETE"
|
||||
name="name"
|
||||
value="foo"
|
||||
>
|
||||
delete
|
||||
</button>
|
||||
<button type="button" class="other-btn" f-partial="/other">
|
||||
other
|
||||
</button>
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".init").wait();
|
||||
|
||||
await page.evaluate(() => {
|
||||
document.querySelector(".delete")!.addEventListener(
|
||||
"click",
|
||||
(e) => e.preventDefault(),
|
||||
);
|
||||
});
|
||||
|
||||
await page.locator(".delete").click();
|
||||
|
||||
// Trigger a second partial request after the cancelled one so we know
|
||||
// the click handler has run before checking the DELETE handler.
|
||||
await page.locator(".other-btn").click();
|
||||
await page.locator(".other").wait();
|
||||
|
||||
expect(deleteCalls).toEqual(0);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - button f-method indicator",
|
||||
fn: async () => {
|
||||
const app = testApp()
|
||||
.delete("/partial", renderMethodPartial)
|
||||
.get("/", (ctx) => {
|
||||
return ctx.render(
|
||||
<Doc>
|
||||
<div f-client-nav>
|
||||
<button
|
||||
type="button"
|
||||
class="delete"
|
||||
f-partial="/partial"
|
||||
f-method="DELETE"
|
||||
name="name"
|
||||
value="foo"
|
||||
>
|
||||
delete
|
||||
</button>
|
||||
<Partial name="foo">
|
||||
<p class="init">init</p>
|
||||
</Partial>
|
||||
</div>
|
||||
</Doc>,
|
||||
);
|
||||
});
|
||||
|
||||
await withBrowserApp(app, async (page, address) => {
|
||||
await page.goto(address, { waitUntil: "load" });
|
||||
await page.locator(".init").wait();
|
||||
|
||||
await page.evaluate(() => {
|
||||
const btn = document.querySelector(".delete")!;
|
||||
const indicator = { _wasTrue: false, _value: false };
|
||||
Object.defineProperty(indicator, "value", {
|
||||
get() {
|
||||
return this._value;
|
||||
},
|
||||
set(v: boolean) {
|
||||
this._value = v;
|
||||
if (v) this._wasTrue = true;
|
||||
},
|
||||
});
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(btn as any)._freshIndicator = indicator;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
(window as any).__indicator = indicator;
|
||||
});
|
||||
|
||||
await page.locator(".delete").click();
|
||||
await page.locator(".done-DELETE-foo").wait();
|
||||
|
||||
const result = await page.evaluate(() => {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const ind = (window as any).__indicator;
|
||||
return { wasTrue: ind._wasTrue, currentValue: ind.value };
|
||||
});
|
||||
expect(result.wasTrue).toBe(true);
|
||||
expect(result.currentValue).toBe(false);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
Deno.test({
|
||||
name: "partials - submit form via external submitter",
|
||||
fn: async () => {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { expect } from "@std/expect";
|
||||
|
||||
// Guards against runtime code importing the esbuild dev builder (`src/dev/`)
|
||||
// or test helpers. That happened once through `app.ts` -> `test_utils.ts` ->
|
||||
// `dev/dev_build_cache.ts`: every app then loaded esbuild at startup, and
|
||||
// Vite projects printed "dynamic import cannot be analyzed" warnings.
|
||||
|
||||
const SRC_URL = new URL("../src/", import.meta.url).href;
|
||||
|
||||
/** Entry points that end up in a user's app at runtime (see deno.json). */
|
||||
const RUNTIME_ENTRIES = [
|
||||
"mod.ts",
|
||||
"runtime/shared.ts",
|
||||
"runtime/client/mod.ts",
|
||||
"internals.ts",
|
||||
"compat.ts",
|
||||
];
|
||||
|
||||
/** Under `src/dev/` but lightweight and needed by the server renderer. */
|
||||
const ALLOWED_DEV_MODULES = ["dev/middlewares/error_overlay/code_frame.ts"];
|
||||
|
||||
/** Paths under `src/` of every local module in the graph, plus all others. */
|
||||
async function moduleGraph(
|
||||
entry: string,
|
||||
): Promise<{ local: string[]; other: string[] }> {
|
||||
const out = await new Deno.Command(Deno.execPath(), {
|
||||
// Must be a file URL: on Windows a bare `C:\...` path parses as a URL
|
||||
// with scheme `c:` and the graph comes back empty.
|
||||
args: ["info", "--json", new URL(entry, SRC_URL).href],
|
||||
stdout: "piped",
|
||||
stderr: "piped",
|
||||
}).output();
|
||||
if (!out.success) {
|
||||
throw new Error(new TextDecoder().decode(out.stderr));
|
||||
}
|
||||
const info = JSON.parse(new TextDecoder().decode(out.stdout)) as {
|
||||
modules: { specifier: string }[];
|
||||
};
|
||||
|
||||
// Drive letter casing can differ between the two, so compare lowercased.
|
||||
const prefix = SRC_URL.toLowerCase();
|
||||
const local: string[] = [];
|
||||
const other: string[] = [];
|
||||
for (const { specifier } of info.modules) {
|
||||
if (specifier.toLowerCase().startsWith(prefix)) {
|
||||
local.push(specifier.slice(prefix.length));
|
||||
} else {
|
||||
other.push(specifier);
|
||||
}
|
||||
}
|
||||
return { local, other };
|
||||
}
|
||||
|
||||
for (const entry of RUNTIME_ENTRIES) {
|
||||
Deno.test(`runtime imports - ${entry} doesn't load dev builder or test helpers`, async () => {
|
||||
const { local, other } = await moduleGraph(entry);
|
||||
|
||||
// Sanity check, so a failed lookup can't pass with an empty graph.
|
||||
expect(local).toContain(entry);
|
||||
|
||||
const forbidden = [
|
||||
...local.filter((rel) =>
|
||||
rel === "test_utils.ts" ||
|
||||
(rel.startsWith("dev/") && !ALLOWED_DEV_MODULES.includes(rel))
|
||||
),
|
||||
...other.filter((spec) => /esbuild/.test(spec)),
|
||||
];
|
||||
expect(forbidden).toEqual([]);
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@paulaboks/sweet-init",
|
||||
"version": "2.3.3",
|
||||
"version": "2.3.7",
|
||||
"license": "MIT",
|
||||
"exports": {
|
||||
".": "./src/mod.ts",
|
||||
|
||||
@@ -5,11 +5,11 @@ import * as semver from "@std/semver";
|
||||
import initConfig from "../deno.json" with { type: "json" };
|
||||
|
||||
// Keep these as is, as we replace these version in our release script
|
||||
const FRESH_VERSION = "2.3.3";
|
||||
const FRESH_VERSION = "2.3.7";
|
||||
const FRESH_TAILWIND_VERSION = "1.0.0";
|
||||
const FRESH_VITE_PLUGIN = "1.1.2";
|
||||
const PREACT_VERSION = "10.29.1";
|
||||
const PREACT_SIGNALS_VERSION = "2.9.0";
|
||||
const PREACT_VERSION = "10.29.8";
|
||||
const PREACT_SIGNALS_VERSION = "2.11.4";
|
||||
const TAILWINDCSS_VERSION = "4.1.10";
|
||||
const TAILWINDCSS_POSTCSS_VERSION = "4.1.10";
|
||||
const POSTCSS_VERSION = "8.5.6";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@fresh/update",
|
||||
"version": "2.3.3",
|
||||
"version": "2.3.7",
|
||||
"license": "MIT",
|
||||
"exports": "./src/mod.ts",
|
||||
"exclude": ["**/tmp/*"],
|
||||
|
||||
@@ -7,9 +7,9 @@ import { walk } from "@std/fs/walk";
|
||||
|
||||
export const SyntaxKind = tsmorph.ts.SyntaxKind;
|
||||
|
||||
export const FRESH_VERSION = "2.3.3";
|
||||
export const PREACT_VERSION = "10.29.1";
|
||||
export const PREACT_SIGNALS_VERSION = "2.9.0";
|
||||
export const FRESH_VERSION = "2.3.7";
|
||||
export const PREACT_VERSION = "10.29.8";
|
||||
export const PREACT_SIGNALS_VERSION = "2.11.4";
|
||||
|
||||
// Directories to skip when walking the project tree. Covers hidden directories,
|
||||
// dependency caches, and common build output folders.
|
||||
|
||||
+18
-3
@@ -104,7 +104,11 @@ function replaceJsonVersion(version: string) {
|
||||
await replaceInFile(denoJsonPath, replaceJsonVersion(nextVersion));
|
||||
await replaceInFile(updateJsonPath, replaceJsonVersion(nextVersion));
|
||||
|
||||
async function getNpmVersion(name: string) {
|
||||
/** Sweet stays on Preact 10; don't follow npm's `latest` to a new major. */
|
||||
const PREACT_MAJOR = 10;
|
||||
|
||||
/** Latest stable version on npm, optionally limited to one major version. */
|
||||
async function getNpmVersion(name: string, major?: number): Promise<string> {
|
||||
const res = await fetch(`https://registry.npmjs.org/${name}`, {
|
||||
headers: {
|
||||
"Accept":
|
||||
@@ -112,11 +116,22 @@ async function getNpmVersion(name: string) {
|
||||
},
|
||||
});
|
||||
const json = await res.json();
|
||||
return json["dist-tags"].latest;
|
||||
if (major === undefined) return json["dist-tags"].latest;
|
||||
|
||||
const versions = Object.keys(json.versions)
|
||||
.map((v) => semver.tryParse(v))
|
||||
.filter((v): v is semver.SemVer =>
|
||||
v !== undefined && v.major === major && !v.prerelease?.length
|
||||
)
|
||||
.sort(semver.compare);
|
||||
if (versions.length === 0) {
|
||||
exitError(`No ${major}.x release of ${name} found on npm`);
|
||||
}
|
||||
return semver.format(versions.at(-1)!);
|
||||
}
|
||||
|
||||
const [preactVersion, preactSignalsVersion] = await Promise.all([
|
||||
getNpmVersion("preact"),
|
||||
getNpmVersion("preact", PREACT_MAJOR),
|
||||
getNpmVersion("@preact/signals"),
|
||||
]);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user