bun-types 1.1.37-canary.20241124T140524 → 1.1.37-canary.20241125T140601

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.
Files changed (272) hide show
  1. package/docs/api/binary-data.md +1028 -0
  2. package/docs/api/cc.md +197 -0
  3. package/docs/api/color.md +262 -0
  4. package/docs/api/console.md +38 -0
  5. package/docs/api/dns.md +113 -0
  6. package/docs/api/fetch.md +308 -0
  7. package/docs/api/ffi.md +536 -0
  8. package/docs/api/file-io.md +358 -0
  9. package/docs/api/file-system-router.md +112 -0
  10. package/docs/api/file.md +19 -0
  11. package/docs/api/glob.md +157 -0
  12. package/docs/api/globals.md +387 -0
  13. package/docs/api/hashing.md +314 -0
  14. package/docs/api/html-rewriter.md +31 -0
  15. package/docs/api/http.md +661 -0
  16. package/docs/api/import-meta.md +69 -0
  17. package/docs/api/node-api.md +16 -0
  18. package/docs/api/semver.md +52 -0
  19. package/docs/api/spawn.md +441 -0
  20. package/docs/api/sqlite.md +692 -0
  21. package/docs/api/streams.md +214 -0
  22. package/docs/api/tcp.md +221 -0
  23. package/docs/api/test.md +1 -0
  24. package/docs/api/transpiler.md +274 -0
  25. package/docs/api/udp.md +125 -0
  26. package/docs/api/utils.md +773 -0
  27. package/docs/api/websockets.md +547 -0
  28. package/docs/api/workers.md +230 -0
  29. package/docs/benchmarks.md +120 -0
  30. package/docs/bun-flavored-toml.md +42 -0
  31. package/docs/bundler/executables.md +291 -0
  32. package/docs/bundler/index.md +1543 -0
  33. package/docs/bundler/intro.md +75 -0
  34. package/docs/bundler/loaders.md +288 -0
  35. package/docs/bundler/macros.md +327 -0
  36. package/docs/bundler/plugins.md +30 -0
  37. package/docs/bundler/vs-esbuild.md +1127 -0
  38. package/docs/cli/add.md +163 -0
  39. package/docs/cli/bun-completions.md +3 -0
  40. package/docs/cli/bun-create.md +254 -0
  41. package/docs/cli/bun-dev.md +21 -0
  42. package/docs/cli/bun-install.md +255 -0
  43. package/docs/cli/bun-upgrade.md +39 -0
  44. package/docs/cli/bunx.md +80 -0
  45. package/docs/cli/filter.md +57 -0
  46. package/docs/cli/init.md +40 -0
  47. package/docs/cli/install.md +205 -0
  48. package/docs/cli/link.md +38 -0
  49. package/docs/cli/outdated.md +61 -0
  50. package/docs/cli/patch-commit.md +9 -0
  51. package/docs/cli/pm.md +150 -0
  52. package/docs/cli/publish.md +107 -0
  53. package/docs/cli/remove.md +5 -0
  54. package/docs/cli/run.md +196 -0
  55. package/docs/cli/test.md +247 -0
  56. package/docs/cli/unlink.md +7 -0
  57. package/docs/cli/update.md +34 -0
  58. package/docs/contributing/upgrading-webkit.md +57 -0
  59. package/docs/ecosystem/elysia.md +24 -0
  60. package/docs/ecosystem/express.md +37 -0
  61. package/docs/ecosystem/hono.md +18 -0
  62. package/docs/ecosystem/react.md +65 -0
  63. package/docs/ecosystem/stric.md +37 -0
  64. package/docs/guides/binary/arraybuffer-to-array.md +27 -0
  65. package/docs/guides/binary/arraybuffer-to-blob.md +24 -0
  66. package/docs/guides/binary/arraybuffer-to-buffer.md +25 -0
  67. package/docs/guides/binary/arraybuffer-to-string.md +15 -0
  68. package/docs/guides/binary/arraybuffer-to-typedarray.md +39 -0
  69. package/docs/guides/binary/blob-to-arraybuffer.md +14 -0
  70. package/docs/guides/binary/blob-to-dataview.md +14 -0
  71. package/docs/guides/binary/blob-to-stream.md +14 -0
  72. package/docs/guides/binary/blob-to-string.md +15 -0
  73. package/docs/guides/binary/blob-to-typedarray.md +14 -0
  74. package/docs/guides/binary/buffer-to-arraybuffer.md +14 -0
  75. package/docs/guides/binary/buffer-to-blob.md +14 -0
  76. package/docs/guides/binary/buffer-to-readablestream.md +41 -0
  77. package/docs/guides/binary/buffer-to-string.md +25 -0
  78. package/docs/guides/binary/buffer-to-typedarray.md +14 -0
  79. package/docs/guides/binary/dataview-to-string.md +15 -0
  80. package/docs/guides/binary/typedarray-to-arraybuffer.md +25 -0
  81. package/docs/guides/binary/typedarray-to-blob.md +16 -0
  82. package/docs/guides/binary/typedarray-to-buffer.md +14 -0
  83. package/docs/guides/binary/typedarray-to-dataview.md +14 -0
  84. package/docs/guides/binary/typedarray-to-readablestream.md +41 -0
  85. package/docs/guides/binary/typedarray-to-string.md +16 -0
  86. package/docs/guides/ecosystem/astro.md +72 -0
  87. package/docs/guides/ecosystem/discordjs.md +77 -0
  88. package/docs/guides/ecosystem/docker.md +140 -0
  89. package/docs/guides/ecosystem/drizzle.md +185 -0
  90. package/docs/guides/ecosystem/edgedb.md +228 -0
  91. package/docs/guides/ecosystem/elysia.md +31 -0
  92. package/docs/guides/ecosystem/express.md +40 -0
  93. package/docs/guides/ecosystem/hono.md +39 -0
  94. package/docs/guides/ecosystem/mongoose.md +87 -0
  95. package/docs/guides/ecosystem/neon-drizzle.md +220 -0
  96. package/docs/guides/ecosystem/neon-serverless-postgres.md +55 -0
  97. package/docs/guides/ecosystem/nextjs.md +38 -0
  98. package/docs/guides/ecosystem/nuxt.md +56 -0
  99. package/docs/guides/ecosystem/pm2.md +57 -0
  100. package/docs/guides/ecosystem/prisma.md +140 -0
  101. package/docs/guides/ecosystem/qwik.md +107 -0
  102. package/docs/guides/ecosystem/react.md +49 -0
  103. package/docs/guides/ecosystem/remix.md +78 -0
  104. package/docs/guides/ecosystem/render.md +79 -0
  105. package/docs/guides/ecosystem/sentry.md +52 -0
  106. package/docs/guides/ecosystem/solidstart.md +58 -0
  107. package/docs/guides/ecosystem/ssr-react.md +51 -0
  108. package/docs/guides/ecosystem/stric.md +55 -0
  109. package/docs/guides/ecosystem/sveltekit.md +125 -0
  110. package/docs/guides/ecosystem/systemd.md +113 -0
  111. package/docs/guides/ecosystem/vite.md +70 -0
  112. package/docs/guides/http/cluster.md +66 -0
  113. package/docs/guides/http/fetch-unix.md +33 -0
  114. package/docs/guides/http/fetch.md +24 -0
  115. package/docs/guides/http/file-uploads.md +94 -0
  116. package/docs/guides/http/hot.md +22 -0
  117. package/docs/guides/http/proxy.md +24 -0
  118. package/docs/guides/http/server.md +46 -0
  119. package/docs/guides/http/simple.md +18 -0
  120. package/docs/guides/http/stream-file.md +48 -0
  121. package/docs/guides/http/stream-iterator.md +47 -0
  122. package/docs/guides/http/stream-node-streams-in-bun.md +20 -0
  123. package/docs/guides/http/tls.md +30 -0
  124. package/docs/guides/install/add-dev.md +26 -0
  125. package/docs/guides/install/add-git.md +36 -0
  126. package/docs/guides/install/add-optional.md +25 -0
  127. package/docs/guides/install/add-peer.md +17 -0
  128. package/docs/guides/install/add-tarball.md +33 -0
  129. package/docs/guides/install/add.md +42 -0
  130. package/docs/guides/install/azure-artifacts.md +73 -0
  131. package/docs/guides/install/cicd.md +41 -0
  132. package/docs/guides/install/custom-registry.md +30 -0
  133. package/docs/guides/install/from-npm-install-to-bun-install.md +214 -0
  134. package/docs/guides/install/git-diff-bun-lockfile.md +38 -0
  135. package/docs/guides/install/jfrog-artifactory.md +28 -0
  136. package/docs/guides/install/npm-alias.md +23 -0
  137. package/docs/guides/install/registry-scope.md +36 -0
  138. package/docs/guides/install/trusted.md +48 -0
  139. package/docs/guides/install/workspaces.md +70 -0
  140. package/docs/guides/install/yarnlock.md +42 -0
  141. package/docs/guides/process/argv.md +57 -0
  142. package/docs/guides/process/ctrl-c.md +16 -0
  143. package/docs/guides/process/ipc.md +66 -0
  144. package/docs/guides/process/nanoseconds.md +13 -0
  145. package/docs/guides/process/os-signals.md +39 -0
  146. package/docs/guides/process/spawn-stderr.md +31 -0
  147. package/docs/guides/process/spawn-stdout.md +26 -0
  148. package/docs/guides/process/spawn.md +41 -0
  149. package/docs/guides/process/stdin.md +54 -0
  150. package/docs/guides/read-file/arraybuffer.md +28 -0
  151. package/docs/guides/read-file/buffer.md +19 -0
  152. package/docs/guides/read-file/exists.md +16 -0
  153. package/docs/guides/read-file/json.md +17 -0
  154. package/docs/guides/read-file/mime.md +20 -0
  155. package/docs/guides/read-file/stream.md +26 -0
  156. package/docs/guides/read-file/string.md +22 -0
  157. package/docs/guides/read-file/uint8array.md +21 -0
  158. package/docs/guides/read-file/watch.md +68 -0
  159. package/docs/guides/runtime/cicd.md +43 -0
  160. package/docs/guides/runtime/define-constant.md +145 -0
  161. package/docs/guides/runtime/import-html.md +15 -0
  162. package/docs/guides/runtime/import-json.md +44 -0
  163. package/docs/guides/runtime/import-toml.md +30 -0
  164. package/docs/guides/runtime/read-env.md +32 -0
  165. package/docs/guides/runtime/set-env.md +37 -0
  166. package/docs/guides/runtime/shell.md +40 -0
  167. package/docs/guides/runtime/timezone.md +35 -0
  168. package/docs/guides/runtime/tsconfig-paths.md +29 -0
  169. package/docs/guides/runtime/typescript.md +47 -0
  170. package/docs/guides/runtime/vscode-debugger.md +47 -0
  171. package/docs/guides/runtime/web-debugger.md +82 -0
  172. package/docs/guides/streams/node-readable-to-arraybuffer.md +11 -0
  173. package/docs/guides/streams/node-readable-to-blob.md +11 -0
  174. package/docs/guides/streams/node-readable-to-json.md +12 -0
  175. package/docs/guides/streams/node-readable-to-string.md +12 -0
  176. package/docs/guides/streams/node-readable-to-uint8array.md +11 -0
  177. package/docs/guides/streams/to-array.md +14 -0
  178. package/docs/guides/streams/to-arraybuffer.md +14 -0
  179. package/docs/guides/streams/to-blob.md +14 -0
  180. package/docs/guides/streams/to-buffer.md +15 -0
  181. package/docs/guides/streams/to-json.md +14 -0
  182. package/docs/guides/streams/to-string.md +14 -0
  183. package/docs/guides/streams/to-typedarray.md +22 -0
  184. package/docs/guides/test/bail.md +22 -0
  185. package/docs/guides/test/coverage-threshold.md +60 -0
  186. package/docs/guides/test/coverage.md +44 -0
  187. package/docs/guides/test/happy-dom.md +68 -0
  188. package/docs/guides/test/migrate-from-jest.md +110 -0
  189. package/docs/guides/test/mock-clock.md +48 -0
  190. package/docs/guides/test/mock-functions.md +68 -0
  191. package/docs/guides/test/rerun-each.md +14 -0
  192. package/docs/guides/test/run-tests.md +111 -0
  193. package/docs/guides/test/skip-tests.md +39 -0
  194. package/docs/guides/test/snapshot.md +99 -0
  195. package/docs/guides/test/spy-on.md +46 -0
  196. package/docs/guides/test/testing-library.md +87 -0
  197. package/docs/guides/test/timeout.md +15 -0
  198. package/docs/guides/test/todo-tests.md +67 -0
  199. package/docs/guides/test/update-snapshots.md +50 -0
  200. package/docs/guides/test/watch-mode.md +19 -0
  201. package/docs/guides/util/base64.md +15 -0
  202. package/docs/guides/util/deep-equals.md +39 -0
  203. package/docs/guides/util/deflate.md +18 -0
  204. package/docs/guides/util/detect-bun.md +23 -0
  205. package/docs/guides/util/entrypoint.md +17 -0
  206. package/docs/guides/util/escape-html.md +22 -0
  207. package/docs/guides/util/file-url-to-path.md +14 -0
  208. package/docs/guides/util/gzip.md +18 -0
  209. package/docs/guides/util/hash-a-password.md +54 -0
  210. package/docs/guides/util/import-meta-dir.md +13 -0
  211. package/docs/guides/util/import-meta-file.md +13 -0
  212. package/docs/guides/util/import-meta-path.md +13 -0
  213. package/docs/guides/util/main.md +32 -0
  214. package/docs/guides/util/path-to-file-url.md +14 -0
  215. package/docs/guides/util/sleep.md +22 -0
  216. package/docs/guides/util/version.md +21 -0
  217. package/docs/guides/util/which-path-to-executable-bin.md +15 -0
  218. package/docs/guides/websocket/compression.md +31 -0
  219. package/docs/guides/websocket/context.md +72 -0
  220. package/docs/guides/websocket/pubsub.md +38 -0
  221. package/docs/guides/websocket/simple.md +33 -0
  222. package/docs/guides/write-file/append.md +52 -0
  223. package/docs/guides/write-file/basic.md +44 -0
  224. package/docs/guides/write-file/blob.md +28 -0
  225. package/docs/guides/write-file/cat.md +17 -0
  226. package/docs/guides/write-file/file-cp.md +16 -0
  227. package/docs/guides/write-file/filesink.md +52 -0
  228. package/docs/guides/write-file/response.md +17 -0
  229. package/docs/guides/write-file/stdout.md +21 -0
  230. package/docs/guides/write-file/stream.md +17 -0
  231. package/docs/guides/write-file/unlink.md +23 -0
  232. package/docs/index.md +77 -0
  233. package/docs/install/cache.md +57 -0
  234. package/docs/install/index.md +202 -0
  235. package/docs/install/lifecycle.md +46 -0
  236. package/docs/install/lockfile.md +90 -0
  237. package/docs/install/npmrc.md +75 -0
  238. package/docs/install/overrides.md +73 -0
  239. package/docs/install/patch.md +57 -0
  240. package/docs/install/registries.md +30 -0
  241. package/docs/install/workspaces.md +70 -0
  242. package/docs/installation.md +289 -0
  243. package/docs/project/benchmarking.md +203 -0
  244. package/docs/project/building-windows.md +162 -0
  245. package/docs/project/internals/build-process-for-ci.md +75 -0
  246. package/docs/project/roadmap.md +87 -0
  247. package/docs/quickstart.md +144 -0
  248. package/docs/runtime/autoimport.md +94 -0
  249. package/docs/runtime/bun-apis.md +129 -0
  250. package/docs/runtime/bunfig.md +532 -0
  251. package/docs/runtime/debugger.md +325 -0
  252. package/docs/runtime/env.md +214 -0
  253. package/docs/runtime/hot.md +139 -0
  254. package/docs/runtime/index.md +309 -0
  255. package/docs/runtime/jsx.md +326 -0
  256. package/docs/runtime/loaders.md +127 -0
  257. package/docs/runtime/modules.md +298 -0
  258. package/docs/runtime/nodejs-apis.md +456 -0
  259. package/docs/runtime/plugins.md +605 -0
  260. package/docs/runtime/shell.md +537 -0
  261. package/docs/runtime/typescript.md +60 -0
  262. package/docs/runtime/web-apis.md +128 -0
  263. package/docs/test/coverage.md +91 -0
  264. package/docs/test/dom.md +75 -0
  265. package/docs/test/hot.md +15 -0
  266. package/docs/test/lifecycle.md +81 -0
  267. package/docs/test/mocks.md +236 -0
  268. package/docs/test/snapshots.md +15 -0
  269. package/docs/test/time.md +106 -0
  270. package/docs/test/writing.md +547 -0
  271. package/docs/typescript.md +51 -0
  272. package/package.json +5 -4
