@fluojs/platform-bun
v3.0.0
Published
Bun-based HTTP adapter for the Fluo runtime.
Maintainers
Readme
@fluojs/platform-bun
Bun-backed HTTP adapter for the fluo runtime, built on native Bun.serve().
Table of Contents
- Installation
- When to Use
- Quick Start
- Common Patterns
- Public API Overview
- Adapter Contract
- Conformance Coverage
- Related Packages
- Example Sources
Installation
npm install @fluojs/platform-bunThis package is intended to run on Bun. The published manifest intentionally does not declare engines.node, so npm metadata stays aligned with the Bun runtime contract; the repository's Node.js 20+ requirement only applies to the maintainer build/test toolchain.
When to Use
Use this package when running fluo applications on the Bun runtime. This adapter leverages Bun's high-performance Request/Response bridge and native fetch-style architecture, providing a seamless and fast experience for Bun users.
During application shutdown, the adapter stops all new ingress, including websocket upgrade attempts, with a 503 shutdown response and starts server.stop(stopActiveConnections) before draining accepted work from realtime binding evaluation through its HTTP response or upgrade outcome. The bounded timeout only rejects the caller-facing close() promise: accepted work and adapter state remain retained until the underlying drain settles, so the timeout does not force another teardown. If signal-driven shutdown exceeds forceExitTimeoutMs or fails, fluo reports that condition through logging and process.exitCode while leaving final process termination to Bun or the surrounding host.
Quick Start
import { createBunAdapter } from '@fluojs/platform-bun';
import { fluoFactory } from '@fluojs/runtime';
import { AppModule } from './app.module';
const app = await fluoFactory.create(AppModule, {
adapter: createBunAdapter({ port: 3000 }),
});
await app.listen();Common Patterns
Early Hints are unsupported
Bun uses Fluo's Web-standard response facade, so context.response.earlyHints is absent. Check for capability presence before use. The adapter does not silently ignore Early Hints and does not copy early fields into the final Response; use a Node.js, Express, or Fastify adapter when application code must emit observable HTTP 103 responses.
Streaming multipart consumption
Set multipart: { strategy: 'stream' } at application bootstrap to receive multipart data incrementally. For
multipart routes, RequestContext.request.body is an AsyncIterableIterator<MultipartPart>: field parts expose
kind: 'field', name, value, and headers; file parts expose kind: 'file', name, filename,
contentType, headers, and a single-consumer ReadableStream<Uint8Array> at stream. Finish or cancel each file
stream before requesting the next part.
Runtime route dispatch owns an iterator created for a route and automatically calls return() after the handler
finishes, cancelling and releasing an active source. Standalone parseMultipartStream(...) consumers own that
responsibility: consume the iterator to completion or call return() when ending early.
Byte Ranges and Cache Validation
Bun preserves the shared @fluojs/http single-byte-range and If-Range contract through its fetch dispatch. After conditional-request evaluation selects cache validators, a valid Range: bytes= request yields the portable 206 identity-byte response; If-Range reuses those selected validators, while malformed or multi-range fields retain the full response and an unsatisfiable range yields bodyless 416. HEAD mirrors GET metadata without consuming a stream.
Manual Fetch Handling
If you prefer to manage the Bun server yourself, you can use the fetch handler directly.
The dispatcher should come from the already bootstrapped application via app.getHttpDispatcher(). createBunFetchHandler(...) synchronously creates the fetch bridge and preserves raw-body and multipart request parsing, while shutdown ownership, websocket upgrades, and native routes acceleration remain responsibilities of the surrounding Bun.serve(...) host or the managed adapter path.
import { createBunFetchHandler } from '@fluojs/platform-bun';
const handler = createBunFetchHandler({
dispatcher: app.getHttpDispatcher(),
});
Bun.serve({
fetch: handler,
port: 3000,
});Native WebSocket Upgrade
The adapter supports Bun's native server.upgrade() through the @fluojs/websockets/bun binding. getRealtimeCapability() preserves fetch-style capability version 1 and adds the optional versioned bindingInstallation extension; first-party WebSocket and Socket.IO modules use that protocol-neutral installer before app.listen(), and the adapter parses the installed value into its Bun binding contract. Import BunWebSocketModule.forRoot(...) into the application module before app.listen() so the runtime can install that binding and discover the registered gateways.
import { Module } from '@fluojs/core';
import { BunWebSocketModule, WebSocketGateway } from '@fluojs/websockets/bun';
@WebSocketGateway({ path: '/ws' })
class MyGateway {}
@Module({
imports: [BunWebSocketModule.forRoot()],
providers: [MyGateway],
})
export class AppModule {}Native routes Object Acceleration
On Bun >=1.2.3, the adapter opportunistically registers safe static and parameterized fluo routes through Bun.serve({ routes }) while still routing matched requests back through the shared fluo dispatcher.
For semantically safe unversioned routes, Bun hands the pre-matched descriptor and params to the shared dispatcher so duplicate route matching is skipped while raw body, multipart, SSE, error responses, shutdown drain behavior, and websocket upgrade delegation stay on the same shared execution path. If route shape parity is unsafe, such as same-shape parameter routes with different param names, ALL-method handlers, normalization-sensitive paths, or non-URI versioning, the adapter falls back to fetch-only dispatch for those routes instead of changing fluo semantics.
If app middleware rewrites the framework request method or path after a Bun native handoff is attached, the dispatcher discards that stale handoff and rematches the rewritten request. Unsupported methods such as OPTIONS and CORS preflight behavior remain owned by the shared dispatcher/middleware path unless a fluo route explicitly owns them.
Validated custom routes such as QUERY and PURGE intentionally remain on the fetch fallback even when Bun native routes acceleration is available. Bun receives the original method and body through Request, and the shared dispatcher performs exact-method matching before ALL. CONNECT remains outside ordinary controller routing conformance.
Public API Overview
createBunAdapter(options): Recommended factory for the Bun adapter.createBunFetchHandler(options): Creates a nativefetch(request)handler for customBun.serve()setups.bootstrapBunApplication(module, options): Advanced bootstrap without implicit startup logging.runBunApplication(module, options): Compatibility helper for quick startup with signal wiring.
The adapter also exports the typed Bun integration seams used by realtime packages:
BunHttpApplicationAdapter:HttpApplicationAdapterimplementation backed byBun.serve(); itsgetRealtimeCapability()preserves fetch-style capability version 1 and includes optionalbindingInstallation.BunAdapterOptions: host, port, TLS, raw-body, multipart, and shutdown options accepted bycreateBunAdapter().BootstrapBunApplicationOptionsandRunBunApplicationOptions: application bootstrap/run options for Bun-hosted apps.BunWebSocketBinding,BunWebSocketUpgradeHost, andBunRealtimeBindingHost: binding contracts used by@fluojs/websockets/bunbefore normal HTTP dispatch. Bindings receive only an upgrade-capable host, not the adapter-owned Bun server lifecycle or raw fetch handler.BunWebSocketBindingHost: Backward-compatible alias for configuring Bun realtime bindings.BunServeOptions,BunServerLike,BunWebSocketHandler,BunServerWebSocket,BunWebSocketMessage,BunApplicationSignal,BunCorsInput,BunTlsOptions, andCreateBunFetchHandlerOptions: Lower-level Bun host, websocket, signal, CORS, TLS, and fetch-handler integration types.
Adapter Contract
- Runtime host: This package requires
globalThis.Bun.serve()at listen time. Tests may provide a Bun-compatible test double, but production use is Bun-only. - Request portability: Fetch requests are translated through the shared web dispatcher, preserving malformed cookie values, query arrays, JSON/text raw bodies when
rawBody: true, byte-exact request handoff for customcreateBunFetchHandler(...)setups, and SSE framing. - Native route acceleration: When Bun's
routesobject is available and a fluo route shape is semantically safe to pre-register, the adapter lets Bun short-circuit path matching before handing the request back to the shared dispatcher. Unsupported or ambiguous route shapes fall back to the regularfetchpath, and stale handoffs are ignored if middleware rewrites method/path before handler matching. - Native route gate: Native routes are enabled only on Bun
>=1.2.3; the adapter omits theroutesoption entirely unless safe native-route entries are concretely enabled. Versioned routes,ALLhandlers, custom methods, same-shape conflicts, normalization-sensitive paths, andOPTIONS/CORS preflight stay on the fetch/shared-dispatch path. - Multipart behavior: Multipart requests never expose
rawBody, and multipart limits continue to flow through the shared runtime parser. - Startup target:
hostname,port, andtlsare forwarded toBun.serve(). Startup logs report the configured HTTP or HTTPS listen URL. - Lifecycle guards:
listen()is idempotent for an already-started adapter and keeps the original live dispatcher binding. Realtime/websocket bindings must be configured beforelisten()starts; later attempts to set or clear the binding fail fast instead of being accepted without affecting live wiring. - Shutdown ownership:
close()stops new HTTP and websocket-upgrade ingress with a503shutdown response, startsserver.stop(stopActiveConnections), and waits for Bun server termination and every accepted request from realtime binding evaluation through HTTP response or upgrade completion. The bounded timeout only rejects the caller-facingclose()promise: accepted work and adapter state remain retained until the underlying drain settles, after whichclose()clears adapter state.runBunApplication()removes its registered signal listeners whenapp.close()begins, before the adapter starts draining. - Realtime seam:
getRealtimeCapability()preserves fetch-style version 1 and exposes its optional version 1bindingInstallationcontract. Bun websocket bindings must be configured beforelisten()starts the server. The capability installer is the canonical configuration path for protocol packages and rejects values withoutfetchandwebsockethost contracts. After startup the binding remains frozen for the live server; the adapterclose()boundary clears its retained binding state after Bun termination and request drain settle. Upgrade requests are offered to the configured binding before falling back to HTTP dispatch while the adapter is accepting new ingress; an accepted request keeps its dispatcher available if shutdown begins during asynchronous binding evaluation, and HTTP fallback is suppressed only after the binding returns a response or successfully upgrades the request. The binding host exposes onlyupgrade(...), so adapter-ownedstop()and rawfetch()control remain outside the realtime seam. - Adapter instance helpers:
BunHttpApplicationAdapterexposesgetServer(),getListenTarget(),getRealtimeCapability(),configureRealtimeBinding(),configureWebSocketBinding(),listen(), andclose().
Stable diagnostic codes
Package-generated caller-visible failures retain their existing Error or TypeError class and message while exposing a stable string through error.code:
| Code | Error class | Failure |
| --- | --- | --- |
| BUN_ADAPTER_INVALID_OPTION | Error | A numeric adapter or shutdown option is outside its documented range. |
| BUN_ADAPTER_REALTIME_BINDING_INVALID | TypeError | The realtime capability installer receives a value without the required fetch and websocket contracts. |
| BUN_ADAPTER_REALTIME_BINDING_LOCKED | Error | A caller attempts to change the realtime/websocket binding after listen() starts the Bun server. |
| BUN_ADAPTER_RUNTIME_UNAVAILABLE | Error | listen() cannot find a callable globalThis.Bun.serve(). |
| BUN_ADAPTER_SHUTDOWN_TIMEOUT | Error | The caller-facing close() wait exceeds its bounded shutdown timeout. |
Errors propagated from Bun or application code keep their original class, message, and metadata instead of receiving a package-owned code.
Conformance Coverage
packages/platform-bun/src/adapter.test.ts is the package-local regression target for the documented contract. It includes Bun fetch-style portability assertions for conditional requests, single-byte ranges and If-Range, custom QUERY/extension-method fallback, malformed cookies, byte-exact JSON/text raw-body preservation, multipart raw-body exclusion for managed and custom fetch handlers, SSE framing, native-route param parity, same-path multi-method handoff, stale native handoff rematching after middleware rewrites the request path or method, versioning fallback, normalization-sensitive fallback, OPTIONS/CORS ownership, same-shape route fallback, and TLS listen-target reporting, plus focused tests for startup logging, duplicate listen idempotency, shutdown listener cleanup, in-flight drain behavior, close during asynchronous realtime binding evaluation, HTTP fallback after binding completion, timeout validation/reporting, shutdown 503 ingress rejection, signal-driven close rejection reporting, and websocket binding delegation/short-circuit behavior through an upgrade-only host.
The broader repository suite also exercises Bun through createWebRuntimeHttpAdapterPortabilityHarness(...) alongside Deno and Cloudflare Workers in packages/testing/src/portability/web-runtime-adapter-portability.test.ts, keeping the shared web-runtime portability baseline aligned across fetch-style platforms.
Related Packages
@fluojs/runtime: Core framework runtime.@fluojs/websockets: Includes specific subpath@fluojs/websockets/bun.@fluojs/socket.io: Supports the native Bun engine.
Example Sources
packages/platform-bun/src/adapter.test.tspackages/websockets/src/bun/bun.test.ts
