@mednours/backon 0.6.0 → 0.7.0

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 (68) hide show
  1. package/README.md +9 -6
  2. package/dist/auth-core.d.ts +25 -0
  3. package/dist/auth-core.d.ts.map +1 -0
  4. package/dist/create-app.d.ts +24 -0
  5. package/dist/create-app.d.ts.map +1 -0
  6. package/dist/define-route.d.ts +38 -0
  7. package/dist/define-route.d.ts.map +1 -0
  8. package/dist/error.d.ts +21 -0
  9. package/dist/error.d.ts.map +1 -0
  10. package/dist/express/create-app.d.ts +36 -0
  11. package/dist/express/create-app.d.ts.map +1 -0
  12. package/dist/express/define-route.d.ts +39 -0
  13. package/dist/express/define-route.d.ts.map +1 -0
  14. package/dist/express/index.d.ts +32 -0
  15. package/dist/express/index.d.ts.map +1 -0
  16. package/dist/express/index.js +496 -0
  17. package/dist/express/logger.d.ts +10 -0
  18. package/dist/express/logger.d.ts.map +1 -0
  19. package/dist/express/openapi.d.ts +21 -0
  20. package/dist/express/openapi.d.ts.map +1 -0
  21. package/dist/express/rate-limit.d.ts +17 -0
  22. package/dist/express/rate-limit.d.ts.map +1 -0
  23. package/dist/express/require-auth.d.ts +17 -0
  24. package/dist/express/require-auth.d.ts.map +1 -0
  25. package/dist/express/router-registry.d.ts +34 -0
  26. package/dist/express/router-registry.d.ts.map +1 -0
  27. package/dist/express/router.d.ts +11 -0
  28. package/dist/express/router.d.ts.map +1 -0
  29. package/dist/express/serve.d.ts +14 -0
  30. package/dist/express/serve.d.ts.map +1 -0
  31. package/dist/express/stream.d.ts +18 -0
  32. package/dist/express/stream.d.ts.map +1 -0
  33. package/dist/express/types.d.ts +33 -0
  34. package/dist/express/types.d.ts.map +1 -0
  35. package/dist/express/upload.d.ts +26 -0
  36. package/dist/express/upload.d.ts.map +1 -0
  37. package/dist/express/websocket.d.ts +25 -0
  38. package/dist/express/websocket.d.ts.map +1 -0
  39. package/dist/index.d.ts +32 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +429 -0
  42. package/dist/logger.d.ts +17 -0
  43. package/dist/logger.d.ts.map +1 -0
  44. package/dist/openapi-core.d.ts +51 -0
  45. package/dist/openapi-core.d.ts.map +1 -0
  46. package/dist/openapi.d.ts +22 -0
  47. package/dist/openapi.d.ts.map +1 -0
  48. package/dist/rate-limit-core.d.ts +27 -0
  49. package/dist/rate-limit-core.d.ts.map +1 -0
  50. package/dist/rate-limit.d.ts +27 -0
  51. package/dist/rate-limit.d.ts.map +1 -0
  52. package/dist/require-auth.d.ts +21 -0
  53. package/dist/require-auth.d.ts.map +1 -0
  54. package/dist/require-env.d.ts +22 -0
  55. package/dist/require-env.d.ts.map +1 -0
  56. package/dist/serve.d.ts +34 -0
  57. package/dist/serve.d.ts.map +1 -0
  58. package/dist/stream.d.ts +17 -0
  59. package/dist/stream.d.ts.map +1 -0
  60. package/dist/types.d.ts +26 -0
  61. package/dist/types.d.ts.map +1 -0
  62. package/dist/upload.d.ts +25 -0
  63. package/dist/upload.d.ts.map +1 -0
  64. package/dist/websocket.d.ts +35 -0
  65. package/dist/websocket.d.ts.map +1 -0
  66. package/package.json +55 -24
  67. package/src/serve.ts +62 -12
  68. package/src/websocket.ts +34 -9
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Plain in-memory token-bucket limiter, shared by the Hono and Express
3
+ * rate-limit middleware — the bucket bookkeeping is identical, only how
4
+ * each framework reads a request and reports 429 differs.
5
+ *
6
+ * NOTE: this is per-process state. It resets on restart and does not share
7
+ * counts across multiple instances (a multi-dyno deploy, serverless
8
+ * functions, etc). Fine for a single long-running server; for anything
9
+ * horizontally scaled, back this with Redis instead — this class exists to
10
+ * make that swap easy (same `check()` contract), not to rule it out.
11
+ */
12
+ export interface RateLimitCheckResult {
13
+ allowed: boolean;
14
+ /** Milliseconds until this key's window resets. Only meaningful when allowed is false. */
15
+ retryAfterMs: number;
16
+ }
17
+ export declare class RateLimiter {
18
+ private readonly windowMs;
19
+ private readonly max;
20
+ private readonly buckets;
21
+ private checksSinceSweep;
22
+ constructor(windowMs: number, max: number);
23
+ check(key: string, now?: number): RateLimitCheckResult;
24
+ /** Opportunistic cleanup so long-lived processes don't accumulate one bucket per distinct key forever. */
25
+ private maybeSweep;
26
+ }
27
+ //# sourceMappingURL=rate-limit-core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit-core.d.ts","sourceRoot":"","sources":["../src/rate-limit-core.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAOH,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,OAAO,CAAC;IACjB,0FAA0F;IAC1F,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,qBAAa,WAAW;IAKpB,OAAO,CAAC,QAAQ,CAAC,QAAQ;IACzB,OAAO,CAAC,QAAQ,CAAC,GAAG;IALtB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA6B;IACrD,OAAO,CAAC,gBAAgB,CAAK;gBAGV,QAAQ,EAAE,MAAM,EAChB,GAAG,EAAE,MAAM;IAG9B,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,GAAG,GAAE,MAAmB,GAAG,oBAAoB;IAiBlE,0GAA0G;IAC1G,OAAO,CAAC,UAAU;CASnB"}
@@ -0,0 +1,27 @@
1
+ import type { Context, Next } from "hono";
2
+ import type { Env } from "./types";
3
+ export interface RateLimitOptions {
4
+ /** Window size in ms. Defaults to 60_000 (1 minute). */
5
+ windowMs?: number;
6
+ /** Max requests allowed per key within the window. Defaults to 60. */
7
+ max?: number;
8
+ /** How to derive the bucket key from a request. Defaults to the caller's IP. */
9
+ keyGenerator?: (c: Context<Env>) => string;
10
+ }
11
+ /**
12
+ * In-memory token-bucket rate limiter. Throws AppError(429, "rate_limited")
13
+ * once a key exceeds `max` requests in the current window, with a
14
+ * Retry-After header set to when the window resets.
15
+ *
16
+ * NOTE: per-process state — resets on restart, and doesn't share counts
17
+ * across multiple instances or serverless invocations. Fine for a single
18
+ * long-running server; for anything horizontally scaled, swap in a
19
+ * Redis-backed limiter instead.
20
+ *
21
+ * Apply per-route or per-group, not necessarily globally — a login route
22
+ * usually wants a tighter limit than the rest of the API:
23
+ *
24
+ * auth.use("/login", rateLimit({ windowMs: 60_000, max: 5 }));
25
+ */
26
+ export declare function rateLimit(options?: RateLimitOptions): (c: Context<Env>, next: Next) => Promise<void>;
27
+ //# sourceMappingURL=rate-limit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../src/rate-limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAInC,MAAM,WAAW,gBAAgB;IAC/B,wDAAwD;IACxD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,gFAAgF;IAChF,YAAY,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,KAAK,MAAM,CAAC;CAC5C;AAKD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,IAIZ,GAAG,OAAO,CAAC,GAAG,CAAC,EAAE,MAAM,IAAI,mBAUtE"}
@@ -0,0 +1,21 @@
1
+ import type { Context, Next } from "hono";
2
+ import type { Env } from "./types";
3
+ import { type VerifyJwtOptions } from "./auth-core";
4
+ /**
5
+ * Verifies a bearer JWT and stashes the decoded payload on the context as
6
+ * `auth`, retrievable in any handler downstream via `c.get("auth")`. Throws
7
+ * AppError(401, "unauthorized") if the header is missing, malformed, or the
8
+ * token fails verification (bad signature, expired, wrong algorithm) —
9
+ * createApp()'s error handler turns that into the standard error JSON shape,
10
+ * same as any other AppError.
11
+ *
12
+ * This is verification only: issuing tokens (login, signup, refresh
13
+ * rotation, revocation) is left to the consuming project, since that's
14
+ * genuinely different per project and baking in an opinion there risks
15
+ * being wrong for whatever project actually uses it. Apply it per-route or
16
+ * per-group, not globally:
17
+ *
18
+ * protectedRoutes.use("*", requireAuth({ secret: process.env.JWT_SECRET! }));
19
+ */
20
+ export declare function requireAuth(options: VerifyJwtOptions): (c: Context<Env>, next: Next) => Promise<void>;
21
+ //# sourceMappingURL=require-auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"require-auth.d.ts","sourceRoot":"","sources":["../src/require-auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,OAAO,EAAiC,KAAK,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEnF;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,gBAAgB,IACP,GAAG,OAAO,CAAC,GAAG,CAAC,EAAE,MAAM,IAAI,mBAexE"}
@@ -0,0 +1,22 @@
1
+ import type { ZodType } from "zod";
2
+ /**
3
+ * Validates process.env against a Zod schema once, at startup, and returns
4
+ * the parsed result. Fails fast with every missing/invalid var named in one
5
+ * error, instead of the app booting cleanly and only crashing later on
6
+ * whichever request happens to be the first to touch a var nobody set.
7
+ *
8
+ * Usage, typically in src/config/env.ts:
9
+ *
10
+ * import { z } from "zod";
11
+ * import { requireEnv } from "@mednours/backon";
12
+ *
13
+ * export const env = requireEnv(z.object({
14
+ * DATABASE_URL: z.string().url(),
15
+ * PORT: z.coerce.number().default(3000),
16
+ * }));
17
+ *
18
+ * `env.DATABASE_URL` is then typed as `string`, not `string | undefined` —
19
+ * everywhere else in the app can trust it's actually there.
20
+ */
21
+ export declare function requireEnv<T>(schema: ZodType<T>): T;
22
+ //# sourceMappingURL=require-env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"require-env.d.ts","sourceRoot":"","sources":["../src/require-env.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AAEnC;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CASnD"}
@@ -0,0 +1,34 @@
1
+ import type { Hono } from "hono";
2
+ import type { Env } from "./types";
3
+ /** The bits of Bun's/`@hono/node-server`'s return value shutdown actually needs — not either library's real type, just the overlap. */
4
+ interface StoppableServer {
5
+ stop?: () => void;
6
+ close?: (callback?: (err?: Error) => void) => void;
7
+ }
8
+ /**
9
+ * Starts the app — `Bun.serve()` when running under Bun (the default, and
10
+ * the faster of the two), `@hono/node-server`'s `serve()` when running
11
+ * under Node — and wires graceful shutdown either way: on SIGTERM/SIGINT,
12
+ * stop accepting new connections, let in-flight requests finish, then
13
+ * exit. Matters for zero-downtime deploys — without this, a deploy or
14
+ * restart can cut off requests mid-flight.
15
+ *
16
+ * Both `hono/bun` (for the websocket handler Bun.serve() needs to complete
17
+ * a defineWebSocket() route's upgrade handshake) and `@hono/node-server`
18
+ * are dynamically imported, and only on the runtime that actually needs
19
+ * them — `hono/bun` throws immediately on import under Node (it touches
20
+ * the `Bun` global at module scope), so it can't be a static import at the
21
+ * top of this file the way it used to be, or importing @mednours/backon at
22
+ * all would crash under Node before serve() was ever called. This is also
23
+ * why serve() is async now, unlike earlier versions — see the 0.7.0
24
+ * CHANGELOG entry.
25
+ *
26
+ * `@hono/node-server` is an optional peer dependency: Bun-only projects
27
+ * never need it installed at all, and `npm install @hono/node-server` is
28
+ * only required the first time this actually runs under Node.
29
+ */
30
+ export declare function serve(app: Hono<Env>, port?: number): Promise<StoppableServer>;
31
+ export declare function serveOnBun(app: Hono<Env>, port: number): Promise<StoppableServer>;
32
+ export declare function serveOnNode(app: Hono<Env>, port: number): Promise<StoppableServer>;
33
+ export {};
34
+ //# sourceMappingURL=serve.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../src/serve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAEjC,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,uIAAuI;AACvI,UAAU,eAAe;IACvB,IAAI,CAAC,EAAE,MAAM,IAAI,CAAC;IAClB,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,KAAK,KAAK,IAAI,KAAK,IAAI,CAAC;CACpD;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,KAAK,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,GAAE,MAAyC,4BAuB1F;AAWD,wBAAsB,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAGvF;AAED,wBAAsB,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAWxF"}
@@ -0,0 +1,17 @@
1
+ import type { BackonContext } from "./types";
2
+ export type StreamWriter = (chunk: string | Uint8Array) => Promise<void>;
3
+ /**
4
+ * Registers a route that writes its response in chunks as they become
5
+ * available, instead of building one body in memory and returning it all at
6
+ * once — server-sent events, a large export, anything too slow or too big
7
+ * to buffer first.
8
+ *
9
+ * app.get("/export", defineStream(async (c, write) => {
10
+ * for (const row of rows) await write(JSON.stringify(row) + "\n");
11
+ * }));
12
+ *
13
+ * Set a Content-Type via c.header() before the first write() if the default
14
+ * (left to the browser/client to infer) isn't right for what's being sent.
15
+ */
16
+ export declare function defineStream(handler: (c: BackonContext, write: StreamWriter) => Promise<void>): (c: BackonContext) => Response;
17
+ //# sourceMappingURL=stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../src/stream.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAE7C,MAAM,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAEzE;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,aAAa,EAAE,KAAK,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,IACpF,GAAG,aAAa,cAMzB"}
@@ -0,0 +1,26 @@
1
+ import type { Context } from "hono";
2
+ import type { JWTPayload } from "hono/utils/jwt/types";
3
+ /**
4
+ * Hono's own generics for per-request state (c.get/c.set). Extend this as
5
+ * createApp() grows more built-in middleware that stashes request-scoped
6
+ * data.
7
+ */
8
+ export interface Env {
9
+ Variables: {
10
+ requestId: string;
11
+ /** Set by requireAuth() middleware; undefined on any route it hasn't run on. */
12
+ auth?: JWTPayload;
13
+ };
14
+ }
15
+ /**
16
+ * BackonContext is, for now, a direct alias of Hono's own Context. That's a
17
+ * deliberate choice, not an oversight: the real framework-agnostic boundary
18
+ * (the seam that would let an Express adapter produce the same shape) only
19
+ * gets designed once that adapter is actually being built. Guessing at that
20
+ * abstraction now, before a second implementation exists to validate it
21
+ * against, tends to mean rebuilding it anyway. Until then, this alias
22
+ * exists so call sites already say `BackonContext` instead of `Context`,
23
+ * which is the only part that needs to stay stable.
24
+ */
25
+ export type BackonContext = Context<Env>;
26
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEvD;;;;GAIG;AACH,MAAM,WAAW,GAAG;IAClB,SAAS,EAAE;QACT,SAAS,EAAE,MAAM,CAAC;QAClB,gFAAgF;QAChF,IAAI,CAAC,EAAE,UAAU,CAAC;KACnB,CAAC;CACH;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC"}
@@ -0,0 +1,25 @@
1
+ import type { BackonContext } from "./types";
2
+ export interface UploadOptions {
3
+ /** Rejects any file over this size with a 400. Unset means no limit. */
4
+ maxFileSizeBytes?: number;
5
+ /** Rejects any file whose type isn't in this list with a 400. Unset means no restriction. */
6
+ allowedMimeTypes?: string[];
7
+ }
8
+ export type UploadHandler = (c: BackonContext, data: {
9
+ files: Record<string, File[]>;
10
+ }) => Response | Promise<Response>;
11
+ /**
12
+ * Parses a multipart/form-data request, validating each file against
13
+ * `maxFileSizeBytes`/`allowedMimeTypes` before the handler runs — the same
14
+ * "validate first, throw AppError(400, ...) on failure" contract as
15
+ * defineRoute(), just for files instead of a JSON body. Fields uploaded more
16
+ * than once under the same name all land under that field's array, same as
17
+ * a single file — `files.avatar` is always an array, even with one file.
18
+ *
19
+ * app.post("/avatar", defineUpload(
20
+ * { maxFileSizeBytes: 2 * 1024 * 1024, allowedMimeTypes: ["image/png", "image/jpeg"] },
21
+ * async (c, { files }) => c.json({ uploaded: files.avatar.length })
22
+ * ));
23
+ */
24
+ export declare function defineUpload(options: UploadOptions, handler: UploadHandler): (c: BackonContext) => Promise<Response>;
25
+ //# sourceMappingURL=upload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../src/upload.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAO7C,MAAM,WAAW,aAAa;IAC5B,wEAAwE;IACxE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,6FAA6F;IAC7F,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;CAC7B;AAED,MAAM,MAAM,aAAa,GAAG,CAC1B,CAAC,EAAE,aAAa,EAChB,IAAI,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAA;CAAE,KACpC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AAElC;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,aAAa,IAC3D,GAAG,aAAa,KAAG,OAAO,CAAC,QAAQ,CAAC,CA2BnD"}
@@ -0,0 +1,35 @@
1
+ import type { Context } from "hono";
2
+ import type { WSContext, WSMessageReceive } from "hono/ws";
3
+ import type { Env } from "./types";
4
+ /** Handlers for one WebSocket route. `ws.send()`/`ws.close()` match the shape the Express adapter's handlers get, too. */
5
+ export interface WebSocketHandlers {
6
+ onOpen?: (ws: WSContext) => void;
7
+ onMessage?: (ws: WSContext, data: WSMessageReceive) => void;
8
+ onClose?: (ws: WSContext) => void;
9
+ }
10
+ /**
11
+ * Registers a WebSocket route. The handshake happens at Bun.serve()'s own
12
+ * level (an HTTP upgrade, not an ordinary request/response cycle), which is
13
+ * why this only works when the app is actually run with this package's
14
+ * serve() on Bun — it passes hono/bun's own websocket handler into
15
+ * Bun.serve() so the upgrade can actually happen. `@hono/node-server`
16
+ * support for the same handshake isn't wired up here yet, so a
17
+ * defineWebSocket() route throws a clear error at request time (not at
18
+ * startup — the rest of the app still runs) if it's ever actually hit
19
+ * under Node, rather than failing in some more confusing way.
20
+ *
21
+ * hono/bun is imported dynamically, at request time, specifically so
22
+ * *importing* this module (and therefore @mednours/backon's main index,
23
+ * which re-exports defineWebSocket) doesn't itself crash under Node —
24
+ * hono/bun touches the `Bun` global at module scope, so a static import at
25
+ * the top of this file would throw the moment anything imported this
26
+ * package at all, whether or not the project actually uses WebSockets.
27
+ *
28
+ * Register it like any other route:
29
+ *
30
+ * app.get("/ws", defineWebSocket({
31
+ * onMessage: (ws, data) => ws.send(`echo: ${data}`),
32
+ * }));
33
+ */
34
+ export declare function defineWebSocket(handlers: WebSocketHandlers): (c: Context<Env>) => Promise<void | Response>;
35
+ //# sourceMappingURL=websocket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../src/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACpC,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAC3D,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC,0HAA0H;AAC1H,MAAM,WAAW,iBAAiB;IAChC,MAAM,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAC5D,OAAO,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,KAAK,IAAI,CAAC;CACnC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,iBAAiB,IAC3C,GAAG,OAAO,CAAC,GAAG,CAAC,8BAgB9B"}
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@mednours/backon",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
- "description": "Opinionated backend framework wrapper for Bun. Wraps Hono (default) or Express (via @mednours/backon/express) with the same baked-in security, logging, and validation defaults.",
5
+ "description": "Opinionated backend framework wrapper, Bun-first but Node-compatible. Wraps Hono (default) or Express (via @mednours/backon/express) with the same baked-in security, logging, and validation defaults.",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/mednours/backon/tree/main/packages/backon#readme",
8
8
  "repository": {
@@ -12,23 +12,36 @@
12
12
  },
