@opentf/afw 0.0.0-stage → 0.33.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 +123 -2
- package/components/Link.d.ts +12 -0
- package/components/Link.jsx +54 -0
- package/core/context.d.ts +7 -0
- package/core/context.js +60 -0
- package/core/dev.js +27 -0
- package/core/errors.d.ts +14 -0
- package/core/errors.js +48 -0
- package/core/html.js +10 -0
- package/core/metadata.js +186 -0
- package/core/reactive.d.ts +5 -0
- package/core/reactive.js +190 -0
- package/core/render-context.js +11 -0
- package/core/signals.d.ts +8 -0
- package/core/signals.js +264 -0
- package/index.d.ts +5 -0
- package/index.js +13 -0
- package/jsx-runtime.d.ts +37 -0
- package/package.json +66 -4
- package/runtime/clipboard.d.ts +7 -0
- package/runtime/clipboard.js +47 -0
- package/runtime/code-block.d.ts +14 -0
- package/runtime/code-block.js +76 -0
- package/runtime/context.browser.js +163 -0
- package/runtime/context.d.ts +13 -0
- package/runtime/context.js +44 -0
- package/runtime/dom.browser.js +423 -0
- package/runtime/dom.d.ts +142 -0
- package/runtime/dom.js +670 -0
- package/runtime/error-boundary.browser.js +140 -0
- package/runtime/error-boundary.d.ts +19 -0
- package/runtime/error-boundary.js +123 -0
- package/runtime/events.browser.js +29 -0
- package/runtime/events.d.ts +1 -0
- package/runtime/events.js +17 -0
- package/runtime/head.js +29 -0
- package/runtime/hmr.js +199 -0
- package/runtime/hydrate.browser.js +144 -0
- package/runtime/hydrate.d.ts +179 -0
- package/runtime/hydrate.js +584 -0
- package/runtime/index.d.ts +14 -0
- package/runtime/index.js +24 -0
- package/runtime/lifecycle.d.ts +6 -0
- package/runtime/lifecycle.js +14 -0
- package/runtime/mount.d.ts +20 -0
- package/runtime/mount.js +88 -0
- package/runtime/portal.browser.js +85 -0
- package/runtime/portal.d.ts +12 -0
- package/runtime/portal.js +74 -0
- package/runtime/raw-html.d.ts +11 -0
- package/runtime/raw-html.js +55 -0
- package/runtime/resource.d.ts +9 -0
- package/runtime/resource.js +139 -0
- package/runtime/route-data.d.ts +15 -0
- package/runtime/route-data.js +64 -0
- package/runtime/router.d.ts +149 -0
- package/runtime/router.js +807 -0
- package/server/adapters/node.d.ts +28 -0
- package/server/adapters/node.js +74 -0
- package/server/api.d.ts +175 -0
- package/server/api.js +233 -0
- package/server/builtins.js +42 -0
- package/server/cookies.d.ts +44 -0
- package/server/cookies.js +122 -0
- package/server/head.js +9 -0
- package/server/index.d.ts +155 -0
- package/server/index.js +31 -0
- package/server/loader.js +201 -0
- package/server/middleware.js +119 -0
- package/server/render-context.js +30 -0
- package/server/render.js +175 -0
- package/server/ssg-runtime.js +297 -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,3 +1,124 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# @opentf/afw
|
|
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";
|
|
23
|
+
|
|
24
|
+
export default function Clock() {
|
|
25
|
+
let now = $state(null);
|
|
26
|
+
|
|
27
|
+
onMount(() => {
|
|
28
|
+
now = new Date();
|
|
29
|
+
const id = setInterval(() => (now = new Date()), 1000);
|
|
30
|
+
return () => clearInterval(id);
|
|
31
|
+
});
|
|
32
|
+
|
|
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
|
|
47
|
+
pnpm add @opentf/afw
|
|
48
|
+
pnpm add -D @opentf/esdev-plugin-afw
|
|
49
|
+
```
|
|
50
|
+
|
|
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 |
|
|
91
|
+
|
|
92
|
+
## TypeScript
|
|
93
|
+
|
|
94
|
+
Declarations ship with the package. Keep JSX for the AFW compiler and point
|
|
95
|
+
`jsxImportSource` at this package:
|
|
96
|
+
|
|
97
|
+
```json
|
|
98
|
+
{
|
|
99
|
+
"compilerOptions": {
|
|
100
|
+
"jsx": "preserve",
|
|
101
|
+
"jsxImportSource": "@opentf/afw",
|
|
102
|
+
"moduleResolution": "bundler",
|
|
103
|
+
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
|
104
|
+
"strict": true,
|
|
105
|
+
"noEmit": true
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`esdev create my-app --language=ts` generates this configuration together with the
|
|
111
|
+
macro declarations.
|
|
112
|
+
|
|
113
|
+
## Documentation
|
|
114
|
+
|
|
115
|
+
| Topic | Link |
|
|
116
|
+
| --- | --- |
|
|
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) |
|
|
121
|
+
|
|
122
|
+
## License
|
|
123
|
+
|
|
124
|
+
MIT — see [LICENSE](https://github.com/Open-Tech-Foundation/afw/blob/main/LICENSE).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { JSX } from "../jsx-runtime.js";
|
|
2
|
+
export interface LinkProps {
|
|
3
|
+
href: string;
|
|
4
|
+
children?: unknown;
|
|
5
|
+
class?: JSX.IntrinsicElements["a"]["class"];
|
|
6
|
+
reload?: boolean | "";
|
|
7
|
+
ariaLabel?: string;
|
|
8
|
+
ariaCurrent?: string;
|
|
9
|
+
"aria-label"?: string;
|
|
10
|
+
"aria-current"?: string;
|
|
11
|
+
}
|
|
12
|
+
export default function Link(props: LinkProps): Node;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// <Link href> — client-side (SPA) navigation.
|
|
2
|
+
//
|
|
3
|
+
// A *pure JSX component*, shipped as source and compiled by the consuming app's
|
|
4
|
+
// pipeline (like a UI library ships components for the user's bundler). The
|
|
5
|
+
// framework dogfoods its own JSX → Custom Element model here instead of a
|
|
6
|
+
// hand-written HTMLElement class — so it gets reactive props, the children slot,
|
|
7
|
+
// and a matching SSG renderer for free, with no separate runtime build step.
|
|
8
|
+
//
|
|
9
|
+
// `class` is a declared prop, so it lands on the rendered <a> (the link), not on
|
|
10
|
+
// the <afw-link> host — no duplicated styling.
|
|
11
|
+
|
|
12
|
+
import { localizePath, navigate, shouldInterceptNav } from "../runtime/router.js";
|
|
13
|
+
|
|
14
|
+
export default function Link(props) {
|
|
15
|
+
const href = props.href;
|
|
16
|
+
const className = props.class;
|
|
17
|
+
const reload = props.reload;
|
|
18
|
+
// Keep the link in the active locale (no-op when i18n is off). Locale is a
|
|
19
|
+
// per-load constant under URL-prefix routing, so resolving it once here is
|
|
20
|
+
// correct — a navigation that changes the locale rebuilds this component.
|
|
21
|
+
const target = localizePath(href);
|
|
22
|
+
// `reload` (a bare attribute → "") forces a full-page navigation for this link.
|
|
23
|
+
// Absent resolves to null (getAttribute), so use loose `!= null` to treat only a
|
|
24
|
+
// present, non-false value as opting out.
|
|
25
|
+
const forceReload = reload != null && reload !== false;
|
|
26
|
+
const ariaLabel = props["aria-label"] || props.ariaLabel;
|
|
27
|
+
const ariaCurrent = props["aria-current"] || props.ariaCurrent;
|
|
28
|
+
|
|
29
|
+
const onclick = (e) => {
|
|
30
|
+
// Let the browser handle modified clicks (new tab, etc.) and non-primary buttons.
|
|
31
|
+
if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
// Full-page navigation when this link opts out (`reload`) or the app runs in MPA
|
|
35
|
+
// mode (docs/HYDRATION.md §7) — leave the click to the browser.
|
|
36
|
+
if (forceReload || !shouldInterceptNav()) {
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
e.preventDefault();
|
|
40
|
+
navigate(target);
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
return (
|
|
44
|
+
<a
|
|
45
|
+
href={target}
|
|
46
|
+
class={className}
|
|
47
|
+
aria-label={ariaLabel}
|
|
48
|
+
aria-current={ariaCurrent}
|
|
49
|
+
onclick={onclick}
|
|
50
|
+
>
|
|
51
|
+
{props.children}
|
|
52
|
+
</a>
|
|
53
|
+
);
|
|
54
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Signal } from "./signals.js";
|
|
2
|
+
export interface Context<T> { id: string; fallback: Signal<T> }
|
|
3
|
+
export function createContext<T>(defaultValue: T): Context<T>;
|
|
4
|
+
export function readContext<T>(context: Context<T>): Signal<T>;
|
|
5
|
+
export function enterHost(element: Element): void;
|
|
6
|
+
export function exitHost(): void;
|
|
7
|
+
export function getCurrentInstance(): Element | null;
|
package/core/context.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Context tokens and host lookup, shared by browser and server entries.
|
|
2
|
+
import { signal } from "./signals.js";
|
|
3
|
+
|
|
4
|
+
let nextId = 0;
|
|
5
|
+
|
|
6
|
+
// Stack of the elements whose component bodies are currently executing. A stack
|
|
7
|
+
// (not a single slot) because filling a component's children slot connects nested
|
|
8
|
+
// components synchronously inside the parent's connect — each push is balanced by
|
|
9
|
+
// a pop in the generated `finally`, so the parent's host is restored after.
|
|
10
|
+
const hostStack = [];
|
|
11
|
+
|
|
12
|
+
/** Push the current component host (compiler-emitted, paired with `exitHost`). */
|
|
13
|
+
export function enterHost(el) {
|
|
14
|
+
hostStack.push(el);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Pop the current component host (compiler-emitted, in a `finally`). */
|
|
18
|
+
export function exitHost() {
|
|
19
|
+
hostStack.pop();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The component host element currently executing its body, or `null` outside a
|
|
24
|
+
* component (e.g. a form created in module scope or a test). Libraries use this
|
|
25
|
+
* as a per-instance identity to scope state to the mounting component — the
|
|
26
|
+
* compiler emits `enterHost(this)` around every component body (csr.rs).
|
|
27
|
+
*/
|
|
28
|
+
export function getCurrentInstance() {
|
|
29
|
+
return hostStack[hostStack.length - 1] ?? null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Create a context with a default value. The returned token is passed to
|
|
34
|
+
* `<ContextProvider context={…}>` and `$context(…)`.
|
|
35
|
+
*/
|
|
36
|
+
export function createContext(defaultValue) {
|
|
37
|
+
return { id: `afw-ctx-${nextId++}`, fallback: signal(defaultValue) };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Resolve the value provided by the nearest ancestor `ContextProvider` for
|
|
42
|
+
* `context`, or the context's default if there is none. Returns a **signal**. This
|
|
43
|
+
* is what the `$context(Ctx)` compiler macro lowers to; the macro registers the
|
|
44
|
+
* binding as a signal so the bare name reads `.value` reactively.
|
|
45
|
+
*/
|
|
46
|
+
export function readContext(context) {
|
|
47
|
+
let el = hostStack[hostStack.length - 1];
|
|
48
|
+
const sel = `[data-afw-ctx~="${context.id}"]`;
|
|
49
|
+
// Walk up the DOM; when the search reaches a portal boundary without finding a
|
|
50
|
+
// provider, hop to the portal's logical location (`__portalHost`) and continue,
|
|
51
|
+
// so context resolves across a <Portal> as if the content were still in place.
|
|
52
|
+
while (el) {
|
|
53
|
+
const provider = el.closest(sel);
|
|
54
|
+
if (provider) return provider._signal;
|
|
55
|
+
const boundary = el.closest("[data-afw-portal]");
|
|
56
|
+
el = boundary ? boundary.__portalHost : null;
|
|
57
|
+
}
|
|
58
|
+
return context.fallback;
|
|
59
|
+
}
|
|
60
|
+
|
package/core/dev.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Development-mode diagnostics. SPEC §5.4.4 specifies warnings that fire "in
|
|
2
|
+
// development mode"; this is the flag they gate on.
|
|
3
|
+
//
|
|
4
|
+
// `process.env.NODE_ENV` is substituted at bundle time by esdev ("development"
|
|
5
|
+
// under `esdev start`, "production" for `esdev build`), so DEV folds to a literal
|
|
6
|
+
// and every `if (DEV)` block is dropped by minification from production output.
|
|
7
|
+
// Unbundled esdev code has no Node `process`, so it defaults to development;
|
|
8
|
+
// Node keeps its own NODE_ENV.
|
|
9
|
+
export const DEV = globalThis.process?.env?.NODE_ENV !== "production";
|
|
10
|
+
|
|
11
|
+
const seen = new Set();
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Warn once per distinct `key`, so a diagnostic raised from inside an effect
|
|
15
|
+
* (which can re-run on every update) doesn't flood the console. Dev-only: the
|
|
16
|
+
* call sites gate on {@link DEV} so this is unreachable in a production bundle.
|
|
17
|
+
*/
|
|
18
|
+
export function warnOnce(key, message) {
|
|
19
|
+
if (seen.has(key)) return;
|
|
20
|
+
seen.add(key);
|
|
21
|
+
console.warn(`[@opentf/afw] ${message}`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Test hook: forget which warnings have fired. */
|
|
25
|
+
export function resetWarnings() {
|
|
26
|
+
seen.clear();
|
|
27
|
+
}
|
package/core/errors.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subscribe to runtime errors. `handler(error, context)` is called for every
|
|
3
|
+
* `reportError`. Returns a disposer that unsubscribes.
|
|
4
|
+
*/
|
|
5
|
+
export function onError(handler: any): () => boolean;
|
|
6
|
+
/**
|
|
7
|
+
* Report a caught error. `context` carries where it happened
|
|
8
|
+
* (`{ phase: "render" | "effect" | "mount" | "event" | "route", … }`).
|
|
9
|
+
* Notifies subscribers, emits the `afw:error` window event, and — if nobody is
|
|
10
|
+
* listening — logs to the console so errors are never silently swallowed.
|
|
11
|
+
*/
|
|
12
|
+
export function reportError(error: any, context?: {}): void;
|
|
13
|
+
/** Signal that the error condition has cleared (e.g. a successful navigation). */
|
|
14
|
+
export function clearError(context?: {}): void;
|
package/core/errors.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
//! Central error reporting for the AFW runtime.
|
|
2
|
+
//
|
|
3
|
+
// Render, effect, lifecycle, and event errors are funneled here instead of being
|
|
4
|
+
// thrown into the void. Userland (and the dev overlay) subscribe via `onError`;
|
|
5
|
+
// in the browser every report is also dispatched as an `afw:error` window event
|
|
6
|
+
// so a fully decoupled listener (e.g. the dev server's injected overlay) can show
|
|
7
|
+
// it without importing the bundle.
|
|
8
|
+
|
|
9
|
+
const handlers = new Set();
|
|
10
|
+
const isBrowser = typeof window !== "undefined";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Subscribe to runtime errors. `handler(error, context)` is called for every
|
|
14
|
+
* `reportError`. Returns a disposer that unsubscribes.
|
|
15
|
+
*/
|
|
16
|
+
export function onError(handler) {
|
|
17
|
+
handlers.add(handler);
|
|
18
|
+
return () => handlers.delete(handler);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Report a caught error. `context` carries where it happened
|
|
23
|
+
* (`{ phase: "render" | "effect" | "mount" | "event" | "route", … }`).
|
|
24
|
+
* Notifies subscribers, emits the `afw:error` window event, and — if nobody is
|
|
25
|
+
* listening — logs to the console so errors are never silently swallowed.
|
|
26
|
+
*/
|
|
27
|
+
export function reportError(error, context = {}) {
|
|
28
|
+
for (const handler of handlers) {
|
|
29
|
+
try {
|
|
30
|
+
handler(error, context);
|
|
31
|
+
} catch {
|
|
32
|
+
// A failing handler must not mask the original error.
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
if (isBrowser) {
|
|
36
|
+
window.dispatchEvent(new CustomEvent("afw:error", { detail: { error, context } }));
|
|
37
|
+
}
|
|
38
|
+
if (handlers.size === 0) {
|
|
39
|
+
console.error(`[afw${context.phase ? `:${context.phase}` : ""}]`, error);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Signal that the error condition has cleared (e.g. a successful navigation). */
|
|
44
|
+
export function clearError(context = {}) {
|
|
45
|
+
if (isBrowser) {
|
|
46
|
+
window.dispatchEvent(new CustomEvent("afw:error-clear", { detail: context }));
|
|
47
|
+
}
|
|
48
|
+
}
|
package/core/html.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Escape text content for HTML. */
|
|
2
|
+
export function escapeHtml(s) {
|
|
3
|
+
return String(s).replace(/[&<>]/g, (c) => (c === "&" ? "&" : c === "<" ? "<" : ">"));
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
/** Escape an attribute value. */
|
|
7
|
+
export function escapeAttr(s) {
|
|
8
|
+
return String(s).replace(/[&"]/g, (c) => (c === "&" ? "&" : """));
|
|
9
|
+
}
|
|
10
|
+
|
package/core/metadata.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { escapeAttr, escapeHtml } from "./html.js";
|
|
2
|
+
|
|
3
|
+
// Sub-objects that merge one level deep (rather than wholesale replace) so a page
|
|
4
|
+
// can override `openGraph.image` without dropping a layout's `openGraph.siteName`.
|
|
5
|
+
const SUBOBJECTS = ["openGraph", "twitter", "robots"];
|
|
6
|
+
|
|
7
|
+
/** Read a route entry's static `metadata` (namespace or its default export). */
|
|
8
|
+
function staticMeta(entry) {
|
|
9
|
+
if (!entry) return null;
|
|
10
|
+
return entry.metadata || (entry.default && entry.default.metadata) || null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Invoke a route entry's `generateMetadata({ params, query })` if it exports one. */
|
|
14
|
+
async function dynamicMeta(entry, params, query, parent) {
|
|
15
|
+
if (!entry) return null;
|
|
16
|
+
const gen = entry.generateMetadata || (entry.default && entry.default.generateMetadata);
|
|
17
|
+
return typeof gen === "function" ? (await gen({ params, query }, parent)) || null : null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Merge `add` over `base`, deep-merging the known sub-objects. */
|
|
21
|
+
function mergeMeta(base, add) {
|
|
22
|
+
if (!add) return base;
|
|
23
|
+
const out = { ...base };
|
|
24
|
+
for (const k in add) {
|
|
25
|
+
const v = add[k];
|
|
26
|
+
if (v == null) continue;
|
|
27
|
+
if (SUBOBJECTS.includes(k) && isPlainObject(v) && isPlainObject(base[k])) {
|
|
28
|
+
out[k] = { ...base[k], ...v };
|
|
29
|
+
} else {
|
|
30
|
+
out[k] = v;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function isPlainObject(v) {
|
|
37
|
+
return v != null && typeof v === "object" && !Array.isArray(v);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Merge resolved layout/page namespaces in order; parent excludes this segment. */
|
|
41
|
+
export async function resolveMetadataModules(modules, { params = {}, query = {} } = {}) {
|
|
42
|
+
let meta = {};
|
|
43
|
+
for (const module of modules) {
|
|
44
|
+
const parent = Promise.resolve(structuredClone(meta));
|
|
45
|
+
meta = mergeMeta(meta, staticMeta(module));
|
|
46
|
+
meta = mergeMeta(meta, await dynamicMeta(module, params, query, parent));
|
|
47
|
+
}
|
|
48
|
+
return meta;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Resolve a possibly-relative URL against `baseUrl` (absolute URLs pass through). */
|
|
52
|
+
function absUrl(baseUrl, p) {
|
|
53
|
+
if (!p) return "";
|
|
54
|
+
if (/^https?:\/\//i.test(p)) return p;
|
|
55
|
+
if (!baseUrl) return p; // no site origin configured → emit relative
|
|
56
|
+
return baseUrl.replace(/\/+$/, "") + (p.startsWith("/") ? p : `/${p}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Resolve a `title` (string or `{ absolute }`) against an optional `template`
|
|
61
|
+
* containing `%s`. A plain string is wrapped by the template; `{ absolute }` (or a
|
|
62
|
+
* template without `%s`) is used verbatim. Returns null when there is no title.
|
|
63
|
+
*/
|
|
64
|
+
function resolveTitle(title, template) {
|
|
65
|
+
if (title != null && typeof title === "object") {
|
|
66
|
+
return title.absolute != null ? String(title.absolute) : null;
|
|
67
|
+
}
|
|
68
|
+
if (title == null) return null;
|
|
69
|
+
const s = String(title);
|
|
70
|
+
return template && template.includes("%s") ? template.replace("%s", s) : s;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** `<meta name|property="key" content="value">` (omitted when value is null). */
|
|
74
|
+
function metaTag(kind, key, content) {
|
|
75
|
+
if (content == null || content === "") return "";
|
|
76
|
+
return `<meta ${kind}="${escapeAttr(key)}" content="${escapeAttr(content)}">`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Normalize `robots` (string passthrough, or `{ index, follow, ... }` flags). */
|
|
80
|
+
function robotsContent(r) {
|
|
81
|
+
if (r == null) return "";
|
|
82
|
+
if (typeof r === "string") return r;
|
|
83
|
+
const parts = [];
|
|
84
|
+
if (r.index === false) parts.push("noindex");
|
|
85
|
+
else if (r.index === true) parts.push("index");
|
|
86
|
+
if (r.follow === false) parts.push("nofollow");
|
|
87
|
+
else if (r.follow === true) parts.push("follow");
|
|
88
|
+
for (const flag of ["noarchive", "nosnippet", "noimageindex", "notranslate"]) {
|
|
89
|
+
if (r[flag]) parts.push(flag);
|
|
90
|
+
}
|
|
91
|
+
return parts.join(", ");
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Escape `</script>` / `<` so a JSON-LD payload can't break out of the script tag.
|
|
95
|
+
function jsonLdSafe(s) {
|
|
96
|
+
return String(s).replace(/</g, "\\u003c");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Render the resolved `meta` to the inner HTML of `<head>` for the route at `path`.
|
|
101
|
+
* `baseUrl` (site origin) makes canonical / og:url / image URLs absolute when set.
|
|
102
|
+
*
|
|
103
|
+
* Pass `path: null` for a *route-independent* head — site-wide layout defaults
|
|
104
|
+
* injected into a single CSR shell shared by every route. In that mode no canonical
|
|
105
|
+
* (or its `og:url` fallback) is emitted unless `meta.canonical` is set explicitly, so
|
|
106
|
+
* the shared shell never claims one route's URL as canonical for all of them.
|
|
107
|
+
*/
|
|
108
|
+
export function renderHead(meta = {}, { path = "/", baseUrl = "", managed = false } = {}) {
|
|
109
|
+
const tags = [];
|
|
110
|
+
const push = (s) => s && tags.push(s);
|
|
111
|
+
|
|
112
|
+
// Resolve the display title. `title` is a string (wrapped by an inherited
|
|
113
|
+
// `titleTemplate` like "%s — AFW") or `{ absolute }` to bypass the template —
|
|
114
|
+
// so a layout can brand every child page while the homepage keeps a bespoke title.
|
|
115
|
+
const title = resolveTitle(meta.title, meta.titleTemplate);
|
|
116
|
+
const description = meta.description;
|
|
117
|
+
if (title != null) push(`<title>${escapeHtml(title)}</title>`);
|
|
118
|
+
push(metaTag("name", "description", description));
|
|
119
|
+
|
|
120
|
+
// `path: null` → route-independent head: only an explicit `meta.canonical` yields a
|
|
121
|
+
// canonical link (never the request path), so a shared CSR shell stays route-neutral.
|
|
122
|
+
const canonicalPath = meta.canonical ?? (path === null ? null : path);
|
|
123
|
+
const canonical = canonicalPath == null ? "" : absUrl(baseUrl, canonicalPath);
|
|
124
|
+
if (canonical) push(`<link rel="canonical" href="${escapeAttr(canonical)}">`);
|
|
125
|
+
|
|
126
|
+
push(metaTag("name", "robots", robotsContent(meta.robots)));
|
|
127
|
+
|
|
128
|
+
// Open Graph (falls back to the top-level title/description).
|
|
129
|
+
const og = isPlainObject(meta.openGraph) ? meta.openGraph : {};
|
|
130
|
+
const ogImage = og.image ? absUrl(baseUrl, og.image) : "";
|
|
131
|
+
push(metaTag("property", "og:title", og.title ?? title));
|
|
132
|
+
push(metaTag("property", "og:description", og.description ?? description));
|
|
133
|
+
push(metaTag("property", "og:type", og.type ?? "website"));
|
|
134
|
+
push(metaTag("property", "og:url", og.url ? absUrl(baseUrl, og.url) : canonical));
|
|
135
|
+
push(metaTag("property", "og:image", ogImage));
|
|
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));
|
|
139
|
+
|
|
140
|
+
// Twitter Card (falls back to Open Graph / top-level values).
|
|
141
|
+
const tw = isPlainObject(meta.twitter) ? meta.twitter : {};
|
|
142
|
+
const twImage = tw.image ? absUrl(baseUrl, tw.image) : ogImage;
|
|
143
|
+
push(metaTag("name", "twitter:card", tw.card ?? (twImage ? "summary_large_image" : "summary")));
|
|
144
|
+
push(metaTag("name", "twitter:title", tw.title ?? og.title ?? title));
|
|
145
|
+
push(metaTag("name", "twitter:description", tw.description ?? og.description ?? description));
|
|
146
|
+
push(metaTag("name", "twitter:image", twImage));
|
|
147
|
+
|
|
148
|
+
// Arbitrary extra tags (escape hatch for anything not modeled above).
|
|
149
|
+
for (const m of Array.isArray(meta.meta) ? meta.meta : []) {
|
|
150
|
+
const kind = m.name ? "name" : m.property ? "property" : m.httpEquiv ? "http-equiv" : null;
|
|
151
|
+
if (kind) push(metaTag(kind, m.name ?? m.property ?? m.httpEquiv, m.content));
|
|
152
|
+
}
|
|
153
|
+
for (const l of Array.isArray(meta.links) ? meta.links : []) {
|
|
154
|
+
const rel = l.rel ? ` rel="${escapeAttr(l.rel)}"` : "";
|
|
155
|
+
const href = l.href ? ` href="${escapeAttr(absUrl(baseUrl, l.href))}"` : "";
|
|
156
|
+
const type = l.type ? ` type="${escapeAttr(l.type)}"` : "";
|
|
157
|
+
const extra = l.hreflang ? ` hreflang="${escapeAttr(l.hreflang)}"` : "";
|
|
158
|
+
if (rel || href) push(`<link${rel}${type}${href}${extra}>`);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Structured data (JSON-LD) for rich results.
|
|
162
|
+
if (meta.jsonLd != null) {
|
|
163
|
+
const json = typeof meta.jsonLd === "string" ? meta.jsonLd : JSON.stringify(meta.jsonLd);
|
|
164
|
+
push(`<script type="application/ld+json">${jsonLdSafe(json)}</script>`);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return tags.map(tag => managed ? tag.replace(/^<(title|meta|link|script)\b/, '<$1 data-afw-head=""') : tag).join("\n");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Build `rel="alternate" hreflang` link descriptors for a locale-agnostic
|
|
172
|
+
* `routePath` (e.g. `/about`) across all configured locales — for the toolchain to
|
|
173
|
+
* pass through `metadata.links` so `renderHead` emits them (docs/I18N.md §6). The
|
|
174
|
+
* default locale also gets `x-default`. `localize(path, locale)` is the router's
|
|
175
|
+
* `localizePath` (kept as a param so this stays free of a router import here).
|
|
176
|
+
*/
|
|
177
|
+
export function localeAlternateLinks(routePath, { locales, defaultLocale } = {}, localize) {
|
|
178
|
+
if (!Array.isArray(locales) || locales.length === 0 || typeof localize !== "function") return [];
|
|
179
|
+
const links = locales.map((locale) => ({
|
|
180
|
+
rel: "alternate",
|
|
181
|
+
hreflang: locale,
|
|
182
|
+
href: localize(routePath, locale),
|
|
183
|
+
}));
|
|
184
|
+
links.push({ rel: "alternate", hreflang: "x-default", href: localize(routePath, defaultLocale) });
|
|
185
|
+
return links;
|
|
186
|
+
}
|