@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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -2
  3. package/components/Link.d.ts +12 -0
  4. package/components/Link.jsx +54 -0
  5. package/core/context.d.ts +7 -0
  6. package/core/context.js +60 -0
  7. package/core/dev.js +27 -0
  8. package/core/errors.d.ts +14 -0
  9. package/core/errors.js +48 -0
  10. package/core/html.js +10 -0
  11. package/core/metadata.js +186 -0
  12. package/core/reactive.d.ts +5 -0
  13. package/core/reactive.js +190 -0
  14. package/core/render-context.js +11 -0
  15. package/core/signals.d.ts +8 -0
  16. package/core/signals.js +264 -0
  17. package/index.d.ts +5 -0
  18. package/index.js +13 -0
  19. package/jsx-runtime.d.ts +37 -0
  20. package/package.json +66 -4
  21. package/runtime/clipboard.d.ts +7 -0
  22. package/runtime/clipboard.js +47 -0
  23. package/runtime/code-block.d.ts +14 -0
  24. package/runtime/code-block.js +76 -0
  25. package/runtime/context.browser.js +163 -0
  26. package/runtime/context.d.ts +13 -0
  27. package/runtime/context.js +44 -0
  28. package/runtime/dom.browser.js +423 -0
  29. package/runtime/dom.d.ts +142 -0
  30. package/runtime/dom.js +670 -0
  31. package/runtime/error-boundary.browser.js +140 -0
  32. package/runtime/error-boundary.d.ts +19 -0
  33. package/runtime/error-boundary.js +123 -0
  34. package/runtime/events.browser.js +29 -0
  35. package/runtime/events.d.ts +1 -0
  36. package/runtime/events.js +17 -0
  37. package/runtime/head.js +29 -0
  38. package/runtime/hmr.js +199 -0
  39. package/runtime/hydrate.browser.js +144 -0
  40. package/runtime/hydrate.d.ts +179 -0
  41. package/runtime/hydrate.js +584 -0
  42. package/runtime/index.d.ts +14 -0
  43. package/runtime/index.js +24 -0
  44. package/runtime/lifecycle.d.ts +6 -0
  45. package/runtime/lifecycle.js +14 -0
  46. package/runtime/mount.d.ts +20 -0
  47. package/runtime/mount.js +88 -0
  48. package/runtime/portal.browser.js +85 -0
  49. package/runtime/portal.d.ts +12 -0
  50. package/runtime/portal.js +74 -0
  51. package/runtime/raw-html.d.ts +11 -0
  52. package/runtime/raw-html.js +55 -0
  53. package/runtime/resource.d.ts +9 -0
  54. package/runtime/resource.js +139 -0
  55. package/runtime/route-data.d.ts +15 -0
  56. package/runtime/route-data.js +64 -0
  57. package/runtime/router.d.ts +149 -0
  58. package/runtime/router.js +807 -0
  59. package/server/adapters/node.d.ts +28 -0
  60. package/server/adapters/node.js +74 -0
  61. package/server/api.d.ts +175 -0
  62. package/server/api.js +233 -0
  63. package/server/builtins.js +42 -0
  64. package/server/cookies.d.ts +44 -0
  65. package/server/cookies.js +122 -0
  66. package/server/head.js +9 -0
  67. package/server/index.d.ts +155 -0
  68. package/server/index.js +31 -0
  69. package/server/loader.js +201 -0
  70. package/server/middleware.js +119 -0
  71. package/server/render-context.js +30 -0
  72. package/server/render.js +175 -0
  73. package/server/ssg-runtime.js +297 -0
