hadars 0.1.9 → 0.1.10

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.
@@ -46,12 +46,52 @@ const noopCtx: ServerContext = { upgrade: () => false };
46
46
  * The `fetchHandler` may return `undefined` to signal that the response was
47
47
  * handled out-of-band (e.g. a Bun WebSocket upgrade).
48
48
  */
49
+ const COMPRESSIBLE_RE = /\b(?:text\/|application\/(?:json|javascript|xml)|image\/svg\+xml)/;
50
+
51
+ function withCompression(handler: FetchHandler): FetchHandler {
52
+ return async (req, ctx) => {
53
+ const res = await handler(req, ctx);
54
+ if (!res?.body) return res;
55
+ if (!COMPRESSIBLE_RE.test(res.headers.get('Content-Type') ?? '')) return res;
56
+ if (res.headers.has('Content-Encoding')) return res; // already compressed
57
+
58
+ const accept = req.headers.get('Accept-Encoding') ?? '';
59
+ const encoding = accept.includes('br') ? 'br' : accept.includes('gzip') ? 'gzip' : null;
60
+ if (!encoding) return res;
61
+
62
+ try {
63
+ const compressed = res.body.pipeThrough(new (globalThis as any).CompressionStream(encoding));
64
+ const headers = new Headers(res.headers);
65
+ headers.set('Content-Encoding', encoding);
66
+ headers.delete('Content-Length');
67
+ return new Response(compressed, { status: res.status, statusText: res.statusText, headers });
68
+ } catch {
69
+ return res;
70
+ }
71
+ };
72
+ }
73
+
74
+ function withRequestLogging(handler: FetchHandler): FetchHandler {
75
+ return async (req, ctx) => {
76
+ const start = performance.now();
77
+ const res = await handler(req, ctx);
78
+ const ms = Math.round(performance.now() - start);
79
+ const status = res?.status ?? 404;
80
+ const path = new URL(req.url).pathname;
81
+ console.log(`[hadars] ${req.method} ${path} ${status} ${ms}ms`);
82
+ return res;
83
+ };
84
+ }
85
+
49
86
  export async function serve(
50
87
  port: number,
51
88
  fetchHandler: FetchHandler,
52
89
  /** Bun WebSocketHandler — ignored on Deno and Node.js. */
53
90
  websocket?: unknown,
54
91
  ): Promise<void> {
92
+ fetchHandler = withCompression(fetchHandler);
93
+ fetchHandler = withRequestLogging(fetchHandler);
94
+
55
95
  // ── Bun ────────────────────────────────────────────────────────────────
56
96
  if (isBun) {
57
97
  (globalThis as any).Bun.serve({
@@ -1,4 +0,0 @@
1
- export const loadModule = <T>(path: string): T => {
2
- return import(path) as unknown as T;
3
- // throw new Error('loadModule should be transformed by loader')
4
- }