@dim24/servin 0.0.1 → 0.2.2
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 +1033 -1063
- package/example/index.js +1 -1
- package/index.js +1 -1
- package/package.json +1 -1
- package/src/server.js +257 -28
- package/src/servin.test.js +77 -261
- package/src/tree.js +216 -17
- package/src/utils.js +139 -16
- package/src/wire.js +21 -0
package/README.md
CHANGED
|
@@ -2,95 +2,94 @@
|
|
|
2
2
|
|
|
3
3
|
**A modern, zero-dependency Node.js web server built around _Domain-Tree Projection_ and _Ambient Wire_.**
|
|
4
4
|
|
|
5
|
-
`servin` lets you build HTTP APIs, HTML pages, Server-Sent Events (SSE), and WebSockets using plain JavaScript functions and nested object trees. Instead of manually wiring string paths, `(req, res)` handlers, and `next()` middleware chains, you express your backend as a clean JavaScript object hierarchy while `servin` handles routing, parameter type coercion, self-invalidating caching, session persistence, rate limiting, and
|
|
5
|
+
`servin` lets you build HTTP APIs, static websites, HTML pages, Server-Sent Events (SSE), and WebSockets using plain JavaScript functions and nested object trees. Instead of manually wiring string paths, `(req, res)` handlers, and `next()` middleware chains, you express your backend as a clean JavaScript object hierarchy while `servin` handles routing, parameter type coercion, self-invalidating caching, session persistence, rate limiting, and zero-build frontend client generation automatically.
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
[see the real example usage here](https://github.com/harakun24/webserver-example)
|
|
8
8
|
|
|
9
9
|
## Table of Contents
|
|
10
10
|
|
|
11
11
|
1. [Why servin?](#1-why-servin)
|
|
12
12
|
2. [Requirements & Installation](#2-requirements--installation)
|
|
13
|
-
3. [Step-by-Step Walkthrough](#3-step-by-step-walkthrough)
|
|
14
|
-
- [Step 1:
|
|
15
|
-
- [Step 2:
|
|
16
|
-
- [Step 3:
|
|
17
|
-
- [Step 4:
|
|
18
|
-
- [Step 5:
|
|
19
|
-
- [Step 6:
|
|
20
|
-
- [Step 7:
|
|
21
|
-
|
|
22
|
-
- [
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
- [
|
|
26
|
-
- [
|
|
27
|
-
|
|
28
|
-
- [5.
|
|
29
|
-
- [5.
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
- [6.
|
|
33
|
-
- [6.
|
|
34
|
-
|
|
35
|
-
- [
|
|
36
|
-
7.
|
|
37
|
-
- [7.
|
|
38
|
-
- [7.
|
|
39
|
-
- [7.
|
|
40
|
-
|
|
41
|
-
- [
|
|
42
|
-
- [
|
|
43
|
-
8.
|
|
44
|
-
- [8.
|
|
45
|
-
- [8.
|
|
46
|
-
|
|
47
|
-
- [
|
|
48
|
-
- [
|
|
49
|
-
- [
|
|
50
|
-
- [
|
|
51
|
-
9.
|
|
52
|
-
- [9.
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
10.
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
- [
|
|
60
|
-
- [
|
|
61
|
-
|
|
62
|
-
- [
|
|
63
|
-
|
|
64
|
-
|
|
13
|
+
3. [Step-by-Step Core Walkthrough](#3-step-by-step-core-walkthrough)
|
|
14
|
+
- [Step 1: Starting the Server (`serve`)](#step-1-starting-the-server-serve)
|
|
15
|
+
- [Step 2: How URL Routing Works & Your First `GET`](#step-2-how-url-routing-works--your-first-get)
|
|
16
|
+
- [Step 3: Reading URL Query Parameters (`?done=true`)](#step-3-reading-url-query-parameters-donetrue)
|
|
17
|
+
- [Step 4: Dynamic URL Segments (`$id`) & Type Rules (`param`)](#step-4-dynamic-url-segments-id--type-rules-param)
|
|
18
|
+
- [Step 5: Creating Data with a Simple `POST`](#step-5-creating-data-with-a-simple-post)
|
|
19
|
+
- [Step 6: Setting HTTP Status Codes & Errors (`wire.status` & `wire.abort`)](#step-6-setting-http-status-codes--errors-wirestatus--wireabort)
|
|
20
|
+
- [Step 7: Updating (`patch` / `'put|patch'`) & Deleting (`delete`)](#step-7-updating-patch--putpatch--deleting-delete)
|
|
21
|
+
- [Step 8: Returning HTML (`wire.html` & `wire.file`)](#step-8-returning-html-wirehtml--wirefile)
|
|
22
|
+
- [Step 9: Assembled CRUD Server](#step-9-assembled-crud-server)
|
|
23
|
+
4. [Zero-Build Virtual ESM Client (`/@client.js`)](#4-zero-build-virtual-esm-client-clientjs)
|
|
24
|
+
- [4.1 Step 1: Importing `api` in Browser or Frontend Apps](#41-step-1-importing-api-in-browser-or-frontend-apps)
|
|
25
|
+
- [4.2 Step 2: Calling `GET`, `POST`, `PATCH`, `DELETE` & Typed Params](#42-step-2-calling-get-post-patch-delete--typed-params)
|
|
26
|
+
- [4.3 Step 3: Consuming SSE Streams & WebSockets on the Client](#43-step-3-consuming-sse-streams--websockets-on-the-client)
|
|
27
|
+
5. [Static Routing, Redirects & Custom Error Pages](#5-static-routing-redirects--custom-error-pages)
|
|
28
|
+
- [5.1 Static File & Folder Routing (`serveStatic` & `static`)](#51-static-file--folder-routing-servestatic--static)
|
|
29
|
+
- [5.2 HTTP Redirects (`wire.redirect` & `redirect`)](#52-http-redirects-wireredirect--redirect)
|
|
30
|
+
- [5.3 Custom Error Pages (`404`, `401`, `403`, `500`, etc.)](#53-custom-error-pages-404-401-403-500-etc)
|
|
31
|
+
6. [Server Configuration (`serve`)](#6-server-configuration-serve)
|
|
32
|
+
- [6.1 All `serve()` Options](#61-all-serve-options)
|
|
33
|
+
- [6.2 Server Instance Control (`port`, `url`, `fetch`, `close`)](#62-server-instance-control-port-url-fetch-close)
|
|
34
|
+
7. [Domain-Tree Projection & Routing](#7-domain-tree-projection--routing)
|
|
35
|
+
- [7.1 Static, Dynamic, Typed, and Wildcard Segments](#71-static-dynamic-typed-and-wildcard-segments)
|
|
36
|
+
- [7.2 Automatic Route Matching Priority](#72-automatic-route-matching-priority)
|
|
37
|
+
- [7.3 Method Unions (`'put|patch'`) & Shorthand Leaf Functions](#73-method-unions-putpatch--shorthand-leaf-functions)
|
|
38
|
+
- [7.4 Handler Argument Order](#74-handler-argument-order)
|
|
39
|
+
- [7.5 Typed Route Parameters (`param`) — All Supported Types & Custom Formats](#75-typed-route-parameters-param--all-supported-types--custom-formats)
|
|
40
|
+
8. [Response Formatting, HTML & Streaming](#8-response-formatting-html--streaming)
|
|
41
|
+
- [8.1 Automatic `Content-Type` Matrix](#81-automatic-content-type-matrix)
|
|
42
|
+
- [8.2 HTML Responses & XSS Protection (`wire.html`)](#82-html-responses--xss-protection-wirehtml)
|
|
43
|
+
- [8.3 File Streaming with `ETag` & Byte-Range (`wire.file`)](#83-file-streaming-with-etag--byte-range-wirefile)
|
|
44
|
+
- [8.4 Server-Sent Events (SSE) with Async Generators](#84-server-sent-events-sse-with-async-generators)
|
|
45
|
+
- [8.5 Sparse Fieldsets (`?fields=`) & Automatic Redaction (`redact`)](#85-sparse-fieldsets-fields--automatic-redaction-redact)
|
|
46
|
+
9. [Security, Sessions & Traffic Control](#9-security-sessions--traffic-control)
|
|
47
|
+
- [9.1 Protecting Routes & Branches (`guard`)](#91-protecting-routes--branches-guard)
|
|
48
|
+
- [9.2 Lazy Encrypted Sessions (`wire.session` & `wire.sessions`)](#92-lazy-encrypted-sessions-wiresession--wiresessions)
|
|
49
|
+
- [9.3 Custom Session Store Interface (Redis / Database)](#93-custom-session-store-interface-redis--database)
|
|
50
|
+
- [9.4 Timing-Safe Webhook Verification (`webhook`)](#94-timing-safe-webhook-verification-webhook)
|
|
51
|
+
- [9.5 Rate Limiting (`limit` & `wire.cost`)](#95-rate-limiting-limit--wirecost)
|
|
52
|
+
- [9.6 CORS & Preflight Handling (`origins`)](#96-cors--preflight-handling-origins)
|
|
53
|
+
10. [Caching, Validation & Resilience](#10-caching-validation--resilience)
|
|
54
|
+
- [10.1 Self-Invalidating Response Cache (`cache`)](#101-self-invalidating-response-cache-cache)
|
|
55
|
+
- [10.2 Request Coalescing (`coalesce`)](#102-request-coalescing-coalesce)
|
|
56
|
+
- [10.3 Idempotent Mutations (`idempotent`)](#103-idempotent-mutations-idempotent)
|
|
57
|
+
- [10.4 Declarative Input Validation (`expect`)](#104-declarative-input-validation-expect)
|
|
58
|
+
- [10.5 Automatic Rollbacks (`wire.undo`) & Dry-Runs (`X-Simulate`)](#105-automatic-rollbacks-wireundo--dry-runs-x-simulate)
|
|
59
|
+
- [10.6 Graceful Background Tasks (`wire.defer`)](#106-graceful-background-tasks-wiredefer)
|
|
60
|
+
- [10.7 Load Shedding (`priority: 'low'`) & Deprecation (`sunset`)](#107-load-shedding-priority-low--deprecation-sunset)
|
|
61
|
+
11. [Linear WebSockets & Pub/Sub](#11-linear-websockets--pubsub)
|
|
62
|
+
- [11.1 Step 1: Minimal Echo WebSocket (`ws` & `for await`)](#111-step-1-minimal-echo-websocket-ws--for-await)
|
|
63
|
+
- [11.2 Step 2: Rooms & Pub/Sub Broadcasting (`socket.join`, `wire.publish`)](#112-step-2-rooms--pubsub-broadcasting-socketjoin-wirepublish)
|
|
64
|
+
- [11.3 Step 3: Guarded WebSockets & `wsConfig`](#113-step-3-guarded-websockets--wsconfig)
|
|
65
|
+
12. [Streaming File Uploads (`wire.multipart` & `rawBody`)](#12-streaming-file-uploads-wiremultipart--rawbody)
|
|
66
|
+
13. [Decoupled Side Effects (`reactTo`)](#13-decoupled-side-effects-reactto)
|
|
67
|
+
14. [Logging, Debugging & Automated Testing](#14-logging-debugging--automated-testing)
|
|
68
|
+
- [14.1 Startup Messages & Access Logs (`message`, `onListen`, `accessLog`)](#141-startup-messages--access-logs-message-onlisten-accesslog)
|
|
69
|
+
- [14.2 Error-Triggered Debug Trace (`wire.log.debug`) & `Server-Timing` (`wire.mark`)](#142-error-triggered-debug-trace-wirelogdebug--server-timing-wiremark)
|
|
70
|
+
- [14.3 Automated Test Synthesis (`synthesizeTests`)](#143-automated-test-synthesis-synthesizetests)
|
|
71
|
+
- [14.4 Error Snapshots & Local Replay (`snapshotOnError` & `replay`)](#144-error-snapshots--local-replay-snapshotonerror--replay)
|
|
72
|
+
15. [Complete Ambient `wire` API Reference](#15-complete-ambient-wire-api-reference)
|
|
73
|
+
16. [License](#16-license)
|
|
65
74
|
|
|
66
75
|
---
|
|
67
76
|
|
|
68
77
|
## 1. Why servin?
|
|
69
78
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
`servin` replaces string routing and middleware chains with two cohesive primitives:
|
|
79
|
+
Conventional Node.js frameworks require you to bind handlers to string URLs, chain `(req, res, next)` middleware, manually parse and validate route parameters, and maintain separate client-side `fetch()` wrappers alongside separate WebSocket and cache-invalidation systems.
|
|
73
80
|
|
|
74
|
-
|
|
75
|
-
2. **Ambient `wire`:** Backed by Node.js `AsyncLocalStorage`, `wire` gives any function in your call stack direct access to headers, status codes, sessions, rollbacks, background tasks, and pub/sub broadcasts without passing `req` or `res` arguments around.
|
|
81
|
+
`servin` replaces that boilerplate with two core concepts:
|
|
76
82
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
| **Route Definition** | String paths (`app.get('/users/:id', ...)`). | Plain JS object tree (`users: { $id: param('int', { get(id) { ... } }) }`). |
|
|
80
|
-
| **Parameter Validation** | Manual `Number(req.params.id)` + `Number.isNaN()` checks in every handler. | Declarative `param('int', branch)` validates before dispatch and passes typed values (`number`, `boolean`, `bigint`). |
|
|
81
|
-
| **Cache Invalidation** | Manual cache key tracking and deletion across update/delete routes. | `cache: '5m'` caches `GET` responses and automatically purges node and parent caches on `POST`, `PUT`, `PATCH`, or `DELETE`. |
|
|
82
|
-
| **Traffic Spikes** | Concurrent requests execute redundant database queries unless custom locks are built. | `coalesce: true` merges simultaneous identical `GET` requests into a single execution. |
|
|
83
|
-
| **Session Overhead** | Global middleware parses cookies and queries stores on every request, including public routes. | **Lazy Proxy:** zero cookie decryption or store lookups unless `wire.session` is actually read or written. |
|
|
84
|
-
| **WebSockets** | Separate callback registration (`open`, `message`, `close`) detached from HTTP routes. | Co-located `ws` method in the same domain tree using a linear `for await (const msg of socket)` loop. |
|
|
85
|
-
| **Frontend Integration** | Hand-written `fetch()` wrappers or build-time OpenAPI code generators. | Native browser/ESM import from `/@client.js` with zero build step. |
|
|
83
|
+
1. **Domain-Tree Projection:** You structure your backend as a plain nested JavaScript object. `servin` projects that tree directly onto HTTP endpoints, static assets, SSE streams, WebSockets, and a browser-ready ES module (`/@client.js`).
|
|
84
|
+
2. **Ambient `wire`:** Powered by Node.js `AsyncLocalStorage`, `wire` lets any function read headers, set status codes, issue redirects, manage sessions, register rollbacks, or publish WebSocket messages without passing `req` or `res` arguments down the call stack.
|
|
86
85
|
|
|
87
86
|
---
|
|
88
87
|
|
|
89
88
|
## 2. Requirements & Installation
|
|
90
89
|
|
|
91
|
-
- **Runtime:** Node.js `v20.0.0` or higher
|
|
92
|
-
- **Dependencies:** Zero external
|
|
93
|
-
- **Module
|
|
90
|
+
- **Runtime:** Node.js `v20.0.0` or higher.
|
|
91
|
+
- **Dependencies:** Zero external dependencies.
|
|
92
|
+
- **Module Format:** ES Modules (`"type": "module"` in `package.json`).
|
|
94
93
|
|
|
95
94
|
Install `servin`:
|
|
96
95
|
|
|
@@ -98,386 +97,336 @@ Install `servin`:
|
|
|
98
97
|
npm install servin
|
|
99
98
|
```
|
|
100
99
|
|
|
100
|
+
Verify your `package.json` includes `"type": "module"`:
|
|
101
|
+
|
|
102
|
+
```json
|
|
103
|
+
{
|
|
104
|
+
"name": "my-servin-app",
|
|
105
|
+
"type": "module",
|
|
106
|
+
"scripts": {
|
|
107
|
+
"start": "node server.js"
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
101
112
|
---
|
|
102
113
|
|
|
103
|
-
## 3. Step-by-Step Walkthrough
|
|
114
|
+
## 3. Step-by-Step Core Walkthrough
|
|
104
115
|
|
|
105
|
-
### Step 1:
|
|
116
|
+
### Step 1: Starting the Server (`serve`)
|
|
106
117
|
|
|
107
|
-
Create
|
|
118
|
+
Create `server.js` and call `serve()`. By default, it listens on `127.0.0.1:3000`:
|
|
108
119
|
|
|
109
120
|
```javascript
|
|
110
121
|
import { serve } from "servin";
|
|
111
122
|
|
|
112
123
|
await serve({
|
|
113
124
|
port: 3000,
|
|
114
|
-
message: ({ port, url }) => `Server is running on port ${port} (${url})`,
|
|
115
125
|
api: {},
|
|
116
126
|
});
|
|
117
127
|
```
|
|
118
128
|
|
|
119
|
-
|
|
129
|
+
You can customize the startup log message using `message`:
|
|
120
130
|
|
|
121
|
-
|
|
131
|
+
```javascript
|
|
132
|
+
import { serve } from "servin";
|
|
133
|
+
|
|
134
|
+
await serve({
|
|
135
|
+
port: 3000,
|
|
136
|
+
message: ({ port }) => `Server is running on port ${port}`,
|
|
137
|
+
api: {},
|
|
138
|
+
});
|
|
139
|
+
```
|
|
122
140
|
|
|
123
|
-
### Step 2:
|
|
141
|
+
### Step 2: How URL Routing Works & Your First `GET`
|
|
124
142
|
|
|
125
|
-
In `servin`, **you never write URL strings**.
|
|
143
|
+
In `servin`, **you never write URL path strings**. Every object key inside `api` becomes a URL segment, and a lowercase HTTP verb (`get`, `post`, `put`, `patch`, `delete`) defines the handler:
|
|
126
144
|
|
|
127
145
|
```text
|
|
128
|
-
|
|
129
|
-
|
|
146
|
+
Object Tree HTTP Endpoint
|
|
147
|
+
───────────────────────────────────────────────────────────────
|
|
130
148
|
api: {
|
|
131
|
-
|
|
132
|
-
get() { ... }
|
|
149
|
+
hello: {
|
|
150
|
+
get() { ... } ──────► GET /hello
|
|
133
151
|
},
|
|
134
152
|
tasks: {
|
|
135
|
-
get(
|
|
153
|
+
get() { ... } ──────► GET /tasks
|
|
136
154
|
}
|
|
137
155
|
}
|
|
138
156
|
```
|
|
139
157
|
|
|
140
|
-
Any plain object or array
|
|
158
|
+
Any plain object or array you `return` is automatically serialized as `application/json` (`200 OK`):
|
|
141
159
|
|
|
142
160
|
```javascript
|
|
143
161
|
import { serve } from "servin";
|
|
144
162
|
|
|
145
|
-
const tasksDb =
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
{
|
|
150
|
-
id: 2,
|
|
151
|
-
title: "Write integration tests",
|
|
152
|
-
priority: "medium",
|
|
153
|
-
done: false,
|
|
154
|
-
},
|
|
155
|
-
],
|
|
156
|
-
]);
|
|
163
|
+
const tasksDb = [
|
|
164
|
+
{ id: 1, title: "Learn servin", done: true },
|
|
165
|
+
{ id: 2, title: "Build an API", done: false },
|
|
166
|
+
];
|
|
157
167
|
|
|
158
168
|
await serve({
|
|
159
169
|
port: 3000,
|
|
160
170
|
api: {
|
|
161
|
-
// GET /
|
|
162
|
-
|
|
163
|
-
get: () => ({
|
|
171
|
+
// GET /hello
|
|
172
|
+
hello: {
|
|
173
|
+
get: () => ({ message: "Hello from servin!" }),
|
|
164
174
|
},
|
|
165
175
|
|
|
166
|
-
// GET /tasks
|
|
176
|
+
// GET /tasks
|
|
167
177
|
tasks: {
|
|
168
|
-
get(
|
|
169
|
-
let list = [...tasksDb.values()];
|
|
170
|
-
if (query.done === "true") list = list.filter((t) => t.done);
|
|
171
|
-
if (query.done === "false") list = list.filter((t) => !t.done);
|
|
172
|
-
return list;
|
|
173
|
-
},
|
|
178
|
+
get: () => tasksDb,
|
|
174
179
|
},
|
|
175
180
|
},
|
|
176
181
|
});
|
|
177
182
|
```
|
|
178
183
|
|
|
179
|
-
|
|
184
|
+
### Step 3: Reading URL Query Parameters (`?done=true`)
|
|
180
185
|
|
|
181
|
-
|
|
186
|
+
Every `get()` handler automatically receives a `query` object containing the URL search parameters:
|
|
187
|
+
|
|
188
|
+
```javascript
|
|
189
|
+
const tasks = {
|
|
190
|
+
// GET /tasks?done=false
|
|
191
|
+
get(query) {
|
|
192
|
+
if (query.done === "true") {
|
|
193
|
+
return tasksDb.filter((t) => t.done);
|
|
194
|
+
}
|
|
195
|
+
if (query.done === "false") {
|
|
196
|
+
return tasksDb.filter((t) => !t.done);
|
|
197
|
+
}
|
|
198
|
+
return tasksDb;
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
```
|
|
182
202
|
|
|
183
|
-
|
|
203
|
+
### Step 4: Dynamic URL Segments (`$id`) & Type Rules (`param`)
|
|
184
204
|
|
|
185
|
-
|
|
186
|
-
2. **Automatic Type Coercion:** The `id` argument passed to `get(id)` is already a JavaScript `number` (`1`), not a string (`"1"`).
|
|
205
|
+
Prefix a key with `$` to capture a dynamic URL segment:
|
|
187
206
|
|
|
188
|
-
```
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
}
|
|
207
|
+
```javascript
|
|
208
|
+
// Matches ANY string: /tasks/1, /tasks/abc, /tasks/hello
|
|
209
|
+
const tasks = {
|
|
210
|
+
$id: {
|
|
211
|
+
get(id) {
|
|
212
|
+
return { rawId: id }; // `id` is always a string when untyped
|
|
213
|
+
},
|
|
214
|
+
},
|
|
215
|
+
};
|
|
196
216
|
```
|
|
197
217
|
|
|
198
|
-
|
|
218
|
+
To restrict a parameter to a specific type or pattern while keeping object keys as clean JavaScript identifiers, wrap the branch in **`param(rule, branch)`**. `param()` supports built-in types (`'int'`, `'number'`, `'float'`, `'bigint'`, `'uuid'`, `'alpha'`, `'alnum'`, `'slug'`, `'bool'`, `'boolean'`, `'string'`), native constructors (`Number`, `Boolean`, `BigInt`, `String`), regular expressions (`/^[A-Z]{3}-\d+$/`), custom functions, and named custom types from `serve({ types })`.
|
|
199
219
|
|
|
200
220
|
```javascript
|
|
201
|
-
import {
|
|
221
|
+
import { param } from "servin";
|
|
202
222
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
// GET /tasks
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
},
|
|
211
|
-
}
|
|
223
|
+
const tasks = {
|
|
224
|
+
// GET /tasks/1 -> matches! `id` is coerced to number `1`
|
|
225
|
+
// GET /tasks/abc -> automatically rejected with 404 Not Found
|
|
226
|
+
$id: param("int", {
|
|
227
|
+
get(id) {
|
|
228
|
+
return tasksDb.find((t) => t.id === id);
|
|
229
|
+
},
|
|
230
|
+
}),
|
|
231
|
+
};
|
|
212
232
|
```
|
|
213
233
|
|
|
214
|
-
|
|
234
|
+
See [Section 7.5](#75-typed-route-parameters-param--all-supported-types--custom-formats) for every supported type and custom format option.
|
|
215
235
|
|
|
216
|
-
###
|
|
236
|
+
### Direct Path Parameters on Route Nodes (`wire.params` & `wire.param(name)`)
|
|
217
237
|
|
|
218
|
-
|
|
238
|
+
Read trailing path segments directly inside a route handler without creating a separate `$id` child branch.
|
|
219
239
|
|
|
220
|
-
- `
|
|
221
|
-
- `
|
|
222
|
-
- `wire.undo(fn)`: Registers a rollback action that automatically undoes the database write if a later step throws an error—or if the client sends `X-Simulate: true` for a dry-run.
|
|
223
|
-
- `wire.status(201)`: Sets the HTTP response status to `201 Created`.
|
|
240
|
+
- `GET /profile?id=234` reads query parameters via `wire.url.searchParams.get('id')`.
|
|
241
|
+
- `GET /profile/234` reads the trailing path segment directly via `wire.params.id` or `wire.param('id')`.
|
|
224
242
|
|
|
225
|
-
|
|
226
|
-
import { wire } from
|
|
243
|
+
````javascript
|
|
244
|
+
import { serve, wire } from './index.js';
|
|
245
|
+
|
|
246
|
+
await serve({
|
|
247
|
+
port: 3000,
|
|
248
|
+
api: {
|
|
249
|
+
profile: {
|
|
250
|
+
get() {
|
|
251
|
+
const id = wire.param('id'); // or wire.params.id
|
|
252
|
+
const queryId = wire.url.searchParams.get('id');
|
|
253
|
+
return { id, queryId };
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
### Step 5: Creating Data with a Simple `POST`
|
|
260
|
+
|
|
261
|
+
Add a `post(payload)` method to handle `POST /tasks`. `servin` automatically parses the incoming JSON body and passes it as `payload`:
|
|
227
262
|
|
|
263
|
+
```javascript
|
|
228
264
|
let nextId = 3;
|
|
229
265
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
priority: ["low", "medium", "high"],
|
|
235
|
-
done: "boolean?",
|
|
236
|
-
},
|
|
237
|
-
idempotent: "10m",
|
|
266
|
+
const tasks = {
|
|
267
|
+
get: () => tasksDb,
|
|
268
|
+
|
|
269
|
+
// POST /tasks
|
|
238
270
|
post(payload) {
|
|
239
|
-
const
|
|
240
|
-
|
|
241
|
-
id,
|
|
271
|
+
const newTask = {
|
|
272
|
+
id: nextId++,
|
|
242
273
|
title: payload.title,
|
|
243
|
-
|
|
244
|
-
done: payload.done ?? false,
|
|
274
|
+
done: false,
|
|
245
275
|
};
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
wire.undo(() => tasksDb.delete(id));
|
|
249
|
-
wire.status(201);
|
|
250
|
-
return record;
|
|
276
|
+
tasksDb.push(newTask);
|
|
277
|
+
return newTask;
|
|
251
278
|
},
|
|
252
279
|
};
|
|
253
|
-
|
|
280
|
+
````
|
|
254
281
|
|
|
255
|
-
|
|
282
|
+
### Step 6: Setting HTTP Status Codes & Errors (`wire.status` & `wire.abort`)
|
|
256
283
|
|
|
257
|
-
|
|
284
|
+
Import `wire` when you need to change the HTTP status code or stop a request with an error:
|
|
258
285
|
|
|
259
|
-
|
|
286
|
+
- `wire.status(201)` sets the response status to `201 Created`.
|
|
287
|
+
- `wire.abort(404, 'Message')` immediately stops execution and returns `{ "error": "Message" }` with status `404`.
|
|
260
288
|
|
|
261
|
-
|
|
262
|
-
|
|
289
|
+
```javascript
|
|
290
|
+
import { wire, param } from "servin";
|
|
263
291
|
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
292
|
+
const tasks = {
|
|
293
|
+
post(payload) {
|
|
294
|
+
const newTask = { id: nextId++, title: payload.title, done: false };
|
|
295
|
+
tasksDb.push(newTask);
|
|
296
|
+
|
|
297
|
+
wire.status(201); // Return 201 Created instead of 200
|
|
298
|
+
return newTask;
|
|
299
|
+
},
|
|
300
|
+
|
|
301
|
+
$id: param("int", {
|
|
302
|
+
get(id) {
|
|
303
|
+
const task = tasksDb.find((t) => t.id === id);
|
|
304
|
+
if (!task) wire.abort(404, `Task #${id} not found`);
|
|
305
|
+
return task;
|
|
306
|
+
},
|
|
307
|
+
}),
|
|
308
|
+
};
|
|
270
309
|
```
|
|
271
310
|
|
|
272
|
-
|
|
273
|
-
import { wire, param } from "servin";
|
|
311
|
+
### Step 7: Updating (`patch` / `'put|patch'`) & Deleting (`delete`)
|
|
274
312
|
|
|
275
|
-
|
|
276
|
-
cache: "5m",
|
|
313
|
+
Add `patch` (or `'put|patch'` to handle both verbs in one function) and `delete` inside `$id`:
|
|
277
314
|
|
|
278
|
-
|
|
315
|
+
```javascript
|
|
316
|
+
const taskById = param("int", {
|
|
279
317
|
get(id) {
|
|
280
|
-
const task = tasksDb.
|
|
318
|
+
const task = tasksDb.find((t) => t.id === id);
|
|
281
319
|
if (!task) wire.abort(404, `Task #${id} not found`);
|
|
282
320
|
return task;
|
|
283
321
|
},
|
|
284
322
|
|
|
285
|
-
//
|
|
286
|
-
|
|
287
|
-
const
|
|
288
|
-
if (!
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
wire.method === "PATCH"
|
|
292
|
-
? { ...existing, ...payload, id }
|
|
293
|
-
: {
|
|
294
|
-
id,
|
|
295
|
-
title: payload.title,
|
|
296
|
-
priority: payload.priority || "medium",
|
|
297
|
-
done: Boolean(payload.done),
|
|
298
|
-
};
|
|
299
|
-
|
|
300
|
-
tasksDb.set(id, updated);
|
|
301
|
-
return updated;
|
|
323
|
+
// PATCH /tasks/:id
|
|
324
|
+
patch(id, payload) {
|
|
325
|
+
const task = tasksDb.find((t) => t.id === id);
|
|
326
|
+
if (!task) wire.abort(404, `Task #${id} not found`);
|
|
327
|
+
Object.assign(task, payload);
|
|
328
|
+
return task;
|
|
302
329
|
},
|
|
303
330
|
|
|
304
331
|
// DELETE /tasks/:id
|
|
305
332
|
delete(id) {
|
|
306
|
-
|
|
307
|
-
|
|
333
|
+
const idx = tasksDb.findIndex((t) => t.id === id);
|
|
334
|
+
if (idx === -1) wire.abort(404, `Task #${id} not found`);
|
|
335
|
+
tasksDb.splice(idx, 1);
|
|
308
336
|
wire.status(204);
|
|
309
|
-
return null;
|
|
337
|
+
return null; // Sends empty 204 No Content
|
|
310
338
|
},
|
|
311
339
|
});
|
|
312
340
|
```
|
|
313
341
|
|
|
314
|
-
|
|
342
|
+
### Step 8: Returning HTML (`wire.html` & `wire.file`)
|
|
315
343
|
|
|
316
|
-
|
|
344
|
+
By default, returning a plain `string` sends `text/plain` so user text cannot accidentally execute scripts. To serve HTML:
|
|
317
345
|
|
|
318
|
-
|
|
346
|
+
**Option A — Inline HTML string with `wire.html`:**
|
|
319
347
|
|
|
320
348
|
```javascript
|
|
321
|
-
|
|
349
|
+
const home = {
|
|
350
|
+
get: () => wire.html("<h1>Welcome to Task Manager</h1>"),
|
|
351
|
+
};
|
|
352
|
+
```
|
|
322
353
|
|
|
323
|
-
|
|
324
|
-
reactTo(tasks.post, ({ output }) => {
|
|
325
|
-
wire.log.info(`Created task #${output.id}: ${output.title}`);
|
|
326
|
-
});
|
|
354
|
+
**Option B — Tagged template ``wire.html`...` `` (auto-escapes variables against XSS):**
|
|
327
355
|
|
|
328
|
-
|
|
329
|
-
const
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
<head>
|
|
335
|
-
<meta charset="utf-8">
|
|
336
|
-
<title>servin Tasks</title>
|
|
337
|
-
</head>
|
|
338
|
-
<body>
|
|
339
|
-
<h1>Tasks (${tasksDb.size})</h1>
|
|
340
|
-
<ul id="list"></ul>
|
|
341
|
-
<script type="module">
|
|
342
|
-
import { api } from '/@client.js';
|
|
343
|
-
const items = await api.tasks.get();
|
|
344
|
-
document.getElementById('list').innerHTML = items
|
|
345
|
-
.map((t) => \`<li>[\${t.priority}] \${t.title}</li>\`)
|
|
346
|
-
.join('');
|
|
347
|
-
</script>
|
|
348
|
-
</body>
|
|
349
|
-
</html>
|
|
350
|
-
`;
|
|
356
|
+
```javascript
|
|
357
|
+
const greet = {
|
|
358
|
+
$name: {
|
|
359
|
+
get(name) {
|
|
360
|
+
return wire.html`<h1>Hello, ${name}!</h1>`;
|
|
361
|
+
},
|
|
351
362
|
},
|
|
352
363
|
};
|
|
353
364
|
```
|
|
354
365
|
|
|
355
|
-
|
|
366
|
+
**Option C — Streaming an HTML file from disk with `wire.file`:**
|
|
367
|
+
|
|
368
|
+
```javascript
|
|
369
|
+
const about = {
|
|
370
|
+
get: () => wire.file("./pages/about.html"),
|
|
371
|
+
};
|
|
372
|
+
```
|
|
356
373
|
|
|
357
|
-
### Step
|
|
374
|
+
### Step 9: Assembled CRUD Server
|
|
358
375
|
|
|
359
|
-
|
|
376
|
+
Combining Steps 1–8 gives you a complete, readable CRUD server:
|
|
360
377
|
|
|
361
378
|
```javascript
|
|
362
|
-
import { serve, wire, param
|
|
379
|
+
import { serve, wire, param } from "servin";
|
|
363
380
|
|
|
364
|
-
const tasksDb =
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
{
|
|
369
|
-
id: 2,
|
|
370
|
-
title: "Write integration tests",
|
|
371
|
-
priority: "medium",
|
|
372
|
-
done: false,
|
|
373
|
-
},
|
|
374
|
-
],
|
|
375
|
-
]);
|
|
381
|
+
const tasksDb = [
|
|
382
|
+
{ id: 1, title: "Learn servin", done: true },
|
|
383
|
+
{ id: 2, title: "Build an API", done: false },
|
|
384
|
+
];
|
|
376
385
|
let nextId = 3;
|
|
377
386
|
|
|
378
387
|
const tasks = {
|
|
379
|
-
cache: "5m",
|
|
380
|
-
|
|
381
|
-
// GET /tasks?done=false
|
|
382
388
|
get(query) {
|
|
383
|
-
|
|
384
|
-
if (query.done === "
|
|
385
|
-
|
|
386
|
-
return list;
|
|
389
|
+
if (query.done === "true") return tasksDb.filter((t) => t.done);
|
|
390
|
+
if (query.done === "false") return tasksDb.filter((t) => !t.done);
|
|
391
|
+
return tasksDb;
|
|
387
392
|
},
|
|
388
393
|
|
|
389
|
-
// POST /tasks
|
|
390
|
-
expect: {
|
|
391
|
-
title: "string",
|
|
392
|
-
priority: ["low", "medium", "high"],
|
|
393
|
-
done: "boolean?",
|
|
394
|
-
},
|
|
395
|
-
idempotent: "10m",
|
|
396
394
|
post(payload) {
|
|
397
|
-
const
|
|
398
|
-
|
|
399
|
-
id,
|
|
400
|
-
title: payload.title,
|
|
401
|
-
priority: payload.priority,
|
|
402
|
-
done: payload.done ?? false,
|
|
403
|
-
};
|
|
404
|
-
tasksDb.set(id, record);
|
|
405
|
-
wire.undo(() => tasksDb.delete(id));
|
|
395
|
+
const newTask = { id: nextId++, title: payload.title, done: false };
|
|
396
|
+
tasksDb.push(newTask);
|
|
406
397
|
wire.status(201);
|
|
407
|
-
return
|
|
398
|
+
return newTask;
|
|
408
399
|
},
|
|
409
400
|
|
|
410
|
-
// /tasks/:id (integer-only)
|
|
411
401
|
$id: param("int", {
|
|
412
|
-
cache: "5m",
|
|
413
|
-
|
|
414
402
|
get(id) {
|
|
415
|
-
const task = tasksDb.
|
|
403
|
+
const task = tasksDb.find((t) => t.id === id);
|
|
416
404
|
if (!task) wire.abort(404, `Task #${id} not found`);
|
|
417
405
|
return task;
|
|
418
406
|
},
|
|
419
407
|
|
|
420
|
-
|
|
421
|
-
const
|
|
422
|
-
if (!
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
wire.method === "PATCH"
|
|
426
|
-
? { ...existing, ...payload, id }
|
|
427
|
-
: {
|
|
428
|
-
id,
|
|
429
|
-
title: payload.title,
|
|
430
|
-
priority: payload.priority || "medium",
|
|
431
|
-
done: Boolean(payload.done),
|
|
432
|
-
};
|
|
433
|
-
|
|
434
|
-
tasksDb.set(id, updated);
|
|
435
|
-
return updated;
|
|
408
|
+
patch(id, payload) {
|
|
409
|
+
const task = tasksDb.find((t) => t.id === id);
|
|
410
|
+
if (!task) wire.abort(404, `Task #${id} not found`);
|
|
411
|
+
Object.assign(task, payload);
|
|
412
|
+
return task;
|
|
436
413
|
},
|
|
437
414
|
|
|
438
415
|
delete(id) {
|
|
439
|
-
|
|
440
|
-
|
|
416
|
+
const idx = tasksDb.findIndex((t) => t.id === id);
|
|
417
|
+
if (idx === -1) wire.abort(404, `Task #${id} not found`);
|
|
418
|
+
tasksDb.splice(idx, 1);
|
|
441
419
|
wire.status(204);
|
|
442
420
|
return null;
|
|
443
421
|
},
|
|
444
422
|
}),
|
|
445
423
|
};
|
|
446
424
|
|
|
447
|
-
reactTo(tasks.post, ({ output }) => {
|
|
448
|
-
wire.log.info(`Created task #${output.id}: ${output.title}`);
|
|
449
|
-
});
|
|
450
|
-
|
|
451
|
-
const home = {
|
|
452
|
-
get() {
|
|
453
|
-
return wire.html`
|
|
454
|
-
<!doctype html>
|
|
455
|
-
<html lang="en">
|
|
456
|
-
<head>
|
|
457
|
-
<meta charset="utf-8">
|
|
458
|
-
<title>servin Tasks</title>
|
|
459
|
-
</head>
|
|
460
|
-
<body>
|
|
461
|
-
<h1>Tasks (${tasksDb.size})</h1>
|
|
462
|
-
<ul id="list"></ul>
|
|
463
|
-
<script type="module">
|
|
464
|
-
import { api } from '/@client.js';
|
|
465
|
-
const items = await api.tasks.get();
|
|
466
|
-
document.getElementById('list').innerHTML = items
|
|
467
|
-
.map((t) => \`<li>[\${t.priority}] \${t.title}</li>\`)
|
|
468
|
-
.join('');
|
|
469
|
-
</script>
|
|
470
|
-
</body>
|
|
471
|
-
</html>
|
|
472
|
-
`;
|
|
473
|
-
},
|
|
474
|
-
};
|
|
475
|
-
|
|
476
425
|
await serve({
|
|
477
426
|
port: 3000,
|
|
478
|
-
message: ({ port
|
|
427
|
+
message: ({ port }) => `Server is running on port ${port}`,
|
|
479
428
|
api: {
|
|
480
|
-
home,
|
|
429
|
+
home: { get: () => wire.html("<h1>Task Manager</h1>") },
|
|
481
430
|
tasks,
|
|
482
431
|
},
|
|
483
432
|
});
|
|
@@ -485,169 +434,411 @@ await serve({
|
|
|
485
434
|
|
|
486
435
|
---
|
|
487
436
|
|
|
488
|
-
## 4.
|
|
437
|
+
## 4. Zero-Build Virtual ESM Client (`/@client.js`)
|
|
489
438
|
|
|
490
|
-
`
|
|
439
|
+
Because `servin` compiles your `api` tree at startup, it automatically serves **`GET /@client.js`**—a lightweight, zero-dependency ES module that mirrors your exact backend domain structure.
|
|
491
440
|
|
|
492
|
-
|
|
441
|
+
Frontend code (vanilla HTML `<script type="module">`, React, Vue, Svelte, or Vite) can import `api` directly from `/@client.js` **without writing `fetch()`, URL strings, JSON serialization, or build-step code generators**.
|
|
493
442
|
|
|
494
|
-
|
|
495
|
-
| :---------------- | :---------------------------- | :------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
496
|
-
| `port` | `number` | `3000` | TCP port to listen on. Pass `0` to let the OS assign an available ephemeral port. |
|
|
497
|
-
| `host` | `string` | `'127.0.0.1'` | Network interface to bind (use `'0.0.0.0'` for containers/external access). |
|
|
498
|
-
| `api` | `object` | `{}` | The root domain tree defining all HTTP routes, SSE streams, and WebSocket endpoints. |
|
|
499
|
-
| `types` | `object` | `{}` | Dictionary of named custom parameter rules (`RegExp` or validator functions) usable via `param('typeName', branch)`. |
|
|
500
|
-
| `session` | `object \| null` | `null` | Enables encrypted lazy sessions. Requires `{ secret: string }`. See [Section 7.2](#72-lazy-reactive-sessions-wiresession--multi-device-control-wiresessions). |
|
|
501
|
-
| `origins` | `string[]` | `undefined` | Allowed CORS origins (e.g., `['https://app.example.com']` or `['*']`). Automatically handles `OPTIONS` preflight requests and credentials. |
|
|
502
|
-
| `redact` | `string[]` | `undefined` | Wildcard key patterns (e.g., `['password*', '*.secret', 'token']`) stripped recursively from all JSON responses. |
|
|
503
|
-
| `message` | `string \| function \| false` | `'[servin] listening on <url>'` | Custom startup log message. Accepts a string, `({ port, host, url }) => string`, or `false` to suppress. |
|
|
504
|
-
| `onListen` | `function` | `undefined` | Sync or async callback `({ port, host, url }) => void` executed right after the port opens. |
|
|
505
|
-
| `accessLog` | `boolean \| function` | `true` | Logs every HTTP and WebSocket request. Pass `false` to disable, or `(info) => string \| null` to customize/filter output. |
|
|
506
|
-
| `silent` | `boolean` | `false` | Suppresses both the startup message and access logs. |
|
|
507
|
-
| `lagThresholdMs` | `number` | `60` | Event-loop p95 latency threshold (in milliseconds) before `priority: 'low'` routes shed load with `503`. |
|
|
508
|
-
| `synthesizeTests` | `string` | `undefined` | File path (e.g., `'./tests/api.test.js'`) where verified request/response pairs are automatically written as `node:test` suites. |
|
|
509
|
-
| `snapshotOnError` | `string` | `undefined` | Directory path (e.g., `'./snapshots'`) where failing `500` request snapshots are saved for local `replay()`. |
|
|
510
|
-
| `onError` | `function` | `undefined` | Custom unhandled error formatter `(err, { req }) => Response \| object`. |
|
|
443
|
+
### 4.1 Step 1: Importing `api` in Browser or Frontend Apps
|
|
511
444
|
|
|
512
|
-
|
|
445
|
+
**Same-origin HTML page served by `servin`:**
|
|
513
446
|
|
|
514
|
-
|
|
447
|
+
```html
|
|
448
|
+
<!doctype html>
|
|
449
|
+
<html>
|
|
450
|
+
<body>
|
|
451
|
+
<ul id="list"></ul>
|
|
452
|
+
|
|
453
|
+
<script type="module">
|
|
454
|
+
import { api } from "/@client.js";
|
|
455
|
+
|
|
456
|
+
const tasks = await api.tasks.get();
|
|
457
|
+
document.getElementById("list").innerHTML = tasks
|
|
458
|
+
.map((t) => `<li>${t.title}</li>`)
|
|
459
|
+
.join("");
|
|
460
|
+
</script>
|
|
461
|
+
</body>
|
|
462
|
+
</html>
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
**Separate frontend dev server (e.g., Vite on `:5173` calling `servin` on `:3000`):**
|
|
515
466
|
|
|
516
467
|
```javascript
|
|
517
|
-
|
|
518
|
-
port: 0,
|
|
519
|
-
api: { health: { get: () => ({ ok: true }) } },
|
|
520
|
-
});
|
|
468
|
+
import { api } from "http://localhost:3000/@client.js";
|
|
521
469
|
|
|
522
|
-
|
|
523
|
-
console.log(app.url); // e.g. "http://127.0.0.1:54321"
|
|
470
|
+
const tasks = await api.tasks.get();
|
|
524
471
|
|
|
525
|
-
//
|
|
526
|
-
const
|
|
527
|
-
console.log(await res.json()); // { ok: true }
|
|
472
|
+
// GET with custom header
|
|
473
|
+
const profile = await api.profile.get(authHeaders);
|
|
528
474
|
|
|
529
|
-
//
|
|
530
|
-
await
|
|
475
|
+
// GET with query + header
|
|
476
|
+
const orders = await api.v1.orders.get({ page: 1 }, authHeaders);
|
|
477
|
+
|
|
478
|
+
// POST with body + header
|
|
479
|
+
const created = await api.v1.orders.post(
|
|
480
|
+
{ item: "Keyboard", qty: 2 },
|
|
481
|
+
authHeaders,
|
|
482
|
+
);
|
|
483
|
+
```
|
|
484
|
+
|
|
485
|
+
### 4.2 Step 2: Calling `GET`, `POST`, `PATCH`, `DELETE` & Typed Params
|
|
486
|
+
|
|
487
|
+
Every method call on `api` matches the exact shape of your server's `api` tree and automatically includes credentials (`HttpOnly` session cookies) and JSON headers:
|
|
488
|
+
|
|
489
|
+
```javascript
|
|
490
|
+
import { api } from "/@client.js";
|
|
491
|
+
|
|
492
|
+
// 1. GET /tasks?done=false
|
|
493
|
+
const pending = await api.tasks.get({ done: "false" });
|
|
494
|
+
|
|
495
|
+
// 2. POST /tasks
|
|
496
|
+
const created = await api.tasks.post({ title: "Ship v1.0" });
|
|
497
|
+
|
|
498
|
+
// 3. GET /tasks/1 (passes `1` into `$id`)
|
|
499
|
+
const single = await api.tasks.$id.get(1);
|
|
500
|
+
|
|
501
|
+
// 4. PATCH /tasks/1 (first arg is `$id`, second arg is JSON body)
|
|
502
|
+
const updated = await api.tasks.$id.patch(1, { done: true });
|
|
503
|
+
|
|
504
|
+
// 5. DELETE /tasks/1 (returns `null` on 204 No Content)
|
|
505
|
+
await api.tasks.$id.delete(1);
|
|
506
|
+
```
|
|
507
|
+
|
|
508
|
+
### 4.3 Step 3: Consuming SSE Streams & WebSockets on the Client
|
|
509
|
+
|
|
510
|
+
`/@client.js` also translates Server-Sent Events and WebSockets into standard JavaScript `for await...of` async iterators:
|
|
511
|
+
|
|
512
|
+
```javascript
|
|
513
|
+
import { api } from "/@client.js";
|
|
514
|
+
|
|
515
|
+
// 1. Consuming an SSE endpoint (async *get())
|
|
516
|
+
for await (const tick of api.clock.get()) {
|
|
517
|
+
console.log("Server tick:", tick);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// 2. Consuming a WebSocket endpoint (async ws(room, socket))
|
|
521
|
+
const room = api.chat.$room.ws("general");
|
|
522
|
+
room.send({ text: "Hello everyone!" });
|
|
523
|
+
|
|
524
|
+
for await (const message of room) {
|
|
525
|
+
console.log("Chat message:", message);
|
|
526
|
+
}
|
|
531
527
|
```
|
|
532
528
|
|
|
533
529
|
---
|
|
534
530
|
|
|
535
|
-
## 5.
|
|
531
|
+
## 5. Static Routing, Redirects & Custom Error Pages
|
|
536
532
|
|
|
537
|
-
### 5.1 Static
|
|
533
|
+
### 5.1 Static File & Folder Routing (`serveStatic` & `static`)
|
|
538
534
|
|
|
539
|
-
|
|
535
|
+
`servin` serves static files and entire directories with automatic MIME detection, `ETag` (`304 Not Modified`), `Byte-Range` streaming (`206 Partial Content`), directory `index.html` resolution, and built-in path-traversal protection.
|
|
540
536
|
|
|
541
|
-
|
|
542
|
-
- **Untyped dynamic parameter (`$slug`, `$username`):** Matches any single non-empty URL segment and decodes URI components (`/posts/:slug`).
|
|
543
|
-
- **Typed dynamic parameter (`$id: param(...)`):** Validates and coerces the URL segment according to the specified rule. If validation fails, the route is skipped (resulting in `404 Not Found` or falling back to a lower-priority sibling route).
|
|
544
|
-
- **Wildcard catch-all (`$path`):** Matches all remaining trailing path segments joined with `/` (`/files/docs/2026/report.pdf` -> `path = "docs/2026/report.pdf"`).
|
|
537
|
+
**Step 1 — Mount static folders or single files via `serve({ static })`:**
|
|
545
538
|
|
|
546
539
|
```javascript
|
|
547
|
-
import { serve
|
|
540
|
+
import { serve } from "servin";
|
|
548
541
|
|
|
549
542
|
await serve({
|
|
550
543
|
port: 3000,
|
|
544
|
+
static: {
|
|
545
|
+
"/assets": "./public/assets", // Serves entire directory at /assets/*
|
|
546
|
+
"/favicon.ico": "./public/favicon.ico", // Serves a single file at /favicon.ico
|
|
547
|
+
},
|
|
551
548
|
api: {
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
549
|
+
health: { get: () => ({ ok: true }) },
|
|
550
|
+
},
|
|
551
|
+
});
|
|
552
|
+
```
|
|
553
|
+
|
|
554
|
+
**Step 2 — Mount static directories inside the `api` tree with `serveStatic()` (and combine with `guard()`):**
|
|
555
|
+
|
|
556
|
+
```javascript
|
|
557
|
+
import { serve, guard, serveStatic } from "servin";
|
|
558
|
+
|
|
559
|
+
await serve({
|
|
560
|
+
port: 3000,
|
|
561
|
+
api: {
|
|
562
|
+
// Public documentation folder with Cache-Control header
|
|
563
|
+
docs: serveStatic("./public/docs", {
|
|
564
|
+
index: "index.html",
|
|
565
|
+
cacheControl: "public, max-age=3600",
|
|
566
|
+
}),
|
|
567
|
+
|
|
568
|
+
// Protected downloads folder requiring login
|
|
569
|
+
downloads: guard(
|
|
570
|
+
requireAuth,
|
|
571
|
+
serveStatic("./storage/private", {
|
|
572
|
+
dotfiles: "deny", // Returns 403 Forbidden for .env, .git, etc.
|
|
570
573
|
}),
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
574
|
+
),
|
|
575
|
+
},
|
|
576
|
+
});
|
|
577
|
+
```
|
|
578
|
+
|
|
579
|
+
**Step 3 — Single-Page Application (SPA) fallback mode:**
|
|
580
|
+
|
|
581
|
+
Set `spa: true` so client-side routes (like `/app/settings/profile`) automatically fall back to `index.html` when no matching asset file exists:
|
|
582
|
+
|
|
583
|
+
```javascript
|
|
584
|
+
const api = {
|
|
585
|
+
app: serveStatic("./dist", {
|
|
586
|
+
spa: true,
|
|
587
|
+
index: "index.html",
|
|
588
|
+
}),
|
|
589
|
+
};
|
|
590
|
+
```
|
|
591
|
+
|
|
592
|
+
**All `serveStatic(targetPath, options)` options:**
|
|
593
|
+
|
|
594
|
+
| Option | Type | Default | Description |
|
|
595
|
+
| :------------- | :------------------------------ | :------------- | :---------------------------------------------------------------------------------------- |
|
|
596
|
+
| `index` | `string \| false` | `'index.html'` | Default file served when a directory URL is requested. Set `false` to disable. |
|
|
597
|
+
| `dotfiles` | `'ignore' \| 'deny' \| 'allow'` | `'ignore'` | How files/folders starting with `.` (e.g., `.env`) are handled (`404`, `403`, or served). |
|
|
598
|
+
| `cacheControl` | `string \| null` | `null` | Optional `Cache-Control` response header (e.g., `'public, max-age=86400'`). |
|
|
599
|
+
| `spa` | `boolean` | `false` | Falls back to `index` (or `fallback`) when a requested sub-path is not found. |
|
|
600
|
+
| `fallback` | `string \| null` | `null` | Custom fallback HTML file path when `spa: true` is enabled. |
|
|
601
|
+
|
|
602
|
+
### 5.2 HTTP Redirects (`wire.redirect` & `redirect`)
|
|
603
|
+
|
|
604
|
+
**1. Declarative redirects in the `api` tree (`redirect(target, status = 301)`):**
|
|
605
|
+
|
|
606
|
+
```javascript
|
|
607
|
+
import { serve, param, redirect } from "servin";
|
|
608
|
+
|
|
609
|
+
await serve({
|
|
610
|
+
port: 3000,
|
|
611
|
+
api: {
|
|
612
|
+
// Static permanent redirect: GET /old-blog -> 301 Location: /articles
|
|
613
|
+
"old-blog": redirect("/articles", 301),
|
|
614
|
+
|
|
615
|
+
// Dynamic redirect using extracted route parameters & query:
|
|
616
|
+
promo: {
|
|
617
|
+
$code: param(
|
|
618
|
+
"alnum",
|
|
619
|
+
redirect((code, query) => {
|
|
620
|
+
const ref = query.ref ? `&ref=${encodeURIComponent(query.ref)}` : "";
|
|
621
|
+
return `/checkout?voucher=${code}${ref}`;
|
|
622
|
+
}, 302),
|
|
623
|
+
),
|
|
624
|
+
},
|
|
625
|
+
},
|
|
626
|
+
});
|
|
627
|
+
```
|
|
628
|
+
|
|
629
|
+
**2. Imperative redirects inside handlers (`wire.redirect(location, status = 302)`):**
|
|
630
|
+
|
|
631
|
+
Calling `wire.redirect()` immediately halts handler execution, **commits any newly created/updated `wire.session` cookies**, and sends the redirect response:
|
|
632
|
+
|
|
633
|
+
```javascript
|
|
634
|
+
const auth = {
|
|
635
|
+
login: {
|
|
636
|
+
async post({ email }) {
|
|
637
|
+
await wire.session.rotate();
|
|
638
|
+
wire.session.user = email;
|
|
639
|
+
|
|
640
|
+
// Session cookie is automatically attached to this 302 redirect response
|
|
641
|
+
wire.redirect("/dashboard");
|
|
642
|
+
},
|
|
643
|
+
},
|
|
644
|
+
};
|
|
645
|
+
```
|
|
646
|
+
|
|
647
|
+
### 5.3 Custom Error Pages (`404`, `401`, `403`, `500`, etc.)
|
|
648
|
+
|
|
649
|
+
Configure `errors` in `serve()` to customize responses for specific HTTP status codes (`404`, `401`, `403`, `405`, `422`, `429`, `500`), status ranges (`'4xx'`, `'5xx'`), or `default`.
|
|
650
|
+
|
|
651
|
+
An error handler can return **`wire.html`**, **`wire.file()`**, a **JSON object**, a **plain string**, or trigger **`wire.redirect()`**:
|
|
652
|
+
|
|
653
|
+
```javascript
|
|
654
|
+
import { serve, wire, guard } from "servin";
|
|
655
|
+
|
|
656
|
+
const requireAdmin = () => {
|
|
657
|
+
if (!wire.session.user) wire.abort(401, "Authentication required");
|
|
658
|
+
if (wire.session.role !== "admin")
|
|
659
|
+
wire.abort(403, "Administrator access required");
|
|
660
|
+
};
|
|
661
|
+
|
|
662
|
+
await serve({
|
|
663
|
+
port: 3000,
|
|
664
|
+
session: { secret: "replace-with-32-char-secret-key!!" },
|
|
665
|
+
|
|
666
|
+
errors: {
|
|
667
|
+
// 1. Custom 404 Not Found HTML page
|
|
668
|
+
404({ path }) {
|
|
669
|
+
return wire.html`
|
|
670
|
+
<h1>404 — Page Not Found</h1>
|
|
671
|
+
<p>No route matches <code>${path}</code>.</p>
|
|
672
|
+
<a href="/">Back to Home</a>
|
|
673
|
+
`;
|
|
674
|
+
},
|
|
675
|
+
|
|
676
|
+
// 2. Custom 401 Unauthorized: redirect browsers to /login, return JSON for API clients
|
|
677
|
+
401({ message }) {
|
|
678
|
+
const accept = wire.headers.get("accept") || "";
|
|
679
|
+
if (accept.includes("text/html")) {
|
|
680
|
+
return wire.redirect("/login");
|
|
681
|
+
}
|
|
682
|
+
return { error: "Unauthorized", reason: message };
|
|
683
|
+
},
|
|
684
|
+
|
|
685
|
+
// 3. Custom 403 Forbidden: stream a static HTML file while keeping status 403
|
|
686
|
+
403: wire.file("./pages/403.html"),
|
|
687
|
+
|
|
688
|
+
// 4. Custom 500 Internal Server Error
|
|
689
|
+
500() {
|
|
690
|
+
return wire.html`<h1>500 — Something went wrong on our end</h1>`;
|
|
577
691
|
},
|
|
578
692
|
},
|
|
693
|
+
|
|
694
|
+
api: {
|
|
695
|
+
admin: guard(requireAdmin, {
|
|
696
|
+
get: () => wire.html`<h1>Welcome, Admin ${wire.session.user}</h1>`,
|
|
697
|
+
}),
|
|
698
|
+
},
|
|
699
|
+
});
|
|
700
|
+
```
|
|
701
|
+
|
|
702
|
+
**Context passed to custom error functions `errors[code](ctx)`:**
|
|
703
|
+
|
|
704
|
+
| Property | Type | Description |
|
|
705
|
+
| :-------- | :-------------- | :-------------------------------------------------------------------------- |
|
|
706
|
+
| `status` | `number` | HTTP status code being returned (e.g., `404`, `401`, `403`, `500`). |
|
|
707
|
+
| `message` | `string` | Default error message (e.g., the message passed to `wire.abort(401, msg)`). |
|
|
708
|
+
| `details` | `any` | Validation field details when `status === 422`. |
|
|
709
|
+
| `path` | `string` | Request URL pathname (e.g., `'/admin'`). |
|
|
710
|
+
| `method` | `string` | Uppercase HTTP method (e.g., `'GET'`). |
|
|
711
|
+
| `error` | `Error \| null` | Original thrown error instance if available. |
|
|
712
|
+
| `wire` | `object` | Active `wire` ambient context handle. |
|
|
713
|
+
|
|
714
|
+
---
|
|
715
|
+
|
|
716
|
+
## 6. Server Configuration (`serve`)
|
|
717
|
+
|
|
718
|
+
### 6.1 All `serve()` Options
|
|
719
|
+
|
|
720
|
+
| Option | Type | Default | Description |
|
|
721
|
+
| :---------------- | :------------------------------------- | :---------------------------- | :---------------------------------------------------------------------------------------- |
|
|
722
|
+
| `port` | `number` | `3000` | TCP port to listen on. Pass `0` for a random OS-assigned port. |
|
|
723
|
+
| `host` | `string` | `'127.0.0.1'` | Host interface to bind (use `'0.0.0.0'` inside Docker/containers). |
|
|
724
|
+
| `api` | `object` | `{}` | Root domain object defining all routes. |
|
|
725
|
+
| `static` | `string \| StaticDescriptor \| object` | `null` | Root or prefix-mapped static files/directories (e.g., `{ '/assets': './public' }`). |
|
|
726
|
+
| `errors` | `object` | `undefined` | Custom status handlers (`404`, `401`, `403`, `500`, `'4xx'`, `'5xx'`, `default`). |
|
|
727
|
+
| `types` | `object` | `{}` | Named custom parameter types usable via `param('typeName', branch)`. |
|
|
728
|
+
| `session` | `object \| null` | `null` | Session config `{ secret, ttl, cookieName, rolling, secure, sameSite, store }`. |
|
|
729
|
+
| `origins` | `string[]` | `undefined` | Allowed CORS origins (e.g., `['https://app.example.com']` or `['*']`). |
|
|
730
|
+
| `redact` | `string[]` | `undefined` | Wildcard keys (e.g., `['password*', '*.secret']`) stripped from all JSON responses. |
|
|
731
|
+
| `message` | `string \| function \| false` | `"[servin] listening on ..."` | Custom startup log message or `false` to silence startup output. |
|
|
732
|
+
| `onListen` | `function` | `undefined` | Sync/async callback `({ port, host, url }) => void` run when listening starts. |
|
|
733
|
+
| `accessLog` | `boolean \| function` | `true` | Enables per-request access logs or accepts a custom formatter `(info) => string \| null`. |
|
|
734
|
+
| `silent` | `boolean` | `false` | Disables both startup and access logs. |
|
|
735
|
+
| `lagThresholdMs` | `number` | `60` | Event-loop p95 delay threshold (ms) before `priority: 'low'` routes return `503`. |
|
|
736
|
+
| `synthesizeTests` | `string` | `undefined` | File path where verified requests are recorded as `node:test` test cases. |
|
|
737
|
+
| `snapshotOnError` | `string` | `undefined` | Directory where `500` error snapshots are saved for local `replay()`. |
|
|
738
|
+
| `onError` | `function` | `undefined` | Custom unhandled error formatter `(err, { req }) => Response \| object`. |
|
|
739
|
+
|
|
740
|
+
### 6.2 Server Instance Control (`port`, `url`, `fetch`, `close`)
|
|
741
|
+
|
|
742
|
+
```javascript
|
|
743
|
+
const app = await serve({
|
|
744
|
+
port: 0,
|
|
745
|
+
api: { ping: { get: () => ({ pong: true }) } },
|
|
579
746
|
});
|
|
747
|
+
|
|
748
|
+
console.log(app.port); // Actual assigned port
|
|
749
|
+
console.log(app.url); // e.g. "http://127.0.0.1:51234"
|
|
750
|
+
|
|
751
|
+
// Call routes directly in-memory without network overhead:
|
|
752
|
+
const res = await app.fetch(new Request("http://localhost/ping"));
|
|
753
|
+
console.log(await res.json()); // { pong: true }
|
|
754
|
+
|
|
755
|
+
// Shut down server and wait for pending wire.defer() tasks:
|
|
756
|
+
await app.close();
|
|
580
757
|
```
|
|
581
758
|
|
|
582
|
-
|
|
759
|
+
---
|
|
760
|
+
|
|
761
|
+
## 7. Domain-Tree Projection & Routing
|
|
762
|
+
|
|
763
|
+
### 7.1 Static, Dynamic, Typed, and Wildcard Segments
|
|
764
|
+
|
|
765
|
+
- **Static (`users`):** Matches `/users` literally.
|
|
766
|
+
- **Dynamic (`$username`):** Matches any single URL segment as a string.
|
|
767
|
+
- **Typed Dynamic (`$id: param(...)`):** Validates and converts the segment type before matching.
|
|
768
|
+
- **Wildcard (`$path`):** Captures all remaining trailing path segments joined by `/`.
|
|
583
769
|
|
|
584
|
-
|
|
770
|
+
```javascript
|
|
771
|
+
const api = {
|
|
772
|
+
users: {
|
|
773
|
+
me: { get: () => "static" }, // GET /users/me
|
|
774
|
+
$id: param("int", { get: (id) => ({ id }) }), // GET /users/42
|
|
775
|
+
$username: { get: (u) => ({ username: u }) }, // GET /users/nadia
|
|
776
|
+
},
|
|
777
|
+
files: {
|
|
778
|
+
$path: { get: (path) => ({ path }) }, // GET /files/docs/2026/a.pdf
|
|
779
|
+
},
|
|
780
|
+
};
|
|
781
|
+
```
|
|
782
|
+
|
|
783
|
+
### 7.2 Automatic Route Matching Priority
|
|
585
784
|
|
|
586
|
-
|
|
587
|
-
2. **Priority 1 — Typed dynamic parameters** (`$id: param(...)`)
|
|
588
|
-
3. **Priority 2 — Untyped dynamic parameters** (`$username`)
|
|
589
|
-
4. **Priority 3 — Wildcard catch-all segments** (`$path`)
|
|
785
|
+
Regardless of object key order, `servin` always matches segments from most specific to least specific:
|
|
590
786
|
|
|
591
|
-
|
|
787
|
+
1. **Static segments** (`me`)
|
|
788
|
+
2. **Typed parameters** (`$id: param(...)`)
|
|
789
|
+
3. **Untyped parameters** (`$username`)
|
|
790
|
+
4. **Wildcard catch-all** (`$path` or `serveStatic` mount)
|
|
592
791
|
|
|
593
|
-
|
|
792
|
+
### 7.3 Method Unions (`'put|patch'`) & Shorthand Leaf Functions
|
|
594
793
|
|
|
595
|
-
|
|
596
|
-
- WebSocket upgrade handler: `ws`
|
|
597
|
-
- **Method Unions:** Combine multiple verbs with `|` to share a single handler cleanly:
|
|
794
|
+
**1. Method Unions:** Share one handler across multiple HTTP verbs using `|`:
|
|
598
795
|
|
|
599
796
|
```javascript
|
|
600
|
-
const
|
|
797
|
+
const items = {
|
|
601
798
|
$id: param("int", {
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
return { id, isPartial, payload };
|
|
799
|
+
"put|patch"(id, payload) {
|
|
800
|
+
return { methodUsed: wire.method, id, payload };
|
|
605
801
|
},
|
|
606
802
|
}),
|
|
607
803
|
};
|
|
608
804
|
```
|
|
609
805
|
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
806
|
+
**2. Shorthand Leaf Functions:** Assigning a function directly to a non-verb key creates a route automatically:
|
|
807
|
+
|
|
808
|
+
- Normal function $\rightarrow$ **`POST`**
|
|
809
|
+
- Async generator (`async *`) $\rightarrow$ **`GET`** (SSE stream)
|
|
613
810
|
|
|
614
811
|
```javascript
|
|
615
|
-
const
|
|
616
|
-
//
|
|
617
|
-
|
|
618
|
-
return {
|
|
812
|
+
const actions = {
|
|
813
|
+
// POST /actions/sync
|
|
814
|
+
sync(payload) {
|
|
815
|
+
return { synced: true, payload };
|
|
619
816
|
},
|
|
620
817
|
|
|
621
|
-
//
|
|
622
|
-
async *
|
|
623
|
-
yield {
|
|
624
|
-
yield {
|
|
818
|
+
// GET /actions/events (SSE stream)
|
|
819
|
+
async *events() {
|
|
820
|
+
yield { status: "started" };
|
|
821
|
+
yield { status: "finished" };
|
|
625
822
|
},
|
|
626
823
|
};
|
|
627
824
|
```
|
|
628
825
|
|
|
629
|
-
###
|
|
826
|
+
### 7.4 Handler Argument Order
|
|
630
827
|
|
|
631
|
-
|
|
828
|
+
Arguments are always passed in this order:
|
|
632
829
|
|
|
633
|
-
1.
|
|
634
|
-
2.
|
|
635
|
-
3.
|
|
636
|
-
4. For **`ws`** handlers: `(...extractedParams, socket)`.
|
|
830
|
+
1. URL parameters (`$...`) from left to right.
|
|
831
|
+
2. Parsed `payload` (only for `POST`, `PUT`, `PATCH`).
|
|
832
|
+
3. `query` object (`url.searchParams`) as the final argument.
|
|
637
833
|
|
|
638
834
|
```javascript
|
|
835
|
+
// PATCH /orgs/10/members/550e8400-e29b-41d4-a716-446655440000?notify=true
|
|
639
836
|
const orgs = {
|
|
640
837
|
$orgId: param("int", {
|
|
641
838
|
members: {
|
|
642
839
|
$memberId: param("uuid", {
|
|
643
|
-
// 1. orgId (number), 2. memberId (string), 3. payload (object), 4. query (object)
|
|
644
840
|
patch(orgId, memberId, payload, query) {
|
|
645
|
-
return { orgId, memberId, payload, notify: query.notify
|
|
646
|
-
},
|
|
647
|
-
|
|
648
|
-
// 1. orgId (number), 2. memberId (string), 3. query (object)
|
|
649
|
-
get(orgId, memberId, query) {
|
|
650
|
-
return { orgId, memberId, includeRoles: query.roles === "1" };
|
|
841
|
+
return { orgId, memberId, payload, notify: query.notify };
|
|
651
842
|
},
|
|
652
843
|
}),
|
|
653
844
|
},
|
|
@@ -655,57 +846,74 @@ const orgs = {
|
|
|
655
846
|
};
|
|
656
847
|
```
|
|
657
848
|
|
|
658
|
-
###
|
|
849
|
+
### 7.5 Typed Route Parameters (`param`) — All Supported Types & Custom Formats
|
|
850
|
+
|
|
851
|
+
`param(rule, branch)` keeps object keys as clean JavaScript identifiers without string quotes. When a URL segment does not satisfy `rule`, `servin` treats that route branch as non-matching (falling through to other routes or returning `404 Not Found`). When it does satisfy `rule`, `servin` passes the **converted value** directly into your handler.
|
|
659
852
|
|
|
660
|
-
|
|
853
|
+
You can supply `rule` in **five ways**:
|
|
661
854
|
|
|
662
855
|
#### A. Built-in String Type Names
|
|
663
856
|
|
|
664
|
-
| Rule
|
|
665
|
-
| :---------- |
|
|
666
|
-
| `'int'` | Non-negative safe integer (`/^\d+$/`)
|
|
667
|
-
| `'number'` | Signed integer or decimal
|
|
668
|
-
| `'float'` | Alias for `'number'`
|
|
669
|
-
| `'bigint'` | Arbitrary-precision
|
|
670
|
-
| `'uuid'` | Standard UUID v1–v5
|
|
671
|
-
| `'alpha'` |
|
|
672
|
-
| `'alnum'` |
|
|
673
|
-
| `'slug'` | Lowercase kebab-case (
|
|
674
|
-
| `'bool'` | `'true'`, `'1'`, `'false'`, `'0'`
|
|
675
|
-
| `'boolean'` | Alias for `'bool'`
|
|
676
|
-
| `'string'` | Any
|
|
857
|
+
| Rule | Validation | Coerced JS Type | Example Match | Example Rejected (`404`) |
|
|
858
|
+
| :---------- | :--------------------------------------- | :------------------- | :------------------------------------- | :----------------------- |
|
|
859
|
+
| `'int'` | Non-negative safe integer (`/^\d+$/`) | `number` | `0`, `42` | `-1`, `3.14`, `42abc` |
|
|
860
|
+
| `'number'` | Signed integer or decimal | `number` | `-10`, `19.99` | `10px`, `abc` |
|
|
861
|
+
| `'float'` | Alias for `'number'` | `number` | `-0.5`, `12.34` | `abc` |
|
|
862
|
+
| `'bigint'` | Arbitrary-precision integer | `bigint` | `9007199254740993` | `12.5`, `abc` |
|
|
863
|
+
| `'uuid'` | Standard UUID v1–v5 | `string` (lowercase) | `550e8400-e29b-41d4-a716-446655440000` | `12345`, `not-uuid` |
|
|
864
|
+
| `'alpha'` | Letters only (`a-z`, `A-Z`) | `string` | `Indonesia` | `id2`, `en-US` |
|
|
865
|
+
| `'alnum'` | Letters and digits (`a-z`, `A-Z`, `0-9`) | `string` | `v2026` | `v-2026` |
|
|
866
|
+
| `'slug'` | Lowercase kebab-case (`a-z`, `0-9`, `-`) | `string` | `hello-world` | `Hello_World` |
|
|
867
|
+
| `'bool'` | `'true'`, `'1'`, `'false'`, `'0'` | `boolean` | `true`, `1`, `0` | `yes`, `2` |
|
|
868
|
+
| `'boolean'` | Alias for `'bool'` | `boolean` | `true`, `false` | `maybe` |
|
|
869
|
+
| `'string'` | Any URI-decoded string | `string` | `anything` | Invalid `%` encoding |
|
|
870
|
+
|
|
871
|
+
```javascript
|
|
872
|
+
const users = {
|
|
873
|
+
$id: param("int", {
|
|
874
|
+
get: (id) => ({ id, isNumber: typeof id === "number" }),
|
|
875
|
+
}),
|
|
876
|
+
$handle: param("slug", {
|
|
877
|
+
get: (handle) => ({ handle }),
|
|
878
|
+
}),
|
|
879
|
+
};
|
|
880
|
+
```
|
|
677
881
|
|
|
678
882
|
#### B. Native JavaScript Constructors
|
|
679
883
|
|
|
680
|
-
|
|
884
|
+
Pass `Number`, `Boolean`, `BigInt`, or `String` directly:
|
|
681
885
|
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
886
|
+
```javascript
|
|
887
|
+
const posts = {
|
|
888
|
+
$id: param(Number, { get: (id) => ({ id }) }),
|
|
889
|
+
$published: param(Boolean, { get: (flag) => ({ published: flag }) }),
|
|
890
|
+
$ledgerId: param(BigInt, { get: (val) => ({ ledgerId: val.toString() }) }),
|
|
891
|
+
};
|
|
892
|
+
```
|
|
686
893
|
|
|
687
|
-
#### C. Inline `RegExp` Literals
|
|
894
|
+
#### C. Inline `RegExp` Literals (Custom Formats)
|
|
688
895
|
|
|
689
|
-
Pass any
|
|
896
|
+
Pass any `RegExp` literal directly for custom code formats, SKUs, or structured identifiers:
|
|
690
897
|
|
|
691
898
|
```javascript
|
|
692
|
-
const
|
|
693
|
-
// Matches /
|
|
899
|
+
const products = {
|
|
900
|
+
// Matches /products/SKU-1024, rejects /products/sku-1024 or /products/1024
|
|
694
901
|
$sku: param(/^[A-Z]{3}-\d{4}$/, {
|
|
695
|
-
get(sku) {
|
|
696
|
-
return { sku };
|
|
697
|
-
},
|
|
902
|
+
get: (sku) => ({ sku }),
|
|
698
903
|
}),
|
|
699
904
|
};
|
|
700
905
|
```
|
|
701
906
|
|
|
702
|
-
#### D.
|
|
907
|
+
#### D. Custom Validator / Transformer Function
|
|
908
|
+
|
|
909
|
+
Pass a function `(rawSegment) => parsedValue | null | undefined | false`:
|
|
703
910
|
|
|
704
|
-
|
|
911
|
+
- Return any non-null, non-undefined value (other than `false`) to **accept** and pass that returned value to the handler.
|
|
912
|
+
- Return `null`, `undefined`, or `false` (or throw an error) to **reject** (`404`).
|
|
705
913
|
|
|
706
914
|
```javascript
|
|
707
915
|
const events = {
|
|
708
|
-
// Parses YYYY-MM-DD
|
|
916
|
+
// Parses "YYYY-MM-DD" into a real Date instance
|
|
709
917
|
$date: param(
|
|
710
918
|
(raw) => {
|
|
711
919
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(raw)) return null;
|
|
@@ -713,10 +921,7 @@ const events = {
|
|
|
713
921
|
return Number.isNaN(d.getTime()) ? null : d;
|
|
714
922
|
},
|
|
715
923
|
{
|
|
716
|
-
get(date) {
|
|
717
|
-
// `date` is already a valid Date object
|
|
718
|
-
return { iso: date.toISOString() };
|
|
719
|
-
},
|
|
924
|
+
get: (date) => ({ iso: date.toISOString() }),
|
|
720
925
|
},
|
|
721
926
|
),
|
|
722
927
|
};
|
|
@@ -724,13 +929,13 @@ const events = {
|
|
|
724
929
|
|
|
725
930
|
#### E. Global Reusable Custom Types (`serve({ types })`)
|
|
726
931
|
|
|
727
|
-
|
|
932
|
+
Define named types once in `serve({ types })`—using either a `RegExp` or a validator function—and reference them by string name anywhere in your tree:
|
|
728
933
|
|
|
729
934
|
```javascript
|
|
730
935
|
await serve({
|
|
731
936
|
port: 3000,
|
|
732
937
|
types: {
|
|
733
|
-
|
|
938
|
+
invoiceCode: /^INV-\d{6}$/,
|
|
734
939
|
positiveInt: (raw) => {
|
|
735
940
|
const n = Number(raw);
|
|
736
941
|
return Number.isInteger(n) && n > 0 ? n : null;
|
|
@@ -738,14 +943,10 @@ await serve({
|
|
|
738
943
|
},
|
|
739
944
|
api: {
|
|
740
945
|
invoices: {
|
|
741
|
-
$
|
|
742
|
-
get: (id) => ({ invoice: id }),
|
|
743
|
-
}),
|
|
946
|
+
$code: param("invoiceCode", { get: (code) => ({ code }) }),
|
|
744
947
|
},
|
|
745
948
|
pages: {
|
|
746
|
-
$page: param("positiveInt", {
|
|
747
|
-
get: (page) => ({ page }),
|
|
748
|
-
}),
|
|
949
|
+
$page: param("positiveInt", { get: (page) => ({ page }) }),
|
|
749
950
|
},
|
|
750
951
|
},
|
|
751
952
|
});
|
|
@@ -753,676 +954,515 @@ await serve({
|
|
|
753
954
|
|
|
754
955
|
---
|
|
755
956
|
|
|
756
|
-
##
|
|
757
|
-
|
|
758
|
-
### 6.1 Content-Type Resolution Matrix
|
|
957
|
+
## 8. Response Formatting, HTML & Streaming
|
|
759
958
|
|
|
760
|
-
|
|
959
|
+
### 8.1 Automatic `Content-Type` Matrix
|
|
761
960
|
|
|
762
|
-
|
|
|
763
|
-
| :------------------------------ |
|
|
764
|
-
|
|
|
765
|
-
| `wire.html(...)` | `200`
|
|
766
|
-
| `wire.file(path)` | `200
|
|
767
|
-
| `string` | `200`
|
|
768
|
-
| `null`
|
|
769
|
-
| `async *generator()` | `200`
|
|
770
|
-
| `ReadableStream` / `Uint8Array` | `200`
|
|
771
|
-
| Web `Response` |
|
|
961
|
+
| Return Value | Status | `Content-Type` | Notes |
|
|
962
|
+
| :------------------------------ | :---------------- | :--------------------------------- | :---------------------------------------------------------- |
|
|
963
|
+
| Object / Array | `200` | `application/json` | Applies `redact` and `?fields=` automatically. |
|
|
964
|
+
| `wire.html(...)` | `200` | `text/html; charset=utf-8` | Sends rendered HTML. |
|
|
965
|
+
| `wire.file(path)` | `200`/`206`/`304` | Auto from extension | Streams file with `ETag` and `Range` support. |
|
|
966
|
+
| `string` | `200` | `text/plain; charset=utf-8` | Plain text (unless `Content-Type` header was set manually). |
|
|
967
|
+
| `null` / `undefined` | `204` | _(none)_ | Empty response body. |
|
|
968
|
+
| `async *generator()` | `200` | `text/event-stream; charset=utf-8` | Streams SSE `data: <json>\n\n` frames. |
|
|
969
|
+
| `ReadableStream` / `Uint8Array` | `200` | _(user-defined)_ | Streams raw binary bytes. |
|
|
970
|
+
| Web `Response` | Custom | Custom | Sent as-is. |
|
|
772
971
|
|
|
773
|
-
###
|
|
972
|
+
### 8.2 HTML Responses & XSS Protection (`wire.html`)
|
|
774
973
|
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
1. **Tagged Template Literal (Recommended):** Automatically HTML-escapes all interpolated variables (`&`, `<`, `>`, `"`, `'`), while preserving nested `wire.html` fragments and arrays of fragments unescaped.
|
|
778
|
-
2. **Direct Function Call:** `wire.html(rawHtmlString)` sends an already-trusted HTML string with `Content-Type: text/html; charset=utf-8`.
|
|
974
|
+
**1. Raw HTML string:**
|
|
779
975
|
|
|
780
976
|
```javascript
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
api: {
|
|
786
|
-
// 1. Tagged template with automatic XSS escaping and nested components
|
|
787
|
-
greet: {
|
|
788
|
-
$name: {
|
|
789
|
-
get(name) {
|
|
790
|
-
const badges = ["Admin", "Verified"].map(
|
|
791
|
-
(b) => wire.html`<span class="badge">${b}</span>`,
|
|
792
|
-
);
|
|
793
|
-
|
|
794
|
-
// If `name` is "<script>alert(1)</script>", it is safely escaped to <script>...
|
|
795
|
-
// Meanwhile `badges` (already HtmlResponse instances) render as real <span> tags.
|
|
796
|
-
return wire.html`
|
|
797
|
-
<!doctype html>
|
|
798
|
-
<html>
|
|
799
|
-
<body>
|
|
800
|
-
<h1>Welcome, ${name}!</h1>
|
|
801
|
-
<div class="badges">${badges}</div>
|
|
802
|
-
</body>
|
|
803
|
-
</html>
|
|
804
|
-
`;
|
|
805
|
-
},
|
|
806
|
-
},
|
|
807
|
-
},
|
|
977
|
+
const page = {
|
|
978
|
+
get: () => wire.html("<h1>Hello World</h1>"),
|
|
979
|
+
};
|
|
980
|
+
```
|
|
808
981
|
|
|
809
|
-
|
|
810
|
-
banner: {
|
|
811
|
-
get: () => wire.html('<div class="banner">System Operational</div>'),
|
|
812
|
-
},
|
|
982
|
+
**2. Tagged template literal (auto-escapes untrusted variables against XSS):**
|
|
813
983
|
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
}
|
|
984
|
+
```javascript
|
|
985
|
+
const profile = {
|
|
986
|
+
$name: {
|
|
987
|
+
get(name) {
|
|
988
|
+
// If `name` is "<script>alert(1)</script>", it is safely escaped to <script>...
|
|
989
|
+
return wire.html`<h1>Profile: ${name}</h1>`;
|
|
820
990
|
},
|
|
821
991
|
},
|
|
822
|
-
}
|
|
992
|
+
};
|
|
823
993
|
```
|
|
824
994
|
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
`wire.file(filePath)` streams files directly from the filesystem without loading them into memory. It automatically:
|
|
828
|
-
|
|
829
|
-
- Resolves MIME types (`.html`, `.css`, `.js`, `.json`, `.svg`, `.png`, `.jpg`, `.webp`, `.pdf`, `.mp4`, `.mp3`, `.zip`, etc.).
|
|
830
|
-
- Computes weak `ETag` headers (`W/"<size>-<mtimeMs>"`) and responds with `304 Not Modified` when `If-None-Match` matches.
|
|
831
|
-
- Supports HTTP `Range: bytes=start-end` headers (`206 Partial Content` and `416 Range Not Satisfiable`) for audio/video scrubbing and resumable downloads.
|
|
995
|
+
**3. Composing nested `wire.html` fragments safely:**
|
|
832
996
|
|
|
833
997
|
```javascript
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
998
|
+
const dashboard = {
|
|
999
|
+
get() {
|
|
1000
|
+
const items = ["Apples", "Bananas"].map(
|
|
1001
|
+
(item) => wire.html`<li>${item}</li>`,
|
|
1002
|
+
);
|
|
1003
|
+
// Nested `wire.html` values and arrays are NOT double-escaped
|
|
1004
|
+
return wire.html`<ul>${items}</ul>`;
|
|
1005
|
+
},
|
|
1006
|
+
};
|
|
1007
|
+
```
|
|
838
1008
|
|
|
839
|
-
|
|
840
|
-
port: 3000,
|
|
841
|
-
api: {
|
|
842
|
-
// GET /home -> ./pages/home.html
|
|
843
|
-
home: {
|
|
844
|
-
get: () => wire.file("./pages/home.html"),
|
|
845
|
-
},
|
|
1009
|
+
### 8.3 File Streaming with `ETag` & Byte-Range (`wire.file`)
|
|
846
1010
|
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
const resolved = path.resolve(PAGES_DIR, `${slug}.html`);
|
|
852
|
-
if (!resolved.startsWith(PAGES_DIR + path.sep)) {
|
|
853
|
-
wire.abort(403, "Access denied");
|
|
854
|
-
}
|
|
855
|
-
return wire.file(resolved);
|
|
856
|
-
},
|
|
857
|
-
},
|
|
858
|
-
},
|
|
859
|
-
},
|
|
860
|
-
});
|
|
1011
|
+
```javascript
|
|
1012
|
+
const landing = {
|
|
1013
|
+
get: () => wire.file("./public/index.html"),
|
|
1014
|
+
};
|
|
861
1015
|
```
|
|
862
1016
|
|
|
863
|
-
###
|
|
1017
|
+
### 8.4 Server-Sent Events (SSE) with Async Generators
|
|
864
1018
|
|
|
865
|
-
|
|
1019
|
+
Use `async *get()` to stream live updates. If the client disconnects early, `servin` automatically stops the generator and runs any `wire.undo()` cleanup:
|
|
866
1020
|
|
|
867
1021
|
```javascript
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
async *stream(query) {
|
|
875
|
-
let count = 0;
|
|
876
|
-
const interval = setInterval(() => {}, 1000);
|
|
877
|
-
wire.undo(() => clearInterval(interval));
|
|
878
|
-
|
|
879
|
-
while (!wire.signal.aborted && count < 5) {
|
|
880
|
-
count++;
|
|
881
|
-
yield {
|
|
882
|
-
id: count,
|
|
883
|
-
channel: query.channel || "general",
|
|
884
|
-
ts: Date.now(),
|
|
885
|
-
};
|
|
886
|
-
await new Promise((r) => setTimeout(r, 1000));
|
|
887
|
-
}
|
|
888
|
-
},
|
|
889
|
-
},
|
|
1022
|
+
const clock = {
|
|
1023
|
+
async *get() {
|
|
1024
|
+
for (let i = 0; i < 5; i++) {
|
|
1025
|
+
yield { tick: i, time: new Date().toISOString() };
|
|
1026
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
1027
|
+
}
|
|
890
1028
|
},
|
|
891
|
-
}
|
|
1029
|
+
};
|
|
892
1030
|
```
|
|
893
1031
|
|
|
894
|
-
###
|
|
1032
|
+
### 8.5 Sparse Fieldsets (`?fields=`) & Automatic Redaction (`redact`)
|
|
895
1033
|
|
|
896
|
-
-
|
|
897
|
-
-
|
|
1034
|
+
- **`redact`:** Strips sensitive keys globally from all JSON responses.
|
|
1035
|
+
- **`?fields=`:** Allows clients on any `GET` endpoint to request only the fields they need.
|
|
898
1036
|
|
|
899
1037
|
```javascript
|
|
900
1038
|
await serve({
|
|
901
1039
|
port: 3000,
|
|
902
|
-
redact: ["password*", "*.secret"
|
|
1040
|
+
redact: ["password*", "*.secret"],
|
|
903
1041
|
api: {
|
|
904
1042
|
users: {
|
|
905
1043
|
get: () => [
|
|
906
1044
|
{
|
|
907
1045
|
id: 1,
|
|
908
1046
|
name: "Nadia",
|
|
909
|
-
|
|
910
|
-
|
|
1047
|
+
email: "nadia@example.com",
|
|
1048
|
+
passwordHash: "xyz",
|
|
911
1049
|
},
|
|
912
1050
|
],
|
|
913
1051
|
},
|
|
914
1052
|
},
|
|
915
1053
|
});
|
|
916
|
-
// GET /users?fields=id,
|
|
1054
|
+
// GET /users?fields=id,name -> [{ "id": 1, "name": "Nadia" }]
|
|
917
1055
|
```
|
|
918
1056
|
|
|
919
1057
|
---
|
|
920
1058
|
|
|
921
|
-
##
|
|
1059
|
+
## 9. Security, Sessions & Traffic Control
|
|
922
1060
|
|
|
923
|
-
###
|
|
1061
|
+
### 9.1 Protecting Routes & Branches (`guard`)
|
|
924
1062
|
|
|
925
|
-
|
|
1063
|
+
**Step 1 — Guard a single endpoint:**
|
|
926
1064
|
|
|
927
1065
|
```javascript
|
|
928
|
-
import {
|
|
1066
|
+
import { wire, guard } from "servin";
|
|
929
1067
|
|
|
930
1068
|
function requireAuth() {
|
|
931
|
-
if (!wire.session.userId)
|
|
932
|
-
wire.abort(401, "Authentication required");
|
|
933
|
-
}
|
|
1069
|
+
if (!wire.session.userId) wire.abort(401, "Please sign in");
|
|
934
1070
|
}
|
|
935
1071
|
|
|
1072
|
+
const secretNote = guard(requireAuth, {
|
|
1073
|
+
get: () => ({ secret: "Top secret data" }),
|
|
1074
|
+
});
|
|
1075
|
+
```
|
|
1076
|
+
|
|
1077
|
+
**Step 2 — Guard an entire branch and stack multiple guards:**
|
|
1078
|
+
|
|
1079
|
+
```javascript
|
|
936
1080
|
function requireAdmin() {
|
|
937
|
-
if (wire.session.role !== "admin")
|
|
938
|
-
wire.abort(403, "Administrator privileges required");
|
|
939
|
-
}
|
|
1081
|
+
if (wire.session.role !== "admin") wire.abort(403, "Admins only");
|
|
940
1082
|
}
|
|
941
1083
|
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
1084
|
+
// `requireAuth` runs first on everything inside `dashboard`,
|
|
1085
|
+
// and `requireAdmin` also runs on everything inside `admin`.
|
|
1086
|
+
const dashboard = guard(requireAuth, {
|
|
1087
|
+
overview: {
|
|
1088
|
+
get: () => ({ userId: wire.session.userId }),
|
|
946
1089
|
},
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
get: () => ({ status: "healthy" }),
|
|
1090
|
+
admin: guard(requireAdmin, {
|
|
1091
|
+
settings: {
|
|
1092
|
+
get: () => ({ maintenanceMode: false }),
|
|
951
1093
|
},
|
|
952
|
-
|
|
953
|
-
// Protected branch: requires authenticated user, and nested `admin` requires admin role
|
|
954
|
-
account: guard(requireAuth, {
|
|
955
|
-
profile: {
|
|
956
|
-
get: () => ({ userId: wire.session.userId, role: wire.session.role }),
|
|
957
|
-
},
|
|
958
|
-
admin: guard(requireAdmin, {
|
|
959
|
-
users: {
|
|
960
|
-
$id: param("int", {
|
|
961
|
-
delete: (id) => ({ deletedUserId: id }),
|
|
962
|
-
}),
|
|
963
|
-
},
|
|
964
|
-
}),
|
|
965
|
-
}),
|
|
966
|
-
},
|
|
1094
|
+
}),
|
|
967
1095
|
});
|
|
968
1096
|
```
|
|
969
1097
|
|
|
970
|
-
###
|
|
1098
|
+
### 9.2 Lazy Encrypted Sessions (`wire.session` & `wire.sessions`)
|
|
971
1099
|
|
|
972
|
-
|
|
1100
|
+
Sessions use AES-256-GCM encrypted `HttpOnly` cookies and are **completely lazy**: if a route never reads or writes `wire.session`, cookies are never decrypted and the session store is never touched.
|
|
973
1101
|
|
|
974
|
-
|
|
975
|
-
- **Plain Object Semantics:** Assign or delete properties directly (`wire.session.userId = 42`, `delete wire.session.tempFlag`). Changes are persisted and `Set-Cookie` is emitted automatically before headers are sent.
|
|
976
|
-
- **Session Fixation Protection:** Call `await wire.session.rotate()` on login to issue a fresh session ID and invalidate the previous one.
|
|
977
|
-
- **Multi-Device Tracking & Cross-Protocol Auto-Kick:** Call `wire.session.bind(userId)` to associate the session with a user account. Setting `wire.session = null` on logout deletes the store record, clears the cookie, and **immediately closes all active WebSockets** bound to that session (`4001 Session revoked`).
|
|
1102
|
+
**Step 1 — Enable sessions in `serve()` and read/write properties:**
|
|
978
1103
|
|
|
979
1104
|
```javascript
|
|
980
|
-
import { serve, wire, guard } from "servin";
|
|
981
|
-
|
|
982
1105
|
await serve({
|
|
983
1106
|
port: 3000,
|
|
984
|
-
session: {
|
|
985
|
-
secret: "super-secret-key-at-least-32-chars",
|
|
986
|
-
cookieName: "app_sid",
|
|
987
|
-
ttl: "7d",
|
|
988
|
-
rolling: true,
|
|
989
|
-
secure: process.env.NODE_ENV === "production",
|
|
990
|
-
sameSite: "Lax",
|
|
991
|
-
},
|
|
1107
|
+
session: { secret: "replace-with-32-char-secret-key!!" },
|
|
992
1108
|
api: {
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
await wire.session.rotate();
|
|
999
|
-
wire.session.bind(user.id);
|
|
1000
|
-
wire.session.userId = user.id;
|
|
1001
|
-
wire.session.role = user.role;
|
|
1002
|
-
wire.session.device = wire.headers.get("user-agent") || "Unknown";
|
|
1003
|
-
|
|
1004
|
-
return { id: user.id, name: user.name };
|
|
1005
|
-
},
|
|
1109
|
+
counter: {
|
|
1110
|
+
get() {
|
|
1111
|
+
wire.session.views = (wire.session.views || 0) + 1;
|
|
1112
|
+
return { views: wire.session.views };
|
|
1006
1113
|
},
|
|
1114
|
+
},
|
|
1115
|
+
},
|
|
1116
|
+
});
|
|
1117
|
+
```
|
|
1007
1118
|
|
|
1008
|
-
|
|
1009
|
-
post() {
|
|
1010
|
-
// Destroys store record, clears cookie, and kicks active WebSockets for this session
|
|
1011
|
-
wire.session = null;
|
|
1012
|
-
return { signedOut: true };
|
|
1013
|
-
},
|
|
1014
|
-
},
|
|
1119
|
+
**Step 2 — Rotate session ID on login & destroy on logout:**
|
|
1015
1120
|
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
// Revoke all other devices and close their active WebSockets
|
|
1025
|
-
revokeOthers: {
|
|
1026
|
-
async post() {
|
|
1027
|
-
const revokedCount = await wire.sessions.revokeOthers(
|
|
1028
|
-
wire.session.userId,
|
|
1029
|
-
);
|
|
1030
|
-
return { revokedCount };
|
|
1031
|
-
},
|
|
1032
|
-
},
|
|
1033
|
-
},
|
|
1034
|
-
),
|
|
1121
|
+
```javascript
|
|
1122
|
+
const auth = {
|
|
1123
|
+
login: {
|
|
1124
|
+
async post({ userId, role }) {
|
|
1125
|
+
await wire.session.rotate(); // Prevents session fixation
|
|
1126
|
+
wire.session.userId = userId;
|
|
1127
|
+
wire.session.role = role;
|
|
1128
|
+
return { loggedIn: true };
|
|
1035
1129
|
},
|
|
1036
1130
|
},
|
|
1037
|
-
|
|
1131
|
+
logout: {
|
|
1132
|
+
post() {
|
|
1133
|
+
wire.session = null; // Deletes store record, clears cookie, closes active WS
|
|
1134
|
+
return { loggedOut: true };
|
|
1135
|
+
},
|
|
1136
|
+
},
|
|
1137
|
+
};
|
|
1138
|
+
```
|
|
1139
|
+
|
|
1140
|
+
**Step 3 — Multi-device session listing & remote revocation:**
|
|
1141
|
+
|
|
1142
|
+
```javascript
|
|
1143
|
+
const devices = {
|
|
1144
|
+
// Bind session to a userId during login: `wire.session.bind(userId)`
|
|
1145
|
+
get: () => wire.sessions.list(wire.session.userId),
|
|
1146
|
+
|
|
1147
|
+
revokeOthers: {
|
|
1148
|
+
async post() {
|
|
1149
|
+
const count = await wire.sessions.revokeOthers(wire.session.userId);
|
|
1150
|
+
return { revokedDevices: count };
|
|
1151
|
+
},
|
|
1152
|
+
},
|
|
1153
|
+
};
|
|
1038
1154
|
```
|
|
1039
1155
|
|
|
1040
|
-
###
|
|
1156
|
+
### 9.3 Custom Session Store Interface (Redis / Database)
|
|
1041
1157
|
|
|
1042
|
-
|
|
1158
|
+
Pass a custom `store` object to `session` for multi-server deployments:
|
|
1043
1159
|
|
|
1044
1160
|
```javascript
|
|
1045
|
-
const
|
|
1161
|
+
const customStore = {
|
|
1046
1162
|
async get(sid) {
|
|
1047
|
-
|
|
1048
|
-
return raw ? JSON.parse(raw) : null; // { userId, data, createdAt, updatedAt, expiresAt }
|
|
1163
|
+
/* return { userId, data, createdAt, updatedAt, expiresAt } | null */
|
|
1049
1164
|
},
|
|
1050
1165
|
async set(sid, record) {
|
|
1051
|
-
|
|
1052
|
-
1,
|
|
1053
|
-
Math.ceil((record.expiresAt - Date.now()) / 1000),
|
|
1054
|
-
);
|
|
1055
|
-
await redis.set(`sess:${sid}`, JSON.stringify(record), "EX", ttlSec);
|
|
1056
|
-
if (record.userId != null) {
|
|
1057
|
-
await redis.sadd(`user_sess:${record.userId}`, sid);
|
|
1058
|
-
}
|
|
1166
|
+
/* persist record */
|
|
1059
1167
|
},
|
|
1060
1168
|
async delete(sid) {
|
|
1061
|
-
|
|
1062
|
-
if (existing?.userId != null) {
|
|
1063
|
-
await redis.srem(`user_sess:${existing.userId}`, sid);
|
|
1064
|
-
}
|
|
1065
|
-
await redis.del(`sess:${sid}`);
|
|
1169
|
+
/* delete sid */
|
|
1066
1170
|
},
|
|
1067
1171
|
async listByUser(userId) {
|
|
1068
|
-
|
|
1069
|
-
const out = [];
|
|
1070
|
-
for (const sid of sids) {
|
|
1071
|
-
const rec = await this.get(sid);
|
|
1072
|
-
if (rec) {
|
|
1073
|
-
out.push({
|
|
1074
|
-
id: sid.slice(0, 8),
|
|
1075
|
-
createdAt: rec.createdAt,
|
|
1076
|
-
updatedAt: rec.updatedAt,
|
|
1077
|
-
device: rec.data?.device,
|
|
1078
|
-
});
|
|
1079
|
-
}
|
|
1080
|
-
}
|
|
1081
|
-
return out;
|
|
1172
|
+
/* return array of active session summaries */
|
|
1082
1173
|
},
|
|
1083
1174
|
async revokeOthers(userId, currentSid) {
|
|
1084
|
-
|
|
1085
|
-
const revoked = [];
|
|
1086
|
-
for (const sid of sids) {
|
|
1087
|
-
if (sid !== currentSid) {
|
|
1088
|
-
await this.delete(sid);
|
|
1089
|
-
revoked.push(sid);
|
|
1090
|
-
}
|
|
1091
|
-
}
|
|
1092
|
-
return revoked;
|
|
1175
|
+
/* delete all user sessions except currentSid; return revoked sids */
|
|
1093
1176
|
},
|
|
1094
1177
|
};
|
|
1095
1178
|
|
|
1096
1179
|
await serve({
|
|
1097
1180
|
port: 3000,
|
|
1098
|
-
session: { secret: process.env.SESSION_SECRET, store:
|
|
1099
|
-
api: {
|
|
1100
|
-
/* ... */
|
|
1101
|
-
},
|
|
1181
|
+
session: { secret: process.env.SESSION_SECRET, store: customStore },
|
|
1182
|
+
api: {},
|
|
1102
1183
|
});
|
|
1103
1184
|
```
|
|
1104
1185
|
|
|
1105
|
-
###
|
|
1186
|
+
### 9.4 Timing-Safe Webhook Verification (`webhook`)
|
|
1106
1187
|
|
|
1107
|
-
|
|
1188
|
+
Verify HMAC signatures automatically over the raw body before JSON parsing:
|
|
1108
1189
|
|
|
1109
1190
|
```javascript
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
// Only reached if HMAC signature is valid
|
|
1119
|
-
return { received: true, type: event.type };
|
|
1120
|
-
},
|
|
1191
|
+
const stripeWebhook = {
|
|
1192
|
+
webhook: {
|
|
1193
|
+
secret: process.env.STRIPE_WEBHOOK_SECRET,
|
|
1194
|
+
header: "stripe-signature",
|
|
1195
|
+
algo: "sha256",
|
|
1196
|
+
},
|
|
1197
|
+
post(event) {
|
|
1198
|
+
return { received: true, type: event.type };
|
|
1121
1199
|
},
|
|
1122
1200
|
};
|
|
1123
1201
|
```
|
|
1124
1202
|
|
|
1125
|
-
###
|
|
1203
|
+
### 9.5 Rate Limiting (`limit` & `wire.cost`)
|
|
1126
1204
|
|
|
1127
|
-
|
|
1205
|
+
**Step 1 — Basic rate limit per window:**
|
|
1128
1206
|
|
|
1129
1207
|
```javascript
|
|
1130
|
-
|
|
1208
|
+
const search = {
|
|
1209
|
+
limit: { max: 30, window: "1m" },
|
|
1210
|
+
get: (query) => ({ results: [], q: query.q }),
|
|
1211
|
+
};
|
|
1212
|
+
```
|
|
1213
|
+
|
|
1214
|
+
**Step 2 — Dynamic point costs with `wire.cost()`:**
|
|
1131
1215
|
|
|
1132
|
-
|
|
1216
|
+
Each request costs `1` point by default. Call `wire.cost(points)` to penalize failed attempts or refund valid ones:
|
|
1217
|
+
|
|
1218
|
+
```javascript
|
|
1219
|
+
const login = {
|
|
1133
1220
|
limit: {
|
|
1134
|
-
max:
|
|
1221
|
+
max: 10,
|
|
1135
1222
|
window: "10m",
|
|
1136
|
-
key: (payload) => `login:${payload?.email || "
|
|
1223
|
+
key: (payload) => `login:${payload?.email || "unknown"}`,
|
|
1137
1224
|
},
|
|
1138
1225
|
async post(payload) {
|
|
1139
|
-
const
|
|
1140
|
-
if (!
|
|
1141
|
-
wire.cost(5); //
|
|
1142
|
-
wire.abort(401, "Invalid
|
|
1226
|
+
const valid = payload.password === "secret123";
|
|
1227
|
+
if (!valid) {
|
|
1228
|
+
wire.cost(5); // Failed attempts consume 5x quota
|
|
1229
|
+
wire.abort(401, "Invalid credentials");
|
|
1143
1230
|
}
|
|
1144
|
-
wire.cost(0); // Successful
|
|
1145
|
-
return {
|
|
1231
|
+
wire.cost(0); // Successful login costs 0 points
|
|
1232
|
+
return { ok: true };
|
|
1146
1233
|
},
|
|
1147
1234
|
};
|
|
1148
1235
|
```
|
|
1149
1236
|
|
|
1150
|
-
###
|
|
1151
|
-
|
|
1152
|
-
Pass `origins` to `serve()` to enable Cross-Origin Resource Sharing with credentials and automatic `OPTIONS` preflight responses:
|
|
1237
|
+
### 9.6 CORS & Preflight Handling (`origins`)
|
|
1153
1238
|
|
|
1154
1239
|
```javascript
|
|
1155
1240
|
await serve({
|
|
1156
1241
|
port: 3000,
|
|
1157
1242
|
origins: ["https://app.example.com", "http://localhost:5173"],
|
|
1158
|
-
api: {
|
|
1159
|
-
/* ... */
|
|
1160
|
-
},
|
|
1243
|
+
api: {},
|
|
1161
1244
|
});
|
|
1162
1245
|
```
|
|
1163
1246
|
|
|
1164
1247
|
---
|
|
1165
1248
|
|
|
1166
|
-
##
|
|
1249
|
+
## 10. Caching, Validation & Resilience
|
|
1250
|
+
|
|
1251
|
+
### 10.1 Self-Invalidating Response Cache (`cache`)
|
|
1252
|
+
|
|
1253
|
+
**Step 1 — Cache a `GET` endpoint:**
|
|
1254
|
+
|
|
1255
|
+
```javascript
|
|
1256
|
+
const stats = {
|
|
1257
|
+
cache: "1m", // Cached for 1 minute
|
|
1258
|
+
get: () => ({ generatedAt: Date.now() }),
|
|
1259
|
+
};
|
|
1260
|
+
```
|
|
1167
1261
|
|
|
1168
|
-
|
|
1262
|
+
**Step 2 — Automatic invalidation on mutations:**
|
|
1169
1263
|
|
|
1170
|
-
|
|
1264
|
+
When `cache` is placed on a parent or item node, any successful `POST`, `PUT`, `PATCH`, or `DELETE` automatically clears both the item cache and parent list cache:
|
|
1171
1265
|
|
|
1172
1266
|
```javascript
|
|
1173
|
-
|
|
1174
|
-
cache: "
|
|
1175
|
-
get: () => db.
|
|
1176
|
-
post: (data) => db.
|
|
1267
|
+
const articles = {
|
|
1268
|
+
cache: "5m",
|
|
1269
|
+
get: () => db.articles.all(),
|
|
1270
|
+
post: (data) => db.articles.create(data), // Automatically clears GET /articles cache
|
|
1177
1271
|
|
|
1178
1272
|
$id: param("int", {
|
|
1179
|
-
cache: "
|
|
1180
|
-
get: (id) => db.
|
|
1181
|
-
patch: (id, data) => db.
|
|
1182
|
-
delete: (id) => db.posts.delete(id), // Purges BOTH GET /posts/:id AND GET /posts
|
|
1273
|
+
cache: "5m",
|
|
1274
|
+
get: (id) => db.articles.find(id),
|
|
1275
|
+
patch: (id, data) => db.articles.update(id, data), // Clears GET /articles/:id AND GET /articles
|
|
1183
1276
|
}),
|
|
1184
1277
|
};
|
|
1185
1278
|
```
|
|
1186
1279
|
|
|
1187
|
-
###
|
|
1280
|
+
### 10.2 Request Coalescing (`coalesce`)
|
|
1188
1281
|
|
|
1189
|
-
|
|
1282
|
+
Deduplicate simultaneous identical `GET` requests during traffic spikes so your database runs the query only once:
|
|
1190
1283
|
|
|
1191
1284
|
```javascript
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
return await db.runHeavyAggregationQuery();
|
|
1198
|
-
},
|
|
1285
|
+
const report = {
|
|
1286
|
+
coalesce: true,
|
|
1287
|
+
cache: "30s",
|
|
1288
|
+
async get() {
|
|
1289
|
+
return await db.runExpensiveQuery();
|
|
1199
1290
|
},
|
|
1200
1291
|
};
|
|
1201
1292
|
```
|
|
1202
1293
|
|
|
1203
|
-
###
|
|
1294
|
+
### 10.3 Idempotent Mutations (`idempotent`)
|
|
1204
1295
|
|
|
1205
|
-
|
|
1296
|
+
Prevent duplicate writes when clients retry requests with the same `Idempotency-Key` header:
|
|
1206
1297
|
|
|
1207
1298
|
```javascript
|
|
1208
|
-
|
|
1299
|
+
const payments = {
|
|
1209
1300
|
idempotent: "24h",
|
|
1210
1301
|
async post(payload) {
|
|
1211
|
-
|
|
1212
|
-
return await ledger.transfer(payload);
|
|
1302
|
+
return await chargeCustomer(payload);
|
|
1213
1303
|
},
|
|
1214
1304
|
};
|
|
1215
1305
|
```
|
|
1216
1306
|
|
|
1217
|
-
###
|
|
1307
|
+
### 10.4 Declarative Input Validation (`expect`)
|
|
1218
1308
|
|
|
1219
|
-
|
|
1309
|
+
**Step 1 — Validate basic required fields (returns `422` if invalid):**
|
|
1220
1310
|
|
|
1221
|
-
|
|
1311
|
+
```javascript
|
|
1312
|
+
const signup = {
|
|
1313
|
+
expect: {
|
|
1314
|
+
email: "email",
|
|
1315
|
+
password: "string",
|
|
1316
|
+
age: "number",
|
|
1317
|
+
},
|
|
1318
|
+
post(payload) {
|
|
1319
|
+
return { created: payload.email };
|
|
1320
|
+
},
|
|
1321
|
+
};
|
|
1322
|
+
```
|
|
1222
1323
|
|
|
1223
|
-
|
|
1224
|
-
- Built-in format: `'email'`
|
|
1225
|
-
- Optional fields: append `?` (e.g., `'string?'`, `'number?'`, `'email?'`)
|
|
1226
|
-
- Enum values: pass an array of allowed literals (e.g., `['free', 'pro', 'enterprise']`)
|
|
1227
|
-
- Nested objects: nest another schema object
|
|
1324
|
+
**Step 2 — Optional fields (`?`), enums, arrays, and nested objects:**
|
|
1228
1325
|
|
|
1229
1326
|
```javascript
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
newsletter: "boolean",
|
|
1240
|
-
},
|
|
1241
|
-
},
|
|
1242
|
-
post(payload) {
|
|
1243
|
-
return { created: true, user: payload };
|
|
1327
|
+
const createProject = {
|
|
1328
|
+
expect: {
|
|
1329
|
+
name: "string",
|
|
1330
|
+
visibility: ["private", "team", "public"], // Enum
|
|
1331
|
+
description: "string?", // Optional string
|
|
1332
|
+
tags: "array?", // Optional array
|
|
1333
|
+
settings: {
|
|
1334
|
+
// Nested object
|
|
1335
|
+
notifications: "boolean",
|
|
1244
1336
|
},
|
|
1245
1337
|
},
|
|
1338
|
+
post: (payload) => payload,
|
|
1246
1339
|
};
|
|
1247
1340
|
```
|
|
1248
1341
|
|
|
1249
|
-
###
|
|
1342
|
+
### 10.5 Automatic Rollbacks (`wire.undo`) & Dry-Runs (`X-Simulate`)
|
|
1250
1343
|
|
|
1251
|
-
|
|
1344
|
+
**Step 1 — Register undo actions after each side effect:**
|
|
1252
1345
|
|
|
1253
|
-
|
|
1346
|
+
If a later step throws an error or calls `wire.abort()`, `servin` runs all `wire.undo()` functions in reverse order (LIFO):
|
|
1254
1347
|
|
|
1255
1348
|
```javascript
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
const hold = await inventory.reserve(order.items);
|
|
1261
|
-
wire.undo(() => inventory.release(hold.id));
|
|
1262
|
-
|
|
1263
|
-
const payment = await billing.charge(order.userId, order.total);
|
|
1264
|
-
wire.undo(() => billing.refund(payment.id));
|
|
1349
|
+
const transfer = {
|
|
1350
|
+
async post({ from, to, amount }) {
|
|
1351
|
+
await db.debit(from, amount);
|
|
1352
|
+
wire.undo(() => db.credit(from, amount)); // Runs automatically if credit() below fails
|
|
1265
1353
|
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
const shipment = await shipping.dispatch(hold.id, order.address);
|
|
1269
|
-
|
|
1270
|
-
wire.status(201);
|
|
1271
|
-
return { trackingId: shipment.id, totalCharged: order.total };
|
|
1354
|
+
await db.credit(to, amount);
|
|
1355
|
+
return { transferred: amount };
|
|
1272
1356
|
},
|
|
1273
1357
|
};
|
|
1274
1358
|
```
|
|
1275
1359
|
|
|
1276
|
-
|
|
1360
|
+
**Step 2 — Speculative dry-runs via `X-Simulate: true`:**
|
|
1277
1361
|
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
```javascript
|
|
1281
|
-
import { wire } from "servin";
|
|
1362
|
+
When a client sends header `X-Simulate: true`, `servin` executes your handler to compute the exact response, then automatically runs `wire.undo()` so no state changes persist.
|
|
1282
1363
|
|
|
1283
|
-
|
|
1284
|
-
async post(payload) {
|
|
1285
|
-
const order = await db.orders.insert(payload);
|
|
1364
|
+
### 10.6 Graceful Background Tasks (`wire.defer`)
|
|
1286
1365
|
|
|
1287
|
-
|
|
1288
|
-
await mailer.sendReceipt(order.email, order.id);
|
|
1289
|
-
});
|
|
1366
|
+
Run non-blocking work after sending the HTTP response. `servin` waits for all deferred tasks to finish during server shutdown:
|
|
1290
1367
|
|
|
1368
|
+
```javascript
|
|
1369
|
+
const register = {
|
|
1370
|
+
async post(user) {
|
|
1371
|
+
const saved = await db.users.insert(user);
|
|
1372
|
+
wire.defer(() => sendWelcomeEmail(saved.email));
|
|
1291
1373
|
wire.status(201);
|
|
1292
|
-
return
|
|
1374
|
+
return saved;
|
|
1293
1375
|
},
|
|
1294
1376
|
};
|
|
1295
1377
|
```
|
|
1296
1378
|
|
|
1297
|
-
###
|
|
1298
|
-
|
|
1299
|
-
- **Adaptive Load Shedding:** Mark non-critical endpoints (like exports or recommendations) with `priority: 'low'`. When the Node.js event-loop p95 delay exceeds `lagThresholdMs` (default `60ms`), `servin` automatically sheds those requests with `503 Service Unavailable` and `Retry-After: 2` to protect critical traffic.
|
|
1300
|
-
- **API Sunset Headers:** Set `sunset: '2027-01-01'` on legacy endpoints to automatically attach standard `Deprecation: true` and `Sunset` HTTP headers.
|
|
1379
|
+
### 10.7 Load Shedding (`priority: 'low'`) & Deprecation (`sunset`)
|
|
1301
1380
|
|
|
1302
1381
|
```javascript
|
|
1303
|
-
|
|
1304
|
-
sunset: "2027-
|
|
1305
|
-
|
|
1306
|
-
priority: "low",
|
|
1307
|
-
get: () =>
|
|
1382
|
+
const exportsApi = {
|
|
1383
|
+
sunset: "2027-01-01", // Emits standard Deprecation and Sunset headers
|
|
1384
|
+
csv: {
|
|
1385
|
+
priority: "low", // Returns 503 Retry-After: 2 if event loop p95 lag > lagThresholdMs
|
|
1386
|
+
get: () => buildHeavyCsv(),
|
|
1308
1387
|
},
|
|
1309
1388
|
};
|
|
1310
1389
|
```
|
|
1311
1390
|
|
|
1312
1391
|
---
|
|
1313
1392
|
|
|
1314
|
-
##
|
|
1393
|
+
## 11. Linear WebSockets & Pub/Sub
|
|
1315
1394
|
|
|
1316
|
-
###
|
|
1395
|
+
### 11.1 Step 1: Minimal Echo WebSocket (`ws` & `for await`)
|
|
1317
1396
|
|
|
1318
|
-
|
|
1397
|
+
Add a `ws(socket)` method anywhere in your tree and iterate over incoming messages linearly with `for await`:
|
|
1319
1398
|
|
|
1320
1399
|
```javascript
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
};
|
|
1400
|
+
const echo = {
|
|
1401
|
+
// WS /echo
|
|
1402
|
+
async ws(socket) {
|
|
1403
|
+
socket.send({ status: "connected" });
|
|
1326
1404
|
|
|
1327
|
-
await
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
api: {
|
|
1331
|
-
rooms: guard(requireUser, {
|
|
1332
|
-
$id: param("slug", {
|
|
1333
|
-
// HTTP GET /rooms/general
|
|
1334
|
-
get: (id) => ({ room: id, active: true }),
|
|
1335
|
-
|
|
1336
|
-
// WS /rooms/general
|
|
1337
|
-
async ws(id, socket) {
|
|
1338
|
-
const topic = `room:${id}`;
|
|
1339
|
-
const joinedAt = Date.now();
|
|
1340
|
-
|
|
1341
|
-
socket.join(topic);
|
|
1342
|
-
socket.send({ type: "welcome", room: id, user: wire.session.userId });
|
|
1343
|
-
socket.broadcast(topic, {
|
|
1344
|
-
type: "user_joined",
|
|
1345
|
-
user: wire.session.userId,
|
|
1346
|
-
});
|
|
1347
|
-
|
|
1348
|
-
// Runs automatically when the client disconnects or session is revoked
|
|
1349
|
-
wire.undo(() => {
|
|
1350
|
-
socket.broadcast(topic, {
|
|
1351
|
-
type: "user_left",
|
|
1352
|
-
user: wire.session.userId,
|
|
1353
|
-
connectedMs: Date.now() - joinedAt,
|
|
1354
|
-
});
|
|
1355
|
-
});
|
|
1356
|
-
|
|
1357
|
-
for await (const message of socket) {
|
|
1358
|
-
wire.publish(topic, {
|
|
1359
|
-
type: "chat",
|
|
1360
|
-
from: wire.session.userId,
|
|
1361
|
-
text: message.text,
|
|
1362
|
-
});
|
|
1363
|
-
}
|
|
1364
|
-
},
|
|
1365
|
-
}),
|
|
1366
|
-
}),
|
|
1405
|
+
for await (const msg of socket) {
|
|
1406
|
+
socket.send({ echoed: msg });
|
|
1407
|
+
}
|
|
1367
1408
|
},
|
|
1368
|
-
}
|
|
1409
|
+
};
|
|
1369
1410
|
```
|
|
1370
1411
|
|
|
1371
|
-
###
|
|
1412
|
+
### 11.2 Step 2: Rooms & Pub/Sub Broadcasting (`socket.join`, `wire.publish`)
|
|
1372
1413
|
|
|
1373
|
-
|
|
1414
|
+
Subscribe sockets to named topics and broadcast messages from either WebSocket handlers or HTTP routes:
|
|
1374
1415
|
|
|
1375
1416
|
```javascript
|
|
1376
|
-
|
|
1377
|
-
$
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1417
|
+
const chat = {
|
|
1418
|
+
$room: {
|
|
1419
|
+
// WS /chat/:room
|
|
1420
|
+
async ws(room, socket) {
|
|
1421
|
+
socket.join(`room:${room}`);
|
|
1422
|
+
socket.broadcast(`room:${room}`, { event: "joined" });
|
|
1423
|
+
|
|
1424
|
+
for await (const msg of socket) {
|
|
1425
|
+
wire.publish(`room:${room}`, { text: msg.text });
|
|
1426
|
+
}
|
|
1385
1427
|
},
|
|
1386
|
-
}
|
|
1428
|
+
},
|
|
1429
|
+
|
|
1430
|
+
// Any HTTP route can also publish to WebSocket subscribers!
|
|
1431
|
+
announce: {
|
|
1432
|
+
post({ room, text }) {
|
|
1433
|
+
wire.publish(`room:${room}`, { announcement: text });
|
|
1434
|
+
return { sent: true };
|
|
1435
|
+
},
|
|
1436
|
+
},
|
|
1387
1437
|
};
|
|
1388
1438
|
```
|
|
1389
1439
|
|
|
1390
|
-
|
|
1440
|
+
### 11.3 Step 3: Guarded WebSockets & `wsConfig`
|
|
1391
1441
|
|
|
1392
|
-
|
|
1393
|
-
- `socket.send(data)` — Sends JSON-serialized data or raw `Uint8Array` binary frames to this client.
|
|
1394
|
-
- `socket.join(topic)` / `socket.leave(topic)` — Subscribes or unsubscribes the socket from a topic (automatically cleaned up on disconnect).
|
|
1395
|
-
- `socket.broadcast(topic, data)` — Sends `data` to all subscribers of `topic` _except_ the sender.
|
|
1396
|
-
- `socket.close(code, reason)` — Closes the WebSocket connection cleanly.
|
|
1397
|
-
- `socket.isOpen` — Boolean indicating whether the underlying TCP socket is open.
|
|
1398
|
-
- `socket.bufferedAmount` — Bytes currently queued in the socket write buffer.
|
|
1399
|
-
|
|
1400
|
-
### 9.3 WebSocket Options (`wsConfig`) & Session Auto-Kick
|
|
1401
|
-
|
|
1402
|
-
Customize frame limits, ping/pong heartbeats, and binary mode per branch using `wsConfig`:
|
|
1442
|
+
Combine `guard()`, `param()`, and `wsConfig` (`heartbeat`, `maxPayload`, `binary`) on the same branch:
|
|
1403
1443
|
|
|
1404
1444
|
```javascript
|
|
1405
|
-
|
|
1445
|
+
const liveStream = guard(requireAuth, {
|
|
1406
1446
|
wsConfig: {
|
|
1407
1447
|
maxPayload: "256kb",
|
|
1408
|
-
heartbeat: "30s",
|
|
1409
|
-
binary: true, // Delivers incoming frames as Uint8Array
|
|
1410
|
-
},
|
|
1411
|
-
async ws(socket) {
|
|
1412
|
-
for await (const chunk of socket) {
|
|
1413
|
-
socket.send(chunk); // Echo binary Uint8Array
|
|
1414
|
-
}
|
|
1448
|
+
heartbeat: "30s",
|
|
1415
1449
|
},
|
|
1416
|
-
|
|
1450
|
+
$channelId: param("int", {
|
|
1451
|
+
async ws(channelId, socket) {
|
|
1452
|
+
socket.join(`ch:${channelId}`);
|
|
1453
|
+
for await (const msg of socket) {
|
|
1454
|
+
socket.broadcast(`ch:${channelId}`, msg);
|
|
1455
|
+
}
|
|
1456
|
+
},
|
|
1457
|
+
}),
|
|
1458
|
+
});
|
|
1417
1459
|
```
|
|
1418
1460
|
|
|
1419
1461
|
---
|
|
1420
1462
|
|
|
1421
|
-
##
|
|
1463
|
+
## 12. Streaming File Uploads (`wire.multipart` & `rawBody`)
|
|
1422
1464
|
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
`wire.multipart(opts)` parses incoming multipart streams sequentially without buffering entire file uploads into RAM:
|
|
1465
|
+
**1. Streaming `multipart/form-data` without buffering in RAM:**
|
|
1426
1466
|
|
|
1427
1467
|
```javascript
|
|
1428
1468
|
import fs from "node:fs";
|
|
@@ -1430,54 +1470,42 @@ import { pipeline } from "node:stream/promises";
|
|
|
1430
1470
|
import { Readable } from "node:stream";
|
|
1431
1471
|
import { wire } from "servin";
|
|
1432
1472
|
|
|
1433
|
-
|
|
1473
|
+
const upload = {
|
|
1434
1474
|
async post() {
|
|
1435
|
-
const
|
|
1436
|
-
const
|
|
1475
|
+
const fields = {};
|
|
1476
|
+
const files = [];
|
|
1437
1477
|
|
|
1438
|
-
for await (const part of wire.multipart({ maxFileSize: "
|
|
1478
|
+
for await (const part of wire.multipart({ maxFileSize: "20mb" })) {
|
|
1439
1479
|
if (part.isField) {
|
|
1440
|
-
|
|
1480
|
+
fields[part.name] = await part.text();
|
|
1441
1481
|
} else if (part.isFile) {
|
|
1442
|
-
const dest = `./uploads/${
|
|
1482
|
+
const dest = `./uploads/${part.filename}`;
|
|
1443
1483
|
await pipeline(
|
|
1444
1484
|
Readable.fromWeb(part.stream),
|
|
1445
1485
|
fs.createWriteStream(dest),
|
|
1446
1486
|
);
|
|
1447
|
-
|
|
1448
|
-
field: part.name,
|
|
1449
|
-
filename: part.filename,
|
|
1450
|
-
savedTo: dest,
|
|
1451
|
-
});
|
|
1487
|
+
files.push(part.filename);
|
|
1452
1488
|
}
|
|
1453
1489
|
}
|
|
1454
1490
|
|
|
1455
|
-
|
|
1456
|
-
return { metadata, uploadedFiles };
|
|
1491
|
+
return { fields, files };
|
|
1457
1492
|
},
|
|
1458
1493
|
};
|
|
1459
1494
|
```
|
|
1460
1495
|
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
Set `rawBody: true` on a route to skip body parsing and pipe `wire.stream` directly:
|
|
1496
|
+
**2. Raw unbuffered binary upload (`rawBody: true`):**
|
|
1464
1497
|
|
|
1465
1498
|
```javascript
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
import { Readable } from "node:stream";
|
|
1469
|
-
import { wire } from "servin";
|
|
1470
|
-
|
|
1471
|
-
export const blobs = {
|
|
1472
|
-
$name: {
|
|
1499
|
+
const rawUpload = {
|
|
1500
|
+
$filename: {
|
|
1473
1501
|
rawBody: true,
|
|
1474
|
-
async put(
|
|
1502
|
+
async put(filename) {
|
|
1475
1503
|
await pipeline(
|
|
1476
1504
|
Readable.fromWeb(wire.stream),
|
|
1477
|
-
fs.createWriteStream(`./
|
|
1505
|
+
fs.createWriteStream(`./uploads/${filename}`),
|
|
1478
1506
|
);
|
|
1479
1507
|
wire.status(201);
|
|
1480
|
-
return {
|
|
1508
|
+
return { saved: filename };
|
|
1481
1509
|
},
|
|
1482
1510
|
},
|
|
1483
1511
|
};
|
|
@@ -1485,171 +1513,113 @@ export const blobs = {
|
|
|
1485
1513
|
|
|
1486
1514
|
---
|
|
1487
1515
|
|
|
1488
|
-
##
|
|
1516
|
+
## 13. Decoupled Side Effects (`reactTo`)
|
|
1489
1517
|
|
|
1490
|
-
|
|
1518
|
+
Attach secondary side effects (analytics, loyalty points, audit logs) from outside your main handler without coupling modules together:
|
|
1491
1519
|
|
|
1492
1520
|
```javascript
|
|
1493
1521
|
import { reactTo } from "servin";
|
|
1494
|
-
import { orders } from "./modules/orders.js";
|
|
1495
1522
|
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
await db.loyalty.addPoints(output.userId, 50);
|
|
1499
|
-
}
|
|
1523
|
+
reactTo(tasks.post, ({ output }) => {
|
|
1524
|
+
console.log(`Audit: task #${output.id} created`);
|
|
1500
1525
|
});
|
|
1501
1526
|
```
|
|
1502
1527
|
|
|
1503
1528
|
---
|
|
1504
1529
|
|
|
1505
|
-
##
|
|
1506
|
-
|
|
1507
|
-
`servin` automatically serves a dynamic ES module at **`GET /@client.js`** mirroring your exact domain tree. Frontend apps can import `api` directly in the browser without `fetch()` boilerplate, URL string interpolation, or build steps:
|
|
1508
|
-
|
|
1509
|
-
```javascript
|
|
1510
|
-
// In your frontend application (Browser / React / Vue / Svelte / Vanilla JS)
|
|
1511
|
-
import { api } from "http://localhost:3000/@client.js";
|
|
1512
|
-
|
|
1513
|
-
// 1. GET /tasks?done=false
|
|
1514
|
-
const pendingTasks = await api.tasks.get({ done: "false" });
|
|
1515
|
-
|
|
1516
|
-
// 2. GET /tasks/1 (typed parameter)
|
|
1517
|
-
const task = await api.tasks.$id.get(1);
|
|
1518
|
-
|
|
1519
|
-
// 3. POST /tasks
|
|
1520
|
-
const created = await api.tasks.post({ title: "Ship v1.0", priority: "high" });
|
|
1521
|
-
|
|
1522
|
-
// 4. Method union PUT|PATCH /tasks/1
|
|
1523
|
-
const updated = await api.tasks.$id["put|patch"](1, { done: true });
|
|
1524
|
-
|
|
1525
|
-
// 5. DELETE /tasks/1 -> returns null on 204
|
|
1526
|
-
await api.tasks.$id.delete(1);
|
|
1530
|
+
## 14. Logging, Debugging & Automated Testing
|
|
1527
1531
|
|
|
1528
|
-
|
|
1529
|
-
for await (const event of api.notifications.stream({ channel: "alerts" })) {
|
|
1530
|
-
console.log("SSE event:", event);
|
|
1531
|
-
}
|
|
1532
|
+
### 14.1 Startup Messages & Access Logs (`message`, `onListen`, `accessLog`)
|
|
1532
1533
|
|
|
1533
|
-
|
|
1534
|
-
const room = api.rooms.$id.ws("general");
|
|
1535
|
-
room.send({ text: "Hello from the browser!" });
|
|
1534
|
+
**1. Custom startup message:**
|
|
1536
1535
|
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1536
|
+
```javascript
|
|
1537
|
+
await serve({
|
|
1538
|
+
port: 3000,
|
|
1539
|
+
message: ({ port, url }) => `Server running on port ${port} (${url})`,
|
|
1540
|
+
api: {},
|
|
1541
|
+
});
|
|
1540
1542
|
```
|
|
1541
1543
|
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
## 13. Observability, Logging & Automated Testing
|
|
1545
|
-
|
|
1546
|
-
### 13.1 Custom Startup Messages & Access Logs (`message`, `onListen`, `accessLog`)
|
|
1547
|
-
|
|
1548
|
-
`servin` logs incoming HTTP and WebSocket traffic automatically (`[servin] GET /tasks 200 1.2ms [CACHE]`) and prints a startup message when ready. Both can be customized or disabled:
|
|
1544
|
+
**2. Custom access log formatter (or `accessLog: false` to disable):**
|
|
1549
1545
|
|
|
1550
1546
|
```javascript
|
|
1551
|
-
import { serve } from "servin";
|
|
1552
|
-
|
|
1553
1547
|
await serve({
|
|
1554
1548
|
port: 3000,
|
|
1555
|
-
|
|
1556
|
-
// Custom startup message (string, function, or false)
|
|
1557
|
-
message: ({ port, url }) => `Server is running on port ${port} -> ${url}`,
|
|
1558
|
-
|
|
1559
|
-
// Optional async hook once listening
|
|
1560
|
-
async onListen({ port }) {
|
|
1561
|
-
console.log(`Health check ready at http://127.0.0.1:${port}/health`);
|
|
1562
|
-
},
|
|
1563
|
-
|
|
1564
|
-
// Custom access log formatter & filter (or pass `accessLog: false` to disable)
|
|
1565
1549
|
accessLog(info) {
|
|
1566
|
-
if (info.url.pathname === "/health") return null; //
|
|
1567
|
-
|
|
1568
|
-
return `[${info.status}] ${info.method} ${info.url.pathname} (${info.durationMs.toFixed(1)}ms)${cacheTag}`;
|
|
1569
|
-
},
|
|
1570
|
-
|
|
1571
|
-
api: {
|
|
1572
|
-
health: { get: () => ({ status: "ok" }) },
|
|
1550
|
+
if (info.url.pathname === "/health") return null; // Hide healthchecks
|
|
1551
|
+
return `[${info.status}] ${info.method} ${info.url.pathname} (${info.durationMs.toFixed(1)}ms)`;
|
|
1573
1552
|
},
|
|
1553
|
+
api: {},
|
|
1574
1554
|
});
|
|
1575
1555
|
```
|
|
1576
1556
|
|
|
1577
|
-
###
|
|
1557
|
+
### 14.2 Error-Triggered Debug Trace (`wire.log.debug`) & `Server-Timing` (`wire.mark`)
|
|
1578
1558
|
|
|
1579
|
-
-
|
|
1580
|
-
-
|
|
1559
|
+
- `wire.log.debug(...)` buffers logs in memory and **only prints them if the request fails with an unhandled error**.
|
|
1560
|
+
- `wire.mark(label)` measures step duration and emits an HTTP `Server-Timing` header.
|
|
1581
1561
|
|
|
1582
1562
|
```javascript
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
export const reports = {
|
|
1563
|
+
const report = {
|
|
1586
1564
|
async get() {
|
|
1587
|
-
wire.log.debug("
|
|
1588
|
-
userId: wire.session.userId,
|
|
1589
|
-
});
|
|
1565
|
+
wire.log.debug("Querying analytics table");
|
|
1590
1566
|
|
|
1591
1567
|
const endDb = wire.mark("db");
|
|
1592
|
-
const rows = await db.
|
|
1568
|
+
const rows = await db.query("SELECT * FROM metrics");
|
|
1593
1569
|
endDb();
|
|
1594
1570
|
|
|
1595
|
-
|
|
1596
|
-
const summary = formatSummary(rows);
|
|
1597
|
-
endFormat();
|
|
1598
|
-
|
|
1599
|
-
// Emits header: Server-Timing: db;dur=14.20, format;dur=1.85
|
|
1600
|
-
return summary;
|
|
1571
|
+
return rows; // Emits header: Server-Timing: db;dur=12.40
|
|
1601
1572
|
},
|
|
1602
1573
|
};
|
|
1603
1574
|
```
|
|
1604
1575
|
|
|
1605
|
-
###
|
|
1576
|
+
### 14.3 Automated Test Synthesis (`synthesizeTests`)
|
|
1606
1577
|
|
|
1607
|
-
|
|
1578
|
+
Set `synthesizeTests: './tests/api.test.js'` in `serve()` during development to automatically record verified endpoints into a runnable `node:test` file.
|
|
1608
1579
|
|
|
1609
|
-
###
|
|
1580
|
+
### 14.4 Error Snapshots & Local Replay (`snapshotOnError` & `replay`)
|
|
1610
1581
|
|
|
1611
|
-
Set `snapshotOnError: './snapshots'` to
|
|
1582
|
+
Set `snapshotOnError: './snapshots'` to save failing `500` requests, then replay them locally against your handler:
|
|
1612
1583
|
|
|
1613
1584
|
```javascript
|
|
1614
1585
|
import { replay } from "servin/test";
|
|
1615
|
-
import {
|
|
1586
|
+
import { tasks } from "./tasks.js";
|
|
1616
1587
|
|
|
1617
|
-
// Re-executes the failing handler locally with captured URL, headers, and extracted parameters
|
|
1618
1588
|
await replay(
|
|
1619
|
-
|
|
1589
|
+
tasks.$id.get,
|
|
1620
1590
|
"./snapshots/err-2026-11-25T12-00-00-000Z-a1b2c3d4.json",
|
|
1621
1591
|
);
|
|
1622
1592
|
```
|
|
1623
1593
|
|
|
1624
1594
|
---
|
|
1625
1595
|
|
|
1626
|
-
##
|
|
1627
|
-
|
|
1628
|
-
|
|
|
1629
|
-
|
|
|
1630
|
-
| `wire.req`
|
|
1631
|
-
| `wire.method`
|
|
1632
|
-
| `wire.url`
|
|
1633
|
-
| `wire.headers`
|
|
1634
|
-
| `wire.stream`
|
|
1635
|
-
| `wire.signal`
|
|
1636
|
-
| `wire.status(code)`
|
|
1637
|
-
| `wire.abort(status, msg)`
|
|
1638
|
-
| `wire.
|
|
1639
|
-
| `wire.
|
|
1640
|
-
| `wire.
|
|
1641
|
-
| `wire.
|
|
1642
|
-
| `wire.
|
|
1643
|
-
| `wire.
|
|
1644
|
-
| `wire.
|
|
1645
|
-
| `wire.
|
|
1646
|
-
| `wire.
|
|
1647
|
-
| `wire.
|
|
1648
|
-
| `wire.log.
|
|
1649
|
-
| `wire.mark(label)`
|
|
1596
|
+
## 15. Complete Ambient `wire` API Reference
|
|
1597
|
+
|
|
1598
|
+
| Member | Signature / Type | Description |
|
|
1599
|
+
| :--------------------------- | :-------------------------------- | :----------------------------------------------------------------------------------------------------------------------- |
|
|
1600
|
+
| `wire.req` | `Request` | Native Web `Request` instance. |
|
|
1601
|
+
| `wire.method` | `string` | Uppercase HTTP method (`'GET'`, `'POST'`, etc.) or `'WS'`. |
|
|
1602
|
+
| `wire.url` | `URL` | Parsed `URL` instance for the current request. |
|
|
1603
|
+
| `wire.headers` | `Headers` (Proxy) | Reads response then request headers (`.get()`, `.has()`); mutates response headers (`.set()`, `.append()`, `.delete()`). |
|
|
1604
|
+
| `wire.stream` | `ReadableStream \| null` | Unbuffered request body stream (used with `rawBody: true`). |
|
|
1605
|
+
| `wire.signal` | `AbortSignal` | Aborted if the client disconnects early. |
|
|
1606
|
+
| `wire.status(code)` | `(number) => void` | Sets the HTTP status code. |
|
|
1607
|
+
| `wire.abort(status, msg)` | `(number, string) => never` | Halts execution, triggers `wire.undo()`, and sends `{ error: msg }`. |
|
|
1608
|
+
| `wire.redirect(url, status)` | `(string, number?) => never` | Halts execution, commits session cookies, and sends a redirect (`302` by default). |
|
|
1609
|
+
| `wire.undo(fn)` | `(() => any) => void` | Registers a LIFO rollback callback run on error, abort, SSE cancel, or `X-Simulate: true`. |
|
|
1610
|
+
| `wire.defer(fn)` | `(() => any) => void` | Schedules a background task tracked during graceful shutdown. |
|
|
1611
|
+
| `wire.html` | `tag \| (string) => HtmlResponse` | Creates an HTML response; escapes interpolated variables when used as a tagged template. |
|
|
1612
|
+
| `wire.file(filePath)` | `(string) => FileStreamResponse` | Streams a file with `ETag` (`304`) and `Range` (`206`) support. |
|
|
1613
|
+
| `wire.multipart(opts)` | `(opts?) => AsyncGenerator` | Iterates streaming `multipart/form-data` fields and files sequentially. |
|
|
1614
|
+
| `wire.session` | `Proxy \| null` | Lazy encrypted session object (`.rotate()`, `.bind(userId)`, or `wire.session = null`). |
|
|
1615
|
+
| `wire.sessions` | `{ list, revokeOthers }` | Multi-device session listing and remote session revocation helpers. |
|
|
1616
|
+
| `wire.publish(topic, data)` | `(string, any) => void` | Broadcasts a message to all WebSocket clients subscribed to `topic`. |
|
|
1617
|
+
| `wire.cost(points)` | `(number) => void` | Adjusts rate-limit quota consumption for the current request. |
|
|
1618
|
+
| `wire.log.debug(msg, meta)` | `(string, any?) => void` | Buffers a debug log entry emitted only on unhandled errors. |
|
|
1619
|
+
| `wire.mark(label)` | `(string) => () => number` | Starts a performance timer; calling the returned function records `Server-Timing`. |
|
|
1650
1620
|
|
|
1651
1621
|
---
|
|
1652
1622
|
|
|
1653
|
-
##
|
|
1623
|
+
## 16. License
|
|
1654
1624
|
|
|
1655
1625
|
MIT
|