rossa 0.0.6 → 0.1.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.
package/README.md CHANGED
@@ -1,12 +1,11 @@
1
1
  # Rossa
2
2
 
3
3
  Rossa is a Bun HTTP server with decorator-based routing, request guards, a
4
- response/context API, and optional WebSocket routes.
4
+ response/context API, SSE, WebSocket routes, authentication building blocks,
5
+ and a small SQL repository layer. This README is the quick start; see
6
+ [`doc/features.md`](doc/features.md) for the complete feature reference.
5
7
 
6
- For browser-side data storage, see the standalone [IndexedDB helper](indexeddb/README.md)
7
- outside `src`, with schema/column builders and typed CRUD operations.
8
-
9
- ## Install and build
8
+ ## Install
10
9
 
11
10
  Rossa requires Bun. In an application, install the published package and import
12
11
  its public API from `rossa`:
@@ -15,9 +14,10 @@ its public API from `rossa`:
15
14
  bun add rossa
16
15
  ```
17
16
 
18
- The package build bundles the runtime entry point for Bun and emits TypeScript
19
- declarations under `dist/`. Run `bun run build` before packing or publishing;
20
- `bun pm pack --dry-run` previews the files included in the package.
17
+ The published package ships bundled JavaScript and TypeScript declarations under
18
+ `dist/`. From a source checkout, run `bun run builder.ts` before packing;
19
+ `bun pm pack --dry-run` previews the files included. The project intentionally
20
+ has no `build` npm script.
21
21
 
22
22
  ## Create a server
23
23
 
@@ -42,19 +42,15 @@ app.register(Users);
42
42
  app.serve({ port: 3000, hostname: "localhost" });
43
43
  ```
44
44
 
45
- Call `app.getPaths()` after registering controllers to get an array of HTTP
46
- route paths, including any `basePath`. Parameter names have their colons removed:
47
-
48
- ```ts
49
- app.getPaths(); // ["/users/id"]
50
- ```
45
+ Call `app.getPaths()` after registering controllers to list HTTP paths, including
46
+ any `basePath`, with parameter colons removed (for example `["/users/id"]`).
51
47
 
52
48
  `Rossa` accepts these options:
53
49
 
54
50
  | Option | Default | Purpose |
55
51
  | ---------------- | ------------ | --------------------------------------------------------------------------------------------------------- |
56
52
  | `basePath` | `""` | Prefix added to registered HTTP and WebSocket routes. |
57
- | `clientPath` | `"./public"` | Directory used by `res.fileServer()`. |
53
+ | `clientPath` | `"./public"` | Directory used by `res.fileServer()`. A relative path is resolved from the parent of `dirPath`. |
58
54
  | `dirPath` | `"./src"` | Anchor used to resolve a relative `clientPath`. |
59
55
  | `fileExtensions` | `[]` | Additional extensions to recognize, with or without a leading dot. Built-in extensions remain recognized. |
60
56
  | `logError` | `false` | Log errors caught by the router pipeline. |
@@ -62,30 +58,12 @@ app.getPaths(); // ["/users/id"]
62
58
 
63
59
  `app.serve(serverOptions, websocketOptions)` starts Bun's server. The first
64
60
  argument accepts Bun serve options plus an optional `fn(port)` callback. The
65
- second argument accepts Bun WebSocket options. If no port is provided, Rossa
66
- uses `3000`.
61
+ second argument accepts Bun WebSocket options plus Rossa's optional
62
+ `messageRateLimit`. If no port is provided, Rossa uses `3000`.
67
63
 
68
- ## Static files
69
-
70
- Rossa recognizes common web, image, font, text, and JSON extensions by
71
- default. Add extensions such as PDF or WebAssembly when creating the app:
72
-
73
- ```ts
74
- const app = new Rossa({ fileExtensions: [".pdf", "wasm"] });
75
- ```
76
-
77
- The `req.isFile` check recognizes these extensions. A catch-all route can then
78
- call `res.fileServer()` to serve from `clientPath`:
79
-
80
- ```ts
81
- @route("/:file")
82
- class PublicFiles extends Methods {
83
- get({ req, res }: ctx): Promise<Response> | Response {
84
- if (req.isFile) return res.fileServer();
85
- return res.null(404);
86
- }
87
- }
88
- ```
64
+ `app.test(request, encoding?)` runs a `Request` through the same pipeline
65
+ without binding a socket. `app.registerWSS(...)` registers WebSocket
66
+ controllers, described below.
89
67
 
