rossa 0.0.5 → 0.0.6

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,226 @@
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, and optional WebSocket routes.
5
+
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
10
+
11
+ Rossa requires Bun. In an application, install the published package and import
12
+ its public API from `rossa`:
13
+
14
+ ```sh
15
+ bun add rossa
16
+ ```
17
+
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.
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 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
+ ```
51
+
52
+ `Rossa` accepts these options:
53
+
54
+ | Option | Default | Purpose |
55
+ | ---------------- | ------------ | --------------------------------------------------------------------------------------------------------- |
56
+ | `basePath` | `""` | Prefix added to registered HTTP and WebSocket routes. |
57
+ | `clientPath` | `"./public"` | Directory used by `res.fileServer()`. |
58
+ | `dirPath` | `"./src"` | Anchor used to resolve a relative `clientPath`. |
59
+ | `fileExtensions` | `[]` | Additional extensions to recognize, with or without a leading dot. Built-in extensions remain recognized. |
60
+ | `logError` | `false` | Log errors caught by the router pipeline. |
61
+ | `Encoding` | `"br"` | Response encoding; supports the `ContentEncodingType` values. |
62
+
63
+ `app.serve(serverOptions, websocketOptions)` starts Bun's server. The first
64
+ 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`.
67
+
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
+ ```
89
+
90
+ ## Routes and request context
91
+
92
+ Extend `Methods` and define lower-case HTTP methods such as `get`, `post`,
93
+ `put`, `patch`, `delete`, `head`, and `options`. `event` handles server-sent
94
+ event requests. A route method receives `ctx`, whose `req` provides request
95
+ data and whose `res` builds the response.
96
+
97
+ ```ts
98
+ @route("/notes")
99
+ class Notes extends Methods {
100
+ async post({ req, res }: ctx): Promise<Response> {
101
+ const note = await req.json<{ title: string }>();
102
+ return res.status(201).json(note);
103
+ }
104
+ }
105
+ ```
106
+
107
+ 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`.
110
+
111
+ ## Guards
112
+
113
+ Use `app.use(...)` for application-wide guards. Use the `@use(...)` decorator
114
+ on a controller class or individual method for narrower scope. A guard factory
115
+ is configured first, then the returned guard is passed to `use`:
116
+
117
+ ```ts
118
+ import { Methods, Rossa, contentType, rateLimit, route, use } from "rossa";
119
+
120
+ const app = new Rossa();
121
+ app.use(rateLimit({ max: 60, windowMs: 60_000 }));
122
+
123
+ @route("/api")
124
+ @use(contentType("application/json"))
125
+ class Api extends Methods {
126
+ get() {
127
+ return Response.json({ ok: true });
128
+ }
129
+ }
130
+ ```
131
+
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.
138
+
139
+ ## WebSockets
140
+
141
+ 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`.
146
+
147
+ ```ts
148
+ import { Rossa, Websocket, wss } from "rossa";
149
+ import type { wssMessage } from "rossa";
150
+
151
+ const app = new Rossa();
152
+
153
+ @wss("/chat")
154
+ class Chat extends Websocket {
155
+ open() {}
156
+ message(message: wssMessage) {
157
+ this.send = JSON.stringify(message);
158
+ }
159
+ close(code: number, reason: string) {}
160
+ }
161
+
162
+ app.registerWSS(Chat);
163
+ app.serve(
164
+ { port: 3000 },
165
+ {
166
+ maxPayloadLength: 64 * 1024,
167
+ messageRateLimit: { max: 60, windowMs: 10_000 },
168
+ backpressureLimit: 1024 * 1024,
169
+ closeOnBackpressureLimit: true,
170
+ },
171
+ );
172
+ ```
173
+
174
+ `messageRateLimit` is optional and counts inbound messages independently for
175
+ each socket using a fixed time window. When a socket exceeds its limit, Rossa
176
+ 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.
181
+
182
+ For the handshake, frame parsing, lifecycle, and sample chat message contract,
183
+ see [`doc/websockets.md`](doc/websockets.md).
184
+
185
+ ## Test requests without starting a server
186
+
187
+ `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.
190
+
191
+ ```ts
192
+ const response = await app.test(
193
+ new Request("http://localhost:3000/api", { method: "GET" }),
194
+ );
195
+ console.log(response.status, await response.text());
196
+ ```
197
+
198
+ ## Public exports
199
+
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.
211
+
212
+ Run the sample with `bun run test.ts`.
213
+
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
+ ## Load harness
219
+
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`,
223
+ `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.