@opentf/afw 0.0.0-stage → 0.32.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.
Files changed (72) hide show
  1. package/README.md +66 -2
  2. package/components/Link.d.ts +12 -0
  3. package/components/Link.jsx +54 -0
  4. package/core/context.d.ts +7 -0
  5. package/core/context.js +60 -0
  6. package/core/dev.js +27 -0
  7. package/core/errors.d.ts +14 -0
  8. package/core/errors.js +48 -0
  9. package/core/html.js +10 -0
  10. package/core/metadata.js +184 -0
  11. package/core/reactive.d.ts +5 -0
  12. package/core/reactive.js +190 -0
  13. package/core/render-context.js +11 -0
  14. package/core/signals.d.ts +8 -0
  15. package/core/signals.js +264 -0
  16. package/index.d.ts +5 -0
  17. package/index.js +13 -0
  18. package/jsx-runtime.d.ts +37 -0
  19. package/package.json +60 -4
  20. package/runtime/clipboard.d.ts +7 -0
  21. package/runtime/clipboard.js +47 -0
  22. package/runtime/code-block.d.ts +14 -0
  23. package/runtime/code-block.js +76 -0
  24. package/runtime/context.browser.js +163 -0
  25. package/runtime/context.d.ts +13 -0
  26. package/runtime/context.js +44 -0
  27. package/runtime/dom.browser.js +423 -0
  28. package/runtime/dom.d.ts +142 -0
  29. package/runtime/dom.js +670 -0
  30. package/runtime/error-boundary.browser.js +140 -0
  31. package/runtime/error-boundary.d.ts +19 -0
  32. package/runtime/error-boundary.js +123 -0
  33. package/runtime/events.browser.js +29 -0
  34. package/runtime/events.d.ts +1 -0
  35. package/runtime/events.js +17 -0
  36. package/runtime/head.js +29 -0
  37. package/runtime/hmr.js +170 -0
  38. package/runtime/hydrate.browser.js +144 -0
  39. package/runtime/hydrate.d.ts +173 -0
  40. package/runtime/hydrate.js +536 -0
  41. package/runtime/index.d.ts +14 -0
  42. package/runtime/index.js +24 -0
  43. package/runtime/lifecycle.d.ts +6 -0
  44. package/runtime/lifecycle.js +14 -0
  45. package/runtime/mount.d.ts +20 -0
  46. package/runtime/mount.js +85 -0
  47. package/runtime/portal.browser.js +85 -0
  48. package/runtime/portal.d.ts +12 -0
  49. package/runtime/portal.js +74 -0
  50. package/runtime/raw-html.d.ts +11 -0
  51. package/runtime/raw-html.js +55 -0
  52. package/runtime/resource.d.ts +9 -0
  53. package/runtime/resource.js +139 -0
  54. package/runtime/route-data.d.ts +15 -0
  55. package/runtime/route-data.js +64 -0
  56. package/runtime/router.d.ts +146 -0
  57. package/runtime/router.js +765 -0
  58. package/server/adapters/node.d.ts +28 -0
  59. package/server/adapters/node.js +74 -0
  60. package/server/api.d.ts +175 -0
  61. package/server/api.js +233 -0
  62. package/server/builtins.js +42 -0
  63. package/server/cookies.d.ts +44 -0
  64. package/server/cookies.js +122 -0
  65. package/server/head.js +9 -0
  66. package/server/index.d.ts +151 -0
  67. package/server/index.js +31 -0
  68. package/server/loader.js +201 -0
  69. package/server/middleware.js +119 -0
  70. package/server/render-context.js +30 -0
  71. package/server/render.js +172 -0
  72. package/server/ssg-runtime.js +239 -0