90
68
  ## Routes and request context
91
69
 
@@ -104,9 +82,18 @@ class Notes extends Methods {
104
82
  }
105
83
  ```
106
84
 
85
+ Rossa supplies an inherited `options` handler for each declared path. It
86
+ returns `204` with an `Allow` header built from the methods registered for that
87
+ path.
88
+
107
89
  Useful response methods include `text`, `html`, `json`, `success`, `error`,
108
- `redirect`, `null`, and `fileServer`. Route parameters are exposed as strings
109
- on `ctx.params`; query parameters are available from `ctx.req.query`.
90
+ `redirect`, `null`, `file`, and `fileServer`. Route parameters are exposed as
91
+ strings on `ctx.params`; query parameters are available from `ctx.req.query`.
92
+ Guards may place validated values on `ctx.query`, `ctx.body`, or `ctx.form`.
93
+
94
+ For SSE, a GET request whose `Accept` header allows `text/event-stream` routes
95
+ to `event`. Return `res.event.asyncStream(...)`, `res.event.eStream(...)`, or
96
+ `res.event.readableStream(...)`; these require a live Bun server.
110
97
 
111
98
  ## Guards
112
99
 
@@ -129,20 +116,52 @@ class Api extends Methods {
129
116
  }
130
117
  ```
131
118
 
132
- The public entry point exports guard factories for authentication, caching,
133
- compression, content type, cookies, CORS, CSRF, errors, forms, headers, IP
134
- filtering, JSON, JWT, logging, multipart, query validation, rate limiting,
135
- sanitization, security headers, sessions, static files, timeouts, and URL
136
- validation. See [`doc/guards.md`](doc/guards.md) for guard behavior and
137
- examples.
119
+ `app.use` prepends guards, so a guard registered later runs earlier. Place
120
+ wrapper guards such as `errorHandler` and `security` before the work whose
121
+ response they should wrap.
122
+
123
+ The public entry point exports guard factories for authentication
124
+ (`authBearer`, `apiKey`, `auth`, `authorize`), caching (`smartCache`), content
125
+ type, cookies, CORS, CSRF, error boundaries (`errorHandler`), headers, IP
126
+ filtering, JSON body validation, required JSON keys (`keys`), JWT (`jwtAuth`,
127
+ `jwtRefresh`), logging (`logger`, `loggerFN`), multipart and URL-encoded forms,
128
+ query and form validation, rate limiting, sanitization, security headers,
129
+ sessions, static files, timeouts, and URL validation. Define reusable custom
130
+ guards with `createGuard`. See [`doc/guards.md`](doc/guards.md) for guard
131
+ behavior and examples.
132
+
133
+ ## Static files
134
+
135
+ Rossa recognizes common web, image, font, text, and JSON extensions by default.
136
+ Add extensions such as PDF or WebAssembly when creating the app:
137
+
138
+ ```ts
139
+ const app = new Rossa({ fileExtensions: [".pdf", "wasm"] });
140
+ ```
141
+
142
+ The `req.isFile` check recognizes these extensions. A catch-all route can then
143
+ call `res.fileServer()` to serve from `clientPath`:
144
+
145
+ ```ts
146
+ @route("/:file")
147
+ class PublicFiles extends Methods {
148
+ get({ req, res }: ctx): Promise<Response> | Response {
149
+ if (req.isFile) return res.fileServer();
150
+ return res.null(404);
151
+ }
152
+ }
153
+ ```
154
+
155
+ The static server checks resolved paths against the configured root (including
156
+ symlink resolution), caches small files, and supports ETags.
138
157
 
139
158
  ## WebSockets
140
159
 
141
160
  Decorate a `Websocket` subclass with `@wss(path)` and register it with
