h3 0.4.1 → 0.5.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.
package/dist/index.d.ts CHANGED
@@ -1,54 +1,92 @@
1
- import { IncomingMessage, ServerResponse } from 'http';
1
+ import http from 'http';
2
+ import { CookieSerializeOptions } from 'cookie-es';
2
3
  import * as ufo from 'ufo';
3
4
 
4
- declare type Encoding = false | 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'latin1' | 'binary' | 'hex';
5
+ interface H3Event {
6
+ '__is_event__': true;
7
+ event: H3Event;
8
+ req: IncomingMessage;
9
+ res: ServerResponse;
10
+ /**
11
+ * Request params only filled with h3 Router handlers
12
+ */
13
+ params?: Record<string, any>;
14
+ }
15
+ declare type CompatibilityEvent = H3Event | IncomingMessage | ServerResponse;
16
+ declare type _JSONValue<T = string | number | boolean> = T | T[] | Record<string, T>;
17
+ declare type JSONValue = _JSONValue<_JSONValue>;
18
+ declare type H3Response = void | JSONValue | Buffer;
19
+ interface EventHandler {
20
+ '__is_handler__'?: true;
21
+ (event: CompatibilityEvent): H3Response | Promise<H3Response>;
22
+ }
23
+ declare function defineEventHandler(handler: EventHandler): EventHandler;
24
+ declare type LazyEventHandler = () => EventHandler | Promise<EventHandler>;
25
+ declare function defineLazyEventHandler(factory: LazyEventHandler): EventHandler;
26
+ declare function isEventHandler(input: any): input is EventHandler;
27
+ declare type CompatibilityEventHandler = EventHandler | Handler | Middleware;
28
+ declare function toEventHandler(handler: CompatibilityEventHandler): EventHandler;
29
+ declare function createEvent(req: http.IncomingMessage, res: http.ServerResponse): CompatibilityEvent;
30
+ declare function isEvent(input: any): input is H3Event;
5
31
 
6
- declare type Handle<T = any, ReqT = {}> = (req: IncomingMessage & ReqT, res: ServerResponse) => T;
7
- declare type PHandle = Handle<Promise<any>>;
32
+ interface IncomingMessage extends http.IncomingMessage {
33
+ originalUrl?: string;
34
+ event: H3Event;
35
+ req: H3Event['req'];
36
+ res: H3Event['res'];
37
+ }
38
+ interface ServerResponse extends http.ServerResponse {
39
+ event: H3Event;
40
+ res: H3Event['res'];
41
+ req: http.ServerResponse['req'] & {
42
+ event: H3Event;
43
+ originalUrl?: string;
44
+ };
45
+ }
46
+ declare type Handler<T = any, ReqT = {}> = (req: IncomingMessage & ReqT, res: ServerResponse) => T;
47
+ declare type PromisifiedHandler = Handler<Promise<any>>;
8
48
  declare type Middleware = (req: IncomingMessage, res: ServerResponse, next: (err?: Error) => any) => any;
9
- declare type LazyHandle = () => Handle | Promise<Handle>;
10
- declare const defineHandle: <T>(handler: Handle<T, {}>) => Handle<T, {}>;
11
- declare const defineMiddleware: (middleware: Middleware) => Middleware;
12
- declare function promisifyHandle(handle: Handle | Middleware): PHandle;
13
- declare function callHandle(handle: Middleware, req: IncomingMessage, res: ServerResponse): Promise<unknown>;
14
- declare function lazyHandle(handle: LazyHandle, promisify?: boolean): PHandle;
15
- declare function useBase(base: string, handle: PHandle): PHandle;
49
+ declare type LazyHandler = () => Handler | Promise<Handler>;
50
+ declare type Encoding = false | 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'latin1' | 'binary' | 'hex';
51
+ declare type HTTPMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE';
16
52
 
17
53
  interface Layer {
18
54
  route: string;
19
55
  match?: Matcher;
20
- handle: Handle;
56
+ handler: EventHandler;
21
57
  }
22
58
  declare type Stack = Layer[];
23
59
  interface InputLayer {
24
60
  route?: string;
25
61
  match?: Matcher;
26
- handle: Handle | LazyHandle;
62
+ handler: Handler | LazyHandler | EventHandler | LazyEventHandler;
27
63
  lazy?: boolean;
64
+ /** @deprecated */
65
+ handle?: Handler;
66
+ /** @deprecated */
28
67
  promisify?: boolean;
29
68
  }