@@ -0,0 +1,122 @@
1
+ // Cookie helpers for server code (middleware, API handlers, loaders) — thin,
2
+ // standards-based wrappers over the `Cookie` / `Set-Cookie` headers (RFC 6265),
3
+ // so nobody hand-rolls header parsing or serialization:
4
+ //
5
+ // import { getCookie, setCookie, deleteCookie } from "@opentf/afw/server";
6
+ //
7
+ // // read (middleware/handler/loader — anything holding the Request)
8
+ // const session = getCookie(request, "session");
9
+ //
10
+ // // write — appends a Set-Cookie header to a Response (or Headers)
11
+ // const res = Response.json({ ok: true });
12
+ // setCookie(res, "session", token, { httpOnly: true, maxAge: 3600 });
13
+ //
14
+ // Values are percent-encoded on write and decoded on read, so any string round-
15
+ // trips. Reading accepts a `Request` (or anything with `.headers`), a `Headers`,
16
+ // or the raw `Cookie` header string. Writing accepts a `Response` (or anything
17
+ // with `.headers`) or a `Headers`; note a *fetched* Response has immutable
18
+ // headers — wrap it first (`new Response(res.body, res)`), which the middleware
19
+ // response-decoration pattern (docs/MIDDLEWARE.md) does anyway.
20
+
21
+ // RFC 6265 cookie-name: an HTTP token (no separators/whitespace/control chars).
22
+ const NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
23
+
24
+ const decode = (s) => {
25
+ try {
26
+ return decodeURIComponent(s);
27
+ } catch {
28
+ return s; // malformed input stays raw rather than throwing
29
+ }
30
+ };
31
+
32
+ /** The Headers of a Request/Response-like target, or the Headers itself. */
33
+ const headersOf = (target) => (target instanceof Headers ? target : target?.headers);
34
+
35
+ /**
36
+ * Parse cookies into a plain `{ name: value }` object. `source` is a `Request`
37
+ * (or anything with `.headers`), a `Headers`, or the raw `Cookie` header string.
38
+ * Values arrive percent-decoded; on a duplicate name the first occurrence wins
39
+ * (the most specific cookie is sent first — RFC 6265 §5.4).
40
+ */
41
+ export function getCookies(source) {
42
+ const header =
43
+ typeof source === "string" ? source : (headersOf(source)?.get("cookie") ?? "");
44
+ const out = {};
45
+ if (!header) return out;
46
+ for (const part of header.split(";")) {
47
+ const eq = part.indexOf("=");
48
+ if (eq === -1) continue;
49
+ const name = part.slice(0, eq).trim();
50
+ if (!name || name in out) continue;
51
+ let value = part.slice(eq + 1).trim();
52
+ // Tolerate the optional RFC 6265 double-quoted form.
53
+ if (value.length >= 2 && value.startsWith('"') && value.endsWith('"')) value = value.slice(1, -1);
54
+ out[name] = decode(value);
55
+ }
56
+ return out;
57
+ }
58
+
59
+ /** One cookie's (percent-decoded) value, or `undefined` when absent. */
60
+ export function getCookie(source, name) {
61
+ return getCookies(source)[name];
62
+ }
63
+
64
+ /**
65
+ * Serialize one `Set-Cookie` header value. The value is percent-encoded (any
66
+ * string round-trips through `getCookie`). `path` defaults to `"/"` — the
67
+ * almost-always-right choice (the spec default is the *request's* path, a
68
+ * classic footgun); pass `path: null` to omit it.
69
+ *
70
+ * Options: `path`, `domain`, `maxAge` (seconds), `expires` (Date or date
71
+ * string/ms), `httpOnly`, `secure`, `sameSite` ("Strict" | "Lax" | "None"),
72
+ * `partitioned`. `sameSite: "None"` requires `secure: true` (browsers reject it
73
+ * otherwise) — enforced here so the mistake fails loudly at write time.
74
+ */
75
+ export function serializeCookie(name, value, options = {}) {
76
+ if (!NAME.test(name)) throw new TypeError(`invalid cookie name: ${JSON.stringify(name)}`);
77
+ const { path = "/", domain, maxAge, expires, httpOnly, secure, sameSite, partitioned } = options;
78
+ let out = `${name}=${encodeURIComponent(value)}`;
79
+ if (path != null) out += `; Path=${path}`;
80
+ if (domain) out += `; Domain=${domain}`;
81
+ if (maxAge != null) {
82
+ if (!Number.isFinite(maxAge)) throw new TypeError(`invalid cookie maxAge: ${maxAge}`);
83
+ out += `; Max-Age=${Math.trunc(maxAge)}`;
84
+ }
85
+ if (expires != null) {
86
+ const d = expires instanceof Date ? expires : new Date(expires);
87
+ if (Number.isNaN(d.getTime())) throw new TypeError(`invalid cookie expires: ${expires}`);
88
+ out += `; Expires=${d.toUTCString()}`;
89
+ }
90
+ if (httpOnly) out += `; HttpOnly`;
91
+ if (secure) out += `; Secure`;
92
+ if (sameSite != null) {
93
+ const norm = { strict: "Strict", lax: "Lax", none: "None" }[String(sameSite).toLowerCase()];
94
+ if (!norm) throw new TypeError(`invalid cookie sameSite: ${sameSite}`);
95
+ if (norm === "None" && !secure) {
96
+ throw new TypeError(`sameSite: "None" requires secure: true (browsers reject it otherwise)`);
97
+ }
98
+ out += `; SameSite=${norm}`;
99
+ }
100
+ if (partitioned) out += `; Partitioned`;
101
+ return out;
102
+ }
103
+
104
+ /**
105
+ * Append a `Set-Cookie` header to `target` — a `Response` (or anything with
106
+ * `.headers`) or a `Headers`. Appends, never overwrites, so multiple cookies on
107
+ * one response coexist (session + CSRF). Returns the serialized header value.
108
+ */
109
+ export function setCookie(target, name, value, options) {
110
+ const serialized = serializeCookie(name, value, options);
111
+ headersOf(target).append("set-cookie", serialized);
112
+ return serialized;
113
+ }
114
+
115
+ /**
116
+ * Expire a cookie on the client: an empty value with `Max-Age=0` and an epoch
117
+ * `Expires`. `path`/`domain` must match how the cookie was set or the browser
118
+ * treats it as a different cookie and keeps the original.
119
+ */
120
+ export function deleteCookie(target, name, { path = "/", domain } = {}) {
121
+ return setCookie(target, name, "", { path, domain, maxAge: 0, expires: new Date(0) });
122
+ }
package/server/head.js ADDED
@@ -0,0 +1,9 @@
1
+ // Server metadata resolution accepts eager modules and lazy route loaders.
2
+ import { layoutChain, resolveModule } from "../runtime/router.js";
3
+ import { resolveMetadataModules } from "../core/metadata.js";
4
+ export { renderHead, localeAlternateLinks } from "../core/metadata.js";
5
+
6
+ export async function resolveMetadata({ route, entry, params = {}, query = {}, layouts = layoutChain(route) } = {}) {
7
+ const modules = await Promise.all([...layouts, entry].map(resolveModule));
8
+ return resolveMetadataModules(modules, { params, query });
9
+ }
@@ -0,0 +1,155 @@
1
+ // Types for the `@opentf/afw/server` entry. The API-routes surface is fully typed
2
+ // (./api); the SSG string-builders and render helpers — authored in JS and mostly
3
+ // consumed by generated entry code — are declared with permissive signatures.
4
+
5
+ export * from "./api.js";
6
+ export * from "./cookies.js";
7
+ export * from "../core/signals.js";
8
+ export * from "../core/reactive.js";
9
+ export * from "../core/errors.js";
10
+ export * from "../core/context.js";
11
+ export * from "../runtime/lifecycle.js";
12
+ export { resource } from "../runtime/resource.js";
13
+ export { copyText, copyWithFeedback } from "../runtime/clipboard.js";
14
+
15
+ /** DOM-free built-in renderers used by the server compiler. */
16
+ export interface ServerComponent {
17
+ (props: Record<string, unknown>, children?: string): string;
18
+ tag: string;
19
+ hostClass?: string;
20
+ hostAttrs?: (props: Record<string, unknown>) => string;
21
+ }
22
+ export const Link: ServerComponent;
23
+ export const ContextProvider: ServerComponent;
24
+ export const Portal: ServerComponent;
25
+ export const ErrorBoundary: ServerComponent;
26
+ export const RawHtml: ServerComponent;
27
+ export const CodeFence: ServerComponent;
28
+ export function shouldInterceptNav(): boolean;
29
+
30
+ /** Register eager namespaces or lazy module loaders, keyed by app file path. */
31
+ export function registerRoutes(modules: Record<string, unknown>): void;
32
+ /** Request-scoped route values during SSR. */
33
+ export const router: {
34
+ readonly pathname: string;
35
+ readonly searchParams: URLSearchParams;
36
+ readonly query: Record<string, string>;
37
+ readonly params: RouteParams;
38
+ readonly locale: string | null;
39
+ readonly data: unknown;
40
+ /** The current page's headings (MDX `export const toc`), or `[]`. */
41
+ readonly toc: { depth: number; id: string; text: string }[];
42
+ };
43
+ export function matchRoute(pathname: string): { entry: unknown; params: RouteParams; route: string } | null;
44
+ export function configureI18n(config: { locales: string[]; defaultLocale?: string } | null): void;
45
+ export function i18nLocales(): { locales: string[]; defaultLocale: string } | null;
46
+ export function resolveLocale(pathname: string): { locale: string | null; path: string };
47
+ export function localizePath(pathname: string, locale?: string | null): string;
48
+ /** Set the current request's locale during server rendering. */
49
+ export function setLocale(locale: string | null): void;
50
+ /** Publish a page module's `toc` export as `router.toc`. */
51
+ export function setRouteToc(pageModule: { toc?: unknown } | null | undefined): void;
52
+ /** Set the current request's route state directly. */
53
+ export function setRouteState(state?: {
54
+ pathname?: string;
55
+ search?: string;
56
+ params?: RouteParams;
57
+ locale?: string | null;
58
+ data?: unknown;
59
+ }): void;
60
+ /** No-op on the server: there is no mounted app to navigate. */
61
+ export function navigate(path: string, replace?: boolean): Promise<void>;
62
+ /** Always `false` during server rendering. */
63
+ export function isHydrating(): boolean;
64
+ export { emit } from "../runtime/events.js";
65
+
66
+ // ── Render / route API (render.js) ─────────────────────────────────────────────
67
+ export interface RenderResult {
68
+ html: string;
69
+ metadata: Record<string, unknown>;
70
+ hydration: unknown;
71
+ status?: number;
72
+ }
73
+ export function renderRoute(
74
+ pathname: string,
75
+ params?: Record<string, unknown> | null,
76
+ search?: string,
77
+ options?: { data?: unknown },
78
+ ): Promise<RenderResult | null>;
79
+ export function renderToString(pathname: string, search?: string): Promise<string>;
80
+ export function collectRoutePaths(): Promise<{
81
+ paths: Array<{ path: string; params: Record<string, unknown>; route: string }>;
82
+ skipped: string[];
83
+ }>;
84
+
85
+ // ── <head> / metadata (head.js) ─────────────────────────────────────────────────
86
+ export function resolveMetadata(args?: {
87
+ route?: string;
88
+ entry?: unknown;
89
+ layouts?: unknown[];
90
+ params?: Record<string, unknown>;
91
+ query?: Record<string, unknown>;
92
+ }): Promise<Record<string, unknown>>;
93
+ export function renderHead(meta?: Record<string, unknown>, opts?: { path?: string; baseUrl?: string; managed?: boolean }): string;
94
+ export function localeAlternateLinks(
95
+ routePath: string,
96
+ cfg?: { locales?: string[]; defaultLocale?: string },
97
+ localize?: (path: string, locale: string) => string,
98
+ ): Array<Record<string, string>>;
99
+
100
+ // ── Route loaders (loader.js) ───────────────────────────────────────────────────
101
+ import type { RouteParams } from "./api.js";
102
+
103
+ /** The context a route loader receives (docs/DATA.md). `request` is the live
104
+ * Request under serve/dev and undefined at SSG prerender; `locals` is reserved. */
105
+ export interface LoaderContext {
106
+ params: RouteParams;
107
+ query: Record<string, string>;
108
+ request?: Request;
109
+ locale: string | null;
110
+ locals: Record<string, unknown>;
111
+ }
112
+
113
+ /** A route loader — the default (or named `loader`) export of a `loader.{js,ts}`
114
+ * file. Returns the page's JSON-serializable data. */
115
+ export type Loader = (context: LoaderContext) => unknown | Promise<unknown>;
116
+
117
+ export interface LoaderMatch {
118
+ route: string;
119
+ params: RouteParams;
120
+ locale: string | null;
121
+ }
122
+
123
+ export interface LoaderRegistry {
124
+ routes: string[];
125
+ match(pathname: string): LoaderMatch | null;
126
+ load(m: LoaderMatch, ctx?: { request?: Request; query?: Record<string, string> }): Promise<unknown>;
127
+ loadSerialized(
128
+ m: LoaderMatch,
129
+ ctx?: { request?: Request; query?: Record<string, string> },
130
+ ): Promise<{ data: unknown; json: string }>;
131
+ handle(request: Request): Promise<Response | null>;
132
+ }
133
+
134
+ export function createLoaderRegistry(
135
+ loaderModules?: Record<string, { default?: Loader; loader?: Loader }>,
136
+ options?: { appDir?: string; i18n?: { locales?: string[]; defaultLocale?: string } },
137
+ ): LoaderRegistry;
138
+ export function loaderRouteFromPath(filePath: string, appDir?: string): string;
139
+ /** Throw "this page does not exist" from inside a loader (404 semantics). */
140
+ export function notFound(message?: string): never;
141
+ export function isNotFound(e: unknown): boolean;
142
+ export function serializeRouteData(value: unknown): string;
143
+
144
+ // ── SSG string-builder helpers (ssg-runtime.js) ─────────────────────────────────
145
+ export function defineSSG(tag: string, render: (...args: any[]) => string): void;
146
+ export function beginHydrationCollect(): void;
147
+ export function endHydrationCollect(): unknown;
148
+ export function escapeHtml(s: unknown): string;
149
+ export function escapeAttr(s: unknown): string;
150
+ export function clsx(value: unknown): string;
151
+ export function styleString(value: unknown): string;
152
+ export function attr(name: string, value: unknown): string;
153
+ export function ssgText(v: unknown): string;
154
+ export function ssgList<T>(arr: T[], fn: (item: T, index: number) => string): string;
155
+ export function ssgComponent(tag: string, props?: Record<string, unknown>, children?: unknown): string;
@@ -0,0 +1,31 @@
1
+ // Server entry for SSG: the string-building helpers the compiler emits, the
2
+ // render/route API, and the built-in component SSG renderers (registered on
3
+ // import). Imported as "@opentf/afw/server".
4
+
5
+ export * from "./ssg-runtime.js";
6
+ export * from "../core/signals.js";
7
+ export * from "../core/reactive.js";
8
+ export * from "../core/errors.js";
9
+ export * from "../core/context.js";
10
+ export * from "../runtime/lifecycle.js";
11
+ export { resource } from "../runtime/resource.js";
12
+ export { copyText, copyWithFeedback } from "../runtime/clipboard.js";
13
+ export { Link, ContextProvider, Portal, ErrorBoundary, RawHtml, CodeFence } from "./builtins.js";
14
+ export * from "./head.js";
15
+ export * from "./render.js";
16
+ // Share registration and request-scoped route state without loading Custom Elements.
17
+ // Server builds resolve a page's `@opentf/afw` imports here, so the client APIs a
18
+ // page may call or reference must exist too: `setLocale`/`setRouteState` write the
19
+ // request's route state, `navigate` is a no-op without a mounted app.
20
+ export {
21
+ registerRoutes, router, matchRoute, configureI18n, i18nLocales,
22
+ resolveLocale, localizePath, shouldInterceptNav,
23
+ setLocale, setRouteState, setRouteToc, navigate,
24
+ } from "../runtime/router.js";
25
+ export { isHydrating } from "../runtime/hydrate.js";
26
+ export { emit } from "../runtime/events.js";
27
+ export * from "./api.js";
28
+ export { createMiddleware } from "./middleware.js";
29
+ export * from "./cookies.js";
30
+ export * from "./loader.js";
31
+ import "./builtins.js";
@@ -0,0 +1,201 @@
1
+ // Route loaders — the server half of data fetching (docs/DATA.md, SPEC §8). A
2
+ // loader is a `loader.{js,ts}` file sibling to a `page.*` (the data analogue of
3
+ // a `route.*` API endpoint): a *plain server module* whose default export (or
4
+ // named `loader` export, the Phase B compiler convention) returns the page's
5
+ // JSON-serializable data:
6
+ //
7
+ // export default async function loader({ params, query, request, locale, locals }) {
8
+ // return db.todos.list();
9
+ // }
10
+ //
11
+ // `createLoaderRegistry` turns a discovered `{ absFilePath: namespace }` map into
12
+ // a matcher + runner shared by every consumer: SSG prerender (build time, no
13
+ // `request`), the SSR server (per request), the dev server, and the
14
+ // `<path>/__data.json` HTTP endpoint SPA navigation fetches from (`handle`).
15
+ //
16
+ // Matching duplicates the `[param]` / `[...rest]` compile/decode approach of the
17
+ // API handler (api.js) — like api.js itself mirrors the page router — so params
18
+ // behave identically across pages, endpoints, and loaders.
19
+
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
+ }
30
+
31
+ /** The page route a `.../app/<...>/loader.{js,ts}` file feeds (folder = URL):
32
+ * `app/todos/loader.js` → `/todos`, `app/loader.js` → `/`. */
33
+ export function loaderRouteFromPath(filePath, appDir) {
34
+ const r = stripAppDir(filePath, appDir).replace(/\/loader\.(js|ts)$/, "");
35
+ return r === "" ? "/" : r;
36
+ }
37
+
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
+ /**
62
+ * Signal "this page does not exist for these params" from inside a loader — the
63
+ * SSR server responds 404 (rendering the 404 page), the data endpoint returns a
64
+ * 404 the client maps to `undefined`, and SSG records the path as failed.
65
+ */
66
+ export function notFound(message = "Not Found") {
67
+ const e = new Error(message);
68
+ e.name = "NotFoundError";
69
+ // A marker property, not a class: the loader bundle and the server bundle are
70
+ // separate module graphs (each bundles its own copy of this file), so an
71
+ // `instanceof` check would fail across the boundary.
72
+ e.afwNotFound = true;
73
+ throw e;
74
+ }
75
+
76
+ /** Was `e` thrown by {@link notFound}? (Property check — see the note there.) */
77
+ export function isNotFound(e) {
78
+ return e?.afwNotFound === true;
79
+ }
80
+
81
+ /**
82
+ * Serialize loader data for embedding: the inline `#__afw_data` script and the
83
+ * static `__data.json` file must carry identical bytes. `<` is escaped so the
84
+ * payload can never close the inline `<script>` (same rule as the island-props
85
+ * collector in ssg-runtime.js). `undefined` (no data) serializes to `""` — the
86
+ * toolchain skips injection entirely.
87
+ */
88
+ export function serializeRouteData(value) {
89
+ const json = JSON.stringify(value);
90
+ return json === undefined ? "" : json.replace(/</g, "\\u003c");
91
+ }
92
+
93
+ /**
94
+ * Build the loader registry from a discovered `{ absFilePath: namespace }` map.
95
+ *
96
+ * @param {Record<string, object>} loaderModules each module's default (or `loader`)
97
+ * export is the loader function.
98
+ * @param {{ appDir?: string, i18n?: { locales?: string[], defaultLocale?: string } }} [options]
99
+ * `appDir` pins exact route derivation; `i18n` lets `match` strip a leading
100
+ * non-default locale prefix (`/fr/todos` matches the `/todos` loader with
101
+ * `locale: "fr"` in the context).
102
+ * @returns {{ routes: string[],
103
+ * match: (pathname: string) => object | null,
104
+ * load: (m: object, ctx?: object) => Promise<unknown>,
105
+ * loadSerialized: (m: object, ctx?: object) => Promise<{ data: unknown, json: string }>,
106
+ * handle: (request: Request, extras?: { locals?: object }) => Promise<Response | null> }}
107
+ */
108
+ export function createLoaderRegistry(loaderModules = {}, { appDir, i18n } = {}) {
109
+ const entries = [];
110
+ for (const file in loaderModules) {
111
+ const ns = loaderModules[file];
112
+ const fn = ns.default ?? ns.loader;
113
+ if (typeof fn !== "function") continue; // a loader file without a loader export is inert
114
+ const route = loaderRouteFromPath(file, appDir);
115
+ entries.push({ route, pattern: compilePattern(route), fn, dynamic: route.includes("[") });
116
+ }
117
+ // Static before dynamic, longer before shorter — most specific wins (see api.js).
118
+ entries.sort((a, b) => a.dynamic - b.dynamic || b.route.length - a.route.length);
119
+
120
+ const i18nOn = !!(i18n && Array.isArray(i18n.locales) && i18n.locales.length);
121
+ const defaultLocale = i18nOn ? (i18n.defaultLocale ?? i18n.locales[0]) : null;
122
+ const nonDefault = i18nOn ? new Set(i18n.locales.filter((l) => l !== defaultLocale)) : null;
123
+
124
+ /** Match a *page* pathname (no `__data.json` suffix) → `{ route, params, locale }` or null. */
125
+ function match(pathname) {
126
+ let path = normalize(pathname);
127
+ let locale = defaultLocale;
128
+ if (nonDefault) {
129
+ const m = path.match(/^\/([^/]+)(\/.*|)$/);
130
+ if (m && nonDefault.has(m[1])) {
131
+ locale = m[1];
132
+ path = m[2] || "/";
133
+ }
134
+ }
135
+ for (const e of entries) {
136
+ const m = path.match(e.pattern);
137
+ if (!m) continue;
138
+ const params = { ...(m.groups || {}) };
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 };
145
+ }
146
+ return null;
147
+ }
148
+
149
+ /** Run a matched loader. `request` is the live Request under serve/dev and
150
+ * `undefined` at SSG prerender; `locals` is the per-request bag pipeline
151
+ * middleware stamped (middleware.js) — empty at prerender, where none runs. */
152
+ async function load(m, { request, query = {}, locals = {} } = {}) {
153
+ return m.fn({ params: m.params, query, request, locale: m.locale, locals });
154
+ }
155
+
156
+ /** {@link load}, plus the serialized form — escaping lives in one place. */
157
+ async function loadSerialized(m, ctx) {
158
+ const data = await load(m, ctx);
159
+ return { data, json: serializeRouteData(data) };
160
+ }
161
+
162
+ /**
163
+ * The `<path>/__data.json` HTTP endpoint (docs/DATA.md): a `Response` for any
164
+ * data URL — including 404 on a miss, so the reserved suffix never falls
165
+ * through to SSR — or `null` for every other path.
166
+ */
167
+ async function handle(request, { locals } = {}) {
168
+ const url = new URL(request.url);
169
+ const pathname = normalize(url.pathname);
170
+ let pagePath = null;
171
+ if (pathname === `/${DATA_FILE}`) pagePath = "/";
172
+ else if (pathname.endsWith(`/${DATA_FILE}`)) {
173
+ pagePath = pathname.slice(0, -(DATA_FILE.length + 1)) || "/";
174
+ }
175
+ if (pagePath === null) return null;
176
+
177
+ const method = request.method.toUpperCase();
178
+ if (method !== "GET" && method !== "HEAD") {
179
+ return new Response(null, { status: 405, headers: { Allow: "GET, HEAD" } });
180
+ }
181
+ const headers = { "content-type": "application/json", "cache-control": "no-store" };
182
+ const m = match(pagePath);
183
+ if (!m) return new Response("null", { status: 404, headers });
184
+ try {
185
+ const { json } = await loadSerialized(m, {
186
+ request,
187
+ query: Object.fromEntries(url.searchParams),
188
+ locals,
189
+ });
190
+ // `json || "null"` — an undefined loader result still yields valid JSON
191
+ // (the client maps a 404 to undefined; a 200 must parse).
192
+ return new Response(method === "HEAD" ? null : json || "null", { status: 200, headers });
193
+ } catch (e) {
194
+ if (isNotFound(e)) return new Response("null", { status: 404, headers });
195
+ console.error(`✗ loader ${pagePath}:`, e?.stack ?? e);
196
+ return Response.json({ error: "Internal Server Error" }, { status: 500 });
197
+ }
198
+ }
199
+
200
+ return { routes: entries.map((e) => e.route), match, load, loadSerialized, handle };
201
+ }
@@ -0,0 +1,119 @@
1
+ // Request middleware for the AFW servers (SPEC §11.5, docs/MIDDLEWARE.md). A
2
+ // `_middleware.{js,ts}` file applies to its folder and everything nested under it —
3
+ // pages, API endpoints, route-loader data requests, and 404s alike, not just
4
+ // `/api/*`. `createMiddleware` turns a discovered `{ absFilePath: namespace }` map
5
+ // into a runner the server wraps around its whole request pipeline:
6
+ //
7
+ // const res = await middleware.run(request, terminal); // terminal: (req, context) => Response
8
+ //
9
+ // Middleware runs *before* routing (like Next.js's middleware), so it can gate a
10
+ // page, stamp `context.locals` for API handlers and loaders, add headers to any
11
+ // response (it wraps `next()`), or rewrite the request by calling
12
+ // `next(new Request(url, request))` — the terminal routes on the rewritten request.
13
+ //
14
+ // Scope matching is security-aware in two ways the raw pathname isn't:
15
+ // • a `<path>/__data.json` loader-data request is governed by the *page's* scope
16
+ // (a guard on `/admin` must also gate `/admin/__data.json`, or SPA navigation
17
+ // would leak the protected loader payload);
18
+ // • a non-default locale prefix is stripped (`/fr/admin` is governed by `/admin`
19
+ // middleware), mirroring the loader registry (loader.js `match`).
20
+
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
+ }
31
+
32
+ /** The folder route a `_middleware.{js,ts}` file governs: `app/api/_middleware.js`
33
+ * → `/api` (applies to `/api` and everything nested under it); `app/_middleware.js`
34
+ * → `/` (every request). */
35
+ export function middlewareScopeFromPath(filePath, appDir) {
36
+ const r = stripAppDir(filePath, appDir).replace(/\/_middleware\.(jsx?|tsx?)$/, "");
37
+ return r === "" ? "/" : r;
38
+ }
39
+
40
+ const normalize = (p) => (p || "/").replace(/(.)\/+$/, "$1");
41
+
42
+ /**
43
+ * Build the middleware runner from a discovered `{ absFilePath: namespace }` map.
44
+ *
45
+ * @param {Record<string, object>} middlewareModules the middleware is each
46
+ * module's default (or named `middleware`) export.
47
+ * @param {{ appDir?: string, i18n?: { locales?: string[], defaultLocale?: string } }} [options]
48
+ * `appDir` pins exact scope derivation; `i18n` lets scope matching strip a
49
+ * leading non-default locale prefix (mirroring the loader registry).
50
+ * @returns {{ size: number, scopes: string[],
51
+ * run: (request: Request,
52
+ * terminal: (req: Request, context: object) => Response | Promise<Response>,
53
+ * extras?: { env?: unknown, ctx?: unknown }) => Promise<Response> }}
54
+ */
55
+ export function createMiddleware(middlewareModules = {}, { appDir, i18n } = {}) {
56
+ const entries = [];
57
+ for (const file in middlewareModules) {
58
+ const mod = middlewareModules[file];
59
+ const fn = mod.default ?? mod.middleware;
60
+ if (typeof fn === "function") entries.push({ scope: middlewareScopeFromPath(file, appDir), fn });
61
+ }
62
+ // Outermost (shortest scope) runs first, so `app/_middleware` wraps `app/api/_middleware`.
63
+ entries.sort((a, b) => a.scope.length - b.scope.length);
64
+
65
+ const i18nOn = !!(i18n && Array.isArray(i18n.locales) && i18n.locales.length);
66
+ const defaultLocale = i18nOn ? (i18n.defaultLocale ?? i18n.locales[0]) : null;
67
+ const nonDefault = i18nOn ? new Set(i18n.locales.filter((l) => l !== defaultLocale)) : null;
68
+
69
+ // The pathname scopes match against: `__data.json` stripped to its page path,
70
+ // locale prefix stripped (see the header comment for why both matter).
71
+ function scopePath(pathname) {
72
+ let path = normalize(pathname);
73
+ if (path === `/${DATA_FILE}`) path = "/";
74
+ else if (path.endsWith(`/${DATA_FILE}`)) path = path.slice(0, -(DATA_FILE.length + 1)) || "/";
75
+ if (nonDefault) {
76
+ const m = path.match(/^\/([^/]+)(\/.*|)$/);
77
+ if (m && nonDefault.has(m[1])) path = m[2] === "" || m[2] === "/" ? "/" : m[2];
78
+ }
79
+ return path;
80
+ }
81
+
82
+ /**
83
+ * Run the applicable middleware chain around `terminal`. The shared `context`
84
+ * (`{ url, locals, env, ctx }`) is handed to every middleware and to the
85
+ * terminal — `locals` is the channel middleware uses to pass data (auth user,
86
+ * validated body) down to API handlers and route loaders. There are no `params`:
87
+ * middleware runs before routing, so no route has matched yet.
88
+ *
89
+ * Each middleware is `(request, context, next)`; `next()` continues with the
90
+ * current request, `next(rewrittenRequest)` re-routes downstream. A returned or
91
+ * thrown `Response` short-circuits; any other throw is a 500. Returning nothing
92
+ * (a forgotten `return next()`) is an error, not a hang.
93
+ */
94
+ async function run(request, terminal, { env, ctx } = {}) {
95
+ const url = new URL(request.url);
96
+ const context = { url, locals: {}, env, ctx };
97
+ const path = scopePath(url.pathname);
98
+ const chain = entries.filter((e) => e.scope === "/" || path === e.scope || path.startsWith(e.scope + "/"));
99
+ let next = (req) => terminal(req, context);
100
+ for (let i = chain.length - 1; i >= 0; i--) {
101
+ const { fn } = chain[i];
102
+ const downstream = next;
103
+ next = (req) => fn(req, context, (nextReq) => downstream(nextReq instanceof Request ? nextReq : req));
104
+ }
105
+ try {
106
+ const res = await next(request);
107
+ if (res instanceof Response) return res;
108
+ throw new Error(
109
+ `middleware for ${request.method} ${url.pathname} returned no Response (did you forget to return next()?)`,
110
+ );
111
+ } catch (e) {
112
+ if (e instanceof Response) return e; // middleware may throw a Response
113
+ console.error(`✗ middleware ${request.method} ${url.pathname}:`, e?.stack ?? e);
114
+ return Response.json({ error: "Internal Server Error" }, { status: 500 });
115
+ }
116
+ }
117
+
118
+ return { size: entries.length, scopes: entries.map((e) => e.scope), run };
119
+ }
@@ -0,0 +1,30 @@
1
+ import { setRenderContextReader } from "../core/render-context.js";
2
+
3
+ let contextPromise;
4
+
5
+ // Resolve at runtime: server consumers can run on esdev or on a runtime with
6
+ // AsyncLocalStorage. Neither runtime-specific module belongs in a browser bundle.
7
+ const loadModule = (specifier) => import(specifier);
8
+
9
+ async function createRenderContext() {
10
+ let context;
11
+ try {
12
+ const { createContext } = await loadModule("runtime:context");
13
+ context = createContext({ name: "afw-render" });
14
+ } catch (nativeError) {
15
+ try {
16
+ const { AsyncLocalStorage } = await loadModule("node:async_hooks");
17
+ const storage = new AsyncLocalStorage();
18
+ context = { get: () => storage.getStore(), run: (value, fn) => storage.run(value, fn) };
19
+ } catch {
20
+ throw new Error("SSR requires runtime:context or AsyncLocalStorage for request isolation.", { cause: nativeError });
21
+ }
22
+ }
23
+ setRenderContextReader(() => context.get());
24
+ return context;
25
+ }
26
+
27
+ export async function withRenderContext(value, fn) {
28
+ const context = await (contextPromise ??= createRenderContext());
29
+ return context.run(value, fn);
30
+ }