142
- `app.registerWSS`. Its `open`, `message`, and `close` methods handle the
143
- connection lifecycle. Guards on the WebSocket route can place verified
144
- identity in `ctx.data`; Rossa copies that data to `this.contextData` before
145
- calling `open`.
161
+ `app.registerWSS`. Its `open`, `message`, `close`, and `drain` methods handle the
162
+ connection lifecycle. Guards on the WebSocket route can place verified identity
163
+ in `ctx.data`; Rossa copies that data to `this.contextData` before calling
164
+ `open`.
146
165
 
147
166
  ```ts
148
167
  import { Rossa, Websocket, wss } from "rossa";
@@ -174,19 +193,64 @@ app.serve(
174
193
  `messageRateLimit` is optional and counts inbound messages independently for
175
194
  each socket using a fixed time window. When a socket exceeds its limit, Rossa
176
195
  closes it with code `1008`. `maxPayloadLength`, `backpressureLimit`, and
177
- `closeOnBackpressureLimit` are Bun WebSocket options. A controller may implement
178
- `drain()` to resume work after Bun drains buffered outbound data. Topic
179
- `manager.broadcast(...)` returns per-topic statuses (`sent`, `backpressured`,
180
- `dropped`, or `oversize`) so handlers can observe publish outcomes.
196
+ `closeOnBackpressureLimit` are Bun options. `drain()` runs after Bun drains
197
+ buffered outbound data.
198
+
199
+ `this.manager` is a per-connection `subManager` backed by the process-wide
200
+ `WSSMAN` singleton. Use it to subscribe to topics, broadcast, inspect members,
201
+ set admin flags, and configure room capacity or payload limits. Broadcast
202
+ results report each topic as `sent`, `backpressured`, `dropped`, or `oversize`.
181
203
 
182
204
  For the handshake, frame parsing, lifecycle, and sample chat message contract,
183
205
  see [`doc/websockets.md`](doc/websockets.md).
184
206
 
207
+ ## MCP (Model Context Protocol)
208
+
209
+ Rossa can expose an MCP server over Streamable HTTP. Extend `McpController`,
210
+ declare tools, resources, and prompts in `build`, then register the decorated
211
+ class:
212
+
213
+ ```ts
214
+ import { McpController, McpServer, Rossa, mcp } from "rossa";
215
+
216
+ const app = new Rossa();
217
+
218
+ @mcp("/mcp", { origin: "https://app.example.com" })
219
+ class Assistant extends McpController {
220
+ build(server: McpServer) {
221
+ server.registerTool(
222
+ "echo",
223
+ { description: "Echo a fixed value" },
224
+ async () => ({ content: [{ type: "text", text: "ok" }] }),
225
+ );
226
+ }
227
+ }
228
+
229
+ app.registerMCP(Assistant);
230
+ ```
231
+
232
+ For an explicit path without a controller class, pass a per-request factory:
233
+ `app.registerMCP("/mcp", (context) => new McpServer({ name: "raw", version: "1.0.0" }))`.
234
+
235
+ `origin` accepts full origins, bare hostnames, or `scheme://*`; requests without
236
+ an `Origin` header always pass. POST is served, GET and DELETE return `405`, and
237
+ OPTIONS/HEAD return `404`. Global `app.use(...)` guards run before the endpoint
238
+ and can block it, but header-only guards such as `cors()` do not decorate the
239
+ SDK's response; use `origin` or handle MCP CORS at a proxy.
240
+
241
+ See the [MCP chapter](doc/features.md#mcp-model-context-protocol) and the
242
+ [official TypeScript SDK docs](https://ts.sdk.modelcontextprotocol.io/v2/).
243
+
244
+ For a runnable notes server backed by Rossa's SQLite repository, run
245
+ `bun run examples/mcp/server.ts`. It exposes `add-note`, `list-notes`, and
246
+ `search-notes`; see [`examples/mcp/README.md`](examples/mcp/README.md) for setup,
247
+ Inspector, and curl examples.
248
+
185
249
  ## Test requests without starting a server
186
250
 
187
251
  `app.test(request)` runs a `Request` through the same router pipeline and
188
- returns a `Response`. The runnable example in [`test.ts`](test.ts) shows HTTP,
189
- guards, WebSockets, and this in-process request method.
252
+ returns a `Response`. The runnable [`test.ts`](test.ts) shows HTTP, guards,
253
+ WebSockets, and this method.
190
254
 
191
255
  ```ts
192
256
  const response = await app.test(
@@ -197,30 +261,35 @@ console.log(response.status, await response.text());
197
261
 
198
262
  ## Public exports
199
263
 
200
- `src/index.ts` is the package entry point. It exports:
201
-
202
- - `Rossa` and its `RossaOptions`, `serverOptions`, and `dev` types.
203
- - `ContentEncodingType` for the supported response encodings.
204
- - `Methods`, `RouterManager`, `route`, `wss`, and router metadata types.
205
- - `use`, `createGuard`, guard factories, and guard-related types.
206
- - `ctx`, `Req`, `Res`, and response error types.
207
- - `Websocket`, `wssMessage`, `WssConfig`, `WssManager`, `subManager`, and the
208
- default `WSSMAN` singleton.
209
- - `Field` for typed field scopes. See [`doc/field-scopes.md`](doc/field-scopes.md)
210
- for a route example.
264
+ `src/index.ts` exports `Rossa` and its option types; `Methods`, `RouterManager`,
265
+ `route`, and `wss`; guard factories with `use` and `createGuard`; `ctx`, `Req`,
266
+ `Res`, and `sendError`; WebSocket classes and `WSSMAN`; MCP (`McpController`,
267
+ `McpServer`, `mcp`); authentication, database, and `Field`/`Scope` APIs. See
268
+ [`doc/features.md`](doc/features.md) for names.
269
+
270
+ ## Documentation and examples
271
+
272
+ | Document | Contents |
273
+ | ---------------------------------------------------------- | ---------------------------------------------------------- |
274
+ | [`doc/features.md`](doc/features.md) | Complete feature and API reference. |
275
+ | [`doc/guards.md`](doc/guards.md) | Guard behavior, ordering, and custom guards. |
276
+ | [`doc/websockets.md`](doc/websockets.md) | WebSocket client contract, lifecycle, and limits. |
277
+ | [MCP TypeScript SDK](https://ts.sdk.modelcontextprotocol.io/v2/) | Official MCP server docs for tools, resources, and prompts. |
278
+ | [`doc/session-auth.md`](doc/session-auth.md) | Session service implementation and login backend example. |
279
+ | [`doc/db.md`](doc/db.md) | Repository, schema, dialects, and schema synchronization. |
280
+ | [`doc/field-scopes.md`](doc/field-scopes.md) | Typed `Field` decorators and shared [`Scope`](doc/scopes.md) values. |
281
+ | [`doc/routing-style.md`](doc/routing-style.md) | Route registration and matching model. |
282
+ | [`src/wss/examples/README.md`](src/wss/examples/README.md) | Group chat, direct message, and bot examples. |
211
283
 
212
284
  Run the sample with `bun run test.ts`.
213
285
 
214
- For a group chat built on per-conversation topics, session authentication,
215
- membership checks, and a persistence adapter, see
216
- [`src/wss/examples/README.md`](src/wss/examples/README.md).
217
-
218
286
  ## Load harness
219
287
 
220
- Run the repeatable local WebSocket load harness with `bun run test:load`. It
221
- reports fan-out delivery ratio, latency percentiles, publish statuses, and RSS
222
- memory change. Set `BENCH_CLIENTS`, `BENCH_DURATION_SECONDS`,
288
+ Run the local WebSocket load harness with `bun run test:load`. It reports
289
+ fan-out delivery, latency percentiles, publish statuses, and RSS change.
290
+ Configure it with `BENCH_CLIENTS`, `BENCH_DURATION_SECONDS`,
223
291
  `BENCH_MESSAGES_PER_SECOND`, `BENCH_DELIVERY_TIMEOUT_MS`, or
224
- `BENCH_BACKPRESSURE_LIMIT` to adjust the workload. Use a staging environment
225
- and representative deployment limits before drawing production capacity
226
- conclusions.
292
+ `BENCH_BACKPRESSURE_LIMIT`. It is a benchmark, not a capacity guarantee.
293
+ WebSocket rooms, rate-limit counters, and the small-file cache are process-local;
294
+ multi-instance deployments need shared pub/sub, membership state, and rate
295
+ limiting.