@thednp/rpc 0.2.1 → 0.3.1

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 (41) hide show
  1. package/AGENTS.md +34 -19
  2. package/CHANGELOG.md +74 -0
  3. package/README.md +23 -10
  4. package/dist/config/config.d.mts +65 -0
  5. package/dist/config/config.d.mts.map +1 -0
  6. package/dist/config/config.mjs +24 -0
  7. package/dist/config/config.mjs.map +1 -0
  8. package/dist/express/express.d.mts +4 -2
  9. package/dist/express/express.d.mts.map +1 -1
  10. package/dist/express/express.mjs +41 -8
  11. package/dist/express/express.mjs.map +1 -1
  12. package/dist/fastify/fastify.d.mts.map +1 -1
  13. package/dist/fastify/fastify.mjs +37 -6
  14. package/dist/fastify/fastify.mjs.map +1 -1
  15. package/dist/fastify/plugin/fastify/plugin.d.mts +13 -0
  16. package/dist/fastify/plugin/fastify/plugin.d.mts.map +1 -1
  17. package/dist/fastify/plugin/fastify/plugin.mjs +37 -6
  18. package/dist/fastify/plugin/fastify/plugin.mjs.map +1 -1
  19. package/dist/h3/h3.d.mts.map +1 -1
  20. package/dist/h3/h3.mjs +47 -16
  21. package/dist/h3/h3.mjs.map +1 -1
  22. package/dist/helpers/helpers.d.mts +63 -5
  23. package/dist/helpers/helpers.d.mts.map +1 -1
  24. package/dist/helpers/helpers.mjs +58 -1
  25. package/dist/helpers/helpers.mjs.map +1 -1
  26. package/dist/hono/hono.d.mts.map +1 -1
  27. package/dist/hono/hono.mjs +37 -6
  28. package/dist/hono/hono.mjs.map +1 -1
  29. package/dist/index.d.mts +48 -12
  30. package/dist/index.d.mts.map +1 -1
  31. package/dist/index.mjs +92 -61
  32. package/dist/index.mjs.map +1 -1
  33. package/dist/koa/koa.d.mts.map +1 -1
  34. package/dist/koa/koa.mjs +47 -16
  35. package/dist/koa/koa.mjs.map +1 -1
  36. package/dist/server/server.d.mts +219 -26
  37. package/dist/server/server.d.mts.map +1 -1
  38. package/dist/server/server.mjs +108 -69
  39. package/dist/server/server.mjs.map +1 -1
  40. package/llms.txt +81 -0
  41. package/package.json +23 -19
package/AGENTS.md CHANGED
@@ -4,6 +4,7 @@
4
4
 
5
5
  ```bash
6
6
  pnpm dev # Run examples/spa dev server
7
+ pnpm dev:advanced # Run examples/advanced dev server
7
8
  pnpm dev:express # Run examples/express dev server
8
9
  pnpm dev:fastify # Run examples/fastify dev server
9
10
  pnpm dev:h3 # Run examples/h3 dev server
@@ -13,18 +14,23 @@ pnpm dev:react-query # Run examples/react-query dev server
13
14
  pnpm dev:solid-query # Run examples/solid-query dev server
14
15
  pnpm dev:ssr # Run examples/ssr dev server
15
16
  pnpm lint # Lint + typecheck (deno lint + tsc)
16
- pnpm test # Run tests with coverage
17
- pnpm test-ui # Run tests with UI
17
+ pnpm test # Run tests once with coverage (vitest run --coverage)
18
+ pnpm test:watch # Run tests in watch mode with coverage
19
+ pnpm test:ui # Run tests with UI
20
+ pnpm test:dev # Run examples in dev mode (scripts/dev-test)
21
+ pnpm test:prod # Run examples in prod preview (scripts/dev-test --mode=preview)
18
22
  pnpm lint:ts # deno lint src
19
23
  pnpm fix:ts # deno lint src --fix
20
24
  pnpm check:ts # tsc -noEmit
21
- pnpm format # deno fmt src
25
+ pnpm format # deno fmt src tests examples/**/src
26
+ pnpm clean # Remove build artifacts and caches
22
27
  pnpm build # tsdown (outputs to dist/)
23
28
  pnpm up:examples # Update all example deps (to latest published @thednp/rpc + latest example deps)
24
29
  pnpm up:examples:lib # Sync examples to the latest published @thednp/rpc version
25
30
  pnpm up:root # Update root deps
26
31
  pnpm up:deno # deno update + sync deno.json deps
27
32
  pnpm upd # Update all deps (up:examples + up:examples:lib + up:root)
33
+ pnpm audit:src # Audit src deps
28
34
  pnpm prepareOnly # upd + up:deno + lint + format + audit:src + build
29
35
  pnpm release # Publish npm + jsr (scripts/release.js)
30
36
  ```
@@ -35,19 +41,20 @@ pnpm release # Publish npm + jsr (scripts/release.js)
35
41
 
36
42
  ## Examples
37
43
 
