@mednours/backon 0.1.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.
- package/LICENSE +21 -0
- package/README.md +82 -0
- package/package.json +63 -0
- package/src/create-app.ts +86 -0
- package/src/define-route.ts +74 -0
- package/src/error.ts +28 -0
- package/src/express/create-app.ts +96 -0
- package/src/express/define-route.ts +77 -0
- package/src/express/index.ts +20 -0
- package/src/express/logger.ts +27 -0
- package/src/express/serve.ts +33 -0
- package/src/express/types.ts +49 -0
- package/src/index.ts +23 -0
- package/src/logger.ts +40 -0
- package/src/serve.ts +28 -0
- package/src/types.ts +24 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nour Sabir
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# @mednours/backon
|
|
2
|
+
|
|
3
|
+
Opinionated backend framework wrapper for Bun. Two adapters, same names,
|
|
4
|
+
same JSON error shape, same defaults — pick per project:
|
|
5
|
+
|
|
6
|
+
- `@mednours/backon` (default export) — wraps [Hono](https://hono.dev)
|
|
7
|
+
- `@mednours/backon/express` — wraps [Express](https://expressjs.com); requires `express`, `cors`, `helmet`, and `compression` as peer dependencies in your own project
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
bun add @mednours/backon
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { createApp, defineRoute, serve } from "@mednours/backon";
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
|
|
21
|
+
const app = createApp();
|
|
22
|
+
|
|
23
|
+
app.get(
|
|
24
|
+
"/hello",
|
|
25
|
+
defineRoute({ query: z.object({ name: z.string().optional() }) }, (c, { query }) =>
|
|
26
|
+
c.json({ message: `hello ${query.name ?? "world"}` })
|
|
27
|
+
)
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
serve(app);
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## What `createApp()` wires in by default
|
|
34
|
+
|
|
35
|
+
- Structured request logging ([pino](https://getpino.io)) with a request id on every response
|
|
36
|
+
- Secure response headers
|
|
37
|
+
- CORS locked to an `ALLOWED_ORIGINS` allowlist — closed by default, not open
|
|
38
|
+
- Response compression
|
|
39
|
+
- A 1mb request body size cap (413 on overflow)
|
|
40
|
+
- An auto-registered `GET /health`
|
|
41
|
+
- A central error handler: throw `AppError(statusCode, code, message, details?)` for expected failures, anything else becomes a generic 500 with internals never leaked to the client
|
|
42
|
+
|
|
43
|
+
## `defineRoute(schema, handler)`
|
|
44
|
+
|
|
45
|
+
Validates `body`/`query`/`params` against Zod schemas before your handler runs, and hands the handler already-parsed, typed data. On failure it throws `AppError(400, "invalid_body" | "invalid_query" | "invalid_params", ...)` with the Zod error attached as `details`, caught automatically by `createApp()`'s error handler.
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
app.post(
|
|
49
|
+
"/users",
|
|
50
|
+
defineRoute({ body: z.object({ name: z.string() }) }, async (c, { body }) => {
|
|
51
|
+
return c.json({ id: crypto.randomUUID(), name: body.name }, 201);
|
|
52
|
+
})
|
|
53
|
+
);
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## `serve(app)`
|
|
57
|
+
|
|
58
|
+
Runs on Bun's native server (Express adapter: Node's http server via Express's own `app.listen`) with graceful shutdown wired to `SIGTERM`/`SIGINT` — new connections stop being accepted and in-flight requests finish before exit.
|
|
59
|
+
|
|
60
|
+
**Express-specific:** `serve(app)` also registers the central error handler for you. Do this *after* every route is registered, not inside `createApp()` — Express's error-handling middleware only catches errors from routes registered *before* it, the opposite of Hono's `onError()`. If you're not using this `serve()` (wrapping the app for a serverless platform, or a `supertest` suite), call `attachErrorHandler(app)` yourself, after your routes.
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
import { createApp, defineRoute, serve } from "@mednours/backon/express";
|
|
64
|
+
import { z } from "zod";
|
|
65
|
+
|
|
66
|
+
const app = createApp();
|
|
67
|
+
|
|
68
|
+
app.get(
|
|
69
|
+
"/hello",
|
|
70
|
+
defineRoute({ query: z.object({ name: z.string().optional() }) }, (c, { query }) =>
|
|
71
|
+
c.json({ message: `hello ${query.name ?? "world"}` })
|
|
72
|
+
)
|
|
73
|
+
);
|
|
74
|
+
|
|
75
|
+
serve(app); // attaches the error handler, then app.listen()
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Requirements
|
|
79
|
+
|
|
80
|
+
Bun >= 1.3. This package ships TypeScript source directly (no build step) since it's Bun-only by design.
|
|
81
|
+
|
|
82
|
+
Part of the [backon monorepo](https://github.com/mednours/backon) — see [`create-backon`](https://www.npmjs.com/package/create-backon) to scaffold a new project on top of this.
|
package/package.json
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mednours/backon",
|
|
3
|
+
"version": "0.1.0",
|
|
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.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"homepage": "https://github.com/mednours/backon/tree/main/packages/backon#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/mednours/backon.git",
|
|
11
|
+
"directory": "packages/backon"
|
|
12
|
+
},
|
|
13
|
+
"bugs": "https://github.com/mednours/backon/issues",
|
|
14
|
+
"engines": {
|
|
15
|
+
"bun": ">=1.3.0"
|
|
16
|
+
},
|
|
17
|
+
"publishConfig": {
|
|
18
|
+
"access": "public"
|
|
19
|
+
},
|
|
20
|
+
"module": "src/index.ts",
|
|
21
|
+
"types": "src/index.ts",
|
|
22
|
+
"exports": {
|
|
23
|
+
".": "./src/index.ts",
|
|
24
|
+
"./express": "./src/express/index.ts"
|
|
25
|
+
},
|
|
26
|
+
"files": ["src"],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"dev": "bun run --watch examples/dev-server.ts",
|
|
29
|
+
"dev:express": "bun run --watch examples/dev-server-express.ts",
|
|
30
|
+
"test": "bun test",
|
|
31
|
+
"typecheck": "tsc --noEmit"
|
|
32
|
+
},
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"hono": "^4.6.14",
|
|
35
|
+
"pino": "^9.5.0",
|
|
36
|
+
"zod": "^3.24.1"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"express": "^4.21.0",
|
|
40
|
+
"cors": "^2.8.5",
|
|
41
|
+
"helmet": "^8.0.0",
|
|
42
|
+
"compression": "^1.7.5"
|
|
43
|
+
},
|
|
44
|
+
"peerDependenciesMeta": {
|
|
45
|
+
"express": { "optional": true },
|
|
46
|
+
"cors": { "optional": true },
|
|
47
|
+
"helmet": { "optional": true },
|
|
48
|
+
"compression": { "optional": true }
|
|
49
|
+
},
|
|
50
|
+
"devDependencies": {
|
|
51
|
+
"@types/bun": "latest",
|
|
52
|
+
"@types/express": "^4.17.21",
|
|
53
|
+
"@types/cors": "^2.8.17",
|
|
54
|
+
"@types/compression": "^1.7.5",
|
|
55
|
+
"@types/supertest": "^6.0.2",
|
|
56
|
+
"typescript": "^5.7.2",
|
|
57
|
+
"express": "^4.21.0",
|
|
58
|
+
"cors": "^2.8.5",
|
|
59
|
+
"helmet": "^8.0.0",
|
|
60
|
+
"compression": "^1.7.5",
|
|
61
|
+
"supertest": "^7.0.0"
|
|
62
|
+
}
|
|
63
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { Hono } from "hono";
|
|
2
|
+
import { secureHeaders } from "hono/secure-headers";
|
|
3
|
+
import { cors } from "hono/cors";
|
|
4
|
+
import { compress } from "hono/compress";
|
|
5
|
+
import { bodyLimit } from "hono/body-limit";
|
|
6
|
+
import { AppError } from "./error";
|
|
7
|
+
import { logger, requestLogger } from "./logger";
|
|
8
|
+
import type { Env } from "./types";
|
|
9
|
+
|
|
10
|
+
export interface CreateAppOptions {
|
|
11
|
+
/**
|
|
12
|
+
* Allowed CORS origins. Defaults to the ALLOWED_ORIGINS env var
|
|
13
|
+
* (comma-separated), and to no origins at all if that's unset — closed by
|
|
14
|
+
* default rather than wide open.
|
|
15
|
+
*/
|
|
16
|
+
allowedOrigins?: string[];
|
|
17
|
+
/** Max request body size in bytes. Defaults to 1mb. */
|
|
18
|
+
bodyLimitBytes?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024; // 1mb
|
|
22
|
+
|
|
23
|
+
function resolveAllowedOrigins(options: CreateAppOptions): string[] {
|
|
24
|
+
if (options.allowedOrigins) return options.allowedOrigins;
|
|
25
|
+
const fromEnv = process.env.ALLOWED_ORIGINS;
|
|
26
|
+
return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()) : [];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Builds a Hono app pre-wired with backon's opinionated defaults: request
|
|
31
|
+
* logging, secure headers, CORS locked to an allowlist, response
|
|
32
|
+
* compression, a body size cap, a /health route, and a central error handler
|
|
33
|
+
* that turns AppError (or anything else) into a consistent JSON shape.
|
|
34
|
+
*
|
|
35
|
+
* This is the "small opinionated helpers" layer agreed on for v1 — enough to
|
|
36
|
+
* be worth having your own package instead of importing hono directly,
|
|
37
|
+
* without trying to cover every possible use case up front.
|
|
38
|
+
*/
|
|
39
|
+
export function createApp(options: CreateAppOptions = {}) {
|
|
40
|
+
const app = new Hono<Env>();
|
|
41
|
+
|
|
42
|
+
app.use("*", requestLogger);
|
|
43
|
+
app.use("*", secureHeaders());
|
|
44
|
+
app.use(
|
|
45
|
+
"*",
|
|
46
|
+
cors({
|
|
47
|
+
origin: resolveAllowedOrigins(options),
|
|
48
|
+
})
|
|
49
|
+
);
|
|
50
|
+
app.use("*", compress());
|
|
51
|
+
app.use(
|
|
52
|
+
"*",
|
|
53
|
+
bodyLimit({
|
|
54
|
+
maxSize: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES,
|
|
55
|
+
onError: (c) =>
|
|
56
|
+
c.json({ error: { code: "payload_too_large", message: "Request body too large" } }, 413),
|
|
57
|
+
})
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
// Registered here, before createApp() returns, so it always gets the
|
|
61
|
+
// middleware above (logging, secure headers, CORS, compression, body
|
|
62
|
+
// limit). It deliberately does NOT get middleware you add afterward in
|
|
63
|
+
// your own app.ts (app.use('*', yourMiddleware) only wraps routes
|
|
64
|
+
// registered after that call) — verified by hand, this is Hono's own
|
|
65
|
+
// registration-order behavior, not something backon adds. That's the
|
|
66
|
+
// right default for a liveness check: an uptime monitor shouldn't get
|
|
67
|
+
// blocked by app-specific middleware like auth. If you want /health
|
|
68
|
+
// behind your own middleware too, register your own route instead of
|
|
69
|
+
// relying on this one.
|
|
70
|
+
app.get("/health", (c) => c.json({ status: "ok" }));
|
|
71
|
+
|
|
72
|
+
app.onError((err, c) => {
|
|
73
|
+
if (err instanceof AppError) {
|
|
74
|
+
logger.warn({ requestId: c.get("requestId"), code: err.code, details: err.details }, err.message);
|
|
75
|
+
return c.json(
|
|
76
|
+
{ error: { code: err.code, message: err.message, details: err.details } },
|
|
77
|
+
err.statusCode as any
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
logger.error({ requestId: c.get("requestId"), err }, "unhandled error");
|
|
82
|
+
return c.json({ error: { code: "internal_error", message: "Something went wrong" } }, 500);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
return app;
|
|
86
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { ZodType } from "zod";
|
|
2
|
+
import { AppError } from "./error";
|
|
3
|
+
import type { BackonContext } from "./types";
|
|
4
|
+
|
|
5
|
+
/** Zod schemas for the parts of a request worth validating. All optional — skip what you don't need. */
|
|
6
|
+
export interface RouteSchema<B = undefined, Q = undefined, P = undefined> {
|
|
7
|
+
body?: ZodType<B>;
|
|
8
|
+
query?: ZodType<Q>;
|
|
9
|
+
params?: ZodType<P>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface RouteData<B, Q, P> {
|
|
13
|
+
body: B;
|
|
14
|
+
query: Q;
|
|
15
|
+
params: P;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type RouteHandler<B, Q, P> = (
|
|
19
|
+
c: BackonContext,
|
|
20
|
+
data: RouteData<B, Q, P>
|
|
21
|
+
) => Response | Promise<Response>;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Wraps a handler with request validation against zod schemas. On failure,
|
|
25
|
+
* throws AppError(400, ...) with the zod error attached as `details` —
|
|
26
|
+
* createApp()'s error handler turns that into the standard error JSON shape,
|
|
27
|
+
* so individual routes never write their own "if invalid, return 400" code.
|
|
28
|
+
*
|
|
29
|
+
* Usage in a *.controller.ts file:
|
|
30
|
+
*
|
|
31
|
+
* export const getTelemetry = defineRoute(
|
|
32
|
+
* { query: z.object({ deviceId: z.string() }) },
|
|
33
|
+
* async (c, { query }) => c.json({ deviceId: query.deviceId })
|
|
34
|
+
* );
|
|
35
|
+
*/
|
|
36
|
+
export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
37
|
+
schema: RouteSchema<B, Q, P>,
|
|
38
|
+
handler: RouteHandler<B, Q, P>
|
|
39
|
+
) {
|
|
40
|
+
return async (c: BackonContext): Promise<Response> => {
|
|
41
|
+
let body = undefined as B;
|
|
42
|
+
let query = undefined as Q;
|
|
43
|
+
let params = undefined as P;
|
|
44
|
+
|
|
45
|
+
if (schema.body) {
|
|
46
|
+
const raw = await c.req.json().catch(() => ({}));
|
|
47
|
+
const parsed = schema.body.safeParse(raw);
|
|
48
|
+
if (!parsed.success) {
|
|
49
|
+
throw new AppError(400, "invalid_body", "Request body failed validation", parsed.error.flatten());
|
|
50
|
+
}
|
|
51
|
+
body = parsed.data;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
if (schema.query) {
|
|
55
|
+
const raw = c.req.query();
|
|
56
|
+
const parsed = schema.query.safeParse(raw);
|
|
57
|
+
if (!parsed.success) {
|
|
58
|
+
throw new AppError(400, "invalid_query", "Query params failed validation", parsed.error.flatten());
|
|
59
|
+
}
|
|
60
|
+
query = parsed.data;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (schema.params) {
|
|
64
|
+
const raw = c.req.param();
|
|
65
|
+
const parsed = schema.params.safeParse(raw);
|
|
66
|
+
if (!parsed.success) {
|
|
67
|
+
throw new AppError(400, "invalid_params", "Route params failed validation", parsed.error.flatten());
|
|
68
|
+
}
|
|
69
|
+
params = parsed.data;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return handler(c, { body, query, params });
|
|
73
|
+
};
|
|
74
|
+
}
|
package/src/error.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AppError is the one type of error backon's error middleware understands as
|
|
3
|
+
* "expected" — it knows the right HTTP status and produces a stable JSON
|
|
4
|
+
* shape. Anything else thrown is treated as a bug: logged at error level and
|
|
5
|
+
* turned into a generic 500 so internals never leak to a client.
|
|
6
|
+
*/
|
|
7
|
+
export class AppError extends Error {
|
|
8
|
+
readonly statusCode: number;
|
|
9
|
+
readonly code: string;
|
|
10
|
+
readonly details?: unknown;
|
|
11
|
+
|
|
12
|
+
constructor(statusCode: number, code: string, message: string, details?: unknown) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "AppError";
|
|
15
|
+
this.statusCode = statusCode;
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.details = details;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Shape every error response is normalized to, expected or not. */
|
|
22
|
+
export interface ErrorResponseBody {
|
|
23
|
+
error: {
|
|
24
|
+
code: string;
|
|
25
|
+
message: string;
|
|
26
|
+
details?: unknown;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import express, { type Express, type NextFunction, type Request, type Response } from "express";
|
|
2
|
+
import cors from "cors";
|
|
3
|
+
import helmet from "helmet";
|
|
4
|
+
import compression from "compression";
|
|
5
|
+
import { AppError } from "../error";
|
|
6
|
+
import { logger } from "../logger";
|
|
7
|
+
import { requestLogger } from "./logger";
|
|
8
|
+
|
|
9
|
+
export interface CreateAppOptions {
|
|
10
|
+
/** Allowed CORS origins. Defaults to ALLOWED_ORIGINS env var (comma-separated), closed by default. */
|
|
11
|
+
allowedOrigins?: string[];
|
|
12
|
+
/** Max request body size in bytes. Defaults to 1mb. */
|
|
13
|
+
bodyLimitBytes?: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024; // 1mb
|
|
17
|
+
|
|
18
|
+
function resolveAllowedOrigins(options: CreateAppOptions): string[] {
|
|
19
|
+
if (options.allowedOrigins) return options.allowedOrigins;
|
|
20
|
+
const fromEnv = process.env.ALLOWED_ORIGINS;
|
|
21
|
+
return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()) : [];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Builds an Express app pre-wired with the same defaults as the Hono
|
|
26
|
+
* createApp(): request logging, secure headers, an allowlisted CORS policy,
|
|
27
|
+
* compression, a body size cap, and a /health route.
|
|
28
|
+
*
|
|
29
|
+
* NOTABLE DIFFERENCE FROM THE HONO VERSION: the central error handler is
|
|
30
|
+
* NOT registered here. Express identifies error-handling middleware by its
|
|
31
|
+
* 4-argument signature and only lets it catch errors from routes/middleware
|
|
32
|
+
* registered BEFORE it — the opposite of Hono's onError(), which is
|
|
33
|
+
* registration-order-independent. If the error handler were added here,
|
|
34
|
+
* inside createApp(), it would never see errors from the routes you add
|
|
35
|
+
* afterward in your own app.ts, exactly the routes it exists to catch.
|
|
36
|
+
* `serve()` calls attachErrorHandler() for you right before starting the
|
|
37
|
+
* server, once all your routes are guaranteed to already be registered. If
|
|
38
|
+
* you're not using backon's serve() — e.g. wrapping this app for a
|
|
39
|
+
* serverless handler or a supertest suite — call attachErrorHandler(app)
|
|
40
|
+
* yourself, after your routes, before you use the app.
|
|
41
|
+
*/
|
|
42
|
+
export function createApp(options: CreateAppOptions = {}): Express {
|
|
43
|
+
const app = express();
|
|
44
|
+
|
|
45
|
+
app.use(requestLogger);
|
|
46
|
+
app.use(helmet());
|
|
47
|
+
|
|
48
|
+
const allowedOrigins = resolveAllowedOrigins(options);
|
|
49
|
+
app.use(cors({ origin: allowedOrigins.length ? allowedOrigins : false }));
|
|
50
|
+
|
|
51
|
+
app.use(compression());
|
|
52
|
+
app.use(express.json({ limit: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES }));
|
|
53
|
+
|
|
54
|
+
// Same reasoning as the Hono version's /health: registered before your
|
|
55
|
+
// own middleware, so it gets logging/security/CORS/compression but not
|
|
56
|
+
// anything you add afterward. Right default for a liveness check.
|
|
57
|
+
app.get("/health", (_req, res) => {
|
|
58
|
+
res.json({ status: "ok" });
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
return app;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The central error handler, kept separate from createApp() — see the
|
|
66
|
+
* NOTABLE DIFFERENCE note above for why. Turns AppError into the standard
|
|
67
|
+
* `{ error: { code, message, details? } }` shape with its own status code,
|
|
68
|
+
* maps express.json()'s built-in payload-too-large error onto the same
|
|
69
|
+
* shape as the Hono adapter's 413, and turns anything else into a generic
|
|
70
|
+
* 500 without leaking internals.
|
|
71
|
+
*/
|
|
72
|
+
export function attachErrorHandler(app: Express): void {
|
|
73
|
+
app.use((err: unknown, _req: Request, res: Response, _next: NextFunction) => {
|
|
74
|
+
if (err instanceof AppError) {
|
|
75
|
+
logger.warn(
|
|
76
|
+
{ requestId: res.locals.requestId, code: err.code, details: err.details },
|
|
77
|
+
err.message
|
|
78
|
+
);
|
|
79
|
+
res
|
|
80
|
+
.status(err.statusCode)
|
|
81
|
+
.json({ error: { code: err.code, message: err.message, details: err.details } });
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const status =
|
|
86
|
+
(err as { status?: number; statusCode?: number } | undefined)?.status ??
|
|
87
|
+
(err as { statusCode?: number } | undefined)?.statusCode;
|
|
88
|
+
if (status === 413) {
|
|
89
|
+
res.status(413).json({ error: { code: "payload_too_large", message: "Request body too large" } });
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
logger.error({ requestId: res.locals.requestId, err }, "unhandled error");
|
|
94
|
+
res.status(500).json({ error: { code: "internal_error", message: "Something went wrong" } });
|
|
95
|
+
});
|
|
96
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from "express";
|
|
2
|
+
import type { ZodType } from "zod";
|
|
3
|
+
import { AppError } from "../error";
|
|
4
|
+
import { createContext, type BackonContext } from "./types";
|
|
5
|
+
|
|
6
|
+
export interface RouteSchema<B = undefined, Q = undefined, P = undefined> {
|
|
7
|
+
body?: ZodType<B>;
|
|
8
|
+
query?: ZodType<Q>;
|
|
9
|
+
params?: ZodType<P>;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface RouteData<B, Q, P> {
|
|
13
|
+
body: B;
|
|
14
|
+
query: Q;
|
|
15
|
+
params: P;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Unlike the Hono version, an Express handler doesn't return a Response —
|
|
20
|
+
* it sends one as a side effect via ctx.json()/ctx.text() (which call
|
|
21
|
+
* res.json()/res.send() under the hood) and the return value is ignored.
|
|
22
|
+
* Handler bodies still read the same either way — `(c, { body }) =>
|
|
23
|
+
* c.json({...})` — because ctx.json() does the right thing for whichever
|
|
24
|
+
* engine is underneath, even though what "the right thing" means differs.
|
|
25
|
+
*/
|
|
26
|
+
export type RouteHandler<B, Q, P> = (
|
|
27
|
+
c: BackonContext,
|
|
28
|
+
data: RouteData<B, Q, P>
|
|
29
|
+
) => unknown | Promise<unknown>;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Same contract as the Hono defineRoute: validates body/query/params
|
|
33
|
+
* against zod schemas and throws AppError(400, ...) on failure. Requires
|
|
34
|
+
* createApp()'s express.json() middleware to have already run so
|
|
35
|
+
* req.body is parsed — see create-app.ts.
|
|
36
|
+
*/
|
|
37
|
+
export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
38
|
+
schema: RouteSchema<B, Q, P>,
|
|
39
|
+
handler: RouteHandler<B, Q, P>
|
|
40
|
+
) {
|
|
41
|
+
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
42
|
+
try {
|
|
43
|
+
let body = undefined as B;
|
|
44
|
+
let query = undefined as Q;
|
|
45
|
+
let params = undefined as P;
|
|
46
|
+
|
|
47
|
+
if (schema.body) {
|
|
48
|
+
const parsed = schema.body.safeParse(req.body ?? {});
|
|
49
|
+
if (!parsed.success) {
|
|
50
|
+
throw new AppError(400, "invalid_body", "Request body failed validation", parsed.error.flatten());
|
|
51
|
+
}
|
|
52
|
+
body = parsed.data;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (schema.query) {
|
|
56
|
+
const parsed = schema.query.safeParse(req.query);
|
|
57
|
+
if (!parsed.success) {
|
|
58
|
+
throw new AppError(400, "invalid_query", "Query params failed validation", parsed.error.flatten());
|
|
59
|
+
}
|
|
60
|
+
query = parsed.data;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (schema.params) {
|
|
64
|
+
const parsed = schema.params.safeParse(req.params);
|
|
65
|
+
if (!parsed.success) {
|
|
66
|
+
throw new AppError(400, "invalid_params", "Route params failed validation", parsed.error.flatten());
|
|
67
|
+
}
|
|
68
|
+
params = parsed.data;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const ctx = createContext(req, res);
|
|
72
|
+
await handler(ctx, { body, query, params });
|
|
73
|
+
} catch (err) {
|
|
74
|
+
next(err);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export { createApp, attachErrorHandler } from "./create-app";
|
|
2
|
+
export type { CreateAppOptions } from "./create-app";
|
|
3
|
+
|
|
4
|
+
export { serve } from "./serve";
|
|
5
|
+
|
|
6
|
+
export { defineRoute } from "./define-route";
|
|
7
|
+
export type { RouteSchema, RouteData, RouteHandler } from "./define-route";
|
|
8
|
+
|
|
9
|
+
export { AppError } from "../error";
|
|
10
|
+
export type { ErrorResponseBody } from "../error";
|
|
11
|
+
|
|
12
|
+
export { logger } from "../logger";
|
|
13
|
+
|
|
14
|
+
export type { BackonContext } from "./types";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Re-exported so generated projects never depend on 'express' directly,
|
|
18
|
+
* same reasoning as re-exporting Hono from the default export.
|
|
19
|
+
*/
|
|
20
|
+
export { Router } from "express";
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import type { Request, Response, NextFunction } from "express";
|
|
3
|
+
import { logger } from "../logger";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Express equivalent of the Hono requestLogger: attaches/reuses a request
|
|
7
|
+
* id and logs one line per request. Express doesn't have Hono's
|
|
8
|
+
* `await next()` continuation model, so this listens for the 'finish'
|
|
9
|
+
* event on the response instead of wrapping next() — that fires once the
|
|
10
|
+
* response has actually been sent, whichever code path sent it.
|
|
11
|
+
*/
|
|
12
|
+
export function requestLogger(req: Request, res: Response, next: NextFunction) {
|
|
13
|
+
const requestId = req.header("x-request-id") ?? randomUUID();
|
|
14
|
+
res.locals.requestId = requestId;
|
|
15
|
+
res.setHeader("x-request-id", requestId);
|
|
16
|
+
|
|
17
|
+
const start = performance.now();
|
|
18
|
+
res.on("finish", () => {
|
|
19
|
+
const durationMs = Math.round(performance.now() - start);
|
|
20
|
+
logger.info(
|
|
21
|
+
{ requestId, method: req.method, path: req.path, status: res.statusCode, durationMs },
|
|
22
|
+
"request"
|
|
23
|
+
);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
next();
|
|
27
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Express } from "express";
|
|
2
|
+
import { attachErrorHandler } from "./create-app";
|
|
3
|
+
import { logger } from "../logger";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Starts the app on Node's http server (via Express's own app.listen) and
|
|
7
|
+
* wires graceful shutdown, same contract as the Hono adapter's serve().
|
|
8
|
+
*
|
|
9
|
+
* Also calls attachErrorHandler(app) first — see the note on createApp()
|
|
10
|
+
* for why that can't happen until every route is registered. If you're not
|
|
11
|
+
* using this serve() (e.g. exporting the app for a serverless platform or a
|
|
12
|
+
* supertest suite), call attachErrorHandler(app) yourself instead.
|
|
13
|
+
*/
|
|
14
|
+
export function serve(app: Express, port: number = Number(process.env.PORT) || 3000) {
|
|
15
|
+
attachErrorHandler(app);
|
|
16
|
+
|
|
17
|
+
const server = app.listen(port, () => {
|
|
18
|
+
logger.info({ port }, "backon app listening");
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
let shuttingDown = false;
|
|
22
|
+
const shutdown = (signal: string) => {
|
|
23
|
+
if (shuttingDown) return;
|
|
24
|
+
shuttingDown = true;
|
|
25
|
+
logger.info({ signal }, "shutting down");
|
|
26
|
+
server.close(() => process.exit(0)); // stop accepting new connections; in-flight requests finish, then exit
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
30
|
+
process.on("SIGINT", () => shutdown("SIGINT"));
|
|
31
|
+
|
|
32
|
+
return server;
|
|
33
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { Request, Response } from "express";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The Express-flavored BackonContext. Same names as the Hono-flavored one
|
|
5
|
+
* (json/text/header/get/set) so a handler written against either reads the
|
|
6
|
+
* same way, but the two are genuinely different types from two different
|
|
7
|
+
* subpath exports (`backon` vs `backon/express`) — there's no shared
|
|
8
|
+
* interface forcing them into one shape. That's a deliberate choice: the
|
|
9
|
+
* only surface that needs to match is what handlers actually use day to
|
|
10
|
+
* day (send a JSON/text response, set a header, read/write a request-scoped
|
|
11
|
+
* variable). Anything past that — streaming, cookies, file uploads,
|
|
12
|
+
* redirects — behaves differently enough between the two engines that
|
|
13
|
+
* pretending otherwise would just move the leak somewhere less visible.
|
|
14
|
+
* Use `.raw` to drop down to the real Express req/res for those cases.
|
|
15
|
+
*/
|
|
16
|
+
export interface BackonContext {
|
|
17
|
+
req: {
|
|
18
|
+
method: string;
|
|
19
|
+
path: string;
|
|
20
|
+
header(name: string): string | undefined;
|
|
21
|
+
};
|
|
22
|
+
json(data: unknown, status?: number): Response;
|
|
23
|
+
text(data: string, status?: number): Response;
|
|
24
|
+
header(name: string, value: string): void;
|
|
25
|
+
get(key: string): unknown;
|
|
26
|
+
set(key: string, value: unknown): void;
|
|
27
|
+
/** Escape hatch to the real Express request/response. */
|
|
28
|
+
raw: { req: Request; res: Response };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function createContext(req: Request, res: Response): BackonContext {
|
|
32
|
+
return {
|
|
33
|
+
req: {
|
|
34
|
+
method: req.method,
|
|
35
|
+
path: req.path,
|
|
36
|
+
header: (name) => req.header(name),
|
|
37
|
+
},
|
|
38
|
+
json: (data, status) => res.status(status ?? 200).json(data),
|
|
39
|
+
text: (data, status) => res.status(status ?? 200).type("text/plain").send(data),
|
|
40
|
+
header: (name, value) => {
|
|
41
|
+
res.setHeader(name, value);
|
|
42
|
+
},
|
|
43
|
+
get: (key) => res.locals[key],
|
|
44
|
+
set: (key, value) => {
|
|
45
|
+
res.locals[key] = value;
|
|
46
|
+
},
|
|
47
|
+
raw: { req, res },
|
|
48
|
+
};
|
|
49
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export { createApp } from "./create-app";
|
|
2
|
+
export type { CreateAppOptions } from "./create-app";
|
|
3
|
+
|
|
4
|
+
export { serve } from "./serve";
|
|
5
|
+
|
|
6
|
+
export { defineRoute } from "./define-route";
|
|
7
|
+
export type { RouteSchema, RouteData, RouteHandler } from "./define-route";
|
|
8
|
+
|
|
9
|
+
export { AppError } from "./error";
|
|
10
|
+
export type { ErrorResponseBody } from "./error";
|
|
11
|
+
|
|
12
|
+
export { logger } from "./logger";
|
|
13
|
+
|
|
14
|
+
export type { BackonContext, Env } from "./types";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Re-exported so generated projects (and anything you build on backon)
|
|
18
|
+
* never need to depend on 'hono' directly, even for the parts backon
|
|
19
|
+
* doesn't add opinions to yet — like building a sub-router with
|
|
20
|
+
* `new Hono()` for a single resource's routes.
|
|
21
|
+
*/
|
|
22
|
+
export { Hono } from "hono";
|
|
23
|
+
export type { Next } from "hono";
|
package/src/logger.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import pino from "pino";
|
|
3
|
+
import type { Context, Next } from "hono";
|
|
4
|
+
import type { Env } from "./types";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Structured logger. pino instead of console.log because it's fast enough to
|
|
8
|
+
* leave on in production and gives us structured (JSON) lines for free —
|
|
9
|
+
* console.log output is not something you can query later.
|
|
10
|
+
*/
|
|
11
|
+
export const logger = pino({
|
|
12
|
+
level: process.env.LOG_LEVEL ?? "info",
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Attaches a request id (reusing an inbound x-request-id header if the
|
|
17
|
+
* platform already set one, e.g. a reverse proxy) and logs one line per
|
|
18
|
+
* request with method, path, status, and duration. Runs first in the
|
|
19
|
+
* middleware stack so it wraps everything else, including errors.
|
|
20
|
+
*/
|
|
21
|
+
export async function requestLogger(c: Context<Env>, next: Next) {
|
|
22
|
+
const requestId = c.req.header("x-request-id") ?? randomUUID();
|
|
23
|
+
c.set("requestId", requestId);
|
|
24
|
+
c.header("x-request-id", requestId);
|
|
25
|
+
|
|
26
|
+
const start = performance.now();
|
|
27
|
+
await next();
|
|
28
|
+
const durationMs = Math.round(performance.now() - start);
|
|
29
|
+
|
|
30
|
+
logger.info(
|
|
31
|
+
{
|
|
32
|
+
requestId,
|
|
33
|
+
method: c.req.method,
|
|
34
|
+
path: c.req.path,
|
|
35
|
+
status: c.res.status,
|
|
36
|
+
durationMs,
|
|
37
|
+
},
|
|
38
|
+
"request"
|
|
39
|
+
);
|
|
40
|
+
}
|
package/src/serve.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Hono } from "hono";
|
|
2
|
+
import { logger } from "./logger";
|
|
3
|
+
import type { Env } from "./types";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Starts the app on Bun's native server and wires graceful shutdown: on
|
|
7
|
+
* SIGTERM/SIGINT, stop accepting new connections, let in-flight requests
|
|
8
|
+
* finish, then exit. Matters for zero-downtime deploys — without this, a
|
|
9
|
+
* deploy or restart can cut off requests mid-flight.
|
|
10
|
+
*/
|
|
11
|
+
export function serve(app: Hono<Env>, port: number = Number(process.env.PORT) || 3000) {
|
|
12
|
+
const server = Bun.serve({ fetch: app.fetch, port });
|
|
13
|
+
logger.info({ port }, "backon app listening");
|
|
14
|
+
|
|
15
|
+
let shuttingDown = false;
|
|
16
|
+
const shutdown = (signal: string) => {
|
|
17
|
+
if (shuttingDown) return;
|
|
18
|
+
shuttingDown = true;
|
|
19
|
+
logger.info({ signal }, "shutting down");
|
|
20
|
+
server.stop(); // stop accepting new connections; lets in-flight requests finish
|
|
21
|
+
process.exit(0);
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
25
|
+
process.on("SIGINT", () => shutdown("SIGINT"));
|
|
26
|
+
|
|
27
|
+
return server;
|
|
28
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { Context } from "hono";
|
|
2
|
+
|
|
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
|
+
};
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* BackonContext is, for now, a direct alias of Hono's own Context. That's a
|
|
16
|
+
* deliberate choice, not an oversight: the real framework-agnostic boundary
|
|
17
|
+
* (the seam that would let an Express adapter produce the same shape) only
|
|
18
|
+
* gets designed once that adapter is actually being built. Guessing at that
|
|
19
|
+
* abstraction now, before a second implementation exists to validate it
|
|
20
|
+
* against, is how you end up rebuilding it anyway. Until then, this alias
|
|
21
|
+
* exists so call sites already say `BackonContext` instead of `Context`,
|
|
22
|
+
* which is the only part that needs to stay stable.
|
|
23
|
+
*/
|
|
24
|
+
export type BackonContext = Context<Env>;
|