13
13
  "bugs": "https://github.com/mednours/backon/issues",
14
14
  "engines": {
15
- "bun": ">=1.3.0"
15
+ "bun": ">=1.3.0",
16
+ "node": ">=18.14.1"
16
17
  },
17
18
  "publishConfig": {
18
19
  "access": "public"
19
20
  },
20
- "module": "src/index.ts",
21
- "types": "src/index.ts",
21
+ "module": "dist/index.js",
22
+ "main": "dist/index.js",
23
+ "types": "dist/index.d.ts",
22
24
  "exports": {
23
- ".": "./src/index.ts",
24
- "./express": "./src/express/index.ts"
25
+ ".": {
26
+ "bun": "./src/index.ts",
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ },
30
+ "./express": {
31
+ "bun": "./src/express/index.ts",
32
+ "types": "./dist/express/index.d.ts",
33
+ "default": "./dist/express/index.js"
34
+ }
25
35
  },
26
- "files": ["src"],
36
+ "files": ["src", "dist"],
27
37
  "scripts": {
28
38
  "dev": "bun run --watch examples/dev-server.ts",
29
39
  "dev:express": "bun run --watch examples/dev-server-express.ts",
30
40
  "test": "bun test",
31
- "typecheck": "tsc --noEmit"
41
+ "typecheck": "tsc --noEmit",
42
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && bun run build:js",
43
+ "build:js": "esbuild src/index.ts src/express/index.ts --outdir=dist --outbase=src --bundle --platform=node --format=esm --target=node18 --packages=external",
44
+ "prepublishOnly": "bun run typecheck && bun run test && bun run build"
32
45
  },