38
- The `examples/` directory contains 9 example apps:
39
-
40
- | Example | Adapter | Type | Run Command | Config |
41
- | ----------------| -------------------------------------------------------------------| ------| -------------------------| -----------------------------------------|
42
- | `spa` | Vite dev server (no adapter) | SPA | `pnpm dev` | `examples/spa/rpc.config.ts` |
43
- | `express` | Express | SSR | `pnpm dev:express` | `examples/express/rpc.config.ts` |
44
- | `fastify` | Fastify | SSR | `pnpm dev:fastify` | `examples/fastify/rpc.config.ts` |
45
- | `h3` | h3 | SSR | `pnpm dev:h3` | `examples/h3/rpc.config.ts` |
46
- | `hono` | Hono | SSR | `pnpm dev:hono` | `examples/hono/rpc.config.ts` |
47
- | `koa` | Koa | SSR | `pnpm dev:koa` | `examples/koa/rpc.config.ts` |
48
- | `react-query` | Express (React + @tanstack/react-query SSR) | SSR | `pnpm dev:react-query` | `examples/react-query/rpc.config.ts` |
49
- | `solid-query` | Express (Solid + @tanstack/solid-query SSR) | SSR | `pnpm dev:solid-query` | `examples/solid-query/rpc.config.ts` |
50
- | `ssr` | Custom `http-express.ts` (Express-compatible `node:http` server ) | SSR | `pnpm dev:ssr` | `examples/ssr/rpc.config.ts` |
44
+ The `examples/` directory contains 10 example apps:
45
+
46
+ | Example | Adapter | Type | Run Command | Config |
47
+ | ---------------| -------------------------------------------------------------------| ------| ------------------------| --------------------------------------|
48
+ | `spa` | Vite dev server (no adapter) | SPA | `pnpm dev` | `examples/spa/rpc.config.ts` |
49
+ | `express` | Express | SSR | `pnpm dev:express` | `examples/express/rpc.config.ts` |
50
+ | `advanced` | Express | SSR | `pnpm dev:advanced` | `examples/advanced/rpc.config.ts` |
51
+ | `fastify` | Fastify | SSR | `pnpm dev:fastify` | `examples/fastify/rpc.config.ts` |
52
+ | `h3` | h3 | SSR | `pnpm dev:h3` | `examples/h3/rpc.config.ts` |
53
+ | `hono` | Hono | SSR | `pnpm dev:hono` | `examples/hono/rpc.config.ts` |
54
+ | `koa` | Koa | SSR | `pnpm dev:koa` | `examples/koa/rpc.config.ts` |
55
+ | `react-query` | Express (React + @tanstack/react-query SSR) | SSR | `pnpm dev:react-query` | `examples/react-query/rpc.config.ts` |
56
+ | `solid-query` | Express (Solid + @tanstack/solid-query SSR) | SSR | `pnpm dev:solid-query` | `examples/solid-query/rpc.config.ts` |
57
+ | `ssr` | Custom `http-express.ts` (Express-compatible `node:http` server ) | SSR | `pnpm dev:ssr` | `examples/ssr/rpc.config.ts` |
51
58
 
52
59
  Each example follows the same structure:
53
60
 
@@ -74,6 +81,7 @@ Each example follows the same structure:
74
81
  The tsdown.config.ts produces multiple entries:
75
82
 
76
83
  - `dist/index.mjs` — main Vite plugin
84
+ - `dist/config/config.mjs` — vite-free `defineConfig` (safe for serverless bundles)
77
85
  - `dist/server/server.mjs` — standalone server
78
86
  - `dist/express/express.mjs` — Express middleware
79
87
  - `dist/fastify/fastify.mjs` — Fastify middleware
@@ -108,9 +116,10 @@ The tsdown.config.ts produces multiple entries:
108
116
 
109
117
  - Vite plugin for creating server functions with automatic RPC generation
110
118
  - Server functions return `{ data: Promise<T>, cancel: (reason?: string) => void }` shape
111
- - Framework-agnostic core with adapters for Express, Fastify, Hono, and Koa
119
+ - Framework-agnostic core with adapters for Express, Fastify, Hono, Koa, and h3
112
120
  - Client modules are auto-generated with `AbortController` support for cancellation
113
121
  - Server-side caching must be handled by third party tools (e.g. `@tanstack/react-query`)
122
+ - **Multi-prefix support**: `createServerFunction(..., { rpcPrefix })` registers functions in a prefix-scoped map (`getFunctionsForPrefix`), so multiple RPC instances can coexist (versioned/namespaced APIs). All five adapters dispatch via `getFunctionsForPrefix(rpcPrefix || defaultPrefix)`; `serverFunctionsMap` is a backward-compatible proxy for the default `"__rpc"` prefix (`defaultPrefix`)
114
123
 
115
124
  ## Security & Hardening
116
125
 
@@ -118,8 +127,8 @@ The tsdown.config.ts produces multiple entries:
118
127
  - **Prefix regex injection prevention**: `rpcPrefix` config string is escaped via `escapeRegExp()` before being embedded in the boundary regex, preventing ReDoS or unintended matching from metacharacters in the prefix
119
128
  - **Regex compilation hoisted**: All prefix/path regexes are compiled once at middleware creation time (not per-request), eliminating per-request regex overhead
120
129
  - **Koa URL normalization**: Koa adapter parses `ctx.url` through `new URL()` to strip query strings and normalize encoding before prefix checking
121
- - **Code injection prevention in client module generation**: `getClientModules.ts` validates all interpolated identifiers (`fnName`, `fnEntry`, `rpcPrefix`) against `/^[A-Za-z_$][A-Za-z0-9_$]*$/` (and a path-safe variant allowing `/`) before interpolating into the generated client bundle. This prevents code injection via malicious export names or prefixes containing template literal interpolations (`${...}`), backticks, or `</script>` sequences.
122
- - **Body size limits**: Host frameworks cap parsed JSON bodies — Express (`express.json({ limit })`), Fastify (`bodyLimit`), Koa (`koa-body`), Hono (`hono/body-limit`). Rely on your framework's body parser middleware for size limits (see wiki/best-practices.md). The raw stream path in `readBody` does not impose a built-in limit — use framework middleware or a custom body limit handler for defense-in-depth.
130
+ - **Code injection prevention in client module generation**: `getClientModules.ts` validates all interpolated identifiers (`fnName`, `fnEntry`, `rpcPrefix`) against `/^[A-Za-z_$][A-Za-z0-9_$]*$/` (and a path-safe variant allowing `/`, `@`, `:`, `-`) before interpolating into the generated client bundle. This prevents code injection via malicious export names or prefixes containing template literal interpolations (`${...}`), backticks, or `</script>` sequences.
131
+ - **Body size limits**: Host frameworks cap parsed JSON bodies — Express (`express.json({ limit })`), Fastify (`bodyLimit`), Koa (`koa-body`), Hono (`hono/body-limit`), h3 (`bodyLimit`/`assertBodySize`). Rely on your framework's body parser middleware for size limits (see wiki/best-practices.md). The raw stream path in `readBody` does not impose a built-in limit — use framework middleware or a custom body limit handler for defense-in-depth.
123
132
  - **Generic 404 responses**: Error messages never echo the requested function name (no message-based function enumeration). Note the status code still distinguishes unknown (`404`) from known functions (`405`/`415`/`403`); function names ship in the client bundle so they are not secret — see `wiki/security.md`
