@thednp/rpc 0.3.5 → 0.3.7

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 (45) hide show
  1. package/AGENTS.md +39 -12
  2. package/CHANGELOG.md +165 -0
  3. package/README.md +2 -2
  4. package/dist/config/config.d.mts +0 -7
  5. package/dist/config/config.d.mts.map +1 -1
  6. package/dist/config/config.mjs +5 -1
  7. package/dist/config/config.mjs.map +1 -1
  8. package/dist/express/express.d.mts +62 -32
  9. package/dist/express/express.d.mts.map +1 -1
  10. package/dist/express/express.mjs +71 -23
  11. package/dist/express/express.mjs.map +1 -1
  12. package/dist/fastify/fastify.d.mts +81 -47
  13. package/dist/fastify/fastify.d.mts.map +1 -1
  14. package/dist/fastify/fastify.mjs +73 -23
  15. package/dist/fastify/fastify.mjs.map +1 -1
  16. package/dist/fastify/plugin/fastify/plugin.d.mts +30 -55
  17. package/dist/fastify/plugin/fastify/plugin.d.mts.map +1 -1
  18. package/dist/fastify/plugin/fastify/plugin.mjs +72 -22
  19. package/dist/fastify/plugin/fastify/plugin.mjs.map +1 -1
  20. package/dist/h3/h3.d.mts +73 -4
  21. package/dist/h3/h3.d.mts.map +1 -1
  22. package/dist/h3/h3.mjs +69 -22
  23. package/dist/h3/h3.mjs.map +1 -1
  24. package/dist/helpers/helpers.d.mts.map +1 -1
  25. package/dist/helpers/helpers.mjs +2 -0
  26. package/dist/helpers/helpers.mjs.map +1 -1
  27. package/dist/hono/hono.d.mts +71 -6
  28. package/dist/hono/hono.d.mts.map +1 -1
  29. package/dist/hono/hono.mjs +94 -24
  30. package/dist/hono/hono.mjs.map +1 -1
  31. package/dist/index.d.mts +43 -25
  32. package/dist/index.d.mts.map +1 -1
  33. package/dist/index.mjs +62 -28
  34. package/dist/index.mjs.map +1 -1
  35. package/dist/koa/koa.d.mts +73 -11
  36. package/dist/koa/koa.d.mts.map +1 -1
  37. package/dist/koa/koa.mjs +75 -23
  38. package/dist/koa/koa.mjs.map +1 -1
  39. package/dist/server/server.d.mts +159 -18
  40. package/dist/server/server.d.mts.map +1 -1
  41. package/dist/server/server.mjs +186 -15
  42. package/dist/server/server.mjs.map +1 -1
  43. package/llms.txt +5 -3
  44. package/package.json +5 -3
  45. package/CLAUDE.md +0 -1
