@mednours/backon 0.1.0 → 0.4.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/src/serve.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Hono } from "hono";
2
+ import { websocket } from "hono/bun";
2
3
  import { logger } from "./logger";
3
4
  import type { Env } from "./types";
4
5
 
@@ -7,9 +8,13 @@ import type { Env } from "./types";
7
8
  * SIGTERM/SIGINT, stop accepting new connections, let in-flight requests
8
9
  * finish, then exit. Matters for zero-downtime deploys — without this, a
9
10
  * deploy or restart can cut off requests mid-flight.
11
+ *
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.
10
15
  */
11
16
  export function serve(app: Hono<Env>, port: number = Number(process.env.PORT) || 3000) {
12
- const server = Bun.serve({ fetch: app.fetch, port });
17
+ const server = Bun.serve({ fetch: app.fetch, websocket, port });
13
18
  logger.info({ port }, "backon app listening");
14
19
 
15
20
  let shuttingDown = false;
package/src/stream.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { stream as honoStream } from "hono/streaming";
2
+ import type { BackonContext } from "./types";
3
+
4
+ export type StreamWriter = (chunk: string | Uint8Array) => Promise<void>;
5
+
6
+ /**
7
+ * Registers a route that writes its response in chunks as they become
8
+ * available, instead of building one body in memory and returning it all at
9
+ * once — server-sent events, a large export, anything too slow or too big
10
+ * to buffer first.
11
+ *
12
+ * app.get("/export", defineStream(async (c, write) => {
13
+ * for (const row of rows) await write(JSON.stringify(row) + "\n");
14
+ * }));
15
+ *
16
+ * Set a Content-Type via c.header() before the first write() if the default
17
+ * (left to the browser/client to infer) isn't right for what's being sent.
18
+ */
19
+ export function defineStream(handler: (c: BackonContext, write: StreamWriter) => Promise<void>) {
20
+ return (c: BackonContext) =>
21
+ honoStream(c, async (s) => {
22
+ await handler(c, async (chunk) => {
23
+ await s.write(chunk);
24
+ });
25
+ });
26
+ }
package/src/types.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Context } from "hono";
2
+ import type { JWTPayload } from "hono/utils/jwt/types";
2
3
 
3
4
  /**
4
5
  * Hono's own generics for per-request state (c.get/c.set). Extend this as
@@ -8,6 +9,8 @@ import type { Context } from "hono";
8
9
  export interface Env {
9
10
  Variables: {
10
11
  requestId: string;
12
+ /** Set by requireAuth() middleware; undefined on any route it hasn't run on. */
13
+ auth?: JWTPayload;
11
14
  };
12
15
  }
13
16
 
@@ -17,7 +20,7 @@ export interface Env {
17
20
  * (the seam that would let an Express adapter produce the same shape) only
18
21
  * gets designed once that adapter is actually being built. Guessing at that
19
22
  * abstraction now, before a second implementation exists to validate it
20
- * against, is how you end up rebuilding it anyway. Until then, this alias
23
+ * against, tends to mean rebuilding it anyway. Until then, this alias
21
24
  * exists so call sites already say `BackonContext` instead of `Context`,
22
25
  * which is the only part that needs to stay stable.
23
26
  */
package/src/upload.ts ADDED
@@ -0,0 +1,62 @@
1
+ import { AppError } from "./error";
2
+ import type { BackonContext } from "./types";
3
+
4
+ /** Content-Type headers can carry parameters ("text/plain;charset=utf-8") — comparisons only care about the type itself. */
5
+ function baseMimeType(type: string): string {
6
+ return type.split(";")[0]?.trim() ?? type;
7
+ }
8
+
9
+ export interface UploadOptions {
10
+ /** Rejects any file over this size with a 400. Unset means no limit. */
11
+ maxFileSizeBytes?: number;
12
+ /** Rejects any file whose type isn't in this list with a 400. Unset means no restriction. */
13
+ allowedMimeTypes?: string[];
14
+ }
15
+
16
+ export type UploadHandler = (
17
+ c: BackonContext,
18
+ data: { files: Record<string, File[]> }
19
+ ) => Response | Promise<Response>;
20
+
21
+ /**
22
+ * Parses a multipart/form-data request, validating each file against
23
+ * `maxFileSizeBytes`/`allowedMimeTypes` before the handler runs — the same
24
+ * "validate first, throw AppError(400, ...) on failure" contract as
25
+ * defineRoute(), just for files instead of a JSON body. Fields uploaded more
26
+ * than once under the same name all land under that field's array, same as
27
+ * a single file — `files.avatar` is always an array, even with one file.
28
+ *
29
+ * app.post("/avatar", defineUpload(
30
+ * { maxFileSizeBytes: 2 * 1024 * 1024, allowedMimeTypes: ["image/png", "image/jpeg"] },
31
+ * async (c, { files }) => c.json({ uploaded: files.avatar.length })
32
+ * ));
33
+ */
34
+ export function defineUpload(options: UploadOptions, handler: UploadHandler) {
35
+ return async (c: BackonContext): Promise<Response> => {
36
+ const raw = await c.req.parseBody({ all: true });
37
+ const files: Record<string, File[]> = {};
38
+
39
+ for (const [field, value] of Object.entries(raw)) {
40
+ const values = Array.isArray(value) ? value : [value];
41
+ const fileValues = values.filter((entry): entry is File => entry instanceof File);
42
+ if (fileValues.length === 0) continue;
43
+
44
+ for (const file of fileValues) {
45
+ if (options.maxFileSizeBytes !== undefined && file.size > options.maxFileSizeBytes) {
46
+ throw new AppError(
47
+ 400,
48
+ "file_too_large",
49
+ `${file.name} is ${file.size} bytes, over the ${options.maxFileSizeBytes} byte limit`
50
+ );
51
+ }
52
+ if (options.allowedMimeTypes && !options.allowedMimeTypes.includes(baseMimeType(file.type))) {
53
+ throw new AppError(400, "unsupported_file_type", `${file.name} has unsupported type "${file.type}"`);
54
+ }
55
+ }
56
+
57
+ files[field] = fileValues;
58
+ }
59
+
60
+ return handler(c, { files });
61
+ };
62
+ }
@@ -0,0 +1,28 @@
1
+ import { upgradeWebSocket } from "hono/bun";
2
+ import type { WSContext, WSMessageReceive } from "hono/ws";
3
+
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
+ /**
12
+ * Registers a WebSocket route. The handshake happens at Bun.serve()'s own
13
+ * 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:
17
+ *
18
+ * app.get("/ws", defineWebSocket({
19
+ * onMessage: (ws, data) => ws.send(`echo: ${data}`),
20
+ * }));
21
+ */
22
+ 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
+ }));
28
+ }