@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,224 @@
|
|
|
1
|
+
# Streaming Helper
|
|
2
|
+
|
|
3
|
+
The Streaming Helper provides methods for streaming responses.
|
|
4
|
+
|
|
5
|
+
## Import
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { Acryl } from '@acryldev/blends'
|
|
9
|
+
import { stream, streamText, streamSSE } from '@acryldev/blends/streaming'
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## `stream()`
|
|
13
|
+
|
|
14
|
+
It returns a simple streaming response as `Response` object.
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
app.get('/stream', (c) => {
|
|
18
|
+
return stream(c, async (stream) => {
|
|
19
|
+
// Write a process to be executed when aborted.
|
|
20
|
+
stream.onAbort(() => {
|
|
21
|
+
console.log('Aborted!')
|
|
22
|
+
})
|
|
23
|
+
// Write a Uint8Array.
|
|
24
|
+
await stream.write(new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]))
|
|
25
|
+
// Pipe a readable stream.
|
|
26
|
+
await stream.pipe(anotherReadableStream)
|
|
27
|
+
})
|
|
28
|
+
})
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## `streamText()`
|
|
32
|
+
|
|
33
|
+
It returns a streaming response with `Content-Type: text/plain`, `Transfer-Encoding: chunked`, and `X-Content-Type-Options: nosniff` headers.
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
app.get('/streamText', (c) => {
|
|
37
|
+
return streamText(c, async (stream) => {
|
|
38
|
+
// Write a text with a new line ('\n').
|
|
39
|
+
await stream.writeln('Hello')
|
|
40
|
+
// Wait 1 second.
|
|
41
|
+
await stream.sleep(1000)
|
|
42
|
+
// Write a text without a new line.
|
|
43
|
+
await stream.write(`Acryl!`)
|
|
44
|
+
})
|
|
45
|
+
})
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
**Warning.**
|
|
49
|
+
|
|
50
|
+
A proxy or a host that compresses the response body can hold a stream back until it ends. If a stream arrives only when it is complete, send `Content-Encoding: Identity` for that route.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
app.get('/streamText', (c) => {
|
|
54
|
+
c.header('Content-Encoding', 'Identity')
|
|
55
|
+
return streamText(c, async (stream) => {
|
|
56
|
+
// ...
|
|
57
|
+
})
|
|
58
|
+
})
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## `streamSSE()`
|
|
62
|
+
|
|
63
|
+
It allows you to stream Server-Sent Events (SSE) seamlessly.
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
const app = new Acryl()
|
|
67
|
+
let id = 0
|
|
68
|
+
|
|
69
|
+
app.get('/sse', async (c) => {
|
|
70
|
+
return streamSSE(c, async (stream) => {
|
|
71
|
+
while (!stream.aborted) {
|
|
72
|
+
const message = `It is ${new Date().toISOString()}`
|
|
73
|
+
await stream.writeSSE({
|
|
74
|
+
data: message,
|
|
75
|
+
event: 'time-update',
|
|
76
|
+
id: String(id++),
|
|
77
|
+
})
|
|
78
|
+
await stream.sleep(1000)
|
|
79
|
+
}
|
|
80
|
+
})
|
|
81
|
+
})
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Cancelling work when the client leaves
|
|
85
|
+
|
|
86
|
+
A reader that closes the tab, loses the network or presses a Stop button should not leave your server working for nobody (a request to a paid model, a database scan). There are two signals, and they are not the same:
|
|
87
|
+
|
|
88
|
+
- **`c.req.raw.signal`** is the request's `AbortSignal`. It aborts when the client goes away. Pass it to anything that takes a `signal`, such as `fetch`, and the work stops with the client. This is the one to use for cancelling work.
|
|
89
|
+
- **`stream.onAbort(callback)`** and **`stream.aborted`** belong to the response stream. They report that the *reader of the response* was cancelled, and they are set when the response body is cancelled, which is what the Node adapter does when the connection closes. Over a real connection, a browser that aborts its `fetch` (or closes the tab) fires both: the request signal and `stream.onAbort`. Under `app.request()` (in-process, no socket) they come apart, and this is how the upstream behaves too: aborting the `signal` you passed to `app.request()` fires `c.req.raw.signal` while `stream.aborted` stays `false`, and cancelling the reader of the response body fires `stream.onAbort` while `c.req.raw.signal` does not. A test that simulates the client leaving therefore aborts the request signal (for work cancelled through the signal) or cancels the body reader (for `stream.onAbort`), whichever the handler listens to. Use `c.req.raw.signal` for the work, and `stream.onAbort` for cleanup of the stream itself.
|
|
90
|
+
|
|
91
|
+
An abort event that has already fired does not fire again, so check `signal.aborted` before you wait for it:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
const waitForAbort = (signal: AbortSignal) =>
|
|
95
|
+
signal.aborted
|
|
96
|
+
? Promise.resolve()
|
|
97
|
+
: new Promise<void>((resolve) => signal.addEventListener('abort', () => resolve(), { once: true }))
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
Keep what you have when the client leaves by saving it in a `finally` block: the stream callback runs to the end whether or not the client is still there.
|
|
101
|
+
|
|
102
|
+
## Streaming an answer from a model
|
|
103
|
+
|
|
104
|
+
A chat answer that arrives token by token is a `streamSSE` response that reads a streaming upstream. This server route calls an OpenAI-compatible chat completions API (`stream: true`), forwards each piece as an event, and cancels the upstream request when the client leaves. The key comes from the environment and is never written anywhere.
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { Acryl } from '@acryldev/blends'
|
|
108
|
+
import { streamSSE } from '@acryldev/blends/streaming'
|
|
109
|
+
|
|
110
|
+
/** The pieces of an OpenAI-compatible streaming answer: each `data:` line holds a JSON chunk, and `[DONE]` ends it. */
|
|
111
|
+
async function* modelPieces(messages: { role: string; content: string }[], signal: AbortSignal): AsyncGenerator<string> {
|
|
112
|
+
const key = process.env.DEEPSEEK_API_KEY
|
|
113
|
+
if (!key) throw new Error('DEEPSEEK_API_KEY is not set')
|
|
114
|
+
const base = process.env.DEEPSEEK_BASE_URL ?? 'https://api.deepseek.com'
|
|
115
|
+
const response = await fetch(`${base}/chat/completions`, {
|
|
116
|
+
method: 'POST',
|
|
117
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
|
|
118
|
+
body: JSON.stringify({ model: process.env.DEEPSEEK_MODEL ?? 'deepseek-chat', messages, stream: true }),
|
|
119
|
+
signal,
|
|
120
|
+
})
|
|
121
|
+
if (!response.ok || !response.body) throw new Error(`the model service answered ${response.status}`)
|
|
122
|
+
const decoder = new TextDecoder()
|
|
123
|
+
let buffer = ''
|
|
124
|
+
for await (const chunk of response.body) {
|
|
125
|
+
buffer += decoder.decode(chunk, { stream: true })
|
|
126
|
+
const lines = buffer.split('\n')
|
|
127
|
+
buffer = lines.pop() ?? ''
|
|
128
|
+
for (const line of lines) {
|
|
129
|
+
if (!line.startsWith('data:')) continue
|
|
130
|
+
const data = line.slice(5).trim()
|
|
131
|
+
if (data === '[DONE]') return
|
|
132
|
+
const piece = (JSON.parse(data) as { choices?: { delta?: { content?: string } }[] }).choices?.[0]?.delta?.content
|
|
133
|
+
if (piece) yield piece
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const app = new Acryl()
|
|
139
|
+
|
|
140
|
+
app.post('/api/chat', async (c) => {
|
|
141
|
+
const { message } = await c.req.json<{ message: string }>()
|
|
142
|
+
const signal = c.req.raw.signal // aborts when the client goes away
|
|
143
|
+
return streamSSE(c, async (stream) => {
|
|
144
|
+
let answer = ''
|
|
145
|
+
try {
|
|
146
|
+
for await (const piece of modelPieces([{ role: 'user', content: message }], signal)) {
|
|
147
|
+
answer += piece
|
|
148
|
+
// JSON-encode the piece: a piece may contain a newline, which would end an SSE `data:` line.
|
|
149
|
+
await stream.writeSSE({ event: 'token', data: JSON.stringify(piece) })
|
|
150
|
+
}
|
|
151
|
+
await stream.writeSSE({ event: 'done', data: '{}' })
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (!signal.aborted) await stream.writeSSE({ event: 'error', data: JSON.stringify('The model could not answer.') })
|
|
154
|
+
} finally {
|
|
155
|
+
console.log(`kept ${answer.length} characters`) // save what arrived, also when the client pressed Stop
|
|
156
|
+
}
|
|
157
|
+
})
|
|
158
|
+
})
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
## Reading a POST event stream in the browser
|
|
162
|
+
|
|
163
|
+
`EventSource` can only send a GET request. For a POST (a chat message), call `fetch` and read the events with `readSSE` from `acrylblends/read-sse`. It is an async iterator over the events of a `text/event-stream` response, parsed by the rules of the SSE standard (LF, CRLF and CR line ends, several `data` lines joined with a line feed, comments, UTF-8 split across chunks):
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
import { readSSE } from '@acryldev/blends/read-sse'
|
|
167
|
+
|
|
168
|
+
const controller = new AbortController() // controller.abort() is the Stop button
|
|
169
|
+
const response = await fetch('/api/chat', {
|
|
170
|
+
method: 'POST',
|
|
171
|
+
headers: { 'content-type': 'application/json' },
|
|
172
|
+
body: JSON.stringify({ message: 'Hello' }),
|
|
173
|
+
signal: controller.signal,
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
let answer = ''
|
|
177
|
+
for await (const { event, data } of readSSE(response)) {
|
|
178
|
+
if (event === 'token') answer += JSON.parse(data) as string
|
|
179
|
+
}
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
- Each event is `{ event, data, id?, retry? }`; `event` is `message` when the server named none, and `data` is a string (parse it yourself when the server sends JSON).
|
|
183
|
+
- Leaving the loop early (a `break`, a thrown error) cancels the response body, so the request to the server ends. Abort the `fetch` with its own `signal` for a Stop button; `readSSE(response, { signal })` also stops reading when a signal aborts.
|
|
184
|
+
- A response that is not `ok` throws with its status (the body is not parsed as events), and a response without a body throws.
|
|
185
|
+
- A client module served by `clientModules` can import it as it is (`import { readSSE } from '@acryldev/blends/read-sse'`): the import is pointed at a browser file the same app serves, like `acrylblends/client`. With a bundler it is an ordinary import.
|
|
186
|
+
|
|
187
|
+
A complete chat component is in the `chat` template of `create-acrylblends` (`npm create @acryldev/blends@latest my-chat -- --template chat`).
|
|
188
|
+
|
|
189
|
+
## Error Handling
|
|
190
|
+
|
|
191
|
+
The third argument of the streaming helper is an error handler.
|
|
192
|
+
This argument is optional, if you don't specify it, the error will be output as a console error.
|
|
193
|
+
|
|
194
|
+
```ts
|
|
195
|
+
app.get('/stream', (c) => {
|
|
196
|
+
return stream(
|
|
197
|
+
c,
|
|
198
|
+
async (stream) => {
|
|
199
|
+
// Write a process to be executed when aborted.
|
|
200
|
+
stream.onAbort(() => {
|
|
201
|
+
console.log('Aborted!')
|
|
202
|
+
})
|
|
203
|
+
// Write a Uint8Array.
|
|
204
|
+
await stream.write(
|
|
205
|
+
new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f])
|
|
206
|
+
)
|
|
207
|
+
// Pipe a readable stream.
|
|
208
|
+
await stream.pipe(anotherReadableStream)
|
|
209
|
+
},
|
|
210
|
+
(err, stream) => {
|
|
211
|
+
stream.writeln('An error occurred!')
|
|
212
|
+
console.error(err)
|
|
213
|
+
}
|
|
214
|
+
)
|
|
215
|
+
})
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
The stream will be automatically closed after the callbacks are executed.
|
|
219
|
+
|
|
220
|
+
> **Warning.**
|
|
221
|
+
> If the callback function of the streaming helper throws an error, the `onError` event of Acryl will not be triggered.
|
|
222
|
+
>
|
|
223
|
+
> `onError` is a hook to handle errors before the response is sent and overwrite the response. However, when the callback function is executed, the stream has already started, so it cannot be overwritten.
|
|
224
|
+
>
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# Testing Helper
|
|
2
|
+
|
|
3
|
+
The Testing Helper provides functions to make testing of Acryl applications easier.
|
|
4
|
+
|
|
5
|
+
## Import
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { Acryl } from '@acryldev/blends'
|
|
9
|
+
import { testClient } from '@acryldev/blends/testing'
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## `testClient()`
|
|
13
|
+
|
|
14
|
+
The `testClient()` function takes an instance of Acryl as its first argument and returns an object typed according to your Acryl application's routes, similar to the [Acryl Client](../guides/rpc.md#client). This allows you to call your defined routes in a type-safe manner with editor autocompletion within your tests.
|
|
15
|
+
|
|
16
|
+
**Important Note on Type Inference:**
|
|
17
|
+
|
|
18
|
+
For the `testClient` to correctly infer the types of your routes and provide autocompletion, **you must define your routes using chained methods directly on the `Acryl` instance**.
|
|
19
|
+
|
|
20
|
+
The type inference relies on the type flowing through the chained `.get()`, `.post()`, etc., calls. If you define routes separately after creating the Acryl instance (like the common pattern shown in the "Hello World" example: `const app = new Acryl(); app.get(...)`), the `testClient` will not have the necessary type information for specific routes, and you won't get the type-safe client features.
|
|
21
|
+
|
|
22
|
+
**Example:**
|
|
23
|
+
|
|
24
|
+
This example works because the `.get()` method is chained directly onto the `new Acryl()` call:
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
// index.ts
|
|
28
|
+
const app = new Acryl().get('/search', (c) => {
|
|
29
|
+
const query = c.req.query('q')
|
|
30
|
+
return c.json({ query: query, results: ['result1', 'result2'] })
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
export default app
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
// index.test.ts
|
|
38
|
+
import { Acryl } from '@acryldev/blends'
|
|
39
|
+
import { testClient } from '@acryldev/blends/testing'
|
|
40
|
+
import { describe, it, expect } from 'vitest' // Or your preferred test runner
|
|
41
|
+
import app from './app'
|
|
42
|
+
|
|
43
|
+
describe('Search Endpoint', () => {
|
|
44
|
+
// Create the test client from the app instance
|
|
45
|
+
const client = testClient(app)
|
|
46
|
+
|
|
47
|
+
it('should return search results', async () => {
|
|
48
|
+
// Call the endpoint using the typed client
|
|
49
|
+
// Notice the type safety for query parameters (if defined in the route)
|
|
50
|
+
// and the direct access via .$get()
|
|
51
|
+
const res = await client.search.$get({
|
|
52
|
+
query: { q: 'acrylblends' },
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
// Assertions
|
|
56
|
+
expect(res.status).toBe(200)
|
|
57
|
+
expect(await res.json()).toEqual({
|
|
58
|
+
query: 'acrylblends',
|
|
59
|
+
results: ['result1', 'result2'],
|
|
60
|
+
})
|
|
61
|
+
})
|
|
62
|
+
})
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
To include headers in your test, pass them as the second parameter in the call. The second parameter can also take an `init` property as a `RequestInit` object, allowing you to set headers, method, body, etc. Learn more about the `init` property [here](../guides/rpc.md#init-option).
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
// index.test.ts
|
|
69
|
+
import { Acryl } from '@acryldev/blends'
|
|
70
|
+
import { testClient } from '@acryldev/blends/testing'
|
|
71
|
+
import { describe, it, expect } from 'vitest' // Or your preferred test runner
|
|
72
|
+
import app from './app'
|
|
73
|
+
|
|
74
|
+
describe('Search Endpoint', () => {
|
|
75
|
+
// Create the test client from the app instance
|
|
76
|
+
const client = testClient(app)
|
|
77
|
+
|
|
78
|
+
it('should return search results', async () => {
|
|
79
|
+
// Include the token in the headers and set the content type
|
|
80
|
+
const token = process.env.API_TOKEN!
|
|
81
|
+
const res = await client.search.$get(
|
|
82
|
+
{
|
|
83
|
+
query: { q: 'acrylblends' },
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
headers: {
|
|
87
|
+
Authorization: `Bearer ${token}`,
|
|
88
|
+
'Content-Type': `application/json`,
|
|
89
|
+
},
|
|
90
|
+
}
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
// Assertions
|
|
94
|
+
expect(res.status).toBe(200)
|
|
95
|
+
expect(await res.json()).toEqual({
|
|
96
|
+
query: 'acrylblends',
|
|
97
|
+
results: ['result1', 'result2'],
|
|
98
|
+
})
|
|
99
|
+
})
|
|
100
|
+
})
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### Default request options
|
|
104
|
+
|
|
105
|
+
`testClient(app, env?, executionCtx?, options?)` takes the client's request options as its fourth argument, so headers every request of a test
|
|
106
|
+
needs, such as a session cookie, are set once. Headers given to a single call are merged over them.
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
import { Acryl } from '@acryldev/blends'
|
|
110
|
+
import { getCookie } from '@acryldev/blends/cookie'
|
|
111
|
+
import { testClient } from '@acryldev/blends/testing'
|
|
112
|
+
|
|
113
|
+
const app = new Acryl().get('/me', (c) => c.json({ session: getCookie(c, 'session') ?? null }))
|
|
114
|
+
|
|
115
|
+
const client = testClient(app, undefined, undefined, { headers: { cookie: 'session=abc' } })
|
|
116
|
+
await (await client.me.$get()).json() // { session: 'abc' }
|
|
117
|
+
await (await client.me.$get(undefined, { headers: { cookie: 'session=xyz' } })).json() // { session: 'xyz' }
|
|
118
|
+
```
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
# WebSocket Helper
|
|
2
|
+
|
|
3
|
+
WebSocket Helper is a helper for server-side WebSockets in Acryl applications.
|
|
4
|
+
The Node.js and Bun adapters are available.
|
|
5
|
+
|
|
6
|
+
## Import
|
|
7
|
+
|
|
8
|
+
The Node.js adapter (`acrylblends/node-server`) and the Bun adapter (`acrylblends/bun`, experimental) provide `upgradeWebSocket`. The other platforms have no adapter in 1.0.
|
|
9
|
+
|
|
10
|
+
**Bun**
|
|
11
|
+
|
|
12
|
+
```ts
|
|
13
|
+
import { Acryl } from '@acryldev/blends'
|
|
14
|
+
import { upgradeWebSocket, websocket } from '@acryldev/blends/bun'
|
|
15
|
+
|
|
16
|
+
// ...
|
|
17
|
+
|
|
18
|
+
export default {
|
|
19
|
+
fetch: app.fetch,
|
|
20
|
+
websocket,
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
**Node.js**
|
|
25
|
+
|
|
26
|
+
```ts
|
|
27
|
+
import { serve, upgradeWebSocket } from '@acryldev/blends/node-server'
|
|
28
|
+
import { Acryl } from '@acryldev/blends'
|
|
29
|
+
import { WebSocketServer } from 'ws'
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
On Node.js, WebSocket support is built into `acrylblends/node-server`. To enable it, install `ws` and, if you use TypeScript, `@types/ws`. Then create a `WebSocketServer` with `{ noServer: true }` and pass it to `serve()` via the `websocket` option.
|
|
33
|
+
|
|
34
|
+
## `upgradeWebSocket()`
|
|
35
|
+
|
|
36
|
+
`upgradeWebSocket()` returns a handler for handling WebSocket.
|
|
37
|
+
|
|
38
|
+
```ts
|
|
39
|
+
const app = new Acryl()
|
|
40
|
+
|
|
41
|
+
app.get(
|
|
42
|
+
'/ws',
|
|
43
|
+
upgradeWebSocket((c) => {
|
|
44
|
+
return {
|
|
45
|
+
onMessage(event, ws) {
|
|
46
|
+
console.log(`Message from client: ${event.data}`)
|
|
47
|
+
ws.send('Hello from server!')
|
|
48
|
+
},
|
|
49
|
+
onClose: () => {
|
|
50
|
+
console.log('Connection closed')
|
|
51
|
+
},
|
|
52
|
+
}
|
|
53
|
+
})
|
|
54
|
+
)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Available events:
|
|
58
|
+
|
|
59
|
+
- `onOpen`
|
|
60
|
+
- `onMessage`
|
|
61
|
+
- `onClose`
|
|
62
|
+
- `onError`
|
|
63
|
+
|
|
64
|
+
> **Warning.**
|
|
65
|
+
> If you use middleware that modifies headers (e.g., applying CORS) on a route that uses WebSocket Helper, you may encounter an error saying you can't modify immutable headers. This is because `upgradeWebSocket()` also changes headers internally.
|
|
66
|
+
>
|
|
67
|
+
> Therefore, please be cautious if you are using WebSocket Helper and middleware at the same time.
|
|
68
|
+
>
|
|
69
|
+
|
|
70
|
+
## RPC-mode
|
|
71
|
+
|
|
72
|
+
Handlers defined with WebSocket Helper support RPC mode.
|
|
73
|
+
|
|
74
|
+
```ts
|
|
75
|
+
// server.ts
|
|
76
|
+
const wsApp = app.get(
|
|
77
|
+
'/ws',
|
|
78
|
+
upgradeWebSocket((c) => {
|
|
79
|
+
//...
|
|
80
|
+
})
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
export type WebSocketApp = typeof wsApp
|
|
84
|
+
|
|
85
|
+
// client.ts
|
|
86
|
+
const client = hc<WebSocketApp>('http://localhost:8787')
|
|
87
|
+
const socket = client.ws.$ws() // A WebSocket object for a client
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Examples
|
|
91
|
+
|
|
92
|
+
See the examples using WebSocket Helper.
|
|
93
|
+
|
|
94
|
+
### Server and Client
|
|
95
|
+
|
|
96
|
+
```ts
|
|
97
|
+
// server.ts
|
|
98
|
+
import { Acryl } from '@acryldev/blends'
|
|
99
|
+
import { upgradeWebSocket } from '@acryldev/blends/node-server'
|
|
100
|
+
|
|
101
|
+
const app = new Acryl().get(
|
|
102
|
+
'/ws',
|
|
103
|
+
upgradeWebSocket(() => {
|
|
104
|
+
return {
|
|
105
|
+
onMessage: (event) => {
|
|
106
|
+
console.log(event.data)
|
|
107
|
+
},
|
|
108
|
+
}
|
|
109
|
+
})
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
export default app
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
// client.ts
|
|
117
|
+
import { hc } from '@acryldev/blends/client'
|
|
118
|
+
import type app from './server'
|
|
119
|
+
|
|
120
|
+
const client = hc<typeof app>('http://localhost:8787')
|
|
121
|
+
const ws = client.ws.$ws(0)
|
|
122
|
+
|
|
123
|
+
ws.addEventListener('open', () => {
|
|
124
|
+
setInterval(() => {
|
|
125
|
+
ws.send(new Date().toString())
|
|
126
|
+
}, 1000)
|
|
127
|
+
})
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
### Bun with JSX
|
|
131
|
+
|
|
132
|
+
```tsx
|
|
133
|
+
import { Acryl } from '@acryldev/blends'
|
|
134
|
+
import { upgradeWebSocket, websocket } from '@acryldev/blends/bun'
|
|
135
|
+
import { html } from '@acryldev/blends/html'
|
|
136
|
+
|
|
137
|
+
const app = new Acryl()
|
|
138
|
+
|
|
139
|
+
app.get('/', (c) => {
|
|
140
|
+
return c.html(
|
|
141
|
+
<html>
|
|
142
|
+
<head>
|
|
143
|
+
<meta charset='UTF-8' />
|
|
144
|
+
</head>
|
|
145
|
+
<body>
|
|
146
|
+
<div id='now-time'></div>
|
|
147
|
+
{html`
|
|
148
|
+
<script>
|
|
149
|
+
const ws = new WebSocket('ws://localhost:3000/ws')
|
|
150
|
+
const $nowTime = document.getElementById('now-time')
|
|
151
|
+
ws.onmessage = (event) => {
|
|
152
|
+
$nowTime.textContent = event.data
|
|
153
|
+
}
|
|
154
|
+
</script>
|
|
155
|
+
`}
|
|
156
|
+
</body>
|
|
157
|
+
</html>
|
|
158
|
+
)
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
const ws = app.get(
|
|
162
|
+
'/ws',
|
|
163
|
+
upgradeWebSocket((c) => {
|
|
164
|
+
let intervalId
|
|
165
|
+
return {
|
|
166
|
+
onOpen(_event, ws) {
|
|
167
|
+
intervalId = setInterval(() => {
|
|
168
|
+
ws.send(new Date().toString())
|
|
169
|
+
}, 200)
|
|
170
|
+
},
|
|
171
|
+
onClose() {
|
|
172
|
+
clearInterval(intervalId)
|
|
173
|
+
},
|
|
174
|
+
}
|
|
175
|
+
})
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
export default {
|
|
179
|
+
fetch: app.fetch,
|
|
180
|
+
websocket,
|
|
181
|
+
}
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
### Node.js
|
|
185
|
+
|
|
186
|
+
```ts
|
|
187
|
+
import { serve, upgradeWebSocket } from '@acryldev/blends/node-server'
|
|
188
|
+
import { Acryl } from '@acryldev/blends'
|
|
189
|
+
import { WebSocketServer } from 'ws'
|
|
190
|
+
|
|
191
|
+
const app = new Acryl()
|
|
192
|
+
|
|
193
|
+
app.get(
|
|
194
|
+
'/ws',
|
|
195
|
+
upgradeWebSocket(() => ({
|
|
196
|
+
onMessage(event, ws) {
|
|
197
|
+
ws.send(String(event.data))
|
|
198
|
+
},
|
|
199
|
+
}))
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
const wss = new WebSocketServer({ noServer: true })
|
|
203
|
+
|
|
204
|
+
serve({
|
|
205
|
+
fetch: app.fetch,
|
|
206
|
+
websocket: { server: wss },
|
|
207
|
+
})
|
|
208
|
+
```
|