@@ -1,10 +1,11 @@
1
- import { escapeRegExp, formatError, getGlobalPrefix, hasContentTypeMismatch, isOriginAllowed, provideRequestContext, scanForServerFiles } from "@thednp/rpc/server";
2
- const defaultRPCOptions = {
3
- rpcPrefix: "__rpc",
4
- adapter: "express",
5
- serverFiles: "exact",
6
- scanRoot: void 0
7
- };
1
+ import { clientErrorMessage, clientErrorStatus, escapeRegExp, formatError, hasContentTypeMismatch, isClientHttpError, isOriginRequestAllowed, provideRequestContext, resolveRPCPrefix, scanForServerFiles } from "@thednp/rpc/server";
2
+ //#region src/options.ts
3
+ /**
4
+ * Baseline middleware options. Note `rpcPrefix` is `undefined` rather than
5
+ * `defaultPrefix` on purpose: leaving it unset lets `resolveRPCPrefix` fall
6
+ * through to the global prefix, which is what makes a published global prefix
7
+ * reach the middleware.
8
+ */
8
9
  const defaultMiddlewareOptions = {
9
10
  rpcPrefix: void 0,
10
11
  path: void 0,
@@ -38,16 +39,40 @@ const getFunctionsForPrefix = (prefix) => {
38
39
  };
39
40
  //#endregion
40
41
  //#region src/constants.ts
42
+ /** Body of a 404. Deliberately does not name the requested function. */
41
43
  const FUNCTION_NOT_FOUND = "Function not found";
44
+ /** Body of a 405, returned when the HTTP method does not match the function's declared method. */
42
45
  const METHOD_NOT_ALLOWED = "Method Not Allowed";
46
+ /** Body of a 403, returned when the optional origin allowlist rejects the request. */
43
47
  const REQUEST_FORBIDDEN = "Forbidden";
48
+ /** Body of a 415, returned when the request's `Content-Type` does not satisfy the function's declared `contentType`. */
44
49
  const UNSUPPORTED_MEDIA_TYPE = "Unsupported Media Type";
50
+ /** Body of a 400, returned when a GET `?args=` value parses but is not an array. */
45
51
  const BAD_REQUEST = "Bad Request";
52
+ /** Abort reason used when the client disconnects mid-dispatch. */
46
53
  const CLIENT_DISCONNECTED = "client disconnected";
47
54
  /** Returns a warning when a middleware name is reused, preventing registration conflicts. @param name - The duplicate middleware name */
48
55
  const MIDDLEWARE_NAME_USED = (name) => `The middleware name "${name}" is already used.`;
49
56
  //#endregion
50
57
  //#region src/server-helpers.ts
58
+ /**
59
+ * Tags an error with an HTTP status for the dispatch to surface.
60
+ *
61
+ * Used where a malformed *request* is the fault — a body that does not parse
62
+ * under a declared JSON `Content-Type`, a GET `?args=` value that is not valid
63
+ * JSON. Every host framework rpc supports answers `400` for these (Express
64
+ * `entity.parse.failed`, Fastify `FST_ERR_CTP_INVALID_JSON_BODY`, koa-bodyparser,
65
+ * and h3's own `readBody`), and treating one as a server fault both misreports
66
+ * the fault and turns a trivial client mistake into a log entry.
67
+ * @param status - The HTTP status to answer with
68
+ * @param message - Internal diagnostic message; never sent to the client
69
+ * @returns An `Error` carrying `status`
70
+ */
71
+ const httpError = (status, message) => {
72
+ const err = new Error(message);
73
+ err.status = status;
74
+ return err;
75
+ };
51
76
  const SAFE_URL_BASE = "http://localhost";
52
77
  /**
53
78
  * Parses a raw request URL against a fixed base without ever throwing.
@@ -78,7 +103,7 @@ const safeURL = (rawUrl, base = SAFE_URL_BASE) => {
78
103
  */
79
104
  async function attachRPC(app) {
80
105
  const { loadRPCConfig } = await import("@thednp/rpc");
81
- const { adapter: _adapter, ...options } = await loadRPCConfig();
106
+ const options = await loadRPCConfig();
82
107
  app.use(createRPCMiddleware(options));
83
108
  }
84
109
  /**
@@ -96,6 +121,20 @@ function attachVite(app, vite) {
96
121
  * @param req - Express or Node.js IncomingMessage
97
122
  * @returns A promise resolving to the parsed body with its content type
98
123
  */
124
+ /**
125
+ * Parses a body leniently: JSON when it parses, otherwise the raw string.
126
+ * Used for bodies that did not declare JSON — notably a request with no
127
+ * `Content-Type` header, which must still arrive parsed if it carries JSON.
128
+ * @param body - The raw body text
129
+ * @returns The parsed JSON value, or the original string
130
+ */
131
+ const parseJsonOrRawText = (body) => {
132
+ try {
133
+ return JSON.parse(body);
134
+ } catch {
135
+ return body;
136
+ }
137
+ };
99
138
  const readBody = (req) => {
100
139
  return new Promise((resolve, reject) => {
101
140
  if (hasPreParsedBody(req) && req.body !== void 0) {
@@ -126,16 +165,13 @@ const readBody = (req) => {
126
165
  const isMultipart = incomingType.includes("multipart/form-data");
127
166
  const isUrlEncoded = incomingType.includes("urlencoded");
128
167
  try {
129
- const data = isMultipart ? { raw: body } : isUrlEncoded ? Object.fromEntries(new URLSearchParams(body)) : JSON.parse(body);
168
+ const data = isMultipart ? { raw: body } : isUrlEncoded ? Object.fromEntries(new URLSearchParams(body)) : isJSON ? JSON.parse(body) : parseJsonOrRawText(body);
130
169
  resolve({
131
170
  contentType: isMultipart ? "multipart/form-data" : isJSON ? "application/json" : isUrlEncoded ? "application/x-www-form-urlencoded" : "text/plain",
132
171
  data: isMultipart ? data : data
133
172
  });
134
173
  } catch (_e) {
135
- resolve({
136
- contentType: "text/plain",
137
- data: String(body)
138
- });
174
+ reject(httpError(400, "Invalid JSON body"));
139
175
  }
140
176
  };
141
177
  const onError = (err) => {
@@ -251,7 +287,7 @@ const middlewareStack = /* @__PURE__ */ new Set();
251
287
  const createMiddleware = (initialOptions = {}) => {
252
288
  const options = Object.assign({}, defaultMiddlewareOptions, initialOptions);
253
289
  const middlewareName = options.name;
254
- let rpcPrefix = options.rpcPrefix;
290
+ const rpcPrefix = options.rpcPrefix;
255
291
  const path = options.path;
256
292
  const handler = options.handler;
257
293
  let name = middlewareName;
@@ -261,16 +297,16 @@ const createMiddleware = (initialOptions = {}) => {
261
297
  }
262
298
  if (middlewareStack.has(name)) throw new Error(MIDDLEWARE_NAME_USED(name));
263
299
  middlewareStack.add(name);
264
- const prefixRegex = rpcPrefix ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`) : null;
300
+ const resolvedPrefix = resolveRPCPrefix(rpcPrefix);
301
+ const prefixRegex = rpcPrefix ? new RegExp(`^/${escapeRegExp(resolvedPrefix)}/`) : null;
265
302
  const pathMatcher = path ? typeof path === "string" ? new RegExp(path) : path : null;
266
303
  const middlewareHandler = async (req, res, next) => {
267
304
  const { url } = getRequestDetails(req);
268
305
  if (!handler) return next?.();
269
306
  if (pathMatcher && !pathMatcher.test(url)) return next?.();
270
307
  if (prefixRegex && !prefixRegex.test(url)) return next?.();
271
- rpcPrefix = rpcPrefix ?? "__rpc";
272
- if (getFunctionsForPrefix(rpcPrefix).size === 0) await scanForServerFiles({
273
- rpcPrefix,
308
+ if (getFunctionsForPrefix(resolvedPrefix).size === 0) await scanForServerFiles({
309
+ rpcPrefix: resolvedPrefix,
274
310
  serverFiles: options.serverFiles,
275
311
  scanRoot: options.scanRoot
276
312
  });
@@ -289,18 +325,19 @@ const createMiddleware = (initialOptions = {}) => {
289
325
  * @returns An Express middleware function
290
326
  */
291
327
  const createRPCMiddleware = (initialOptions = {}) => {
292
- const options = Object.assign({}, defaultMiddlewareOptions, { rpcPrefix: defaultRPCOptions.rpcPrefix }, initialOptions);
328
+ const options = Object.assign({}, defaultMiddlewareOptions, initialOptions);
293
329
  const rpcPrefix = options.rpcPrefix;
294
- const prefix = rpcPrefix || getGlobalPrefix() || "__rpc";
295
- const prefixRegex = rpcPrefix ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`) : null;
330
+ const prefix = resolveRPCPrefix(rpcPrefix);
331
+ const prefixRegex = new RegExp(`^/${escapeRegExp(prefix)}/`);
296
332
  const prefixReplace = `/${prefix}/`;
297
333
  return createMiddleware({
298
334
  ...options,
335
+ rpcPrefix: prefix,
299
336
  handler: async (req, res, _next) => {
300
337
  const { url: path, searchParams } = getRequestDetails(req);
301
338
  const { sendResponse } = getResponseDetails(res);
302
339
  if (prefixRegex && !prefixRegex.test(path)) return;
303
- if (!isOriginAllowed(options.origin, req.headers.origin)) {
340
+ if (!isOriginRequestAllowed(options.origin, req.headers.origin, req.headers["sec-fetch-site"])) {
304
341
  sendResponse(403, { error: REQUEST_FORBIDDEN });
305
342
  return;
306
343
  }
@@ -320,7 +357,13 @@ const createRPCMiddleware = (initialOptions = {}) => {
320
357
  if (method === "GET") {
321
358
  const raw = searchParams.get("args");
322
359
  if (raw) {
323
- const parsed = JSON.parse(raw);
360
+ let parsed;
361
+ try {
362
+ parsed = JSON.parse(raw);
363
+ } catch {
364
+ sendResponse(400, { error: BAD_REQUEST });
365
+ return;
366
+ }
324
367
  if (!Array.isArray(parsed)) {
325
368
  sendResponse(400, { error: BAD_REQUEST });
326
369
  return;
@@ -369,6 +412,11 @@ const createRPCMiddleware = (initialOptions = {}) => {
369
412
  req.off("close", onClose);
370
413
  if (!requestEvent.redirected && !requestEvent.sent && !res.headersSent) sendResponse(200, { data: result });
371
414
  } catch (err) {
415
+ if (isClientHttpError(err)) {
416
+ const status = clientErrorStatus(err);
417
+ sendResponse(status, { error: clientErrorMessage(status) });
418
+ return;
419
+ }
372
420
  console.error(String(err));
373
421
  const isProduction = process.env.NODE_ENV === "production";
374
422
  sendResponse(500, formatError(err, isProduction));
@@ -1 +1 @@
1
- {"version":3,"file":"express.mjs","names":[],"sources":["../../src/options.ts","../../src/functionsMap.ts","../../src/constants.ts","../../src/server-helpers.ts","../../src/express/helpers.ts","../../src/express/createMiddleware.ts"],"sourcesContent":["import type {\n MiddlewareOptions,\n RpcPluginOptions,\n ServerFunctionOptions,\n} from \"./types.d.ts\";\n\nexport const defaultServerFnOptions: ServerFunctionOptions = {\n contentType: \"application/json\",\n credentials: \"same-origin\",\n method: \"POST\",\n};\n\nexport const defaultPrefix = \"__rpc\";\n\nexport const defaultRPCOptions: RpcPluginOptions = {\n rpcPrefix: defaultPrefix,\n adapter: \"express\",\n serverFiles: \"exact\",\n scanRoot: undefined,\n};\n\nexport const defaultMiddlewareOptions: MiddlewareOptions = {\n rpcPrefix: undefined,\n path: undefined,\n origin: undefined,\n};\n","import type { ServerFnEntry } from \"./types.d.ts\";\nimport { defaultPrefix } from \"./options.ts\";\n\n/**\n * Global symbol under which the shared `serverFunctionsByPrefix` map is stored\n * on `globalThis`. Keeping it on a `Symbol.for` key makes it instance-stable\n * across the bundled entry copies (`index.mjs`, `server.mjs`, `express.mjs`,\n * ...) and dev-server hot reloads, exactly like the request-context storage in\n * `context.ts`. Without this, `scanForServerFiles` (bundled into the plugin)\n * would populate a map copy the adapter middleware could not read.\n */\nconst functionsMapSymbol = Symbol.for(\"thednp.rpc.functionsMap\");\n\n/**\n * Map of rpcPrefix -> Map of function names -> ServerFnEntry\n * Enables multiple RPC instances with different prefixes to coexist\n * without name collisions.\n */\nexport const serverFunctionsByPrefix: Map<\n string,\n Map<string, ServerFnEntry>\n> = ((globalThis as Record<symbol, Map<string, Map<string, ServerFnEntry>>>)[\n functionsMapSymbol\n] ??= new Map());\n\n/**\n * Gets or creates the function map for a specific prefix.\n * @param prefix - The RPC prefix (e.g., \"__rpc\", \"v1:rpc\", \"admin:rpc\")\n * @returns Map of function names to ServerFnEntry for that prefix\n */\nexport const getFunctionsForPrefix = (\n prefix: string,\n): Map<string, ServerFnEntry> => {\n if (!serverFunctionsByPrefix.has(prefix)) {\n serverFunctionsByPrefix.set(prefix, new Map());\n }\n return serverFunctionsByPrefix.get(prefix)!;\n};\n\n/**\n * Backward compatibility: default map for the default prefix.\n * Legacy code can still use serverFunctionsMap.set(name, entry).\n */\nexport const serverFunctionsMap: Map<string, ServerFnEntry> = {\n get: (key: string) => getFunctionsForPrefix(defaultPrefix).get(key),\n set: (key: string, value: ServerFnEntry) =>\n getFunctionsForPrefix(defaultPrefix).set(key, value),\n has: (key: string) => getFunctionsForPrefix(defaultPrefix).has(key),\n delete: (key: string) => getFunctionsForPrefix(defaultPrefix).delete(key),\n clear: () => getFunctionsForPrefix(defaultPrefix).clear(),\n get size() {\n return getFunctionsForPrefix(defaultPrefix).size;\n },\n entries: () => getFunctionsForPrefix(defaultPrefix).entries(),\n keys: () => getFunctionsForPrefix(defaultPrefix).keys(),\n values: () => getFunctionsForPrefix(defaultPrefix).values(),\n forEach: (\n callback: (\n value: ServerFnEntry,\n key: string,\n map: Map<string, ServerFnEntry>,\n ) => void,\n ) => getFunctionsForPrefix(defaultPrefix).forEach(callback),\n [Symbol.iterator]: () =>\n getFunctionsForPrefix(defaultPrefix)[Symbol.iterator](),\n} as unknown as Map<string, ServerFnEntry>;\n","export const OPERATION_ABORTED = \"Operation aborted\";\n\nexport const REQUEST_CANCELLED = \"Request was cancelled\";\n\nexport const FETCH_ERROR_PREFIX = \"Fetch error: \";\n\nexport const NO_SERVER_FUNCTION_FOUND = \"No server function found.\";\n\nexport const ERROR_LOADING_FILE = \"Error loading file:\";\n\nexport const FUNCTION_NOT_FOUND = \"Function not found\";\n\nexport const METHOD_NOT_ALLOWED = \"Method Not Allowed\";\n\nexport const REQUEST_FORBIDDEN = \"Forbidden\";\n\nexport const UNSUPPORTED_MEDIA_TYPE = \"Unsupported Media Type\";\n\nexport const BAD_REQUEST = \"Bad Request\";\n\nexport const INTERNAL_SERVER_ERROR = \"Internal Server Error\";\n\nexport const CLIENT_DISCONNECTED = \"client disconnected\";\n\n/** Returns a warning when a middleware name is reused, preventing registration conflicts. @param name - The duplicate middleware name */\nexport const MIDDLEWARE_NAME_USED = (name: string) =>\n `The middleware name \"${name}\" is already used.`;\n\n/** Error message when a value fails the safe-identifier validation. @param label - What kind of value was being validated. @param name - The rejected value */\nexport const INVALID_IDENTIFIER = (label: string, name: string) =>\n `Invalid ${label}: \"${name}\" must match /^[A-Za-z_$][A-Za-z0-9_$]*$/`;\n\n/** Error message when a value fails the safe-path-segment validation. @param label - What kind of value was being validated. @param segment - The rejected value */\nexport const INVALID_PATH_SEGMENT = (label: string, segment: string) =>\n `Invalid ${label}: \"${segment}\" must match /^[A-Za-z0-9_$@:][A-Za-z0-9_$@:/-]*$/`;\n\n/** Warning message when a specified RPC config file cannot be resolved on disk. @param configFile - The requested config filename. @param configFilePath - The resolved absolute path */\nexport const CONFIG_FILE_NOT_FOUND = (\n configFile: string,\n configFilePath: string,\n) =>\n ` ⚠︎ The specified RPC config file ${configFile} cannot be found at ${configFilePath}, loading the defaults..`;\n\nexport const NO_CONFIG_FOUND =\n ` ⚡︎ No RPC config found, loading the defaults..`;\n\nexport const FAILED_LOAD_CONFIG = ` ⚠︎ Failed to load RPC config:`;\n\n/** Error template for duplicate server function names across files. @param name - The duplicate registered name */\nexport const DUPLICATE_FUNCTION_NAME = (name: string) =>\n `Duplicate server function \"${name}\" detected. Each server function must have a unique name. Remove or rename the duplicate.`;\n","/** @module Server-side utilities. Exports the `RPCError` class for typed server-side errors, `formatError` for middleware error responses, `isFormContentType` and `hasContentTypeMismatch` for content-type validation, and `walkGlobFiles` for recursively discovering `*.server.*` files. Never import this module in client code — it is server-only. */\nimport type { ContentType, JsonObject, JsonValue } from \"./types.d.ts\";\nimport { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { INTERNAL_SERVER_ERROR } from \"./constants.ts\";\n\nconst GLOB_REGEX = /^.+\\.server\\.(ts|js|mjs|mts)$/;\n\n/**\n * Recursively walks `dir` and collects absolute paths to files whose\n * basename matches the `*.server.{ts,js,mjs,mts}` glob pattern.\n */\nexport const walkGlobFiles = async (dir: string): Promise<string[]> => {\n const results: string[] = [];\n const stack = [dir];\n while (stack.length) {\n const current = stack.pop()!;\n let entries;\n try {\n entries = await readdir(current, { withFileTypes: true });\n } catch (_e) {\n continue;\n }\n for (const entry of entries) {\n const fullPath = join(current, entry.name);\n if (entry.isFile() && GLOB_REGEX.test(entry.name)) {\n results.push(fullPath);\n } else if (entry.isDirectory()) {\n stack.push(fullPath);\n }\n }\n }\n return results;\n};\n\n/**\n * A typed error thrown from server functions.\n * The middleware serializes the `message` and `code` in the response,\n * allowing clients to recognise and handle specific error conditions.\n */\nexport class RPCError extends Error {\n /** Machine-readable error code (e.g. \"VALIDATION_FAILED\", \"UNAUTHORIZED\") */\n code: string;\n /** Optional diagnostic payload */\n data?: JsonValue;\n constructor(message: string, code = \"INTERNAL\", data?: JsonValue) {\n super(message);\n this.name = \"RPCError\";\n this.code = code;\n this.data = data;\n }\n}\n\n/**\n * Formats an error for the RPC middleware response.\n * In development the full `RPCError` payload is included so developers\n * can quickly identify issues. Unexpected exceptions never expose their\n * message — only the generic \"Internal Server Error\" is sent, preventing\n * information disclosure; server-side diagnostics are preserved via the\n * middleware's `console.error` logging.\n */\nexport const formatError = (\n err: unknown,\n isProduction: boolean,\n): JsonObject => {\n if (isProduction) {\n return { error: INTERNAL_SERVER_ERROR };\n }\n if (err instanceof RPCError) {\n const payload: JsonObject = {\n error: err.message || INTERNAL_SERVER_ERROR,\n code: err.code,\n };\n if (err.data !== undefined) payload.data = err.data;\n return payload;\n }\n return { error: INTERNAL_SERVER_ERROR };\n};\n\n/**\n * Checks whether a content type maps to a form encoding\n * (`multipart/form-data` or `application/x-www-form-urlencoded`).\n * Form-declared functions accept either encoding so native browser\n * submissions (urlencoded) keep working without JavaScript.\n */\nexport const isFormContentType = (contentType: string): boolean =>\n contentType === \"multipart/form-data\" ||\n contentType === \"application/x-www-form-urlencoded\";\n\n/**\n * Detects whether an incoming request's `Content-Type` header conflicts\n * with the function's declared content type. JSON and text functions are\n * enforced strictly (exact match wins), while form functions accept both\n * form encodings because the nojs fallback submits urlencoded forms to\n * multipart-declared endpoints. Requests without a `Content-Type` header\n * (curl, GET, legacy clients) are exempt from enforcement.\n * @param declared - The declared `contentType` from the server function options\n * @param rawHeader - The raw `Content-Type` request header, if present\n */\nexport const hasContentTypeMismatch = (\n declared: ContentType,\n rawHeader: string | undefined,\n): boolean => {\n // No Content-Type header → exempt (url bar, GET, curl compatibility)\n if (!rawHeader) return false;\n // Strip parameters (charset, boundary) before comparison\n const incomingType = rawHeader.trim().toLowerCase().split(\";\")[0].trim();\n if (isFormContentType(declared)) {\n // Forms: reject only non-form encodings (lenient between the two)\n return !isFormContentType(incomingType);\n }\n return incomingType !== declared;\n};\n\n/**\n * Escapes special regex metacharacters in a string.\n * Used to safely embed user-configurable values (like rpcPrefix) into regular expressions,\n * preventing ReDoS and regex injection attacks.\n * @param s - The raw string to escape\n * @returns The escaped string safe for use in new RegExp()\n */\nexport function escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Decides whether a request's `Origin` header is allowed by the configured\n * allowlist. Shared by all five adapters so the rule lives in exactly one place.\n *\n * - No `allowed` value (option unset) → everything passes: no validation.\n * - No `requestOrigin` header → passes, preserving curl/native-client access.\n * - Otherwise the header must match one of the entries exactly.\n *\n * A single string and a one-element array behave identically, so widening\n * `origin` to `string | string[]` is backward compatible.\n *\n * `Origin: null` (sandboxed iframes, `file://`, extension pages) is rejected\n * whenever an allowlist is set, because it never equals a real origin.\n * @param allowed - The configured `origin` option, if any\n * @param requestOrigin - The raw `Origin` request header, if present\n * @returns `true` when the request may proceed\n */\nexport const isOriginAllowed = (\n allowed: string | string[] | undefined,\n requestOrigin: string | undefined,\n): boolean => {\n if (!allowed || !requestOrigin) return true;\n return Array.isArray(allowed)\n ? allowed.includes(requestOrigin)\n : requestOrigin === allowed;\n};\n\nconst SAFE_URL_BASE = \"http://localhost\";\n\n/**\n * Parses a raw request URL against a fixed base without ever throwing.\n * Malformed request-targets (e.g. `/\\`, `//`, `/\\/`) make the WHATWG URL\n * parser throw `TypeError: Invalid URL`; the adapters call this while\n * building the per-request URL **before** their dispatch `try` block, so an\n * unhandled rejection there crashes raw `node:http` hosts (and Express 4).\n * On failure we fall back to the base root: the resulting pathname never\n * matches the RPC prefix, so the request is treated as non-RPC and falls\n * through to `next()` / 404 instead of crashing the process.\n * @param rawUrl - Raw request URL (path + optional query string)\n * @param base - Optional base URL, defaults to a fixed localhost origin\n * @returns A URL object; never throws\n */\nexport const safeURL = (rawUrl: string, base = SAFE_URL_BASE): URL => {\n try {\n return new URL(rawUrl, base);\n } catch {\n return new URL(\"/\", base);\n }\n};\n\nconst globalPrefixSymbol = Symbol.for(\"thednp.rpc.globalPrefix\");\n\n/** Global rpcPrefix from the last loaded config / middleware — fallback for functions without explicit prefix. */\nexport const getGlobalPrefix = (): string | undefined =>\n (globalThis as unknown as Record<symbol, string | undefined>)[\n globalPrefixSymbol\n ];\n\nexport const setGlobalPrefix = (prefix: string | undefined): void => {\n if (prefix) {\n (globalThis as unknown as Record<symbol, string | undefined>)[\n globalPrefixSymbol\n ] = prefix;\n } else {\n delete (globalThis as unknown as Record<symbol, string | undefined>)[\n globalPrefixSymbol\n ];\n }\n};\n","// src/express/helpers.ts\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n} from \"express\";\nimport type { BodyResult, JsonValue } from \"@thednp/rpc\";\nimport type { Buffer } from \"node:buffer\";\nimport type { ViteDevServer } from \"vite\";\nimport type { Express } from \"express\";\nimport { createRPCMiddleware } from \"./createMiddleware.ts\";\nimport type { RequestDetails, ResponseDetails } from \"./types.d.ts\";\nimport { safeURL } from \"../server-helpers.ts\";\n\n/**\n * Convenience function to load RPC config and attach the RPC middleware to an Express app.\n * Dynamically imports loadRPCConfig and creates the middleware with loaded options.\n * @param app - Express application instance\n */\nexport async function attachRPC(app: Express) {\n // The main plugin entry statically imports Vite, so loadRPCConfig is\n // imported lazily: function bundles that never call attachRPC (e.g.\n // serverless functions) keep Vite out of the bundle (or externalized).\n const { loadRPCConfig } = await import(\"@thednp/rpc\");\n const { adapter: _adapter, ...options } = await loadRPCConfig();\n app.use(createRPCMiddleware(options));\n}\n\n/**\n * Attaches Vite's dev server middlewares to an Express app for development mode.\n * @param app - Express application instance\n * @param vite - Running Vite dev server\n */\nexport function attachVite(app: Express, vite: ViteDevServer) {\n app.use(vite.middlewares);\n}\n\n/**\n * Reads and parses the HTTP request body from an Express or Node IncomingMessage.\n * If a body parser middleware (e.g. express.json()) already consumed the stream,\n * uses the pre-parsed body from `req.body`.\n * @param req - Express or Node.js IncomingMessage\n * @returns A promise resolving to the parsed body with its content type\n */\nexport const readBody = (\n req: ExpressRequest | IncomingMessage,\n): Promise<BodyResult> => {\n return new Promise((resolve, reject) => {\n // If an Express body parser already consumed the stream\n // via app.use(express.json()), use req.body directly\n if (hasPreParsedBody(req) && req.body !== undefined) {\n // istanbul ignore next\n const contentType = req.headers[\"content-type\"]?.toLowerCase() || \"\";\n const isJSON = contentType.includes(\"json\");\n const isMultipart = contentType.includes(\"multipart/form-data\");\n const isUrlEncoded = contentType.includes(\"urlencoded\");\n resolve({\n contentType: isMultipart\n ? \"multipart/form-data\"\n : isJSON\n ? \"application/json\"\n : isUrlEncoded\n ? \"application/x-www-form-urlencoded\"\n : \"text/plain\",\n data: isMultipart\n ? (req.body as Record<string, unknown>)\n : isJSON\n ? req.body\n : isUrlEncoded\n ? (req.body as Record<string, unknown>)\n : String(req.body),\n } as BodyResult);\n return;\n }\n\n // Else we parse the body right away\n let body = \"\";\n\n const toggleListeners = (add?: boolean) => {\n const method = add ? \"on\" : \"off\";\n req[method](\"data\", onData);\n req[method](\"end\", onEnd);\n req[method](\"error\", onError);\n };\n\n const onData = (chunk: Buffer) => {\n body += chunk.toString();\n };\n\n const onEnd = () => {\n toggleListeners();\n const incomingType = req.headers[\"content-type\"]?.toLowerCase() || \"\";\n const isJSON = incomingType.includes(\"json\");\n const isMultipart = incomingType.includes(\"multipart/form-data\");\n const isUrlEncoded = incomingType.includes(\"urlencoded\");\n try {\n const data = isMultipart\n ? { raw: body }\n : isUrlEncoded\n ? Object.fromEntries(new URLSearchParams(body))\n : JSON.parse(body);\n resolve({\n contentType: isMultipart\n ? \"multipart/form-data\"\n : isJSON\n ? \"application/json\"\n : isUrlEncoded\n ? \"application/x-www-form-urlencoded\"\n : \"text/plain\",\n data: isMultipart ? (data as Record<string, unknown>) : data,\n } as BodyResult);\n } catch (_e) {\n resolve({ contentType: \"text/plain\", data: String(body) });\n }\n };\n\n const onError = (err: Error) => {\n toggleListeners();\n\n reject(err);\n };\n\n toggleListeners(true);\n });\n};\n\n/**\n * Type guard that checks whether a request is an Express Request (has `originalUrl`).\n * @param req - A Node IncomingMessage or Express Request\n * @returns True if the request is an Express Request\n */\nexport const isExpressRequest = (\n req: IncomingMessage | ExpressRequest,\n): req is ExpressRequest => {\n return \"originalUrl\" in req;\n};\n\n/**\n * Type guard that checks whether a response is an Express Response (has `json` and `send` methods).\n * @param res - A Node ServerResponse or Express Response\n * @returns True if the response is an Express Response\n */\nexport const isExpressResponse = (\n res: ServerResponse | ExpressResponse,\n): res is ExpressResponse => {\n return \"json\" in res && \"send\" in res;\n};\n\n/**\n * Issues an HTTP redirect on an Express or raw Node ServerResponse.\n * Uses Express's native `res.redirect(status, location)` when an Express\n * Response is provided, otherwise writes the status code and `Location`\n * header directly on the raw `ServerResponse` (safe for Connect-compatible\n * middlewares and serverless adapters whose mock responses lack `.redirect`).\n * Defaults to `303 See Other` for convention (Post/Redirect/Get).\n * @param res - Express Response or raw Node ServerResponse\n * @param location - The URL to redirect to\n * @param status - HTTP status code, defaults to 303\n */\nexport const redirect = (\n res: ServerResponse | ExpressResponse,\n location: string,\n status = 303,\n): void => {\n if (isExpressResponse(res)) {\n res.redirect(status, location);\n return;\n }\n res.statusCode = status;\n res.setHeader(\"Location\", location);\n res.end();\n};\n\n/**\n * Type guard that checks whether a request has a pre-parsed body (`body` property).\n * Used to detect if a body-parser middleware already consumed the stream.\n * @param req - A Node IncomingMessage or Express Request\n * @returns True if the request has a body property\n */\nexport const hasPreParsedBody = (\n req: IncomingMessage | ExpressRequest,\n): req is ExpressRequest => {\n return \"body\" in req;\n};\n\n/**\n * Extracts normalized request details from an Express or Node IncomingMessage.\n * Parses the URL to extract pathname, search string, and search params.\n * @param request - Express or Node.js request object\n * @returns Normalized request details including URL, headers, and method\n */\nexport const getRequestDetails = (\n request: ExpressRequest | IncomingMessage,\n): RequestDetails => {\n const rawUrl = (\n isExpressRequest(request) ? request.originalUrl : request.url\n ) as string;\n const url = safeURL(rawUrl);\n\n return {\n url: url.pathname,\n search: url.search,\n searchParams: url.searchParams,\n headers: request.headers,\n method: request.method,\n };\n};\n\n/**\n * Wraps an Express or Node ServerResponse with a uniform API for setting headers,\n * status codes, and sending JSON responses. Handles the Express vs raw Node API differences.\n * @param response - Express or Node.js server response object\n * @returns A ResponseDetails object with setHeader, setStatusCode, and sendResponse helpers\n */\nexport const getResponseDetails = (\n response: ExpressResponse | ServerResponse,\n): ResponseDetails => {\n const isResponseSent = response.headersSent || response.writableEnded;\n\n const setHeader = (name: string, value: string) => {\n if (isExpressResponse(response)) {\n response.header(name, value);\n } else {\n response.setHeader(name, value);\n }\n };\n\n const setStatusCode = (code: number) => {\n if (isExpressResponse(response)) {\n response.status(code);\n } else {\n response.statusCode = code;\n }\n };\n\n const sendResponse = (code: number, output: JsonValue) => {\n setStatusCode(code);\n setHeader(\"Content-Type\", \"application/json\");\n\n if (isExpressResponse(response)) {\n response.send(JSON.stringify(output));\n } else {\n response.end(JSON.stringify(output));\n }\n };\n\n return {\n isResponseSent,\n setHeader,\n statusCode: response.statusCode,\n setStatusCode,\n sendResponse,\n };\n};\n","// src/express/createMidleware.ts\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type {\n NextFunction,\n Request as ExpressRequest,\n Response as ExpressResponse,\n} from \"express\";\nimport type {\n ExpressMiddlewareFn,\n ExpressMiddlewareOptions,\n} from \"./types.d.ts\";\nimport type { Connect } from \"vite\";\nimport type { JsonValue } from \"../types.d.ts\";\nimport type { RequestEvent } from \"@thednp/rpc/server\";\nimport {\n escapeRegExp,\n formatError,\n getGlobalPrefix,\n hasContentTypeMismatch,\n isOriginAllowed,\n provideRequestContext,\n scanForServerFiles,\n} from \"@thednp/rpc/server\";\nimport { getFunctionsForPrefix } from \"../functionsMap.ts\";\nimport {\n defaultMiddlewareOptions,\n defaultPrefix,\n defaultRPCOptions,\n} from \"../options.ts\";\nimport {\n getRequestDetails,\n getResponseDetails,\n readBody,\n redirect as expressRedirect,\n} from \"./helpers.ts\";\nimport {\n BAD_REQUEST,\n CLIENT_DISCONNECTED,\n FUNCTION_NOT_FOUND,\n METHOD_NOT_ALLOWED,\n MIDDLEWARE_NAME_USED,\n REQUEST_FORBIDDEN,\n UNSUPPORTED_MEDIA_TYPE,\n} from \"../constants.ts\";\n\nlet middlewareCount = 0;\nconst middlewareStack = new Set<string>();\n\n/**\n * Creates an Express middleware with optional path and rpcPrefix filtering.\n * Middleware names are deduplicated — reusing a name throws an error.\n * Prefix and path regexes are compiled once at creation time (hoisted) for performance.\n * @param initialOptions - Options for rpcPrefix, path matching, and the handler function\n * @returns An Express middleware function\n */\nexport const createMiddleware: ExpressMiddlewareFn = (initialOptions = {}) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n initialOptions,\n ) as ExpressMiddlewareOptions;\n const middlewareName = options.name;\n let rpcPrefix = options.rpcPrefix;\n const path = options.path;\n const handler = options.handler;\n\n let name = middlewareName;\n if (!name) {\n name = \"viteRPCMiddleware-\" + middlewareCount;\n middlewareCount += 1;\n }\n if (middlewareStack.has(name)) {\n throw new Error(MIDDLEWARE_NAME_USED(name));\n }\n middlewareStack.add(name);\n\n // Hoist regex compilation out of per-request path. Escape the prefix to\n // prevent regex injection via metacharacters in the config string.\n const prefixRegex: RegExp | null = rpcPrefix\n ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`)\n : null;\n const pathMatcher: RegExp | null = path\n ? (typeof path === \"string\" ? new RegExp(path) : path)\n : null;\n\n const middlewareHandler = async (\n req: IncomingMessage | ExpressRequest,\n res: ServerResponse | ExpressResponse,\n next: Connect.NextFunction | NextFunction,\n ) => {\n const { url } = getRequestDetails(req);\n\n // No need to continue when no handler provided\n if (!handler) {\n return next?.();\n }\n\n // Path matching\n if (pathMatcher && !pathMatcher.test(url)) return next?.();\n\n // rpcPrefix matching (boundary-safe via escaped regex)\n if (prefixRegex && !prefixRegex.test(url)) {\n return next?.();\n }\n\n rpcPrefix = (rpcPrefix ?? defaultPrefix) as string;\n\n // When serving from production server, scan for server files\n if (getFunctionsForPrefix(rpcPrefix).size === 0) {\n await scanForServerFiles({\n rpcPrefix,\n serverFiles: options.serverFiles,\n scanRoot: options.scanRoot,\n } as never);\n }\n\n // Execute handler\n await handler(req, res, next);\n };\n\n Object.defineProperty(middlewareHandler, \"name\", {\n value: name,\n });\n\n return middlewareHandler;\n};\n\n/**\n * Creates the Express RPC middleware that routes incoming requests to registered server functions.\n * Reads the request body, dispatches to the matching function via getFunctionsForPrefix,\n * and sends the JSON-serialized result. Handles client disconnection via abort signals.\n * Supports multi-prefix setups where different middleware instances can route to functions\n * registered under different prefixes.\n * @param initialOptions - Options including rpcPrefix for URL routing and prefix-scoped function lookup\n * @returns An Express middleware function\n */\nexport const createRPCMiddleware: ExpressMiddlewareFn = (\n initialOptions = {},\n) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n { rpcPrefix: defaultRPCOptions.rpcPrefix },\n initialOptions,\n ) as ExpressMiddlewareOptions;\n\n // Hoist prefix regex (escaped) and the literal prefix-for-replace out of the\n // per-request handler to avoid regex injection and per-request compilation.\n const rpcPrefix = options.rpcPrefix;\n const prefix = rpcPrefix || getGlobalPrefix() || defaultPrefix;\n\n const prefixRegex = rpcPrefix\n ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`)\n : /* istanbul ignore next */ null;\n const prefixReplace = `/${prefix}/`;\n\n return createMiddleware({\n ...options,\n handler: async (\n req: IncomingMessage | ExpressRequest,\n res: ServerResponse | ExpressResponse,\n _next: NextFunction | Connect.NextFunction,\n ) => {\n const { url: path, searchParams } = getRequestDetails(req);\n const { sendResponse } = getResponseDetails(res);\n\n // Validate the url starts with the prefix via the escaped regex\n // istanbul ignore next\n if (prefixRegex && !prefixRegex.test(path)) {\n // falls through to next handler (never reached in practice; the outer\n // createMiddleware already gates on this, but kept for defense-in-depth)\n return;\n }\n\n // Optional origin check: reject requests whose Origin header is not in\n // the configured allowlist. Requests without an Origin header\n // (curl, native clients) pass through unchecked.\n if (!isOriginAllowed(options.origin, req.headers.origin)) {\n sendResponse(403, { error: REQUEST_FORBIDDEN });\n return;\n }\n\n const functionName = path.replace(prefixReplace, \"\");\n // Look up function in the prefix-scoped map\n const serverFunctionsForPrefix = getFunctionsForPrefix(prefix);\n const serverFunction = serverFunctionsForPrefix.get(functionName);\n\n if (!serverFunction) {\n sendResponse(404, { error: FUNCTION_NOT_FOUND });\n return;\n }\n\n try {\n const method = serverFunction.options?.method || \"POST\";\n if (req.method?.toUpperCase() !== method) {\n sendResponse(405, { error: METHOD_NOT_ALLOWED });\n return;\n }\n\n let args: JsonValue[] = [];\n if (method === \"GET\") {\n const raw = searchParams.get(\"args\");\n if (raw) {\n const parsed: unknown = JSON.parse(raw);\n if (!Array.isArray(parsed)) {\n sendResponse(400, { error: BAD_REQUEST });\n return;\n }\n args = parsed as JsonValue[];\n }\n } else {\n // Content-type enforcement: strict for json/text, lenient between forms.\n // Requests without a Content-Type header are exempt (curl/GET compat).\n // Checked BEFORE readBody so mismatched bodies are never buffered.\n if (\n hasContentTypeMismatch(\n serverFunction.options?.contentType ?? \"application/json\",\n req.headers[\"content-type\"],\n )\n ) {\n sendResponse(415, { error: UNSUPPORTED_MEDIA_TYPE });\n return;\n }\n const body = await readBody(req);\n args = Array.isArray(body.data)\n ? (body.data as JsonValue[])\n : [body.data as JsonValue];\n }\n // ─── Dispatch ────────────────────────────────────────────────────\n // Establish the per-request context around the *entire* dispatch so\n // server functions (and async continuations spawned by their work)\n // read `getRequestContext()` and can call the framework-level\n // `redirect(location)`. The adapter-specific redirect is bound into the\n // context here; `serverFunction.handler` must be invoked inside the\n // context callback so its async increments run with the context live.\n const requestEvent: RequestEvent = {\n request: req,\n response: res,\n nativeEvent: { req, res },\n locals: (res as ExpressResponse).locals ?? {},\n functionName,\n redirect: (location, status = 303) => {\n requestEvent.redirected = { location, status };\n expressRedirect(res, location, status);\n },\n send: (status, body, headers) => {\n requestEvent.sent = { status, body, headers };\n const details = getResponseDetails(res);\n if (headers) {\n for (const [name, value] of Object.entries(headers)) {\n details.setHeader(name, value);\n }\n }\n details.sendResponse(status, body);\n },\n };\n\n const { data, cancel } = provideRequestContext(\n requestEvent,\n () => serverFunction.handler(...args),\n );\n const onClose = () => cancel(CLIENT_DISCONNECTED);\n req.on(\"close\", onClose);\n const result = await data;\n req.off(\"close\", onClose);\n\n // Skip the JSON send when the server function issued a redirect or\n // short-circuited with `send`; the bound adapter already wrote the\n // response. Express may also have ended the response via headersSent.\n // istanbul ignore else\n if (\n !requestEvent.redirected &&\n !requestEvent.sent &&\n !res.headersSent\n ) {\n sendResponse(200, { data: result });\n }\n } catch (err) {\n console.error(String(err));\n const isProduction = process.env.NODE_ENV === \"production\";\n sendResponse(500, formatError(err, isProduction));\n }\n },\n });\n};\n"],"mappings":";AAcA,MAAa,oBAAsC;CACjD,WAAW;CACX,SAAS;CACT,aAAa;CACb,UAAU,KAAA;AACZ;AAEA,MAAa,2BAA8C;CACzD,WAAW,KAAA;CACX,MAAM,KAAA;CACN,QAAQ,KAAA;AACV;;;;;;;;;;;ACdA,MAAM,qBAAqB,OAAO,IAAI,yBAAyB;;;;;;AAO/D,MAAa,0BAGR,WACH,wCACI,IAAI,IAAI;;;;;;AAOd,MAAa,yBACX,WAC+B;CAC/B,IAAI,CAAC,wBAAwB,IAAI,MAAM,GACrC,wBAAwB,IAAI,wBAAQ,IAAI,IAAI,CAAC;CAE/C,OAAO,wBAAwB,IAAI,MAAM;AAC3C;;;AC3BA,MAAa,qBAAqB;AAElC,MAAa,qBAAqB;AAElC,MAAa,oBAAoB;AAEjC,MAAa,yBAAyB;AAEtC,MAAa,cAAc;AAI3B,MAAa,sBAAsB;;AAGnC,MAAa,wBAAwB,SACnC,wBAAwB,KAAK;;;AC+H/B,MAAM,gBAAgB;;;;;;;;;;;;;;AAetB,MAAa,WAAW,QAAgB,OAAO,kBAAuB;CACpE,IAAI;EACF,OAAO,IAAI,IAAI,QAAQ,IAAI;CAC7B,QAAQ;EACN,OAAO,IAAI,IAAI,KAAK,IAAI;CAC1B;AACF;;;;;;;;AC3JA,eAAsB,UA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a,KAAK,YAAY,KAAK,YAAY,CAAC;GAClD;EACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"express.mjs","names":[],"sources":["../../src/options.ts","../../src/functionsMap.ts","../../src/constants.ts","../../src/server-helpers.ts","../../src/express/helpers.ts","../../src/express/createMiddleware.ts"],"sourcesContent":["import type {\n MiddlewareOptions,\n RpcPluginOptions,\n ServerFunctionOptions,\n} from \"./types.d.ts\";\n\n/**\n * Defaults applied to a server function that declares no `method`,\n * `credentials`, or `contentType` of its own.\n */\nexport const defaultServerFnOptions: ServerFunctionOptions = {\n contentType: \"application/json\",\n credentials: \"same-origin\",\n method: \"POST\",\n};\n\n/**\n * The built-in RPC endpoint prefix, used when neither an explicit prefix nor a\n * global one (`getGlobalPrefix`) is supplied. Kept for backward compatibility\n * with pre-multi-prefix setups, where every function lived under this one map.\n */\nexport const defaultPrefix = \"__rpc\";\n\n/**\n * Baseline plugin options. `defineConfig` merges a user's partial config over\n * these, and `loadRPCConfig` merges a loaded config file over them, so every\n * option has a defined value even when a config file omits it.\n */\nexport const defaultRPCOptions: RpcPluginOptions = {\n rpcPrefix: defaultPrefix,\n serverFiles: \"exact\",\n scanRoot: undefined,\n};\n\n/**\n * Baseline middleware options. Note `rpcPrefix` is `undefined` rather than\n * `defaultPrefix` on purpose: leaving it unset lets `resolveRPCPrefix` fall\n * through to the global prefix, which is what makes a published global prefix\n * reach the middleware.\n */\nexport const defaultMiddlewareOptions: MiddlewareOptions = {\n rpcPrefix: undefined,\n path: undefined,\n origin: undefined,\n};\n","import type { ServerFnEntry } from \"./types.d.ts\";\nimport { defaultPrefix } from \"./options.ts\";\n\n/**\n * Global symbol under which the shared `serverFunctionsByPrefix` map is stored\n * on `globalThis`. Keeping it on a `Symbol.for` key makes it instance-stable\n * across the bundled entry copies (`index.mjs`, `server.mjs`, `express.mjs`,\n * ...) and dev-server hot reloads, exactly like the request-context storage in\n * `context.ts`. Without this, `scanForServerFiles` (bundled into the plugin)\n * would populate a map copy the adapter middleware could not read.\n */\nconst functionsMapSymbol = Symbol.for(\"thednp.rpc.functionsMap\");\n\n/**\n * Map of rpcPrefix -> Map of function names -> ServerFnEntry\n * Enables multiple RPC instances with different prefixes to coexist\n * without name collisions.\n */\nexport const serverFunctionsByPrefix: Map<\n string,\n Map<string, ServerFnEntry>\n> = ((globalThis as Record<symbol, Map<string, Map<string, ServerFnEntry>>>)[\n functionsMapSymbol\n] ??= new Map());\n\n/**\n * Gets or creates the function map for a specific prefix.\n * @param prefix - The RPC prefix (e.g., \"__rpc\", \"v1:rpc\", \"admin:rpc\")\n * @returns Map of function names to ServerFnEntry for that prefix\n */\nexport const getFunctionsForPrefix = (\n prefix: string,\n): Map<string, ServerFnEntry> => {\n if (!serverFunctionsByPrefix.has(prefix)) {\n serverFunctionsByPrefix.set(prefix, new Map());\n }\n return serverFunctionsByPrefix.get(prefix)!;\n};\n\n/**\n * Backward compatibility: default map for the default prefix.\n * Legacy code can still use serverFunctionsMap.set(name, entry).\n */\nexport const serverFunctionsMap: Map<string, ServerFnEntry> = {\n get: (key: string) => getFunctionsForPrefix(defaultPrefix).get(key),\n set: (key: string, value: ServerFnEntry) =>\n getFunctionsForPrefix(defaultPrefix).set(key, value),\n has: (key: string) => getFunctionsForPrefix(defaultPrefix).has(key),\n delete: (key: string) => getFunctionsForPrefix(defaultPrefix).delete(key),\n clear: () => getFunctionsForPrefix(defaultPrefix).clear(),\n get size() {\n return getFunctionsForPrefix(defaultPrefix).size;\n },\n entries: () => getFunctionsForPrefix(defaultPrefix).entries(),\n keys: () => getFunctionsForPrefix(defaultPrefix).keys(),\n values: () => getFunctionsForPrefix(defaultPrefix).values(),\n forEach: (\n callback: (\n value: ServerFnEntry,\n key: string,\n map: Map<string, ServerFnEntry>,\n ) => void,\n ) => getFunctionsForPrefix(defaultPrefix).forEach(callback),\n [Symbol.iterator]: () =>\n getFunctionsForPrefix(defaultPrefix)[Symbol.iterator](),\n} as unknown as Map<string, ServerFnEntry>;\n","/**\n * @module User-facing message strings.\n *\n * Two shapes live here: plain message constants (the exact text an RPC\n * response body carries) and message *factories* for the cases that need a\n * value interpolated. Both are part of the wire contract for the bodies below,\n * so the casing is deliberate — e.g. a client matching on\n * `METHOD_NOT_ALLOWED` must see `\"Method Not Allowed\"`, not `\"Method not\n * allowed\"`. These strings are also what keeps error responses generic: they\n * never include the requested function name, so a response cannot be used to\n * enumerate what exists.\n */\n/** Thrown-name for an operation stopped by its own `cancel()`. */\nexport const OPERATION_ABORTED = \"Operation aborted\";\n\n/** Warning text used when a request is cancelled by an HTTP 408/499 response. */\nexport const REQUEST_CANCELLED = \"Request was cancelled\";\n\n/** Prefix of the `Error` message the client helpers throw for a non-OK HTTP response. The status text is appended; the response body is deliberately not read, so server-side detail never reaches the client through this path. */\nexport const FETCH_ERROR_PREFIX = \"Fetch error: \";\n\n/** Warning logged when a scanned server module exports nothing. */\nexport const NO_SERVER_FUNCTION_FOUND = \"No server function found.\";\n\n/** Error logged when a server function file cannot be loaded by Vite's SSR loader. */\nexport const ERROR_LOADING_FILE = \"Error loading file:\";\n\n/** Body of a 404. Deliberately does not name the requested function. */\nexport const FUNCTION_NOT_FOUND = \"Function not found\";\n\n/** Body of a 405, returned when the HTTP method does not match the function's declared method. */\nexport const METHOD_NOT_ALLOWED = \"Method Not Allowed\";\n\n/** Body of a 403, returned when the optional origin allowlist rejects the request. */\nexport const REQUEST_FORBIDDEN = \"Forbidden\";\n\n/** Body of a 415, returned when the request's `Content-Type` does not satisfy the function's declared `contentType`. */\nexport const UNSUPPORTED_MEDIA_TYPE = \"Unsupported Media Type\";\n\n/** Body of a 413, returned when the request body exceeds the host's configured size limit. */\nexport const PAYLOAD_TOO_LARGE = \"Payload Too Large\";\n\n/** Body of a 400, returned when a GET `?args=` value parses but is not an array. */\nexport const BAD_REQUEST = \"Bad Request\";\n\n/** Body of a 500. Always generic — never the underlying error, so internals cannot leak. */\nexport const INTERNAL_SERVER_ERROR = \"Internal Server Error\";\n\n/** Abort reason used when the client disconnects mid-dispatch. */\nexport const CLIENT_DISCONNECTED = \"client disconnected\";\n\n/** Returns a warning when a middleware name is reused, preventing registration conflicts. @param name - The duplicate middleware name */\nexport const MIDDLEWARE_NAME_USED = (name: string) =>\n `The middleware name \"${name}\" is already used.`;\n\n/** Error message when a value fails the safe-identifier validation. @param label - What kind of value was being validated. @param name - The rejected value */\nexport const INVALID_IDENTIFIER = (label: string, name: string) =>\n `Invalid ${label}: \"${name}\" must match /^[A-Za-z_$][A-Za-z0-9_$]*$/`;\n\n/** Error message when a value fails the safe-path-segment validation. @param label - What kind of value was being validated. @param segment - The rejected value */\nexport const INVALID_PATH_SEGMENT = (label: string, segment: string) =>\n `Invalid ${label}: \"${segment}\" must match /^[A-Za-z0-9_$@:][A-Za-z0-9_$@:/-]*$/`;\n\n/** Warning message when a specified RPC config file cannot be resolved on disk. @param configFile - The requested config filename. @param configFilePath - The resolved absolute path */\nexport const CONFIG_FILE_NOT_FOUND = (\n configFile: string,\n configFilePath: string,\n) =>\n ` ⚠︎ The specified RPC config file ${configFile} cannot be found at ${configFilePath}, loading the defaults..`;\n\n/** Warning logged when no config file is discovered and the defaults are used. */\nexport const NO_CONFIG_FOUND =\n ` ⚡︎ No RPC config found, loading the defaults..`;\n\n/** Warning logged when a config file exists but could not be loaded; the defaults are used. */\nexport const FAILED_LOAD_CONFIG = ` ⚠︎ Failed to load RPC config:`;\n\n/** Error template for duplicate server function names across files. @param name - The duplicate registered name */\nexport const DUPLICATE_FUNCTION_NAME = (name: string) =>\n `Duplicate server function \"${name}\" detected. Each server function must have a unique name. Remove or rename the duplicate.`;\n","/** @module Server-side utilities. Exports the `RPCError` class for typed server-side errors, `formatError` for middleware error responses, `isFormContentType` and `hasContentTypeMismatch` for content-type validation, and `walkGlobFiles` for recursively discovering `*.server.*` files. Never import this module in client code — it is server-only. */\nimport type { ContentType, JsonObject, JsonValue } from \"./types.d.ts\";\nimport { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport {\n BAD_REQUEST,\n INTERNAL_SERVER_ERROR,\n PAYLOAD_TOO_LARGE,\n UNSUPPORTED_MEDIA_TYPE,\n} from \"./constants.ts\";\nimport { defaultPrefix } from \"./options.ts\";\n\nconst GLOB_REGEX = /^.+\\.server\\.(ts|js|mjs|mts)$/;\n\n/**\n * Recursively walks `dir` and collects absolute paths to files whose\n * basename matches the `*.server.{ts,js,mjs,mts}` glob pattern.\n */\nexport const walkGlobFiles = async (dir: string): Promise<string[]> => {\n const results: string[] = [];\n const stack = [dir];\n while (stack.length) {\n const current = stack.pop()!;\n let entries;\n try {\n entries = await readdir(current, { withFileTypes: true });\n } catch (_e) {\n continue;\n }\n for (const entry of entries) {\n const fullPath = join(current, entry.name);\n if (entry.isFile() && GLOB_REGEX.test(entry.name)) {\n results.push(fullPath);\n } else if (entry.isDirectory()) {\n stack.push(fullPath);\n }\n }\n }\n return results;\n};\n\n/**\n * A typed error thrown from server functions.\n * The middleware serializes the `message` and `code` in the response,\n * allowing clients to recognise and handle specific error conditions.\n */\nexport class RPCError extends Error {\n /** Machine-readable error code (e.g. \"VALIDATION_FAILED\", \"UNAUTHORIZED\") */\n code: string;\n /** Optional diagnostic payload */\n data?: JsonValue;\n constructor(message: string, code = \"INTERNAL\", data?: JsonValue) {\n super(message);\n this.name = \"RPCError\";\n this.code = code;\n this.data = data;\n }\n}\n\n/**\n * Formats an error for the RPC middleware response.\n * In development the full `RPCError` payload is included so developers\n * can quickly identify issues. Unexpected exceptions never expose their\n * message — only the generic \"Internal Server Error\" is sent, preventing\n * information disclosure; server-side diagnostics are preserved via the\n * middleware's `console.error` logging.\n */\nexport const formatError = (\n err: unknown,\n isProduction: boolean,\n): JsonObject => {\n if (isProduction) {\n return { error: INTERNAL_SERVER_ERROR };\n }\n if (err instanceof RPCError) {\n const payload: JsonObject = {\n error: err.message || INTERNAL_SERVER_ERROR,\n code: err.code,\n };\n if (err.data !== undefined) payload.data = err.data;\n return payload;\n }\n return { error: INTERNAL_SERVER_ERROR };\n};\n\n/**\n * Checks whether a content type maps to a form encoding\n * (`multipart/form-data` or `application/x-www-form-urlencoded`).\n * Form-declared functions accept either encoding so native browser\n * submissions (urlencoded) keep working without JavaScript.\n */\n/**\n * An error carrying an HTTP status, so the dispatch can answer that status\n * instead of flattening every failure to a `500`.\n */\nexport interface ClientHttpError extends Error {\n status?: number;\n statusCode?: number;\n}\n\n/**\n * Tags an error with an HTTP status for the dispatch to surface.\n *\n * Used where a malformed *request* is the fault — a body that does not parse\n * under a declared JSON `Content-Type`, a GET `?args=` value that is not valid\n * JSON. Every host framework rpc supports answers `400` for these (Express\n * `entity.parse.failed`, Fastify `FST_ERR_CTP_INVALID_JSON_BODY`, koa-bodyparser,\n * and h3's own `readBody`), and treating one as a server fault both misreports\n * the fault and turns a trivial client mistake into a log entry.\n * @param status - The HTTP status to answer with\n * @param message - Internal diagnostic message; never sent to the client\n * @returns An `Error` carrying `status`\n */\nexport const httpError = (status: number, message: string): ClientHttpError => {\n const err = new Error(message) as ClientHttpError;\n err.status = status;\n return err;\n};\n\n/**\n * Recognises an error that should produce a `4xx` response rather than a `500`.\n *\n * Matches the `status` / `statusCode` convention used by h3's `HTTPError`, the\n * `http-errors` objects Express's `body-parser` throws, and anything else that\n * carries a numeric 4xx. Shared by all five adapters so a host-framework\n * signal and an rpc-raised one are handled by the same rule.\n * @param err - The caught error\n * @returns True when the error denotes a client (4xx) fault\n */\nconst readClientStatus = (err: unknown): number | undefined => {\n const candidate = err as ClientHttpError | null | undefined;\n // Reads both conventions: h3's `HTTPError` and rpc's `httpError` use\n // `status`, while the `http-errors` objects Express's `body-parser` throws\n // and Koa's `ctx.throw` use `statusCode`.\n const status = candidate?.status ?? candidate?.statusCode;\n return typeof status === \"number\" && status >= 400 && status < 500\n ? status\n : undefined;\n};\n\n/**\n * Recognises an error that should produce a `4xx` response rather than a `500`.\n * Matches the `status` / `statusCode` convention used by h3's `HTTPError`, the\n * `http-errors` objects Express's `body-parser` throws, and anything else\n * carrying a numeric 4xx. Shared by all five adapters so a host-framework\n * signal and an rpc-raised one are handled by the same rule.\n * @param err - The caught error\n * @returns True when the error denotes a client (4xx) fault\n */\nexport const isClientHttpError = (err: unknown): boolean =>\n readClientStatus(err) !== undefined;\n\n/**\n * Reads the status to answer for a client error. Defaults to `400` rather than\n * `500` so an unrecognised 4xx is never reported as a server fault.\n * @param err - The caught error\n * @returns The 4xx status to answer with\n */\nexport const clientErrorStatus = (err: unknown): number =>\n readClientStatus(err) ?? 400;\n\nexport const clientErrorMessage = (status: number): string => {\n if (status === 413) return PAYLOAD_TOO_LARGE;\n if (status === 415) return UNSUPPORTED_MEDIA_TYPE;\n return BAD_REQUEST;\n};\n\nexport const isFormContentType = (contentType: string): boolean =>\n contentType === \"multipart/form-data\" ||\n contentType === \"application/x-www-form-urlencoded\";\n\n/**\n * Detects whether an incoming request's `Content-Type` header conflicts\n * with the function's declared content type. JSON and text functions are\n * enforced strictly (exact match wins), while form functions accept both\n * form encodings because the nojs fallback submits urlencoded forms to\n * multipart-declared endpoints. Requests without a `Content-Type` header\n * (curl, GET, legacy clients) are exempt from enforcement.\n * @param declared - The declared `contentType` from the server function options\n * @param rawHeader - The raw `Content-Type` request header, if present\n */\nexport const hasContentTypeMismatch = (\n declared: ContentType,\n rawHeader: string | undefined,\n): boolean => {\n // No Content-Type header → exempt (url bar, GET, curl compatibility)\n if (!rawHeader) return false;\n // Strip parameters (charset, boundary) before comparison\n const incomingType = rawHeader.trim().toLowerCase().split(\";\")[0].trim();\n if (isFormContentType(declared)) {\n // Forms: reject only non-form encodings (lenient between the two)\n return !isFormContentType(incomingType);\n }\n return incomingType !== declared;\n};\n\n/**\n * Decides whether a request may proceed, given the configured origin allowlist\n * and the two headers a browser can be made to reveal.\n *\n * Four tiers, evaluated in order — the first tier with a signal decides:\n *\n * 1. `origin` option unset → everything passes. No validation is performed.\n * 2. `Origin` present → the allowlist decides, exactly as {@link isOriginAllowed}.\n * 3. `Origin` absent but `Sec-Fetch-Site` present → allow only `same-origin`\n * and `none`; anything else (including an unrecognised value) is rejected.\n * 4. Both absent → passes. This is the deliberate, documented curl/native hole.\n *\n * Tier 2 must short-circuit ahead of tier 3. `Sec-Fetch-Site` is a coarse\n * four-value enum that cannot name a host, so on its own it would reject a\n * legitimate request from an allowlisted sibling subdomain (`same-site`). The\n * allowlist exists precisely to admit that case, and it can only do so while\n * `Origin` survives. `Sec-Fetch-Site` earns a vote only once the precise signal\n * has been stripped away by something in the chain — at which point there is\n * nothing left to trust, so it fails closed.\n *\n * Browsers never strip `Origin` themselves, so tier 3 can only fire when a\n * proxy, sanitising middleware, or misconfigured CDN removed it. No legitimate\n * browser request can regress.\n *\n * An empty (or whitespace-only) header value counts as **absent**, not as an\n * unrecognised signal. No browser emits an empty `Sec-Fetch-Site`, and adapters\n * disagree on what their header accessor returns for a missing header (Node's\n * `req.headers` yields `undefined`, Hono's `c.req.header()` may yield `\"\"`).\n * Normalising here keeps all five adapters behaving identically instead of\n * inheriting whichever convention their framework happens to use.\n * @param allowed - The configured `origin` option, if any\n * @param origin - The raw `Origin` request header, if present\n * @param site - The raw `Sec-Fetch-Site` request header, if present\n * @returns `true` when the request may proceed\n */\nexport const isOriginRequestAllowed = (\n allowed: string | string[] | undefined,\n origin: string | undefined,\n site: string | undefined,\n): boolean => {\n if (!allowed) return true; // tier 1 — the check is opt-in\n if (origin?.trim()) return isOriginAllowed(allowed, origin); // tier 2 — precise\n if (!site?.trim()) return true; // tier 4 — curl / native client\n // tier 3 — precision lost, so fail closed\n return site === \"same-origin\" || site === \"none\";\n};\n\n/**\n * Escapes special regex metacharacters in a string.\n * Used to safely embed user-configurable values (like rpcPrefix) into regular expressions,\n * preventing ReDoS and regex injection attacks.\n * @param s - The raw string to escape\n * @returns The escaped string safe for use in new RegExp()\n */\nexport function escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Decides whether a request's `Origin` header is allowed by the configured\n * allowlist. Shared by all five adapters so the rule lives in exactly one place.\n *\n * - No `allowed` value (option unset) → everything passes: no validation.\n * - No `requestOrigin` header → passes, preserving curl/native-client access.\n * - Otherwise the header must match one of the entries exactly.\n *\n * A single string and a one-element array behave identically, so widening\n * `origin` to `string | string[]` is backward compatible.\n *\n * `Origin: null` (sandboxed iframes, `file://`, extension pages) is rejected\n * whenever an allowlist is set, because it never equals a real origin.\n * @param allowed - The configured `origin` option, if any\n * @param requestOrigin - The raw `Origin` request header, if present\n * @returns `true` when the request may proceed\n */\nexport const isOriginAllowed = (\n allowed: string | string[] | undefined,\n requestOrigin: string | undefined,\n): boolean => {\n if (!allowed || !requestOrigin) return true;\n return Array.isArray(allowed)\n ? allowed.includes(requestOrigin)\n : requestOrigin === allowed;\n};\n\nconst SAFE_URL_BASE = \"http://localhost\";\n\n/**\n * Parses a raw request URL against a fixed base without ever throwing.\n * Malformed request-targets (e.g. `/\\`, `//`, `/\\/`) make the WHATWG URL\n * parser throw `TypeError: Invalid URL`; the adapters call this while\n * building the per-request URL **before** their dispatch `try` block, so an\n * unhandled rejection there crashes raw `node:http` hosts (and Express 4).\n * On failure we fall back to the base root: the resulting pathname never\n * matches the RPC prefix, so the request is treated as non-RPC and falls\n * through to `next()` / 404 instead of crashing the process.\n * @param rawUrl - Raw request URL (path + optional query string)\n * @param base - Optional base URL, defaults to a fixed localhost origin\n * @returns A URL object; never throws\n */\nexport const safeURL = (rawUrl: string, base = SAFE_URL_BASE): URL => {\n try {\n return new URL(rawUrl, base);\n } catch {\n return new URL(\"/\", base);\n }\n};\n\nconst globalPrefixSymbol = Symbol.for(\"thednp.rpc.globalPrefix\");\n\n/** Global rpcPrefix from the last loaded config / middleware — fallback for functions without explicit prefix. */\nexport const getGlobalPrefix = (): string | undefined =>\n (globalThis as unknown as Record<symbol, string | undefined>)[\n globalPrefixSymbol\n ];\n\n/**\n * Publishes the global RPC prefix, consulted by `resolveRPCPrefix` whenever no\n * explicit prefix is supplied. `loadRPCConfig` calls this on every return path\n * so a loaded config is the fallback for later registrations and dispatches.\n *\n * Stored on a `Symbol.for` key on `globalThis` so it stays instance-stable\n * across the bundled entry copies (`server.mjs`, `express.mjs`, ...) and dev\n * server hot reloads — the same technique as the request-context storage.\n * @param prefix - The prefix to publish, or `undefined` to clear it\n */\nexport const setGlobalPrefix = (prefix: string | undefined): void => {\n if (prefix) {\n (globalThis as unknown as Record<symbol, string | undefined>)[\n globalPrefixSymbol\n ] = prefix;\n } else {\n delete (globalThis as unknown as Record<symbol, string | undefined>)[\n globalPrefixSymbol\n ];\n }\n};\n\n/**\n * Resolves the effective RPC prefix: the explicit one when given, otherwise\n * the global prefix set by `setGlobalPrefix` / `loadRPCConfig`, otherwise the\n * built-in default.\n *\n * Every adapter resolves its prefix through this single function — in both the\n * outer `createMiddleware` gate and the `createRPCMiddleware` dispatch — so the\n * two halves of a request can never disagree, and so a prefix registered by\n * `createServerFunction` (which resolves the same way) is always the prefix the\n * middleware looks up. Resolving the two sides independently is what allowed\n * h3 to drift from the other four adapters, and what left the documented\n * global-prefix flow returning 404 on all of them.\n * @param rpcPrefix - Explicit prefix from config or middleware options\n * @returns The prefix to gate on, look up in, and strip from the request path\n */\nexport const resolveRPCPrefix = (rpcPrefix?: string): string =>\n rpcPrefix || getGlobalPrefix() || defaultPrefix;\n","// src/express/helpers.ts\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type {\n Request as ExpressRequest,\n Response as ExpressResponse,\n} from \"express\";\nimport type { BodyResult, JsonValue } from \"@thednp/rpc\";\nimport type { Buffer } from \"node:buffer\";\nimport type { ViteDevServer } from \"vite\";\nimport type { Express } from \"express\";\nimport { createRPCMiddleware } from \"./createMiddleware.ts\";\nimport type { RequestDetails, ResponseDetails } from \"./types.d.ts\";\nimport { httpError, safeURL } from \"../server-helpers.ts\";\n\n/**\n * Convenience function to load RPC config and attach the RPC middleware to an Express app.\n * Dynamically imports loadRPCConfig and creates the middleware with loaded options.\n * @param app - Express application instance\n */\nexport async function attachRPC(app: Express) {\n // The main plugin entry statically imports Vite, so loadRPCConfig is\n // imported lazily: function bundles that never call attachRPC (e.g.\n // serverless functions) keep Vite out of the bundle (or externalized).\n const { loadRPCConfig } = await import(\"@thednp/rpc\");\n const options = await loadRPCConfig();\n app.use(createRPCMiddleware(options));\n}\n\n/**\n * Attaches Vite's dev server middlewares to an Express app for development mode.\n * @param app - Express application instance\n * @param vite - Running Vite dev server\n */\nexport function attachVite(app: Express, vite: ViteDevServer) {\n app.use(vite.middlewares);\n}\n\n/**\n * Reads and parses the HTTP request body from an Express or Node IncomingMessage.\n * If a body parser middleware (e.g. express.json()) already consumed the stream,\n * uses the pre-parsed body from `req.body`.\n * @param req - Express or Node.js IncomingMessage\n * @returns A promise resolving to the parsed body with its content type\n */\n/**\n * Parses a body leniently: JSON when it parses, otherwise the raw string.\n * Used for bodies that did not declare JSON — notably a request with no\n * `Content-Type` header, which must still arrive parsed if it carries JSON.\n * @param body - The raw body text\n * @returns The parsed JSON value, or the original string\n */\nconst parseJsonOrRawText = (body: string): unknown => {\n try {\n return JSON.parse(body);\n } catch {\n return body;\n }\n};\n\nexport const readBody = (\n req: ExpressRequest | IncomingMessage,\n): Promise<BodyResult> => {\n return new Promise((resolve, reject) => {\n // If an Express body parser already consumed the stream\n // via app.use(express.json()), use req.body directly\n if (hasPreParsedBody(req) && req.body !== undefined) {\n // istanbul ignore next\n const contentType = req.headers[\"content-type\"]?.toLowerCase() || \"\";\n const isJSON = contentType.includes(\"json\");\n const isMultipart = contentType.includes(\"multipart/form-data\");\n const isUrlEncoded = contentType.includes(\"urlencoded\");\n resolve({\n contentType: isMultipart\n ? \"multipart/form-data\"\n : isJSON\n ? \"application/json\"\n : isUrlEncoded\n ? \"application/x-www-form-urlencoded\"\n : \"text/plain\",\n data: isMultipart\n ? (req.body as Record<string, unknown>)\n : isJSON\n ? req.body\n : isUrlEncoded\n ? (req.body as Record<string, unknown>)\n : String(req.body),\n } as BodyResult);\n return;\n }\n\n // Else we parse the body right away\n let body = \"\";\n\n const toggleListeners = (add?: boolean) => {\n const method = add ? \"on\" : \"off\";\n req[method](\"data\", onData);\n req[method](\"end\", onEnd);\n req[method](\"error\", onError);\n };\n\n const onData = (chunk: Buffer) => {\n body += chunk.toString();\n };\n\n const onEnd = () => {\n toggleListeners();\n const incomingType = req.headers[\"content-type\"]?.toLowerCase() || \"\";\n const isJSON = incomingType.includes(\"json\");\n const isMultipart = incomingType.includes(\"multipart/form-data\");\n const isUrlEncoded = incomingType.includes(\"urlencoded\");\n try {\n // Only a *declared* JSON body is parsed strictly; everything else keeps\n // the lenient sniff. Previously all three fell through to a single\n // `JSON.parse(body)`, so a malformed JSON body and a legitimate text\n // body produced the same exception and were indistinguishable — the\n // catch \"recovered\" both into a text/plain string, which silently\n // handed a JSON-declared function a string and answered 200.\n //\n // The lenient branch is deliberate and must stay: a request with no\n // `Content-Type` at all (curl, and the nojs form fallback) that\n // happens to carry JSON still has to arrive parsed.\n const data = isMultipart\n ? { raw: body }\n : isUrlEncoded\n ? Object.fromEntries(new URLSearchParams(body))\n : isJSON\n ? JSON.parse(body)\n : parseJsonOrRawText(body);\n resolve({\n contentType: isMultipart\n ? \"multipart/form-data\"\n : isJSON\n ? \"application/json\"\n : isUrlEncoded\n ? \"application/x-www-form-urlencoded\"\n : \"text/plain\",\n data: isMultipart ? (data as Record<string, unknown>) : data,\n } as BodyResult);\n } catch (_e) {\n // A body that does not parse under a declared JSON Content-Type is a\n // client error. It used to resolve as `text/plain` with the raw string,\n // which silently handed a JSON-declared function a string and answered\n // 200 — failing open on malformed input. Every host framework rpc\n // supports answers 400 here (Express `entity.parse.failed`, Fastify\n // `FST_ERR_CTP_INVALID_JSON_BODY`, koa-bodyparser, h3's own readBody).\n reject(httpError(400, \"Invalid JSON body\"));\n }\n };\n\n const onError = (err: Error) => {\n toggleListeners();\n\n reject(err);\n };\n\n toggleListeners(true);\n });\n};\n\n/**\n * Type guard that checks whether a request is an Express Request (has `originalUrl`).\n * @param req - A Node IncomingMessage or Express Request\n * @returns True if the request is an Express Request\n */\nexport const isExpressRequest = (\n req: IncomingMessage | ExpressRequest,\n): req is ExpressRequest => {\n return \"originalUrl\" in req;\n};\n\n/**\n * Type guard that checks whether a response is an Express Response (has `json` and `send` methods).\n * @param res - A Node ServerResponse or Express Response\n * @returns True if the response is an Express Response\n */\nexport const isExpressResponse = (\n res: ServerResponse | ExpressResponse,\n): res is ExpressResponse => {\n return \"json\" in res && \"send\" in res;\n};\n\n/**\n * Issues an HTTP redirect on an Express or raw Node ServerResponse.\n * Uses Express's native `res.redirect(status, location)` when an Express\n * Response is provided, otherwise writes the status code and `Location`\n * header directly on the raw `ServerResponse` (safe for Connect-compatible\n * middlewares and serverless adapters whose mock responses lack `.redirect`).\n * Defaults to `303 See Other` for convention (Post/Redirect/Get).\n * @param res - Express Response or raw Node ServerResponse\n * @param location - The URL to redirect to\n * @param status - HTTP status code, defaults to 303\n */\nexport const redirect = (\n res: ServerResponse | ExpressResponse,\n location: string,\n status = 303,\n): void => {\n if (isExpressResponse(res)) {\n res.redirect(status, location);\n return;\n }\n res.statusCode = status;\n res.setHeader(\"Location\", location);\n res.end();\n};\n\n/**\n * Type guard that checks whether a request has a pre-parsed body (`body` property).\n * Used to detect if a body-parser middleware already consumed the stream.\n * @param req - A Node IncomingMessage or Express Request\n * @returns True if the request has a body property\n */\nexport const hasPreParsedBody = (\n req: IncomingMessage | ExpressRequest,\n): req is ExpressRequest => {\n return \"body\" in req;\n};\n\n/**\n * Extracts normalized request details from an Express or Node IncomingMessage.\n * Parses the URL to extract pathname, search string, and search params.\n * @param request - Express or Node.js request object\n * @returns Normalized request details including URL, headers, and method\n */\nexport const getRequestDetails = (\n request: ExpressRequest | IncomingMessage,\n): RequestDetails => {\n const rawUrl = (\n isExpressRequest(request) ? request.originalUrl : request.url\n ) as string;\n const url = safeURL(rawUrl);\n\n return {\n url: url.pathname,\n search: url.search,\n searchParams: url.searchParams,\n headers: request.headers,\n method: request.method,\n };\n};\n\n/**\n * Wraps an Express or Node ServerResponse with a uniform API for setting headers,\n * status codes, and sending JSON responses. Handles the Express vs raw Node API differences.\n * @param response - Express or Node.js server response object\n * @returns A ResponseDetails object with setHeader, setStatusCode, and sendResponse helpers\n */\nexport const getResponseDetails = (\n response: ExpressResponse | ServerResponse,\n): ResponseDetails => {\n const isResponseSent = response.headersSent || response.writableEnded;\n\n const setHeader = (name: string, value: string) => {\n if (isExpressResponse(response)) {\n response.header(name, value);\n } else {\n response.setHeader(name, value);\n }\n };\n\n const setStatusCode = (code: number) => {\n if (isExpressResponse(response)) {\n response.status(code);\n } else {\n response.statusCode = code;\n }\n };\n\n const sendResponse = (code: number, output: JsonValue) => {\n setStatusCode(code);\n setHeader(\"Content-Type\", \"application/json\");\n\n if (isExpressResponse(response)) {\n response.send(JSON.stringify(output));\n } else {\n response.end(JSON.stringify(output));\n }\n };\n\n return {\n isResponseSent,\n setHeader,\n statusCode: response.statusCode,\n setStatusCode,\n sendResponse,\n };\n};\n","// src/express/createMidleware.ts\nimport type { IncomingMessage, ServerResponse } from \"node:http\";\nimport type {\n NextFunction,\n Request as ExpressRequest,\n Response as ExpressResponse,\n} from \"express\";\nimport type {\n ExpressMiddlewareFn,\n ExpressMiddlewareOptions,\n} from \"./types.d.ts\";\nimport type { Connect } from \"vite\";\nimport type { JsonValue } from \"../types.d.ts\";\nimport type { RequestEvent } from \"@thednp/rpc/server\";\nimport {\n clientErrorMessage,\n clientErrorStatus,\n escapeRegExp,\n formatError,\n hasContentTypeMismatch,\n isClientHttpError,\n isOriginRequestAllowed,\n provideRequestContext,\n resolveRPCPrefix,\n scanForServerFiles,\n} from \"@thednp/rpc/server\";\nimport { getFunctionsForPrefix } from \"../functionsMap.ts\";\nimport { defaultMiddlewareOptions } from \"../options.ts\";\nimport {\n getRequestDetails,\n getResponseDetails,\n readBody,\n redirect as expressRedirect,\n} from \"./helpers.ts\";\nimport {\n BAD_REQUEST,\n CLIENT_DISCONNECTED,\n FUNCTION_NOT_FOUND,\n METHOD_NOT_ALLOWED,\n MIDDLEWARE_NAME_USED,\n REQUEST_FORBIDDEN,\n UNSUPPORTED_MEDIA_TYPE,\n} from \"../constants.ts\";\n\nlet middlewareCount = 0;\nconst middlewareStack = new Set<string>();\n\n/**\n * Creates an Express middleware with optional path and rpcPrefix filtering.\n * Middleware names are deduplicated — reusing a name throws an error.\n * Prefix and path regexes are compiled once at creation time (hoisted) for performance.\n * @param initialOptions - Options for rpcPrefix, path matching, and the handler function\n * @returns An Express middleware function\n */\nexport const createMiddleware: ExpressMiddlewareFn = (initialOptions = {}) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n initialOptions,\n ) as ExpressMiddlewareOptions;\n const middlewareName = options.name;\n const rpcPrefix = options.rpcPrefix;\n const path = options.path;\n const handler = options.handler;\n\n let name = middlewareName;\n if (!name) {\n name = \"viteRPCMiddleware-\" + middlewareCount;\n middlewareCount += 1;\n }\n if (middlewareStack.has(name)) {\n throw new Error(MIDDLEWARE_NAME_USED(name));\n }\n middlewareStack.add(name);\n\n // Hoist regex compilation out of per-request path. Escape the prefix to\n // prevent regex injection via metacharacters in the config string.\n // Resolved once at creation time so the hoisted regex and the\n // function-map lookup can never disagree. `createRPCMiddleware` hands\n // over its already-resolved prefix, making this a no-op in that path.\n const resolvedPrefix = resolveRPCPrefix(rpcPrefix);\n // Gated only when an explicit prefix was supplied: a bare\n // `createMiddleware({ path, handler })` has never prefix-gated.\n // `createRPCMiddleware` always supplies one, so RPC dispatch does.\n const prefixRegex: RegExp | null = rpcPrefix\n ? new RegExp(`^/${escapeRegExp(resolvedPrefix)}/`)\n : null;\n const pathMatcher: RegExp | null = path\n ? (typeof path === \"string\" ? new RegExp(path) : path)\n : null;\n\n const middlewareHandler = async (\n req: IncomingMessage | ExpressRequest,\n res: ServerResponse | ExpressResponse,\n next: Connect.NextFunction | NextFunction,\n ) => {\n const { url } = getRequestDetails(req);\n\n // No need to continue when no handler provided\n if (!handler) {\n return next?.();\n }\n\n // Path matching\n if (pathMatcher && !pathMatcher.test(url)) return next?.();\n\n // rpcPrefix matching (boundary-safe via escaped regex)\n if (prefixRegex && !prefixRegex.test(url)) {\n return next?.();\n }\n\n // When serving from production server, scan for server files\n if (getFunctionsForPrefix(resolvedPrefix).size === 0) {\n await scanForServerFiles({\n rpcPrefix: resolvedPrefix,\n serverFiles: options.serverFiles,\n scanRoot: options.scanRoot,\n } as never);\n }\n\n // Execute handler\n await handler(req, res, next);\n };\n\n Object.defineProperty(middlewareHandler, \"name\", {\n value: name,\n });\n\n return middlewareHandler;\n};\n\n/**\n * Creates the Express RPC middleware that routes incoming requests to registered server functions.\n * Reads the request body, dispatches to the matching function via getFunctionsForPrefix,\n * and sends the JSON-serialized result. Handles client disconnection via abort signals.\n * Supports multi-prefix setups where different middleware instances can route to functions\n * registered under different prefixes.\n * @param initialOptions - Options including rpcPrefix for URL routing and prefix-scoped function lookup\n * @returns An Express middleware function\n */\nexport const createRPCMiddleware: ExpressMiddlewareFn = (\n initialOptions = {},\n) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n initialOptions,\n ) as ExpressMiddlewareOptions;\n\n // Hoist prefix regex (escaped) and the literal prefix-for-replace out of the\n // per-request handler to avoid regex injection and per-request compilation.\n const rpcPrefix = options.rpcPrefix;\n const prefix = resolveRPCPrefix(rpcPrefix);\n\n const prefixRegex = new RegExp(`^/${escapeRegExp(prefix)}/`);\n const prefixReplace = `/${prefix}/`;\n\n return createMiddleware({\n ...options,\n // Hand the resolved prefix down so the gate and the dispatch agree.\n rpcPrefix: prefix,\n handler: async (\n req: IncomingMessage | ExpressRequest,\n res: ServerResponse | ExpressResponse,\n _next: NextFunction | Connect.NextFunction,\n ) => {\n const { url: path, searchParams } = getRequestDetails(req);\n const { sendResponse } = getResponseDetails(res);\n\n // Validate the url starts with the prefix via the escaped regex\n // istanbul ignore next\n if (prefixRegex && !prefixRegex.test(path)) {\n // falls through to next handler (never reached in practice; the outer\n // createMiddleware already gates on this, but kept for defense-in-depth)\n return;\n }\n\n // Optional origin check. When Origin survives, the allowlist decides;\n // when it has been stripped, Sec-Fetch-Site is consulted instead and\n // fails closed. See `isOriginRequestAllowed` for the four tiers.\n if (\n !isOriginRequestAllowed(\n options.origin,\n req.headers.origin,\n req.headers[\"sec-fetch-site\"],\n )\n ) {\n sendResponse(403, { error: REQUEST_FORBIDDEN });\n return;\n }\n\n const functionName = path.replace(prefixReplace, \"\");\n // Look up function in the prefix-scoped map\n const serverFunctionsForPrefix = getFunctionsForPrefix(prefix);\n const serverFunction = serverFunctionsForPrefix.get(functionName);\n\n if (!serverFunction) {\n sendResponse(404, { error: FUNCTION_NOT_FOUND });\n return;\n }\n\n try {\n const method = serverFunction.options?.method || \"POST\";\n if (req.method?.toUpperCase() !== method) {\n sendResponse(405, { error: METHOD_NOT_ALLOWED });\n return;\n }\n\n let args: JsonValue[] = [];\n if (method === \"GET\") {\n const raw = searchParams.get(\"args\");\n if (raw) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // A malformed `?args=` is a malformed request, not a server\n // fault. Express-style hosts answer 400 for the equivalent\n // malformed-body case, so match them.\n sendResponse(400, { error: BAD_REQUEST });\n return;\n }\n if (!Array.isArray(parsed)) {\n sendResponse(400, { error: BAD_REQUEST });\n return;\n }\n args = parsed as JsonValue[];\n }\n } else {\n // Content-type enforcement: strict for json/text, lenient between forms.\n // Requests without a Content-Type header are exempt (curl/GET compat).\n // Checked BEFORE readBody so mismatched bodies are never buffered.\n if (\n hasContentTypeMismatch(\n serverFunction.options?.contentType ?? \"application/json\",\n req.headers[\"content-type\"],\n )\n ) {\n sendResponse(415, { error: UNSUPPORTED_MEDIA_TYPE });\n return;\n }\n const body = await readBody(req);\n args = Array.isArray(body.data)\n ? (body.data as JsonValue[])\n : [body.data as JsonValue];\n }\n // ─── Dispatch ────────────────────────────────────────────────────\n // Establish the per-request context around the *entire* dispatch so\n // server functions (and async continuations spawned by their work)\n // read `getRequestContext()` and can call the framework-level\n // `redirect(location)`. The adapter-specific redirect is bound into the\n // context here; `serverFunction.handler` must be invoked inside the\n // context callback so its async increments run with the context live.\n const requestEvent: RequestEvent = {\n request: req,\n response: res,\n nativeEvent: { req, res },\n locals: (res as ExpressResponse).locals ?? {},\n functionName,\n redirect: (location, status = 303) => {\n requestEvent.redirected = { location, status };\n expressRedirect(res, location, status);\n },\n send: (status, body, headers) => {\n requestEvent.sent = { status, body, headers };\n const details = getResponseDetails(res);\n if (headers) {\n for (const [name, value] of Object.entries(headers)) {\n details.setHeader(name, value);\n }\n }\n details.sendResponse(status, body);\n },\n };\n\n const { data, cancel } = provideRequestContext(\n requestEvent,\n () => serverFunction.handler(...args),\n );\n const onClose = () => cancel(CLIENT_DISCONNECTED);\n req.on(\"close\", onClose);\n const result = await data;\n req.off(\"close\", onClose);\n\n // Skip the JSON send when the server function issued a redirect or\n // short-circuited with `send`; the bound adapter already wrote the\n // response. Express may also have ended the response via headersSent.\n // istanbul ignore else\n if (\n !requestEvent.redirected &&\n !requestEvent.sent &&\n !res.headersSent\n ) {\n sendResponse(200, { data: result });\n }\n } catch (err) {\n // A malformed request is a client error, not a server fault. rpc raises\n // these with a status (see `httpError`), and host frameworks signal the\n // same class the same way — h3's body limit throws 413 from inside the\n // read, Express's body-parser throws 400, and Fastify's parser does the\n // same before rpc is reached. Answering 500 for any of them both\n // misreports the fault and turns a trivial client mistake into a log\n // entry. The body comes from a fixed table, so nothing from the\n // underlying error is echoed back.\n if (isClientHttpError(err)) {\n const status = clientErrorStatus(err);\n sendResponse(status, { error: clientErrorMessage(status) });\n return;\n }\n console.error(String(err));\n const isProduction = process.env.NODE_ENV === \"production\";\n sendResponse(500, formatError(err, isProduction));\n }\n },\n });\n};\n"],"mappings":";;;;;;;;AAwCA,MAAa,2BAA8C;CACzD,WAAW,KAAA;CACX,MAAM,KAAA;CACN,QAAQ,KAAA;AACV;;;;;;;;;;;ACjCA,MAAM,qBAAqB,OAAO,IAAI,yBAAyB;;;;;;AAO/D,MAAa,0BAG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B;IAC7B;IAQA,MAAM,eAA6B;KACjC,SAAS;KACT,UAAU;KACV,aAAa;MAAE;MAAK;KAAI;KACxB,QAAS,IAAwB,UAAU,CAAC;KAC5C;KACA,WAAW,UAAU,SAAS,QAAQ;MACpC,aAAa,aAAa;OAAE;OAAU;MAAO;MAC7C,SAAgB,KAAK,UAAU,MAAM;KACvC;KACA,OAAO,QAAQ,MAAM,YAAY;MAC/B,aAAa,OAAO;OAAE;OAAQ;OAAM;MAAQ;MAC5C,MAAM,UAAU,mBAAmB,GAAG;MACtC,IAAI,SACF,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,OAAO,GAChD,QAAQ,UAAU,MAAM,KAAK;MAGjC,QAAQ,aAAa,QAAQ,IAAI;KACnC;IACF;IAEA,MAAM,EAAE,MAAM,WAAW,sBACvB,oBACM,eAAe,QAAQ,GAAG,IAAI,CACtC;IACA,MAAM,gBAAgB,OAAO,mBAAmB;IAChD,IAAI,GAAG,SAAS,OAAO;IACvB,MAAM,SAAS,MAAM;IACrB,IAAI,IAAI,SAAS,OAAO;IAMxB,IACE,CAAC,aAAa,cACd,CAAC,aAAa,QACd,CAAC,IAAI,aAEL,aAAa,KAAK,EAAE,MAAM,OAAO,CAAC;GAEtC,SAAS,KAAK;IASZ,IAAI,kBAAkB,GAAG,GAAG;KAC1B,MAAM,SAAS,kBAAkB,GAAG;KACpC,aAAa,QAAQ,EAAE,OAAO,mBAAmB,MAAM,EAAE,CAAC;KAC1D;IACF;IACA,QAAQ,MAAM,OAAO,GAAG,CAAC;IACzB,MAAM,eAAe,QAAQ,IAAI,aAAa;IAC9C,aAAa,KAAK,YAAY,KAAK,YAAY,CAAC;GAClD;EACF;CACF,CAAC;AACH"}
@@ -1,6 +1,7 @@
1
1
  import fp from "fastify-plugin";
2
- import { FastifyInstance, FastifyInstance as Fastify, FastifyReply, FastifyReply as FastifyReply$1, FastifyRequest, FastifyRequest as FastifyRequest$1, HookHandlerDoneFunction } from "fastify";
3
- import { MiddlewareOptions, RpcPluginOptions } from "@thednp/rpc";
2
+ import { FastifyInstance, FastifyInstance as Fastify, FastifyInstance as FastifyApp, FastifyReply, FastifyReply as FastifyReply$1, FastifyReply as FastifyResponse, FastifyRequest, FastifyRequest as FastifyRequest$1, HookHandlerDoneFunction, HookHandlerDoneFunction as FastifyNext } from "fastify";
3
+ import { AdapterName, MiddlewareOptions } from "@thednp/rpc";
4
+ import { IncomingHttpHeaders } from "node:http";
4
5
  import { ViteDevServer } from "vite";
5
6
  import "express";
6
7
  import "hono";
@@ -9,6 +10,82 @@ import "hono/utils/http-status";
9
10
  import "hono/factory";
10
11
  import "koa";
11
12
  import "h3";
13
+ //#region src/types.d.ts
14
+ /**
15
+ * Parsed request body result discriminated by content type.
16
+ */
17
+ type BodyResult = {
18
+ contentType: "application/json";
19
+ data: JsonValue;
20
+ } | {
21
+ contentType: "text/plain";
22
+ data: string;
23
+ } | {
24
+ contentType: "application/x-www-form-urlencoded";
25
+ data: Record<string, unknown>;
26
+ } | {
27
+ contentType: "multipart/form-data";
28
+ data: Record<string, unknown>;
29
+ };
30
+ // primitives and their compositions
31
+ /**
32
+ * Primitive JSON values, including `undefined` for optional parameters.
33
+ */
34
+ type JsonPrimitive = string | number | boolean | null | undefined;
35
+ /**
36
+ * A JSON object whose values are JSON values or arrays.
37
+ */
38
+ type JsonObject = {
39
+ [key: string]: JsonValue | JsonArray;
40
+ };
41
+ /**
42
+ * A JSON array of JSON values.
43
+ */
44
+ type JsonArray = (FormData | JsonValue)[];
45
+ /**
46
+ * Any JSON-serializable value: primitive, array, or object.
47
+ */
48
+ type JsonValue = JsonPrimitive | JsonArray | JsonObject;
49
+ //#endregion
50
+ //#region src/adapter-types.d.ts
51
+ /**
52
+ * Wraps a server response to normalize status, header, and send operations
53
+ * across Node `ServerResponse` and framework response objects.
54
+ *
55
+ * Re-exported from every adapter (`@thednp/rpc/express`, `/fastify`, `/hono`,
56
+ * `/koa`, `/h3`) so a consumer can name the shape without importing from the
57
+ * express adapter specifically.
58
+ */
59
+ type ResponseDetails = {
60
+ /** Whether the response was already sent */
61
+ isResponseSent: boolean;
62
+ /** Sets a response header */
63
+ setHeader: (name: string, value: string) => void;
64
+ /** Current response status code */
65
+ statusCode: number;
66
+ /** Sets the response status code */
67
+ setStatusCode: (code: number) => void;
68
+ /** Sends a JSON response with the given status code and output */
69
+ sendResponse: (code: number, output: JsonValue) => void;
70
+ };
71
+ /**
72
+ * Normalized view of an incoming request: URL parts, headers, and method.
73
+ *
74
+ * Re-exported from every adapter, for the same reason as {@link ResponseDetails}.
75
+ */
76
+ type RequestDetails = {
77
+ /** Full request URL (path + query string) */
78
+ url: string;
79
+ /** Query string including the leading `?` */
80
+ search: string;
81
+ /** Parsed query string parameters */
82
+ searchParams: URLSearchParams;
83
+ /** Raw request headers */
84
+ headers: IncomingHttpHeaders;
85
+ /** HTTP method (GET, POST, etc.) */
86
+ method: string | undefined;
87
+ };
88
+ //#endregion
12
89
  //#region src/fastify/types.d.ts
13
90
  /**
14
91
  * Fastify RPC plugin signature: registers the middleware as a preHandler hook.
@@ -37,7 +114,7 @@ type FastifyMiddlewareOptions = MiddlewareOptions<"fastify">;
37
114
  * Fastify middleware factory: takes optional initial options and returns
38
115
  * the Fastify-compatible handler.
39
116
  */
40
- type FastifyMiddlewareFn = <A extends RpcPluginOptions["adapter"] = "fastify">(initialOptions?: Partial<FastifyMiddlewareOptions>) => FastifyMiddlewareHooks["handler"];
117
+ type FastifyMiddlewareFn = <A extends AdapterName = "fastify">(initialOptions?: Partial<FastifyMiddlewareOptions>) => FastifyMiddlewareHooks["handler"];
41
118
  /**
42
119
  * Fastify middleware handler signature used by the RPC middleware.
43
120
  */
@@ -68,43 +145,6 @@ export declare const createMiddleware: FastifyMiddlewareFn;
68
145
  */
69
146
  export declare const createRPCMiddleware: FastifyMiddlewareFn;
70
147
  //#endregion
71
- //#region src/types.d.ts
72
- /**
73
- * Parsed request body result discriminated by content type.
74
- */
75
- type BodyResult = {
76
- contentType: "application/json";
77
- data: JsonValue;
78
- } | {
79
- contentType: "text/plain";
80
- data: string;
81
- } | {
82
- contentType: "application/x-www-form-urlencoded";
83
- data: Record<string, unknown>;
84
- } | {
85
- contentType: "multipart/form-data";
86
- data: Record<string, unknown>;
87
- };
88
- // primitives and their compositions
89
- /**
90
- * Primitive JSON values, including `undefined` for optional parameters.
91
- */
92
- type JsonPrimitive = string | number | boolean | null | undefined;
93
- /**
94
- * A JSON object whose values are JSON values or arrays.
95
- */
96
- type JsonObject = {
97
- [key: string]: JsonValue | JsonArray;
98
- };
99
- /**
100
- * A JSON array of JSON values.
101
- */
102
- type JsonArray = (FormData | JsonValue)[];
103
- /**
104
- * Any JSON-serializable value: primitive, array, or object.
105
- */
106
- type JsonValue = JsonPrimitive | JsonArray | JsonObject;
107
- //#endregion
108
148
  //#region src/fastify/helpers.d.ts
109
149
  /**
110
150
  * Convenience function to load RPC config and register the RPC plugin to a Fastify instance.
@@ -137,12 +177,6 @@ export declare function attachVite(app: FastifyInstance, vite: ViteDevServer): v
137
177
  * @returns A Fastify `onRequest` hook handler
138
178
  */
139
179
  export declare function viteMiddleware(vite: ViteDevServer): (request: FastifyRequest$1, reply: FastifyReply$1) => Promise<void>;
140
- /**
141
- * Reads and parses the HTTP request body from a Fastify request.
142
- * If Fastify's body parser already consumed the stream, uses the pre-parsed body from `req.body`.
143
- * @param req - Fastify request object
144
- * @returns A promise resolving to the parsed body with its content type
145
- */
146
180
  export declare const readBody: (req: FastifyRequest$1) => Promise<BodyResult>;
147
181
  /**
148
182
  * Issues an HTTP redirect on a Fastify reply using the native
@@ -155,5 +189,5 @@ export declare const readBody: (req: FastifyRequest$1) => Promise<BodyResult>;
155
189
  */
156
190
  export declare const redirect: (reply: FastifyReply$1, location: string, status?: number) => void;
157
191
  //#endregion
158
- export type { Fastify, FastifyMiddlewareFn, FastifyMiddlewareHooks, FastifyMiddlewareOptions, FastifyPlugin, FastifyRPCPlugin, FastifyReply, FastifyRequest, RegisteredFastifyRPCPlugin, RpcFastifyPluginOptions };
192
+ export type { Fastify, FastifyApp, FastifyMiddlewareFn, FastifyMiddlewareHooks, FastifyMiddlewareOptions, FastifyNext, FastifyPlugin, FastifyRPCPlugin, FastifyReply, FastifyRequest, FastifyResponse, RegisteredFastifyRPCPlugin, RequestDetails, ResponseDetails, RpcFastifyPluginOptions };
159
193
  //# sourceMappingURL=fastify.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"fastify.d.mts","names":["FastifyRequest","FastifyReply","FastifyRequest","FastifyReply"],"sources":["../../src/fastify/types.d.ts","../../src/fastify/createMiddleware.ts","../../src/types.d.ts","../../src/fastify/helpers.ts"],"mappings":";;;;;;;;;;;;;;;KAYY,oBACV,SAAS,iBACT,gBAAgB,QAAQ,+BACxB;;;;KAMU,uBAAuB;;;;KAKvB,6BAA6B,WAAW;;;;KAKxC,0BAA0B;;EAEpC;;;;;KAMU,2BAA2B;;;;;KAM3B,uBACV,UAAU,yCAEV,iBAAiB,QAAQ,8BACtB;;;;UAKY;;;;;;;EAOf,UACE,KAAKA,kBACL,KAAKC,gBACL,MAAM,4BACH;;;;;;;;;;qBCjBM,kBAAkB;;;;;;;;qBAuFlB,qBAAqB;;;;;;KCvDtB;EACN;EAAiC,MAAM;;EACvC;EAA2B;;EAE7B;EACA,MAAM;;EAEJ;EAAoC,MAAM;;;;;;KAmCpC;;;;KAIA;GAAgB,cAAc,YAAY;;;;;KAI1C,aAAa,WAAW;;;;KAIxB,YAAY,gBAAgB,YAAY;;;;;;;;wBCzH9B,UAAU,KAAK,kBAAe;;;;;;;wBAepC,WAAW,KAAK,iBAAiB,MAAM;;;;;;;;;;;;;;;;;;wBA2BvC,eACd,MAAM,iBACJ,SAASC,kBAAgB,OAAOC,mBAAiB;;;;;;;qBAgBxC,WAAQ,KACdD,qBACJ,QAAQ;;;;;;;;;;qBAoFE,WAAQ,OACZC,gBAAY,kBACH"}
1
+ {"version":3,"file":"fastify.d.mts","names":["FastifyRequest","FastifyReply","FastifyRequest","FastifyReply"],"sources":["../../src/types.d.ts","../../src/adapter-types.ts","../../src/fastify/types.d.ts","../../src/fastify/createMiddleware.ts","../../src/fastify/helpers.ts"],"mappings":";;;;;;;;;;;;;;;;KA4FY;EACN;EAAiC,MAAM;;EACvC;EAA2B;;EAE7B;EACA,MAAM;;EAEJ;EAAoC,MAAM;;;;;;KAmCpC;;;;KAIA;GAAgB,cAAc,YAAY;;;;;KAI1C,aAAa,WAAW;;;;KAIxB,YAAY,gBAAgB,YAAY;;;;;;;;;;;KCtIxC;;EAEV;;EAEA,YAAY,cAAc;;EAE1B;;EAEA,gBAAgB;;EAEhB,eAAe,cAAc,QAAQ;;;;;;;KAQ3B;;EAEV;;EAEA;;EAEA,cAAc;;EAEd,SAAS;;EAET;;;;;;;KC5BU,oBACV,SAAS,iBACT,gBAAgB,QAAQ,+BACxB;;;;KAMU,uBAAuB;;;;KAKvB,6BAA6B,WAAW;;;;KAKxC,0BAA0B;;EAEpC;;;;;KAMU,2BAA2B;;;;;KAM3B,uBACV,UAAU,yBAEV,iBAAiB,QAAQ,8BACtB;;;;UAKY;;;;;;;EAOf,UACE,KAAKA,kBACL,KAAKC,gBACL,MAAM,4BACH;;;;;;;;;;qBClBM,kBAAkB;;;;;;;;qBA4FlB,qBAAqB;;;;;;;;wBC7HZ,UAAU,KAAK,kBAAe;;;;;;;wBAepC,WAAW,KAAK,iBAAiB,MAAM;;;;;;;;;;;;;;;;;;wBA2BvC,eACd,MAAM,iBACJ,SAASC,kBAAgB,OAAOC,mBAAiB;qBA+BxC,WAAQ,KACdD,qBACJ,QAAQ;;;;;;;;;;qBAsGE,WAAQ,OACZC,gBAAY,kBACH"}