@opentf/afw 0.33.0 → 0.35.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/components/Link.d.ts +2 -0
- package/components/Link.jsx +28 -1
- package/core/fn-codec.js +30 -0
- package/index.d.ts +1 -0
- package/jsx-runtime.d.ts +3 -1
- package/macros.d.ts +24 -0
- package/package.json +6 -2
- package/runtime/hmr.js +29 -4
- package/runtime/hot-carry.js +52 -0
- package/runtime/index.d.ts +2 -0
- package/runtime/index.js +2 -0
- package/runtime/invalidate.d.ts +6 -0
- package/runtime/invalidate.js +89 -0
- package/runtime/resource.d.ts +8 -2
- package/runtime/resource.js +22 -8
- package/runtime/route-match.js +99 -0
- package/runtime/router.d.ts +4 -0
- package/runtime/router.js +99 -22
- package/runtime/server-function.d.ts +14 -0
- package/runtime/server-function.js +53 -0
- package/server/adapters/node.js +31 -6
- package/server/api.d.ts +3 -1
- package/server/api.js +14 -58
- package/server/index.d.ts +55 -0
- package/server/index.js +4 -1
- package/server/loader.js +5 -42
- package/server/middleware.js +16 -14
- package/server/server-functions.js +138 -0
package/server/middleware.js
CHANGED
|
@@ -19,15 +19,7 @@
|
|
|
19
19
|
// middleware), mirroring the loader registry (loader.js `match`).
|
|
20
20
|
|
|
21
21
|
import { DATA_FILE } from "../runtime/route-data.js";
|
|
22
|
-
|
|
23
|
-
/** See `stripAppDir` in api.js — exact-prefix strip with a `/app` segment fallback. */
|
|
24
|
-
function stripAppDir(filePath, appDir) {
|
|
25
|
-
if (appDir) {
|
|
26
|
-
const base = appDir.replace(/\/+$/, "");
|
|
27
|
-
if (filePath.startsWith(base + "/")) return filePath.slice(base.length);
|
|
28
|
-
}
|
|
29
|
-
return filePath.replace(/^.*\/app(?=\/)/, "");
|
|
30
|
-
}
|
|
22
|
+
import { compareRoutes, compileScope, normalizePath as normalize, stripAppDir } from "../runtime/route-match.js";
|
|
31
23
|
|
|
32
24
|
/** The folder route a `_middleware.{js,ts}` file governs: `app/api/_middleware.js`
|
|
33
25
|
* → `/api` (applies to `/api` and everything nested under it); `app/_middleware.js`
|
|
@@ -37,7 +29,15 @@ export function middlewareScopeFromPath(filePath, appDir) {
|
|
|
37
29
|
return r === "" ? "/" : r;
|
|
38
30
|
}
|
|
39
31
|
|
|
40
|
-
|
|
32
|
+
/**
|
|
33
|
+
* Sort comparator for middleware scopes: outermost (fewest segments) first, so
|
|
34
|
+
* `app/_middleware` wraps `app/api/_middleware`; at equal depth a dynamic folder
|
|
35
|
+
* wraps a static one. Ties fall back to a lexical order, independent of discovery.
|
|
36
|
+
*/
|
|
37
|
+
export function outermostFirst(a, b) {
|
|
38
|
+
const depth = (s) => s.split("/").filter(Boolean).length;
|
|
39
|
+
return depth(a.scope) - depth(b.scope) || compareRoutes(b.scope, a.scope);
|
|
40
|
+
}
|
|
41
41
|
|
|
42
42
|
/**
|
|
43
43
|
* Build the middleware runner from a discovered `{ absFilePath: namespace }` map.
|
|
@@ -57,10 +57,12 @@ export function createMiddleware(middlewareModules = {}, { appDir, i18n } = {})
|
|
|
57
57
|
for (const file in middlewareModules) {
|
|
58
58
|
const mod = middlewareModules[file];
|
|
59
59
|
const fn = mod.default ?? mod.middleware;
|
|
60
|
-
if (typeof fn === "function")
|
|
60
|
+
if (typeof fn === "function") {
|
|
61
|
+
const scope = middlewareScopeFromPath(file, appDir);
|
|
62
|
+
entries.push({ scope, matcher: compileScope(scope), fn });
|
|
63
|
+
}
|
|
61
64
|
}
|
|
62
|
-
|
|
63
|
-
entries.sort((a, b) => a.scope.length - b.scope.length);
|
|
65
|
+
entries.sort(outermostFirst);
|
|
64
66
|
|
|
65
67
|
const i18nOn = !!(i18n && Array.isArray(i18n.locales) && i18n.locales.length);
|
|
66
68
|
const defaultLocale = i18nOn ? (i18n.defaultLocale ?? i18n.locales[0]) : null;
|
|
@@ -95,7 +97,7 @@ export function createMiddleware(middlewareModules = {}, { appDir, i18n } = {})
|
|
|
95
97
|
const url = new URL(request.url);
|
|
96
98
|
const context = { url, locals: {}, env, ctx };
|
|
97
99
|
const path = scopePath(url.pathname);
|
|
98
|
-
const chain = entries.filter((e) => e.
|
|
100
|
+
const chain = entries.filter((e) => e.matcher.test(path));
|
|
99
101
|
let next = (req) => terminal(req, context);
|
|
100
102
|
for (let i = chain.length - 1; i >= 0; i--) {
|
|
101
103
|
const { fn } = chain[i];
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// Server functions (docs/SERVER_FUNCTIONS.md): `query()` and `action()` exports of
|
|
2
|
+
// `*.server.{js,ts}` modules, callable from the browser through a generated stub and
|
|
3
|
+
// directly from other server code.
|
|
4
|
+
//
|
|
5
|
+
// export const listTodos = query(async (args, { locals }) => db.list(locals.user));
|
|
6
|
+
// export const addTodo = action(schema, async (input, context) => db.insert(input));
|
|
7
|
+
//
|
|
8
|
+
// The build gives each function an endpoint under its folder (`/todos/__fn/<id>`), so
|
|
9
|
+
// that folder's `_middleware` guards it like a page. `createServerFunctions` turns the
|
|
10
|
+
// build's `{ endpoint: fn }` map into a handler for those requests.
|
|
11
|
+
|
|
12
|
+
import { CONTENT_TYPE, MAX_DEPTH, SerializeError, decode, encode } from "../core/fn-codec.js";
|
|
13
|
+
import { isNotFound } from "./loader.js";
|
|
14
|
+
|
|
15
|
+
const MARK = Symbol.for("afw.serverFunction");
|
|
16
|
+
|
|
17
|
+
/** Thrown to the caller when the input does not match the function's schema. */
|
|
18
|
+
export class ValidationError extends Error {
|
|
19
|
+
constructor(issues) {
|
|
20
|
+
super("Invalid input");
|
|
21
|
+
this.name = "ValidationError";
|
|
22
|
+
this.issues = issues;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const isSchema = (value) => typeof value?.["~standard"]?.validate === "function";
|
|
27
|
+
|
|
28
|
+
/** Validate `input` with a Standard Schema (https://standardschema.dev) schema. */
|
|
29
|
+
async function validate(schema, input) {
|
|
30
|
+
if (!schema) return input;
|
|
31
|
+
const result = await schema["~standard"].validate(input);
|
|
32
|
+
if (result.issues) throw new ValidationError(result.issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) })));
|
|
33
|
+
return result.value;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function define(kind, args) {
|
|
37
|
+
const [schema, handler] = args.length >= 2 ? args : [undefined, args[0]];
|
|
38
|
+
if (schema !== undefined && !isSchema(schema)) {
|
|
39
|
+
throw new TypeError(`${kind}(schema, fn): the schema must implement Standard Schema (zod, valibot, arktype…)`);
|
|
40
|
+
}
|
|
41
|
+
if (typeof handler !== "function") throw new TypeError(`${kind}(): the last argument must be a function`);
|
|
42
|
+
// Called directly from server code (a loader, an API route, another function): run it
|
|
43
|
+
// with the given context, input validated the same way as over HTTP.
|
|
44
|
+
const fn = async (input, context = {}) => handler(await validate(schema, input), context);
|
|
45
|
+
Object.defineProperty(fn, MARK, { value: { kind, schema, handler } });
|
|
46
|
+
return fn;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A read: idempotent, callable with GET or POST. `query(fn)` or `query(schema, fn)`. */
|
|
50
|
+
export function query(...args) {
|
|
51
|
+
return define("query", args);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A write: POST only. `action(fn)` or `action(schema, fn)`. */
|
|
55
|
+
export function action(...args) {
|
|
56
|
+
return define("action", args);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The kind of a server function export (`"query"` | `"action"`), or null. */
|
|
60
|
+
export function serverFunctionKind(value) {
|
|
61
|
+
return (typeof value === "function" && value[MARK]?.kind) || null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const json = (status, body, headers = {}) =>
|
|
65
|
+
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers } });
|
|
66
|
+
|
|
67
|
+
// A cross-site request carrying the user's cookies must not reach an endpoint. Browsers
|
|
68
|
+
// send `Origin` on POST and `Sec-Fetch-Site` on every request; a client that sends
|
|
69
|
+
// neither is not a browser, so it cannot be forging a user's request.
|
|
70
|
+
function crossSite(request, url) {
|
|
71
|
+
const origin = request.headers.get("origin");
|
|
72
|
+
if (origin) return origin !== url.origin;
|
|
73
|
+
const site = request.headers.get("sec-fetch-site");
|
|
74
|
+
return site != null && site !== "same-origin" && site !== "none";
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The handler for server function requests.
|
|
79
|
+
*
|
|
80
|
+
* @param {Record<string, Function>} endpoints `{ "/todos/__fn/<id>": listTodos }`, built
|
|
81
|
+
* by the toolchain from the app's `*.server` modules.
|
|
82
|
+
* @param {{ maxBodyBytes?: number, maxDepth?: number }} [options] limits on the decoded
|
|
83
|
+
* input: body size (default 1 MiB) and nesting depth (default 64)
|
|
84
|
+
* @returns {{ size: number, handle: (request: Request, context?: object) => Promise<Response | null> }}
|
|
85
|
+
* `handle` answers a request for one of the endpoints, or returns null. `context` is
|
|
86
|
+
* what middleware built (`locals`, `env`, `ctx`).
|
|
87
|
+
*/
|
|
88
|
+
export function createServerFunctions(endpoints = {}, { maxBodyBytes = 1024 * 1024, maxDepth = MAX_DEPTH } = {}) {
|
|
89
|
+
const limits = { maxLength: maxBodyBytes, maxDepth };
|
|
90
|
+
const table = new Map();
|
|
91
|
+
for (const [path, fn] of Object.entries(endpoints)) {
|
|
92
|
+
const kind = serverFunctionKind(fn);
|
|
93
|
+
if (!kind) throw new TypeError(`${path}: not a query() or action()`);
|
|
94
|
+
table.set(path, { kind, fn });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function handle(request, context = {}) {
|
|
98
|
+
const url = new URL(request.url);
|
|
99
|
+
const entry = table.get(url.pathname);
|
|
100
|
+
if (!entry) return null;
|
|
101
|
+
const method = request.method.toUpperCase();
|
|
102
|
+
const allowed = entry.kind === "query" ? "GET, POST" : "POST";
|
|
103
|
+
if (!allowed.split(", ").includes(method)) return json(405, { error: { message: "Method not allowed" } }, { allow: allowed });
|
|
104
|
+
if (crossSite(request, url)) return json(403, { error: { message: "Cross-site request refused" } });
|
|
105
|
+
|
|
106
|
+
let input;
|
|
107
|
+
try {
|
|
108
|
+
if (method === "GET") {
|
|
109
|
+
input = decode(url.searchParams.get("a") ?? "", limits);
|
|
110
|
+
} else {
|
|
111
|
+
const type = request.headers.get("content-type") ?? "";
|
|
112
|
+
// Forms and plain-text posts can be sent cross-site without a preflight; JSON cannot.
|
|
113
|
+
if (!type.startsWith(CONTENT_TYPE)) return json(415, { error: { message: `Expected ${CONTENT_TYPE}` } });
|
|
114
|
+
input = decode(await request.text(), limits);
|
|
115
|
+
}
|
|
116
|
+
} catch (error) {
|
|
117
|
+
if (error instanceof SerializeError && error.code === "INPUT_TOO_LARGE") {
|
|
118
|
+
return json(413, { error: { message: "Request body too large" } });
|
|
119
|
+
}
|
|
120
|
+
return json(400, { error: { message: "Malformed request body" } });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const ctx = { request, url, locals: context.locals ?? {}, env: context.env, ctx: context.ctx };
|
|
124
|
+
try {
|
|
125
|
+
const result = await entry.fn(input, ctx);
|
|
126
|
+
// A result the codec refuses (a class instance, a function) is a server bug: 500.
|
|
127
|
+
return new Response(encode(result), { status: 200, headers: { "content-type": CONTENT_TYPE, "cache-control": "no-store" } });
|
|
128
|
+
} catch (error) {
|
|
129
|
+
if (error instanceof Response) return error; // a redirect or custom status from the function
|
|
130
|
+
if (error instanceof ValidationError) return json(400, { error: { message: error.message, issues: error.issues } });
|
|
131
|
+
if (isNotFound(error)) return json(404, { error: { message: "Not found" } });
|
|
132
|
+
console.error(`✗ server function ${url.pathname}:`, error?.stack ?? error);
|
|
133
|
+
return json(500, { error: { message: "Internal Server Error" } });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return { size: table.size, handle };
|
|
138
|
+
}
|