@opentf/afw 0.32.0 → 0.34.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +93 -36
- package/core/metadata.js +2 -0
- package/index.d.ts +1 -0
- package/jsx-runtime.d.ts +3 -1
- package/macros.d.ts +24 -0
- package/package.json +12 -5
- package/runtime/hmr.js +52 -9
- package/runtime/hydrate.d.ts +6 -0
- package/runtime/hydrate.js +48 -0
- package/runtime/mount.js +3 -0
- package/runtime/route-match.js +99 -0
- package/runtime/router.d.ts +3 -0
- package/runtime/router.js +72 -30
- package/server/adapters/node.js +31 -6
- package/server/api.d.ts +3 -1
- package/server/api.js +14 -58
- package/server/index.d.ts +8 -0
- package/server/index.js +1 -1
- package/server/loader.js +5 -42
- package/server/middleware.js +16 -14
- package/server/render.js +3 -0
- package/server/ssg-runtime.js +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Open Tech Foundation and contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,26 +1,98 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
1
3
|
# @opentf/afw
|
|
2
4
|
|
|
3
|
-
The
|
|
4
|
-
|
|
5
|
+
***The AFW runtime: signals and zero-VDOM DOM bindings***
|
|
6
|
+
|
|
7
|
+
[Docs](https://afw.opentechf.org/docs) | [Reactivity](https://afw.opentechf.org/docs/core-concepts/reactivity) | [Changelog](https://github.com/Open-Tech-Foundation/afw/blob/main/packages/afw/CHANGELOG.md) | [GitHub](https://github.com/Open-Tech-Foundation/afw)
|
|
8
|
+
|
|
9
|
+
</div>
|
|
10
|
+
|
|
11
|
+
<div align="right">
|
|
12
|
+
|
|
13
|
+
*An [Open Tech Foundation](https://opentechf.org/) project*
|
|
14
|
+
|
|
15
|
+
</div>
|
|
16
|
+
|
|
17
|
+
> You write `.jsx` components; the AFW compiler lowers them to plain DOM code that
|
|
18
|
+
> imports its helpers from this package. Each component becomes a self-registering
|
|
19
|
+
> Custom Element, and each `{expression}` becomes one binding to one signal.
|
|
20
|
+
|
|
21
|
+
```jsx
|
|
22
|
+
import { onMount } from "@opentf/afw";
|
|
5
23
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
`bindText`, `bindList`, …) from this package. Components compile to self-registering
|
|
9
|
-
`web-*` Custom Elements.
|
|
24
|
+
export default function Clock() {
|
|
25
|
+
let now = $state(null);
|
|
10
26
|
|
|
11
|
-
|
|
27
|
+
onMount(() => {
|
|
28
|
+
now = new Date();
|
|
29
|
+
const id = setInterval(() => (now = new Date()), 1000);
|
|
30
|
+
return () => clearInterval(id);
|
|
31
|
+
});
|
|
12
32
|
|
|
13
|
-
|
|
33
|
+
return <time>{now ? now.toLocaleTimeString() : "Loading clock…"}</time>;
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Every second, one text node changes; nothing else on the page is touched.
|
|
38
|
+
Returning a function from `onMount` registers its cleanup.
|
|
39
|
+
|
|
40
|
+
> [!NOTE]
|
|
41
|
+
> **Alpha.** The API can change between minor versions; see the
|
|
42
|
+
> [changelog](https://github.com/Open-Tech-Foundation/afw/blob/main/packages/afw/CHANGELOG.md).
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
```sh
|
|
14
47
|
pnpm add @opentf/afw
|
|
48
|
+
pnpm add -D @opentf/esdev-plugin-afw
|
|
15
49
|
```
|
|
16
50
|
|
|
17
|
-
|
|
18
|
-
|
|
51
|
+
Components compile through [`@opentf/esdev-plugin-afw`](https://www.npmjs.com/package/@opentf/esdev-plugin-afw)
|
|
52
|
+
on [esdev](https://esrun.opentechf.org/esdev) 0.17 or newer. To start from a
|
|
53
|
+
working app instead, run `esdev create my-app --template=spa`.
|
|
54
|
+
|
|
55
|
+
## What's inside
|
|
56
|
+
|
|
57
|
+
| Area | Contents |
|
|
58
|
+
| --- | --- |
|
|
59
|
+
| **Reactivity** | A signal / computed / effect core, written from scratch |
|
|
60
|
+
| **DOM bindings** | `bindText`, `bindAttr`, `bindList`, `bindChild`, `setProp`, `spread`, `clsx`: the targets the compiler emits |
|
|
61
|
+
| **Components** | `Context`, `Portal`, `ErrorBoundary`, event dispatch with `emit` |
|
|
62
|
+
| **Routing** | `mountApp`, the reactive `router`, `<Link>`, guards, loaders, locale prefixes |
|
|
63
|
+
| **Server** | DOM-free SSR/SSG rendering, API routes, middleware, cookies, a Node adapter |
|
|
64
|
+
|
|
65
|
+
## Macros and hooks
|
|
66
|
+
|
|
67
|
+
Written in your components and resolved by the compiler; nothing to import for the
|
|
68
|
+
`$` macros.
|
|
69
|
+
|
|
70
|
+
| Macro / hook | Purpose |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `$state(value)` | Reactive local state; assign to it like a variable |
|
|
73
|
+
| `$derived(expr)` | A value recomputed when its inputs change |
|
|
74
|
+
| `$effect(fn)` | Run side effects when their inputs change |
|
|
75
|
+
| `$ref()` | A reference to a rendered element or component |
|
|
76
|
+
| `$context(Context)` | Read the nearest provided context value |
|
|
77
|
+
| `$expose({ … })` | Methods a parent can call through a ref |
|
|
78
|
+
| `onMount`, `onCleanup` | Lifecycle of the component's host element |
|
|
79
|
+
| `onResize`, `onVisibilityChange`, `onMediaQuery` | Observers that clean up with the component |
|
|
80
|
+
|
|
81
|
+
## Entry points
|
|
82
|
+
|
|
83
|
+
| Import | Contents |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `@opentf/afw` | Runtime, reactivity and `Link`: what compiled components import |
|
|
86
|
+
| `@opentf/afw/signals` | The reactivity core on its own |
|
|
87
|
+
| `@opentf/afw/runtime` | DOM helpers, `Context`, `Portal`, `ErrorBoundary` |
|
|
88
|
+
| `@opentf/afw/server` | DOM-free rendering, route registration, API and middleware helpers |
|
|
89
|
+
| `@opentf/afw/server/adapters/node` | `toNodeListener` for `node:http` servers |
|
|
90
|
+
| `@opentf/afw/jsx-runtime` | JSX type definitions for TypeScript |
|
|
19
91
|
|
|
20
92
|
## TypeScript
|
|
21
93
|
|
|
22
|
-
|
|
23
|
-
|
|
94
|
+
Declarations ship with the package. Keep JSX for the AFW compiler and point
|
|
95
|
+
`jsxImportSource` at this package:
|
|
24
96
|
|
|
25
97
|
```json
|
|
26
98
|
{
|
|
@@ -35,33 +107,18 @@ JSX for the AFW compiler and select the framework's type entry:
|
|
|
35
107
|
}
|
|
36
108
|
```
|
|
37
109
|
|
|
38
|
-
`esdev create my-app --language=ts`
|
|
39
|
-
declarations.
|
|
40
|
-
still runs through `@opentf/esdev-plugin-afw`. Compiler helper signatures remain
|
|
41
|
-
permissive; signals and lifecycle callbacks carry their value and event types.
|
|
42
|
-
|
|
43
|
-
## What's inside
|
|
44
|
-
|
|
45
|
-
- **Reactivity** — a from-scratch `signal` / `computed` / `effect` core.
|
|
46
|
-
- **DOM runtime** — fine-grained bindings (`bindText`, `bindAttr`, `bindList`,
|
|
47
|
-
`bindChild`, `setProp`, `spread`, `clsx`) the compiler targets, plus `Context`,
|
|
48
|
-
`Portal`, `ErrorBoundary`, and event dispatch (`emit`).
|
|
49
|
-
- **Compiler macros** — authored in your components, resolved at compile time:
|
|
50
|
-
`$state`, `$derived`, `$ref`, `$context`, `$effect`, `$expose`, and the
|
|
51
|
-
`onMount` / `onCleanup` / `onResize` / `onVisibilityChange` / `onMediaQuery`
|
|
52
|
-
lifecycle hooks.
|
|
53
|
-
- **`<Link>`** — client-side navigation, shipped as JSX source and compiled by your
|
|
54
|
-
app's pipeline.
|
|
110
|
+
`esdev create my-app --language=ts` generates this configuration together with the
|
|
111
|
+
macro declarations.
|
|
55
112
|
|
|
56
|
-
##
|
|
113
|
+
## Documentation
|
|
57
114
|
|
|
58
|
-
|
|
|
115
|
+
| Topic | Link |
|
|
59
116
|
| --- | --- |
|
|
60
|
-
|
|
|
61
|
-
|
|
|
62
|
-
|
|
|
63
|
-
|
|
|
117
|
+
| Components and JSX | [Core concepts](https://afw.opentechf.org/docs/core-concepts/components) |
|
|
118
|
+
| Reactivity | [Signals, derived values and effects](https://afw.opentechf.org/docs/core-concepts/reactivity) |
|
|
119
|
+
| Routing | [Pages, layouts, guards and API routes](https://afw.opentechf.org/docs/routing/pages-and-layouts) |
|
|
120
|
+
| Deployment | [Static generation, hydration and servers](https://afw.opentechf.org/docs/deployment) |
|
|
64
121
|
|
|
65
122
|
## License
|
|
66
123
|
|
|
67
|
-
MIT
|
|
124
|
+
MIT — see [LICENSE](https://github.com/Open-Tech-Foundation/afw/blob/main/LICENSE).
|
package/core/metadata.js
CHANGED
|
@@ -134,6 +134,8 @@ export function renderHead(meta = {}, { path = "/", baseUrl = "", managed = fals
|
|
|
134
134
|
push(metaTag("property", "og:url", og.url ? absUrl(baseUrl, og.url) : canonical));
|
|
135
135
|
push(metaTag("property", "og:image", ogImage));
|
|
136
136
|
push(metaTag("property", "og:site_name", og.siteName));
|
|
137
|
+
push(metaTag("property", "og:locale", og.locale));
|
|
138
|
+
for (const alt of [].concat(og.alternateLocale ?? [])) push(metaTag("property", "og:locale:alternate", alt));
|
|
137
139
|
|
|
138
140
|
// Twitter Card (falls back to Open Graph / top-level values).
|
|
139
141
|
const tw = isPlainObject(meta.twitter) ? meta.twitter : {};
|
package/index.d.ts
CHANGED
package/jsx-runtime.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference path="./macros.d.ts" />
|
|
1
2
|
/** Type-only JSX entry for the AFW compiler (`jsx: "preserve"`). */
|
|
2
3
|
export namespace JSX {
|
|
3
4
|
type Element = Node;
|
|
@@ -15,7 +16,8 @@ export namespace JSX {
|
|
|
15
16
|
class?: string | Record<string, unknown> | unknown[];
|
|
16
17
|
className?: string;
|
|
17
18
|
style?: string | Record<string, string | number | undefined>;
|
|
18
|
-
ref
|
|
19
|
+
/** A signal holding the element, or a `$ref()` variable (typed as the element itself). */
|
|
20
|
+
ref?: { value: E | null | undefined } | E;
|
|
19
21
|
tabindex?: number;
|
|
20
22
|
autofocus?: boolean;
|
|
21
23
|
readonly?: boolean;
|
package/macros.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Types for AFW's compiler macros. The compiler rewrites these calls, so they are
|
|
2
|
+
// globals with no runtime import; this file only teaches TypeScript and editors
|
|
3
|
+
// their shapes. It is referenced from the package's types and its JSX types, so a
|
|
4
|
+
// project typed against `@opentf/afw` sees them without extra setup.
|
|
5
|
+
|
|
6
|
+
import type { Context } from "./core/context.js";
|
|
7
|
+
|
|
8
|
+
declare global {
|
|
9
|
+
/** Reactive state: read and write the variable directly (`count++`). */
|
|
10
|
+
function $state<T>(initial: T): T;
|
|
11
|
+
function $state<T = undefined>(): T | undefined;
|
|
12
|
+
/** A cached value, recomputed when the state it reads changes. */
|
|
13
|
+
function $derived<T>(value: T): T;
|
|
14
|
+
/** A side effect that re-runs when the state it reads changes; may return a cleanup. */
|
|
15
|
+
function $effect(fn: () => void | (() => void)): void;
|
|
16
|
+
/** A handle to a DOM node or component element, bound with `ref={…}`. */
|
|
17
|
+
function $ref<T = any>(): T;
|
|
18
|
+
/** The value of the nearest `<ContextProvider>` for `context`. */
|
|
19
|
+
function $context<T>(context: Context<T>): T;
|
|
20
|
+
/** Publish methods on this component's element for a parent holding its `$ref`. */
|
|
21
|
+
function $expose(api: Record<string, unknown>): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opentf/afw",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "The
|
|
3
|
+
"version": "0.34.0",
|
|
4
|
+
"description": "The AFW runtime: signals and zero-VDOM DOM bindings, with routing and server rendering.",
|
|
5
5
|
"type": "module",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"build": "cp ../../LICENSE LICENSE"
|
|
8
|
+
},
|
|
6
9
|
"exports": {
|
|
7
10
|
".": {
|
|
8
11
|
"types": "./index.d.ts",
|
|
@@ -33,6 +36,7 @@
|
|
|
33
36
|
"index.js",
|
|
34
37
|
"index.d.ts",
|
|
35
38
|
"jsx-runtime.d.ts",
|
|
39
|
+
"macros.d.ts",
|
|
36
40
|
"core",
|
|
37
41
|
"runtime",
|
|
38
42
|
"components",
|
|
@@ -40,11 +44,14 @@
|
|
|
40
44
|
"!**/*.test.js"
|
|
41
45
|
],
|
|
42
46
|
"keywords": [
|
|
47
|
+
"afw",
|
|
43
48
|
"opentf",
|
|
44
|
-
"web-components",
|
|
45
49
|
"signals",
|
|
46
50
|
"reactivity",
|
|
47
|
-
"
|
|
51
|
+
"web-components",
|
|
52
|
+
"custom-elements",
|
|
53
|
+
"jsx",
|
|
54
|
+
"ssr",
|
|
48
55
|
"ssg"
|
|
49
56
|
],
|
|
50
57
|
"repository": {
|
|
@@ -52,7 +59,7 @@
|
|
|
52
59
|
"url": "https://github.com/Open-Tech-Foundation/afw.git",
|
|
53
60
|
"directory": "packages/afw"
|
|
54
61
|
},
|
|
55
|
-
"homepage": "https://
|
|
62
|
+
"homepage": "https://afw.opentechf.org",
|
|
56
63
|
"bugs": "https://github.com/Open-Tech-Foundation/afw/issues",
|
|
57
64
|
"license": "MIT",
|
|
58
65
|
"publishConfig": {
|
package/runtime/hmr.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
// Imported only by development compiler output.
|
|
1
|
+
// Imported only by development compiler output. It runs under esdev's and Vite's
|
|
2
|
+
// `import.meta.hot`: it uses `data`, `accept` and `invalidate`, which both provide,
|
|
3
|
+
// and `keep` where esdev has it (see `keep` below). The Custom Elements registry
|
|
2
4
|
// caches lifecycle callbacks at define time, so stable callbacks dispatch to the
|
|
3
5
|
// current implementation rather than redefining an existing tag.
|
|
4
6
|
import { scope } from "../core/signals.js";
|
|
@@ -19,14 +21,33 @@ export function hotRouteState(key, create) {
|
|
|
19
21
|
return routeSlots.get(key);
|
|
20
22
|
}
|
|
21
23
|
|
|
22
|
-
|
|
24
|
+
/**
|
|
25
|
+
* A value made once and returned on every replacement of the module. esdev provides
|
|
26
|
+
* `hot.keep`; Vite's `import.meta.hot` has no `keep`, but its `data` object survives
|
|
27
|
+
* replacement the same way, so the value is kept there.
|
|
28
|
+
*/
|
|
29
|
+
function keep(hot, key, make) {
|
|
30
|
+
if (typeof hot.keep === "function") return hot.keep(key, make);
|
|
31
|
+
const slot = `afwKeep:${key}`;
|
|
32
|
+
if (!(slot in hot.data)) hot.data[slot] = make();
|
|
33
|
+
return hot.data[slot];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* `exports` is the source of the page's exports other than its view and the route data the
|
|
38
|
+
* router re-reads (see the compiler's `hot_exports_shape`). Importers hold the old values,
|
|
39
|
+
* so a change there reloads; an edit to the view, its metadata or its headings refreshes.
|
|
40
|
+
*/
|
|
41
|
+
export function registerHotRoute(hot, factory, shape = "", exports = "", data = {}) {
|
|
23
42
|
if (!hot) return factory;
|
|
24
|
-
if (
|
|
25
|
-
|
|
43
|
+
if (hot.data.afwRouteBoundary && hot.data.afwExports !== exports) {
|
|
44
|
+
hot.data.afwExports = exports;
|
|
45
|
+
hot.invalidate();
|
|
26
46
|
return factory;
|
|
27
47
|
}
|
|
48
|
+
hot.data.afwExports = exports;
|
|
28
49
|
hot.data.afwRouteBoundary = true;
|
|
29
|
-
const record =
|
|
50
|
+
const record = keep(hot, "afw-route", () => {
|
|
30
51
|
const entry = { factory, shape };
|
|
31
52
|
// `previous` is the view node this build replaces during a refresh. Its state
|
|
32
53
|
// slots carry over when the declarations still match; otherwise state is fresh.
|
|
@@ -61,9 +82,12 @@ export function registerHotRoute(hot, factory, safe, shape = "") {
|
|
|
61
82
|
const updated = record.factory !== factory || record.shape !== shape;
|
|
62
83
|
record.factory = factory;
|
|
63
84
|
record.shape = shape;
|
|
85
|
+
// `data`: this update's `metadata`/`generateMetadata`/`toc`, which the router's import of
|
|
86
|
+
// the route (the original module) would not see.
|
|
87
|
+
record.data = data;
|
|
64
88
|
hot.accept();
|
|
65
89
|
if (updated) queueMicrotask(() => {
|
|
66
|
-
if (!hot.data.afwInvalidated) void refreshHotRoute(record.view);
|
|
90
|
+
if (!hot.data.afwInvalidated) void refreshHotRoute(record.view, record.data);
|
|
67
91
|
});
|
|
68
92
|
return record.view;
|
|
69
93
|
}
|
|
@@ -111,16 +135,35 @@ function refresh(record, hosts) {
|
|
|
111
135
|
}
|
|
112
136
|
}
|
|
113
137
|
|
|
114
|
-
|
|
138
|
+
/**
|
|
139
|
+
* `exports` is the source of the module's exports other than its components: importers
|
|
140
|
+
* hold the old values, so a change there reloads, while an edit to the components alone
|
|
141
|
+
* refreshes them in place. Each entry's shape covers what a refresh can't carry over
|
|
142
|
+
* (props, state declarations, the exposed method names).
|
|
143
|
+
*/
|
|
144
|
+
/**
|
|
145
|
+
* `$expose` in a development build: publish `api` on the host like `Object.assign`, after
|
|
146
|
+
* removing whatever the previous version of the component exposed there. A refresh
|
|
147
|
+
* re-runs the component on the same host, so a renamed or removed method would otherwise
|
|
148
|
+
* linger beside its replacement.
|
|
149
|
+
*/
|
|
150
|
+
export function hotExpose(host, api) {
|
|
151
|
+
for (const key of host.__afwExposed ?? []) if (!(key in api)) delete host[key];
|
|
152
|
+
Object.assign(host, api);
|
|
153
|
+
host.__afwExposed = Object.keys(api);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function registerHotModule(hot, entries, accept = true, exports = "") {
|
|
115
157
|
const signature = entries.map(([component, shape]) => [component.tag, shape]);
|
|
116
158
|
const previous = hot?.data.afwSignature;
|
|
117
|
-
if (previous && (
|
|
159
|
+
if (previous && (JSON.stringify(previous) !== JSON.stringify(signature) || hot.data.afwExports !== exports)) {
|
|
118
160
|
hot.data.afwInvalidated = true;
|
|
119
161
|
hot.invalidate();
|
|
120
162
|
return;
|
|
121
163
|
}
|
|
122
164
|
if (hot) {
|
|
123
165
|
hot.data.afwSignature = signature;
|
|
166
|
+
hot.data.afwExports = exports;
|
|
124
167
|
hot.data.afwInvalidated = false;
|
|
125
168
|
}
|
|
126
169
|
const changed = [];
|
|
@@ -166,5 +209,5 @@ export function registerHotModule(hot, entries, safe, accept = true) {
|
|
|
166
209
|
}));
|
|
167
210
|
jobs.sort((a, b) => a.depth - b.depth);
|
|
168
211
|
for (const { record, host } of jobs) refresh(record, [host]);
|
|
169
|
-
if (
|
|
212
|
+
if (accept) hot?.accept();
|
|
170
213
|
}
|
package/runtime/hydrate.d.ts
CHANGED
|
@@ -171,3 +171,9 @@ export const SLOT_END: "c]";
|
|
|
171
171
|
export class HydrationMismatch extends Error {
|
|
172
172
|
constructor(message: any);
|
|
173
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* Adopt a `<p>` holding a component, past its `<!--p]-->` end marker: kept as served when
|
|
176
|
+
* the parser left it intact, rebuilt with `build()` when a block element in a component
|
|
177
|
+
* made the parser close it early. Compiler-emitted.
|
|
178
|
+
*/
|
|
179
|
+
export function hydrateParagraph(cur: any, adopt: (el: any) => void, build: () => any): any;
|
package/runtime/hydrate.js
CHANGED
|
@@ -285,6 +285,54 @@ export function claimElement(cur, tag) {
|
|
|
285
285
|
return el;
|
|
286
286
|
}
|
|
287
287
|
|
|
288
|
+
/**
|
|
289
|
+
* Adopt a `<p>` holding a component (a *recoverable region*), advancing the cursor past
|
|
290
|
+
* its `<!--p]-->` end marker. The compiler cannot see a component's markup, and a block
|
|
291
|
+
* element in it (`<div>`) makes the HTML parser close the `<p>` early, moving the rest of
|
|
292
|
+
* the paragraph out after it. So:
|
|
293
|
+
*
|
|
294
|
+
* - intact (the component rendered inline markup, the common case): `adopt(el)` wires the
|
|
295
|
+
* served paragraph and the marker follows it directly. Nothing is rebuilt.
|
|
296
|
+
* - restructured: `adopt` throws {@link HydrationMismatch}, or nodes the parser moved out
|
|
297
|
+
* sit between the `<p>` and its marker. Everything from the `<p>` up to the marker is
|
|
298
|
+
* removed and `build()` puts a fresh paragraph in its place. One paragraph is rebuilt,
|
|
299
|
+
* not the whole view. (The build warned about it: see `ssgParagraph`.)
|
|
300
|
+
*
|
|
301
|
+
* Comments are never moved by the parser, so the marker always ends the region. Without
|
|
302
|
+
* one there is no boundary to recover inside, and the mismatch propagates as before.
|
|
303
|
+
*/
|
|
304
|
+
export function hydrateParagraph(cur, adopt, build) {
|
|
305
|
+
const el = claimElement(cur, "p");
|
|
306
|
+
let intact = true;
|
|
307
|
+
try {
|
|
308
|
+
adopt(el);
|
|
309
|
+
} catch (e) {
|
|
310
|
+
if (!(e instanceof HydrationMismatch)) throw e;
|
|
311
|
+
intact = false;
|
|
312
|
+
}
|
|
313
|
+
let end = el.nextSibling;
|
|
314
|
+
if (intact && isParagraphEnd(end)) {
|
|
315
|
+
cur.node = end.nextSibling;
|
|
316
|
+
return el;
|
|
317
|
+
}
|
|
318
|
+
while (end && !isParagraphEnd(end)) end = end.nextSibling;
|
|
319
|
+
if (!end) throw new HydrationMismatch("expected a <!--p]--> paragraph end marker");
|
|
320
|
+
const parent = end.parentNode;
|
|
321
|
+
for (let n = el; n !== end; ) {
|
|
322
|
+
const next = n.nextSibling;
|
|
323
|
+
parent.removeChild(n);
|
|
324
|
+
n = next;
|
|
325
|
+
}
|
|
326
|
+
// A build, not an adoption: the components in the fresh paragraph must build their
|
|
327
|
+
// own markup rather than look for server nodes that were just removed.
|
|
328
|
+
const fresh = runBuild(build);
|
|
329
|
+
parent.insertBefore(fresh, end);
|
|
330
|
+
cur.node = end.nextSibling;
|
|
331
|
+
return fresh;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const isParagraphEnd = (n) => n?.nodeType === 8 && n.data === "p]";
|
|
335
|
+
|
|
288
336
|
/**
|
|
289
337
|
* Claim a dynamic text hole delimited by `<!--$-->…<!--/-->`, returning the text node
|
|
290
338
|
* to bind onto (created empty when the server rendered no value), and advance the
|
package/runtime/mount.js
CHANGED
|
@@ -26,6 +26,9 @@ export function buildScopedView(view) {
|
|
|
26
26
|
try {
|
|
27
27
|
const lc = (node.__lifecycle ??= { mounts: [], cleanups: [] });
|
|
28
28
|
lc.cleanups.push(owned.dispose);
|
|
29
|
+
// A fragment root (an MDX page, a `<>…</>` view) is empty once inserted. Keep the
|
|
30
|
+
// nodes it held, so the router can still find the view to replace or re-parent.
|
|
31
|
+
if (node.nodeType === 11) node.__afwNodes = Array.from(node.childNodes);
|
|
29
32
|
return node;
|
|
30
33
|
} catch (error) {
|
|
31
34
|
try { owned.dispose(); } catch (cleanupError) { console.error(cleanupError); }
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Route-pattern matching shared by the page router, API routes, route loaders and
|
|
2
|
+
// middleware scopes, so `[param]` / `[...rest]` folders behave identically in each.
|
|
3
|
+
//
|
|
4
|
+
// Precedence is by specificity, segment by segment: a static segment beats a
|
|
5
|
+
// `[param]`, which beats a `[...rest]`. So `/blog/new` wins over `/blog/[slug]` and
|
|
6
|
+
// `/api/[id]` wins over `/api/[...rest]`, whatever order the files were discovered in
|
|
7
|
+
// and whatever the params are called.
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Strip the app-directory prefix from a route/middleware file path. When the caller
|
|
11
|
+
* knows the app dir, the exact prefix is removed — unambiguous even for an
|
|
12
|
+
* `app/app/...` folder. Without it, fall back to the last complete `/app` path
|
|
13
|
+
* segment; the lookahead keeps folders that merely *start* with "app"
|
|
14
|
+
* (`/appointments`, `/apps`) intact.
|
|
15
|
+
*/
|
|
16
|
+
export function stripAppDir(filePath, appDir) {
|
|
17
|
+
if (appDir) {
|
|
18
|
+
const base = appDir.replace(/\/+$/, "");
|
|
19
|
+
if (filePath.startsWith(base + "/")) return filePath.slice(base.length);
|
|
20
|
+
}
|
|
21
|
+
return filePath.replace(/^.*\/app(?=\/)/, "");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Drop a trailing slash, except for the root "/". */
|
|
25
|
+
export const normalizePath = (p) => (p || "/").replace(/(.)\/+$/, "$1");
|
|
26
|
+
|
|
27
|
+
const PARAM_SPLIT = /(\[\.\.\.[^\]]+\]|\[[^\]]+\])/;
|
|
28
|
+
|
|
29
|
+
/** Regex source for a route with `[param]` / `[...rest]` segments. Named groups
|
|
30
|
+
* become params; literal parts are regex-escaped (`v1.0` must not match `v1X0`). */
|
|
31
|
+
function patternSource(route) {
|
|
32
|
+
return route
|
|
33
|
+
.split(PARAM_SPLIT)
|
|
34
|
+
.map((part) => {
|
|
35
|
+
if (part.startsWith("[...")) return `(?<${part.slice(4, -1)}>.+)`;
|
|
36
|
+
if (part.startsWith("[")) return `(?<${part.slice(1, -1)}>[^/]+)`;
|
|
37
|
+
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
38
|
+
})
|
|
39
|
+
.join("");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A full-path matcher for `route`; the optional trailing slash is tolerated. */
|
|
43
|
+
export function compileRoute(route) {
|
|
44
|
+
return new RegExp(`^${patternSource(route)}/?$`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A scope matcher for a middleware folder route: the folder itself and anything
|
|
49
|
+
* nested under it. `/users/[id]` covers `/users/7` and `/users/7/edit`; `/` covers
|
|
50
|
+
* every path.
|
|
51
|
+
*/
|
|
52
|
+
export function compileScope(scope) {
|
|
53
|
+
if (scope === "/") return /^\//;
|
|
54
|
+
return new RegExp(`^${patternSource(scope)}(?:/.*)?$`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Segment kinds, most specific first.
|
|
58
|
+
const segmentKind = (seg) => (seg.startsWith("[...") ? 2 : seg.startsWith("[") ? 1 : 0);
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Sort comparator: more specific routes first. Compares segment kinds left to
|
|
62
|
+
* right (static < `[param]` < `[...rest]`); with equal kinds the route with more
|
|
63
|
+
* segments is more specific; the final tie-break is lexical, for a deterministic order.
|
|
64
|
+
*/
|
|
65
|
+
export function compareRoutes(a, b) {
|
|
66
|
+
const sa = a.split("/").filter(Boolean);
|
|
67
|
+
const sb = b.split("/").filter(Boolean);
|
|
68
|
+
for (let i = 0; i < Math.min(sa.length, sb.length); i++) {
|
|
69
|
+
const d = segmentKind(sa[i]) - segmentKind(sb[i]);
|
|
70
|
+
if (d !== 0) return d;
|
|
71
|
+
}
|
|
72
|
+
if (sa.length !== sb.length) return sb.length - sa.length;
|
|
73
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Percent-decode a match's named groups into params: catch-all segments are split
|
|
78
|
+
* first (so an encoded `%2F` never adds a segment) and arrive as an array. Returns
|
|
79
|
+
* `null` on malformed percent-encoding when `strict`, else keeps the raw text.
|
|
80
|
+
*/
|
|
81
|
+
export function decodeParams(route, groups, { strict = false } = {}) {
|
|
82
|
+
const params = { ...(groups || {}) };
|
|
83
|
+
for (const k in params) {
|
|
84
|
+
const decode = (s) => {
|
|
85
|
+
try {
|
|
86
|
+
return decodeURIComponent(s);
|
|
87
|
+
} catch (e) {
|
|
88
|
+
if (strict) throw e;
|
|
89
|
+
return s;
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
try {
|
|
93
|
+
params[k] = route.includes(`[...${k}]`) ? params[k].split("/").map(decode) : decode(params[k]);
|
|
94
|
+
} catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return params;
|
|
99
|
+
}
|
package/runtime/router.d.ts
CHANGED
|
@@ -80,6 +80,7 @@ export function resolveModule(entry: any): Promise<any>;
|
|
|
80
80
|
* so a page reading `router.pathname`/`params`/`query` resolves to the route being
|
|
81
81
|
* pre-rendered. The client uses `navigate` instead.
|
|
82
82
|
*/
|
|
83
|
+
export function setRouteToc(pageModule: any): void;
|
|
83
84
|
export function setRouteState({ pathname, search, params, locale, data }?: {
|
|
84
85
|
locale?: string | null;
|
|
85
86
|
data?: unknown;
|
|
@@ -141,6 +142,8 @@ export namespace router {
|
|
|
141
142
|
const params: any;
|
|
142
143
|
const locale: any;
|
|
143
144
|
const data: any;
|
|
145
|
+
/** The current page's headings (MDX `export const toc`), or `[]`. */
|
|
146
|
+
const toc: { depth: number; id: string; text: string }[];
|
|
144
147
|
function push(path: any): Promise<void>;
|
|
145
148
|
function replace(path: any): Promise<void>;
|
|
146
149
|
}
|
package/runtime/router.js
CHANGED
|
@@ -22,6 +22,7 @@ import { prepareRouteHead, updateRouteHead } from "./head.js";
|
|
|
22
22
|
import { beginHydration, cursor, endHydration, renderedForPath } from "./hydrate.js";
|
|
23
23
|
import { buildScopedView, runCleanup, runMount } from "./mount.js";
|
|
24
24
|
import { fetchRouteData, readInlineRouteData } from "./route-data.js";
|
|
25
|
+
import { compareRoutes, compileRoute, decodeParams } from "./route-match.js";
|
|
25
26
|
|
|
26
27
|
const isBrowser = typeof window !== "undefined";
|
|
27
28
|
|
|
@@ -40,6 +41,7 @@ const state = {
|
|
|
40
41
|
params: signal({}),
|
|
41
42
|
locale: signal(null),
|
|
42
43
|
data: signal(undefined),
|
|
44
|
+
toc: signal([]),
|
|
43
45
|
};
|
|
44
46
|
|
|
45
47
|
export const routes = { pages: {}, layouts: {}, notFound: null, loaderRoutes: new Set() };
|
|
@@ -154,6 +156,10 @@ export const router = {
|
|
|
154
156
|
get data() {
|
|
155
157
|
return routeValue("data");
|
|
156
158
|
},
|
|
159
|
+
/** The current page's headings (`export const toc`, emitted for MDX), or `[]`. */
|
|
160
|
+
get toc() {
|
|
161
|
+
return routeValue("toc");
|
|
162
|
+
},
|
|
157
163
|
push: (path) => navigate(path),
|
|
158
164
|
replace: (path) => navigate(path, true),
|
|
159
165
|
};
|
|
@@ -267,6 +273,7 @@ export async function buildRouteNode(match, query = {}) {
|
|
|
267
273
|
const modules = [...layoutModules, pageModule].map(namespace);
|
|
268
274
|
const pageFactory = pageModule?.default ?? pageModule;
|
|
269
275
|
const layoutFactories = layoutModules.map(module => module?.default ?? module);
|
|
276
|
+
setRouteToc(pageModule);
|
|
270
277
|
let node = buildScopedView(() => pageFactory(props));
|
|
271
278
|
const nodes = [node];
|
|
272
279
|
try {
|
|
@@ -298,6 +305,7 @@ export async function hydrateRouteNode(match, query, rootEl) {
|
|
|
298
305
|
// checked after they all land rather than short-circuiting on the page: bailing
|
|
299
306
|
// early would only skip imports the CSR fallback below is about to need anyway.
|
|
300
307
|
const [pageMod, ...layoutMods] = await resolveAll([match.entry, ...chain], resolveModule);
|
|
308
|
+
setRouteToc(pageMod);
|
|
301
309
|
if (!pageMod || typeof pageMod.hydrateAt !== "function") return null;
|
|
302
310
|
// The whole chain must be adoptable — one non-adoptable layout means a clean CSR build.
|
|
303
311
|
if (layoutMods.some((m) => !m || typeof m.hydrateAt !== "function")) return null;
|
|
@@ -339,6 +347,18 @@ export async function resolveModule(entry) {
|
|
|
339
347
|
* so a page reading `router.pathname`/`params`/`query` resolves to the route being
|
|
340
348
|
* pre-rendered. The client uses `navigate` instead.
|
|
341
349
|
*/
|
|
350
|
+
/**
|
|
351
|
+
* Publish the page module's `toc` export as `router.toc`. Called once the page module is
|
|
352
|
+
* resolved and before any factory runs, so a layout's `<Toc>` renders the same outline on
|
|
353
|
+
* the server, at hydration and after a client navigation.
|
|
354
|
+
*/
|
|
355
|
+
export function setRouteToc(pageModule) {
|
|
356
|
+
const toc = Array.isArray(pageModule?.toc) ? pageModule.toc : [];
|
|
357
|
+
const route = getRenderContext()?.route;
|
|
358
|
+
if (route) route.toc = toc;
|
|
359
|
+
else state.toc.value = toc;
|
|
360
|
+
}
|
|
361
|
+
|
|
342
362
|
export function setRouteState({ pathname = "/", search = "", params = {}, locale, data } = {}) {
|
|
343
363
|
const route = getRenderContext()?.route;
|
|
344
364
|
if (route) {
|
|
@@ -367,32 +387,31 @@ export function setRouteState({ pathname = "/", search = "", params = {}, locale
|
|
|
367
387
|
*/
|
|
368
388
|
export function matchRoute(pathname) {
|
|
369
389
|
pathname = resolveLocale(pathname).path;
|
|
370
|
-
for (const route
|
|
371
|
-
|
|
372
|
-
// (a `v1.0` folder must not match `v1X0`).
|
|
373
|
-
const pattern = route
|
|
374
|
-
.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\])/)
|
|
375
|
-
.map((part) => {
|
|
376
|
-
if (part.startsWith("[...")) return `(?<${part.slice(4, -1)}>.+)`;
|
|
377
|
-
if (part.startsWith("[")) return `(?<${part.slice(1, -1)}>[^/]+)`;
|
|
378
|
-
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
379
|
-
})
|
|
380
|
-
.join("");
|
|
381
|
-
const m = pathname.match(new RegExp(`^${pattern}/?$`));
|
|
390
|
+
for (const { route, pattern } of rankedPages()) {
|
|
391
|
+
const m = pathname.match(pattern);
|
|
382
392
|
if (m) {
|
|
383
|
-
const params =
|
|
384
|
-
|
|
385
|
-
try {
|
|
386
|
-
params[k] = route.includes(`[...${k}]`)
|
|
387
|
-
? params[k].split("/").map(decodeURIComponent) : decodeURIComponent(params[k]);
|
|
388
|
-
} catch { return null; }
|
|
389
|
-
}
|
|
393
|
+
const params = decodeParams(route, m.groups, { strict: true });
|
|
394
|
+
if (!params) return null;
|
|
390
395
|
return { entry: routes.pages[route], params, route };
|
|
391
396
|
}
|
|
392
397
|
}
|
|
393
398
|
return null;
|
|
394
399
|
}
|
|
395
400
|
|
|
401
|
+
// Compiled page patterns, most specific first (route-match.js `compareRoutes`), so a
|
|
402
|
+
// static `/blog/new` beats `/blog/[slug]` whatever order the files were discovered in.
|
|
403
|
+
// Rebuilt when the set of routes changes (registration, HMR, tests swapping the table).
|
|
404
|
+
let ranked = { key: null, list: [] };
|
|
405
|
+
function rankedPages() {
|
|
406
|
+
const names = Object.keys(routes.pages);
|
|
407
|
+
const key = names.join("\0");
|
|
408
|
+
if (ranked.key !== key) {
|
|
409
|
+
const list = names.sort(compareRoutes).map((route) => ({ route, pattern: compileRoute(route) }));
|
|
410
|
+
ranked = { key, list };
|
|
411
|
+
}
|
|
412
|
+
return ranked.list;
|
|
413
|
+
}
|
|
414
|
+
|
|
396
415
|
// Monotonic navigation sequence: a navigation that awaited its loader-data fetch
|
|
397
416
|
// commits only if no newer navigation started meanwhile (stale data must never
|
|
398
417
|
// win over a later click).
|
|
@@ -646,7 +665,20 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
|
|
|
646
665
|
// the declarations still match (see `registerHotRoute`), outer layouts keep their
|
|
647
666
|
// nodes and state, and an edited layout receives the existing inner route view as
|
|
648
667
|
// `children`, so the page and its components move into it without remounting.
|
|
649
|
-
|
|
668
|
+
// The nodes a route view occupies in the document: the element itself, or the nodes a
|
|
669
|
+
// fragment root held (see `buildScopedView`).
|
|
670
|
+
const viewNodes = (node) => (node?.nodeType === 11 ? node.__afwNodes ?? [] : node ? [node] : []);
|
|
671
|
+
|
|
672
|
+
// A route view to pass on as a layout's `children`: a fragment root is empty once
|
|
673
|
+
// inserted, so it is refilled with the nodes it held.
|
|
674
|
+
function asChildren(node) {
|
|
675
|
+
if (node?.nodeType !== 11) return node;
|
|
676
|
+
const frag = document.createDocumentFragment();
|
|
677
|
+
frag.append(...viewNodes(node));
|
|
678
|
+
return frag;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
export async function refreshHotRoute(factory, data = null) {
|
|
650
682
|
const index = currentNodes.findIndex(node => node.__afwHotFactory === factory);
|
|
651
683
|
if (!rootEl || index < 0) return;
|
|
652
684
|
const seq = navSeq;
|
|
@@ -656,8 +688,9 @@ export async function refreshHotRoute(factory) {
|
|
|
656
688
|
if (!match) return;
|
|
657
689
|
const query = Object.fromEntries(state.searchParams.value);
|
|
658
690
|
const inner = index > 0 ? currentNodes[index - 1] : null;
|
|
659
|
-
const
|
|
660
|
-
const
|
|
691
|
+
const innerFirst = viewNodes(inner)[0];
|
|
692
|
+
const innerParent = innerFirst?.parentNode;
|
|
693
|
+
const innerNext = viewNodes(inner).at(-1)?.nextSibling;
|
|
661
694
|
let node;
|
|
662
695
|
try {
|
|
663
696
|
const [pageModule, ...layoutModules] = await resolveAll(
|
|
@@ -668,24 +701,33 @@ export async function refreshHotRoute(factory) {
|
|
|
668
701
|
const focusedId = rootEl.contains(document.activeElement) ? document.activeElement.id : null;
|
|
669
702
|
const scroll = [window.scrollX, window.scrollY];
|
|
670
703
|
const props = { params: match.params, query };
|
|
671
|
-
if (inner) props.children = inner;
|
|
704
|
+
if (inner) props.children = asChildren(inner);
|
|
705
|
+
// `data` is the edited module's route data; the modules imported above are the
|
|
706
|
+
// originals. currentNodes runs page → innermost layout → root, the chain root first.
|
|
707
|
+
const namespace = module => typeof module === "function" ? { default: module } : module;
|
|
708
|
+
const fresh = module => (data ? { ...namespace(module), ...data } : namespace(module));
|
|
709
|
+
const page = index === 0 ? fresh(pageModule) : namespace(pageModule);
|
|
710
|
+
const layouts = layoutModules.map((module, i) => (index === layoutModules.length - i ? fresh(module) : namespace(module)));
|
|
711
|
+
// An edited page may have new headings: publish them before the view rebuilds.
|
|
712
|
+
setRouteToc(page);
|
|
672
713
|
node = buildScopedView(() => factory(props, previous));
|
|
673
|
-
previous
|
|
714
|
+
const old = viewNodes(previous);
|
|
715
|
+
if (old.length === 0) throw new Error("the refreshed view has no nodes in the document to replace");
|
|
716
|
+
old[0].parentNode.insertBefore(node, old[0]);
|
|
717
|
+
for (const n of old) n.remove();
|
|
674
718
|
runCleanup(previous);
|
|
675
719
|
currentNodes = currentNodes.map((current, i) => (i === index ? node : current));
|
|
676
720
|
runMount(node);
|
|
677
|
-
const
|
|
678
|
-
const metadata = await resolveMetadataModules(
|
|
679
|
-
[...layoutModules, pageModule].map(namespace),
|
|
680
|
-
{ params: match.params, query },
|
|
681
|
-
);
|
|
721
|
+
const metadata = await resolveMetadataModules([...layouts, page], { params: match.params, query });
|
|
682
722
|
if (seq === navSeq) updateRouteHead(metadata, state.pathname.value);
|
|
683
723
|
if (focusedId) document.getElementById(focusedId)?.focus({ preventScroll: true });
|
|
684
724
|
window.scrollTo(...scroll);
|
|
685
725
|
clearError({ phase: "route" });
|
|
686
726
|
} catch (error) {
|
|
687
727
|
// A failed layout build may already hold the inner view; put it back.
|
|
688
|
-
if (
|
|
728
|
+
if (innerParent && innerFirst.parentNode !== innerParent) {
|
|
729
|
+
for (const n of viewNodes(inner)) innerParent.insertBefore(n, innerNext ?? null);
|
|
730
|
+
}
|
|
689
731
|
if (node && !node.isConnected) runCleanup(node);
|
|
690
732
|
reportError(error, { phase: "route", path: state.pathname.value });
|
|
691
733
|
}
|
package/server/adapters/node.js
CHANGED
|
@@ -45,11 +45,30 @@ export async function sendWebResponse(res, webRes) {
|
|
|
45
45
|
const cookies = webRes.headers.getSetCookie?.() ?? [];
|
|
46
46
|
if (cookies.length > 0) headers["set-cookie"] = cookies;
|
|
47
47
|
res.writeHead(webRes.status, headers);
|
|
48
|
-
if (webRes.body) {
|
|
49
|
-
const buf = Buffer.from(await webRes.arrayBuffer());
|
|
50
|
-
res.end(buf);
|
|
51
|
-
} else {
|
|
48
|
+
if (!webRes.body) {
|
|
52
49
|
res.end();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
// Stream the body chunk by chunk, so server-sent events and large downloads reach
|
|
53
|
+
// the client as they are produced instead of after the whole body is buffered.
|
|
54
|
+
// Honour backpressure (`write()` returning false waits for "drain") and stop
|
|
55
|
+
// reading when the client goes away.
|
|
56
|
+
const reader = webRes.body.getReader();
|
|
57
|
+
let closed = false;
|
|
58
|
+
const onClose = () => {
|
|
59
|
+
closed = true;
|
|
60
|
+
reader.cancel().catch(() => {});
|
|
61
|
+
};
|
|
62
|
+
res.on?.("close", onClose);
|
|
63
|
+
try {
|
|
64
|
+
while (!closed) {
|
|
65
|
+
const { done, value } = await reader.read();
|
|
66
|
+
if (done) break;
|
|
67
|
+
if (!res.write(value)) await new Promise((resolve) => res.once("drain", resolve));
|
|
68
|
+
}
|
|
69
|
+
} finally {
|
|
70
|
+
res.off?.("close", onClose);
|
|
71
|
+
if (!closed) res.end();
|
|
53
72
|
}
|
|
54
73
|
}
|
|
55
74
|
|
|
@@ -66,9 +85,15 @@ export function toNodeListener(handler, { fallback } = {}) {
|
|
|
66
85
|
if (!webRes) webRes = fallback ? await fallback(request) : new Response("Not Found", { status: 404 });
|
|
67
86
|
await sendWebResponse(res, webRes);
|
|
68
87
|
} catch (e) {
|
|
69
|
-
if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" });
|
|
70
|
-
res.end(JSON.stringify({ error: "Internal Server Error" }));
|
|
71
88
|
console.error("✗ API (node adapter):", e?.stack ?? e);
|
|
89
|
+
if (res.headersSent) {
|
|
90
|
+
// Mid-stream failure: the status is already out, so appending an error body
|
|
91
|
+
// would corrupt the response. Abort the connection instead.
|
|
92
|
+
res.destroy?.(e);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
96
|
+
res.end(JSON.stringify({ error: "Internal Server Error" }));
|
|
72
97
|
}
|
|
73
98
|
};
|
|
74
99
|
}
|
package/server/api.d.ts
CHANGED
|
@@ -20,7 +20,9 @@ export type RouteParams = Record<string, string | string[]>;
|
|
|
20
20
|
export interface ApiContext {
|
|
21
21
|
/** Dynamic route params resolved from the matched path. */
|
|
22
22
|
params: RouteParams;
|
|
23
|
-
/** Parsed query-string parameters
|
|
23
|
+
/** Parsed query-string parameters, one string per name: a repeated name keeps its
|
|
24
|
+
* last value (`?tag=a&tag=b` → `{ tag: "b" }`). Read every value with
|
|
25
|
+
* `url.searchParams.getAll("tag")`. */
|
|
24
26
|
query: Record<string, string>;
|
|
25
27
|
/** The parsed request URL. */
|
|
26
28
|
url: URL;
|
package/server/api.js
CHANGED
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
// approach of the page router (runtime/router.js `matchRoute`) so behavior is
|
|
15
15
|
// identical across pages and API and across every deployment target.
|
|
16
16
|
|
|
17
|
-
import {
|
|
17
|
+
import { compareRoutes, compileRoute, compileScope, decodeParams, normalizePath as normalize, stripAppDir } from "../runtime/route-match.js";
|
|
18
|
+
import { middlewareScopeFromPath, outermostFirst } from "./middleware.js";
|
|
18
19
|
|
|
19
20
|
// Scope derivation lives in middleware.js now that middleware governs the whole
|
|
20
21
|
// pipeline, not just API routes; re-exported here for backward compatibility.
|
|
@@ -22,21 +23,6 @@ export { middlewareScopeFromPath };
|
|
|
22
23
|
|
|
23
24
|
const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
|
|
24
25
|
|
|
25
|
-
/**
|
|
26
|
-
* Strip the app-directory prefix from a route/middleware file path. When the
|
|
27
|
-
* caller knows the app dir (the CLI always does), the exact prefix is removed —
|
|
28
|
-
* unambiguous even for an `app/app/...` folder. Without it, fall back to the last
|
|
29
|
-
* complete `/app` path segment; the lookahead keeps folders that merely *start*
|
|
30
|
-
* with "app" (`/appointments`, `/apps`) intact.
|
|
31
|
-
*/
|
|
32
|
-
function stripAppDir(filePath, appDir) {
|
|
33
|
-
if (appDir) {
|
|
34
|
-
const base = appDir.replace(/\/+$/, "");
|
|
35
|
-
if (filePath.startsWith(base + "/")) return filePath.slice(base.length);
|
|
36
|
-
}
|
|
37
|
-
return filePath.replace(/^.*\/app(?=\/)/, "");
|
|
38
|
-
}
|
|
39
|
-
|
|
40
26
|
/**
|
|
41
27
|
* Derive the API route path from a `.../app/<...>/route.{js,ts}` file path — the
|
|
42
28
|
* folder is the URL, mirroring `routeFromPath` in the page router.
|
|
@@ -49,32 +35,6 @@ export function apiRouteFromPath(filePath, appDir) {
|
|
|
49
35
|
return r === "" ? "/" : r;
|
|
50
36
|
}
|
|
51
37
|
|
|
52
|
-
/** Compile a route path with `[param]` / `[...rest]` segments to a matcher regex.
|
|
53
|
-
* Named groups become route params; literal parts are regex-escaped (a `v1.0`
|
|
54
|
-
* folder must not match `v1X0`); the optional trailing slash is tolerated. */
|
|
55
|
-
function compilePattern(route) {
|
|
56
|
-
const src = route
|
|
57
|
-
.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\])/)
|
|
58
|
-
.map((part) => {
|
|
59
|
-
if (part.startsWith("[...")) return `(?<${part.slice(4, -1)}>.+)`;
|
|
60
|
-
if (part.startsWith("[")) return `(?<${part.slice(1, -1)}>[^/]+)`;
|
|
61
|
-
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
62
|
-
})
|
|
63
|
-
.join("");
|
|
64
|
-
return new RegExp(`^${src}/?$`);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// Percent-decode a matched param segment; malformed input stays raw rather than throwing.
|
|
68
|
-
const decodeParam = (s) => {
|
|
69
|
-
try {
|
|
70
|
-
return decodeURIComponent(s);
|
|
71
|
-
} catch {
|
|
72
|
-
return s;
|
|
73
|
-
}
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
const normalize = (p) => (p || "/").replace(/(.)\/+$/, "$1");
|
|
77
|
-
|
|
78
38
|
/** The `Allow` header value for a handler module: the methods it exports, plus the
|
|
79
39
|
* auto-provided HEAD (when GET exists) and OPTIONS. */
|
|
80
40
|
function allowedMethods(mod) {
|
|
@@ -101,20 +61,23 @@ export function createApiHandler(routeModules = {}, middlewareModules = {}, { ap
|
|
|
101
61
|
const routes = [];
|
|
102
62
|
for (const file in routeModules) {
|
|
103
63
|
const route = apiRouteFromPath(file, appDir);
|
|
104
|
-
routes.push({ route, pattern:
|
|
64
|
+
routes.push({ route, pattern: compileRoute(route), module: routeModules[file] });
|
|
105
65
|
}
|
|
106
|
-
//
|
|
107
|
-
//
|
|
108
|
-
routes.sort((a, b) => a.
|
|
66
|
+
// Most specific first, segment by segment (static, then `[param]`, then
|
|
67
|
+
// `[...rest]`), so the winner never depends on discovery order or param names.
|
|
68
|
+
routes.sort((a, b) => compareRoutes(a.route, b.route));
|
|
109
69
|
|
|
110
70
|
const middleware = [];
|
|
111
71
|
for (const file in middlewareModules) {
|
|
112
72
|
const mod = middlewareModules[file];
|
|
113
73
|
const fn = mod.default ?? mod.middleware;
|
|
114
|
-
if (typeof fn === "function")
|
|
74
|
+
if (typeof fn === "function") {
|
|
75
|
+
const scope = middlewareScopeFromPath(file, appDir);
|
|
76
|
+
middleware.push({ scope, matcher: compileScope(scope), fn });
|
|
77
|
+
}
|
|
115
78
|
}
|
|
116
|
-
// Outermost
|
|
117
|
-
middleware.sort(
|
|
79
|
+
// Outermost runs first, so `/api/_middleware` wraps `/api/users/_middleware`.
|
|
80
|
+
middleware.sort(outermostFirst);
|
|
118
81
|
|
|
119
82
|
return async function handle(request, env, ctx, init) {
|
|
120
83
|
const url = new URL(request.url);
|
|
@@ -126,14 +89,9 @@ export function createApiHandler(routeModules = {}, middlewareModules = {}, { ap
|
|
|
126
89
|
const m = pathname.match(r.pattern);
|
|
127
90
|
if (!m) continue;
|
|
128
91
|
matched = r;
|
|
129
|
-
params = { ...(m.groups || {}) };
|
|
130
92
|
// Params reach handlers percent-decoded (`/users/John%20Doe` → "John Doe");
|
|
131
93
|
// catch-all segments are split first so an encoded `%2F` never adds a segment.
|
|
132
|
-
|
|
133
|
-
params[k] = r.route.includes(`[...${k}]`)
|
|
134
|
-
? params[k].split("/").map(decodeParam)
|
|
135
|
-
: decodeParam(params[k]);
|
|
136
|
-
}
|
|
94
|
+
params = decodeParams(r.route, m.groups);
|
|
137
95
|
break;
|
|
138
96
|
}
|
|
139
97
|
if (!matched) return null; // no API route — fall through to SSR / 404
|
|
@@ -171,9 +129,7 @@ export function createApiHandler(routeModules = {}, middlewareModules = {}, { ap
|
|
|
171
129
|
|
|
172
130
|
// Compose the applicable middleware chain around dispatch (outermost first).
|
|
173
131
|
// The root scope ("/", from an `app/_middleware.*`) governs every route.
|
|
174
|
-
const chain = middleware.filter(
|
|
175
|
-
(mw) => mw.scope === "/" || pathname === mw.scope || pathname.startsWith(mw.scope + "/"),
|
|
176
|
-
);
|
|
132
|
+
const chain = middleware.filter((mw) => mw.matcher.test(pathname));
|
|
177
133
|
let next = dispatch;
|
|
178
134
|
for (let i = chain.length - 1; i >= 0; i--) {
|
|
179
135
|
const { fn } = chain[i];
|
package/server/index.d.ts
CHANGED
|
@@ -33,10 +33,14 @@ export function registerRoutes(modules: Record<string, unknown>): void;
|
|
|
33
33
|
export const router: {
|
|
34
34
|
readonly pathname: string;
|
|
35
35
|
readonly searchParams: URLSearchParams;
|
|
36
|
+
/** One string per name; a repeated name keeps its last value. Use
|
|
37
|
+
* `searchParams.getAll(name)` for every value. */
|
|
36
38
|
readonly query: Record<string, string>;
|
|
37
39
|
readonly params: RouteParams;
|
|
38
40
|
readonly locale: string | null;
|
|
39
41
|
readonly data: unknown;
|
|
42
|
+
/** The current page's headings (MDX `export const toc`), or `[]`. */
|
|
43
|
+
readonly toc: { depth: number; id: string; text: string }[];
|
|
40
44
|
};
|
|
41
45
|
export function matchRoute(pathname: string): { entry: unknown; params: RouteParams; route: string } | null;
|
|
42
46
|
export function configureI18n(config: { locales: string[]; defaultLocale?: string } | null): void;
|
|
@@ -45,6 +49,8 @@ export function resolveLocale(pathname: string): { locale: string | null; path:
|
|
|
45
49
|
export function localizePath(pathname: string, locale?: string | null): string;
|
|
46
50
|
/** Set the current request's locale during server rendering. */
|
|
47
51
|
export function setLocale(locale: string | null): void;
|
|
52
|
+
/** Publish a page module's `toc` export as `router.toc`. */
|
|
53
|
+
export function setRouteToc(pageModule: { toc?: unknown } | null | undefined): void;
|
|
48
54
|
/** Set the current request's route state directly. */
|
|
49
55
|
export function setRouteState(state?: {
|
|
50
56
|
pathname?: string;
|
|
@@ -100,6 +106,8 @@ import type { RouteParams } from "./api.js";
|
|
|
100
106
|
* Request under serve/dev and undefined at SSG prerender; `locals` is reserved. */
|
|
101
107
|
export interface LoaderContext {
|
|
102
108
|
params: RouteParams;
|
|
109
|
+
/** One string per name; a repeated name keeps its last value. For every value, read
|
|
110
|
+
* `new URL(request.url).searchParams.getAll(name)` (request servers only). */
|
|
103
111
|
query: Record<string, string>;
|
|
104
112
|
request?: Request;
|
|
105
113
|
locale: string | null;
|
package/server/index.js
CHANGED
|
@@ -20,7 +20,7 @@ export * from "./render.js";
|
|
|
20
20
|
export {
|
|
21
21
|
registerRoutes, router, matchRoute, configureI18n, i18nLocales,
|
|
22
22
|
resolveLocale, localizePath, shouldInterceptNav,
|
|
23
|
-
setLocale, setRouteState, navigate,
|
|
23
|
+
setLocale, setRouteState, setRouteToc, navigate,
|
|
24
24
|
} from "../runtime/router.js";
|
|
25
25
|
export { isHydrating } from "../runtime/hydrate.js";
|
|
26
26
|
export { emit } from "../runtime/events.js";
|
package/server/loader.js
CHANGED
|
@@ -18,15 +18,7 @@
|
|
|
18
18
|
// behave identically across pages, endpoints, and loaders.
|
|
19
19
|
|
|
20
20
|
import { DATA_FILE } from "../runtime/route-data.js";
|
|
21
|
-
|
|
22
|
-
/** See `stripAppDir` in api.js — exact-prefix strip with a `/app` segment fallback. */
|
|
23
|
-
function stripAppDir(filePath, appDir) {
|
|
24
|
-
if (appDir) {
|
|
25
|
-
const base = appDir.replace(/\/+$/, "");
|
|
26
|
-
if (filePath.startsWith(base + "/")) return filePath.slice(base.length);
|
|
27
|
-
}
|
|
28
|
-
return filePath.replace(/^.*\/app(?=\/)/, "");
|
|
29
|
-
}
|
|
21
|
+
import { compareRoutes, compileRoute, decodeParams, normalizePath as normalize, stripAppDir } from "../runtime/route-match.js";
|
|
30
22
|
|
|
31
23
|
/** The page route a `.../app/<...>/loader.{js,ts}` file feeds (folder = URL):
|
|
32
24
|
* `app/todos/loader.js` → `/todos`, `app/loader.js` → `/`. */
|
|
@@ -35,29 +27,6 @@ export function loaderRouteFromPath(filePath, appDir) {
|
|
|
35
27
|
return r === "" ? "/" : r;
|
|
36
28
|
}
|
|
37
29
|
|
|
38
|
-
/** Compile a route with `[param]` / `[...rest]` segments to a matcher regex (see api.js). */
|
|
39
|
-
function compilePattern(route) {
|
|
40
|
-
const src = route
|
|
41
|
-
.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\])/)
|
|
42
|
-
.map((part) => {
|
|
43
|
-
if (part.startsWith("[...")) return `(?<${part.slice(4, -1)}>.+)`;
|
|
44
|
-
if (part.startsWith("[")) return `(?<${part.slice(1, -1)}>[^/]+)`;
|
|
45
|
-
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
46
|
-
})
|
|
47
|
-
.join("");
|
|
48
|
-
return new RegExp(`^${src}/?$`);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const decodeParam = (s) => {
|
|
52
|
-
try {
|
|
53
|
-
return decodeURIComponent(s);
|
|
54
|
-
} catch {
|
|
55
|
-
return s;
|
|
56
|
-
}
|
|
57
|
-
};
|
|
58
|
-
|
|
59
|
-
const normalize = (p) => (p || "/").replace(/(.)\/+$/, "$1");
|
|
60
|
-
|
|
61
30
|
/**
|
|
62
31
|
* Signal "this page does not exist for these params" from inside a loader — the
|
|
63
32
|
* SSR server responds 404 (rendering the 404 page), the data endpoint returns a
|
|
@@ -112,10 +81,10 @@ export function createLoaderRegistry(loaderModules = {}, { appDir, i18n } = {})
|
|
|
112
81
|
const fn = ns.default ?? ns.loader;
|
|
113
82
|
if (typeof fn !== "function") continue; // a loader file without a loader export is inert
|
|
114
83
|
const route = loaderRouteFromPath(file, appDir);
|
|
115
|
-
entries.push({ route, pattern:
|
|
84
|
+
entries.push({ route, pattern: compileRoute(route), fn });
|
|
116
85
|
}
|
|
117
|
-
//
|
|
118
|
-
entries.sort((a, b) => a.
|
|
86
|
+
// Most specific first, segment by segment — the same ranking as pages and API routes.
|
|
87
|
+
entries.sort((a, b) => compareRoutes(a.route, b.route));
|
|
119
88
|
|
|
120
89
|
const i18nOn = !!(i18n && Array.isArray(i18n.locales) && i18n.locales.length);
|
|
121
90
|
const defaultLocale = i18nOn ? (i18n.defaultLocale ?? i18n.locales[0]) : null;
|
|
@@ -135,13 +104,7 @@ export function createLoaderRegistry(loaderModules = {}, { appDir, i18n } = {})
|
|
|
135
104
|
for (const e of entries) {
|
|
136
105
|
const m = path.match(e.pattern);
|
|
137
106
|
if (!m) continue;
|
|
138
|
-
|
|
139
|
-
for (const k in params) {
|
|
140
|
-
params[k] = e.route.includes(`[...${k}]`)
|
|
141
|
-
? params[k].split("/").map(decodeParam)
|
|
142
|
-
: decodeParam(params[k]);
|
|
143
|
-
}
|
|
144
|
-
return { route: e.route, params, locale, fn: e.fn };
|
|
107
|
+
return { route: e.route, params: decodeParams(e.route, m.groups), locale, fn: e.fn };
|
|
145
108
|
}
|
|
146
109
|
return null;
|
|
147
110
|
}
|
package/server/middleware.js
CHANGED
|
@@ -19,15 +19,7 @@
|
|
|
19
19
|
// middleware), mirroring the loader registry (loader.js `match`).
|
|
20
20
|
|
|
21
21
|
import { DATA_FILE } from "../runtime/route-data.js";
|
|
22
|
-
|
|
23
|
-
/** See `stripAppDir` in api.js — exact-prefix strip with a `/app` segment fallback. */
|
|
24
|
-
function stripAppDir(filePath, appDir) {
|
|
25
|
-
if (appDir) {
|
|
26
|
-
const base = appDir.replace(/\/+$/, "");
|
|
27
|
-
if (filePath.startsWith(base + "/")) return filePath.slice(base.length);
|
|
28
|
-
}
|
|
29
|
-
return filePath.replace(/^.*\/app(?=\/)/, "");
|
|
30
|
-
}
|
|
22
|
+
import { compareRoutes, compileScope, normalizePath as normalize, stripAppDir } from "../runtime/route-match.js";
|
|
31
23
|
|
|
32
24
|
/** The folder route a `_middleware.{js,ts}` file governs: `app/api/_middleware.js`
|
|
33
25
|
* → `/api` (applies to `/api` and everything nested under it); `app/_middleware.js`
|
|
@@ -37,7 +29,15 @@ export function middlewareScopeFromPath(filePath, appDir) {
|
|
|
37
29
|
return r === "" ? "/" : r;
|
|
38
30
|
}
|
|
39
31
|
|
|
40
|
-
|
|
32
|
+
/**
|
|
33
|
+
* Sort comparator for middleware scopes: outermost (fewest segments) first, so
|
|
34
|
+
* `app/_middleware` wraps `app/api/_middleware`; at equal depth a dynamic folder
|
|
35
|
+
* wraps a static one. Ties fall back to a lexical order, independent of discovery.
|
|
36
|
+
*/
|
|
37
|
+
export function outermostFirst(a, b) {
|
|
38
|
+
const depth = (s) => s.split("/").filter(Boolean).length;
|
|
39
|
+
return depth(a.scope) - depth(b.scope) || compareRoutes(b.scope, a.scope);
|
|
40
|
+
}
|
|
41
41
|
|
|
42
42
|
/**
|
|
43
43
|
* Build the middleware runner from a discovered `{ absFilePath: namespace }` map.
|
|
@@ -57,10 +57,12 @@ export function createMiddleware(middlewareModules = {}, { appDir, i18n } = {})
|
|
|
57
57
|
for (const file in middlewareModules) {
|
|
58
58
|
const mod = middlewareModules[file];
|
|
59
59
|
const fn = mod.default ?? mod.middleware;
|
|
60
|
-
if (typeof fn === "function")
|
|
60
|
+
if (typeof fn === "function") {
|
|
61
|
+
const scope = middlewareScopeFromPath(file, appDir);
|
|
62
|
+
entries.push({ scope, matcher: compileScope(scope), fn });
|
|
63
|
+
}
|
|
61
64
|
}
|
|
62
|
-
|
|
63
|
-
entries.sort((a, b) => a.scope.length - b.scope.length);
|
|
65
|
+
entries.sort(outermostFirst);
|
|
64
66
|
|
|
65
67
|
const i18nOn = !!(i18n && Array.isArray(i18n.locales) && i18n.locales.length);
|
|
66
68
|
const defaultLocale = i18nOn ? (i18n.defaultLocale ?? i18n.locales[0]) : null;
|
|
@@ -95,7 +97,7 @@ export function createMiddleware(middlewareModules = {}, { appDir, i18n } = {})
|
|
|
95
97
|
const url = new URL(request.url);
|
|
96
98
|
const context = { url, locals: {}, env, ctx };
|
|
97
99
|
const path = scopePath(url.pathname);
|
|
98
|
-
const chain = entries.filter((e) => e.
|
|
100
|
+
const chain = entries.filter((e) => e.matcher.test(path));
|
|
99
101
|
let next = (req) => terminal(req, context);
|
|
100
102
|
for (let i = chain.length - 1; i >= 0; i--) {
|
|
101
103
|
const { fn } = chain[i];
|
package/server/render.js
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
resolveModule,
|
|
14
14
|
routes,
|
|
15
15
|
setRouteState,
|
|
16
|
+
setRouteToc,
|
|
16
17
|
} from "../runtime/router.js";
|
|
17
18
|
import { resolveMetadata } from "./head.js";
|
|
18
19
|
import { beginHydrationCollect, endHydrationCollect } from "./ssg-runtime.js";
|
|
@@ -60,6 +61,8 @@ async function renderInContext(pathname, params, search, data) {
|
|
|
60
61
|
);
|
|
61
62
|
const page = pageModule?.default ?? pageModule;
|
|
62
63
|
const layouts = layoutModules.map(module => module?.default ?? module);
|
|
64
|
+
// Before any factory runs, so a layout's `<Toc>` serves the page's outline.
|
|
65
|
+
setRouteToc(pageModule);
|
|
63
66
|
|
|
64
67
|
// Each context owns its hydration ids, including when another render is nested.
|
|
65
68
|
let html, hydration;
|
package/server/ssg-runtime.js
CHANGED
|
@@ -161,6 +161,64 @@ export function attr(name, value) {
|
|
|
161
161
|
return ` ${name}="${escapeAttr(String(value))}"`;
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
+
/**
|
|
165
|
+
* The dynamic attributes of an element that carries a spread (`<div {...rest} class="x">`).
|
|
166
|
+
* `entries` lists, in source order, `[name, value]` pairs for named attributes and plain
|
|
167
|
+
* objects for spreads. A later entry overrides an earlier one with the same name, which is
|
|
168
|
+
* the order the client's `spread`/`setAttribute` calls apply them in. A served tag can't
|
|
169
|
+
* repeat an attribute (the parser keeps the first one), so the merge has to happen here.
|
|
170
|
+
* Event handlers and functions have no HTML form and are left to the client.
|
|
171
|
+
*/
|
|
172
|
+
export function ssgAttrs(entries) {
|
|
173
|
+
const merged = new Map();
|
|
174
|
+
for (const entry of entries) {
|
|
175
|
+
if (Array.isArray(entry)) merged.set(entry[0], entry[1]);
|
|
176
|
+
else if (entry && typeof entry === "object") {
|
|
177
|
+
for (const k in entry) merged.set(k, entry[k]);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
let s = "";
|
|
181
|
+
for (const [name, value] of merged) {
|
|
182
|
+
if (name === "ref" || name === "children" || typeof value === "function") continue;
|
|
183
|
+
s += attr(name, value);
|
|
184
|
+
}
|
|
185
|
+
return s;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Tags that close an open `<p>` (the HTML parser's "close a p element" list). Mirrors
|
|
189
|
+
// `CLOSES_P` in the compiler's static_tree.rs.
|
|
190
|
+
const CLOSES_P = /<(address|article|aside|blockquote|center|details|dialog|dir|div|dl|dd|dt|fieldset|figcaption|figure|footer|form|h[1-6]|header|hgroup|hr|li|listing|main|menu|nav|ol|p|plaintext|pre|search|section|summary|table|ul|xmp)[\s/>]/i;
|
|
191
|
+
const warnedParagraphs = new Set();
|
|
192
|
+
|
|
193
|
+
/** The first tag in a paragraph's inner HTML that would close the `<p>`, or null. */
|
|
194
|
+
export function paragraphBlockTag(html) {
|
|
195
|
+
const m = CLOSES_P.exec(html);
|
|
196
|
+
return m ? m[1].toLowerCase() : null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The inner HTML of a `<p>` holding components (`names`, e.g. "<Badge>"), returned
|
|
201
|
+
* unchanged. If a component's markup put a block element in it, the browser will close
|
|
202
|
+
* the paragraph early and hydration rebuilds it (`hydrateParagraph`), so say so once per
|
|
203
|
+
* page and paragraph, with the fix.
|
|
204
|
+
*/
|
|
205
|
+
export function ssgParagraph(html, names) {
|
|
206
|
+
const tag = paragraphBlockTag(html);
|
|
207
|
+
if (tag) {
|
|
208
|
+
const page = getRenderContext()?.route?.pathname ?? "";
|
|
209
|
+
const key = `${page}\0${names}\0${tag}`;
|
|
210
|
+
if (!warnedParagraphs.has(key)) {
|
|
211
|
+
warnedParagraphs.add(key);
|
|
212
|
+
console.warn(
|
|
213
|
+
`⚠ ${names} renders a <${tag}> inside a paragraph${page ? ` on ${page}` : ""}. ` +
|
|
214
|
+
"The browser moves it out of the <p>, so that paragraph is rebuilt on load. " +
|
|
215
|
+
"Put the component on its own line, or render inline markup (<span>) from it.",
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return html;
|
|
220
|
+
}
|
|
221
|
+
|
|
164
222
|
/**
|
|
165
223
|
* A dynamic hole's value → HTML: trusted `{__html}` raw, else escaped text. An
|
|
166
224
|
* array (`{[<a/>, <b/>]}` or `{[1, 2, 3]}`) renders each item concatenated with no
|