@@ -0,0 +1,547 @@
1
+ `Bun.serve()` supports server-side WebSockets, with on-the-fly compression, TLS support, and a Bun-native publish-subscribe API.
2
+
3
+ {% callout %}
4
+
5
+ **⚡️ 7x more throughput** — Bun's WebSockets are fast. For a [simple chatroom](https://github.com/oven-sh/bun/tree/main/bench/websocket-server/README.md) on Linux x64, Bun can handle 7x more requests per second than Node.js + [`"ws"`](https://github.com/websockets/ws).
6
+
7
+ | Messages sent per second | Runtime | Clients |
8
+ | ------------------------ | ------------------------------ | ------- |
9
+ | ~700,000 | (`Bun.serve`) Bun v0.2.1 (x64) | 16 |
10
+ | ~100,000 | (`ws`) Node v18.10.0 (x64) | 16 |
11
+
12
+ Internally Bun's WebSocket implementation is built on [uWebSockets](https://github.com/uNetworking/uWebSockets).
13
+ {% /callout %}
14
+
15
+ ## Start a WebSocket server
16
+
17
+ Below is a simple WebSocket server built with `Bun.serve`, in which all incoming requests are [upgraded](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) to WebSocket connections in the `fetch` handler. The socket handlers are declared in the `websocket` parameter.
18
+
19
+ ```ts
20
+ Bun.serve({
21
+ fetch(req, server) {
22
+ // upgrade the request to a WebSocket
23
+ if (server.upgrade(req)) {
24
+ return; // do not return a Response
25
+ }
26
+ return new Response("Upgrade failed", { status: 500 });
27
+ },
28
+ websocket: {}, // handlers
29
+ });
30
+ ```
31
+
32
+ The following WebSocket event handlers are supported:
33
+
34
+ ```ts
35
+ Bun.serve({
36
+ fetch(req, server) {}, // upgrade logic
37
+ websocket: {
38
+ message(ws, message) {}, // a message is received
39
+ open(ws) {}, // a socket is opened
40
+ close(ws, code, message) {}, // a socket is closed
41
+ drain(ws) {}, // the socket is ready to receive more data
42
+ },
43
+ });
44
+ ```
45
+
46
+ {% details summary="An API designed for speed" %}
47
+
48
+ In Bun, handlers are declared once per server, instead of per socket.
49
+
50
+ `ServerWebSocket` expects you to pass a `WebSocketHandler` object to the `Bun.serve()` method which has methods for `open`, `message`, `close`, `drain`, and `error`. This is different than the client-side `WebSocket` class which extends `EventTarget` (onmessage, onopen, onclose),
51
+
52
+ Clients tend to not have many socket connections open so an event-based API makes sense.
53
+
54
+ But servers tend to have **many** socket connections open, which means:
55
+
56
+ - Time spent adding/removing event listeners for each connection adds up
57
+ - Extra memory spent on storing references to callbacks function for each connection
58
+ - Usually, people create new functions for each connection, which also means more memory
59
+
60
+ So, instead of using an event-based API, `ServerWebSocket` expects you to pass a single object with methods for each event in `Bun.serve()` and it is reused for each connection.
61
+
62
+ This leads to less memory usage and less time spent adding/removing event listeners.
63
+ {% /details %}
64
+
65
+ The first argument to each handler is the instance of `ServerWebSocket` handling the event. The `ServerWebSocket` class is a fast, Bun-native implementation of [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) with some additional features.
66
+
67
+ ```ts
68
+ Bun.serve({
69
+ fetch(req, server) {}, // upgrade logic
70
+ websocket: {
71
+ message(ws, message) {
72
+ ws.send(message); // echo back the message
73
+ },
74
+ },
75
+ });
76
+ ```
77
+
78
+ ### Sending messages
79
+
80
+ Each `ServerWebSocket` instance has a `.send()` method for sending messages to the client. It supports a range of input types.
81
+
82
+ ```ts
83
+ ws.send("Hello world"); // string
84
+ ws.send(response.arrayBuffer()); // ArrayBuffer
85
+ ws.send(new Uint8Array([1, 2, 3])); // TypedArray | DataView
86
+ ```
87
+
88
+ ### Headers
89
+
90
+ Once the upgrade succeeds, Bun will send a `101 Switching Protocols` response per the [spec](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism). Additional `headers` can be attached to this `Response` in the call to `server.upgrade()`.
91
+
92
+ ```ts
93
+ Bun.serve({
94
+ fetch(req, server) {
95
+ const sessionId = await generateSessionId();
96
+ server.upgrade(req, {
97
+ headers: {
98
+ "Set-Cookie": `SessionId=${sessionId}`,
99
+ },
100
+ });
101
+ },
102
+ websocket: {}, // handlers
103
+ });
104
+ ```
105
+
106
+ ### Contextual data
107
+
108
+ Contextual `data` can be attached to a new WebSocket in the `.upgrade()` call. This data is made available on the `ws.data` property inside the WebSocket handlers.
109
+
110
+ ```ts
111
+ type WebSocketData = {
112
+ createdAt: number;
113
+ channelId: string;
114
+ authToken: string;
115
+ };
116
+
117
+ // TypeScript: specify the type of `data`
118
+ Bun.serve<WebSocketData>({
119
+ fetch(req, server) {
120
+ // use a library to parse cookies
121
+ const cookies = parseCookies(req.headers.get("Cookie"));
122
+ server.upgrade(req, {
123
+ // this object must conform to WebSocketData
124
+ data: {
125
+ createdAt: Date.now(),
126
+ channelId: new URL(req.url).searchParams.get("channelId"),
127
+ authToken: cookies["X-Token"],
128
+ },
129
+ });
130
+
131
+ return undefined;
132
+ },
133
+ websocket: {
134
+ // handler called when a message is received
135
+ async message(ws, message) {
136
+ const user = getUserFromToken(ws.data.authToken);
137
+
138
+ await saveMessageToDatabase({
139
+ channel: ws.data.channelId,
140
+ message: String(message),
141
+ userId: user.id,
142
+ });
143
+ },
144
+ },
145
+ });
146
+ ```
147
+
148
+ To connect to this server from the browser, create a new `WebSocket`.
149
+
150
+ ```ts#browser.js
151
+ const socket = new WebSocket("ws://localhost:3000/chat");
152
+
153
+ socket.addEventListener("message", event => {
154
+ console.log(event.data);
155
+ })
156
+ ```
157
+
158
+ {% callout %}
159
+ **Identifying users** — The cookies that are currently set on the page will be sent with the WebSocket upgrade request and available on `req.headers` in the `fetch` handler. Parse these cookies to determine the identity of the connecting user and set the value of `data` accordingly.
160
+ {% /callout %}
161
+
162
+ ### Pub/Sub
163
+
164
+ Bun's `ServerWebSocket` implementation implements a native publish-subscribe API for topic-based broadcasting. Individual sockets can `.subscribe()` to a topic (specified with a string identifier) and `.publish()` messages to all other subscribers to that topic (excluding itself). This topic-based broadcast API is similar to [MQTT](https://en.wikipedia.org/wiki/MQTT) and [Redis Pub/Sub](https://redis.io/topics/pubsub).
165
+
166
+ ```ts
167
+ const server = Bun.serve<{ username: string }>({
168
+ fetch(req, server) {
169
+ const url = new URL(req.url);
170
+ if (url.pathname === "/chat") {
171
+ console.log(`upgrade!`);
172
+ const username = getUsernameFromReq(req);
173
+ const success = server.upgrade(req, { data: { username } });
174
+ return success
175
+ ? undefined
176
+ : new Response("WebSocket upgrade error", { status: 400 });
177
+ }
178
+
179
+ return new Response("Hello world");
180
+ },
181
+ websocket: {
182
+ open(ws) {
183
+ const msg = `${ws.data.username} has entered the chat`;
184
+ ws.subscribe("the-group-chat");
185
+ server.publish("the-group-chat", msg);
186
+ },
187
+ message(ws, message) {
188
+ // this is a group chat
189
+ // so the server re-broadcasts incoming message to everyone
190
+ server.publish("the-group-chat", `${ws.data.username}: ${message}`);
191
+ },
192
+ close(ws) {
193
+ const msg = `${ws.data.username} has left the chat`;
194
+ ws.unsubscribe("the-group-chat");
195
+ server.publish("the-group-chat", msg);
196
+ },
197
+ },
198
+ });
199
+
200
+ console.log(`Listening on ${server.hostname}:${server.port}`);
201
+ ```
202
+
203
+ Calling `.publish(data)` will send the message to all subscribers of a topic _except_ the socket that called `.publish()`. To send a message to all subscribers of a topic, use the `.publish()` method on the `Server` instance.
204
+
205
+ ```ts
206
+ const server = Bun.serve({
207
+ websocket: {
208
+ // ...
209
+ },
210
+ });
211
+
212
+ // listen for some external event
213
+ server.publish("the-group-chat", "Hello world");
214
+ ```
215
+
216
+ ### Compression
217
+
218
+ Per-message [compression](https://websockets.readthedocs.io/en/stable/topics/compression.html) can be enabled with the `perMessageDeflate` parameter.
219
+
220
+ ```ts
221
+ Bun.serve({
222
+ fetch(req, server) {}, // upgrade logic
223
+ websocket: {
224
+ // enable compression and decompression
225
+ perMessageDeflate: true,
226
+ },
227
+ });
228
+ ```
229
+
230
+ Compression can be enabled for individual messages by passing a `boolean` as the second argument to `.send()`.
231
+
232
+ ```ts
233
+ ws.send("Hello world", true);
234
+ ```
235
+
236
+ For fine-grained control over compression characteristics, refer to the [Reference](#reference).
237
+
238
+ ### Backpressure
239
+
240
+ The `.send(message)` method of `ServerWebSocket` returns a `number` indicating the result of the operation.
241
+
242
+ - `-1` — The message was enqueued but there is backpressure
243
+ - `0` — The message was dropped due to a connection issue
244
+ - `1+` — The number of bytes sent
245
+
246
+ This gives you better control over backpressure in your server.
247
+
248
+ ### Timeouts and limits
249
+
250
+ By default, Bun will close a WebSocket connection if it is idle for 120 seconds. This can be configured with the `idleTimeout` parameter.
251
+
252
+ ```ts
253
+ Bun.serve({
254
+ fetch(req, server) {}, // upgrade logic
255
+ websocket: {
256
+ idleTimeout: 60, // 60 seconds
257
+
258
+ // ...
259
+ },
260
+ });
261
+ ```
262
+
263
+ Bun will also close a WebSocket connection if it receives a message that is larger than 16 MB. This can be configured with the `maxPayloadLength` parameter.
264
+
265
+ ```ts
266
+ Bun.serve({
267
+ fetch(req, server) {}, // upgrade logic
268
+ websocket: {
269
+ maxPayloadLength: 1024 * 1024, // 1 MB
270
+
271
+ // ...
272
+ },
273
+ });
274
+ ```
275
+
276
+ ## Connect to a `Websocket` server
277
+
278
+ Bun implements the `WebSocket` class. To create a WebSocket client that connects to a `ws://` or `wss://` server, create an instance of `WebSocket`, as you would in the browser.
279
+
280
+ ```ts
281
+ const socket = new WebSocket("ws://localhost:3000");
282
+ ```
283
+
284
+ In browsers, the cookies that are currently set on the page will be sent with the WebSocket upgrade request. This is a standard feature of the `WebSocket` API.
285
+
286
+ For convenience, Bun lets you setting custom headers directly in the constructor. This is a Bun-specific extension of the `WebSocket` standard. _This will not work in browsers._
287
+
288
+ ```ts
289
+ const socket = new WebSocket("ws://localhost:3000", {
290
+ headers: {
291
+ // custom headers
292
+ },
293
+ });
294
+ ```
295
+
296
+ To add event listeners to the socket:
297
+
298
+ ```ts
299
+ // message is received
300
+ socket.addEventListener("message", event => {});
301
+
302
+ // socket opened
303
+ socket.addEventListener("open", event => {});
304
+
305
+ // socket closed
306
+ socket.addEventListener("close", event => {});
307
+
308
+ // error handler
309
+ socket.addEventListener("error", event => {});
310
+ ```
311
+
312
+ ## Reference
313
+
314
+ ```ts
315
+ namespace Bun {
316
+ export function serve(params: {
317
+ fetch: (req: Request, server: Server) => Response | Promise<Response>;
318
+ websocket?: {
319
+ message: (
320
+ ws: ServerWebSocket,
321
+ message: string | ArrayBuffer | Uint8Array,
322
+ ) => void;
323
+ open?: (ws: ServerWebSocket) => void;
324
+ close?: (ws: ServerWebSocket, code: number, reason: string) => void;
325
+ error?: (ws: ServerWebSocket, error: Error) => void;
326
+ drain?: (ws: ServerWebSocket) => void;
327
+
328
+ maxPayloadLength?: number; // default: 16 * 1024 * 1024 = 16 MB
329
+ idleTimeout?: number; // default: 120 (seconds)
330
+ backpressureLimit?: number; // default: 1024 * 1024 = 1 MB
331
+ closeOnBackpressureLimit?: boolean; // default: false
332
+ sendPings?: boolean; // default: true
333
+ publishToSelf?: boolean; // default: false
334
+
335
+ perMessageDeflate?:
336
+ | boolean
337
+ | {
338
+ compress?: boolean | Compressor;
339
+ decompress?: boolean | Compressor;
340
+ };
341
+ };
342
+ }): Server;
343
+ }
344
+
345
+ type Compressor =
346
+ | `"disable"`
347
+ | `"shared"`
348
+ | `"dedicated"`
349
+ | `"3KB"`
350
+ | `"4KB"`
351
+ | `"8KB"`
352
+ | `"16KB"`
353
+ | `"32KB"`
354
+ | `"64KB"`
355
+ | `"128KB"`
356
+ | `"256KB"`;
357
+
358
+ interface Server {
359
+ pendingWebSockets: number;
360
+ publish(
361
+ topic: string,
362
+ data: string | ArrayBufferView | ArrayBuffer,
363
+ compress?: boolean,
364
+ ): number;
365
+ upgrade(
366
+ req: Request,
367
+ options?: {
368
+ headers?: HeadersInit;
369
+ data?: any;
370
+ },
371
+ ): boolean;
372
+ }
373
+
374
+ interface ServerWebSocket {
375
+ readonly data: any;
376
+ readonly readyState: number;
377
+ readonly remoteAddress: string;
378
+ send(message: string | ArrayBuffer | Uint8Array, compress?: boolean): number;
379
+ close(code?: number, reason?: string): void;
380
+ subscribe(topic: string): void;
381
+ unsubscribe(topic: string): void;
382
+ publish(topic: string, message: string | ArrayBuffer | Uint8Array): void;
383
+ isSubscribed(topic: string): boolean;
384
+ cork(cb: (ws: ServerWebSocket) => void): void;
385
+ }
386
+ ```
387
+
388
+ <!--
389
+ ### `Bun.serve(params)`
390
+
391
+ {% param name="params" %}
392
+ Configuration object for WebSocket server
393
+ {% /param %}
394
+
395
+ {% param name=" fetch" %}
396
+ `(req: Request, server: Server) => Response | Promise<Response>`
397
+
398
+ Call `server.upgrade(req)` to upgrade the request to a WebSocket connection. This method returns `true` if the upgrade succeeds, or `false` if the upgrade fails.
399
+ {% /param %}
400
+
401
+ {% param name=" websocket" %}
402
+ Configuration object for WebSocket server
403
+ {% /param %}
404
+
405
+ {% param name=" message" %}
406
+ `(ws: ServerWebSocket, message: string | ArrayBuffer | Uint8Array) => void`
407
+
408
+ This handler is called when a `WebSocket` receives a message.
409
+ {% /param %}
410
+
411
+ {% param name=" open" %}
412
+ `(ws: ServerWebSocket) => void`
413
+
414
+ This handler is called when a `WebSocket` is opened.
415
+ {% /param %}
416
+
417
+ {% param name=" close" %}
418
+ `(ws: ServerWebSocket, code: number, message: string) => void`
419
+
420
+ This handler is called when a `WebSocket` is closed.
421
+ {% /param %}
422
+
423
+ {% param name=" drain" %}
424
+ `(ws: ServerWebSocket) => void`
425
+
426
+ This handler is called when a `WebSocket` is ready to receive more data.
427
+ {% /param %}
428
+
429
+ {% param name=" perMessageDeflate" %}
430
+ `boolean | {\n compress?: boolean | Compressor;\n decompress?: boolean | Compressor \n}`
431
+
432
+ Enable per-message compression and decompression. This is a boolean value or an object with `compress` and `decompress` properties. Each property can be a boolean value or one of the following `Compressor` types:
433
+
434
+ - `"disable"`
435
+ - `"shared"`
436
+ - `"dedicated"`
437
+ - `"3KB"`
438
+ - `"4KB"`
439
+ - `"8KB"`
440
+ - `"16KB"`
441
+ - `"32KB"`
442
+ - `"64KB"`
443
+ - `"128KB"`
444
+ - `"256KB"`
445
+
446
+ {% /param %}
447
+
448
+ ### `ServerWebSocket`
449
+
450
+ {% param name="readyState" %}
451
+ `number`
452
+
453
+ The current state of the `WebSocket` connection. This is one of the following values:
454
+
455
+ - `0` `CONNECTING`
456
+ - `1` `OPEN`
457
+ - `2` `CLOSING`
458
+ - `3` `CLOSED`
459
+
460
+ {% /param %}
461
+
462
+ {% param name="remoteAddress" %}
463
+
464
+ `string`
465
+
466
+ The remote address of the `WebSocket` connection
467
+ {% /param %}
468
+
469
+ {% param name="data" %}
470
+ The data associated with the `WebSocket` connection. This is set in the `server.upgrade()` call.
471
+ {% /param %}
472
+
473
+ {% param name=".send()" %}
474
+ `send(message: string | ArrayBuffer | Uint8Array, compress?: boolean): number`
475
+
476
+ Send a message to the client. Returns a `number` indicating the result of the operation.
477
+
478
+ - `-1`: the message was enqueued but there is backpressure
479
+ - `0`: the message was dropped due to a connection issue
480
+ - `1+`: the number of bytes sent
481
+
482
+ The `compress` argument will enable compression for this message, even if the `perMessageDeflate` option is disabled.
483
+ {% /param %}
484
+
485
+ {% param name=".subscribe()" %}
486
+ `subscribe(topic: string): void`
487
+
488
+ Subscribe to a topic
489
+ {% /param %}
490
+
491
+ {% param name=".unsubscribe()" %}
492
+ `unsubscribe(topic: string): void`
493
+
494
+ Unsubscribe from a topic
495
+ {% /param %}
496
+
497
+ {% param name=".publish()" %}
498
+ `publish(topic: string, data: string | ArrayBufferView | ArrayBuffer, compress?: boolean): number;`
499
+
500
+ Send a message to all subscribers of a topic
501
+ {% /param %}
502
+
503
+ {% param name=".isSubscribed()" %}
504
+ `isSubscribed(topic: string): boolean`
505
+
506
+ Check if the `WebSocket` is subscribed to a topic
507
+ {% /param %}
508
+ {% param name=".cork()" %}
509
+ `cork(cb: (ws: ServerWebSocket) => void): void;`
510
+
511
+ Batch a set of operations on a `WebSocket` connection. The `message`, `open`, and `drain` callbacks are automatically corked, so
512
+ you only need to call this if you are sending messages outside of those
513
+ callbacks or in async functions.
514
+
515
+ ```ts
516
+ ws.cork((ws) => {
517
+ ws.send("first");
518
+ ws.send("second");
519
+ ws.send("third");
520
+ });
521
+ ```
522
+
523
+ {% /param %}
524
+
525
+ {% param name=".close()" %}
526
+ `close(code?: number, message?: string): void`
527
+
528
+ Close the `WebSocket` connection
529
+ {% /param %}
530
+
531
+ ### `Server`
532
+
533
+ {% param name="pendingWebsockets" %}
534
+ Number of in-flight `WebSocket` messages
535
+ {% /param %}
536
+
537
+ {% param name=".publish()" %}
538
+ `publish(topic: string, data: string | ArrayBufferView | ArrayBuffer, compress?: boolean): number;`
539
+
540
+ Send a message to all subscribers of a topic
541
+ {% /param %}
542
+
543
+ {% param name=".upgrade()" %}
544
+ `upgrade(req: Request): boolean`
545
+
546
+ Upgrade a request to a `WebSocket` connection. Returns `true` if the upgrade succeeds, or `false` if the upgrade fails.
547
+ {% /param %} -->