h3 0.4.2 → 0.5.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/dist/index.mjs CHANGED
@@ -3,34 +3,30 @@ import { createRouter as createRouter$1 } from 'radix3';
3
3
  import destr from 'destr';
4
4
  import { parse, serialize } from 'cookie-es';
5
5
 
6
- const defineHandle = (handler) => handler;
6
+ const defineHandler = (handler) => handler;
7
+ const defineHandle = defineHandler;
7
8
  const defineMiddleware = (middleware) => middleware;
8
- function promisifyHandle(handle) {
9
+ function promisifyHandler(handler) {
9
10
  return function(req, res) {
10
- return callHandle(handle, req, res);
11
+ return callHandler(handler, req, res);
11
12
  };
12
13
  }
13
- function callHandle(handle, req, res) {
14
+ const promisifyHandle = promisifyHandler;
15
+ function callHandler(handler, req, res) {
14
16
  return new Promise((resolve, reject) => {
15
17
  const next = (err) => err ? reject(err) : resolve(void 0);
16
18
  try {
17
- const returned = handle(req, res, next);
18
- if (returned !== void 0) {
19
- resolve(returned);
20
- } else {
21
- res.once("close", next);
22
- res.once("error", next);
23
- }
19
+ return resolve(handler(req, res, next));
24
20
  } catch (err) {
25
21
  next(err);
26
22
  }
27
23
  });
28
24
  }
29
- function lazyHandle(handle, promisify) {
25
+ function defineLazyHandler(handler, promisify) {
30
26
  let _promise;
31
27
  const resolve = () => {
32
28
  if (!_promise) {
33
- _promise = Promise.resolve(handle()).then((r) => promisify ? promisifyHandle(r.default || r) : r.default || r);
29
+ _promise = Promise.resolve(handler()).then((r) => promisify ? promisifyHandler(r.default || r) : r.default || r);
34
30
  }
35
31
  return _promise;
36
32
  };
@@ -38,26 +34,84 @@ function lazyHandle(handle, promisify) {
38
34
  return resolve().then((h) => h(req, res));
39
35
  };
40
36
  }
41
- function useBase(base, handle) {
37
+ const lazyHandle = defineLazyHandler;
38
+ function useBase(base, handler) {
42
39
  base = withoutTrailingSlash(base);
43
40
  if (!base) {
44
- return handle;
41
+ return handler;
45
42
  }
46
43
  return function(req, res) {
47
44
  req.originalUrl = req.originalUrl || req.url || "/";
48
45
  req.url = withoutBase(req.url || "/", base);
49
- return handle(req, res);
46
+ return handler(req, res);
50
47
  };
51
48
  }
52
49
 
53
- function useQuery(req) {
54
- return getQuery(req.url || "");
50
+ function defineEventHandler(handler) {
51
+ handler.__is_handler__ = true;
52
+ return handler;
53
+ }
54
+ function defineLazyEventHandler(factory) {
55
+ let _promise;
56
+ let _resolved;
57
+ const resolveHandler = () => {
58
+ if (_resolved) {
59
+ return Promise.resolve(_resolved);
60
+ }
61
+ if (!_promise) {
62
+ _promise = Promise.resolve(factory()).then((r) => {
63
+ _resolved = r.default || r;
64
+ return _resolved;
65
+ });
66
+ }
67
+ return _promise;
68
+ };
69
+ return defineEventHandler((event) => {
70
+ if (_resolved) {
71
+ return _resolved(event);
72
+ }
73
+ return resolveHandler().then((handler) => handler(event));
74
+ });
75
+ }
76
+ function isEventHandler(input) {
77
+ return "__is_handler__" in input;
55
78
  }
56
- function useMethod(req, defaultMethod = "GET") {
57
- return (req.method || defaultMethod).toUpperCase();
79
+ function toEventHandler(handler) {
80
+ if (isEventHandler(handler)) {
81
+ return handler;
82
+ }
83
+ return defineEventHandler((event) => {
84
+ return callHandler(handler, event.req, event.res);
85
+ });
86
+ }
87
+ function createEvent(req, res) {
88
+ const event = {
89
+ __is_event__: true,
90
+ req,
91
+ res
92
+ };
93
+ event.event = event;
94
+ req.event = event;
95
+ req.req = req;
96
+ req.res = res;
97
+ res.event = event;
98
+ res.res = res;
99
+ res.req.res = res;
100
+ res.req.req = req;
101
+ return event;
58
102
  }
59
- function isMethod(req, expected, allowHead) {
60
- const method = useMethod(req);
103
+ function isEvent(input) {
104
+ return "__is_event__" in input;
105
+ }
106
+
107
+ function useQuery(event) {
108
+ return getQuery(event.req.url || "");
109
+ }
110
+ function useMethod(event, defaultMethod = "GET") {
111
+ return (event.req.method || defaultMethod).toUpperCase();
112
+ }
113
+ function isMethod(event, expected, allowHead) {
114
+ const method = useMethod(event);
61
115
  if (allowHead && method === "HEAD") {
62
116
  return true;
63
117
  }
@@ -70,8 +124,8 @@ function isMethod(req, expected, allowHead) {
70
124
  }
71
125
  return false;
72
126
  }
73
- function assertMethod(req, expected, allowHead) {
74
- if (!isMethod(req, expected, allowHead)) {
127
+ function assertMethod(event, expected, allowHead) {
128
+ if (!isMethod(event, expected, allowHead)) {
75
129
  throw createError({
76
130
  statusCode: 405,
77
131
  statusMessage: "HTTP method is not allowed."
@@ -82,18 +136,18 @@ function assertMethod(req, expected, allowHead) {
82
136
  const RawBodySymbol = Symbol("h3RawBody");
83
137
  const ParsedBodySymbol = Symbol("h3RawBody");
84
138
  const PayloadMethods = ["PATCH", "POST", "PUT", "DELETE"];
85
- function useRawBody(req, encoding = "utf-8") {
86
- assertMethod(req, PayloadMethods);
87
- if (RawBodySymbol in req) {
88
- const promise2 = Promise.resolve(req[RawBodySymbol]);
139
+ function useRawBody(event, encoding = "utf-8") {
140
+ assertMethod(event, PayloadMethods);
141
+ if (RawBodySymbol in event.req) {
142
+ const promise2 = Promise.resolve(event.req[RawBodySymbol]);
89
143
  return encoding ? promise2.then((buff) => buff.toString(encoding)) : promise2;
90
144
  }
91
- if ("body" in req) {
92
- return Promise.resolve(req.body);
145
+ if ("body" in event.req) {
146
+ return Promise.resolve(event.req.body);
93
147
  }
94
- const promise = req[RawBodySymbol] = new Promise((resolve, reject) => {
148
+ const promise = event.req[RawBodySymbol] = new Promise((resolve, reject) => {
95
149
  const bodyData = [];
96
- req.on("error", (err) => {
150
+ event.req.on("error", (err) => {
97
151
  reject(err);
98
152
  }).on("data", (chunk) => {
99
153
  bodyData.push(chunk);
@@ -103,13 +157,13 @@ function useRawBody(req, encoding = "utf-8") {
103
157
  });
104
158
  return encoding ? promise.then((buff) => buff.toString(encoding)) : promise;
105
159
  }
106
- async function useBody(req) {
107
- if (ParsedBodySymbol in req) {
108
- return req[ParsedBodySymbol];
160
+ async function useBody(event) {
161
+ if (ParsedBodySymbol in event.req) {
162
+ return event.req[ParsedBodySymbol];
109
163
  }
110
- const body = await useRawBody(req);
164
+ const body = await useRawBody(event);
111
165
  const json = destr(body);
112
- req[ParsedBodySymbol] = json;
166
+ event.req[ParsedBodySymbol] = json;
113
167
  return json;
114
168
  }
115
169
 
@@ -119,61 +173,61 @@ const MIMES = {
119
173
  };
120
174
 
121
175
  const defer = typeof setImmediate !== "undefined" ? setImmediate : (fn) => fn();
122
- function send(res, data, type) {
176
+ function send(event, data, type) {
123
177
  if (type) {
124
- defaultContentType(res, type);
178
+ defaultContentType(event, type);
125
179
  }
126
180
  return new Promise((resolve) => {
127
181
  defer(() => {
128
- res.end(data);
182
+ event.res.end(data);
129
183
  resolve(void 0);
130
184
  });
131
185
  });
132
186
  }
133
- function defaultContentType(res, type) {
134
- if (type && !res.getHeader("Content-Type")) {
135
- res.setHeader("Content-Type", type);
187
+ function defaultContentType(event, type) {
188
+ if (type && !event.res.getHeader("Content-Type")) {
189
+ event.res.setHeader("Content-Type", type);
136
190
  }
137
191
  }
138
- function sendRedirect(res, location, code = 302) {
139
- res.statusCode = code;
140
- res.setHeader("Location", location);
141
- return send(res, "Redirecting to " + location, MIMES.html);
192
+ function sendRedirect(event, location, code = 302) {
193
+ event.res.statusCode = code;
194
+ event.res.setHeader("Location", location);
195
+ return send(event, "Redirecting to " + location, MIMES.html);
142
196
  }
143
- function appendHeader(res, name, value) {
144
- let current = res.getHeader(name);
197
+ function appendHeader(event, name, value) {
198
+ let current = event.res.getHeader(name);
145
199
  if (!current) {
146
- res.setHeader(name, value);
200
+ event.res.setHeader(name, value);
147
201
  return;
148
202
  }
149
203
  if (!Array.isArray(current)) {
150
204
  current = [current.toString()];
151
205
  }
152
- res.setHeader(name, current.concat(value));
206
+ event.res.setHeader(name, current.concat(value));
153
207
  }
154
208
  function isStream(data) {
155
- return typeof data === "object" && typeof data.pipe === "function" && typeof data.on === "function";
209
+ return data && typeof data === "object" && typeof data.pipe === "function" && typeof data.on === "function";
156
210
  }
157
- function sendStream(res, data) {
211
+ function sendStream(event, data) {
158
212
  return new Promise((resolve, reject) => {
159
- data.pipe(res);
213
+ data.pipe(event.res);
160
214
  data.on("end", () => resolve(void 0));
161
215
  data.on("error", (error) => reject(createError(error)));
162
216
  });
163
217
  }
164
218
 
165
- function useCookies(req) {
166
- return parse(req.headers.cookie || "");
219
+ function useCookies(event) {
220
+ return parse(event.req.headers.cookie || "");
167
221
  }
168
- function useCookie(req, name) {
169
- return useCookies(req)[name];
222
+ function useCookie(event, name) {
223
+ return useCookies(event)[name];
170
224
  }
171
- function setCookie(res, name, value, serializeOptions) {
225
+ function setCookie(event, name, value, serializeOptions) {
172
226
  const cookieStr = serialize(name, value, serializeOptions);
173
- appendHeader(res, "Set-Cookie", cookieStr);
227
+ appendHeader(event, "Set-Cookie", cookieStr);
174
228
  }
175
- function deleteCookie(res, name, serializeOptions) {
176
- setCookie(res, name, "", {
229
+ function deleteCookie(event, name, serializeOptions) {
230
+ setCookie(event, name, "", {
177
231
  ...serializeOptions,
178
232
  maxAge: 0
179
233
  });
@@ -202,7 +256,7 @@ function createError(input) {
202
256
  }
203
257
  return err;
204
258
  }
205
- function sendError(res, error, debug) {
259
+ function sendError(event, error, debug) {
206
260
  let h3Error;
207
261
  if (error instanceof H3Error) {
208
262
  h3Error = error;
@@ -210,37 +264,41 @@ function sendError(res, error, debug) {
210
264
  console.error(error);
211
265
  h3Error = createError(error);
212
266
  }
213
- if (res.writableEnded) {
267
+ if (event.res.writableEnded) {
214
268
  return;
215
269
  }
216
- res.statusCode = h3Error.statusCode;
217
- res.statusMessage = h3Error.statusMessage;
270
+ event.res.statusCode = h3Error.statusCode;
271
+ event.res.statusMessage = h3Error.statusMessage;
218
272
  const responseBody = {
219
- statusCode: res.statusCode,
220
- statusMessage: res.statusMessage,
273
+ statusCode: event.res.statusCode,
274
+ statusMessage: event.res.statusMessage,
221
275
  stack: [],
222
276
  data: h3Error.data
223
277
  };
224
278
  if (debug) {
225
279
  responseBody.stack = (h3Error.stack || "").split("\n").map((l) => l.trim());
226
280
  }
227
- res.setHeader("Content-Type", MIMES.json);
228
- res.end(JSON.stringify(responseBody, null, 2));
281
+ event.res.setHeader("Content-Type", MIMES.json);
282
+ event.res.end(JSON.stringify(responseBody, null, 2));
229
283
  }
230
284
 
231
285
  function createApp(options = {}) {
232
286
  const stack = [];
233
- const _handle = createHandle(stack, options);
234
- const app = function(req, res) {
235
- return _handle(req, res).catch((error) => {
287
+ const handler = createAppEventHandler(stack, options);
288
+ const nodeHandler = async function(req, res) {
289
+ const event = createEvent(req, res);
290
+ try {
291
+ await handler(event);
292
+ } catch (err) {
236
293
  if (options.onError) {
237
- return options.onError(error, req, res);
294
+ await options.onError(err, event);
238
295
  }
239
- return sendError(res, error, !!options.debug);
240
- });
296
+ await sendError(event, err, !!options.debug);
297
+ }
241
298
  };
299
+ const app = nodeHandler;
242
300
  app.stack = stack;
243
- app._handle = _handle;
301
+ app.handler = handler;
244
302
  app.use = (arg1, arg2, arg3) => use(app, arg1, arg2, arg3);
245
303
  return app;
246
304
  }
@@ -250,63 +308,70 @@ function use(app, arg1, arg2, arg3) {
250
308
  } else if (Array.isArray(arg2)) {
251
309
  arg2.forEach((i) => use(app, arg1, i, arg3));
252
310
  } else if (typeof arg1 === "string") {
253
- app.stack.push(normalizeLayer({ ...arg3, route: arg1, handle: arg2 }));
311
+ app.stack.push(normalizeLayer({ ...arg3, route: arg1, handler: arg2 }));
254
312
  } else if (typeof arg1 === "function") {
255
- app.stack.push(normalizeLayer({ ...arg2, route: "/", handle: arg1 }));
313
+ app.stack.push(normalizeLayer({ ...arg2, route: "/", handler: arg1 }));
256
314
  } else {
257
315
  app.stack.push(normalizeLayer({ ...arg1 }));
258
316
  }
259
317
  return app;
260
318
  }
261
- function createHandle(stack, options) {
319
+ function createAppEventHandler(stack, options) {
262
320
  const spacing = options.debug ? 2 : void 0;
263
- return async function handle(req, res) {
264
- req.originalUrl = req.originalUrl || req.url || "/";
265
- const reqUrl = req.url || "/";
321
+ return defineEventHandler(async (event) => {
322
+ event.req.originalUrl = event.req.originalUrl || event.req.url || "/";
323
+ const reqUrl = event.req.url || "/";
266
324
  for (const layer of stack) {
267
325
  if (layer.route.length > 1) {
268
326
  if (!reqUrl.startsWith(layer.route)) {
269
327
  continue;
270
328
  }
271
- req.url = reqUrl.slice(layer.route.length) || "/";
329
+ event.req.url = reqUrl.slice(layer.route.length) || "/";
272
330
  } else {
273
- req.url = reqUrl;
331
+ event.req.url = reqUrl;
274
332
  }
275
- if (layer.match && !layer.match(req.url, req)) {
333
+ if (layer.match && !layer.match(event.req.url, event)) {
276
334
  continue;
277
335
  }
278
- const val = await layer.handle(req, res);
279
- if (res.writableEnded) {
336
+ const val = await layer.handler(event);
337
+ if (event.res.writableEnded) {
280
338
  return;
281
339
  }
282
340
  const type = typeof val;
283
341
  if (type === "string") {
284
- return send(res, val, MIMES.html);
342
+ return send(event, val, MIMES.html);
285
343
  } else if (isStream(val)) {
286
- return sendStream(res, val);
344
+ return sendStream(event, val);
287
345
  } else if (type === "object" || type === "boolean" || type === "number") {
288
346
  if (val && val.buffer) {
289
- return send(res, val);
347
+ return send(event, val);
290
348
  } else if (val instanceof Error) {
291
349
  throw createError(val);
292
350
  } else {
293
- return send(res, JSON.stringify(val, null, spacing), MIMES.json);
351
+ return send(event, JSON.stringify(val, null, spacing), MIMES.json);
294
352
  }
295
353
  }
296
354
  }
297
- if (!res.writableEnded) {
355
+ if (!event.res.writableEnded) {
298
356
  throw createError({ statusCode: 404, statusMessage: "Not Found" });
299
357
  }
300
- };
358
+ });
301
359
  }
302
- function normalizeLayer(layer) {
303
- if (layer.promisify === void 0) {
304
- layer.promisify = layer.handle.length > 2;
360
+ function normalizeLayer(input) {
361
+ let handler = input.handler;
362
+ if (handler.handler) {
363
+ handler = handler.handler;
364
+ }
365
+ if (!isEventHandler(handler)) {
366
+ if (input.lazy) {
367
+ handler = defineLazyHandler(handler);
368
+ }
369
+ handler = toEventHandler(handler);
305
370
  }
306
371
  return {
307
- route: withoutTrailingSlash(layer.route),
308
- match: layer.match,
309
- handle: layer.lazy ? lazyHandle(layer.handle, layer.promisify) : layer.promisify ? promisifyHandle(layer.handle) : layer.handle
372
+ route: withoutTrailingSlash(input.route),
373
+ match: input.match,
374
+ handler
310
375
  };
311
376
  }
312
377
 
@@ -315,28 +380,34 @@ function createRouter() {
315
380
  const _router = createRouter$1({});
316
381
  const routes = {};
317
382
  const router = {};
318
- router.add = (path, handle, method = "all") => {
383
+ const addRoute = (path, handler, method) => {
319
384
  let route = routes[path];
320
385
  if (!route) {
321
386
  routes[path] = route = { handlers: {} };
322
387
  _router.insert(path, route);
323
388
  }
324
- route.handlers[method] = handle;
389
+ route.handlers[method] = toEventHandler(handler);
325
390
  return router;
326
391
  };
392
+ router.use = router.add = (path, handler, method) => addRoute(path, handler, method || "all");
327
393
  for (const method of RouterMethods) {
328
394
  router[method] = (path, handle) => router.add(path, handle, method);
329
395
  }
330
- router.handle = (req, res) => {
331
- const matched = _router.lookup(req.url || "/");
396
+ router.handler = defineEventHandler((event) => {
397
+ let path = event.req.url || "/";
398
+ const queryUrlIndex = path.lastIndexOf("?");
399
+ if (queryUrlIndex > -1) {
400
+ path = path.substring(0, queryUrlIndex);
401
+ }
402
+ const matched = _router.lookup(path);
332
403
  if (!matched) {
333
404
  throw createError({
334
405
  statusCode: 404,
335
406
  name: "Not Found",
336
- statusMessage: `Cannot find any route matching ${req.url || "/"}.`
407
+ statusMessage: `Cannot find any route matching ${event.req.url || "/"}.`
337
408
  });
338
409
  }
339
- const method = (req.method || "get").toLowerCase();
410
+ const method = (event.req.method || "get").toLowerCase();
340
411
  const handler = matched.handlers[method] || matched.handlers.all;
341
412
  if (!handler) {
342
413
  throw createError({
@@ -345,10 +416,11 @@ function createRouter() {
345
416
  statusMessage: `Method ${method} is not allowed on this route.`
346
417
  });
347
418
  }
348
- req.params = matched.params || {};
349
- return handler(req, res);
350
- };
419
+ event.event.params = matched.params || {};
420
+ event.req.params = event.event.params;
421
+ return handler(event);
422
+ });
351
423
  return router;
352
424
  }
353
425
 
354
- export { H3Error, MIMES, appendHeader, assertMethod, callHandle, createApp, createError, createHandle, createRouter, defaultContentType, defineHandle, defineMiddleware, deleteCookie, isMethod, isStream, lazyHandle, promisifyHandle, send, sendError, sendRedirect, sendStream, setCookie, use, useBase, useBody, useCookie, useCookies, useMethod, useQuery, useRawBody };
426
+ export { H3Error, MIMES, appendHeader, assertMethod, callHandler, createApp, createAppEventHandler, createError, createEvent, createRouter, defaultContentType, defineEventHandler, defineHandle, defineHandler, defineLazyEventHandler, defineLazyHandler, defineMiddleware, deleteCookie, isEvent, isEventHandler, isMethod, isStream, lazyHandle, promisifyHandle, promisifyHandler, send, sendError, sendRedirect, sendStream, setCookie, toEventHandler, use, useBase, useBody, useCookie, useCookies, useMethod, useQuery, useRawBody };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "h3",
3
- "version": "0.4.2",
3
+ "version": "0.5.0",
4
4
  "description": "Tiny JavaScript Server",
5
5
  "repository": "unjs/h3",
6
6
  "license": "MIT",
@@ -47,11 +47,12 @@
47
47
  "packageManager": "pnpm@6.32.3",
48
48
  "scripts": {
49
49
  "build": "unbuild",
50
- "dev": "jiti ./playground/index.ts",
50
+ "dev": "vitest",
51
51
  "lint": "eslint --ext ts,mjs,cjs .",
52
+ "play": "jiti ./playground/index.ts",
52
53
  "profile": "0x -o -D .profile -P 'autocannon -c 100 -p 10 -d 40 http://localhost:$PORT' ./playground/server.cjs",
53
54
  "release": "pnpm lint && pnpm test && pnpm build && standard-version && pnpm publish && git push --follow-tags",
54
55
  "test": "vitest run"
55
56
  },
56
- "readme": "[![npm downloads](https://img.shields.io/npm/dm/h3.svg?style=flat-square)](https://npmjs.com/package/h3)\n[![version](https://img.shields.io/npm/v/h3/latest.svg?style=flat-square)](https://npmjs.com/package/h3)\n[![bundlephobia](https://img.shields.io/bundlephobia/min/h3/latest.svg?style=flat-square)](https://bundlephobia.com/result?p=h3)\n[![build status](https://img.shields.io/github/workflow/status/unjs/h3/ci/main?style=flat-square)](https://github.com/unjs/h3/actions)\n[![coverage](https://img.shields.io/codecov/c/gh/unjs/h3/main?style=flat-square)](https://codecov.io/gh/unjs/h3)\n[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue?style=flat-square)](https://www.jsdocs.io/package/h3)\n\n> H3 is a minimal h(ttp) framework built for high performance and portability\n\n<!-- ![h3 - Tiny JavaScript Server](.github/banner.svg) -->\n\n## Features\n\n✔️ &nbsp;**Portable:** Works perfectly in Serverless, Workers, and Node.js\n\n✔️ &nbsp;**Compatible:** Support connect/express middleware\n\n✔️ &nbsp;**Minimal:** Small, tree-shakable and zero-dependency\n\n✔️ &nbsp;**Modern:** Native promise support\n\n✔️ &nbsp;**Extendable:** Ships with a set of composable utilities but can be extended\n\n✔️ &nbsp;**Router:** Super fast route matching using [unjs/radix3](https://github.com/unjs/radix3)\n\n## Install\n\n```bash\n# Using npm\nnpm install h3\n\n# Using pnpm\npnpm add h3\n\n# Using pnpm\npnpm add h3\n```\n\n## Usage\n\n```ts\nimport { createServer } from 'http'\nimport { createApp } from 'h3'\n\nconst app = createApp()\napp.use('/', () => 'Hello world!')\n\ncreateServer(app).listen(process.env.PORT || 3000)\n```\n\n<details>\n <summary>Example using <a href=\"https://github.com/unjs/listhen\">listhen</a> for an elegant listener.</summary>\n\n```ts\nimport { createApp } from 'h3'\nimport { listen } from 'listhen'\n\nconst app = createApp()\napp.use('/', () => 'Hello world!')\n\nlisten(app)\n```\n</details>\n\n## Router\n\nThe `app` instance created by `h3` uses a middleware stack (see [how it works](#how-it-works)) with the ability to match route prefix and apply matched middleware.\n\nTo opt-in using a more advanced and convenient routing system, we can create a router instance and register it to app instance.\n\n```ts\nimport { createApp, createRouter } from 'h3'\n\nconst app = createApp()\n\nconst router = createRouter()\n .get('/', () => 'Hello World!')\n .get('/hello/:name', req => `Hello ${req.params.name}!`)\n\napp.use(router)\n```\n\n**Tip:** We can register same route more than once with different methods.\n\nRoutes are internally stored in a [Radix Tree](https://en.wikipedia.org/wiki/Radix_tree) and matched using [unjs/radix3](https://github.com/unjs/radix3).\n\n## More usage examples\n\n```js\n// Handle can directly return object or Promise<object> for JSON response\napp.use('/api', (req) => ({ url: req.url }))\n\n// We can have better matching other than quick prefix match\napp.use('/odd', () => 'Is odd!', { match: url => url.substr(1) % 2 })\n\n// Handle can directly return string for HTML response\napp.use(() => '<h1>Hello world!</h1>')\n\n// We can chain calls to .use()\napp.use('/1', () => '<h1>Hello world!</h1>')\n .use('/2', () => '<h1>Goodbye!</h1>')\n\n// Legacy middleware with 3rd argument are automatically promisified\napp.use((req, res, next) => { req.setHeader('X-Foo', 'bar'); next() })\n\n// Force promisify a legacy middleware\n// app.use(someMiddleware, { promisify: true })\n\n// Lazy loaded routes using { lazy: true }\n// app.use('/big', () => import('./big'), { lazy: true })\n```\n\n## Utilities\n\nInstead of adding helpers to `req` and `res`, h3 exposes them as composable utilities.\n\n- `useRawBody(req, encoding?)`\n- `useBody(req)`\n- `useCookies(req)`\n- `useCookie(req, name)`\n- `setCookie(res, name, value, opts?)`\n- `deleteCookie(res, name, opts?)`\n- `useQuery(req)`\n- `send(res, data, type?)`\n- `sendRedirect(res, location, code=302)`\n- `appendHeader(res, name, value)`\n- `createError({ statusCode, statusMessage, data? })`\n- `sendError(res, error, debug?)`\n- `defineHandle(handle)`\n- `defineMiddleware(middlware)`\n- `useMethod(req, default?)`\n- `isMethod(req, expected, allowHead?)`\n- `assertMethod(req, expected, allowHead?)`\n\n👉 You can learn more about usage in [JSDocs Documentation](https://www.jsdocs.io/package/h3#package-functions).\n\n## How it works?\n\nUsing `createApp`, it returns a standard `(req, res)` handler function and internally an array called middleware stack. using`use()` method we can add an item to this internal stack.\n\nWhen a request comes, each stack item that matches the route will be called and resolved until [`res.writableEnded`](https://nodejs.org/api/http.html#http_response_writableended) flag is set, which means the response is sent. If `writableEnded` is not set after all middleware, a `404` error will be thrown. And if one of the stack items resolves to a value, it will be serialized and sent as response as a shorthand method to sending responses.\n\nFor maximum compatibility with connect/express middleware (`req, res, next?` signature), h3 converts classic middleware into a promisified version ready to use with stack runner:\n\n- If middleware has 3rd next/callback param, the promise will `resolve/reject` when called\n- If middleware returns a promise, it will be **chained** to the main promise\n- If calling middleware throws an immediate error, the promise will be rejected\n- On `close` and `error` events of res, the promise will `resolve/reject` (to ensure if middleware simply calls `res.end`)\n\n## License\n\nMIT\n"
57
+ "readme": "[![npm downloads](https://img.shields.io/npm/dm/h3.svg?style=flat-square)](https://npmjs.com/package/h3)\n[![version](https://img.shields.io/npm/v/h3/latest.svg?style=flat-square)](https://npmjs.com/package/h3)\n[![bundlephobia](https://img.shields.io/bundlephobia/min/h3/latest.svg?style=flat-square)](https://bundlephobia.com/result?p=h3)\n[![build status](https://img.shields.io/github/workflow/status/unjs/h3/ci/main?style=flat-square)](https://github.com/unjs/h3/actions)\n[![coverage](https://img.shields.io/codecov/c/gh/unjs/h3/main?style=flat-square)](https://codecov.io/gh/unjs/h3)\n[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue?style=flat-square)](https://www.jsdocs.io/package/h3)\n\n> H3 is a minimal h(ttp) framework built for high performance and portability\n\n<!-- ![h3 - Tiny JavaScript Server](.github/banner.svg) -->\n\n## Features\n\n✔️ &nbsp;**Portable:** Works perfectly in Serverless, Workers, and Node.js\n\n✔️ &nbsp;**Compatible:** Support connect/express middleware\n\n✔️ &nbsp;**Minimal:** Small, tree-shakable and zero-dependency\n\n✔️ &nbsp;**Modern:** Native promise support\n\n✔️ &nbsp;**Extendable:** Ships with a set of composable utilities but can be extended\n\n✔️ &nbsp;**Router:** Super fast route matching using [unjs/radix3](https://github.com/unjs/radix3)\n\n## Install\n\n```bash\n# Using npm\nnpm install h3\n\n# Using yarn\nyarn add h3\n\n# Using pnpm\npnpm add h3\n```\n\n## Usage\n\n```ts\nimport { createServer } from 'http'\nimport { createApp } from 'h3'\n\nconst app = createApp()\napp.use('/', () => 'Hello world!')\n\ncreateServer(app).listen(process.env.PORT || 3000)\n```\n\n<details>\n <summary>Example using <a href=\"https://github.com/unjs/listhen\">listhen</a> for an elegant listener.</summary>\n\n```ts\nimport { createApp } from 'h3'\nimport { listen } from 'listhen'\n\nconst app = createApp()\napp.use('/', () => 'Hello world!')\n\nlisten(app)\n```\n</details>\n\n## Router\n\nThe `app` instance created by `h3` uses a middleware stack (see [how it works](#how-it-works)) with the ability to match route prefix and apply matched middleware.\n\nTo opt-in using a more advanced and convenient routing system, we can create a router instance and register it to app instance.\n\n```ts\nimport { createApp, createRouter } from 'h3'\n\nconst app = createApp()\n\nconst router = createRouter()\n .get('/', () => 'Hello World!')\n .get('/hello/:name', req => `Hello ${req.params.name}!`)\n\napp.use(router)\n```\n\n**Tip:** We can register same route more than once with different methods.\n\nRoutes are internally stored in a [Radix Tree](https://en.wikipedia.org/wiki/Radix_tree) and matched using [unjs/radix3](https://github.com/unjs/radix3).\n\n## More usage examples\n\n```js\n// Handle can directly return object or Promise<object> for JSON response\napp.use('/api', (req) => ({ url: req.url }))\n\n// We can have better matching other than quick prefix match\napp.use('/odd', () => 'Is odd!', { match: url => url.substr(1) % 2 })\n\n// Handle can directly return string for HTML response\napp.use(() => '<h1>Hello world!</h1>')\n\n// We can chain calls to .use()\napp.use('/1', () => '<h1>Hello world!</h1>')\n .use('/2', () => '<h1>Goodbye!</h1>')\n\n// Legacy middleware with 3rd argument are automatically promisified\napp.use((req, res, next) => { req.setHeader('X-Foo', 'bar'); next() })\n\n// Force promisify a legacy middleware\n// app.use(someMiddleware, { promisify: true })\n\n// Lazy loaded routes using { lazy: true }\n// app.use('/big', () => import('./big'), { lazy: true })\n```\n\n## Utilities\n\nInstead of adding helpers to `req` and `res`, h3 exposes them as composable utilities.\n\n- `useRawBody(req, encoding?)`\n- `useBody(req)`\n- `useCookies(req)`\n- `useCookie(req, name)`\n- `setCookie(res, name, value, opts?)`\n- `deleteCookie(res, name, opts?)`\n- `useQuery(req)`\n- `send(res, data, type?)`\n- `sendRedirect(res, location, code=302)`\n- `appendHeader(res, name, value)`\n- `createError({ statusCode, statusMessage, data? })`\n- `sendError(res, error, debug?)`\n- `defineHandle(handle)`\n- `defineMiddleware(middlware)`\n- `useMethod(req, default?)`\n- `isMethod(req, expected, allowHead?)`\n- `assertMethod(req, expected, allowHead?)`\n\n👉 You can learn more about usage in [JSDocs Documentation](https://www.jsdocs.io/package/h3#package-functions).\n\n## How it works?\n\nUsing `createApp`, it returns a standard `(req, res)` handler function and internally an array called middleware stack. using`use()` method we can add an item to this internal stack.\n\nWhen a request comes, each stack item that matches the route will be called and resolved until [`res.writableEnded`](https://nodejs.org/api/http.html#http_response_writableended) flag is set, which means the response is sent. If `writableEnded` is not set after all middleware, a `404` error will be thrown. And if one of the stack items resolves to a value, it will be serialized and sent as response as a shorthand method to sending responses.\n\nFor maximum compatibility with connect/express middleware (`req, res, next?` signature), h3 converts classic middleware into a promisified version ready to use with stack runner:\n\n- If middleware has 3rd next/callback param, the promise will `resolve/reject` when called\n- If middleware returns a promise, it will be **chained** to the main promise\n- If calling middleware throws an immediate error, the promise will be rejected\n- On `close` and `error` events of res, the promise will `resolve/reject` (to ensure if middleware simply calls `res.end`)\n\n## License\n\nMIT\n"
57
58
  }