33
46
  "dependencies": {
34
47
  "hono": "^4.6.14",
@@ -42,31 +55,49 @@
42
55
  "helmet": "^8.0.0",
43
56
  "compression": "^1.7.5",
44
57
  "ws": "^8.18.0",
45
- "multer": "^1.4.5"
58
+ "multer": "^1.4.5",
59
+ "@hono/node-server": "^2.0.0"
46
60
  },
47
61
  "peerDependenciesMeta": {
48
- "express": { "optional": true },
49
- "cors": { "optional": true },
50
- "helmet": { "optional": true },
51
- "compression": { "optional": true },
52
- "ws": { "optional": true },
53
- "multer": { "optional": true }
62
+ "express": {
63
+ "optional": true
64
+ },
65
+ "cors": {
66
+ "optional": true
67
+ },
68
+ "helmet": {
69
+ "optional": true
70
+ },
71
+ "compression": {
72
+ "optional": true
73
+ },
74
+ "ws": {
75
+ "optional": true
76
+ },
77
+ "multer": {
78
+ "optional": true
79
+ },
80
+ "@hono/node-server": {
81
+ "optional": true
82
+ }
54
83
  },
55
84
  "devDependencies": {
85
+ "@hono/node-server": "^2.1.1",
56
86
  "@types/bun": "latest",
57
- "@types/express": "^4.17.21",
58
- "@types/cors": "^2.8.17",
59
87
  "@types/compression": "^1.7.5",
88
+ "@types/cors": "^2.8.17",
89
+ "@types/express": "^4.17.21",
90
+ "@types/multer": "^1.4.12",
60
91
  "@types/supertest": "^6.0.2",
61
92
  "@types/ws": "^8.5.13",
62
- "@types/multer": "^1.4.12",
63
- "typescript": "^5.7.2",
64
- "express": "^4.21.0",
93
+ "compression": "^1.7.5",
65
94
  "cors": "^2.8.5",
95
+ "esbuild": "^0.28.2",
96
+ "express": "^4.21.0",
66
97
  "helmet": "^8.0.0",
67
- "compression": "^1.7.5",
68
- "ws": "^8.18.0",
69
98
  "multer": "^1.4.5-lts.1",
70
- "supertest": "^7.0.0"
99
+ "supertest": "^7.0.0",
100
+ "typescript": "^5.7.2",
101
+ "ws": "^8.18.0"
71
102
  }
