@depup/h3 2.0.1-rc.17-depup.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.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +25 -0
  3. package/bin/h3.mjs +35 -0
  4. package/changes.json +5 -0
  5. package/dist/THIRD-PARTY-LICENSES.md +70 -0
  6. package/dist/_entries/bun.d.mts +8 -0
  7. package/dist/_entries/bun.mjs +11 -0
  8. package/dist/_entries/cloudflare.d.mts +8 -0
  9. package/dist/_entries/cloudflare.mjs +11 -0
  10. package/dist/_entries/deno.d.mts +8 -0
  11. package/dist/_entries/deno.mjs +11 -0
  12. package/dist/_entries/generic.d.mts +8 -0
  13. package/dist/_entries/generic.mjs +11 -0
  14. package/dist/_entries/node.d.mts +12 -0
  15. package/dist/_entries/node.mjs +14 -0
  16. package/dist/_entries/service-worker.d.mts +8 -0
  17. package/dist/_entries/service-worker.mjs +11 -0
  18. package/dist/h3-C304D6TZ.d.mts +1275 -0
  19. package/dist/h3-CGHxXEqb.mjs +2605 -0
  20. package/dist/h3-DagAgogP.mjs +4 -0
  21. package/dist/h3-QfzdiyNf.d.mts +836 -0
  22. package/dist/tracing.d.mts +26 -0
  23. package/dist/tracing.mjs +76 -0
  24. package/package.json +128 -0
  25. package/skills/h3/SKILL.md +10 -0
  26. package/skills/h3/docs/TOC.md +35 -0
  27. package/skills/h3/docs/_navigation.json +311 -0
  28. package/skills/h3/docs/examples/handle-cookie.md +67 -0
  29. package/skills/h3/docs/examples/handle-session.md +130 -0
  30. package/skills/h3/docs/examples/index.md +16 -0
  31. package/skills/h3/docs/examples/serve-static-assets.md +66 -0
  32. package/skills/h3/docs/examples/stream-response.md +76 -0
  33. package/skills/h3/docs/examples/validate-data.md +193 -0
  34. package/skills/h3/docs/guide/advanced/nightly.md +13 -0
  35. package/skills/h3/docs/guide/advanced/plugins.md +50 -0
  36. package/skills/h3/docs/guide/advanced/websocket.md +124 -0
  37. package/skills/h3/docs/guide/api/h3.md +145 -0
  38. package/skills/h3/docs/guide/api/h3event.md +113 -0
  39. package/skills/h3/docs/guide/basics/error.md +117 -0
  40. package/skills/h3/docs/guide/basics/handler.md +165 -0
  41. package/skills/h3/docs/guide/basics/lifecycle.md +68 -0
  42. package/skills/h3/docs/guide/basics/middleware.md +97 -0
  43. package/skills/h3/docs/guide/basics/nested-apps.md +57 -0
  44. package/skills/h3/docs/guide/basics/response.md +162 -0
  45. package/skills/h3/docs/guide/basics/routing.md +92 -0
  46. package/skills/h3/docs/guide/index.md +117 -0
  47. package/skills/h3/docs/migration/index.md +200 -0
  48. package/skills/h3/docs/utils/community.md +42 -0
  49. package/skills/h3/docs/utils/cookie.md +33 -0
  50. package/skills/h3/docs/utils/index.md +46 -0
  51. package/skills/h3/docs/utils/mcp.md +71 -0
  52. package/skills/h3/docs/utils/more.md +78 -0
  53. package/skills/h3/docs/utils/proxy.md +31 -0
  54. package/skills/h3/docs/utils/request.md +355 -0
  55. package/skills/h3/docs/utils/response.md +144 -0
  56. package/skills/h3/docs/utils/security.md +109 -0
