@acryldev/create-blends 1.7.1 → 1.7.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/{LICENSE → docs/framework/LICENSE} +3 -1
- package/docs/framework/README.md +70 -0
- package/docs/framework/agents/index.md +59 -0
- package/docs/framework/api/acryl.md +247 -0
- package/docs/framework/api/context.md +478 -0
- package/docs/framework/api/exception.md +80 -0
- package/docs/framework/api/index.md +12 -0
- package/docs/framework/api/presets.md +62 -0
- package/docs/framework/api/request.md +396 -0
- package/docs/framework/api/routing.md +303 -0
- package/docs/framework/api/summary.md +143 -0
- package/docs/framework/concepts/benchmarks.md +26 -0
- package/docs/framework/concepts/developer-experience.md +5 -0
- package/docs/framework/concepts/middleware.md +21 -0
- package/docs/framework/concepts/motivation.md +14 -0
- package/docs/framework/concepts/routers.md +63 -0
- package/docs/framework/concepts/stacks.md +235 -0
- package/docs/framework/concepts/web-standard.md +27 -0
- package/docs/framework/cordis/acryl-in-a-cordis-app.md +160 -0
- package/docs/framework/cordis/concepts.md +105 -0
- package/docs/framework/cordis/middleware.md +8 -0
- package/docs/framework/cordis/migration-from-0-3.md +111 -0
- package/docs/framework/cordis/migration-from-0-4.md +14 -0
- package/docs/framework/cordis/migration-from-dsh-webserver.md +109 -0
- package/docs/framework/cordis/migration-to-1-0.md +46 -0
- package/docs/framework/cordis/mounting.md +85 -0
- package/docs/framework/cordis/node-server.md +100 -0
- package/docs/framework/cordis/plugin-lifecycle.md +111 -0
- package/docs/framework/cordis/surfaces.md +71 -0
- package/docs/framework/cordis/transport-and-cancellation.md +57 -0
- package/docs/framework/cordis/validation.md +135 -0
- package/docs/framework/getting-started/basic.md +201 -0
- package/docs/framework/getting-started/bun.md +219 -0
- package/docs/framework/getting-started/deploy.md +133 -0
- package/docs/framework/getting-started/desktop.md +80 -0
- package/docs/framework/getting-started/nodejs.md +365 -0
- package/docs/framework/getting-started/other-runtimes.md +30 -0
- package/docs/framework/guides/best-practices.md +231 -0
- package/docs/framework/guides/bring-your-own-tool.md +218 -0
- package/docs/framework/guides/client-modules.md +210 -0
- package/docs/framework/guides/create-acrylblends.md +143 -0
- package/docs/framework/guides/data.md +314 -0
- package/docs/framework/guides/examples.md +3 -0
- package/docs/framework/guides/faq.md +19 -0
- package/docs/framework/guides/forms-and-sessions.md +235 -0
- package/docs/framework/guides/helpers.md +33 -0
- package/docs/framework/guides/jsx-dom.md +301 -0
- package/docs/framework/guides/jsx.md +487 -0
- package/docs/framework/guides/middleware.md +253 -0
- package/docs/framework/guides/production.md +80 -0
- package/docs/framework/guides/rpc.md +878 -0
- package/docs/framework/guides/testing.md +133 -0
- package/docs/framework/guides/validation.md +470 -0
- package/docs/framework/helpers/accepts.md +60 -0
- package/docs/framework/helpers/adapter.md +57 -0
- package/docs/framework/helpers/conninfo.md +77 -0
- package/docs/framework/helpers/cookie.md +232 -0
- package/docs/framework/helpers/css.md +282 -0
- package/docs/framework/helpers/dev.md +64 -0
- package/docs/framework/helpers/factory.md +180 -0
- package/docs/framework/helpers/html.md +123 -0
- package/docs/framework/helpers/jwt.md +184 -0
- package/docs/framework/helpers/proxy.md +115 -0
- package/docs/framework/helpers/route.md +143 -0
- package/docs/framework/helpers/ssg.md +390 -0
- package/docs/framework/helpers/streaming.md +224 -0
- package/docs/framework/helpers/testing.md +118 -0
- package/docs/framework/helpers/websocket.md +208 -0
- package/docs/framework/middleware/builtin/basic-auth.md +165 -0
- package/docs/framework/middleware/builtin/bearer-auth.md +138 -0
- package/docs/framework/middleware/builtin/body-limit.md +71 -0
- package/docs/framework/middleware/builtin/cache.md +99 -0
- package/docs/framework/middleware/builtin/combine.md +94 -0
- package/docs/framework/middleware/builtin/compress.md +59 -0
- package/docs/framework/middleware/builtin/context-storage.md +74 -0
- package/docs/framework/middleware/builtin/cors.md +134 -0
- package/docs/framework/middleware/builtin/csrf.md +105 -0
- package/docs/framework/middleware/builtin/etag.md +54 -0
- package/docs/framework/middleware/builtin/ip-restriction.md +69 -0
- package/docs/framework/middleware/builtin/jsx-renderer.md +283 -0
- package/docs/framework/middleware/builtin/jwk.md +192 -0
- package/docs/framework/middleware/builtin/jwt.md +145 -0
- package/docs/framework/middleware/builtin/language.md +232 -0
- package/docs/framework/middleware/builtin/logger.md +74 -0
- package/docs/framework/middleware/builtin/loopback-only.md +31 -0
- package/docs/framework/middleware/builtin/method-not-allowed.md +48 -0
- package/docs/framework/middleware/builtin/method-override.md +80 -0
- package/docs/framework/middleware/builtin/mount.md +103 -0
- package/docs/framework/middleware/builtin/pretty-json.md +53 -0
- package/docs/framework/middleware/builtin/request-id.md +87 -0
- package/docs/framework/middleware/builtin/secure-headers.md +247 -0
- package/docs/framework/middleware/builtin/timeout.md +98 -0
- package/docs/framework/middleware/builtin/timing.md +100 -0
- package/docs/framework/middleware/builtin/trailing-slash.md +74 -0
- package/docs/framework/middleware/third-party.md +4 -0
- package/docs/framework/workshop/README.md +294 -0
- package/docs/framework/workshop/facilitator.md +101 -0
- package/package.json +2 -2
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# Node server
|
|
2
|
+
|
|
3
|
+
`@acryldev/node-server` serves the whole router over HTTP from a standalone Node.js process. Use it for an app that runs without the ACRYL
|
|
4
|
+
Host. Inside the Host (Web and Desktop), the Host owns the web server and a plugin asks `@acryldev/router-http` to serve its prefix instead.
|
|
5
|
+
|
|
6
|
+
## Serve the router
|
|
7
|
+
|
|
8
|
+
The server is a Cordis plugin that provides the `nodeServer` service:
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { Context } from '@deepseek-ai/cordis'
|
|
12
|
+
import * as router from '@acryldev/blends/cordis/router'
|
|
13
|
+
import * as nodeServer from '@acryldev/blends/cordis/node-server'
|
|
14
|
+
import * as todo from './todo.ts'
|
|
15
|
+
|
|
16
|
+
const root = new Context()
|
|
17
|
+
root.plugin(router)
|
|
18
|
+
root.plugin(nodeServer, { port: 3000 })
|
|
19
|
+
root.plugin(todo)
|
|
20
|
+
|
|
21
|
+
root.inject(['nodeServer'], ctx => {
|
|
22
|
+
console.log(`listening on ${ctx.nodeServer.url}`)
|
|
23
|
+
})
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
| Option | Default | Meaning |
|
|
27
|
+
| --- | --- | --- |
|
|
28
|
+
| `hostname` | `127.0.0.1` | address to bind; binding elsewhere exposes the app to the network |
|
|
29
|
+
| `port` | `0` | port to listen on; 0 lets the system choose |
|
|
30
|
+
| `scan` | `20` | how many further ports to try when the configured one is taken |
|
|
31
|
+
|
|
32
|
+
Without Cordis, `serve()` from `acrylblends/node-server` binds the same default, `127.0.0.1`; pass `hostname: '0.0.0.0'` to accept other
|
|
33
|
+
machines (see [Node.js](../getting-started/nodejs.md#listen-on-another-interface)).
|
|
34
|
+
|
|
35
|
+
The plugin becomes active once the server listens, so a plugin that injects `nodeServer` can rely on `ctx.nodeServer.url` and
|
|
36
|
+
`ctx.nodeServer.port`. A failure to bind fails the plugin.
|
|
37
|
+
|
|
38
|
+
Every request goes to `ctx.router.fetch`, so routes appear and disappear as plugins mount and unload, with no restart. A plugin's
|
|
39
|
+
`ctx.inject(['routerHttp'], ...)` call never fires here: this adapter serves every prefix already.
|
|
40
|
+
|
|
41
|
+
## Connection information
|
|
42
|
+
|
|
43
|
+
The adapter passes the socket's peer address and local port to the router as connection facts. Handlers read them through
|
|
44
|
+
`connectionOf(c)` or `getConnInfo(c)` and never touch Node socket objects, so the same handler runs in process and through the Host. See
|
|
45
|
+
[Context](../api/context.md#transport-facts).
|
|
46
|
+
|
|
47
|
+
## Static files
|
|
48
|
+
|
|
49
|
+
The Node `serveStatic` reads files from disk:
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { serveStatic } from '@acryldev/blends/node-server'
|
|
53
|
+
|
|
54
|
+
const app = new Acryl()
|
|
55
|
+
.use('/assets/*', serveStatic({ root: './public' }))
|
|
56
|
+
.get('/', serveStatic({ path: './public/index.html' }))
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`root` is joined with the request path, relative to the working directory unless absolute. A request path with a `.` or `..` segment, a
|
|
60
|
+
doubled slash, a backslash or (unless `allowPercentInPath`) an encoded `%` is treated as not found and passed on with `next()`. Only `GET`
|
|
61
|
+
and `HEAD` are served. Other options: `rewriteRequestPath`, `precompressed` (serve a `.br`, `.zst` or `.gz` sibling when the client
|
|
62
|
+
accepts it), `index` (default `index.html`), and `onFound` / `onNotFound` hooks. Serve build output, never source folders.
|
|
63
|
+
|
|
64
|
+
## Shutdown
|
|
65
|
+
|
|
66
|
+
Disposing the plugin (or the root context) ends open streams, closes every connection and returns once the port is free. Disposing a
|
|
67
|
+
plugin that only mounted routes is different: its mount and the requests it is serving end, and the server keeps serving the others (see
|
|
68
|
+
[Plugin lifecycle](./plugin-lifecycle.md#disposal-sequence)).
|
|
69
|
+
|
|
70
|
+
## Choosing a port
|
|
71
|
+
|
|
72
|
+
Let the process configuration choose the address. Do not hard-code a development port in a reusable plugin: a plugin mounts routes and
|
|
73
|
+
leaves the socket to whichever adapter the app runs with.
|
|
74
|
+
|
|
75
|
+
## WebSocket upgrades
|
|
76
|
+
|
|
77
|
+
A plugin takes WebSocket upgrades with `ctx.nodeServer.upgrades()` (or `ctx.routerHttp.upgrades()` on the Host's web server, with `ctx.routerHttp.mount(prefix, { upgrade: [paths] })` naming the exact paths). It returns the ported `upgradeWebSocket`; the route is an ordinary route with ordinary middleware in front of it:
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
export function apply(ctx: Context) {
|
|
81
|
+
const upgrade = ctx.nodeServer.upgrades()
|
|
82
|
+
ctx.router.route('/', new Acryl()
|
|
83
|
+
// Checks run before the upgrade: own page, loopback peer, exact Origin and Host. A refusal is a plain HTTP status with Connection: close, sent before any handshake.
|
|
84
|
+
.use('/terminal', ownPage)
|
|
85
|
+
.get('/terminal', upgrade(() => ({
|
|
86
|
+
onMessage(event, socket) {
|
|
87
|
+
if (socket.bufferedAmount < 1_000_000) socket.send(`echo ${String(event.data)}`)
|
|
88
|
+
},
|
|
89
|
+
onClose(event) {
|
|
90
|
+
// Called exactly once, whoever closed the socket.
|
|
91
|
+
},
|
|
92
|
+
}), { textOnly: true })))
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
- **Limits.** Text frames only with `{ textOnly: true }` (binary frames never reach `onMessage`); `websocket.maxPayload` (default 1 MiB, a bigger frame closes the socket with 1009); no per-message compression; `socket.bufferedAmount` for back-pressure; `socket.close(code, reason)` with application codes such as 1013 or 4404 (a code the protocol forbids on the wire becomes 1011). No raw socket is exposed.
|
|
97
|
+
- **Dead peers.** The server pings every `websocket.heartbeat` ms (default 30 000) and terminates a peer that did not answer the last ping. `websocket.grace` (default 2000) is how long a closing socket gets.
|
|
98
|
+
- **Ownership.** The sockets a plugin's routes accepted belong to that plugin. When it unloads they are closed with 1001 within the grace (what is left is terminated), its handler sees `close` once, other plugins' sockets are untouched, and `ctx.nodeServer.sockets` counts what is still open. Stopping the server closes every socket.
|
|
99
|
+
- **Needs `ws`.** `npm install ws`; an app that never upgrades does not need it.
|
|
100
|
+
- **Tests.** `testWebSocket((request, env) => app.fetch(request, env), '/terminal', { headers })` from `acrylblends/node-server` runs the route and its middleware in process: a refusal answers `{ status }`, an accepted connection gives a `socket` that sends text frames, collects what the handler sent (`received`) and closes.
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# Plugin lifecycle and disposal
|
|
2
|
+
|
|
3
|
+
Cordis gives every framework registration an owner and a lifetime. This is the main difference between using the application API on its
|
|
4
|
+
own and using it as part of ACRYL.
|
|
5
|
+
|
|
6
|
+
## Every registration has an owner
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
export const name = 'todo'
|
|
10
|
+
export const inject = ['router']
|
|
11
|
+
|
|
12
|
+
export function apply(ctx: Context): void {
|
|
13
|
+
ctx.router.route('/todo', createTodoApp())
|
|
14
|
+
}
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`route`, `onError` and `notFound` register themselves as effects of the plugin that called them, so there is nothing to wrap: when the
|
|
18
|
+
plugin's fiber unloads, its mount goes away, and a reload mounts it again without duplicates. `route` returns a function that removes the
|
|
19
|
+
mount sooner. Never register routes as a side effect of importing a module.
|
|
20
|
+
|
|
21
|
+
Resources an app uses (timers, watchers, connections, subprocesses) belong to one `ctx.effect()` of the plugin, whose disposer releases
|
|
22
|
+
them:
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
export function apply(ctx: Context): void {
|
|
26
|
+
const events = new EventEmitter()
|
|
27
|
+
ctx.effect(() => {
|
|
28
|
+
const timer = setInterval(() => events.emit('tick'), 1000)
|
|
29
|
+
return () => clearInterval(timer)
|
|
30
|
+
}, 'todo: ticker')
|
|
31
|
+
ctx.router.route('/todo', createTodoApp(events))
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Live composition
|
|
36
|
+
|
|
37
|
+
The router is built for a host whose plugin set changes while it runs. Mounts are added and removed, and each request after a change is
|
|
38
|
+
served by an app composed from the mounts that are live at that time; a request already running keeps the app it started with. The core's
|
|
39
|
+
route tables only grow, so the router rebuilds the composition instead of editing it. Application code does not manage this.
|
|
40
|
+
|
|
41
|
+
A mount is a snapshot of the app's routes at the `route` call. Build the app, then mount it.
|
|
42
|
+
|
|
43
|
+
## Missing providers
|
|
44
|
+
|
|
45
|
+
A plugin that injects `router` stays PENDING while no router exists. That is a normal Cordis state, not an error: when a router appears the
|
|
46
|
+
plugin activates and mounts. When the router is replaced, the plugin unloads and activates again against the new one, so it must not keep
|
|
47
|
+
the old service object anywhere else.
|
|
48
|
+
|
|
49
|
+
## Disposal sequence
|
|
50
|
+
|
|
51
|
+
When a plugin that owns a mount unloads:
|
|
52
|
+
|
|
53
|
+
1. The mount leaves the composition, so new requests no longer reach it.
|
|
54
|
+
2. The requests its code is still serving end: a request inside one of its handlers or middleware (before `next()` returned), and a
|
|
55
|
+
response body one of its handlers produced. Their signals abort (`c.req.raw.signal`) and their bodies are cancelled, which runs the
|
|
56
|
+
stream helpers' `onAbort`.
|
|
57
|
+
3. The unload waits for those requests, their bodies and their `c.executionCtx.waitUntil` work, bounded by the router's `disposeGraceMs`.
|
|
58
|
+
|
|
59
|
+
A request the plugin's middleware already passed on to another plugin's handler is not touched. When the router itself is disposed, the
|
|
60
|
+
same happens to every running request, and new requests are answered with 503.
|
|
61
|
+
|
|
62
|
+
Handlers get a chance to release their resources, nothing a plugin started outlives it, and disposal cannot hang forever.
|
|
63
|
+
|
|
64
|
+
## Services and the shadow context
|
|
65
|
+
|
|
66
|
+
A plugin reaches a service through its own view of it: `ctx.router` in one plugin and in another are two different objects over one
|
|
67
|
+
service. Two facts follow, each with a test as proof.
|
|
68
|
+
|
|
69
|
+
**Fields are shared.** Reading or assigning a service's field through any plugin's view reads or writes the one instance, so every caller
|
|
70
|
+
sees the same value (`plugins/router/tests/shadow-state.spec.ts`). Keeping changing state in one object, as the router does, is a
|
|
71
|
+
readability choice, not a requirement.
|
|
72
|
+
|
|
73
|
+
**`this.ctx` inside a method is the caller's view, not the service's own context.** It is what lets `route` tie a mount to the plugin
|
|
74
|
+
that called it. It is the wrong context for starting something that should belong to the service: a plugin started with
|
|
75
|
+
`this.ctx.plugin(...)` from a method resolves services as the service's own fiber and fails with "cannot get property router without
|
|
76
|
+
inject". Keep the context the constructor received and use that:
|
|
77
|
+
|
|
78
|
+
```ts
|
|
79
|
+
class Installer extends Service {
|
|
80
|
+
private readonly owner: Context
|
|
81
|
+
|
|
82
|
+
constructor(ctx: Context) {
|
|
83
|
+
super(ctx, 'installer')
|
|
84
|
+
this.owner = ctx // the service's own context
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async install(plugin: Plugin): Promise<void> {
|
|
88
|
+
await this.owner.plugin(plugin) // right: behaves like a plugin mounted at startup
|
|
89
|
+
// await this.ctx.plugin(plugin) // wrong: the caller's view, see above
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
The proof is `plugins/router/tests/live-install.spec.ts`, which runs both forms against a live router. This sits next to the general
|
|
95
|
+
rule: a plugin started with `this.ctx.plugin(...)` in `apply` is a child of the plugin and unloads with it.
|
|
96
|
+
|
|
97
|
+
## Module state
|
|
98
|
+
|
|
99
|
+
Do not hide mutable state in module globals. Cordis can reload a plugin and run several surfaces from one host, and a module global
|
|
100
|
+
outlives the plugin that wrote it.
|
|
101
|
+
|
|
102
|
+
## What to test
|
|
103
|
+
|
|
104
|
+
Test a route-owning plugin through real Cordis activation for:
|
|
105
|
+
|
|
106
|
+
- activation when the router is present, and PENDING until it appears;
|
|
107
|
+
- route removal after the plugin unloads, and a clean mount after reload, without duplicates over repeated cycles;
|
|
108
|
+
- router replacement without stale service references;
|
|
109
|
+
- disposal while a response is still open.
|
|
110
|
+
|
|
111
|
+
`app.request` tests prove handler behavior. Only activation tests prove ownership.
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# Surfaces and adapters
|
|
2
|
+
|
|
3
|
+
An ACRYL application is written once and reached through the surface that fits the user. Surfaces provide transport and presentation;
|
|
4
|
+
plugins provide capabilities.
|
|
5
|
+
|
|
6
|
+
## Surface model
|
|
7
|
+
|
|
8
|
+
| Surface | How requests arrive | Typical use |
|
|
9
|
+
| --- | --- | --- |
|
|
10
|
+
| Web | HTTP to the ACRYL Host's web server, through `@acryldev/router-http` | browser applications and APIs |
|
|
11
|
+
| Desktop | the same Host web server on a loopback port, opened in the Electron window | local-first applications |
|
|
12
|
+
| Terminal UI | in process: `ctx.router.request(...)` or `ctx.router.fetch(...)` | operator tools, agents, terminal workflows |
|
|
13
|
+
| Standalone process | HTTP through `@acryldev/node-server` | an app that runs without the Host |
|
|
14
|
+
| Tests | `ctx.router.request(...)` or `app.request(...)` | handler and contract tests |
|
|
15
|
+
|
|
16
|
+
The handler does not know which row supplied the request. When it needs a transport fact it reads the connection from the context
|
|
17
|
+
(`connectionOf(c)`), which is empty for an in-process call.
|
|
18
|
+
|
|
19
|
+
## Web
|
|
20
|
+
|
|
21
|
+
The Host owns the listening socket, the address and process shutdown. A plugin mounts its app on the router, then asks the adapter to
|
|
22
|
+
serve the prefix over HTTP:
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
ctx.router.route('/todo', app)
|
|
26
|
+
ctx.inject(['routerHttp'], inner => { inner.routerHttp.mount('/todo') })
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Only prefixes asked for this way are served over HTTP. A prefix the Host's web server already serves cannot be claimed: `mount` throws,
|
|
30
|
+
so a plugin cannot take over a Host route by mounting on it.
|
|
31
|
+
|
|
32
|
+
## Desktop
|
|
33
|
+
|
|
34
|
+
Desktop runs the same Host inside Electron, and its window talks to the Host's web server on a loopback port. A plugin's routes therefore
|
|
35
|
+
serve Desktop exactly as they serve Web, with no Desktop-specific code. Guard local control routes with `loopbackOnly` (see
|
|
36
|
+
[Middleware](../concepts/middleware.md#loopbackonly)).
|
|
37
|
+
|
|
38
|
+
A transport without a port, handing `ctx.router.fetch` to Electron's `protocol.handle`, needs no change to plugins and is a later task
|
|
39
|
+
(`specs/047-framework-port/plan.md` T014).
|
|
40
|
+
|
|
41
|
+
Desktop capabilities such as windows, files and native dialogs belong in declared Cordis services. A handler calls the service; it does not
|
|
42
|
+
import Electron.
|
|
43
|
+
|
|
44
|
+
## Terminal UI
|
|
45
|
+
|
|
46
|
+
A terminal surface needs no server. It calls the composed router in process:
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
const response = await ctx.router.request('/todo/todos')
|
|
50
|
+
const todos = await response.json()
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The `routerHttp` service does not exist there, so the plugin's `ctx.inject(['routerHttp'], ...)` simply never runs. Check the services a
|
|
54
|
+
host declares instead of assuming a network route exists.
|
|
55
|
+
|
|
56
|
+
## What belongs where
|
|
57
|
+
|
|
58
|
+
| Concern | Owner |
|
|
59
|
+
| --- | --- |
|
|
60
|
+
| Route handlers and middleware | the feature plugin's `Acryl` |
|
|
61
|
+
| Mount path and lifetime | the feature plugin, through `ctx.router.route` |
|
|
62
|
+
| Socket and port | the Host (`@acryldev/router-http`) or `@acryldev/node-server` |
|
|
63
|
+
| Terminal rendering and input | the terminal surface |
|
|
64
|
+
| Shared domain behavior | a domain service every surface uses |
|
|
65
|
+
| Shared reactive state | `@acryldev/state` or an application service |
|
|
66
|
+
|
|
67
|
+
## Loopback-only routes
|
|
68
|
+
|
|
69
|
+
Some routes exist only for the local host, such as callbacks and control endpoints. Guard them with `loopbackOnly` at the framework
|
|
70
|
+
boundary; do not rely on an obscure path or a missing link as access control. Loopback restriction is separate from authentication: a
|
|
71
|
+
local route that does privileged work still needs the host's authorization policy.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# Transport facts and cancellation
|
|
2
|
+
|
|
3
|
+
`c.env` carries what the caller of the router supplied for this request. Under the router that is `{ connection }`: the socket's peer
|
|
4
|
+
address and the real local port, filled by the HTTP adapter and empty for an in-process call. Transport facts never travel in headers.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
import { Acryl } from '@acryldev/blends'
|
|
8
|
+
import { connectionOf, type RouterEnv } from '@acryldev/blends/conninfo'
|
|
9
|
+
import { getConnInfo } from '@acryldev/blends/conninfo'
|
|
10
|
+
|
|
11
|
+
const app = new Acryl<RouterEnv>() // types c.env.connection
|
|
12
|
+
app.get('/peer', c => c.json({
|
|
13
|
+
connection: connectionOf(c), // { remoteAddress?, localPort? }
|
|
14
|
+
info: getConnInfo(c), // the same peer in the core's conninfo shape, for middleware such as ipRestriction
|
|
15
|
+
}))
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The same handler then runs over HTTP, in process or in a test, and reads an empty connection where there is no socket. Guards such as
|
|
19
|
+
`loopbackOnly` refuse an empty one unless told otherwise.
|
|
20
|
+
|
|
21
|
+
## Cancellation and background work
|
|
22
|
+
|
|
23
|
+
- `c.req.raw.signal` aborts when the caller goes away, when the plugin whose code is serving the request unloads, and when the router is
|
|
24
|
+
disposed. Long work
|
|
25
|
+
should pass it on (`fetch(url, { signal: c.req.raw.signal })`) or check it.
|
|
26
|
+
- `c.executionCtx.waitUntil(promise)` keeps the request in flight until the promise settles, for work that continues after the response
|
|
27
|
+
is returned.
|
|
28
|
+
|
|
29
|
+
Both belong to the current request, and both end with their owner: see [Plugin lifecycle](./plugin-lifecycle.md#disposal-sequence).
|
|
30
|
+
|
|
31
|
+
## Errors and control flow
|
|
32
|
+
|
|
33
|
+
Return a response for expected failures, or throw an `HTTPException`, which becomes its own response:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { HTTPException } from '@acryldev/blends/http-exception'
|
|
37
|
+
|
|
38
|
+
if (!todo) return c.json({ error: 'todo_not_found' }, 404)
|
|
39
|
+
if (!allowed) throw new HTTPException(403, { message: 'not yours' })
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Anything else that is thrown goes to the app's `onError`, or to the router's when the app has none. A middleware's `await next()` never
|
|
43
|
+
throws: the error has already become a response by then, and the error itself is in `c.error`:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
app.use(async (c, next) => {
|
|
47
|
+
await next()
|
|
48
|
+
if (c.error) report(c.error)
|
|
49
|
+
})
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
## Context rules
|
|
53
|
+
|
|
54
|
+
- Treat the context as request-local.
|
|
55
|
+
- Do not retain it after the handler returns.
|
|
56
|
+
- Do not put sockets, server objects or Cordis internals into context values for other plugins to discover accidentally.
|
|
57
|
+
- Put cross-plugin capabilities in a declared Cordis service, not in `c.set`.
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# Validation
|
|
2
|
+
|
|
3
|
+
Validate untrusted input at the route boundary. `schemaValidator` takes any [Standard Schema](https://standardschema.dev): Schemastery
|
|
4
|
+
(the schema library Cordis already uses for plugin config), Zod and Valibot all implement it, so a route needs no extra dependency.
|
|
5
|
+
|
|
6
|
+
## Validate JSON
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import z from '@deepseek-ai/schemastery'
|
|
10
|
+
import { Acryl } from '@acryldev/blends'
|
|
11
|
+
import { schemaValidator } from '@acryldev/blends/schema-validator'
|
|
12
|
+
|
|
13
|
+
const NewTodo = z.object({
|
|
14
|
+
title: z.string().required(),
|
|
15
|
+
done: z.boolean().default(false),
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
const app = new Acryl().post('/todos', schemaValidator('json', NewTodo), c => {
|
|
19
|
+
const todo = c.req.valid('json') // typed by the schema's output
|
|
20
|
+
return c.json({ todo }, 201)
|
|
21
|
+
})
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
A validated route has three parts: a schema for one input target, the validator middleware for that target, and a handler that reads
|
|
25
|
+
`c.req.valid(target)` instead of the raw body.
|
|
26
|
+
|
|
27
|
+
## Failures
|
|
28
|
+
|
|
29
|
+
When the schema reports issues the handler does not run and the answer is 400 with `Content-Type: application/json` and exactly this
|
|
30
|
+
shape:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
{ error: `invalid ${target}`, issues: Array<{ message: string, path: string }> }
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```json
|
|
37
|
+
{ "error": "invalid json", "issues": [{ "message": "title must be 1 to 200 characters", "path": "title" }] }
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
- `error` names the target: `invalid json`, `invalid query`, `invalid param`, ...
|
|
41
|
+
- There is one entry per issue the schema reported, in its order, with the schema's own `message`.
|
|
42
|
+
- `path` is the issue's path joined with dots: `["items", 0, "title"]` becomes `"items.0.title"`, and a path segment given as
|
|
43
|
+
`{ key }` (as Standard Schema allows) contributes its `key`.
|
|
44
|
+
- An issue without a path, which a hand-written Standard Schema often reports for a whole-value check, gets `"path": ""`.
|
|
45
|
+
`{ issues: [{ message: 'not allowed' }] }` answers `{ "error": "invalid json", "issues": [{ "message": "not allowed", "path": "" }] }`.
|
|
46
|
+
Give issues a path when a client should point at a field.
|
|
47
|
+
|
|
48
|
+
### A JSON body without a JSON content type
|
|
49
|
+
|
|
50
|
+
A `json` target reads the body only when the request's `Content-Type` is JSON (`application/json`, with or without parameters such as
|
|
51
|
+
`; charset=utf-8`, or `application/*+json`). Any other content type, or none, is not an error by itself: the schema sees `{}`. So a
|
|
52
|
+
client that forgets the header gets a misleading field error for a field it did send:
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
curl -X POST -d '{"title":"milk"}' http://127.0.0.1:<port>/todo/api # no content type: curl sends a form type
|
|
56
|
+
# 400 {"error":"invalid json","issues":[{"message":"title must be 1 to 200 characters","path":"title"}]}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
If you see a field error for a field the request clearly carries, check the request's `Content-Type` first. A route that wants to say so
|
|
60
|
+
explicitly can refuse other content types before the validator:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
import type { MiddlewareHandler } from '@acryldev/blends'
|
|
64
|
+
|
|
65
|
+
const jsonOnly: MiddlewareHandler = async (c, next) => {
|
|
66
|
+
// The same types the json target reads: application/json and application/*+json, parameters allowed.
|
|
67
|
+
const type = c.req.header('content-type')?.split(';', 1)[0]?.trim() ?? ''
|
|
68
|
+
if (!/^application\/([a-z.-]+\+)?json$/i.test(type)) return c.json({ error: 'content type must be JSON' }, 415)
|
|
69
|
+
await next()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
app.post('/todos', jsonOnly, schemaValidator('json', NewTodo), createTodo)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### A body that is not JSON
|
|
76
|
+
|
|
77
|
+
A JSON content type with a body that does not parse fails before the schema runs: the answer is 400 with the text body
|
|
78
|
+
`Malformed JSON in request body` (a thrown `HTTPException`, so an `onError` handler can reshape it). The `form` target does the same for
|
|
79
|
+
a form body that does not parse, with the text `Malformed FormData request.`
|
|
80
|
+
|
|
81
|
+
Keep the public failure shape consistent across the application and do not leak internals in messages. An application that needs a
|
|
82
|
+
different body writes its own check with the core `validator` (below). Valid input is not proof that the caller may use it:
|
|
83
|
+
authentication and authorization stay separate checks.
|
|
84
|
+
|
|
85
|
+
## Targets
|
|
86
|
+
|
|
87
|
+
| Target | Read from |
|
|
88
|
+
| --- | --- |
|
|
89
|
+
| `json` | the JSON body |
|
|
90
|
+
| `form` | a `multipart/form-data` or `application/x-www-form-urlencoded` body |
|
|
91
|
+
| `query` | the query string |
|
|
92
|
+
| `param` | route parameters |
|
|
93
|
+
| `header` | request headers (names in lowercase) |
|
|
94
|
+
| `cookie` | cookies |
|
|
95
|
+
|
|
96
|
+
Validate only the targets the route uses, and chain one validator per target:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
app.get('/todos/:id', schemaValidator('param', z.object({ id: z.natural() })), schemaValidator('query', Paging), handler)
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## The core validator
|
|
103
|
+
|
|
104
|
+
`validator` (from `acrylblends/validator`) takes a function instead of a schema. Return the value the handler should see, or a
|
|
105
|
+
response to refuse:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
import { validator } from '@acryldev/blends/validator'
|
|
109
|
+
|
|
110
|
+
app.post('/posts', validator('form', (value, c) => {
|
|
111
|
+
const body = value['body']
|
|
112
|
+
if (typeof body !== 'string') return c.text('Invalid!', 400)
|
|
113
|
+
return { body }
|
|
114
|
+
}), c => c.json({ body: c.req.valid('form').body }, 201))
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
## Limit the body first
|
|
118
|
+
|
|
119
|
+
Validation reads the whole body. Put `bodyLimit` in front of a validator on any route open to untrusted callers:
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
import { bodyLimit } from '@acryldev/blends/body-limit'
|
|
123
|
+
|
|
124
|
+
app.post('/todos', bodyLimit({ maxSize: 16 * 1024 }), schemaValidator('json', NewTodo), createTodo)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Typed clients
|
|
128
|
+
|
|
129
|
+
The validated input types flow into the route types, so the typed `testClient` and `acrylblends/client` check the request a caller sends.
|
|
130
|
+
See [Helpers](../guides/helpers.md#testing).
|
|
131
|
+
|
|
132
|
+
## What not to validate twice
|
|
133
|
+
|
|
134
|
+
Validate shape at the HTTP boundary, then enforce domain rules in the domain service. The route checks that `title` is a string; the
|
|
135
|
+
todo service decides whether that title is allowed.
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
# Getting Started
|
|
2
|
+
|
|
3
|
+
Using Acryl is easy. You set up the project, write code, develop with a local server, and run it. The same application code runs on Node.js, the verified runtime, and on Bun,
|
|
4
|
+
which is experimental; only the entry point differs. This page shows the basic usage.
|
|
5
|
+
|
|
6
|
+
## Starter
|
|
7
|
+
|
|
8
|
+
A starter is a Cordis app that arrives already wired: `blend.yaml`, its plugins in `plugins/`, and a test. Use the "create-acrylblends" command.
|
|
9
|
+
|
|
10
|
+
**npm**
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm create @acryldev/blends@latest my-app
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
**yarn**
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
yarn create acrylblends my-app
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
**pnpm**
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
pnpm create @acryldev/blends@latest my-app
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
**bun**
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
bun create acrylblends@latest my-app
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
You are asked which template you want:
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
Templates:
|
|
38
|
+
blank the router, a server and one route: the smallest app
|
|
39
|
+
nodejs a web app with a page and a client component
|
|
40
|
+
notes a multi-user notes app on the db port (sign-up, log-in, sessions)
|
|
41
|
+
chat a chat app that streams an answer over server-sent events
|
|
42
|
+
todo a to-do list on the router and state
|
|
43
|
+
agent the blank app with an offline agent that builds plugins into the running app
|
|
44
|
+
Which template do you want to use? [nodejs]:
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Every template is a Cordis app: `blend.yaml` lists its plugins and every plugin is a folder in `plugins/`. `blank` is the smallest app, `nodejs` is a web app with a page and a client component, `notes` and `chat` add a database, `todo` is a to-do list, and `agent` adds an agent that can extend the app while it
|
|
48
|
+
runs (see [Acryl in a Cordis app](../cordis/acryl-in-a-cordis-app.md)). Pass `--template` to skip the question, see [create-acrylblends](../guides/create-acrylblends.md).
|
|
49
|
+
|
|
50
|
+
The template is created in `my-app`: go to it, install the dependencies and start the local server.
|
|
51
|
+
|
|
52
|
+
```sh
|
|
53
|
+
cd my-app
|
|
54
|
+
npm install
|
|
55
|
+
npm run dev
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Hello World
|
|
59
|
+
|
|
60
|
+
In a generated app the routes live in `src/routes.ts`, which builds an `Acryl` app and mounts it with `ctx.router.route`; `src/main.ts` picks where the app lives and starts it. The app on its own is plain:
|
|
61
|
+
|
|
62
|
+
The `import` and the final `export default` are the same on Node.js and on Bun; what differs is how the runtime starts the app (see [Node.js](nodejs.md) and [Bun](bun.md)).
|
|
63
|
+
|
|
64
|
+
```ts twoslash
|
|
65
|
+
import { Acryl } from '@acryldev/blends'
|
|
66
|
+
|
|
67
|
+
const app = new Acryl()
|
|
68
|
+
|
|
69
|
+
app.get('/', (c) => {
|
|
70
|
+
return c.text('Acryl!')
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
export default app
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Start the development server and open the address it prints.
|
|
77
|
+
|
|
78
|
+
## Return JSON
|
|
79
|
+
|
|
80
|
+
Returning JSON is also easy. The following handles a GET request to `/api/hello` and returns an `application/json` response.
|
|
81
|
+
|
|
82
|
+
```ts twoslash
|
|
83
|
+
import { Acryl } from '@acryldev/blends'
|
|
84
|
+
|
|
85
|
+
const app = new Acryl()
|
|
86
|
+
|
|
87
|
+
app.get('/api/hello', (c) => {
|
|
88
|
+
return c.json({
|
|
89
|
+
ok: true,
|
|
90
|
+
message: 'Acryl!',
|
|
91
|
+
})
|
|
92
|
+
})
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Request and Response
|
|
96
|
+
|
|
97
|
+
Getting a path parameter, a URL query value, and adding a response header is written as follows.
|
|
98
|
+
|
|
99
|
+
```ts twoslash
|
|
100
|
+
import { Acryl } from '@acryldev/blends'
|
|
101
|
+
|
|
102
|
+
const app = new Acryl()
|
|
103
|
+
|
|
104
|
+
app.get('/posts/:id', (c) => {
|
|
105
|
+
const page = c.req.query('page')
|
|
106
|
+
const id = c.req.param('id')
|
|
107
|
+
c.header('X-Message', 'Hi!')
|
|
108
|
+
return c.text(`You want to see ${page} of ${id}`)
|
|
109
|
+
})
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
POST, PUT and DELETE are handled the same way as GET.
|
|
113
|
+
|
|
114
|
+
```ts twoslash
|
|
115
|
+
import { Acryl } from '@acryldev/blends'
|
|
116
|
+
|
|
117
|
+
const app = new Acryl()
|
|
118
|
+
|
|
119
|
+
app.post('/posts', (c) => c.text('Created!', 201))
|
|
120
|
+
app.delete('/posts/:id', (c) => c.text(`${c.req.param('id')} is deleted!`))
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
## Return HTML
|
|
124
|
+
|
|
125
|
+
Write HTML with [the html helper](../helpers/html.md):
|
|
126
|
+
|
|
127
|
+
```ts twoslash
|
|
128
|
+
import { Acryl } from '@acryldev/blends'
|
|
129
|
+
import { html } from '@acryldev/blends/html'
|
|
130
|
+
|
|
131
|
+
const app = new Acryl()
|
|
132
|
+
|
|
133
|
+
app.get('/', (c) => {
|
|
134
|
+
const name = 'Acryl'
|
|
135
|
+
return c.html(html`<!doctype html><h1>Hello ${name}!</h1>`)
|
|
136
|
+
})
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
JSX works too: `acrylblends/jsx` renders on the server and in the browser, and the `nodejs` template ships a `.tsx` page. See [JSX](../guides/jsx.md).
|
|
140
|
+
|
|
141
|
+
## Return raw Response
|
|
142
|
+
|
|
143
|
+
You can also return a raw Web Standard `Response`.
|
|
144
|
+
|
|
145
|
+
```ts twoslash
|
|
146
|
+
import { Acryl } from '@acryldev/blends'
|
|
147
|
+
|
|
148
|
+
const app = new Acryl()
|
|
149
|
+
|
|
150
|
+
app.get('/', () => {
|
|
151
|
+
return new Response('Good morning!')
|
|
152
|
+
})
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Using Middleware
|
|
156
|
+
|
|
157
|
+
Middleware can do the hard work for you. For example, add Basic Authentication.
|
|
158
|
+
|
|
159
|
+
```ts twoslash
|
|
160
|
+
import { Acryl } from '@acryldev/blends'
|
|
161
|
+
import { basicAuth } from '@acryldev/blends/basic-auth'
|
|
162
|
+
|
|
163
|
+
const app = new Acryl()
|
|
164
|
+
|
|
165
|
+
app.use(
|
|
166
|
+
'/admin/*',
|
|
167
|
+
basicAuth({
|
|
168
|
+
username: 'admin',
|
|
169
|
+
password: process.env.ADMIN_PASSWORD!,
|
|
170
|
+
})
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
app.get('/admin', (c) => {
|
|
174
|
+
return c.text('You are authorized!')
|
|
175
|
+
})
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
There are useful middleware included, such as Bearer and JWT authentication, CORS and ETag. See [Built-in middleware](../middleware/builtin/basic-auth.md).
|
|
179
|
+
|
|
180
|
+
## Testing
|
|
181
|
+
|
|
182
|
+
An app is a function from `Request` to `Response`, so a test needs no server:
|
|
183
|
+
|
|
184
|
+
```ts twoslash
|
|
185
|
+
import { Acryl } from '@acryldev/blends'
|
|
186
|
+
|
|
187
|
+
const app = new Acryl()
|
|
188
|
+
app.get('/', (c) => c.text('Acryl!'))
|
|
189
|
+
|
|
190
|
+
const response = await app.request('/')
|
|
191
|
+
console.log(response.status, await response.text())
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
See [Testing](../guides/testing.md).
|
|
195
|
+
|
|
196
|
+
## Next
|
|
197
|
+
|
|
198
|
+
- [Node.js](nodejs.md) and [Bun](bun.md) (experimental)
|
|
199
|
+
- [Desktop](desktop.md): the same app in an Electron window
|
|
200
|
+
- [Routing](../api/routing.md), [Context](../api/context.md) and [Request](../api/request.md)
|
|
201
|
+
- [Validation](../guides/validation.md)
|