72
103
  }
package/src/serve.ts CHANGED
@@ -1,28 +1,51 @@
1
1
  import type { Hono } from "hono";
2
- import { websocket } from "hono/bun";
3
2
  import { logger } from "./logger";
4
3
  import type { Env } from "./types";
5
4
 
5
+ /** The bits of Bun's/`@hono/node-server`'s return value shutdown actually needs — not either library's real type, just the overlap. */
6
+ interface StoppableServer {
7
+ stop?: () => void;
8
+ close?: (callback?: (err?: Error) => void) => void;
9
+ }
10
+
6
11
  /**
7
- * Starts the app on Bun's native server and wires graceful shutdown: on
8
- * SIGTERM/SIGINT, stop accepting new connections, let in-flight requests
9
- * finish, then exit. Matters for zero-downtime deploys — without this, a
10
- * deploy or restart can cut off requests mid-flight.
12
+ * Starts the app — `Bun.serve()` when running under Bun (the default, and
13
+ * the faster of the two), `@hono/node-server`'s `serve()` when running
14
+ * under Node — and wires graceful shutdown either way: on SIGTERM/SIGINT,
15
+ * stop accepting new connections, let in-flight requests finish, then
16
+ * exit. Matters for zero-downtime deploys — without this, a deploy or
17
+ * restart can cut off requests mid-flight.
18
+ *
19
+ * Both `hono/bun` (for the websocket handler Bun.serve() needs to complete
20
+ * a defineWebSocket() route's upgrade handshake) and `@hono/node-server`
21
+ * are dynamically imported, and only on the runtime that actually needs
22
+ * them — `hono/bun` throws immediately on import under Node (it touches
23
+ * the `Bun` global at module scope), so it can't be a static import at the
24
+ * top of this file the way it used to be, or importing @mednours/backon at
25
+ * all would crash under Node before serve() was ever called. This is also
26
+ * why serve() is async now, unlike earlier versions — see the 0.7.0
27
+ * CHANGELOG entry.
11
28
  *
12
- * Also passes hono/bun's own websocket handler into Bun.serve() — needed
13
- * for any defineWebSocket() route to actually complete its upgrade
14
- * handshake, and harmless when there are none.
29
+ * `@hono/node-server` is an optional peer dependency: Bun-only projects
30
+ * never need it installed at all, and `npm install @hono/node-server` is
31
+ * only required the first time this actually runs under Node.
15
32
  */