@@ -0,0 +1,1275 @@
1
+ import { C as DynamicEventHandler, D as EventHandlerRequest, E as EventHandlerObject, F as Middleware, L as MaybePromise$1, M as HTTPHandler, N as InferEventInput, O as EventHandlerResponse, R as TypedRequest, S as HTTPError, Y as CookieSerializeOptions, a as H3EventContext, b as ErrorDetails, d as H3RouteMeta, f as HTTPMethod, i as HTTPEvent, j as FetchableObject, k as EventHandlerWithFetch, l as H3Plugin, o as H3$1, r as H3Event, s as H3Config, t as H3, w as EventHandler } from "./h3-QfzdiyNf.mjs";
2
+ import { NodeServerRequest, NodeServerResponse, ServerRequest, ServerRequestContext } from "srvx";
3
+ import { Hooks, Hooks as WebSocketHooks, Message as WebSocketMessage, Peer, Peer as WebSocketPeer } from "crossws";
4
+ /**
5
+ * Checks if the input is an H3Event object.
6
+ * @param input - The input to check.
7
+ * @returns True if the input is an H3Event object, false otherwise.
8
+ * @see H3Event
9
+ */
10
+ declare function isEvent(input: any): input is H3Event;
11
+ /**
12
+ * Checks if the input is an object with `{ req: Request }` signature.
13
+ * @param input - The input to check.
14
+ * @returns True if the input is `{ req: Request }`
15
+ */
16
+ declare function isHTTPEvent(input: any): input is HTTPEvent;
17
+ /**
18
+ * Gets the context of the event, if it does not exists, initializes a new context on `req.context`.
19
+ */
20
+ declare function getEventContext<T extends ServerRequestContext | H3EventContext>(event: HTTPEvent | H3Event): T;
21
+ declare function mockEvent(_request: string | URL | Request, options?: RequestInit & {
22
+ h3?: H3EventContext;
23
+ }): H3Event;
24
+ /** The Standard Schema interface. */
25
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
26
+ /** The Standard Schema properties. */
27
+ readonly "~standard": Props<Input, Output>;
28
+ }
29
+ /** The Standard Schema properties interface. */
30
+ interface Props<Input = unknown, Output = Input> {
31
+ /** The version number of the standard. */
32
+ readonly version: 1;
33
+ /** The vendor name of the schema library. */
34
+ readonly vendor: string;
35
+ /** Validates unknown input values. */
36
+ readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
37
+ /** Inferred types associated with the schema. */
38
+ readonly types?: Types<Input, Output> | undefined;
39
+ }
40
+ /** The result interface of the validate function. */
41
+ type Result<Output> = SuccessResult<Output> | FailureResult;
42
+ /** The result interface if validation succeeds. */
43
+ interface SuccessResult<Output> {
44
+ /** The typed output value. */
45
+ readonly value: Output;
46
+ /** The non-existent issues. */
47
+ readonly issues?: undefined;
48
+ }
49
+ /** The result interface if validation fails. */
50
+ interface FailureResult {
51
+ /** The issues of failed validation. */
52
+ readonly issues: ReadonlyArray<Issue>;
53
+ }
54
+ /** The issue interface of the failure output. */
55
+ interface Issue {
56
+ /** The error message of the issue. */
57
+ readonly message: string;
58
+ /** The path of the issue, if any. */
59
+ readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
60
+ }
61
+ /** The path segment interface of the issue. */
62
+ interface PathSegment {
63
+ /** The key representing a path segment. */
64
+ readonly key: PropertyKey;
65
+ }
66
+ /** The Standard Schema types interface. */
67
+ interface Types<Input = unknown, Output = Input> {
68
+ /** The input type of the schema. */
69
+ readonly input: Input;
70
+ /** The output type of the schema. */
71
+ readonly output: Output;
72
+ }
73
+ /** Infers the output type of a Standard Schema. */
74
+ type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
75
+ type ValidateResult<T> = T | true | false | void;
76
+ type OnValidateError<Source extends string = string> = (result: FailureResult & {
77
+ _source?: Source;
78
+ }) => ErrorDetails;
79
+ declare function defineHandler<Req extends EventHandlerRequest = EventHandlerRequest, Res = EventHandlerResponse>(handler: EventHandler<Req, Res>): EventHandlerWithFetch<Req, Res>;
80
+ declare function defineHandler<Req extends EventHandlerRequest = EventHandlerRequest, Res = EventHandlerResponse>(def: EventHandlerObject<Req, Res>): EventHandlerWithFetch<Req, Res>;
81
+ type StringHeaders<T> = { [K in keyof T]: Extract<T[K], string> };
82
+ /**
83
+ * @experimental defineValidatedHandler is an experimental feature and API may change.
84
+ */
85
+ declare function defineValidatedHandler<RequestBody extends StandardSchemaV1, RequestHeaders extends StandardSchemaV1, RequestQuery extends StandardSchemaV1, Res extends EventHandlerResponse = EventHandlerResponse>(def: Omit<EventHandlerObject, "handler"> & {
86
+ validate?: {
87
+ body?: RequestBody;
88
+ headers?: RequestHeaders;
89
+ query?: RequestQuery;
90
+ onError?: OnValidateError;
91
+ };
92
+ handler: EventHandler<{
93
+ body: InferOutput<RequestBody>;
94
+ query: StringHeaders<InferOutput<RequestQuery>>;
95
+ }, Res>;
96
+ }): EventHandlerWithFetch<TypedRequest<InferOutput<RequestBody>, InferOutput<RequestHeaders>>, Res>;
97
+ declare function dynamicEventHandler(initial?: EventHandler | FetchableObject): DynamicEventHandler;
98
+ type MaybePromise<T> = T | Promise<T>;
99
+ declare function defineLazyEventHandler(loader: () => MaybePromise<HTTPHandler>): EventHandlerWithFetch;
100
+ declare function toEventHandler(handler: HTTPHandler | undefined): EventHandler | undefined;
101
+ declare function defineMiddleware(input: Middleware): Middleware;
102
+ declare function callMiddleware(event: H3Event, middleware: Middleware[], handler: EventHandler, index?: number): unknown | Promise<unknown>;
103
+ /**
104
+ * Converts any HTTPHandler or Middleware into Middleware.
105
+ *
106
+ * If FetchableObject or Handler returns a Response with 404 status, the next middleware will be called.
107
+ */
108
+ declare function toMiddleware(input: HTTPHandler | Middleware | undefined): Middleware;
109
+ declare function toResponse(val: unknown, event: H3Event, config?: H3Config): Response | Promise<Response>;
110
+ declare class HTTPResponse {
111
+ #private;
112
+ body?: BodyInit | null;
113
+ constructor(body: BodyInit | null, init?: Pick<ResponseInit, "status" | "statusText" | "headers">);
114
+ get status(): number;
115
+ get statusText(): string;
116
+ get headers(): Headers;
117
+ }
118
+ type NodeHandler = (req: NodeServerRequest, res: NodeServerResponse) => unknown | Promise<unknown>;
119
+ type NodeMiddleware = (req: NodeServerRequest, res: NodeServerResponse, next: (error?: Error) => void) => unknown | Promise<unknown>;
120
+ /**
121
+ * @deprecated Since h3 v2 you can directly use `app.fetch(request, init?, context?)`
122
+ */
123
+ declare function toWebHandler(app: H3): (request: ServerRequest, context?: H3EventContext) => Promise<Response>;
124
+ declare function fromWebHandler(handler: (request: ServerRequest, context?: H3EventContext) => Promise<Response>): EventHandler;
125
+ /**
126
+ * Convert a Node.js handler function (req, res, next?) to an EventHandler.
127
+ *
128
+ * **Note:** The returned event handler requires to be executed with h3 Node.js handler.
129
+ */
130
+ declare function fromNodeHandler(handler: NodeMiddleware): EventHandler;
131
+ declare function fromNodeHandler(handler: NodeHandler): EventHandler;
132
+ declare function defineNodeHandler(handler: NodeHandler): NodeHandler;
133
+ declare function defineNodeMiddleware(handler: NodeMiddleware): NodeMiddleware;
134
+ /**
135
+ * Route definition options
136
+ */
137
+ interface RouteDefinition {
138
+ /**
139
+ * HTTP method for the route, e.g. 'GET', 'POST', etc.
140
+ */
141
+ method: HTTPMethod;
142
+ /**
143
+ * Route pattern, e.g. '/api/users/:id'
144
+ */
145
+ route: string;
146
+ /**
147
+ * Handler function for the route.
148
+ */
149
+ handler: EventHandler;
150
+ /**
151
+ * Optional middleware to run before the handler.
152
+ */
153
+ middleware?: Middleware[];
154
+ /**
155
+ * Additional route metadata.
156
+ */
157
+ meta?: H3RouteMeta;
158
+ validate?: {
159
+ body?: StandardSchemaV1;
160
+ headers?: StandardSchemaV1;
161
+ query?: StandardSchemaV1;
162
+ };
163
+ }
164
+ /**
165
+ * Define a route as a plugin that can be registered with app.register()
166
+ *
167
+ * @example
168
+ * ```js
169
+ * import { z } from "zod";
170
+ *
171
+ * const userRoute = defineRoute({
172
+ * method: 'POST',
173
+ * validate: {
174
+ * query: z.object({ id: z.string().uuid() }),
175
+ * body: z.object({ name: z.string() }),
176
+ * },
177
+ * handler: (event) => {
178
+ * return { success: true };
179
+ * }
180
+ * });
181
+ *
182
+ * app.register(userRoute);
183
+ * ```
184
+ */
185
+ declare function defineRoute(def: RouteDefinition): H3Plugin;
186
+ /**
187
+ * Remove a route handler from the app.
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * import { H3, removeRoute } from "h3";
192
+ *
193
+ * const app = new H3();
194
+ * app.get("/temp", () => "hello");
195
+ *
196
+ * removeRoute(app, "GET", "/temp"); // route removed
197
+ * ```
198
+ */
199
+ declare function removeRoute(app: H3$1, method: HTTPMethod | Lowercase<HTTPMethod> | "", route: string): void;
200
+ /**
201
+ * Create a lightweight request proxy that overrides only the URL.
202
+ *
203
+ * Avoids cloning the original request (no `new Request()` allocation).
204
+ */
205
+ declare function requestWithURL(req: ServerRequest, url: string): ServerRequest;
206
+ /**
207
+ * Create a lightweight request proxy with the base path stripped from the URL pathname.
208
+ */
209
+ declare function requestWithBaseURL(req: ServerRequest, base: string): ServerRequest;
210
+ /**
211
+ * Convert input into a web [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request).
212
+ *
213
+ * If input is a relative URL, it will be normalized into a full path based on headers.
214
+ *
215
+ * If input is already a Request and no options are provided, it will be returned as-is.
216
+ */
217
+ declare function toRequest(input: ServerRequest | URL | string, options?: RequestInit): ServerRequest;
218
+ /**
219
+ * Get parsed query string object from the request URL.
220
+ *
221
+ * @example
222
+ * app.get("/", (event) => {
223
+ * const query = getQuery(event); // { key: "value", key2: ["value1", "value2"] }
224
+ * });
225
+ */
226
+ declare function getQuery<T, Event extends H3Event | HTTPEvent = HTTPEvent, _T = Exclude<InferEventInput<"query", Event, T>, undefined>>(event: Event): _T;
227
+ declare function getValidatedQuery<Event extends HTTPEvent, S extends StandardSchemaV1<any, any>>(event: Event, validate: S, options?: {
228
+ onError?: (result: FailureResult) => ErrorDetails;
229
+ }): Promise<InferOutput<S>>;
230
+ declare function getValidatedQuery<Event extends HTTPEvent, OutputT, InputT = InferEventInput<"query", Event, OutputT>>(event: Event, validate: (data: InputT) => ValidateResult<OutputT> | Promise<ValidateResult<OutputT>>, options?: {
231
+ onError?: () => ErrorDetails;
232
+ }): Promise<OutputT>;
233
+ /**
234
+ * Get matched route params.
235
+ *
236
+ * If `decode` option is `true`, it will decode the matched route params using `decodeURIComponent`.
237
+ *
238
+ * @example
239
+ * app.get("/", (event) => {
240
+ * const params = getRouterParams(event); // { key: "value" }
241
+ * });
242
+ */
243
+ declare function getRouterParams(event: HTTPEvent, opts?: {
244
+ decode?: boolean;
245
+ }): NonNullable<H3Event["context"]["params"]>;
246
+ declare function getValidatedRouterParams<Event extends HTTPEvent, S extends StandardSchemaV1>(event: Event, validate: S, options?: {
247
+ decode?: boolean;
248
+ onError?: (result: FailureResult) => ErrorDetails;
249
+ }): Promise<InferOutput<S>>;
250
+ declare function getValidatedRouterParams<Event extends HTTPEvent, OutputT, InputT = InferEventInput<"routerParams", Event, OutputT>>(event: Event, validate: (data: InputT) => ValidateResult<OutputT> | Promise<ValidateResult<OutputT>>, options?: {
251
+ decode?: boolean;
252
+ onError?: () => ErrorDetails;
253
+ }): Promise<OutputT>;
254
+ /**
255
+ * Get a matched route param by name.
256
+ *
257
+ * If `decode` option is `true`, it will decode the matched route param using `decodeURI`.
258
+ *
259
+ * @example
260
+ * app.get("/", (event) => {
261
+ * const param = getRouterParam(event, "key");
262
+ * });
263
+ */
264
+ declare function getRouterParam(event: HTTPEvent, name: string, opts?: {
265
+ decode?: boolean;
266
+ }): string | undefined;
267
+ /**
268
+ *
269
+ * Checks if the incoming request method is of the expected type.
270
+ *
271
+ * If `allowHead` is `true`, it will allow `HEAD` requests to pass if the expected method is `GET`.
272
+ *
273
+ * @example
274
+ * app.get("/", (event) => {
275
+ * if (isMethod(event, "GET")) {
276
+ * // Handle GET request
277
+ * } else if (isMethod(event, ["POST", "PUT"])) {
278
+ * // Handle POST or PUT request
279
+ * }
280
+ * });
281
+ */
282
+ declare function isMethod(event: HTTPEvent, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): boolean;
283
+ /**
284
+ * Asserts that the incoming request method is of the expected type using `isMethod`.
285
+ *
286
+ * If the method is not allowed, it will throw a 405 error and include an `Allow`
287
+ * response header listing the permitted methods, as required by RFC 9110.
288
+ *
289
+ * If `allowHead` is `true`, it will allow `HEAD` requests to pass if the expected method is `GET`.
290
+ *
291
+ * @example
292
+ * app.get("/", (event) => {
293
+ * assertMethod(event, "GET");
294
+ * // Handle GET request, otherwise throw 405 error
295
+ * });
296
+ */
297
+ declare function assertMethod(event: HTTPEvent, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): void;
298
+ /**
299
+ * Get the request hostname.
300
+ *
301
+ * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.
302
+ *
303
+ * If no host header is found, it will return an empty string.
304
+ *
305
+ * @example
306
+ * app.get("/", (event) => {
307
+ * const host = getRequestHost(event); // "example.com"
308
+ * });
309
+ */
310
+ declare function getRequestHost(event: HTTPEvent, opts?: {
311
+ xForwardedHost?: boolean;
312
+ }): string;
313
+ /**
314
+ * Get the request protocol.
315
+ *
316
+ * If `x-forwarded-proto` header is set to "https", it will return "https". You can disable this behavior by setting `xForwardedProto` to `false`.
317
+ *
318
+ * If protocol cannot be determined, it will default to "http".
319
+ *
320
+ * @example
321
+ * app.get("/", (event) => {
322
+ * const protocol = getRequestProtocol(event); // "https"
323
+ * });
324
+ */
325
+ declare function getRequestProtocol(event: HTTPEvent | H3Event, opts?: {
326
+ xForwardedProto?: boolean;
327
+ }): "http" | "https" | (string & {});
328
+ /**
329
+ * Generated the full incoming request URL.
330
+ *
331
+ * If `xForwardedHost` is `true`, it will use the `x-forwarded-host` header if it exists.
332
+ *
333
+ * If `xForwardedProto` is `false`, it will not use the `x-forwarded-proto` header.
334
+ *
335
+ * @example
336
+ * app.get("/", (event) => {
337
+ * const url = getRequestURL(event); // "https://example.com/path"
338
+ * });
339
+ */
340
+ declare function getRequestURL(event: HTTPEvent | H3Event, opts?: {
341
+ xForwardedHost?: boolean;
342
+ xForwardedProto?: boolean;
343
+ }): URL;
344
+ /**
345
+ * Try to get the client IP address from the incoming request.
346
+ *
347
+ * If `xForwardedFor` is `true`, it will use the `x-forwarded-for` header if it exists.
348
+ *
349
+ * If IP cannot be determined, it will default to `undefined`.
350
+ *
351
+ * @example
352
+ * app.get("/", (event) => {
353
+ * const ip = getRequestIP(event); // "192.0.2.0"
354
+ * });
355
+ */
356
+ declare function getRequestIP(event: HTTPEvent, opts?: {
357
+ /**
358
+ * Use the X-Forwarded-For HTTP header set by proxies.
359
+ *
360
+ * Note: Make sure that this header can be trusted (your application running behind a CDN or reverse proxy) before enabling.
361
+ */
362
+ xForwardedFor?: boolean;
363
+ }): string | undefined;
364
+ type IterationSource<Val, Ret = Val> = Iterable<Val> | AsyncIterable<Val> | Iterator<Val, Ret | undefined> | AsyncIterator<Val, Ret | undefined> | (() => Iterator<Val, Ret | undefined> | AsyncIterator<Val, Ret | undefined>);
365
+ type IteratorSerializer<Value> = (value: Value) => Uint8Array | undefined;
366
+ /**
367
+ * Respond with an empty payload.<br>
368
+ *
369
+ * @example
370
+ * app.get("/", () => noContent());
371
+ *
372
+ * @param status status code to be send. By default, it is `204 No Content`.
373
+ */
374
+ declare function noContent(status?: number): HTTPResponse;
375
+ /**
376
+ * Send a redirect response to the client.
377
+ *
378
+ * It adds the `location` header to the response and sets the status code to 302 by default.
379
+ *
380
+ * In the body, it sends a simple HTML page with a meta refresh tag to redirect the client in case the headers are ignored.
381
+ *
382
+ * @example
383
+ * app.get("/", () => {
384
+ * return redirect("https://example.com");
385
+ * });
386
+ *
387
+ * @example
388
+ * app.get("/", () => {
389
+ * return redirect("https://example.com", 301); // Permanent redirect
390
+ * });
391
+ */
392
+ declare function redirect(location: string, status?: number, statusText?: string): HTTPResponse;
393
+ /**
394
+ * Redirect the client back to the previous page using the `referer` header.
395
+ *
396
+ * If the `referer` header is missing or is a different origin, it falls back to the provided URL (default `"/"`).
397
+ *
398
+ * By default, only the **pathname** of the referer is used (query string and hash are stripped)
399
+ * to prevent spoofed referers from carrying unintended parameters. Set `allowQuery: true` to preserve the query string.
400
+ *
401
+ * **Security:** The `fallback` value MUST be a trusted, hardcoded path — never use user input.
402
+ * Passing user-controlled values (e.g., query params) as `fallback` creates an open redirect vulnerability.
403
+ *
404
+ * @example
405
+ * app.post("/submit", (event) => {
406
+ * // process form...
407
+ * return redirectBack(event, { fallback: "/form" });
408
+ * });
409
+ */
410
+ declare function redirectBack(event: H3Event, opts?: {
411
+ /** Fallback URL when referer is missing or cross-origin (default: `"/"`). **Must be a trusted, hardcoded path — never user input.** */fallback?: string; /** HTTP status code for the redirect (default: `302`). */
412
+ status?: number; /** Preserve the query string from the referer URL (default: `false`). */
413
+ allowQuery?: boolean;
414
+ }): HTTPResponse;
415
+ /**
416
+ * Write `HTTP/1.1 103 Early Hints` to the client.
417
+ *
418
+ * In runtimes that don't support early hints natively, this function
419
+ * falls back to setting response headers which can be used by CDN.
420
+ */
421
+ declare function writeEarlyHints(event: H3Event, hints: Record<string, string | string[]>): void | Promise<void>;
422
+ /**
423
+ * Iterate a source of chunks and send back each chunk in order.
424
+ * Supports mixing async work together with emitting chunks.
425
+ *
426
+ * Each chunk must be a string or a buffer.
427
+ *
428
+ * For generator (yielding) functions, the returned value is treated the same as yielded values.
429
+ *
430
+ * @param iterable - Iterator that produces chunks of the response.
431
+ * @param serializer - Function that converts values from the iterable into stream-compatible values.
432
+ * @template Value - Test
433
+ *
434
+ * @example
435
+ * return iterable(async function* work() {
436
+ * // Open document body
437
+ * yield "<!DOCTYPE html>\n<html><body><h1>Executing...</h1><ol>\n";
438
+ * // Do work ...
439
+ * for (let i = 0; i < 1000; i++) {
440
+ * await delay(1000);
441
+ * // Report progress
442
+ * yield `<li>Completed job #`;
443
+ * yield i;
444
+ * yield `</li>\n`;
445
+ * }
446
+ * // Close out the report
447
+ * return `</ol></body></html>`;
448
+ * });
449
+ * async function delay(ms) {
450
+ * return new Promise((resolve) => setTimeout(resolve, ms));
451
+ * }
452
+ */
453
+ declare function iterable<Value = unknown, Return = unknown>(iterable: IterationSource<Value, Return>, options?: {
454
+ serializer: IteratorSerializer<Value | Return>;
455
+ }): HTTPResponse;
456
+ /**
457
+ * Respond with HTML content.
458
+ *
459
+ * @example
460
+ * app.get("/", () => html("<h1>Hello, World!</h1>"));
461
+ * app.get("/", () => html`<h1>Hello, ${name}!</h1>`);
462
+ */
463
+ declare function html(strings: TemplateStringsArray, ...values: unknown[]): HTTPResponse;
464
+ declare function html(markup: string): HTTPResponse;
465
+ /**
466
+ * Define a middleware that runs on each request.
467
+ */
468
+ declare function onRequest(hook: (event: H3Event) => MaybePromise$1<void>): Middleware;
469
+ /**
470
+ * Define a middleware that runs after Response is generated.
471
+ *
472
+ * You can return a new Response from the handler to replace the original response.
473
+ */
474
+ declare function onResponse(hook: (response: Response, event: H3Event) => unknown): Middleware;
475
+ /**
476
+ * Define a middleware that runs when an error occurs.
477
+ *
478
+ * You can return a new Response from the handler to gracefully handle the error.
479
+ */
480
+ declare function onError(hook: (error: HTTPError, event: H3Event) => unknown): Middleware;
481
+ /**
482
+ * Define a middleware that checks whether request body size is within specified limit.
483
+ *
484
+ * If body size exceeds the limit, throws a `413` Request Entity Too Large response error.
485
+ * If you need custom handling for this case, use `assertBodySize` instead.
486
+ *
487
+ * @param limit Body size limit in bytes
488
+ * @see {assertBodySize}
489
+ */
490
+ declare function bodyLimit(limit: number): Middleware;
491
+ interface ProxyOptions {
492
+ headers?: HeadersInit;
493
+ forwardHeaders?: string[];
494
+ filterHeaders?: string[];
495
+ fetchOptions?: RequestInit & {
496
+ duplex?: "half" | "full";
497
+ };
498
+ cookieDomainRewrite?: string | Record<string, string>;
499
+ cookiePathRewrite?: string | Record<string, string>;
500
+ onResponse?: (event: H3Event, response: Response) => void;
501
+ }
502
+ /**
503
+ * Proxy the incoming request to a target URL.
504
+ *
505
+ * If the `target` starts with `/`, the request is handled internally by the app router
506
+ * via `event.app.fetch()` instead of making an external HTTP request.
507
+ *
508
+ * **Security:** Never pass unsanitized user input as the `target`. Callers are
509
+ * responsible for validating and restricting the target URL (e.g. allowlisting
510
+ * hosts, blocking internal paths, enforcing protocol). Consider using
511
+ * `bodyLimit()` middleware to prevent large request bodies from consuming
512
+ * excessive resources when proxying untrusted input.
513
+ */
514
+ declare function proxyRequest(event: H3Event, target: string, opts?: ProxyOptions): Promise<HTTPResponse>;
515
+ /**
516
+ * Make a proxy request to a target URL and send the response back to the client.
517
+ *
518
+ * If the `target` starts with `/`, the request is dispatched internally via
519
+ * `event.app.fetch()` (sub-request) and never leaves the process. This bypasses
520
+ * any external security layer (reverse proxy auth, IP allowlisting, mTLS).
521
+ *
522
+ * **Security:** Never pass unsanitized user input as the `target`. Callers are
523
+ * responsible for validating and restricting the target URL (e.g. allowlisting
524
+ * hosts, blocking internal paths, enforcing protocol).
525
+ */
526
+ declare function proxy(event: H3Event, target: string, opts?: ProxyOptions): Promise<HTTPResponse>;
527
+ /**
528
+ * Get the request headers object without headers known to cause issues when proxying.
529
+ */
530
+ declare function getProxyRequestHeaders(event: H3Event, opts?: {
531
+ host?: boolean;
532
+ forwardHeaders?: string[];
533
+ filterHeaders?: string[];
534
+ }): Record<string, string>;
535
+ /**
536
+ * Make a fetch request with the event's context and headers.
537
+ *
538
+ * If the `url` starts with `/`, the request is dispatched internally via
539
+ * `event.app.fetch()` (sub-request) and never leaves the process.
540
+ *
541
+ * **Security:** Never pass unsanitized user input as the `url`. Callers are
542
+ * responsible for validating and restricting the URL.
543
+ */
544
+ declare function fetchWithEvent(event: H3Event, url: string, init?: RequestInit): Promise<Response>;
545
+ /**
546
+ * Reads request body and tries to parse using JSON.parse or URLSearchParams.
547
+ *
548
+ * @example
549
+ * app.get("/", async (event) => {
550
+ * const body = await readBody(event);
551
+ * });
552
+ *
553
+ * @param event H3 event passed by h3 handler
554
+ * @param encoding The character encoding to use, defaults to 'utf-8'.
555
+ *
556
+ * @return {*} The `Object`, `Array`, `String`, `Number`, `Boolean`, or `null` value corresponding to the request JSON body
557
+ */
558
+ declare function readBody<T, _Event extends HTTPEvent = HTTPEvent, _T = InferEventInput<"body", _Event, T>>(event: _Event): Promise<undefined | _T>;
559
+ declare function readValidatedBody<Event extends HTTPEvent, S extends StandardSchemaV1>(event: Event, validate: S, options?: {
560
+ onError?: (result: FailureResult) => ErrorDetails;
561
+ }): Promise<InferOutput<S>>;
562
+ declare function readValidatedBody<Event extends HTTPEvent, OutputT, InputT = InferEventInput<"body", Event, OutputT>>(event: Event, validate: (data: InputT) => ValidateResult<OutputT> | Promise<ValidateResult<OutputT>>, options?: {
563
+ onError?: () => ErrorDetails;
564
+ }): Promise<OutputT>;
565
+ /**
566
+ * Asserts that request body size is within the specified limit.
567
+ *
568
+ * If body size exceeds the limit, throws a `413` Request Entity Too Large response error.
569
+ *
570
+ * @example
571
+ * app.get("/", async (event) => {
572
+ * await assertBodySize(event, 10 * 1024 * 1024); // 10MB
573
+ * const data = await event.req.formData();
574
+ * });
575
+ *
576
+ * @param event HTTP event
577
+ * @param limit Body size limit in bytes
578
+ */
579
+ declare function assertBodySize(event: HTTPEvent, limit: number): Promise<void>;
580
+ /**
581
+ * Parse the request to get HTTP Cookie header string and returning an object of all cookie name-value pairs.
582
+ * @param event {HTTPEvent} H3 event or req passed by h3 handler
583
+ * @returns Object of cookie name-value pairs
584
+ * ```ts
585
+ * const cookies = parseCookies(event)
586
+ * ```
587
+ */
588
+ declare function parseCookies(event: HTTPEvent): Record<string, string>;
589
+ /**
590
+ * Get and validate all cookies using a Standard Schema or custom validator.
591
+ *
592
+ * @example
593
+ * app.get("/", async (event) => {
594
+ * const cookies = await getValidatedCookies(event, z.object({
595
+ * session: z.string(),
596
+ * theme: z.enum(["light", "dark"]).optional(),
597
+ * }));
598
+ * });
599
+ */
600
+ declare function getValidatedCookies<Event extends HTTPEvent, S extends StandardSchemaV1<any, any>>(event: Event, validate: S, options?: {
601
+ onError?: (result: FailureResult) => ErrorDetails;
602
+ }): Promise<InferOutput<S>>;
603
+ declare function getValidatedCookies<Event extends HTTPEvent, OutputT>(event: Event, validate: (data: Record<string, string>) => ValidateResult<OutputT> | Promise<ValidateResult<OutputT>>, options?: {
604
+ onError?: () => ErrorDetails;
605
+ }): Promise<OutputT>;
606
+ /**
607
+ * Get a cookie value by name.
608
+ * @param event {HTTPEvent} H3 event or req passed by h3 handler
609
+ * @param name Name of the cookie to get
610
+ * @returns {*} Value of the cookie (String or undefined)
611
+ * ```ts
612
+ * const authorization = getCookie(request, 'Authorization')
613
+ * ```
614
+ */
615
+ declare function getCookie(event: HTTPEvent, name: string): string | undefined;
616
+ /**
617
+ * Set a cookie value by name.
618
+ * @param event {H3Event} H3 event or res passed by h3 handler
619
+ * @param name Name of the cookie to set
620
+ * @param value Value of the cookie to set
621
+ * @param options {CookieSerializeOptions} Options for serializing the cookie
622
+ * ```ts
623
+ * setCookie(res, 'Authorization', '1234567')
624
+ * ```
625
+ */
626
+ declare function setCookie(event: H3Event, name: string, value: string, options?: CookieSerializeOptions): void;
627
+ /**
628
+ * Remove a cookie by name.
629
+ * @param event {H3Event} H3 event or res passed by h3 handler
630
+ * @param name Name of the cookie to delete
631
+ * @param serializeOptions {CookieSerializeOptions} Cookie options
632
+ * ```ts
633
+ * deleteCookie(res, 'SessionId')
634
+ * ```
635
+ */
636
+ declare function deleteCookie(event: H3Event, name: string, serializeOptions?: CookieSerializeOptions): void;
637
+ /**
638
+ * Get a chunked cookie value by name. Will join chunks together.
639
+ * @param event {HTTPEvent} { req: Request }
640
+ * @param name Name of the cookie to get
641
+ * @returns {*} Value of the cookie (String or undefined)
642
+ * ```ts
643
+ * const session = getChunkedCookie(event, 'Session')
644
+ * ```
645
+ */
646
+ declare function getChunkedCookie(event: HTTPEvent, name: string): string | undefined;
647
+ /**
648
+ * Set a cookie value by name. Chunked cookies will be created as needed.
649
+ * @param event {H3Event} H3 event or res passed by h3 handler
650
+ * @param name Name of the cookie to set
651
+ * @param value Value of the cookie to set
652
+ * @param options {CookieSerializeOptions} Options for serializing the cookie
653
+ * ```ts
654
+ * setCookie(res, 'Session', '<session data>')
655
+ * ```
656
+ */
657
+ declare function setChunkedCookie(event: H3Event, name: string, value: string, options?: CookieSerializeOptions & {
658
+ chunkMaxLength?: number;
659
+ }): void;
660
+ /**
661
+ * Remove a set of chunked cookies by name.
662
+ * @param event {H3Event} H3 event or res passed by h3 handler
663
+ * @param name Name of the cookie to delete
664
+ * @param serializeOptions {CookieSerializeOptions} Cookie options
665
+ * ```ts
666
+ * deleteCookie(res, 'Session')
667
+ * ```
668
+ */
669
+ declare function deleteChunkedCookie(event: H3Event, name: string, serializeOptions?: CookieSerializeOptions): void;
670
+ /**
671
+ * A helper class for [server sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format)
672
+ */
673
+ declare class EventStream {
674
+ private readonly _event;
675
+ private readonly _transformStream;
676
+ private readonly _writer;
677
+ private readonly _encoder;
678
+ private _writerIsClosed;
679
+ private _paused;
680
+ private _unsentData;
681
+ private _disposed;
682
+ private _handled;
683
+ constructor(event: H3Event, opts?: EventStreamOptions);
684
+ /**
685
+ * Publish new event(s) for the client
686
+ */
687
+ push(message: string): Promise<void>;
688
+ push(message: string[]): Promise<void>;
689
+ push(message: EventStreamMessage): Promise<void>;
690
+ push(message: EventStreamMessage[]): Promise<void>;
691
+ pushComment(comment: string): Promise<void>;
692
+ private _sendEvent;
693
+ private _sendEvents;
694
+ pause(): void;
695
+ get isPaused(): boolean;
696
+ resume(): Promise<void>;
697
+ flush(): Promise<void>;
698
+ /**
699
+ * Close the stream and the connection if the stream is being sent to the client
700
+ */
701
+ close(): Promise<void>;
702
+ /**
703
+ * Triggers callback when the writable stream is closed.
704
+ * It is also triggered after calling the `close()` method.
705
+ */
706
+ onClosed(cb: () => any): void;
707
+ send(): Promise<BodyInit>;
708
+ }
709
+ interface EventStreamOptions {
710
+ /**
711
+ * Automatically close the writable stream when the request is closed
712
+ *
713
+ * Default is `true`
714
+ */
715
+ autoclose?: boolean;
716
+ }
717
+ /**
718
+ * See https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#fields
719
+ */
720
+ interface EventStreamMessage {
721
+ id?: string;
722
+ event?: string;
723
+ retry?: number;
724
+ data: string;
725
+ }
726
+ /**
727
+ * Initialize an EventStream instance for creating [server sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)
728
+ *
729
+ * @experimental This function is experimental and might be unstable in some environments.
730
+ *
731
+ * @example
732
+ *
733
+ * ```ts
734
+ * import { createEventStream, sendEventStream } from "h3";
735
+ *
736
+ * app.get("/sse", (event) => {
737
+ * const eventStream = createEventStream(event);
738
+ *
739
+ * // Send a message every second
740
+ * const interval = setInterval(async () => {
741
+ * await eventStream.push("Hello world");
742
+ * }, 1000);
743
+ *
744
+ * // cleanup the interval and close the stream when the connection is terminated
745
+ * eventStream.onClosed(async () => {
746
+ * console.log("closing SSE...");
747
+ * clearInterval(interval);
748
+ * await eventStream.close();
749
+ * });
750
+ *
751
+ * return eventStream.send();
752
+ * });
753
+ * ```
754
+ */
755
+ declare function createEventStream(event: H3Event, opts?: EventStreamOptions): EventStream;
756
+ /**
757
+ * Append a `Server-Timing` entry to the response.
758
+ *
759
+ * Multiple calls append to the same header (comma-separated per spec).
760
+ *
761
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Server-Timing
762
+ *
763
+ * @example
764
+ * app.get("/", (event) => {
765
+ * setServerTiming(event, "db", { dur: 53, desc: "Database query" });
766
+ * return { data: "..." };
767
+ * });
768
+ * // Response header: Server-Timing: db;desc="Database query";dur=53
769
+ */
770
+ declare function setServerTiming(event: H3Event, name: string, opts?: {
771
+ dur?: number;
772
+ desc?: string;
773
+ }): void;
774
+ /**
775
+ * Measure an async operation and append the timing to the `Server-Timing` header.
776
+ *
777
+ * Uses `performance.now()` for high-resolution timing.
778
+ *
779
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Server-Timing
780
+ *
781
+ * @example
782
+ * app.get("/", async (event) => {
783
+ * const users = await withServerTiming(event, "db", () => fetchUsers());
784
+ * return users;
785
+ * });
786
+ * // Response header: Server-Timing: db;dur=42.5
787
+ */
788
+ declare function withServerTiming<T>(event: H3Event, name: string, fn: () => T | Promise<T>): Promise<T>;
789
+ /**
790
+ * Make sure the status message is safe to use in a response.
791
+ *
792
+ * Allowed characters: horizontal tabs, spaces or visible ascii characters: https://www.rfc-editor.org/rfc/rfc7230#section-3.1.2
793
+ */
794
+ declare function sanitizeStatusMessage(statusMessage?: string): string;
795
+ /**
796
+ * Make sure the status code is a valid HTTP status code.
797
+ */
798
+ declare function sanitizeStatusCode(statusCode?: string | number, defaultStatusCode?: number): number;
799
+ interface CacheConditions {
800
+ modifiedTime?: string | Date;
801
+ maxAge?: number;
802
+ etag?: string;
803
+ cacheControls?: string[];
804
+ }
805
+ /**
806
+ * Check request caching headers (`If-Modified-Since`) and add caching headers (Last-Modified, Cache-Control)
807
+ * Note: `public` cache control will be added by default
808
+ * @returns `true` when cache headers are matching. When `true` is returned, no response should be sent anymore
809
+ */
810
+ declare function handleCacheHeaders(event: H3Event, opts: CacheConditions): boolean;
811
+ interface StaticAssetMeta {
812
+ type?: string;
813
+ etag?: string;
814
+ mtime?: number | string | Date;
815
+ path?: string;
816
+ size?: number;
817
+ encoding?: string;
818
+ }
819
+ interface ServeStaticOptions {
820
+ /**
821
+ * This function should resolve asset meta
822
+ */
823
+ getMeta: (id: string) => StaticAssetMeta | undefined | Promise<StaticAssetMeta | undefined>;
824
+ /**
825
+ * This function should resolve asset content
826
+ */
827
+ getContents: (id: string) => BodyInit | null | undefined | Promise<BodyInit | null | undefined>;
828
+ /**
829
+ * Headers to set on the response
830
+ */
831
+ headers?: HeadersInit;
832
+ /**
833
+ * Map of supported encodings (compressions) and their file extensions.
834
+ *
835
+ * Each extension will be appended to the asset path to find the compressed version of the asset.
836
+ *
837
+ * @example { gzip: ".gz", br: ".br" }
838
+ */
839
+ encodings?: Record<string, string>;
840
+ /**
841
+ * Default index file to serve when the path is a directory
842
+ *
843
+ * @default ["/index.html"]
844
+ */
845
+ indexNames?: string[];
846
+ /**
847
+ * When set to true, the function will not throw 404 error when the asset meta is not found or meta validation failed
848
+ */
849
+ fallthrough?: boolean;
850
+ /**
851
+ * Custom MIME type resolver function
852
+ * @param ext - File extension including dot (e.g., ".css", ".js")
853
+ */
854
+ getType?: (ext: string) => string | undefined;
855
+ }
856
+ /**
857
+ * Dynamically serve static assets based on the request path.
858
+ */
859
+ declare function serveStatic(event: H3Event, options: ServeStaticOptions): Promise<HTTPResponse | undefined>;
860
+ /**
861
+ * Returns a new event handler that removes the base url of the event before calling the original handler.
862
+ *
863
+ * @example
864
+ * const api = new H3()
865
+ * .get("/", () => "Hello API!");
866
+ * const app = new H3();
867
+ * .use("/api/**", withBase("/api", api.handler));
868
+ *
869
+ * @param base The base path to prefix.
870
+ * @param handler The event handler to use with the adapted path.
871
+ */
872
+ declare function withBase(base: string, input: HTTPHandler): EventHandler;
873
+ /**
874
+ * Check if the origin is allowed.
875
+ */
876
+ declare function isCorsOriginAllowed(origin: string | null | undefined, options: CorsOptions): boolean;
877
+ interface CorsOptions {
878
+ /**
879
+ * This determines the value of the "access-control-allow-origin" response header.
880
+ * If "*", it can be used to allow all origins.
881
+ * If an array of strings or regular expressions, it can be used with origin matching.
882
+ * If a custom function, it's used to validate the origin. It takes the origin as an argument and returns `true` if allowed.
883
+ *
884
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
885
+ * @default "*"
886
+ */
887
+ origin?: "*" | "null" | (string | RegExp)[] | ((origin: string) => boolean);
888
+ /**
889
+ * This determines the value of the "access-control-allow-methods" response header of a preflight request.
890
+ *
891
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
892
+ * @default "*"
893
+ * @example ["GET", "HEAD", "PUT", "POST"]
894
+ */
895
+ methods?: "*" | string[];
896
+ /**
897
+ * This determines the value of the "access-control-allow-headers" response header of a preflight request.
898
+ *
899
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
900
+ * @default "*"
901
+ */
902
+ allowHeaders?: "*" | string[];
903
+ /**
904
+ * This determines the value of the "access-control-expose-headers" response header.
905
+ *
906
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
907
+ * @default "*"
908
+ */
909
+ exposeHeaders?: "*" | string[];
910
+ /**
911
+ * This determines the value of the "access-control-allow-credentials" response header.
912
+ * When request with credentials, the options that `origin`, `methods`, `exposeHeaders` and `allowHeaders` should not be set "*".
913
+ *
914
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
915
+ * @see https://fetch.spec.whatwg.org/#cors-protocol-and-credentials
916
+ * @default false
917
+ */
918
+ credentials?: boolean;
919
+ /**
920
+ * This determines the value of the "access-control-max-age" response header of a preflight request.
921
+ *
922
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
923
+ * @default false
924
+ */
925
+ maxAge?: string | false;
926
+ /**
927
+ *
928
+ * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
929
+ */
930
+ preflight?: {
931
+ statusCode?: number;
932
+ };
933
+ }
934
+ /**
935
+ * Check if the incoming request is a CORS preflight request.
936
+ */
937
+ declare function isPreflightRequest(event: HTTPEvent): boolean;
938
+ /**
939
+ * Append CORS preflight headers to the response.
940
+ */
941
+ declare function appendCorsPreflightHeaders(event: H3Event, options: CorsOptions): void;
942
+ /**
943
+ * Append CORS headers to the response.
944
+ */
945
+ declare function appendCorsHeaders(event: H3Event, options: CorsOptions): void;
946
+ /**
947
+ * Handle CORS for the incoming request.
948
+ *
949
+ * If the incoming request is a CORS preflight request, it will append the CORS preflight headers and send a 204 response.
950
+ *
951
+ * If return value is not `false`, the request is handled and no further action is needed.
952
+ *
953
+ * @example
954
+ * const app = new H3();
955
+ * app.all("/", async (event) => {
956
+ * const corsRes = handleCors(event, {
957
+ * origin: "*",
958
+ * preflight: {
959
+ * statusCode: 204,
960
+ * },
961
+ * methods: "*",
962
+ * });
963
+ * if (corsRes !== false) {
964
+ * return corsRes;
965
+ * }
966
+ * // Your code here
967
+ * });
968
+ */
969
+ declare function handleCors(event: H3Event, options: CorsOptions): false | HTTPResponse;
970
+ type _BasicAuthOptions = {
971
+ /**
972
+ * Validate username for basic auth.
973
+ */
974
+ username: string;
975
+ /***
976
+ * Simple password for basic auth.
977
+ */
978
+ password: string;
979
+ /**
980
+ * Custom validation function for basic auth.
981
+ */
982
+ validate: (username: string, password: string) => boolean | Promise<boolean>;
983
+ /**
984
+ * Realm for the basic auth challenge.
985
+ *
986
+ * Defaults to "auth".
987
+ */
988
+ realm: string;
989
+ };
990
+ type BasicAuthOptions = Partial<_BasicAuthOptions> & ({
991
+ validate: _BasicAuthOptions["validate"];
992
+ } | {
993
+ password: _BasicAuthOptions["password"];
994
+ });
995
+ /**
996
+ * Apply basic authentication for current request.
997
+ *
998
+ * @example
999
+ * import { defineHandler, requireBasicAuth } from "h3";
1000
+ * export default defineHandler(async (event) => {
1001
+ * await requireBasicAuth(event, { password: "test" });
1002
+ * return `Hello, ${event.context.basicAuth.username}!`;
1003
+ * });
1004
+ */
1005
+ declare function requireBasicAuth(event: HTTPEvent, opts: BasicAuthOptions): Promise<true>;
1006
+ /**
1007
+ * Create a basic authentication middleware.
1008
+ *
1009
+ * @example
1010
+ * import { H3, serve, basicAuth } from "h3";
1011
+ * const auth = basicAuth({ password: "test" });
1012
+ * app.get("/", (event) => `Hello ${event.context.basicAuth?.username}!`, [auth]);
1013
+ * serve(app, { port: 3000 });
1014
+ */
1015
+ declare function basicAuth(opts: BasicAuthOptions): Middleware;
1016
+ interface RequestFingerprintOptions {
1017
+ /** @default SHA-1 */
1018
+ hash?: false | "SHA-1";
1019
+ /** @default `true` */
1020
+ ip?: boolean;
1021
+ /** @default `false` */
1022
+ xForwardedFor?: boolean;
1023
+ /** @default `false` */
1024
+ method?: boolean;
1025
+ /** @default `false` */
1026
+ url?: boolean;
1027
+ /** @default `false` */
1028
+ userAgent?: boolean;
1029
+ }
1030
+ /**
1031
+ *
1032
+ * Get a unique fingerprint for the incoming request.
1033
+ *
1034
+ * @experimental Behavior of this utility might change in the future versions
1035
+ */
1036
+ declare function getRequestFingerprint(event: HTTPEvent, opts?: RequestFingerprintOptions): Promise<string | null>;
1037
+ /**
1038
+ * Define WebSocket hooks.
1039
+ *
1040
+ * @see https://h3.dev/guide/websocket
1041
+ */
1042
+ declare function defineWebSocket(hooks: Partial<Hooks>): Partial<Hooks>;
1043
+ /**
1044
+ * Define WebSocket event handler.
1045
+ *
1046
+ * @see https://h3.dev/guide/websocket
1047
+ */
1048
+ declare function defineWebSocketHandler(hooks: Partial<Hooks> | ((event: H3Event) => Partial<Hooks> | Promise<Partial<Hooks>>)): EventHandler;
1049
+ /**
1050
+ * JSON-RPC 2.0 Interfaces based on the specification.
1051
+ * https://www.jsonrpc.org/specification
1052
+ */
1053
+ /**
1054
+ * JSON-RPC 2.0 params.
1055
+ */
1056
+ type JsonRpcParams = Record<string, unknown> | unknown[];
1057
+ /**
1058
+ * JSON-RPC 2.0 Request object.
1059
+ */
1060
+ interface JsonRpcRequest<I extends JsonRpcParams | undefined = JsonRpcParams | undefined> {
1061
+ jsonrpc: "2.0";
1062
+ method: string;
1063
+ params?: I;
1064
+ id?: string | number | null;
1065
+ }
1066
+ /**
1067
+ * JSON-RPC 2.0 Error object.
1068
+ */
1069
+ interface JsonRpcError {
1070
+ code: number;
1071
+ message: string;
1072
+ data?: any;
1073
+ }
1074
+ /**
1075
+ * JSON-RPC 2.0 Response object.
1076
+ */
1077
+ type JsonRpcResponse<O = unknown> = {
1078
+ jsonrpc: "2.0";
1079
+ id: string | number | null;
1080
+ result: O;
1081
+ } | {
1082
+ jsonrpc: "2.0";
1083
+ id: string | number | null;
1084
+ error: JsonRpcError;
1085
+ };
1086
+ /**
1087
+ * A function that handles a JSON-RPC method call.
1088
+ * It receives the parameters from the request and the original H3Event.
1089
+ */
1090
+ type JsonRpcMethod<O = unknown, I extends JsonRpcParams | undefined = JsonRpcParams | undefined> = (data: JsonRpcRequest<I>, event: H3Event) => O | Promise<O>;
1091
+ /**
1092
+ * A function that handles a JSON-RPC method call over WebSocket.
1093
+ * It receives the parameters from the request and the WebSocket peer.
1094
+ */
1095
+ type JsonRpcWebSocketMethod<O = unknown, I extends JsonRpcParams | undefined = JsonRpcParams | undefined> = (data: JsonRpcRequest<I>, peer: Peer) => O | Promise<O>;
1096
+ /**
1097
+ * Creates an H3 event handler that implements the JSON-RPC 2.0 specification.
1098
+ *
1099
+ * @param methods A map of RPC method names to their handler functions.
1100
+ * @param middleware Optional middleware to apply to the handler.
1101
+ * @returns An H3 EventHandler.
1102
+ *
1103
+ * @example
1104
+ * app.post(
1105
+ * "/rpc",
1106
+ * defineJsonRpcHandler({
1107
+ * methods: {
1108
+ * echo: ({ params }, event) => {
1109
+ * return `Received \`${params}\` on path \`${event.url.pathname}\``;
1110
+ * },
1111
+ * sum: ({ params }, event) => {
1112
+ * return params.a + params.b;
1113
+ * },
1114
+ * },
1115
+ * }),
1116
+ * );
1117
+ */
1118
+ declare function defineJsonRpcHandler<RequestT extends EventHandlerRequest = EventHandlerRequest>(opts?: Omit<EventHandlerObject<RequestT>, "handler" | "fetch"> & {
1119
+ methods: Record<string, JsonRpcMethod>;
1120
+ }): EventHandler<RequestT>;
1121
+ /**
1122
+ * Creates an H3 event handler that implements JSON-RPC 2.0 over WebSocket.
1123
+ *
1124
+ * This is an opt-in feature that allows JSON-RPC communication over WebSocket
1125
+ * connections for bi-directional messaging. Each incoming WebSocket text message
1126
+ * is processed as a JSON-RPC request, and responses are sent back to the peer.
1127
+ *
1128
+ * @param opts Options including methods map and optional WebSocket hooks.
1129
+ * @returns An H3 EventHandler that upgrades to a WebSocket connection.
1130
+ *
1131
+ * @example
1132
+ * app.get(
1133
+ * "/rpc/ws",
1134
+ * defineJsonRpcWebSocketHandler({
1135
+ * methods: {
1136
+ * echo: ({ params }) => {
1137
+ * return `Received: ${Array.isArray(params) ? params[0] : params?.message}`;
1138
+ * },
1139
+ * sum: ({ params }) => {
1140
+ * return params.a + params.b;
1141
+ * },
1142
+ * },
1143
+ * }),
1144
+ * );
1145
+ *
1146
+ * @example
1147
+ * // With additional WebSocket hooks
1148
+ * app.get(
1149
+ * "/rpc/ws",
1150
+ * defineJsonRpcWebSocketHandler({
1151
+ * methods: {
1152
+ * greet: ({ params }) => `Hello, ${params.name}!`,
1153
+ * },
1154
+ * hooks: {
1155
+ * open(peer) {
1156
+ * console.log(`Peer connected: ${peer.id}`);
1157
+ * },
1158
+ * close(peer, details) {
1159
+ * console.log(`Peer disconnected: ${peer.id}`, details);
1160
+ * },
1161
+ * },
1162
+ * }),
1163
+ * );
1164
+ */
1165
+ declare function defineJsonRpcWebSocketHandler(opts: {
1166
+ methods: Record<string, JsonRpcWebSocketMethod>;
1167
+ hooks?: Partial<Omit<Hooks, "message">>;
1168
+ }): EventHandler;
1169
+ /** @deprecated Use `HTTPError` */
1170
+ type H3Error = HTTPError;
1171
+ /** @deprecated Use `HTTPError` */
1172
+ declare const H3Error: typeof HTTPError;
1173
+ /** @deprecated Use new HTTPError() */
1174
+ declare function createError(message: number, details?: ErrorDetails): HTTPError;
1175
+ /** @deprecated Use new HTTPError() */
1176
+ declare function createError(details: ErrorDetails): HTTPError;
1177
+ /**
1178
+ * @deprecated Use `HTTPError.isError`
1179
+ */
1180
+ declare function isError(input: any): input is HTTPError;
1181
+ /** @deprecated Please use `event.url` */
1182
+ declare const getRequestPath: (event: H3Event) => string;
1183
+ /** @deprecated Please use `event.req.headers.get(name)` */
1184
+ declare function getRequestHeader(event: H3Event, name: string): string | undefined;
1185
+ /** @deprecated Please use `event.req.headers.get(name)` */
1186
+ declare const getHeader: (event: H3Event, name: string) => string | undefined;
1187
+ /** @deprecated Please use `Object.fromEntries(event.req.headers.entries())` */
1188
+ declare function getRequestHeaders(event: H3Event): Record<string, string>;
1189
+ /** @deprecated Please use `Object.fromEntries(event.req.headers.entries())` */
1190
+ declare const getHeaders: (event: H3Event) => Record<string, string>;
1191
+ /** @deprecated Please use `event.req.method` */
1192
+ declare function getMethod(event: H3Event, defaultMethod?: string): string;
1193
+ /** @deprecated Please use `event.req.text()` or `event.req.arrayBuffer()` */
1194
+ declare function readRawBody<E extends "utf8" | false = "utf8">(event: H3Event, encoding?: E): E extends false ? Promise<Uint8Array | undefined> : Promise<string | undefined>;
1195
+ /** @deprecated Please use `event.req.formData()` */
1196
+ declare function readFormDataBody(event: H3Event): Promise<FormData>;
1197
+ /** @deprecated Please use `event.req.formData()` */
1198
+ declare const readFormData: (event: H3Event) => Promise<FormData>;
1199
+ /** @deprecated Please use `event.req.formData()` */
1200
+ declare function readMultipartFormData(event: H3Event): Promise<Array<{
1201
+ data: Uint8Array;
1202
+ name?: string;
1203
+ filename?: string;
1204
+ type?: string;
1205
+ }>>;
1206
+ /** @deprecated Please use `event.req.body` */
1207
+ declare function getBodyStream(event: H3Event): ReadableStream<Uint8Array> | undefined;
1208
+ /** @deprecated Please use `event.req.body` */
1209
+ declare const getRequestWebStream: (event: H3Event) => ReadableStream | undefined;
1210
+ /** @deprecated Please directly return stream */
1211
+ declare function sendStream(_event: H3Event, value: ReadableStream): ReadableStream;
1212
+ /** @deprecated Please use `return noContent(event)` */
1213
+ declare const sendNoContent: (event: H3Event, code?: number) => HTTPResponse;
1214
+ /** @deprecated Please use `return redirect(event, code)` */
1215
+ declare const sendRedirect: (event: H3Event, location: string, code: number) => HTTPResponse;
1216
+ /** @deprecated Please directly return response */
1217
+ declare const sendWebResponse: (response: Response) => Response;
1218
+ /** @deprecated Please use `return proxy(event)` */
1219
+ declare const sendProxy: (event: H3Event, target: string, opts?: ProxyOptions) => Promise<HTTPResponse>;
1220
+ /** @deprecated Please use `return iterable(event, value)` */
1221
+ declare const sendIterable: <Value = unknown, Return = unknown>(_event: H3Event, val: IterationSource<Value, Return>, options?: {
1222
+ serializer: IteratorSerializer<Value | Return>;
1223
+ }) => HTTPResponse;
1224
+ /** @deprecated Please use `event.res.statusText` */
1225
+ declare function getResponseStatusText(event: H3Event): string;
1226
+ /** @deprecated Please use `event.res.headers.append(name, value)` */
1227
+ declare function appendResponseHeader(event: H3Event, name: string, value: string | string[]): void;
1228
+ /** @deprecated Please use `event.res.headers.append(name, value)` */
1229
+ declare const appendHeader: (event: H3Event, name: string, value: string | string[]) => void;
1230
+ /** @deprecated Please use `event.res.headers.set(name, value)` */
1231
+ declare function setResponseHeader(event: H3Event, name: string, value: string | string[]): void;
1232
+ /** @deprecated Please use `event.res.headers.set(name, value)` */
1233
+ declare const setHeader: (event: H3Event, name: string, value: string | string[]) => void;
1234
+ /** @deprecated Please use `event.res.headers.set(name, value)` */
1235
+ declare function setResponseHeaders(event: H3Event, headers: Record<string, string>): void;
1236
+ /** @deprecated Please use `event.res.headers.set(name, value)` */
1237
+ declare const setHeaders: (event: H3Event, headers: Record<string, string>) => void;
1238
+ /** @deprecated Please use `event.res.status` */
1239
+ declare function getResponseStatus(event: H3Event): number;
1240
+ /** @deprecated Please directly set `event.res.status` and `event.res.statusText` */
1241
+ declare function setResponseStatus(event: H3Event, code?: number, text?: string): void;
1242
+ /** @deprecated Please use `event.res.headers.set("content-type", type)` */
1243
+ declare function defaultContentType(event: H3Event, type?: string): void;
1244
+ /** @deprecated Please use `Object.fromEntries(event.res.headers.entries())` */
1245
+ declare function getResponseHeaders(event: H3Event): Record<string, string>;
1246
+ /** @deprecated Please use `event.res.headers.get(name)` */
1247
+ declare function getResponseHeader(event: H3Event, name: string): string | undefined;
1248
+ /** @deprecated Please use `event.res.headers.delete(name)` instead. */
1249
+ declare function removeResponseHeader(event: H3Event, name: string): void;
1250
+ /** @deprecated Please use `event.res.headers.append(name, value)` */
1251
+ declare function appendResponseHeaders(event: H3Event, headers: string): void;
1252
+ /** @deprecated Please use `event.res.headers.append(name, value)` */
1253
+ declare const appendHeaders: (event: H3Event, headers: string) => void;
1254
+ /** @deprecated Please use `event.res.headers.delete` */
1255
+ declare function clearResponseHeaders(event: H3Event, headerNames?: string[]): void;
1256
+ declare const defineEventHandler: typeof defineHandler;
1257
+ declare const eventHandler: typeof defineHandler;
1258
+ declare const lazyEventHandler: typeof defineLazyEventHandler;
1259
+ /** @deprecated Please use `defineNodeHandler` */
1260
+ declare const defineNodeListener: typeof defineNodeHandler;
1261
+ /** @deprecated Please use `defineNodeHandler` */
1262
+ declare const fromNodeMiddleware: (handler: NodeHandler | NodeMiddleware) => EventHandler;
1263
+ /**
1264
+ * @deprecated please use `toNodeHandler` from `h3/node`.
1265
+ */
1266
+ declare function toNodeHandler(app: H3): NodeHandler;
1267
+ /** @deprecated Please use `toNodeHandler` */
1268
+ declare const toNodeListener: (app: H3) => NodeHandler;
1269
+ /** @deprecated Please use `new H3()` */
1270
+ declare const createApp: (config?: H3Config) => H3;
1271
+ /** @deprecated Please use `new H3()` */
1272
+ declare const createRouter: (config?: H3Config) => H3;
1273
+ /** @deprecated Please use `withBase()` */
1274
+ declare const useBase: (base: string, input: EventHandler | H3) => EventHandler;
1275
+ export { JsonRpcWebSocketMethod as $, noContent as $t, readFormDataBody as A, defineMiddleware as An, createEventStream as At, setHeader as B, mockEvent as Bn, readBody as Bt, getResponseHeader as C, defineNodeMiddleware as Cn, handleCacheHeaders as Ct, isError as D, HTTPResponse as Dn, withServerTiming as Dt, getResponseStatusText as E, toWebHandler as En, setServerTiming as Et, sendNoContent as F, dynamicEventHandler as Fn, getValidatedCookies as Ft, toNodeHandler as G, proxy as Gt, setResponseHeader as H, ProxyOptions as Ht, sendProxy as I, toEventHandler as In, parseCookies as It, JsonRpcError as J, onError as Jt, toNodeListener as K, proxyRequest as Kt, sendRedirect as L, getEventContext as Ln, setChunkedCookie as Lt, readRawBody as M, defineHandler as Mn, deleteCookie as Mt, removeResponseHeader as N, defineLazyEventHandler as Nn, getChunkedCookie as Nt, lazyEventHandler as O, toResponse as On, EventStreamMessage as Ot, sendIterable as P, defineValidatedHandler as Pn, getCookie as Pt, JsonRpcResponse as Q, iterable as Qt, sendStream as R, isEvent as Rn, setCookie as Rt, getRequestWebStream as S, defineNodeHandler as Sn, CacheConditions as St, getResponseStatus as T, fromWebHandler as Tn, sanitizeStatusMessage as Tt, setResponseHeaders as U, fetchWithEvent as Ut, setHeaders as V, readValidatedBody as Vt, setResponseStatus as W, getProxyRequestHeaders as Wt, JsonRpcParams as X, onResponse as Xt, JsonRpcMethod as Y, onRequest as Yt, JsonRpcRequest as Z, html as Zt, getHeaders as _, RouteDefinition as _n, isCorsOriginAllowed as _t, appendResponseHeaders as a, getRequestHost as an, defineWebSocket as at, getRequestHeaders as b, NodeHandler as bn, StaticAssetMeta as bt, createError as c, getRequestURL as cn, getRequestFingerprint as ct, defineEventHandler as d, getValidatedQuery as dn, requireBasicAuth as dt, redirect as en, defineJsonRpcHandler as et, defineNodeListener as f, getValidatedRouterParams as fn, CorsOptions as ft, getHeader as g, toRequest as gn, isPreflightRequest as gt, getBodyStream as h, requestWithURL as hn, handleCors as ht, appendResponseHeader as i, getQuery as in, WebSocketPeer as it, readMultipartFormData as j, toMiddleware as jn, deleteChunkedCookie as jt, readFormData as k, callMiddleware as kn, EventStreamOptions as kt, createRouter as l, getRouterParam as ln, BasicAuthOptions as lt, fromNodeMiddleware as m, requestWithBaseURL as mn, appendCorsPreflightHeaders as mt, appendHeader as n, writeEarlyHints as nn, WebSocketHooks as nt, clearResponseHeaders as o, getRequestIP as on, defineWebSocketHandler as ot, eventHandler as p, isMethod as pn, appendCorsHeaders as pt, useBase as q, bodyLimit as qt, appendHeaders as r, assertMethod as rn, WebSocketMessage as rt, createApp as s, getRequestProtocol as sn, RequestFingerprintOptions as st, H3Error as t, redirectBack as tn, defineJsonRpcWebSocketHandler as tt, defaultContentType as u, getRouterParams as un, basicAuth as ut, getMethod as v, defineRoute as vn, withBase as vt, getResponseHeaders as w, fromNodeHandler as wn, sanitizeStatusCode as wt, getRequestPath as x, NodeMiddleware as xn, serveStatic as xt, getRequestHeader as y, removeRoute as yn, ServeStaticOptions as yt, sendWebResponse as z, isHTTPEvent as zn, assertBodySize as zt };