30
69
  declare type InputStack = InputLayer[];
31
- declare type Matcher = (url: string, req?: IncomingMessage) => boolean;
70
+ declare type Matcher = (url: string, event?: CompatibilityEvent) => boolean;
32
71
  interface AppUse {
33
- (route: string | string[], handle: Middleware | Middleware[], options?: Partial<InputLayer>): App;
34
- (route: string | string[], handle: Handle | Handle[], options?: Partial<InputLayer>): App;
35
- (handle: Middleware | Middleware[], options?: Partial<InputLayer>): App;
36
- (handle: Handle | Handle[], options?: Partial<InputLayer>): App;
72
+ (route: string | string[], handler: CompatibilityEventHandler | CompatibilityEventHandler[], options?: Partial<InputLayer>): App;
73
+ (handler: CompatibilityEventHandler | CompatibilityEventHandler[], options?: Partial<InputLayer>): App;
37
74
  (options: InputLayer): App;
38
75
  }
39
- interface App {
40
- (req: IncomingMessage, res: ServerResponse): Promise<any>;
76
+ declare type NodeHandler = (req: http.IncomingMessage, res: http.ServerResponse) => Promise<void>;
77
+ interface App extends NodeHandler {
41
78
  stack: Stack;
42
- _handle: PHandle;
79
+ handler: EventHandler;
80
+ nodeHandler: NodeHandler;
43
81
  use: AppUse;
44
82
  }
45
83
  interface AppOptions {
46
84
  debug?: boolean;
47
- onError?: (error: Error, req: IncomingMessage, res: ServerResponse) => any;
85
+ onError?: (error: Error, event: CompatibilityEvent) => any;
48
86
  }
49
87
  declare function createApp(options?: AppOptions): App;
50
- declare function use(app: App, arg1: string | Handle | InputLayer | InputLayer[], arg2?: Handle | Partial<InputLayer> | Handle[] | Middleware | Middleware[], arg3?: Partial<InputLayer>): App;
51
- declare function createHandle(stack: Stack, options: AppOptions): PHandle;
88
+ declare function use(app: App, arg1: string | Handler | InputLayer | InputLayer[], arg2?: Handler | Partial<InputLayer> | Handler[] | Middleware | Middleware[], arg3?: Partial<InputLayer>): App;
89
+ declare function createAppEventHandler(stack: Stack, options: AppOptions): EventHandler;
52
90
 
53
91
  /**
54
92
  * H3 Runtime Error
@@ -77,30 +115,37 @@ declare function createError(input: Partial<H3Error>): H3Error;
77
115
  * H3 internally uses this function to handle unhandled errors.<br>
78
116
  * Note that calling this function will close the connection and no other data will be sent to client afterwards.
79
117
  *
80
- * @param res {ServerResponse} The ServerResponse object is passed as the second parameter in the handler function
118
+ @param event {CompatibilityEvent} H3 event or req passed by h3 handler
81
119
  * @param error {H3Error|Error} Raised error
82
120
  * @param debug {Boolean} Whether application is in debug mode.<br>
83
121
  * In the debug mode the stack trace of errors will be return in response.
84
122
  */
85
- declare function sendError(res: ServerResponse, error: Error | H3Error, debug?: boolean): void;
123
+ declare function sendError(event: CompatibilityEvent, error: Error | H3Error, debug?: boolean): void;
124
+
125
+ declare const defineHandler: <T>(handler: Handler<T, {}>) => Handler<T, {}>;
126
+ /** @deprecated Use defineHandler */
127
+ declare const defineHandle: <T>(handler: Handler<T, {}>) => Handler<T, {}>;
128
+ declare const defineMiddleware: (middleware: Middleware) => Middleware;
129
+ declare function promisifyHandler(handler: Handler | Middleware): PromisifiedHandler;
130
+ /** @deprecated Use defineHandler */
131
+ declare const promisifyHandle: typeof promisifyHandler;
132
+ declare function callHandler(handler: Middleware, req: IncomingMessage, res: ServerResponse): Promise<unknown>;
133
+ declare function defineLazyHandler(handler: LazyHandler, promisify?: boolean): Handler;
134
+ /** @deprecated Use defineLazyHandler */
135
+ declare const lazyHandle: typeof defineLazyHandler;
136
+ declare function useBase(base: string, handler: Handler): Handler;
86
137
 
87
- declare const RawBodySymbol: unique symbol;
88
- interface _IncomingMessage extends IncomingMessage {
89
- [RawBodySymbol]?: Promise<Buffer>;
90
- ParsedBodySymbol?: any;
91
- body?: any;
92
- }
93
138
  /**
94
139
  * Reads body of the request and returns encoded raw string (default) or `Buffer` if encoding if falsy.
95
- * @param req {IncomingMessage} An IncomingMessage object is created by [http.Server](https://nodejs.org/api/http.html#http_class_http_server)
140
+ * @param event {CompatibilityEvent} H3 event or req passed by h3 handler
96
141
  * @param encoding {Encoding} encoding="utf-8" - The character encoding to use.
97
142
  *
98
143
  * @return {String|Buffer} Encoded raw string or raw Buffer of the body
99
144
  */
100
- declare function useRawBody(req: _IncomingMessage, encoding?: Encoding): Encoding extends false ? Buffer : Promise<string>;
145
+ declare function useRawBody(event: CompatibilityEvent, encoding?: Encoding): Encoding extends false ? Buffer : Promise<string | Buffer>;
101
146
  /**
102
147
  * Reads request body and try to safely parse using [destr](https://github.com/unjs/destr)
103
- * @param req {IncomingMessage} An IncomingMessage object created by [http.Server](https://nodejs.org/api/http.html#http_class_http_server)
148
+ * @param event {CompatibilityEvent} H3 event or req passed by h3 handler
104
149
  * @param encoding {Encoding} encoding="utf-8" - The character encoding to use.
105
150
  *
106
151
  * @return {*} The `Object`, `Array`, `String`, `Number`, `Boolean`, or `null` value corresponding to the request JSON body
@@ -109,121 +154,35 @@ declare function useRawBody(req: _IncomingMessage, encoding?: Encoding): Encodin
109
154
  * const body = await useBody(req)
110
155
  * ```
111
156
  */
112
- declare function useBody<T = any>(req: _IncomingMessage): Promise<T>;
157
+ declare function useBody<T = any>(event: CompatibilityEvent): Promise<T>;
113
158
 
114
159
  declare const MIMES: {
115
160
  html: string;
116
161
  json: string;
117
162
  };
118
163
 
119
- /**
120
- * Additional serialization options
121
- */
122
- interface CookieSerializeOptions {
123
- /**
124
- * Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.3|Domain Set-Cookie attribute}. By default, no
125
- * domain is set, and most clients will consider the cookie to apply to only
126
- * the current domain.
127
- */
128
- domain?: string;
129
- /**
130
- * Specifies a function that will be used to encode a cookie's value. Since
131
- * value of a cookie has a limited character set (and must be a simple
132
- * string), this function can be used to encode a value into a string suited
133
- * for a cookie's value.
134
- *
135
- * The default function is the global `encodeURIComponent`, which will
136
- * encode a JavaScript string into UTF-8 byte sequences and then URL-encode
137
- * any that fall outside of the cookie range.
138
- */
139
- encode?(value: string): string;
140
- /**
141
- * Specifies the `Date` object to be the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.1|`Expires` `Set-Cookie` attribute}. By default,
142
- * no expiration is set, and most clients will consider this a "non-persistent cookie" and will delete
143
- * it on a condition like exiting a web browser application.
144
- *
145
- * *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}
146
- * states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
147
- * possible not all clients by obey this, so if both are set, they should
148
- * point to the same date and time.
149
- */
150
- expires?: Date;
151
- /**
152
- * Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.6|`HttpOnly` `Set-Cookie` attribute}.
153
- * When truthy, the `HttpOnly` attribute is set, otherwise it is not. By
154
- * default, the `HttpOnly` attribute is not set.
155
- *
156
- * *Note* be careful when setting this to true, as compliant clients will
157
- * not allow client-side JavaScript to see the cookie in `document.cookie`.
158
- */
159
- httpOnly?: boolean;
160
- /**
161
- * Specifies the number (in seconds) to be the value for the `Max-Age`
162
- * `Set-Cookie` attribute. The given number will be converted to an integer
163
- * by rounding down. By default, no maximum age is set.
164
- *
165
- * *Note* the {@link https://tools.ietf.org/html/rfc6265#section-5.3|cookie storage model specification}
166
- * states that if both `expires` and `maxAge` are set, then `maxAge` takes precedence, but it is
167
- * possible not all clients by obey this, so if both are set, they should
168
- * point to the same date and time.
169
- */
170
- maxAge?: number;
171
- /**
172
- * Specifies the value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.4|`Path` `Set-Cookie` attribute}.
173
- * By default, the path is considered the "default path".
174
- */
175
- path?: string;
176
- /**
177
- * Specifies the boolean or string to be the value for the {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|`SameSite` `Set-Cookie` attribute}.
178
- *
179
- * - `true` will set the `SameSite` attribute to `Strict` for strict same
180
- * site enforcement.
181
- * - `false` will not set the `SameSite` attribute.
182
- * - `'lax'` will set the `SameSite` attribute to Lax for lax same site
183
- * enforcement.
184
- * - `'strict'` will set the `SameSite` attribute to Strict for strict same
185
- * site enforcement.
186
- * - `'none'` will set the SameSite attribute to None for an explicit
187
- * cross-site cookie.
188
- *
189
- * More information about the different enforcement levels can be found in {@link https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-03#section-4.1.2.7|the specification}.
190
- *
191
- * *note* This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.
192
- */
193
- sameSite?: true | false | 'lax' | 'strict' | 'none';
194
- /**
195
- * Specifies the boolean value for the {@link https://tools.ietf.org/html/rfc6265#section-5.2.5|`Secure` `Set-Cookie` attribute}. When truthy, the
196
- * `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
197
- *
198
- * *Note* be careful when setting this to `true`, as compliant clients will
199
- * not send the cookie back to the server in the future if the browser does
200
- * not have an HTTPS connection.
201
- */
202
- secure?: boolean;
203
- }
204
-
205
164
  /**
206
165
  * Parse the request to get HTTP Cookie header string and returning an object of all cookie name-value pairs.
207
- * @param req {IncomingMessage} An IncomingMessage object created by [http.Server](https://nodejs.org/api/http.html#http_class_http_server)
166
+ * @param event {CompatibilityEvent} H3 event or req passed by h3 handler
208
167
  * @returns Object of cookie name-value pairs
209
168
  * ```ts
210
169
  * const cookies = useCookies(req)
211
170
  * ```
212
171
  */
213
- declare function useCookies(req: IncomingMessage): Record<string, string>;
172
+ declare function useCookies(event: CompatibilityEvent): Record<string, string>;
214
173
  /**
215
174
  * Get a cookie value by name.
216
- * @param req {IncomingMessage} An IncomingMessage object created by [http.Server](https://nodejs.org/api/http.html#http_class_http_server)
175
+ * @param event {CompatibilityEvent} H3 event or req passed by h3 handler
217
176
  * @param name Name of the cookie to get
218
177
  * @returns {*} Value of the cookie (String or undefined)
219
178
  * ```ts
220
179
  * const authorization = useCookie(request, 'Authorization')
221
180
  * ```
222
181
  */
223
- declare function useCookie(req: IncomingMessage, name: string): string | undefined;
182
+ declare function useCookie(event: CompatibilityEvent, name: string): string | undefined;
224
183
  /**
225
184
  * Set a cookie value by name.
226
- * @param res {ServerResponse} A ServerResponse object created by [http.Server](https://nodejs.org/api/http.html#http_class_http_server)
185
+ * @param event {CompatibilityEvent} H3 event or res passed by h3 handler
227
186
  * @param name Name of the cookie to set
228
187
  * @param value Value of the cookie to set
229
188
  * @param serializeOptions {CookieSerializeOptions} Options for serializing the cookie
@@ -231,40 +190,38 @@ declare function useCookie(req: IncomingMessage, name: string): string | undefin
231
190
  * setCookie(res, 'Authorization', '1234567')
232
191
  * ```
233
192
  */
234
- declare function setCookie(res: ServerResponse, name: string, value: string, serializeOptions?: CookieSerializeOptions): void;
193
+ declare function setCookie(event: CompatibilityEvent, name: string, value: string, serializeOptions?: CookieSerializeOptions): void;
235
194
  /**
236
195
  * Set a cookie value by name.
237
- * @param res {ServerResponse} A ServerResponse object created by [http.Server](https://nodejs.org/api/http.html#http_class_http_server)
196
+ * @param event {CompatibilityEvent} H3 event or res passed by h3 handler
238
197
  * @param name Name of the cookie to delete
239
198
  * @param serializeOptions {CookieSerializeOptions} Cookie options
240
199
  * ```ts
241
200
  * deleteCookie(res, 'SessionId')
242
201
  * ```
243
202
  */
244
- declare function deleteCookie(res: ServerResponse, name: string, serializeOptions?: CookieSerializeOptions): void;
245
-
246
- declare type HTTPMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE';
203
+ declare function deleteCookie(event: CompatibilityEvent, name: string, serializeOptions?: CookieSerializeOptions): void;
247
204
 
248
- declare function useQuery(req: IncomingMessage): ufo.QueryObject;
249
- declare function useMethod(req: IncomingMessage, defaultMethod?: HTTPMethod): HTTPMethod;
250
- declare function isMethod(req: IncomingMessage, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): boolean;
251
- declare function assertMethod(req: IncomingMessage, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): void;
205
+ declare function useQuery(event: CompatibilityEvent): ufo.QueryObject;
206
+ declare function useMethod(event: CompatibilityEvent, defaultMethod?: HTTPMethod): HTTPMethod;
207
+ declare function isMethod(event: CompatibilityEvent, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): boolean;
208
+ declare function assertMethod(event: CompatibilityEvent, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): void;
252
209
 
253
- declare function send(res: ServerResponse, data: any, type?: string): Promise<unknown>;
254
- declare function defaultContentType(res: ServerResponse, type?: string): void;
255
- declare function sendRedirect(res: ServerResponse, location: string, code?: number): Promise<unknown>;
256
- declare function appendHeader(res: ServerResponse, name: string, value: string): void;
210
+ declare function send(event: CompatibilityEvent, data: any, type?: string): Promise<void>;
211
+ declare function defaultContentType(event: CompatibilityEvent, type?: string): void;
212
+ declare function sendRedirect(event: CompatibilityEvent, location: string, code?: number): Promise<void>;
213
+ declare function appendHeader(event: CompatibilityEvent, name: string, value: string): void;
214
+ declare function isStream(data: any): any;
215
+ declare function sendStream(event: CompatibilityEvent, data: any): Promise<void>;
257
216
 
258
217
  declare type RouterMethod = Lowercase<HTTPMethod>;
259
- declare type HandleWithParams = Handle<any, {
260
- params: Record<string, string>;
261
- }>;
262
- declare type AddWithMethod = (path: string, handle: HandleWithParams) => Router;
263
- declare type AddRouteShortcuts = Record<Lowercase<HTTPMethod>, AddWithMethod>;
218
+ declare type RouterUse = (path: string, handler: CompatibilityEventHandler, method?: RouterMethod) => Router;
219
+ declare type AddRouteShortcuts = Record<RouterMethod, RouterUse>;
264
220
  interface Router extends AddRouteShortcuts {
265
- add: (path: string, handle: HandleWithParams, method?: RouterMethod | 'all') => Router;
266
- handle: Handle;
221
+ add: RouterUse;
222
+ use: RouterUse;
223
+ handler: EventHandler;
267
224
  }
268
225
  declare function createRouter(): Router;
269
226
 
270
- export { AddRouteShortcuts, AddWithMethod, App, AppOptions, AppUse, H3Error, Handle, HandleWithParams, InputLayer, InputStack, Layer, LazyHandle, MIMES, Matcher, Middleware, PHandle, Router, RouterMethod, Stack, appendHeader, assertMethod, callHandle, createApp, createError, createHandle, createRouter, defaultContentType, defineHandle, defineMiddleware, deleteCookie, isMethod, lazyHandle, promisifyHandle, send, sendError, sendRedirect, setCookie, use, useBase, useBody, useCookie, useCookies, useMethod, useQuery, useRawBody };
227
+ export { AddRouteShortcuts, App, AppOptions, AppUse, CompatibilityEvent, CompatibilityEventHandler, Encoding, EventHandler, H3Error, H3Event, H3Response, HTTPMethod, Handler, IncomingMessage, InputLayer, InputStack, JSONValue, Layer, LazyEventHandler, LazyHandler, MIMES, Matcher, Middleware, NodeHandler, PromisifiedHandler, Router, RouterMethod, RouterUse, ServerResponse, Stack, _JSONValue, 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 };