16
- export function serve(app: Hono<Env>, port: number = Number(process.env.PORT) || 3000) {
17
- const server = Bun.serve({ fetch: app.fetch, websocket, port });
18
- logger.info({ port }, "backon app listening");
33
+ export async function serve(app: Hono<Env>, port: number = Number(process.env.PORT) || 3000) {
34
+ const isBun = typeof Bun !== "undefined";
35
+ const server: StoppableServer = isBun ? await serveOnBun(app, port) : await serveOnNode(app, port);
36
+
37
+ logger.info({ port, runtime: isBun ? "bun" : "node" }, "backon app listening");
19
38
 
20
39
  let shuttingDown = false;
21
40
  const shutdown = (signal: string) => {
22
41
  if (shuttingDown) return;
23
42
  shuttingDown = true;
24
43
  logger.info({ signal }, "shutting down");
25
- server.stop(); // stop accepting new connections; lets in-flight requests finish
44
+ // Bun.serve()'s stop() and @hono/node-server's close() are both
45
+ // "stop accepting new connections, let in-flight ones finish" — same
46
+ // intent, different method name depending which one is present.
47
+ server.stop?.();
48
+ server.close?.();
26
49
  process.exit(0);
27
50
  };
28
51
 
@@ -31,3 +54,30 @@ export function serve(app: Hono<Env>, port: number = Number(process.env.PORT) ||
31
54
 
32
55
  return server;
33
56
  }
57
+
58
+ // Exported (not just internal to serve()) mainly so each runtime's path can
59
+ // be exercised directly in tests without needing to fake away the `Bun`
60
+ // global — it isn't writable/deletable, so a test can't actually simulate
61
+ // "no Bun" from inside a process Bun itself started. Calling serveOnNode()
62
+ // straight from a Bun-run test still genuinely exercises the same code
63
+ // this function runs under real Node — nothing in its body is
64
+ // runtime-conditional. Also usable directly by anyone who wants to skip
65
+ // the detection, e.g. a Node-only serverless entry point.
66
+
67
+ export async function serveOnBun(app: Hono<Env>, port: number): Promise<StoppableServer> {
68
+ const { websocket } = await import("hono/bun");
69
+ return Bun.serve({ fetch: app.fetch, websocket, port });
70
+ }
71
+
72
+ export async function serveOnNode(app: Hono<Env>, port: number): Promise<StoppableServer> {
73
+ let nodeServer: typeof import("@hono/node-server");
74
+ try {
75
+ nodeServer = await import("@hono/node-server");
76
+ } catch {
77
+ throw new Error(
78
+ "serve() needs @hono/node-server to run under Node — install it with `npm install @hono/node-server` " +
79
+ "(or your package manager's equivalent). Bun doesn't need this; it uses Bun.serve() instead."
80
+ );
81
+ }
82
+ return nodeServer.serve({ fetch: app.fetch, port });
83
+ }
package/src/websocket.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { upgradeWebSocket } from "hono/bun";
1
+ import type { Context } from "hono";
2
2
  import type { WSContext, WSMessageReceive } from "hono/ws";
3
+ import type { Env } from "./types";
3
4
 
4
5
  /** Handlers for one WebSocket route. `ws.send()`/`ws.close()` match the shape the Express adapter's handlers get, too. */
5
6
  export interface WebSocketHandlers {
@@ -11,18 +12,42 @@ export interface WebSocketHandlers {
11
12
  /**
12
13
  * Registers a WebSocket route. The handshake happens at Bun.serve()'s own
13
14
  * level (an HTTP upgrade, not an ordinary request/response cycle), which is
14
- * why this only works with the serve() this package exports — it passes
15
- * hono/bun's own websocket handler into Bun.serve() so the upgrade can
16
- * actually happen. Register it like any other route:
15
+ * why this only works when the app is actually run with this package's
16
+ * serve() on Bun — it passes hono/bun's own websocket handler into
17
+ * Bun.serve() so the upgrade can actually happen. `@hono/node-server`
18
+ * support for the same handshake isn't wired up here yet, so a
19
+ * defineWebSocket() route throws a clear error at request time (not at
20
+ * startup — the rest of the app still runs) if it's ever actually hit
21
+ * under Node, rather than failing in some more confusing way.
22
+ *
23
+ * hono/bun is imported dynamically, at request time, specifically so
24
+ * *importing* this module (and therefore @mednours/backon's main index,
25
+ * which re-exports defineWebSocket) doesn't itself crash under Node —
26
+ * hono/bun touches the `Bun` global at module scope, so a static import at
27
+ * the top of this file would throw the moment anything imported this
28
+ * package at all, whether or not the project actually uses WebSockets.
29
+ *
30
+ * Register it like any other route:
17
31
  *
18
32
  * app.get("/ws", defineWebSocket({
19
33
  * onMessage: (ws, data) => ws.send(`echo: ${data}`),
20
34
  * }));
21
35
  */
22
36
  export function defineWebSocket(handlers: WebSocketHandlers) {
23
- return upgradeWebSocket(() => ({
24
- onOpen: (_event, ws) => handlers.onOpen?.(ws),
25
- onMessage: (event, ws) => handlers.onMessage?.(ws, event.data),
26
- onClose: (_event, ws) => handlers.onClose?.(ws),
27
- }));
37
+ return async (c: Context<Env>) => {
38
+ if (typeof Bun === "undefined") {
39
+ throw new Error(
40
+ "defineWebSocket() only works when this app is running on Bun — it relies on hono/bun's upgrade " +
41
+ "handshake, which backon doesn't yet have a Node equivalent for. Run this project on Bun, or drop the " +
42
+ "WebSocket route for a Node deploy."
43
+ );
44
+ }
45
+ const { upgradeWebSocket } = await import("hono/bun");
46
+ const handler = upgradeWebSocket(() => ({
47
+ onOpen: (_event, ws) => handlers.onOpen?.(ws),
48
+ onMessage: (event, ws) => handlers.onMessage?.(ws, event.data),
49
+ onClose: (_event, ws) => handlers.onClose?.(ws),
50
+ }));
51
+ return handler(c, async () => {});
52
+ };
28
53
  }