@thednp/rpc 0.0.1 → 0.0.4

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 +5 -5
  2. package/CLAUDE.md +1 -0
  3. package/README.md +193 -47
  4. package/dist/express/express.d.mts +110 -16
  5. package/dist/express/express.d.mts.map +1 -1
  6. package/dist/express/express.mjs +113 -20
  7. package/dist/express/express.mjs.map +1 -1
  8. package/dist/fastify/fastify.d.mts +66 -1
  9. package/dist/fastify/fastify.d.mts.map +1 -1
  10. package/dist/fastify/fastify.mjs +89 -18
  11. package/dist/fastify/fastify.mjs.map +1 -1
  12. package/dist/fastify/plugin/fastify/plugin.d.mts +64 -9
  13. package/dist/fastify/plugin/fastify/plugin.d.mts.map +1 -1
  14. package/dist/fastify/plugin/fastify/plugin.mjs +78 -18
  15. package/dist/fastify/plugin/fastify/plugin.mjs.map +1 -1
  16. package/dist/helpers/helpers.d.mts +64 -3
  17. package/dist/helpers/helpers.d.mts.map +1 -1
  18. package/dist/helpers/helpers.mjs +34 -7
  19. package/dist/helpers/helpers.mjs.map +1 -1
  20. package/dist/hono/hono.d.mts +66 -5
  21. package/dist/hono/hono.d.mts.map +1 -1
  22. package/dist/hono/hono.mjs +84 -24
  23. package/dist/hono/hono.mjs.map +1 -1
  24. package/dist/index.d.mts +182 -18
  25. package/dist/index.d.mts.map +1 -1
  26. package/dist/index.mjs +137 -31
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/koa/koa.d.mts +52 -0
  29. package/dist/koa/koa.d.mts.map +1 -1
  30. package/dist/koa/koa.mjs +86 -16
  31. package/dist/koa/koa.mjs.map +1 -1
  32. package/dist/server/server.d.mts +104 -4
  33. package/dist/server/server.d.mts.map +1 -1
  34. package/dist/server/server.mjs +117 -17
  35. package/dist/server/server.mjs.map +1 -1
  36. package/package.json +48 -30
  37. package/wiki/adapters.md +31 -2
  38. package/wiki/best-practices.md +172 -9
  39. package/wiki/client-usage.md +7 -3
  40. package/wiki/configuration.md +5 -6
  41. package/wiki/getting-started.md +35 -6
  42. package/wiki/index.md +8 -20
  43. package/wiki/security.md +27 -5
  44. package/wiki/server-functions.md +49 -5
  45. package/wiki/setup.md +8 -4
@@ -1,23 +1,41 @@
1
1
  import { scanForServerFiles, serverFunctionsMap } from "@thednp/rpc/server";
2
2
  //#region src/options.ts
3
3
  const defaultRPCOptions = {
4
- rpcPreffix: "__rpc",
4
+ rpcPrefix: "__rpc",
5
5
  adapter: "express"
6
6
  };
7
7
  const defaultMiddlewareOptions = {
8
- rpcPreffix: void 0,
9
- path: void 0
8
+ rpcPrefix: void 0,
9
+ path: void 0,
10
+ origin: void 0
10
11
  };
11
12
  //#endregion
12
13
  //#region src/express/helpers.ts
14
+ /**
15
+ * Convenience function to load RPC config and attach the RPC middleware to an Express app.
16
+ * Dynamically imports loadRPCConfig and creates the middleware with loaded options.
17
+ * @param app - Express application instance
18
+ */
13
19
  async function attachRPC(app) {
14
20
  const { loadRPCConfig } = await import("@thednp/rpc");
15
21
  const { adapter: _adapter, ...options } = await loadRPCConfig();
16
22
  app.use(createRPCMiddleware(options));
17
23
  }
24
+ /**
25
+ * Attaches Vite's dev server middlewares to an Express app for development mode.
26
+ * @param app - Express application instance
27
+ * @param vite - Running Vite dev server
28
+ */
18
29
  function attachVite(app, vite) {
19
30
  app.use(vite.middlewares);
20
31
  }
