rossa 0.0.5 → 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/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 Mark Yalung
3
+ Copyright (c) 2026 Mark Yalung
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1 +1,295 @@
1
- # ROSSA BunJS Server Framework
1
+ # Rossa
2
+
3
+ Rossa is a Bun HTTP server with decorator-based routing, request guards, a
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.
7
+
8
+ ## Install
9
+
10
+ Rossa requires Bun. In an application, install the published package and import
11
+ its public API from `rossa`:
12
+
13
+ ```sh
14
+ bun add rossa
15
+ ```
16
+
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
+
22
+ ## Create a server
23
+
24
+ Import the public API from the package entry point, create a `Rossa` instance,
25
+ declare controller classes, then register them. Route decorators use a path
26
+ pattern; named segments such as `:id` are available in `ctx.params`.
27
+
28
+ ```ts
29
+ import { Methods, Rossa, route } from "rossa";
30
+ import type { ctx } from "rossa";
31
+
32
+ const app = new Rossa();
33
+
34
+ @route("/users/:id")
35
+ class Users extends Methods {
36
+ get({ params, res }: ctx): Response {
37
+ return res.json({ id: params.id });
38
+ }
39
+ }
40
+
41
+ app.register(Users);
42
+ app.serve({ port: 3000, hostname: "localhost" });
43
+ ```
44
+
45
+ Call `app.getPaths()` after registering controllers to list HTTP paths, including
46
+ any `basePath`, with parameter colons removed (for example `["/users/id"]`).
47
+
48
+ `Rossa` accepts these options:
49
+
50
+ | Option | Default | Purpose |
51
+ | ---------------- | ------------ | --------------------------------------------------------------------------------------------------------- |
52
+ | `basePath` | `""` | Prefix added to registered HTTP and WebSocket routes. |
53
+ | `clientPath` | `"./public"` | Directory used by `res.fileServer()`. A relative path is resolved from the parent of `dirPath`. |
54
+ | `dirPath` | `"./src"` | Anchor used to resolve a relative `clientPath`. |
55
+ | `fileExtensions` | `[]` | Additional extensions to recognize, with or without a leading dot. Built-in extensions remain recognized. |
56
+ | `logError` | `false` | Log errors caught by the router pipeline. |
57
+ | `Encoding` | `"br"` | Response encoding; supports the `ContentEncodingType` values. |
58
+
59
+ `app.serve(serverOptions, websocketOptions)` starts Bun's server. The first
60
+ argument accepts Bun serve options plus an optional `fn(port)` callback. The
61
+ second argument accepts Bun WebSocket options plus Rossa's optional
62
+ `messageRateLimit`. If no port is provided, Rossa uses `3000`.
63
+
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.
67
+
68
+ ## Routes and request context
69
+
70
+ Extend `Methods` and define lower-case HTTP methods such as `get`, `post`,
71
+ `put`, `patch`, `delete`, `head`, and `options`. `event` handles server-sent
72
+ event requests. A route method receives `ctx`, whose `req` provides request
73
+ data and whose `res` builds the response.
74
+
75
+ ```ts
76
+ @route("/notes")
77
+ class Notes extends Methods {
78
+ async post({ req, res }: ctx): Promise<Response> {
79
+ const note = await req.json<{ title: string }>();
80
+ return res.status(201).json(note);
81
+ }
82
+ }
83
+ ```
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
+
89
+ Useful response methods include `text`, `html`, `json`, `success`, `error`,
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.
97
+
98
+ ## Guards
99
+
100
+ Use `app.use(...)` for application-wide guards. Use the `@use(...)` decorator
101
+ on a controller class or individual method for narrower scope. A guard factory
102
+ is configured first, then the returned guard is passed to `use`:
103
+
104
+ ```ts
105
+ import { Methods, Rossa, contentType, rateLimit, route, use } from "rossa";
106
+
107
+ const app = new Rossa();
108
+ app.use(rateLimit({ max: 60, windowMs: 60_000 }));
109
+
110
+ @route("/api")
111
+ @use(contentType("application/json"))
112
+ class Api extends Methods {
113
+ get() {
114
+ return Response.json({ ok: true });
115
+ }
116
+ }
117
+ ```
118
+
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.
157
+
158
+ ## WebSockets
159
+
160
+ Decorate a `Websocket` subclass with `@wss(path)` and register it with
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`.
165
+
166
+ ```ts
167
+ import { Rossa, Websocket, wss } from "rossa";
168
+ import type { wssMessage } from "rossa";
169
+
170
+ const app = new Rossa();
171
+
172
+ @wss("/chat")
173
+ class Chat extends Websocket {
174
+ open() {}
175
+ message(message: wssMessage) {
176
+ this.send = JSON.stringify(message);
177
+ }
178
+ close(code: number, reason: string) {}
179
+ }
180
+
181
+ app.registerWSS(Chat);
182
+ app.serve(
183
+ { port: 3000 },
184
+ {
185
+ maxPayloadLength: 64 * 1024,
186
+ messageRateLimit: { max: 60, windowMs: 10_000 },
187
+ backpressureLimit: 1024 * 1024,
188
+ closeOnBackpressureLimit: true,
189
+ },
190
+ );
191
+ ```
192
+
193
+ `messageRateLimit` is optional and counts inbound messages independently for
194
+ each socket using a fixed time window. When a socket exceeds its limit, Rossa
195
+ closes it with code `1008`. `maxPayloadLength`, `backpressureLimit`, and
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`.
203
+
204
+ For the handshake, frame parsing, lifecycle, and sample chat message contract,
205
+ see [`doc/websockets.md`](doc/websockets.md).
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
+
249
+ ## Test requests without starting a server
250
+
251
+ `app.test(request)` runs a `Request` through the same router pipeline and
252
+ returns a `Response`. The runnable [`test.ts`](test.ts) shows HTTP, guards,
253
+ WebSockets, and this method.
254
+
255
+ ```ts
256
+ const response = await app.test(
257
+ new Request("http://localhost:3000/api", { method: "GET" }),
258
+ );
259
+ console.log(response.status, await response.text());
260
+ ```
261
+
262
+ ## Public exports
263
+
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. |
283
+
284
+ Run the sample with `bun run test.ts`.
285
+
286
+ ## Load harness
287
+
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`,
291
+ `BENCH_MESSAGES_PER_SECOND`, `BENCH_DELIVERY_TIMEOUT_MS`, or
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.