package/README.md CHANGED
@@ -1,3 +1,67 @@
1
- # Temporary Holding Version
1
+ # @opentf/afw
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The native-first **AFW** runtime — signal-based reactivity and zero-VDOM DOM
4
+ operations, paired with the IR-based compiler ([`@opentf/afw-compiler`](https://github.com/Open-Tech-Foundation/afw/tree/main/packages/afw-compiler)).
5
+
6
+ You normally don't call this API by hand. You write `.jsx` components; the compiler
7
+ lowers them to plain DOM code that imports its helpers (`signal`, `computed`,
8
+ `bindText`, `bindList`, …) from this package. Components compile to self-registering
9
+ `web-*` Custom Elements.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pnpm add @opentf/afw
15
+ ```
16
+
17
+ Scaffold a ready-to-run app with [`esdev create`](https://esrun.opentechf.org/esdev/create)
18
+ and use `esdev start`, `esdev build`, and `esdev typecheck`.
19
+
20
+ ## TypeScript
21
+
22
+ The package includes runtime declarations and JSX types. For `.tsx` sources, keep
23
+ JSX for the AFW compiler and select the framework's type entry:
24
+
25
+ ```json
26
+ {
27
+ "compilerOptions": {
28
+ "jsx": "preserve",
29
+ "jsxImportSource": "@opentf/afw",
30
+ "moduleResolution": "bundler",
31
+ "lib": ["ESNext", "DOM", "DOM.Iterable"],
32
+ "strict": true,
33
+ "noEmit": true
34
+ }
35
+ }
36
+ ```
37
+
38
+ `esdev create my-app --language=ts` supplies the starter configuration and macro
39
+ declarations. `@opentf/afw/jsx-runtime` is a type entry; component compilation
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.
55
+
56
+ ## Entry points
57
+
58
+ | Import | Contents |
59
+ | --- | --- |
60
+ | `@opentf/afw` | runtime + reactivity + `Link` (what compiled components import) |
61
+ | `@opentf/afw/signals` | the reactivity core on its own |
62
+ | `@opentf/afw/runtime` | DOM helpers, Context, Portal, ErrorBoundary |
63
+ | `@opentf/afw/server` | DOM-free SSR/SSG rendering, route registration and shared framework helpers |
64
+
65
+ ## License
66
+
67
+ MIT © [Open Tech Foundation](https://github.com/Open-Tech-Foundation)
@@ -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;
@@ -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
+ }
@@ -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 === "&" ? "&amp;" : c === "<" ? "&lt;" : "&gt;"));
4
+ }
5
+
6
+ /** Escape an attribute value. */
7
+ export function escapeAttr(s) {
8
+ return String(s).replace(/[&"]/g, (c) => (c === "&" ? "&amp;" : "&quot;"));
9
+ }
10
+
@@ -0,0 +1,184 @@
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
+
138
+ // Twitter Card (falls back to Open Graph / top-level values).
139
+ const tw = isPlainObject(meta.twitter) ? meta.twitter : {};
140
+ const twImage = tw.image ? absUrl(baseUrl, tw.image) : ogImage;
141
+ push(metaTag("name", "twitter:card", tw.card ?? (twImage ? "summary_large_image" : "summary")));
142
+ push(metaTag("name", "twitter:title", tw.title ?? og.title ?? title));
143
+ push(metaTag("name", "twitter:description", tw.description ?? og.description ?? description));
144
+ push(metaTag("name", "twitter:image", twImage));
145
+
146
+ // Arbitrary extra tags (escape hatch for anything not modeled above).
147
+ for (const m of Array.isArray(meta.meta) ? meta.meta : []) {
148
+ const kind = m.name ? "name" : m.property ? "property" : m.httpEquiv ? "http-equiv" : null;
149
+ if (kind) push(metaTag(kind, m.name ?? m.property ?? m.httpEquiv, m.content));
150
+ }
151
+ for (const l of Array.isArray(meta.links) ? meta.links : []) {
152
+ const rel = l.rel ? ` rel="${escapeAttr(l.rel)}"` : "";
153
+ const href = l.href ? ` href="${escapeAttr(absUrl(baseUrl, l.href))}"` : "";
154
+ const type = l.type ? ` type="${escapeAttr(l.type)}"` : "";
155
+ const extra = l.hreflang ? ` hreflang="${escapeAttr(l.hreflang)}"` : "";
156
+ if (rel || href) push(`<link${rel}${type}${href}${extra}>`);
157
+ }
158
+
159
+ // Structured data (JSON-LD) for rich results.
160
+ if (meta.jsonLd != null) {
161
+ const json = typeof meta.jsonLd === "string" ? meta.jsonLd : JSON.stringify(meta.jsonLd);
162
+ push(`<script type="application/ld+json">${jsonLdSafe(json)}</script>`);
163
+ }
164
+
165
+ return tags.map(tag => managed ? tag.replace(/^<(title|meta|link|script)\b/, '<$1 data-afw-head=""') : tag).join("\n");
166
+ }
167
+
168
+ /**
169
+ * Build `rel="alternate" hreflang` link descriptors for a locale-agnostic
170
+ * `routePath` (e.g. `/about`) across all configured locales — for the toolchain to
171
+ * pass through `metadata.links` so `renderHead` emits them (docs/I18N.md §6). The
172
+ * default locale also gets `x-default`. `localize(path, locale)` is the router's
173
+ * `localizePath` (kept as a param so this stays free of a router import here).
174
+ */
175
+ export function localeAlternateLinks(routePath, { locales, defaultLocale } = {}, localize) {
176
+ if (!Array.isArray(locales) || locales.length === 0 || typeof localize !== "function") return [];
177
+ const links = locales.map((locale) => ({
178
+ rel: "alternate",
179
+ hreflang: locale,
180
+ href: localize(routePath, locale),
181
+ }));
182
+ links.push({ rel: "alternate", hreflang: "x-default", href: localize(routePath, defaultLocale) });
183
+ return links;
184
+ }
@@ -0,0 +1,5 @@
1
+ export function reactive<T extends object>(initial: T): T;
2
+ export function reactive(): Record<string, unknown>;
3
+ export function isReactive(value: unknown): boolean;
4
+ export function toRawValue<T>(value: T): T;
5
+ export function snapshot<T>(value: T): T;