124
133
  - **Auth is middleware's responsibility**: Authentication should be handled by middleware registered before `createRPCMiddleware()`. The middleware chain naturally composes — no built-in auth hook is needed.
125
134
  - **No client-side secrets or stack traces**: Error responses always return `"Internal Server Error"` regardless of the underlying error; `console.error(String(err))` is server-side only for debugging and does not surface internals to the client
@@ -146,6 +155,12 @@ The framework's security boundary is the **RPC prefix-gated HTTP endpoint**. Inp
146
155
  - Be free to hit any URL (no auth — host's responsibility via prior middleware)
147
156
  - Be rejected with generic error bodies (no function-name disclosure in messages, no stack traces); status-code differential still reveals existence — see `wiki/security.md`
148
157
 
158
+ ## Workflow notes (important!)
159
+
160
+ - **Harness folders**: when scaffolding a minimal repro/harness to debug the Vite plugin or an adapter, create it inside the repo (e.g. `TEMP/`) — **never** in the root or in OS temp dirs. Root-level harness files break `tsdown`/`vitest` path resolution, and temp dirs outside the project get swept by OS cleaners and leave stale `node_modules`/`.vite` state that corrupts the next run.
161
+ - **Never delete files**: do not `rm` source/test files. If a file must be removed from the tree, **rename it to `<name>-bak.<ext>`** (e.g. `foo.ts` → `foo-bak.ts`) and leave it in place. The `-bak` suffix is the only sanctioned way to retire a file; the repo may be scanned for history or references later.
162
+
163
+
149
164
  ## Documentation
150
165
 
151
166
  - `wiki/quickstart.md` — Rebuild the Express SSR example from `create-vite` in under a minute (copy-paste)
package/CHANGELOG.md CHANGED
@@ -1,5 +1,78 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.3.1] - 2026-08-21
4
+
5
+ ### Breaking Changes
6
+
7
+ - **`defineConfig` moved to `@thednp/rpc/config`**: the config helper no longer ships from the main plugin entry. `@thednp/rpc` statically imports Vite (it *is* a Vite plugin), so any server-side file importing it — including a serverless function bundle that merely reads your `rpc.config.ts` — would emit a runtime `require("vite")` and crash at cold start on platforms where Vite isn't installed (Netlify: `Runtime.ImportModuleError: Cannot find module 'vite'` → 502). The new `/config` subpath has zero dependencies, making serverless deployments behave like any other Express server. Update one import line in `rpc.config.ts`: `import { defineConfig } from "@thednp/rpc/config"`. All examples and the demo updated; `tests/fixtures/*` configs now import from source to stay resolution-safe before publish
8
+ - **demo Netlify function hardened** (`demo/netlify/functions/rpc.ts`): URL rewrite reconstructs the path from `cfg.rpcPrefix` instead of a hardcoded `"/@demo/"`; `serverless-http` moved from devDependencies to dependencies (it is runtime code inside the function bundle)
9
+
10
+ ### Added
11
+
12
+ - **Vite-free `defineConfig` module** (`src/config.ts`, built to `dist/config/config.mjs`): merges partial config over `defaultRPCOptions`, skipping explicitly `undefined` values so callers can't accidentally blank out defaults; zero runtime dependencies (type-only import erased at build)
13
+ - **`./config` subpath export**: wired into `package.json` exports and `deno.json` exports/imports maps; new tsdown build entry alongside the existing adapter/helper entries
14
+
15
+ ### Removed
16
+
17
+ - **`ensurePrefixFromGlobal` deleted** (`src/functionsMap.ts`) together with its call sites across all five adapter `createMiddleware` files — the copy-from-default-prefix fallback is superseded by the explicit prefix bootstrap below; also removed dead commented `setGlobalPrefix` calls from the adapters and `src/index.ts`
18
+ - **Serverless prefix bootstrap made explicit**: `setGlobalPrefix(cfg.rpcPrefix)` at the top of `src/api/server.ts` replaces implicit framework magic — static-import hoisting guarantees it runs before any `createServerFunction`, regardless of import order in the host function bundle (`demo/src/api/server.ts`)
19
+
20
+ ### Docs
21
+
22
+ - `wiki/adapters.md` **Serverless section rewritten** around two rules: (1) import `defineConfig` from `@thednp/rpc/config`, never the main entry, with the cold-start crash explained; (2) set the prefix at the top of `src/api/server.ts`; references the working [demo/netlify/functions/rpc.ts](../demo/netlify/functions/rpc.ts) and keeps `netlify.toml external_node_modules = ["vite"]` documented as a size optimization
23
+ - `wiki/configuration.md` — `defineConfig` section documents the `/config` subpath and why the main entry must never be imported server-side
24
+ - `README.md`, `wiki/quickstart.md`, `wiki/getting-started.md` — all `rpc.config.ts` snippets switched to `@thednp/rpc/config`
25
+ - `AGENTS.md` — h3 added to the adapter list and body-size-limits row (`bodyLimit`/`assertBodySize`); build output table gains `dist/config/config.mjs`
26
+ - `llms.txt` — config section notes the vite-free subpath and its serverless rationale
27
+
28
+ ### Tests
29
+
30
+ - Fixtures (`tests/fixtures/*.config.ts`) import `defineConfig` from source instead of the main entry, keeping `loadRPCConfig` suites green before publish
31
+ - "load config from file" suite targets `examples/advanced/rpc.config.ts` (the `link:../..` example) so it resolves current source including the unpublished `./config` export
32
+ - New coverage: `defineConfig` skips explicitly `undefined` values back to defaults — **428 tests, 100% on all metrics**
33
+
34
+ ### Fixed
35
+
36
+ - **Graceful scan without Vite** (`src/scanForServerFiles.ts`): the lazy `import("vite")` is now wrapped in try/catch — when Vite isn't installed (serverless bundles where it's externalized or absent), the scan exits silently instead of crashing the host cold start with `Runtime.ImportModuleError: Cannot find module 'vite'` → 502. Defense-in-depth for deployments whose function bundle doesn't import its server module directly; covered by a new suite that mocks Vite as missing (`tests/scan.test.ts`) — **429 tests, 100% on all metrics**
37
+ - **demo `rpc.config.ts` restored to `defineConfig`**: the plain-object workaround from the Netlify debugging session is retired — the config file now uses the documented `defineConfig({ rpcPrefix: "@demo" })` from `@thednp/rpc/config`, proving the vite-free subpath works end-to-end inside the live Netlify function bundle
38
+
39
+ ## [0.3.0] - 2026-08-21
40
+
41
+ ### Features
42
+
43
+ - **Multi-prefix support**: `createServerFunction` accepts a per-function `rpcPrefix` option (`{ rpcPrefix: "v1:rpc" }`) so multiple RPC instances can coexist in parallel — versioned APIs, namespaced endpoints, and API segregation without function-name collisions. The server functions map is now scoped by prefix (`getFunctionsForPrefix(prefix)`), the plugin generates client stubs per prefix (`getClientModules` reads only the requested prefix's map), and all five adapters (Express, Fastify, Hono, Koa, h3) look functions up in the prefix-scoped map instead of a single global map. Functions default to `"__rpc"` for full backward compatibility; the same registered name under different prefixes is no longer a duplicate, while same-prefix duplicates still throw in dev / warn in production
44
+ - **`getFunctionsForPrefix(prefix)`**: new exported server helper returning (and lazily creating) the `Map<name, ServerFnEntry>` for a given RPC prefix; `serverFunctionsMap` remains as the backward-compatible proxy for the default `"__rpc"` prefix
45
+ - **`defaultPrefix` constant**: the default `"__rpc"` prefix is now a named export from `@thednp/rpc/server`, used consistently across the scan, adapters, and function registration instead of a hardcoded string
46
+ - **Prefix charset widened**: `validatePathSegment` now permits `:` (and `@` in the first position) so versioned prefixes like `v1:rpc` / `v2:rpc` pass validation; `.` remains disallowed to keep path-traversal rejection (`foo..bar`, `foo/../bar`) intact
47
+ - **`getClientStub` helper** (`@thednp/rpc/helpers`): manual typed client stub factory for privileged prefixes not emitted in the public bundle — `getClientStub("admin:rpc","get-user")` (also curried `getClientStub("admin:rpc")("get-user")`) returns the same `{data,cancel}` shape as auto-generated stubs, with `method`/`credentials`/`contentType` options; code-splittable so `admin:rpc` literals never appear in the public chunk when `await import`-ed only inside `/admin` routes
48
+ - **Advanced example auth**: `examples/advanced` now has cookie-session auth (`HttpOnly; SameSite=Lax` `sid` via `Symbol.for("thednp.rpc.advanced.session")`), `public:rpc/login`/`logout`/`me`, `admin:rpc` guarded by `requireAdminSession` (403 without admin role), and SSR guard for `/admin` → `403` in `server.js` — demonstrates that `admin:rpc` isolation is not obscurity and that `getClientStub` must be used with real auth
49
+
50
+ ### Fixes
51
+
52
+ - **Cross-bundle map sharing**: `serverFunctionsByPrefix` now on `globalThis[Symbol.for("thednp.rpc.functionsMap")]` (`src/functionsMap.ts:12`) like `requestContext` — plugin scan (`dist/index.mjs`) and adapter dispatch (`dist/express/*.mjs`) share one map instead of per-bundle copies (dev 404 fix)
53
+ - **Config fallback**: scan fallback `exportValue.options?.rpcPrefix || config.rpcPrefix || defaultPrefix` (`src/scanForServerFiles.ts:138`) and `ScanConfig.rpcPrefix` (`src/types.d.ts:217`) propagated from `vite.config.ts`/`rpc.config.ts` via `src/index.ts:193` and lazy `src/*/*createMiddleware.ts:107` — existing examples without per-function `rpcPrefix` now register under the config prefix instead of `__rpc`
54
+ - **Glob scan in prod**: `MiddlewareOptions.serverFiles/scanRoot` (`src/types.d.ts:333`) now forwarded to lazy `scanForServerFiles` in all five adapters, and `examples/advanced/server.js:25` `admin:rpc` mounts with `serverFiles:"glob"` — prod `preview` finds `*.server.ts` files instead of defaulting to `exact`
55
+ - **Client generation DRY**: `src/getClientModules.ts:47` now emits `getClientStub("prefix","name",{...})` via `src/client-helpers.ts:32` `makeStub` instead of duplicating `body`/`headers` per function
56
+
57
+ ### Docs
58
+
59
+ - New `wiki/multi-prefix-guide.md` — parallel RPC instances: versioned/public/admin API layouts, per-prefix middleware wiring, canary deployments, origin validation per instance, and backward compatibility; added **Security: Do Not Trust the Prefix** section
60
+ - `wiki/security.md:92` **Multi-Prefix Client Isolation** — `getClientModules` virtual modules (`src/index.ts:221`), no disk files, only config prefix emitted, prefix is not a secret, must use `requireAdminSession`/`sendResponse(403)`
61
+ - `wiki/index.md` TOC + cross-links from `wiki/configuration.md` and `wiki/adapters.md` to the multi-prefix guide
62
+ - `AGENTS.md`, `llms.txt`, and `README.md` updated for the multi-prefix feature, `defaultPrefix` constant, `getClientStub`, and `dev:advanced`/`test:dev`/`test:prod` scripts
63
+ - `examples/advanced/README.md` rewritten for auth + multi-prefix demo
64
+
65
+ ### Tests
66
+
67
+ - Multi-prefix coverage: `createServerFunction` registers under a custom prefix (isolated from the default map), `getClientModules` generates `getClientStub` stubs only for the requested prefix, and the scan registers functions under their declared prefix without name collision
68
+ - Adapter middleware tests updated to register functions in the prefix-scoped map for non-default prefixes
69
+ - `getClientStub` coverage: curried `getClientStub("admin:rpc")("get-user")` and direct `getClientStub("admin:rpc","get-user")` plus `GET`/`text/plain`/`urlencoded`/`multipart` branches (`tests/client-helpers.test.ts:198`)
70
+ - **100% coverage**: all metrics (statements, branches, functions, lines) at 100% — 427 tests
71
+
72
+ ### Chores
73
+
74
+ - `pnpm test` now `vitest run --coverage`; new `pnpm test:watch` `vitest --watch --coverage`; `pnpm test:dev`/`test:prod` now `test:dev`/`test:prod` with colon; `pnpm clean` and `pnpm audit:src` documented; `scripts/update-examples.js:33` skips `advanced` (`link:../..`)
75
+
3
76
  ## [0.2.1] - 2026-08-10
4
77
 
5
78
  ### Features
@@ -16,6 +89,7 @@
16
89
  - **demo**: `body-limit.ts` stashes multipart bodies as `{ raw: body }` to mirror `@thednp/rpc/express`'s `readBody` streaming semantics; the render page and `getLibraryInfo` now count 9 examples and list the h3 adapter; the features grid grows to 9 cards (3×3) with request-context, no-JS form-fallback, and boundary-enforcement entries
17
90
  - **fastify example**: switch the production server to `@fastify/compress` (gzip) for the RPC endpoint and static HTML. `@fastify/compress` attaches its per-route `onSend` hook via `onRoute`, which never fires for the RPC plugin's global `preHandler` handling, so the example registers a scoped `app.post("/_server/*")` catch-all route — the RPC `preHandler` short-circuits before the handler runs, letting compress's hook attach to RPC POSTs while non-RPC POSTs still get a 404. Verified with curl: HTML and RPC POST responses (200 and 404) compress (gzip) with byte-identical decompression (md5 match), and non-RPC POSTs keep their 404
18
91
  - Sync all 9 examples to `@thednp/rpc ^0.2.0`
92
+ - **advanced example** (`examples/advanced`): Express SSR showcase of the multi-prefix model and universal middleware — the same `get-user` function name is registered under both `public:rpc` (rate-limited, 5 req/10s, returns public user data) and `admin:rpc` (guarded by a `x-admin-token` header check, returns full record), served by two `createRPCMiddleware` instances mounted in `server.js` while the client stubs are generated only for the config `public:rpc` prefix; a `middleware.ts` module (`rateLimit`, `auditLog`, `requireAdmin`) built on `getRequestContext`/`getRequestMeta`/`sendResponse` is shared across both prefixes. Dev mode mounts the admin middleware explicitly since the Vite plugin only auto-mounts the configured prefix; `scripts/dev-test.js` PREFIX_MAP includes `advanced: "public:rpc"` and the root `dev:advanced` script runs it
19
93
 
20
94
  ### Docs
21
95
 
package/README.md CHANGED
@@ -99,6 +99,18 @@ Server errors return a generic `Internal Server Error` — no messages, codes, o
99
99
  Generic type inference flows from your server function's arguments and return type all the way to the client stub. You get autocomplete for function names, argument types, and return types without writing a single type annotation on the client side.
100
100
  </details>
101
101
 
102
+ <details>
103
+ <summary><b>Multi-prefix support</b></summary>
104
+
105
+ Run multiple RPC instances in parallel. Pass `{ rpcPrefix: "v1:rpc" }` to `createServerFunction` to register a function under a custom prefix — versioned APIs, namespaced endpoints, and API segregation without function-name collisions. The same name can coexist under different prefixes (`v1:rpc/login` + `v2:rpc/login`), middleware dispatches to the prefix-scoped map, and the plugin generates client stubs per prefix. Functions default to `"__rpc"` for full backward compatibility. See the [Multi-Prefix Guide](./wiki/multi-prefix-guide.md).
106
+ </details>
107
+
108
+ <details>
109
+ <summary><b>Universal middleware</b></summary>
110
+
111
+ Write **one** middleware function that runs unchanged on every adapter (Express, Fastify, Hono, Koa, h3). Because every dispatch runs inside a per-request context, middleware written against `getRequestContext()` — reading normalized request data via `getRequestMeta()`, short-circuiting with `sendResponse(status, body, headers)` — behaves identically regardless of the host framework. No per-framework rewrites for cross-cutting RPC rules like per-function rate limiting, audit logging, or feature flags. See the [Middleware Guide](./wiki/middleware.md).
112
+ </details>
113
+
102
114
  ## Examples
103
115
 
104
116
  | Source | Demo | Clone |
@@ -112,6 +124,7 @@ Generic type inference flows from your server function's arguments and return ty
112
124
  | [examples/koa](https://github.com/thednp/rpc/tree/master/examples/koa) | [StackBlitz](https://stackblitz.com/fork/github/thednp/rpc/tree/master/examples/koa) | `pnpm dlx degit thednp/rpc/examples/koa my-app` |
113
125
  | [examples/react-query](https://github.com/thednp/rpc/tree/master/examples/react-query) | [StackBlitz](https://stackblitz.com/fork/github/thednp/rpc/tree/master/examples/react-query) | `pnpm dlx degit thednp/rpc/examples/react-query my-app` |
114
126
  | [examples/solid-query](https://github.com/thednp/rpc/tree/master/examples/solid-query) | [StackBlitz](https://stackblitz.com/fork/github/thednp/rpc/tree/master/examples/solid-query) | `pnpm dlx degit thednp/rpc/examples/solid-query my-app` |
127
+ | [examples/advanced](https://github.com/thednp/rpc/tree/master/examples/advanced) | [StackBlitz](https://stackblitz.com/fork/github/thednp/rpc/tree/master/examples/advanced) | `pnpm dlx degit thednp/rpc/examples/advanced my-app` |
115
128
 
116
129
  > **Clone an example**: `degit` scaffolds a fresh copy straight from the repo — no git history, ready to run:
117
130
 
@@ -156,7 +169,7 @@ npm i @thednp/rpc
156
169
  Create `rpc.config.ts` at your project root:
157
170
 
158
171
  ```ts
159
- import { defineConfig } from "@thednp/rpc";
172
+ import { defineConfig } from "@thednp/rpc/config";
160
173
 
161
174
  export default defineConfig({
162
175
  adapter: "express",
@@ -244,9 +257,9 @@ See the [Adapters guide](./wiki/adapters.md) for full snippets for each framewor
244
257
  ### Unit Testing
245
258
 
246
259
  ```bash
247
- pnpm test # Run tests with coverage
248
- pnpm test-ui # Run tests with UI
249
- pnpm test --run # Single run
260
+ pnpm test # Run tests once with coverage (vitest run --coverage)
261
+ pnpm test:watch # Run tests in watch mode with coverage
262
+ pnpm test:ui # Run tests with UI
250
263
  ```
251
264
 
252
265
  Tests use **Vitest** with **Istanbul** coverage — 10 test files covering the plugin, scanning, server/client helpers, request context, and all five adapters, at 100% coverage.
@@ -254,8 +267,8 @@ Tests use **Vitest** with **Istanbul** coverage — 10 test files covering the p
254
267
  ### Live Testing
255
268
 
256
269
  ```bash
257
- pnpm test-dev # Runs all examples/<example> in DEV mode and reports their status in a table
258
- pnpm test-prod # Runs all examples/<example> in PRODUCTION mode and reports their status in a table
270
+ pnpm test:dev # Runs all examples/<example> in DEV mode and reports their status in a table
271
+ pnpm test:prod # Runs all examples/<example> in PRODUCTION mode and reports their status in a table
259
272
  ```
260
273
 
261
274
  These tests check the following:
@@ -277,10 +290,10 @@ Contributions are welcome. This project uses:
277
290
 
278
291
  ```bash
279
292
  pnpm lint # deno lint + tsc -noEmit
280
- pnpm format # deno fmt src
281
- pnpm test # Run tests with coverage
282
- pnpm test-ui # Run tests with interactive UI
283
- pnpm build # Bundle with tsdown
293
+ pnpm format # deno fmt src tests examples/**/src
294
+ pnpm test # Run tests once with coverage (vitest run --coverage)
295
+ pnpm test:ui # Run tests with UI
296
+ pnpm build # Bundle with tsdown (tsdown)
284
297
  ```
285
298
 
286
299
  All changes should pass `pnpm lint && pnpm format && pnpm test` before submitting. See [AGENTS.md](./AGENTS.md) for the full command reference and project conventions.
@@ -0,0 +1,65 @@
1
+ import "vite";
2
+ import "@thednp/rpc";
3
+ import "express";
4
+ import "hono";
5
+ import "@hono/node-server";
6
+ import "hono/utils/http-status";
7
+ import "hono/factory";
8
+ import "fastify";
9
+ import "fastify-plugin";
10
+ import "koa";
11
+ import "h3";
12
+ //#region src/types.d.ts
13
+ /**
14
+ * ### @thednp/rpc
15
+ * The plugin configuration allows for granular control of your
16
+ * application RPC calls. The default settings are optimized for development
17
+ * environments while providing a secure foundation for production use.
18
+ */
19
+ interface RpcPluginOptions {
20
+ // RPC Middleware Options
21
+ /**
22
+ * RPC prefix without leading slash (e.g. "__rpc")
23
+ * Leading slash will be added automatically by the middleware.
24
+ * This prefix defines the base path for all RPC endpoints.
25
+ * @default "__rpc"
26
+ * @example
27
+ * // Results in endpoints like: /api/rpc/myFunction
28
+ * rpcPrefix: "api/rpc"
29
+ */
30
+ rpcPrefix: "__rpc" | string;
31
+ /**
32
+ * Option to set an adapter for the middleware connection. The default is _express_,
33
+ * which is the most popular and battle tested server app. The _express_ adapter is
34
+ * also compatible with the vite's Connect development server.
35
+ * @default express
36
+ */
37
+ adapter: "express" | "hono" | "h3" | "fastify" | "koa";
38
+ /**
39
+ * Root directory from which the plugin scans for server files.
40
+ * Defaults to `<root>/src/api`. Use this in monorepos where server files
41
+ * live in a shared package outside the current project root.
42
+ * @default undefined (resolves to src/api relative to the Vite root)
43
+ */
44
+ scanRoot?: string;
45
+ /**
46
+ * Server file matching mode. Use `"exact"` (default) for the classic
47
+ * `server.ts|js|mjs|mts` names, or `"glob"` to match `**\/*.server.{ts,js,mjs,mts}`
48
+ * inside the scan root.
49
+ * @default "exact"
50
+ */
51
+ serverFiles?: "exact" | "glob";
52
+ }
53
+ //#endregion
54
+ //#region src/config.d.ts
55
+ /**
56
+ * Type-safe helper to create an RPC configuration object.
57
+ * Merges the provided partial config over the built-in defaults,
58
+ * skipping explicitly `undefined` values.
59
+ * @param uniConfig - System-wide RPC configuration overrides
60
+ * @returns Complete RPC plugin options with defaults applied
61
+ */
62
+ declare const defineConfig: (c: Partial<RpcPluginOptions>) => RpcPluginOptions;
63
+ //#endregion
64
+ export { defineConfig };
65
+ //# sourceMappingURL=config.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.mts","names":[],"sources":["../../src/types.d.ts","../../src/config.ts"],"mappings":";;;;;;;;;;;;;;;;;;UAsPiB;;;;;;;;;;;EAWf;;;;;;;EAQA;;;;;;;EAQA;;;;;;;EAQA;;;;;;;;;;;cCvQW,eACX,GAAG,QAAQ,sBACR"}
@@ -0,0 +1,24 @@
1
+ const defaultRPCOptions = {
2
+ rpcPrefix: "__rpc",
3
+ adapter: "express",
4
+ serverFiles: "exact",
5
+ scanRoot: void 0
6
+ };
7
+ //#endregion
8
+ //#region src/config.ts
9
+ /**
10
+ * Type-safe helper to create an RPC configuration object.
11
+ * Merges the provided partial config over the built-in defaults,
12
+ * skipping explicitly `undefined` values.
13
+ * @param uniConfig - System-wide RPC configuration overrides
14
+ * @returns Complete RPC plugin options with defaults applied
15
+ */
16
+ const defineConfig = (uniConfig) => {
17
+ const merged = { ...defaultRPCOptions };
18
+ for (const [key, value] of Object.entries(uniConfig)) if (value !== void 0) merged[key] = value;
19
+ return merged;
20
+ };
21
+ //#endregion
22
+ export { defineConfig };
23
+
24
+ //# sourceMappingURL=config.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.mjs","names":[],"sources":["../../src/options.ts","../../src/config.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","/**\n * Vite-free configuration helpers.\n *\n * This module intentionally has zero runtime dependencies (not even on `vite`),\n * so `rpc.config.ts` files that import it stay safe to load in serverless\n * bundles where Vite is not installed. Importing the main plugin entry\n * (`@thednp/rpc`) instead would drag Vite into every server-side consumer.\n */\nimport type { RpcPluginOptions } from \"./types.d.ts\";\nimport { defaultRPCOptions } from \"./options.ts\";\n\n/**\n * Type-safe helper to create an RPC configuration object.\n * Merges the provided partial config over the built-in defaults,\n * skipping explicitly `undefined` values.\n * @param uniConfig - System-wide RPC configuration overrides\n * @returns Complete RPC plugin options with defaults applied\n */\nexport const defineConfig: (\n c: Partial<RpcPluginOptions>,\n) => RpcPluginOptions = (uniConfig: Partial<RpcPluginOptions>) => {\n const merged: RpcPluginOptions & Record<string, string> = {\n ...defaultRPCOptions,\n };\n for (const [key, value] of Object.entries(uniConfig)) {\n // istanbul ignore else\n if (value !== undefined) {\n merged[key] = value;\n }\n }\n return merged;\n};\n"],"mappings":"AAcA,MAAa,oBAAsC;CACjD,WAAW;CACX,SAAS;CACT,aAAa;CACb,UAAU,KAAA;AACZ;;;;;;;;;;ACDA,MAAa,gBAEY,cAAyC;CAChE,MAAM,SAAoD,EACxD,GAAG,kBACL;CACA,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,SAAS,GAEjD,IAAI,UAAU,KAAA,GACZ,OAAO,OAAO;CAGlB,OAAO;AACT"}
@@ -67,9 +67,11 @@ type RequestDetails = {
67
67
  declare const createMiddleware: ExpressMiddlewareFn;
68
68
  /**
69
69
  * Creates the Express RPC middleware that routes incoming requests to registered server functions.
70
- * Reads the request body, dispatches to the matching function via serverFunctionsMap,
70
+ * Reads the request body, dispatches to the matching function via getFunctionsForPrefix,
71
71
  * and sends the JSON-serialized result. Handles client disconnection via abort signals.
72
- * @param initialOptions - Options including rpcPrefix for URL routing
72
+ * Supports multi-prefix setups where different middleware instances can route to functions
73
+ * registered under different prefixes.
74
+ * @param initialOptions - Options including rpcPrefix for URL routing and prefix-scoped function lookup
73
75
  * @returns An Express middleware function
74
76
  */
75
77
  declare const createRPCMiddleware: ExpressMiddlewareFn;
@@ -1 +1 @@
1
- {"version":3,"file":"express.d.mts","names":[],"sources":["../../src/express/types.d.ts","../../src/express/createMiddleware.ts","../../src/express/helpers.ts"],"mappings":";;;;;;;;KAgBY,2BAA2B;;;;;KAM3B,uBACV,UAAU,yCAEV,iBAAiB,QAAQ,8BACtB;;;;UAKY;;;;;;;EAOf,UACE,KAAK,kBAAkB,SACvB,KAAK,iBAAiB,UACtB,MAAM,QAAQ,eAAe,iBAC1B;;;;;;KAOK;;EAEV;;EAEA,YAAY,cAAc;;EAE1B;;EAEA,gBAAgB;;EAEhB,eAAe,cAAc,QAAQ;;;;;KAM3B;;EAEV;;EAEA;;EAEA,cAAc;;EAEd,SAAS;;EAET;;;;;;;;;;;cC1BW,kBAAkB;;;;;;;;cAyElB,qBAAqB;;;;;;;;iBCvGZ,UAAU,KAAK,UAAO;;;;;;iBAc5B,WAAW,KAAK,SAAS,MAAM;;;;;;;;cAWlC,WAAQ,KACd,UAAiB,oBACrB,QAAQ;;;;;;cAqFE,mBAAgB,KACtB,kBAAkB,YACtB,OAAO;;;;;;cASG,oBAAiB,KACvB,iBAAiB,aACrB,OAAO;;;;;;;;;;;;cAeG,WAAQ,KACd,iBAAiB,UAAe,kBACrB;;;;;;;cAkBL,mBAAgB,KACtB,kBAAkB,YACtB,OAAO;;;;;;;cAUG,oBAAiB,SACnB,UAAiB,oBACzB;;;;;;;cAqBU,qBAAkB,UACnB,WAAkB,mBAC3B"}
1
+ {"version":3,"file":"express.d.mts","names":[],"sources":["../../src/express/types.d.ts","../../src/express/createMiddleware.ts","../../src/express/helpers.ts"],"mappings":";;;;;;;;KAgBY,2BAA2B;;;;;KAM3B,uBACV,UAAU,yCAEV,iBAAiB,QAAQ,8BACtB;;;;UAKY;;;;;;;EAOf,UACE,KAAK,kBAAkB,SACvB,KAAK,iBAAiB,UACtB,MAAM,QAAQ,eAAe,iBAC1B;;;;;;KAOK;;EAEV;;EAEA,YAAY,cAAc;;EAE1B;;EAEA,gBAAgB;;EAEhB,eAAe,cAAc,QAAQ;;;;;KAM3B;;EAEV;;EAEA;;EAEA,cAAc;;EAEd,SAAS;;EAET;;;;;;;;;;;cCrBW,kBAAkB;;;;;;;;;;cAiFlB,qBAAqB;;;;;;;;iBCpHZ,UAAU,KAAK,UAAO;;;;;;iBAc5B,WAAW,KAAK,SAAS,MAAM;;;;;;;;cAWlC,WAAQ,KACd,UAAiB,oBACrB,QAAQ;;;;;;cAqFE,mBAAgB,KACtB,kBAAkB,YACtB,OAAO;;;;;;cASG,oBAAiB,KACvB,iBAAiB,aACrB,OAAO;;;;;;;;;;;;cAeG,WAAQ,KACd,iBAAiB,UAAe,kBACrB;;;;;;;cAkBL,mBAAgB,KACtB,kBAAkB,YACtB,OAAO;;;;;;;cAUG,oBAAiB,SACnB,UAAiB,oBACzB;;;;;;;cAqBU,qBAAkB,UACnB,WAAkB,mBAC3B"}
@@ -1,5 +1,4 @@
1
- import { escapeRegExp, formatError, hasContentTypeMismatch, provideRequestContext, scanForServerFiles, serverFunctionsMap } from "@thednp/rpc/server";
2
- //#region src/options.ts
1
+ import { escapeRegExp, formatError, getGlobalPrefix, hasContentTypeMismatch, provideRequestContext, scanForServerFiles } from "@thednp/rpc/server";
3
2
  const defaultRPCOptions = {
4
3
  rpcPrefix: "__rpc",
5
4
  adapter: "express",
@@ -12,6 +11,32 @@ const defaultMiddlewareOptions = {
12
11
  origin: void 0
13
12
  };
14
13
  //#endregion
14
+ //#region src/functionsMap.ts
15
+ /**
16
+ * Global symbol under which the shared `serverFunctionsByPrefix` map is stored
17
+ * on `globalThis`. Keeping it on a `Symbol.for` key makes it instance-stable
18
+ * across the bundled entry copies (`index.mjs`, `server.mjs`, `express.mjs`,
19
+ * ...) and dev-server hot reloads, exactly like the request-context storage in
20
+ * `context.ts`. Without this, `scanForServerFiles` (bundled into the plugin)
21
+ * would populate a map copy the adapter middleware could not read.
22
+ */
23
+ const functionsMapSymbol = Symbol.for("thednp.rpc.functionsMap");
24
+ /**
25
+ * Map of rpcPrefix -> Map of function names -> ServerFnEntry
26
+ * Enables multiple RPC instances with different prefixes to coexist
27
+ * without name collisions.
28
+ */
29
+ const serverFunctionsByPrefix = globalThis[functionsMapSymbol] ??= /* @__PURE__ */ new Map();
30
+ /**
31
+ * Gets or creates the function map for a specific prefix.
32
+ * @param prefix - The RPC prefix (e.g., "__rpc", "v1:rpc", "admin:rpc")
33
+ * @returns Map of function names to ServerFnEntry for that prefix
34
+ */
35
+ const getFunctionsForPrefix = (prefix) => {
36
+ if (!serverFunctionsByPrefix.has(prefix)) serverFunctionsByPrefix.set(prefix, /* @__PURE__ */ new Map());
37
+ return serverFunctionsByPrefix.get(prefix);
38
+ };
39
+ //#endregion
15
40
  //#region src/constants.ts
16
41
  const FUNCTION_NOT_FOUND = "Function not found";
17
42
  const METHOD_NOT_ALLOWED = "Method Not Allowed";
@@ -226,7 +251,7 @@ const middlewareStack = /* @__PURE__ */ new Set();
226
251
  const createMiddleware = (initialOptions = {}) => {
227
252
  const options = Object.assign({}, defaultMiddlewareOptions, initialOptions);
228
253
  const middlewareName = options.name;
229
- const rpcPrefix = options.rpcPrefix;
254
+ let rpcPrefix = options.rpcPrefix;
230
255
  const path = options.path;
231
256
  const handler = options.handler;
232
257
  let name = middlewareName;
@@ -240,10 +265,15 @@ const createMiddleware = (initialOptions = {}) => {
240
265
  const pathMatcher = path ? typeof path === "string" ? new RegExp(path) : path : null;
241
266
  const middlewareHandler = async (req, res, next) => {
242
267
  const { url } = getRequestDetails(req);
243
- if (serverFunctionsMap.size === 0) await scanForServerFiles();
244
268
  if (!handler) return next?.();
245
269
  if (pathMatcher && !pathMatcher.test(url)) return next?.();
246
270
  if (prefixRegex && !prefixRegex.test(url)) return next?.();
271
+ rpcPrefix = rpcPrefix ?? "__rpc";
272
+ if (getFunctionsForPrefix(rpcPrefix).size === 0) await scanForServerFiles({
273
+ rpcPrefix,
274
+ serverFiles: options.serverFiles,
275
+ scanRoot: options.scanRoot
276
+ });
247
277
  await handler(req, res, next);
248
278
  };
249
279
  Object.defineProperty(middlewareHandler, "name", { value: name });
@@ -251,16 +281,19 @@ const createMiddleware = (initialOptions = {}) => {
251
281
  };
252
282
  /**
253
283
  * Creates the Express RPC middleware that routes incoming requests to registered server functions.
254
- * Reads the request body, dispatches to the matching function via serverFunctionsMap,
284
+ * Reads the request body, dispatches to the matching function via getFunctionsForPrefix,
255
285
  * and sends the JSON-serialized result. Handles client disconnection via abort signals.
256
- * @param initialOptions - Options including rpcPrefix for URL routing
286
+ * Supports multi-prefix setups where different middleware instances can route to functions
287
+ * registered under different prefixes.
288
+ * @param initialOptions - Options including rpcPrefix for URL routing and prefix-scoped function lookup
257
289
  * @returns An Express middleware function
258
290
  */
259
291
  const createRPCMiddleware = (initialOptions = {}) => {
260
292
  const options = Object.assign({}, defaultMiddlewareOptions, { rpcPrefix: defaultRPCOptions.rpcPrefix }, initialOptions);
261
293
  const rpcPrefix = options.rpcPrefix;
294
+ const prefix = rpcPrefix || getGlobalPrefix() || "__rpc";
262
295
  const prefixRegex = rpcPrefix ? new RegExp(`^/${escapeRegExp(rpcPrefix)}/`) : null;
263
- const prefixReplace = `/${rpcPrefix}/`;
296
+ const prefixReplace = `/${prefix}/`;
264
297
  return createMiddleware({
265
298
  ...options,
266
299
  handler: async (req, res, _next) => {
@@ -274,7 +307,7 @@ const createRPCMiddleware = (initialOptions = {}) => {
274
307
  return;
275
308
  }
276
309
  const functionName = path.replace(prefixReplace, "");
277
- const serverFunction = serverFunctionsMap.get(functionName);
310
+ const serverFunction = getFunctionsForPrefix(prefix).get(functionName);
278
311
  if (!serverFunction) {
279
312
  sendResponse(404, { error: FUNCTION_NOT_FOUND });
280
313
  return;