32
+ /**
33
+ * Reads and parses the HTTP request body from an Express or Node IncomingMessage.
34
+ * If a body parser middleware (e.g. express.json()) already consumed the stream,
35
+ * uses the pre-parsed body from `req.body`.
36
+ * @param req - Express or Node.js IncomingMessage
37
+ * @returns A promise resolving to the parsed body with its content type
38
+ */
21
39
  const readBody = (req) => {
22
40
  return new Promise((resolve, reject) => {
23
41
  if (hasPreParsedBody(req) && req.body !== void 0) {
@@ -61,15 +79,37 @@ const readBody = (req) => {
61
79
  toggleListeners(true);
62
80
  });
63
81
  };
82
+ /**
83
+ * Type guard that checks whether a request is an Express Request (has `originalUrl`).
84
+ * @param req - A Node IncomingMessage or Express Request
85
+ * @returns True if the request is an Express Request
86
+ */
64
87
  const isExpressRequest = (req) => {
65
88
  return "originalUrl" in req;
66
89
  };
90
+ /**
91
+ * Type guard that checks whether a response is an Express Response (has `json` and `send` methods).
92
+ * @param res - A Node ServerResponse or Express Response
93
+ * @returns True if the response is an Express Response
94
+ */
67
95
  const isExpressResponse = (res) => {
68
96
  return "json" in res && "send" in res;
69
97
  };
98
+ /**
99
+ * Type guard that checks whether a request has a pre-parsed body (`body` property).
100
+ * Used to detect if a body-parser middleware already consumed the stream.
101
+ * @param req - A Node IncomingMessage or Express Request
102
+ * @returns True if the request has a body property
103
+ */
70
104
  const hasPreParsedBody = (req) => {
71
105
  return "body" in req;
72
106
  };
107
+ /**
108
+ * Extracts normalized request details from an Express or Node IncomingMessage.
109
+ * Parses the URL to extract pathname, search string, and search params.
110
+ * @param request - Express or Node.js request object
111
+ * @returns Normalized request details including URL, headers, and method
112
+ */
73
113
  const getRequestDetails = (request) => {
74
114
  const rawUrl = isExpressRequest(request) ? request.originalUrl : request.url;
75
115
  const url = new URL(rawUrl, "http://localhost");
@@ -81,6 +121,12 @@ const getRequestDetails = (request) => {
81
121
  method: request.method
82
122
  };
83
123
  };
124
+ /**
125
+ * Wraps an Express or Node ServerResponse with a uniform API for setting headers,
126
+ * status codes, and sending JSON responses. Handles the Express vs raw Node API differences.
127
+ * @param response - Express or Node.js server response object
128
+ * @returns A ResponseDetails object with setHeader, setStatusCode, and sendResponse helpers
129
+ */
84
130
  const getResponseDetails = (response) => {
85
131
  const isResponseSent = response.headersSent || response.writableEnded;
86
132
  const setHeader = (name, value) => {
@@ -107,17 +153,40 @@ const getResponseDetails = (response) => {
107
153
  };
108
154
  //#endregion
109
155
  //#region src/tools.ts
156
+ /**
157
+ * Escapes special regex metacharacters in a string.
158
+ * Used to safely embed user-configurable values (like rpcPrefix) into regular expressions,
159
+ * preventing ReDoS and regex injection attacks.
160
+ * @param s - The raw string to escape
161
+ * @returns The escaped string safe for use in new RegExp()
162
+ */
110
163
  function escapeRegExp(s) {
111
164
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
112
165
  }
113
166
  //#endregion
167
+ //#region src/constants.ts
168
+ const FUNCTION_NOT_FOUND = "Function not found";
169
+ const METHOD_NOT_ALLOWED = "Method Not Allowed";
170
+ const REQUEST_FORBIDDEN = "Forbidden";
171
+ const INTERNAL_SERVER_ERROR = "Internal Server Error";
172
+ const CLIENT_DISCONNECTED = "client disconnected";
173
+ /** Returns a warning when a middleware name is reused, preventing registration conflicts. @param name - The duplicate middleware name */
174
+ const MIDDLEWARE_NAME_USED = (name) => `The middleware name "${name}" is already used.`;
175
+ //#endregion
114
176
  //#region src/express/createMiddleware.ts
115
177
  let middlewareCount = 0;
116
178
  const middlewareStack = /* @__PURE__ */ new Set();
179
+ /**
180
+ * Creates an Express middleware with optional path and rpcPrefix filtering.
181
+ * Middleware names are deduplicated — reusing a name throws an error.
182
+ * Prefix and path regexes are compiled once at creation time (hoisted) for performance.
183
+ * @param initialOptions - Options for rpcPrefix, path matching, and the handler function
184
+ * @returns An Express middleware function
185
+ */
117
186
  const createMiddleware = (initialOptions = {}) => {
118
187
  const options = Object.assign({}, defaultMiddlewareOptions, initialOptions);
119
188
  const middlewareName = options.name;
120
- const rpcPreffix = options.rpcPreffix;
189
+ const rpcPrefix = options.rpcPrefix;
121
190
  const path = options.path;
122
191
  const handler = options.handler;
123
192
  let name = middlewareName;
@@ -125,50 +194,74 @@ const createMiddleware = (initialOptions = {}) => {
125
194
  name = "viteRPCMiddleware-" + middlewareCount;
126
195
  middlewareCount += 1;
127
196
  }
128
- if (middlewareStack.has(name)) throw new Error(`The middleware name "${name}" is already used.`);
197
+ if (middlewareStack.has(name)) throw new Error(MIDDLEWARE_NAME_USED(name));
129
198
  middlewareStack.add(name);
130
- const prefixRegex = rpcPreffix ? new RegExp(`^/${escapeRegExp(rpcPreffix)}/`) : null;
199
+ const prefixRegex = rpcPrefix ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`) : null;
131
200
  const pathMatcher = path ? typeof path === "string" ? new RegExp(path) : path : null;
132
- const middlewareHandler = async (req, _res, next) => {
201
+ const middlewareHandler = async (req, res, next) => {
133
202
  const { url } = getRequestDetails(req);
134
203
  if (serverFunctionsMap.size === 0) await scanForServerFiles();
135
204
  if (!handler) return next?.();
136
205
  if (pathMatcher && !pathMatcher.test(url)) return next?.();
137
206
  if (prefixRegex && !prefixRegex.test(url)) return next?.();
138
- await handler(req, _res, next);
207
+ await handler(req, res, next);
139
208
  };
140
209
  Object.defineProperty(middlewareHandler, "name", { value: name });
141
210
  return middlewareHandler;
142
211
  };
212
+ /**
213
+ * Creates the Express RPC middleware that routes incoming requests to registered server functions.
214
+ * Reads the request body, dispatches to the matching function via serverFunctionsMap,
215
+ * and sends the JSON-serialized result. Handles client disconnection via abort signals.
216
+ * @param initialOptions - Options including rpcPrefix for URL routing
217
+ * @returns An Express middleware function
218
+ */
143
219
  const createRPCMiddleware = (initialOptions = {}) => {
144
- const options = Object.assign({}, defaultMiddlewareOptions, { rpcPreffix: defaultRPCOptions.rpcPreffix }, initialOptions);
145
- const rpcPreffix = options.rpcPreffix;
146
- const prefixRegex = rpcPreffix ? new RegExp(`^/${escapeRegExp(rpcPreffix)}/`) : null;
147
- const prefixReplace = `/${rpcPreffix}/`;
220
+ const options = Object.assign({}, defaultMiddlewareOptions, { rpcPrefix: defaultRPCOptions.rpcPrefix }, initialOptions);
221
+ const rpcPrefix = options.rpcPrefix;
222
+ const prefixRegex = rpcPrefix ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`) : null;
223
+ const prefixReplace = `/${rpcPrefix}/`;
148
224
  return createMiddleware({
149
225
  ...options,
150
226
  handler: async (req, res, _next) => {
151
- const { url } = getRequestDetails(req);
227
+ const { url: path, searchParams } = getRequestDetails(req);
152
228
  const { sendResponse } = getResponseDetails(res);
153
- if (prefixRegex && !prefixRegex.test(url)) return;
154
- const functionName = url.replace(prefixReplace, "");
229
+ if (prefixRegex && !prefixRegex.test(path)) return;
230
+ const origin = options.origin;
231
+ const requestOrigin = req.headers.origin;
232
+ if (origin && requestOrigin && requestOrigin !== origin) {
233
+ sendResponse(403, { error: REQUEST_FORBIDDEN });
234
+ return;
235
+ }
236
+ const functionName = path.replace(prefixReplace, "");
155
237
  const serverFunction = serverFunctionsMap.get(functionName);
156
238
  if (!serverFunction) {
157
- sendResponse(404, { error: "Function not found" });
239
+ sendResponse(404, { error: FUNCTION_NOT_FOUND });
158
240
  return;
159
241
  }
160
242
  try {
161
- const body = await readBody(req);
162
- const args = Array.isArray(body.data) ? body.data : [body.data];
243
+ const method = serverFunction.options?.method || "POST";
244
+ if (req.method?.toUpperCase() !== method) {
245
+ sendResponse(405, { error: METHOD_NOT_ALLOWED });
246
+ return;
247
+ }
248
+ let args = [];
249
+ if (method === "GET") {
250
+ const raw = searchParams.get("args");
251
+ if (raw) args = JSON.parse(raw);
252
+ } else {
253
+ const body = await readBody(req);
254
+ args = Array.isArray(body.data) ? body.data : [body.data];
255
+ }
163
256
  const { data, cancel } = serverFunction.handler(...args);
164
- const onClose = () => cancel("client disconnected");
257
+ const onClose = () => cancel(CLIENT_DISCONNECTED);
165
258
  req.on("close", onClose);
166
259
  const result = await data;
167
260
  req.off("close", onClose);
168
261
  if (!res.headersSent) sendResponse(200, { data: result });
169
262
  } catch (err) {
170
263
  console.error(String(err));
171
- sendResponse(500, { error: "Internal Server Error" });
264
+ sendResponse(500, { error: INTERNAL_SERVER_ERROR });
172
265
  }
173
266
  }
174
267
  });
@@ -1 +1 @@
1
- {"version":3,"file":"express.mjs","names":[],"sources":["../../src/options.ts","../../src/express/helpers.ts","../../src/tools.ts","../../src/express/createMiddleware.ts"],"sourcesContent":["import type {\n MiddlewareOptions,\n RpcPluginOptions,\n ServerFunctionOptions,\n} from \"./types.d.ts\";\n\nexport const defaultServerFnOptions = {\n contentType: \"application/json\",\n} satisfies ServerFunctionOptions;\n\nexport const defaultRPCOptions: RpcPluginOptions = {\n rpcPreffix: \"__rpc\",\n adapter: \"express\",\n};\n\nexport const defaultMiddlewareOptions = {\n rpcPreffix: undefined,\n path: undefined,\n} satisfies MiddlewareOptions;\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 { Buffer } from \"node:buffer\";\nimport type { ViteDevServer } from \"vite\";\nimport type { Express } from \"express\";\nimport { createRPCMiddleware } from \"./createMiddleware.ts\";\n\nexport async function attachRPC(app: Express) {\n const { loadRPCConfig } = await import(\"@thednp/rpc\");\n const { adapter: _adapter, ...options } = await loadRPCConfig();\n app.use(createRPCMiddleware(options));\n}\n\nexport function attachVite(app: Express, vite: ViteDevServer) {\n app.use(vite.middlewares);\n}\n\n// src/express/helpers.ts\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 resolve({\n contentType: isJSON ? \"application/json\" : \"text/plain\",\n data: isJSON ? req.body : 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 try {\n const data = JSON.parse(body);\n resolve({\n contentType: isJSON ? \"application/json\" : \"text/plain\",\n data,\n });\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\nexport const isExpressRequest = (\n req: IncomingMessage | ExpressRequest,\n): req is ExpressRequest => {\n return \"originalUrl\" in req;\n};\n\nexport const isExpressResponse = (\n res: ServerResponse | ExpressResponse,\n): res is ExpressResponse => {\n return \"json\" in res && \"send\" in res;\n};\n\nexport const hasPreParsedBody = (\n req: IncomingMessage | ExpressRequest,\n): req is ExpressRequest => {\n return \"body\" in req;\n};\n\nexport const getRequestDetails = (\n request: ExpressRequest | IncomingMessage,\n) => {\n const rawUrl = (\n isExpressRequest(request) ? request.originalUrl : request.url\n ) as string;\n const url = new URL(rawUrl, \"http://localhost\");\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\nexport const getResponseDetails = (\n response: ExpressResponse | ServerResponse,\n) => {\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: Record<string, 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","export function escapeRegExp(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\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\";\n// import type { JsonArray, JsonValue } from \"@thednp/rpc\";\nimport { scanForServerFiles, serverFunctionsMap } from \"@thednp/rpc/server\";\nimport { defaultMiddlewareOptions, defaultRPCOptions } from \"../options.ts\";\nimport { getRequestDetails, getResponseDetails, readBody } from \"./helpers.ts\";\nimport { escapeRegExp } from \"../tools.ts\";\n\nlet middlewareCount = 0;\nconst middlewareStack = new Set<string>();\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 rpcPreffix = options.rpcPreffix;\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(`The middleware name \"${name}\" is already used.`);\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 = rpcPreffix\n ? new RegExp(`^/${escapeRegExp(rpcPreffix)}/`)\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 // When serving from production server, scan for server files\n if (serverFunctionsMap.size === 0) {\n await scanForServerFiles();\n }\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 // rpcPreffix matching (boundary-safe via escaped regex)\n if (prefixRegex && !prefixRegex.test(url)) {\n return next?.();\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// Create RPC middleware\nexport const createRPCMiddleware: ExpressMiddlewareFn = (\n initialOptions = {},\n) => {\n const options = Object.assign(\n {},\n defaultMiddlewareOptions,\n { rpcPreffix: defaultRPCOptions.rpcPreffix },\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 rpcPreffix = options.rpcPreffix;\n const prefixRegex = rpcPreffix\n ? new RegExp(`^/${escapeRegExp(rpcPreffix)}/`)\n : /* istanbul ignore next */ null;\n const prefixReplace = `/${rpcPreffix}/`;\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 } = 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(url)) {\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 const functionName = url.replace(prefixReplace, \"\");\n const serverFunction = serverFunctionsMap.get(functionName);\n\n if (!serverFunction) {\n sendResponse(404, { error: \"Function not found\" });\n return;\n }\n\n try {\n const body = await readBody(req);\n const args = Array.isArray(body.data) ? body.data : [body.data];\n const { data, cancel } = serverFunction.handler(...args);\n const onClose = () => cancel(\"client disconnected\");\n\n req.on(\"close\", onClose);\n const result = await data;\n req.off(\"close\", onClose);\n\n // istanbul ignore else\n if (!res.headersSent) sendResponse(200, { data: result });\n } catch (err) {\n console.error(String(err));\n sendResponse(500, { error: \"Internal Server Error\" });\n }\n },\n });\n};\n"],"mappings":";;AAUA,MAAa,oBAAsC;CACjD,YAAY;CACZ,SAAS;AACX;AAEA,MAAa,2BAA2B;CACtC,YAAY,KAAA;CACZ,MAAM,KAAA;AACR;;;ACN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AGF,MAAM,eAAe,IAAI,QAAQ,eAAe,EAAE;GAClD,MAAM,iBAAiB,mBAAmB,IAAI,YAAY;GAE1D,IAAI,CAAC,gBAAgB;IACnB,aAAa,KAAK,EAAE,OAAO,qBAAqB,CAAC;IACjD;GACF;GAEA,IAAI;IACF,MAAM,OAAO,MAAM,SAAS,GAAG;IAC/B,MAAM,OAAO,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;IAC9D,MAAM,EAAE,MAAM,WAAW,eAAe,QAAQ,GAAG,IAAI;IACvD,MAAM,gBAAgB,OAAO,qBAAqB;IAElD,IAAI,GAAG,SAAS,OAAO;IACvB,MAAM,SAAS,MAAM;IACrB,IAAI,IAAI,SAAS,OAAO;IAGxB,IAAI,CAAC,IAAI,aAAa,aAAa,KAAK,EAAE,MAAM,OAAO,CAAC;GAC1D,SAAS,KAAK;IACZ,QAAQ,MAAM,OAAO,GAAG,CAAC;IACzB,aAAa,KAAK,EAAE,OAAO,wBAAwB,CAAC;GACtD;EACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"express.mjs","names":[],"sources":["../../src/options.ts","../../src/express/helpers.ts","../../src/tools.ts","../../src/constants.ts","../../src/express/createMiddleware.ts"],"sourcesContent":["import type {\n MiddlewareOptions,\n RpcPluginOptions,\n ServerFunctionOptions,\n} from \"./types.d.ts\";\n\nexport const defaultServerFnOptions = {\n contentType: \"application/json\",\n credentials: \"same-origin\",\n method: \"POST\",\n} satisfies ServerFunctionOptions;\n\nexport const defaultRPCOptions: RpcPluginOptions = {\n rpcPrefix: \"__rpc\",\n adapter: \"express\",\n};\n\nexport const defaultMiddlewareOptions = {\n rpcPrefix: undefined,\n path: undefined,\n origin: undefined,\n} satisfies MiddlewareOptions;\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\";\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 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 resolve({\n contentType: isJSON ? \"application/json\" : \"text/plain\",\n data: isJSON ? req.body : 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 try {\n const data = JSON.parse(body);\n resolve({\n contentType: isJSON ? \"application/json\" : \"text/plain\",\n data,\n });\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 * 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 = new URL(rawUrl, \"http://localhost\");\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: Record<string, 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","/**\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","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 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 = ` ⚡︎ No RPC config found, loading the defaults..`;\n\nexport const FAILED_LOAD_CONFIG = ` ⚠︎ Failed to load RPC config:`;\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\";\n// import type { JsonArray, JsonValue } from \"@thednp/rpc\";\nimport type { JsonValue } from \"../types.d.ts\";\nimport { scanForServerFiles, serverFunctionsMap } from \"@thednp/rpc/server\";\nimport { defaultMiddlewareOptions, defaultRPCOptions } from \"../options.ts\";\nimport { getRequestDetails, getResponseDetails, readBody } from \"./helpers.ts\";\nimport { escapeRegExp } from \"../tools.ts\";\nimport {\n CLIENT_DISCONNECTED,\n FUNCTION_NOT_FOUND,\n INTERNAL_SERVER_ERROR,\n METHOD_NOT_ALLOWED,\n MIDDLEWARE_NAME_USED,\n REQUEST_FORBIDDEN,\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 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 // When serving from production server, scan for server files\n if (serverFunctionsMap.size === 0) {\n await scanForServerFiles();\n }\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 // 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 serverFunctionsMap,\n * and sends the JSON-serialized result. Handles client disconnection via abort signals.\n * @param initialOptions - Options including rpcPrefix for URL routing\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 prefixRegex = rpcPrefix\n ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`)\n : /* istanbul ignore next */ null;\n const prefixReplace = `/${rpcPrefix}/`;\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 does not\n // match the configured origin. Requests without an Origin header\n // (curl, native clients) pass through unchecked.\n const origin = options.origin;\n const requestOrigin = req.headers.origin;\n if (origin && requestOrigin && requestOrigin !== origin) {\n sendResponse(403, { error: REQUEST_FORBIDDEN });\n return;\n }\n\n const functionName = path.replace(prefixReplace, \"\");\n const serverFunction = serverFunctionsMap.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 // istanbul ignore else\n if (raw) args = JSON.parse(raw);\n } else {\n const body = await readBody(req);\n args = Array.isArray(body.data) ? body.data : [body.data];\n }\n const { data, cancel } = serverFunction.handler(...args);\n const onClose = () => cancel(CLIENT_DISCONNECTED);\n\n req.on(\"close\", onClose);\n const result = await data;\n req.off(\"close\", onClose);\n\n // istanbul ignore else\n if (!res.headersSent) sendResponse(200, { data: result });\n } catch (err) {\n console.error(String(err));\n sendResponse(500, { error: INTERNAL_SERVER_ERROR });\n }\n },\n });\n};\n"],"mappings":";;AAYA,MAAa,oBAAsC;CACjD,WAAW;CACX,SAAS;AACX;AAEA,MAAa,2BAA2B;CACtC,WAAW,KAAA;CACX,MAAM,KAAA;CACN,QAAQ,KAAA;AACV;;;;;;;;ACHA,eAAsB,UAAU,KAAc;CAC5C,MAAM,EAAE,kBAAkB,MAAM,OAAO;CACvC,MAAM,EAAE,SAAS,UAAU,GAAG,YAAY,MAAM,cAAc;CAC9D,IAAI,IAAI,oBAAoB,OAAO,CAAC;AACtC;;;;;;AAOA,SAAgB,WAAW,KAAc,MAAqB;CAC5D,IAAI,IAAI,KAAK,WAAW;AAC1B;;;;;;;;AASA,MAAa,YACX,QACwB;CACxB,OAAO,IAAI,SAAS,SAAS,WAAW;EAGtC,IAAI,iBAAiB,GAAG,KAAK,IAAI,SAAS,KAAA,GAAW;GAGnD,MAAM,UADc,IAAI,QAAQ,eAAe,EAAE,YAAY,KAAK,GAAA,CACvC,SAAS,MAAM;GAC1C,QAAQ;IACN,aAAa,SAAS,qBAAqB;IAC3C,MAAM,SAAS,IAAI,OAAO,OAAO,IAAI,IAAI;GAC3C,CAAe;GACf;EACF;EAGA,IAAI,OAAO;EAEX,MAAM,mBAAmB,QAAkB;GACzC,MAAM,SAAS,MAAM,OAAO;GAC5B,IAAI,OAAO,CAAC,QAAQ,MAAM;GAC1B,IAAI,OAAO,CAAC,OAAO,KAAK;GACxB,IAAI,OAAO,CAAC,SAAS,OAAO;EAC9B;EAEA,MAAM,UAAU,UAAkB;GAChC,QAAQ,MAAM,SAAS;EACzB;EAEA,MAAM,cAAc;GAClB,gBAAgB;GAEhB,MAAM,UADe,IAAI,QAAQ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MAAM,SAAS,GAAG;KAC/B,OAAO,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,OAAO,CAAC,KAAK,IAAI;IAC1D;IACA,MAAM,EAAE,MAAM,WAAW,eAAe,QAAQ,GAAG,IAAI;IACvD,MAAM,gBAAgB,OAAO,mBAAmB;IAEhD,IAAI,GAAG,SAAS,OAAO;IACvB,MAAM,SAAS,MAAM;IACrB,IAAI,IAAI,SAAS,OAAO;IAGxB,IAAI,CAAC,IAAI,aAAa,aAAa,KAAK,EAAE,MAAM,OAAO,CAAC;GAC1D,SAAS,KAAK;IACZ,QAAQ,MAAM,OAAO,GAAG,CAAC;IACzB,aAAa,KAAK,EAAE,OAAO,sBAAsB,CAAC;GACpD;EACF;CACF,CAAC;AACH"}
@@ -4,23 +4,59 @@ import { ViteDevServer } from "vite";
4
4
  import "express";
5
5
  import "hono";
6
6
  import "@hono/node-server";
7
+ import "hono/factory";
7
8
  import "koa";
8
9
  //#region src/fastify/types.d.ts
10
+ /**
11
+ * Fastify-specific middleware options, constrained to the `"fastify"` adapter.
12
+ */
9
13
  type FastifyMiddlewareOptions = MiddlewareOptions<"fastify">;
14
+ /**
15
+ * Fastify middleware factory: takes optional initial options and returns
16
+ * the Fastify-compatible handler.
17
+ */
10
18
  type FastifyMiddlewareFn = <A extends RpcPluginOptions["adapter"] = "fastify">(initialOptions?: Partial<FastifyMiddlewareOptions>) => FastifyMiddlewareHooks["handler"];
19
+ /**
20
+ * Fastify middleware handler signature used by the RPC middleware.
21
+ */
11
22
  interface FastifyMiddlewareHooks {
23
+ /**
24
+ * The handler invoked for each matched request.
25
+ * @param req - Fastify request object
26
+ * @param res - Fastify reply object
27
+ * @param done - Fastify hook completion callback
28
+ */
12
29
  handler: (req: FastifyRequest, res: FastifyReply, done: HookHandlerDoneFunction) => Promise<void>;
13
30
  }
14
- // Define the plugin function
31
+ /**
32
+ * Options accepted by the Fastify RPC plugin (`fp()`-wrapped registration).
33
+ */
15
34
  type RpcFastifyPluginOptions = MiddlewareOptions<"fastify"> & {
35
+ /** Whether this is an RPC plugin registration */
16
36
  isRPC: boolean;
17
37
  };
18
38
  //#endregion
19
39
  //#region src/fastify/createMiddleware.d.ts
40
+ /**
41
+ * Creates a Fastify preHandler hook with optional path and rpcPrefix filtering.
42
+ * Middleware names are deduplicated. Prefix and path regexes are compiled once at creation time.
43
+ * @param initialOptions - Options for rpcPrefix, path matching, and the handler function
44
+ * @returns A Fastify preHandler hook function
45
+ */
20
46
  declare const createMiddleware: FastifyMiddlewareFn;
47
+ /**
48
+ * Creates the Fastify RPC middleware that routes incoming requests to registered server functions.
49
+ * Wraps the generic createMiddleware with the RPC handler that reads the body, dispatches
50
+ * to the matching function, and sends the JSON-serialized result.
51
+ * @param initialOptions - Options including rpcPrefix for URL routing
52
+ * @returns A Fastify preHandler hook function
53
+ */
21
54
  declare const createRPCMiddleware: FastifyMiddlewareFn;
22
55
  //#endregion
23
56
  //#region src/types.d.ts
57
+ /**
58
+ * Parsed request body result discriminated by content type.
59
+ */
24
60
  type BodyResult = {
25
61
  contentType: "application/json";
26
62
  data: JsonValue;
@@ -29,16 +65,45 @@ type BodyResult = {
29
65
  data: string;
30
66
  };
31
67
  // primitives and their compositions
68
+ /**
69
+ * Primitive JSON values, including `undefined` for optional parameters.
70
+ */
32
71
  type JsonPrimitive = string | number | boolean | null | undefined;
72
+ /**
73
+ * A JSON object whose values are JSON values or arrays.
74
+ */
33
75
  type JsonObject = {
34
76
  [key: string]: JsonValue | JsonArray;
35
77
  };
78
+ /**
79
+ * A JSON array of JSON values.
80
+ */
36
81
  type JsonArray = JsonValue[];
82
+ /**
83
+ * Any JSON-serializable value: primitive, array, or object.
84
+ */
37
85
  type JsonValue = JsonPrimitive | JsonArray | JsonObject;
38
86
  //#endregion
39
87
  //#region src/fastify/helpers.d.ts
88
+ /**
89
+ * Convenience function to load RPC config and register the RPC plugin to a Fastify instance.
90
+ * Dynamically imports loadRPCConfig and registers the fastify-rpc plugin.
91
+ * @param app - Fastify instance
92
+ */
40
93
  declare function attachRPC(app: FastifyInstance): Promise<void>;
94
+ /**
95
+ * Attaches Vite's dev server middlewares to a Fastify instance for development mode.
96
+ * Uses an `onRequest` hook to delegate to Vite's connect-compatible middleware stack.
97
+ * @param app - Fastify instance
98
+ * @param vite - Running Vite dev server
99
+ */
41
100
  declare function attachVite(app: FastifyInstance, vite: ViteDevServer): void;
101
+ /**
102
+ * Reads and parses the HTTP request body from a Fastify request.
103
+ * If Fastify's body parser already consumed the stream, uses the pre-parsed body from `req.body`.
104
+ * @param req - Fastify request object
105
+ * @returns A promise resolving to the parsed body with its content type
106
+ */
42
107
  declare const readBody: (req: FastifyRequest) => Promise<BodyResult>;
43
108
  //#endregion
44
109
  export { type FastifyMiddlewareFn, type FastifyMiddlewareHooks, type FastifyMiddlewareOptions, type RpcFastifyPluginOptions, attachRPC, attachVite, createMiddleware, createRPCMiddleware, readBody };
@@ -1 +1 @@
1
- {"version":3,"file":"fastify.d.mts","names":[],"sources":["../../src/fastify/types.d.ts","../../src/fastify/createMiddleware.ts","../../src/types.d.ts","../../src/fastify/helpers.ts"],"mappings":";;;;;;;;KAOY,2BAA2B;KAE3B,uBACV,UAAU,yCAEV,iBAAiB,QAAQ,8BACtB;UAEY;EACf,UACE,KAAK,gBACL,KAAK,cACL,MAAM,4BACH;;;KAIK,0BAA0B;EACpC;;;;cCLW,kBAAkB;cAyElB,qBAAqB;;;KCxDtB;EACN;EAAiC,MAAM;;EACvC;EAA2B;;;KAOrB;KACA;GAAgB,cAAc,YAAY;;KAC1C,YAAY;KACZ,YAAY,gBAAgB,YAAY;;;iBCzC9B,UAAU,KAAK,kBAAe;iBAMpC,WAAW,KAAK,iBAAiB,MAAM;cAU1C,WAAQ,KACd,mBACJ,QAAQ"}
1
+ {"version":3,"file":"fastify.d.mts","names":[],"sources":["../../src/fastify/types.d.ts","../../src/fastify/createMiddleware.ts","../../src/types.d.ts","../../src/fastify/helpers.ts"],"mappings":";;;;;;;;;;;;KAUY,2BAA2B;;;;;KAM3B,uBACV,UAAU,yCAEV,iBAAiB,QAAQ,8BACtB;;;;UAKY;;;;;;;EAOf,UACE,KAAK,gBACL,KAAK,cACL,MAAM,4BACH;;;;;KAMK,0BAA0B;;EAEpC;;;;;;;;;;cCXW,kBAAkB;;;;;;;;cAgFlB,qBAAqB;;;;;;KC9CtB;EACN;EAAiC,MAAM;;EACvC;EAA2B;;;;;;KA8BrB;;;;KAIA;GAAgB,cAAc,YAAY;;;;;KAI1C,YAAY;;;;KAIZ,YAAY,gBAAgB,YAAY;;;;;;;;iBClG9B,UAAU,KAAK,kBAAe;;;;;;;iBAYpC,WAAW,KAAK,iBAAiB,MAAM;;;;;;;cAgB1C,WAAQ,KACd,mBACJ,QAAQ"}
@@ -2,20 +2,43 @@ import { scanForServerFiles, serverFunctionsMap } from "@thednp/rpc/server";
2
2
  import fp from "fastify-plugin";
3
3
  //#region src/options.ts
4
4
  const defaultRPCOptions = {
5
- rpcPreffix: "__rpc",
5
+ rpcPrefix: "__rpc",
6
6
  adapter: "express"
7
7
  };
8
8
  const defaultMiddlewareOptions = {
9
- rpcPreffix: void 0,
10
- path: void 0
9
+ rpcPrefix: void 0,
10
+ path: void 0,
11
+ origin: void 0
11
12
  };
12
13
  //#endregion
13
14
  //#region src/tools.ts
15
+ /**
16
+ * Escapes special regex metacharacters in a string.
17
+ * Used to safely embed user-configurable values (like rpcPrefix) into regular expressions,
18
+ * preventing ReDoS and regex injection attacks.
19
+ * @param s - The raw string to escape
20
+ * @returns The escaped string safe for use in new RegExp()
21
+ */
14
22
  function escapeRegExp(s) {
15
23
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
16
24
  }
17
25
  //#endregion
26
+ //#region src/constants.ts
27
+ const FUNCTION_NOT_FOUND = "Function not found";
28
+ const METHOD_NOT_ALLOWED = "Method Not Allowed";
29
+ const REQUEST_FORBIDDEN = "Forbidden";
30
+ const INTERNAL_SERVER_ERROR = "Internal Server Error";
31
+ const CLIENT_DISCONNECTED = "client disconnected";
32
+ /** Returns a warning when a middleware name is reused, preventing registration conflicts. @param name - The duplicate middleware name */
33
+ const MIDDLEWARE_NAME_USED = (name) => `The middleware name "${name}" is already used.`;
34
+ //#endregion
18
35
  //#region src/fastify/plugin.ts
36
+ /**
37
+ * Fastify plugin factory that registers the RPC middleware as a preHandler hook.
38
+ * @param fastify - Fastify instance
39
+ * @param initialOptions - Middleware options including rpcPrefix
40
+ * @param done - Callback to signal plugin registration completion
41
+ */
19
42
  const RpcPlugin = (fastify, initialOptions, done) => {
20
43
  const rpcMiddleware = createRPCMiddleware(initialOptions);
21
44
  fastify.addHook("preHandler", async (request, reply) => {
@@ -29,11 +52,22 @@ const RpcPlugin = (fastify, initialOptions, done) => {
29
52
  const rpcPlugin = fp(RpcPlugin, { name: "uni-rpc-fastify-plugin" });
30
53
  //#endregion
31
54
  //#region src/fastify/helpers.ts
55
+ /**
56
+ * Convenience function to load RPC config and register the RPC plugin to a Fastify instance.
57
+ * Dynamically imports loadRPCConfig and registers the fastify-rpc plugin.
58
+ * @param app - Fastify instance
59
+ */
32
60
  async function attachRPC(app) {
33
61
  const { loadRPCConfig } = await import("@thednp/rpc");
34
62
  const { adapter: _adapter, ...options } = await loadRPCConfig();
35
63
  await app.register(rpcPlugin, options);
36
64
  }
65
+ /**
66
+ * Attaches Vite's dev server middlewares to a Fastify instance for development mode.
67
+ * Uses an `onRequest` hook to delegate to Vite's connect-compatible middleware stack.
68
+ * @param app - Fastify instance
69
+ * @param vite - Running Vite dev server
70
+ */
37
71
  function attachVite(app, vite) {
38
72
  app.addHook("onRequest", async (request, reply) => {
39
73
  const next = () => new Promise((resolve) => {
@@ -42,6 +76,12 @@ function attachVite(app, vite) {
42
76
  await next();
43
77
  });
44
78
  }
79
+ /**
80
+ * Reads and parses the HTTP request body from a Fastify request.
81
+ * If Fastify's body parser already consumed the stream, uses the pre-parsed body from `req.body`.
82
+ * @param req - Fastify request object
83
+ * @returns A promise resolving to the parsed body with its content type
84
+ */
45
85
  const readBody = (req) => {
46
86
  return new Promise((resolve, reject) => {
47
87
  const contentType = req.headers["content-type"]?.toLowerCase() || "";
@@ -91,10 +131,16 @@ const readBody = (req) => {
91
131
  //#region src/fastify/createMiddleware.ts
92
132
  let middlewareCount = 0;
93
133
  const middlewareStack = /* @__PURE__ */ new Set();
134
+ /**
135
+ * Creates a Fastify preHandler hook with optional path and rpcPrefix filtering.
136
+ * Middleware names are deduplicated. Prefix and path regexes are compiled once at creation time.
137
+ * @param initialOptions - Options for rpcPrefix, path matching, and the handler function
138
+ * @returns A Fastify preHandler hook function
139
+ */
94
140
  const createMiddleware = (initialOptions = {}) => {
95
141
  const options = Object.assign({}, defaultMiddlewareOptions, initialOptions);
96
142
  const middlewareName = options.name;
97
- const rpcPreffix = options.rpcPreffix;
143
+ const rpcPrefix = options.rpcPrefix;
98
144
  const path = options.path;
99
145
  const handler = options.handler;
100
146
  let name = middlewareName;
@@ -102,11 +148,11 @@ const createMiddleware = (initialOptions = {}) => {
102
148
  name = "viteRPCMiddleware-" + middlewareCount;
103
149
  middlewareCount += 1;
104
150
  }
105
- if (middlewareStack.has(name)) throw new Error(`The middleware name "${name}" is already used.`);
151
+ if (middlewareStack.has(name)) throw new Error(MIDDLEWARE_NAME_USED(name));
106
152
  middlewareStack.add(name);
107
- const prefixRegex = rpcPreffix ? new RegExp(`^/${escapeRegExp(rpcPreffix)}/`) : null;
153
+ const prefixRegex = rpcPrefix ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`) : null;
108
154
  const pathMatcher = path ? typeof path === "string" ? new RegExp(path) : path : null;
109
- const middlewareHandler = async (req, _reply, done) => {
155
+ const middlewareHandler = async (req, reply, done) => {
110
156
  const url = new URL(req.url, "http://localhost").pathname;
111
157
  if (serverFunctionsMap.size === 0) await scanForServerFiles();
112
158
  if (!handler) {
@@ -121,39 +167,64 @@ const createMiddleware = (initialOptions = {}) => {
121
167
  done();
122
168
  return;
123
169
  }
124
- await handler(req, _reply, done);
170
+ await handler(req, reply, done);
125
171
  };
126
172
  Object.defineProperty(middlewareHandler, "name", { value: name });
127
173
  return middlewareHandler;
128
174
  };
175
+ /**
176
+ * Creates the Fastify RPC middleware that routes incoming requests to registered server functions.
177
+ * Wraps the generic createMiddleware with the RPC handler that reads the body, dispatches
178
+ * to the matching function, and sends the JSON-serialized result.
179
+ * @param initialOptions - Options including rpcPrefix for URL routing
180
+ * @returns A Fastify preHandler hook function
181
+ */
129
182
  const createRPCMiddleware = (initialOptions = {}) => {
130
- const options = Object.assign({}, defaultMiddlewareOptions, { rpcPreffix: defaultRPCOptions.rpcPreffix }, initialOptions);
131
- const rpcPreffix = options.rpcPreffix;
132
- const prefixRegex = rpcPreffix ? new RegExp(`^/${escapeRegExp(rpcPreffix)}/`) : null;
133
- const prefixReplace = `/${rpcPreffix}/`;
183
+ const options = Object.assign({}, defaultMiddlewareOptions, { rpcPrefix: defaultRPCOptions.rpcPrefix }, initialOptions);
184
+ const rpcPrefix = options.rpcPrefix;
185
+ const prefixRegex = rpcPrefix ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`) : null;
186
+ const prefixReplace = `/${rpcPrefix}/`;
134
187
  return createMiddleware({
135
188
  ...options,
136
189
  handler: async (req, reply, _done) => {
137
- const url = new URL(req.url, "http://localhost").pathname;
190
+ const reqUrl = new URL(req.url, "http://localhost");
191
+ const url = reqUrl.pathname;
138
192
  if (prefixRegex && !prefixRegex.test(url)) return;
193
+ const origin = options.origin;
194
+ const requestOrigin = req.headers.origin;
195
+ if (origin && requestOrigin && requestOrigin !== origin) {
196
+ reply.status(403).send({ error: REQUEST_FORBIDDEN });
197
+ return;
198
+ }
139
199
  const functionName = url.replace(prefixReplace, "");
140
200
  const serverFunction = serverFunctionsMap.get(functionName);
141
201
  if (!serverFunction) {
142
- reply.status(404).send({ error: "Function not found" });
202
+ reply.status(404).send({ error: FUNCTION_NOT_FOUND });
143
203
  return;
144
204
  }
145
205
  try {
146
- const body = await readBody(req);
147
- const args = Array.isArray(body.data) ? body.data : [body.data];
206
+ const method = serverFunction.options?.method || "POST";
207
+ if (req.method.toUpperCase() !== method) {
208
+ reply.status(405).send({ error: METHOD_NOT_ALLOWED });
209
+ return;
210
+ }
211
+ let args = [];
212
+ if (method === "GET") {
213
+ const raw = reqUrl.searchParams.get("args");
214
+ if (raw) args = JSON.parse(raw);
215
+ } else {
216
+ const body = await readBody(req);
217
+ args = Array.isArray(body.data) ? body.data : [body.data];
218
+ }
148
219
  const { data: dataResult, cancel } = serverFunction.handler(...args);
149
- const onClose = () => cancel("client disconnected");
220
+ const onClose = () => cancel(CLIENT_DISCONNECTED);
150
221
  req.raw.on("close", onClose);
151
222
  const data = await dataResult;
152
223
  req.raw.off("close", onClose);
153
224
  if (!reply.raw.headersSent) reply.status(200).send({ data });
154
225
  } catch (err) {
155
226
  console.error(String(err));
156
- reply.status(500).send({ error: "Internal Server Error" });
227
+ reply.status(500).send({ error: INTERNAL_SERVER_ERROR });
157
228
  }
158
229
  }
159
230
  });