@mednours/backon 0.6.0 → 0.7.1

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 +56 -24
  67. package/src/serve.ts +62 -12
  68. package/src/websocket.ts +34 -9
@@ -0,0 +1,33 @@
1
+ import type { Request, Response } from "express";
2
+ /**
3
+ * The Express-flavored BackonContext. Same names as the Hono-flavored one
4
+ * (json/text/header/get/set) so a handler written against either reads the
5
+ * same way, but the two are genuinely different types from two different
6
+ * subpath exports (`backon` vs `backon/express`) — there's no shared
7
+ * interface forcing them into one shape. That's a deliberate choice: the
8
+ * only surface that needs to match is what handlers actually use day to
9
+ * day (send a JSON/text response, set a header, read/write a request-scoped
10
+ * variable). Anything past that — streaming, cookies, file uploads,
11
+ * redirects — behaves differently enough between the two engines that
12
+ * pretending otherwise would just move the leak somewhere less visible.
13
+ * Use `.raw` to drop down to the real Express req/res for those cases.
14
+ */
15
+ export interface BackonContext {
16
+ req: {
17
+ method: string;
18
+ path: string;
19
+ header(name: string): string | undefined;
20
+ };
21
+ json(data: unknown, status?: number): Response;
22
+ text(data: string, status?: number): Response;
23
+ header(name: string, value: string): void;
24
+ get(key: string): unknown;
25
+ set(key: string, value: unknown): void;
26
+ /** Escape hatch to the real Express request/response. */
27
+ raw: {
28
+ req: Request;
29
+ res: Response;
30
+ };
31
+ }
32
+ export declare function createContext(req: Request, res: Response): BackonContext;
33
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/express/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAEjD;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,aAAa;IAC5B,GAAG,EAAE;QACH,MAAM,EAAE,MAAM,CAAC;QACf,IAAI,EAAE,MAAM,CAAC;QACb,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;KAC1C,CAAC;IACF,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,QAAQ,CAAC;IAC/C,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,QAAQ,CAAC;IAC9C,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1C,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;IAC1B,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;IACvC,yDAAyD;IACzD,GAAG,EAAE;QAAE,GAAG,EAAE,OAAO,CAAC;QAAC,GAAG,EAAE,QAAQ,CAAA;KAAE,CAAC;CACtC;AAED,wBAAgB,aAAa,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,GAAG,aAAa,CAkBxE"}
@@ -0,0 +1,26 @@
1
+ import type { Request, Response, NextFunction } from "express";
2
+ import { type BackonContext } from "./types";
3
+ export interface UploadOptions {
4
+ /** Rejects any file over this size with a 400. Unset means no limit. */
5
+ maxFileSizeBytes?: number;
6
+ /** Rejects any file whose type isn't in this list with a 400. Unset means no restriction. */
7
+ allowedMimeTypes?: string[];
8
+ }
9
+ export type UploadHandler = (c: BackonContext, data: {
10
+ files: Record<string, Express.Multer.File[]>;
11
+ }) => unknown | Promise<unknown>;
12
+ /**
13
+ * Same contract as the Hono defineUpload: parses a multipart/form-data
14
+ * request, validates each file against maxFileSizeBytes/allowedMimeTypes,
15
+ * throws AppError(400, ...) on the first violation. Built on multer (kept
16
+ * in memory, not written to disk — same "handler decides what happens to
17
+ * the data" philosophy as everything else here) since Express has no
18
+ * built-in multipart parser the way Hono's c.req.parseBody() is.
19
+ *
20
+ * app.post("/avatar", defineUpload(
21
+ * { maxFileSizeBytes: 2 * 1024 * 1024, allowedMimeTypes: ["image/png", "image/jpeg"] },
22
+ * async (c, { files }) => c.json({ uploaded: files.avatar.length })
23
+ * ));
24
+ */
25
+ export declare function defineUpload(options: UploadOptions, handler: UploadHandler): (req: Request, res: Response, next: NextFunction) => void;
26
+ //# sourceMappingURL=upload.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload.d.ts","sourceRoot":"","sources":["../../src/express/upload.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAG/D,OAAO,EAAiB,KAAK,aAAa,EAAE,MAAM,SAAS,CAAC;AAO5D,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,OAAO,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAA;CAAE,KACnD,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;AAEhC;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,aAAa,EAAE,OAAO,EAAE,aAAa,IAOjE,KAAK,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,KAAG,IAAI,CAwB/D"}
@@ -0,0 +1,25 @@
1
+ import type { Server } from "node:http";
2
+ import type { IncomingMessage } from "node:http";
3
+ import { type WebSocket, type RawData } from "ws";
4
+ /** Handlers for one WebSocket route. `ws.send()`/`ws.close()` match the shape the Hono adapter's handlers get, too. */
5
+ export interface WebSocketHandlers {
6
+ onOpen?: (ws: WebSocket, req: IncomingMessage) => void;
7
+ onMessage?: (ws: WebSocket, data: RawData) => void;
8
+ onClose?: (ws: WebSocket) => void;
9
+ }
10
+ /**
11
+ * Registers a WebSocket route. Unlike Hono's version, this can't be
12
+ * registered as a normal GET route — Express has no route-level concept of
13
+ * an HTTP upgrade, only `ws`'s own server does, and that server doesn't
14
+ * exist until serve() has actually started listening. Call this on `app`
15
+ * any time before serve(); it's wired up once serve() has a real
16
+ * http.Server to attach to:
17
+ *
18
+ * defineWebSocket(app, "/ws", {
19
+ * onMessage: (ws, data) => ws.send(`echo: ${data}`),
20
+ * });
21
+ */
22
+ export declare function defineWebSocket(app: object, path: string, handlers: WebSocketHandlers): void;
23
+ /** Called by serve() once the real http.Server exists — attaches one `ws` WebSocketServer per registered path. */
24
+ export declare function attachWebSockets(app: object, server: Server): void;
25
+ //# sourceMappingURL=websocket.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../../src/express/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AACjD,OAAO,EAAmB,KAAK,SAAS,EAAE,KAAK,OAAO,EAAE,MAAM,IAAI,CAAC;AAEnE,uHAAuH;AACvH,MAAM,WAAW,iBAAiB;IAChC,MAAM,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,GAAG,EAAE,eAAe,KAAK,IAAI,CAAC;IACvD,SAAS,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,KAAK,IAAI,CAAC;IACnD,OAAO,CAAC,EAAE,CAAC,EAAE,EAAE,SAAS,KAAK,IAAI,CAAC;CACnC;AASD;;;;;;;;;;;GAWG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,iBAAiB,GAAG,IAAI,CAI5F;AAED,kHAAkH;AAClH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CASlE"}
@@ -0,0 +1,32 @@
1
+ export { createApp } from "./create-app";
2
+ export type { CreateAppOptions } from "./create-app";
3
+ export { serve } from "./serve";
4
+ export { defineRoute } from "./define-route";
5
+ export type { RouteSchema, RouteData, RouteHandler } from "./define-route";
6
+ export { AppError } from "./error";
7
+ export type { ErrorResponseBody } from "./error";
8
+ export { logger } from "./logger";
9
+ export { requireEnv } from "./require-env";
10
+ export { requireAuth } from "./require-auth";
11
+ export type { VerifyJwtOptions } from "./auth-core";
12
+ export { rateLimit } from "./rate-limit";
13
+ export type { RateLimitOptions } from "./rate-limit";
14
+ export { defineWebSocket } from "./websocket";
15
+ export type { WebSocketHandlers } from "./websocket";
16
+ export { defineStream } from "./stream";
17
+ export type { StreamWriter } from "./stream";
18
+ export { defineUpload } from "./upload";
19
+ export type { UploadOptions, UploadHandler } from "./upload";
20
+ export { generateOpenApiSpec, serveApiDocs } from "./openapi";
21
+ export type { OpenApiOptions } from "./openapi";
22
+ export { apiReferenceHtml, apiReferenceHtmlInline } from "./openapi-core";
23
+ export type { BackonContext, Env } from "./types";
24
+ /**
25
+ * Re-exported so generated projects (and anything built on backon) never
26
+ * need to depend on 'hono' directly, even for the parts backon doesn't add
27
+ * opinions to yet — like building a sub-router with `new Hono()` for a
28
+ * single resource's routes.
29
+ */
30
+ export { Hono } from "hono";
31
+ export type { Next } from "hono";
32
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,YAAY,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAEhC,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,YAAY,EAAE,WAAW,EAAE,SAAS,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAE3E,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,YAAY,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAEjD,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAElC,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,YAAY,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEpD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,YAAY,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,YAAY,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAE7C,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,YAAY,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAE7D,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAC9D,YAAY,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,gBAAgB,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAE1E,YAAY,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAElD;;;;;GAKG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC5B,YAAY,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,429 @@
1
+ // src/create-app.ts
2
+ import { Hono } from "hono";
3
+ import { secureHeaders } from "hono/secure-headers";
4
+ import { cors } from "hono/cors";
5
+ import { compress } from "hono/compress";
6
+ import { bodyLimit } from "hono/body-limit";
7
+
8
+ // src/error.ts
9
+ var AppError = class extends Error {
10
+ statusCode;
11
+ code;
12
+ details;
13
+ constructor(statusCode, code, message, details) {
14
+ super(message);
15
+ this.name = "AppError";
16
+ this.statusCode = statusCode;
17
+ this.code = code;
18
+ this.details = details;
19
+ }
20
+ };
21
+
22
+ // src/logger.ts
23
+ import { randomUUID } from "node:crypto";
24
+ import pino from "pino";
25
+ var logger = pino({
26
+ level: process.env.LOG_LEVEL ?? "info"
27
+ });
28
+ async function requestLogger(c, next) {
29
+ const requestId = c.req.header("x-request-id") ?? randomUUID();
30
+ c.set("requestId", requestId);
31
+ c.header("x-request-id", requestId);
32
+ const start = performance.now();
33
+ await next();
34
+ const durationMs = Math.round(performance.now() - start);
35
+ logger.info(
36
+ {
37
+ requestId,
38
+ method: c.req.method,
39
+ path: c.req.path,
40
+ status: c.res.status,
41
+ durationMs
42
+ },
43
+ "request"
44
+ );
45
+ }
46
+
47
+ // src/create-app.ts
48
+ var DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024;
49
+ function resolveAllowedOrigins(options) {
50
+ if (options.allowedOrigins) return options.allowedOrigins;
51
+ const fromEnv = process.env.ALLOWED_ORIGINS;
52
+ return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()) : [];
53
+ }
54
+ function createApp(options = {}) {
55
+ const app = new Hono();
56
+ app.use("*", requestLogger);
57
+ app.use("*", secureHeaders());
58
+ app.use(
59
+ "*",
60
+ cors({
61
+ origin: resolveAllowedOrigins(options)
62
+ })
63
+ );
64
+ app.use("*", compress());
65
+ app.use(
66
+ "*",
67
+ bodyLimit({
68
+ maxSize: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES,
69
+ onError: (c) => c.json({ error: { code: "payload_too_large", message: "Request body too large" } }, 413)
70
+ })
71
+ );
72
+ app.get("/health", (c) => c.json({ status: "ok" }));
73
+ app.onError((err, c) => {
74
+ if (err instanceof AppError) {
75
+ logger.warn({ requestId: c.get("requestId"), code: err.code, details: err.details }, err.message);
76
+ return c.json(
77
+ { error: { code: err.code, message: err.message, details: err.details } },
78
+ err.statusCode
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
+ return app;
85
+ }
86
+
87
+ // src/serve.ts
88
+ async function serve(app, port = Number(process.env.PORT) || 3e3) {
89
+ const isBun = typeof Bun !== "undefined";
90
+ const server = isBun ? await serveOnBun(app, port) : await serveOnNode(app, port);
91
+ logger.info({ port, runtime: isBun ? "bun" : "node" }, "backon app listening");
92
+ let shuttingDown = false;
93
+ const shutdown = (signal) => {
94
+ if (shuttingDown) return;
95
+ shuttingDown = true;
96
+ logger.info({ signal }, "shutting down");
97
+ server.stop?.();
98
+ server.close?.();
99
+ process.exit(0);
100
+ };
101
+ process.on("SIGTERM", () => shutdown("SIGTERM"));
102
+ process.on("SIGINT", () => shutdown("SIGINT"));
103
+ return server;
104
+ }
105
+ async function serveOnBun(app, port) {
106
+ const { websocket } = await import("hono/bun");
107
+ return Bun.serve({ fetch: app.fetch, websocket, port });
108
+ }
109
+ async function serveOnNode(app, port) {
110
+ let nodeServer;
111
+ try {
112
+ nodeServer = await import("@hono/node-server");
113
+ } catch {
114
+ throw new Error(
115
+ "serve() needs @hono/node-server to run under Node \u2014 install it with `npm install @hono/node-server` (or your package manager's equivalent). Bun doesn't need this; it uses Bun.serve() instead."
116
+ );
117
+ }
118
+ return nodeServer.serve({ fetch: app.fetch, port });
119
+ }
120
+
121
+ // src/define-route.ts
122
+ function defineRoute(schema, handler) {
123
+ const wrapped = async (c) => {
124
+ let body = void 0;
125
+ let query = void 0;
126
+ let params = void 0;
127
+ if (schema.body) {
128
+ const raw = await c.req.json().catch(() => ({}));
129
+ const parsed = schema.body.safeParse(raw);
130
+ if (!parsed.success) {
131
+ throw new AppError(400, "invalid_body", "Request body failed validation", parsed.error.flatten());
132
+ }
133
+ body = parsed.data;
134
+ }
135
+ if (schema.query) {
136
+ const raw = c.req.query();
137
+ const parsed = schema.query.safeParse(raw);
138
+ if (!parsed.success) {
139
+ throw new AppError(400, "invalid_query", "Query params failed validation", parsed.error.flatten());
140
+ }
141
+ query = parsed.data;
142
+ }
143
+ if (schema.params) {
144
+ const raw = c.req.param();
145
+ const parsed = schema.params.safeParse(raw);
146
+ if (!parsed.success) {
147
+ throw new AppError(400, "invalid_params", "Route params failed validation", parsed.error.flatten());
148
+ }
149
+ params = parsed.data;
150
+ }
151
+ return handler(c, { body, query, params });
152
+ };
153
+ wrapped.__backonRouteSchema = schema;
154
+ return wrapped;
155
+ }
156
+
157
+ // src/require-env.ts
158
+ function requireEnv(schema) {
159
+ const parsed = schema.safeParse(process.env);
160
+ if (!parsed.success) {
161
+ const issues = parsed.error.issues.map((issue) => ` - ${issue.path.join(".") || "(root)"}: ${issue.message}`).join("\n");
162
+ throw new Error(`Invalid environment variables:
163
+ ${issues}`);
164
+ }
165
+ return parsed.data;
166
+ }
167
+
168
+ // src/auth-core.ts
169
+ import { verify } from "hono/jwt";
170
+ var DEFAULT_ALG = "HS256";
171
+ function verifyJwt(token, options) {
172
+ return verify(token, options.secret, options.alg ?? DEFAULT_ALG);
173
+ }
174
+ function extractBearerToken(header) {
175
+ if (!header) return void 0;
176
+ const [scheme, token] = header.split(" ");
177
+ if (scheme?.toLowerCase() !== "bearer" || !token) return void 0;
178
+ return token;
179
+ }
180
+
181
+ // src/require-auth.ts
182
+ function requireAuth(options) {
183
+ return async function requireAuthMiddleware(c, next) {
184
+ const token = extractBearerToken(c.req.header("authorization"));
185
+ if (!token) {
186
+ throw new AppError(401, "unauthorized", "Missing or malformed Authorization header");
187
+ }
188
+ try {
189
+ const payload = await verifyJwt(token, options);
190
+ c.set("auth", payload);
191
+ } catch {
192
+ throw new AppError(401, "unauthorized", "Invalid or expired token");
193
+ }
194
+ await next();
195
+ };
196
+ }
197
+
198
+ // src/rate-limit-core.ts
199
+ var RateLimiter = class {
200
+ constructor(windowMs, max) {
201
+ this.windowMs = windowMs;
202
+ this.max = max;
203
+ }
204
+ windowMs;
205
+ max;
206
+ buckets = /* @__PURE__ */ new Map();
207
+ checksSinceSweep = 0;
208
+ check(key, now = Date.now()) {
209
+ this.maybeSweep(now);
210
+ let bucket = this.buckets.get(key);
211
+ if (!bucket || bucket.resetAt <= now) {
212
+ bucket = { count: 0, resetAt: now + this.windowMs };
213
+ this.buckets.set(key, bucket);
214
+ }
215
+ bucket.count += 1;
216
+ if (bucket.count > this.max) {
217
+ return { allowed: false, retryAfterMs: bucket.resetAt - now };
218
+ }
219
+ return { allowed: true, retryAfterMs: 0 };
220
+ }
221
+ /** Opportunistic cleanup so long-lived processes don't accumulate one bucket per distinct key forever. */
222
+ maybeSweep(now) {
223
+ this.checksSinceSweep += 1;
224
+ if (this.checksSinceSweep < 1e3) return;
225
+ this.checksSinceSweep = 0;
226
+ for (const [key, bucket] of this.buckets) {
227
+ if (bucket.resetAt <= now) this.buckets.delete(key);
228
+ }
229
+ }
230
+ };
231
+
232
+ // src/rate-limit.ts
233
+ var DEFAULT_WINDOW_MS = 6e4;
234
+ var DEFAULT_MAX = 60;
235
+ function rateLimit(options = {}) {
236
+ const limiter = new RateLimiter(options.windowMs ?? DEFAULT_WINDOW_MS, options.max ?? DEFAULT_MAX);
237
+ const keyGenerator = options.keyGenerator ?? defaultKey;
238
+ return async function rateLimitMiddleware(c, next) {
239
+ const result = limiter.check(keyGenerator(c));
240
+ if (!result.allowed) {
241
+ c.header("Retry-After", String(Math.ceil(result.retryAfterMs / 1e3)));
242
+ throw new AppError(429, "rate_limited", "Too many requests", {
243
+ retryAfterMs: result.retryAfterMs
244
+ });
245
+ }
246
+ await next();
247
+ };
248
+ }
249
+ function defaultKey(c) {
250
+ return c.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? c.req.header("x-real-ip") ?? "unknown";
251
+ }
252
+
253
+ // src/websocket.ts
254
+ function defineWebSocket(handlers) {
255
+ return async (c) => {
256
+ if (typeof Bun === "undefined") {
257
+ throw new Error(
258
+ "defineWebSocket() only works when this app is running on Bun \u2014 it relies on hono/bun's upgrade handshake, which backon doesn't yet have a Node equivalent for. Run this project on Bun, or drop the WebSocket route for a Node deploy."
259
+ );
260
+ }
261
+ const { upgradeWebSocket } = await import("hono/bun");
262
+ const handler = upgradeWebSocket(() => ({
263
+ onOpen: (_event, ws) => handlers.onOpen?.(ws),
264
+ onMessage: (event, ws) => handlers.onMessage?.(ws, event.data),
265
+ onClose: (_event, ws) => handlers.onClose?.(ws)
266
+ }));
267
+ return handler(c, async () => {
268
+ });
269
+ };
270
+ }
271
+
272
+ // src/stream.ts
273
+ import { stream as honoStream } from "hono/streaming";
274
+ function defineStream(handler) {
275
+ return (c) => honoStream(c, async (s) => {
276
+ await handler(c, async (chunk) => {
277
+ await s.write(chunk);
278
+ });
279
+ });
280
+ }
281
+
282
+ // src/upload.ts
283
+ function baseMimeType(type) {
284
+ return type.split(";")[0]?.trim() ?? type;
285
+ }
286
+ function defineUpload(options, handler) {
287
+ return async (c) => {
288
+ const raw = await c.req.parseBody({ all: true });
289
+ const files = {};
290
+ for (const [field, value] of Object.entries(raw)) {
291
+ const values = Array.isArray(value) ? value : [value];
292
+ const fileValues = values.filter((entry) => entry instanceof File);
293
+ if (fileValues.length === 0) continue;
294
+ for (const file of fileValues) {
295
+ if (options.maxFileSizeBytes !== void 0 && file.size > options.maxFileSizeBytes) {
296
+ throw new AppError(
297
+ 400,
298
+ "file_too_large",
299
+ `${file.name} is ${file.size} bytes, over the ${options.maxFileSizeBytes} byte limit`
300
+ );
301
+ }
302
+ if (options.allowedMimeTypes && !options.allowedMimeTypes.includes(baseMimeType(file.type))) {
303
+ throw new AppError(400, "unsupported_file_type", `${file.name} has unsupported type "${file.type}"`);
304
+ }
305
+ }
306
+ files[field] = fileValues;
307
+ }
308
+ return handler(c, { files });
309
+ };
310
+ }
311
+
312
+ // src/openapi-core.ts
313
+ import { zodToJsonSchema } from "zod-to-json-schema";
314
+ function toOpenApiPath(path) {
315
+ return path.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
316
+ }
317
+ function paramNames(path) {
318
+ return [...path.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1]).filter((name) => name !== void 0);
319
+ }
320
+ function buildOperation(path, schema) {
321
+ const operation = { responses: { "200": { description: "Success" } } };
322
+ const parameters = [];
323
+ if (schema.params) {
324
+ const jsonSchema = zodToJsonSchema(schema.params, { target: "openApi3" });
325
+ for (const name of paramNames(path)) {
326
+ parameters.push({
327
+ name,
328
+ in: "path",
329
+ required: true,
330
+ schema: jsonSchema.properties?.[name] ?? { type: "string" }
331
+ });
332
+ }
333
+ }
334
+ if (schema.query) {
335
+ const jsonSchema = zodToJsonSchema(schema.query, { target: "openApi3" });
336
+ const required = new Set(jsonSchema.required ?? []);
337
+ for (const [name, propSchema] of Object.entries(jsonSchema.properties ?? {})) {
338
+ parameters.push({ name, in: "query", required: required.has(name), schema: propSchema });
339
+ }
340
+ }
341
+ if (parameters.length) operation.parameters = parameters;
342
+ if (schema.body) {
343
+ operation.requestBody = {
344
+ required: true,
345
+ content: { "application/json": { schema: zodToJsonSchema(schema.body, { target: "openApi3" }) } }
346
+ };
347
+ }
348
+ return operation;
349
+ }
350
+ function buildOpenApiDocument(routes, options) {
351
+ const paths = {};
352
+ for (const route of routes) {
353
+ if (!route.schema) continue;
354
+ const openApiPath = toOpenApiPath(route.path);
355
+ paths[openApiPath] ??= {};
356
+ paths[openApiPath][route.method.toLowerCase()] = buildOperation(route.path, route.schema);
357
+ }
358
+ return {
359
+ openapi: "3.0.3",
360
+ info: {
361
+ title: options.title ?? "API",
362
+ version: options.version ?? "0.1.0",
363
+ ...options.description ? { description: options.description } : {}
364
+ },
365
+ paths
366
+ };
367
+ }
368
+ function pageShell(title, config) {
369
+ const fullConfig = { showDeveloperTools: "never", ...config };
370
+ return `<!doctype html>
371
+ <html>
372
+ <head>
373
+ <title>${title}</title>
374
+ <meta charset="utf-8" />
375
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
376
+ </head>
377
+ <body>
378
+ <div id="api-reference"></div>
379
+ <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
380
+ <script>
381
+ Scalar.createApiReference("#api-reference", ${JSON.stringify(fullConfig)});
382
+ </script>
383
+ </body>
384
+ </html>
385
+ `;
386
+ }
387
+ function apiReferenceHtml(specUrl, title = "API Reference") {
388
+ return pageShell(title, { url: specUrl });
389
+ }
390
+ function apiReferenceHtmlInline(spec, title = "API Reference") {
391
+ return pageShell(title, { content: spec });
392
+ }
393
+
394
+ // src/openapi.ts
395
+ var HTTP_METHODS = /* @__PURE__ */ new Set(["get", "post", "put", "patch", "delete", "options", "head"]);
396
+ function generateOpenApiSpec(app, options = {}) {
397
+ const routes = app.routes.filter((route) => HTTP_METHODS.has(route.method.toLowerCase())).map((route) => ({
398
+ method: route.method,
399
+ path: route.path,
400
+ schema: route.handler.__backonRouteSchema
401
+ }));
402
+ return buildOpenApiDocument(routes, options);
403
+ }
404
+ function serveApiDocs(app, path = "/docs", options = {}) {
405
+ const specPath = `${path}/openapi.json`;
406
+ app.get(specPath, (c) => c.json(generateOpenApiSpec(app, options)));
407
+ app.get(path, (c) => c.html(apiReferenceHtmlInline(generateOpenApiSpec(app, options), options.title)));
408
+ }
409
+
410
+ // src/index.ts
411
+ import { Hono as Hono2 } from "hono";
412
+ export {
413
+ AppError,
414
+ Hono2 as Hono,
415
+ apiReferenceHtml,
416
+ apiReferenceHtmlInline,
417
+ createApp,
418
+ defineRoute,
419
+ defineStream,
420
+ defineUpload,
421
+ defineWebSocket,
422
+ generateOpenApiSpec,
423
+ logger,
424
+ rateLimit,
425
+ requireAuth,
426
+ requireEnv,
427
+ serve,
428
+ serveApiDocs
429
+ };
@@ -0,0 +1,17 @@
1
+ import pino from "pino";
2
+ import type { Context, Next } from "hono";
3
+ import type { Env } from "./types";
4
+ /**
5
+ * Structured logger. pino instead of console.log because it's fast enough to
6
+ * leave on in production and gives structured (JSON) lines for free —
7
+ * console.log output isn't queryable later, structured log lines are.
8
+ */
9
+ export declare const logger: pino.Logger<never, boolean>;
10
+ /**
11
+ * Attaches a request id (reusing an inbound x-request-id header if the
12
+ * platform already set one, e.g. a reverse proxy) and logs one line per
13
+ * request with method, path, status, and duration. Runs first in the
14
+ * middleware stack so it wraps everything else, including errors.
15
+ */
16
+ export declare function requestLogger(c: Context<Env>, next: Next): Promise<void>;
17
+ //# sourceMappingURL=logger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AACA,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAEnC;;;;GAIG;AACH,eAAO,MAAM,MAAM,6BAEjB,CAAC;AAEH;;;;;GAKG;AACH,wBAAsB,aAAa,CAAC,CAAC,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,IAAI,EAAE,IAAI,iBAmB9D"}
@@ -0,0 +1,51 @@
1
+ import type { ZodType } from "zod";
2
+ export interface OpenApiOptions {
3
+ /** Defaults to "API". */
4
+ title?: string;
5
+ /** Defaults to "0.1.0". */
6
+ version?: string;
7
+ description?: string;
8
+ }
9
+ export interface RouteSchemaLike {
10
+ body?: ZodType<unknown>;
11
+ query?: ZodType<unknown>;
12
+ params?: ZodType<unknown>;
13
+ }
14
+ export interface CollectedRoute {
15
+ method: string;
16
+ path: string;
17
+ schema?: RouteSchemaLike;
18
+ }
19
+ /** Converts a framework's own param syntax (Hono and Express both use `:id`) to OpenAPI's `{id}`. */
20
+ export declare function toOpenApiPath(path: string): string;
21
+ /**
22
+ * Builds an OpenAPI 3.0 document from a flat list of routes, each carrying
23
+ * the same Zod schema defineRoute() validates against — the spec is derived
24
+ * from the schemas actually enforced at runtime instead of a hand-written
25
+ * document that can drift out of sync with them. A route with no schema
26
+ * (a plain handler, /health, a WebSocket route) is skipped, since there is
27
+ * nothing to describe past its existence.
28
+ */
29
+ export declare function buildOpenApiDocument(routes: CollectedRoute[], options: OpenApiOptions): Record<string, unknown>;
30
+ /**
31
+ * A minimal page that renders an OpenAPI document with Scalar (loaded from a
32
+ * CDN, not bundled as a dependency), fetching the document from `specUrl` —
33
+ * a real HTTP path the page can reach at render time, e.g. what
34
+ * `serveApiDocs()` mounts. Uses `Scalar.createApiReference()`, the
35
+ * documented initialization API — an older pattern (a magic script tag with
36
+ * a `data-url` attribute) is no longer reliable across Scalar versions and
37
+ * fails outright when the page is opened as a local file rather than served
38
+ * over HTTP, since fetching one `file://` URL from another is blocked by the
39
+ * browser. For that case, use `apiReferenceHtmlInline()` instead.
40
+ */
41
+ export declare function apiReferenceHtml(specUrl: string, title?: string): string;
42
+ /**
43
+ * Same rendered page as `apiReferenceHtml()`, but with the OpenAPI document
44
+ * embedded directly in the page instead of fetched from a URL — no request
45
+ * happens at render time, so this works when the file is opened straight
46
+ * from disk (double-clicked, `file://`) and not just when served over HTTP.
47
+ * This is what a static-generation script (writing the page to disk rather
48
+ * than serving it from a running app) should use.
49
+ */
50
+ export declare function apiReferenceHtmlInline(spec: Record<string, unknown>, title?: string): string;
51
+ //# sourceMappingURL=openapi-core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openapi-core.d.ts","sourceRoot":"","sources":["../src/openapi-core.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AAEnC,MAAM,WAAW,cAAc;IAC7B,yBAAyB;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,2BAA2B;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACxB,KAAK,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACzB,MAAM,CAAC,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3B;AAED,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,CAAC,EAAE,eAAe,CAAC;CAC1B;AAED,qGAAqG;AACrG,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAElD;AA4CD;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,cAAc,EAAE,EAAE,OAAO,EAAE,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAmB/G;AA0BD;;;;;;;;;;GAUG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,SAAkB,GAAG,MAAM,CAEjF;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,KAAK,SAAkB,GAAG,MAAM,CAErG"}
@@ -0,0 +1,22 @@
1
+ import type { Hono } from "hono";
2
+ import { type OpenApiOptions } from "./openapi-core";
3
+ export type { OpenApiOptions };
4
+ /**
5
+ * Reads every route registered on `app` (including ones mounted through
6
+ * nested `.route()` calls, since Hono copies a sub-app's own route entries
7
+ * onto the parent) and builds an OpenAPI document from whichever ones were
8
+ * wrapped in defineRoute() — those are the only ones carrying a schema.
9
+ */
10
+ export declare function generateOpenApiSpec(app: Hono<any>, options?: OpenApiOptions): Record<string, unknown>;
11
+ /**
12
+ * Mounts two routes: the OpenAPI document itself as JSON, and a page that
13
+ * renders it. The page embeds the document directly rather than fetching it
14
+ * from the JSON route — one less request, and it keeps working if the JSON
15
+ * route is ever removed or renamed. Call after every other route is
16
+ * registered — same registration-order rule as any other route reading from
17
+ * `app.routes`.
18
+ *
19
+ * serveApiDocs(app, "/docs", { title: "My API" });
20
+ */
21
+ export declare function serveApiDocs(app: Hono<any>, path?: string, options?: OpenApiOptions): void;
22
+ //# sourceMappingURL=openapi.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../src/openapi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AACjC,OAAO,EAAgD,KAAK,cAAc,EAAuB,MAAM,gBAAgB,CAAC;AAGxH,YAAY,EAAE,cAAc,EAAE,CAAC;AAI/B;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,cAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAUzG;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,EAAE,IAAI,SAAU,EAAE,OAAO,GAAE,cAAmB,GAAG,IAAI,CAI/F"}