express-zod-api 29.0.0-beta.2 → 29.0.0-beta.3

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.
@@ -0,0 +1,742 @@
1
+ import { z } from "zod";
2
+ import { HttpError } from "http-errors";
3
+ import "ansis";
4
+ import express, { IRouter, NextFunction, Request, RequestHandler, Response } from "express";
5
+ import { ServerOptions } from "node:https";
6
+ import compression from "compression";
7
+ import fileUpload from "express-fileupload";
8
+ import cookieParser from "cookie-parser";
9
+ import { ListenOptions } from "node:net";
10
+ declare const defaultStatusCodes: {
11
+ positive: number;
12
+ negative: number;
13
+ };
14
+ type ResponseVariant = keyof typeof defaultStatusCodes;
15
+ /**
16
+ * @desc A container for describing an API response: its schema, status code(s) and MIME type(s).
17
+ * @see ResultHandler
18
+ * */
19
+ interface ApiResponse<S extends z.ZodType> {
20
+ /** @desc The Zod schema describing the response body. */
21
+ schema: S;
22
+ /**
23
+ * @desc The status code(s) for this response.
24
+ * @default 200 for a positive response, 400 for a negative one
25
+ * */
26
+ statusCode?: number | [number, ...number[]];
27
+ /**
28
+ * @desc The MIME type(s) of the response.
29
+ * @default "application/json"
30
+ * @example null — no content, typical for 204 and 302
31
+ * */
32
+ mimeType?: string | [string, ...string[]] | null;
33
+ }
34
+ declare const severity: {
35
+ debug: number;
36
+ info: number;
37
+ warn: number;
38
+ error: number;
39
+ };
40
+ type Severity = keyof typeof severity;
41
+ /** @desc You can use any logger compatible with this type. */
42
+ type AbstractLogger = Record<Severity, (message: string, meta?: any) => any>;
43
+ /**
44
+ * @desc Using module augmentation approach you can set the type of the actual logger used
45
+ * @example declare module "express-zod-api" { interface LoggerOverrides extends winston.Logger {} }
46
+ * @link https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
47
+ * */
48
+ interface LoggerOverrides {}
49
+ type ActualLogger = AbstractLogger & LoggerOverrides;
50
+ interface Context extends FlatObject {
51
+ requestId?: string;
52
+ }
53
+ interface BuiltinLoggerConfig {
54
+ /**
55
+ * @desc The minimal severity to log or "silent" to disable logging
56
+ * @example "debug" also enables pretty output for inspected entities
57
+ * */
58
+ level: "silent" | "warn" | "info" | "debug";
59
+ /** @desc Enables colors on printed severity and inspected entities */
60
+ color: boolean;
61
+ /**
62
+ * @desc Control how deeply entities should be inspected
63
+ * @example null
64
+ * @example Infinity
65
+ * */
66
+ depth: number | null;
67
+ /**
68
+ * @desc Context: the metadata applicable for each logged entry, used by .child() method
69
+ * @see childLoggerProvider
70
+ * */
71
+ ctx: Context;
72
+ }
73
+ interface ProfilerOptions {
74
+ message: string;
75
+ /** @default "debug" */
76
+ severity?: Severity | ((ms: number) => Severity);
77
+ /** @default formatDuration - adaptive units and limited fraction */
78
+ formatter?: (ms: number) => string | number;
79
+ }
80
+ /** @desc Built-in console logger with optional colorful inspections */
81
+ declare class BuiltinLogger implements AbstractLogger {
82
+ protected readonly config: BuiltinLoggerConfig;
83
+ /** @example new BuiltinLogger({ level: "debug", color: true, depth: 4 }) */
84
+ constructor({ color, level, depth, ctx }?: Partial<BuiltinLoggerConfig>);
85
+ protected format(subject: unknown): string;
86
+ protected print(method: Severity, message: string, meta?: unknown): void;
87
+ debug(message: string, meta?: unknown): void;
88
+ info(message: string, meta?: unknown): void;
89
+ warn(message: string, meta?: unknown): void;
90
+ error(message: string, meta?: unknown): void;
91
+ child(ctx: Context): BuiltinLogger;
92
+ /**
93
+ * @desc The argument used for instance created by .child() method
94
+ * @see ChildLoggerProvider
95
+ * */
96
+ get ctx(): Context;
97
+ /** @desc Measures the duration until you invoke the returned callback */
98
+ profile(message: string): () => void;
99
+ profile(options: ProfilerOptions): () => void;
100
+ }
101
+ declare const methods: ("get" | "post" | "put" | "delete" | "patch" | "query")[];
102
+ declare const clientMethods: ("get" | "post" | "put" | "delete" | "patch" | "head" | "query")[];
103
+ /**
104
+ * @desc Methods supported by the framework API to produce Endpoints on EndpointsFactory.
105
+ * @see BuildProps
106
+ * @example "get" | "post" | "put" | "delete" | "patch" | "query"
107
+ * */
108
+ type Method = (typeof methods)[number];
109
+ /**
110
+ * @desc Methods usable on the client side, available via generated Integration and Documentation
111
+ * @see withHead
112
+ * @example Method | "head"
113
+ * */
114
+ type ClientMethod = (typeof clientMethods)[number];
115
+ type Base = object & {
116
+ [Symbol.iterator]?: never;
117
+ };
118
+ /** @desc The type allowed on the top level of Middlewares and Endpoints */
119
+ type IOSchema = z.ZodType<Base>;
120
+ /** EndpointsFactory schema extended type when adding a Middleware */
121
+ type Extension<Current extends IOSchema | undefined, Inc extends IOSchema | undefined> = Current extends IOSchema
122
+ ? Inc extends IOSchema
123
+ ? z.ZodIntersection<Current, Inc>
124
+ : Current
125
+ : Inc;
126
+ /** The Endpoint input schema type, condition wrapped into schema to make it z.output-compatible */
127
+ type FinalInputSchema<FIN extends IOSchema | undefined, BIN extends IOSchema> = z.ZodIntersection<
128
+ FIN extends IOSchema ? FIN : BIN,
129
+ BIN
130
+ >;
131
+ type ResultSchema<R extends Result> = R extends Result<infer S> ? S : never;
132
+ type DiscriminatedResult =
133
+ | {
134
+ output: FlatObject;
135
+ error: null;
136
+ }
137
+ | {
138
+ output: null;
139
+ error: Error;
140
+ };
141
+ /**
142
+ * @example InputValidationError —> BadRequest(400)
143
+ * @example Error —> InternalServerError(500)
144
+ * */
145
+ declare const ensureHttpError: (error: Error) => HttpError;
146
+ type Handler$2<RES = unknown> = (
147
+ params: DiscriminatedResult & {
148
+ /** null in case of failure to parse or to find the matching endpoint (error: not found) */
149
+ input: FlatObject | null;
150
+ /** can be empty: check the presence of the required property using the "in" operator */
151
+ ctx: FlatObject;
152
+ request: Request;
153
+ response: Response<RES>;
154
+ logger: ActualLogger;
155
+ },
156
+ ) => void | Promise<void>;
157
+ /**
158
+ * @desc Result definition for ResultHandler: a plain schema (for JSON and default status codes) or custom ApiResponse.
159
+ * @see ApiResponse
160
+ * */
161
+ type Result<S extends z.ZodType = z.ZodType> = S | ApiResponse<S> | ApiResponse<S>[];
162
+ /** @desc A function that lazily produces a Result definition. */
163
+ type LazyResult<R extends Result, A extends unknown[] = []> = (...args: A) => R;
164
+ declare abstract class AbstractResultHandler {
165
+ protected constructor(handler: Handler$2);
166
+ execute(...params: Parameters<Handler$2>): Promise<void>;
167
+ }
168
+ /**
169
+ * @desc The entity responsible to respond consistently. Accepts positive and negative Result definitions.
170
+ * The positive definition can be a lazy function receiving the output schema of an Endpoint.
171
+ * @see Result
172
+ * */
173
+ declare class ResultHandler<POS extends Result, NEG extends Result> extends AbstractResultHandler {
174
+ constructor(params: {
175
+ /** @desc A description of the API response in case of success (schema, status code, MIME type) */
176
+ positive: POS | LazyResult<POS, [IOSchema]>;
177
+ /** @desc A description of the API response in case of error (schema, status code, MIME type) */
178
+ negative: NEG | LazyResult<NEG>;
179
+ /** @desc The actual implementation to transmit the response in any case */
180
+ handler: Handler$2<z.output<ResultSchema<POS> | ResultSchema<NEG>>>;
181
+ });
182
+ }
183
+ /**
184
+ * @desc The default ResultHandler wrapping Endpoint output in `{ status: "success", data: output }`
185
+ * and errors in `{ status: "error", error: { message } }`. Responds with JSON Content-Type.
186
+ * Respects the status of errors from createHttpError(), others become InternalServerError (500).
187
+ * @see ensureHttpError
188
+ * */
189
+ declare const defaultResultHandler: ResultHandler<
190
+ z.ZodObject<
191
+ {
192
+ status: z.ZodLiteral<"success">;
193
+ data: IOSchema;
194
+ },
195
+ z.core.$strip
196
+ >,
197
+ z.ZodObject<
198
+ {
199
+ status: z.ZodLiteral<"error">;
200
+ error: z.ZodObject<
201
+ {
202
+ message: z.ZodString;
203
+ },
204
+ z.core.$strip
205
+ >;
206
+ },
207
+ z.core.$strip
208
+ >
209
+ >;
210
+ /**
211
+ * @deprecated Resist the urge of using it: this handler is designed only to simplify the migration of legacy APIs.
212
+ * @desc Responding with an array is a bad practice keeping your endpoints from evolving without breaking changes.
213
+ * @desc This handler expects your endpoint to have the property 'items' in the output object schema
214
+ * */
215
+ declare const arrayResultHandler: ResultHandler<
216
+ z.ZodArray<z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>> | z.ZodArray<z.ZodAny>,
217
+ {
218
+ schema: z.ZodString;
219
+ mimeType: string;
220
+ }
221
+ >;
222
+ /** @desc Returns child logger for the given request (if configured) or the configured logger otherwise */
223
+ type GetLogger = (request?: Request) => ActualLogger;
224
+ type InputSource = keyof Pick<Request, "query" | "body" | "files" | "params" | "headers" | "cookies" | "signedCookies">;
225
+ type InputSources = Record<Method, InputSource[]>;
226
+ type ChildLoggerProvider = (params: { request: Request; parent: ActualLogger }) => ActualLogger | Promise<ActualLogger>;
227
+ type LogAccess = (request: Request, logger: ActualLogger) => void;
228
+ interface CommonConfig {
229
+ /**
230
+ * @desc Enables cross-origin resource sharing.
231
+ * @desc You can provide custom middleware or the `cors` package.
232
+ * @example cors({ origin: "https://example.com" }) // import cors from "cors"
233
+ * @link https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
234
+ * @link https://www.npmjs.com/package/cors
235
+ */
236
+ cors: boolean | RequestHandler;
237
+ /**
238
+ * @desc Controls how to respond to a request to an existing endpoint with an invalid HTTP method.
239
+ * @example true — respond with status code 405 and "Allow" header containing a list of valid methods
240
+ * @example false — respond with status code 404 (Not found)
241
+ * @default true
242
+ */
243
+ hintAllowedMethods?: boolean;
244
+ /**
245
+ * @desc Controls how to treat Routing keys matching HTTP methods ("get", "post") and having Endpoint assigned.
246
+ * @example true — treat such keys as HTTP methods complementing their parent paths
247
+ * { users: { get: ... }} becomes GET /users
248
+ * @example false — treat such keys as nested path segments regardless of the name
249
+ * { users: { get: ... }} remains /users/get
250
+ * @default true
251
+ */
252
+ recognizeMethodDependentRoutes?: boolean;
253
+ /**
254
+ * @desc The ResultHandler to use for handling routing, parsing and upload errors
255
+ * @default defaultResultHandler
256
+ * @see defaultResultHandler
257
+ */
258
+ errorHandler?: AbstractResultHandler;
259
+ /**
260
+ * @desc Built-in logger configuration or an instance of any compatible logger.
261
+ * @example { level: "debug", color: true }
262
+ * @default { level: NODE_ENV === "production" ? "warn" : "debug", color: isSupported(), depth: 2 }
263
+ * */
264
+ logger?: Partial<BuiltinLoggerConfig> | AbstractLogger;
265
+ /**
266
+ * @desc A child logger returned by this function can override the logger in all handlers for each request
267
+ * @example ({ parent }) => parent.child({ requestId: uuid() })
268
+ * */
269
+ childLoggerProvider?: ChildLoggerProvider;
270
+ /**
271
+ * @desc The function for producing access logs
272
+ * @default ({ method, path }, logger) => logger.debug(`${method}: ${path}`)
273
+ * @example null — disables the feature
274
+ * */
275
+ accessLogger?: null | LogAccess;
276
+ /**
277
+ * @desc You can disable the startup logo.
278
+ * @default true
279
+ */
280
+ startupLogo?: boolean;
281
+ /**
282
+ * @desc Which properties of request are combined into the input for endpoints and middlewares.
283
+ * @desc The order matters: priority from lowest to highest
284
+ * @default defaultInputSources
285
+ * @see defaultInputSources
286
+ */
287
+ inputSources?: Partial<InputSources>;
288
+ }
289
+ type BeforeUpload = (params: { request: Request; logger: ActualLogger }) => void | Promise<void>;
290
+ type UploadOptions = Pick<
291
+ fileUpload.Options,
292
+ | "createParentPath"
293
+ | "uriDecodeFileNames"
294
+ | "safeFileNames"
295
+ | "preserveExtension"
296
+ | "useTempFiles"
297
+ | "tempFileDir"
298
+ | "debug"
299
+ | "uploadTimeout"
300
+ | "limits"
301
+ > & {
302
+ /**
303
+ * @desc The error to throw when the file exceeds the configured fileSize limit (handled by errorHandler).
304
+ * @see limits
305
+ * @override limitHandler
306
+ * @example createHttpError(413, "The file is too large")
307
+ * */
308
+ limitError?: Error;
309
+ /**
310
+ * @desc A handler to execute before uploading — it can be used for restrictions by throwing an error.
311
+ * @example ({ request }) => { throw createHttpError(403, "Not authorized"); }
312
+ * */
313
+ beforeUpload?: BeforeUpload;
314
+ };
315
+ interface CookieParserOptions extends cookieParser.CookieParseOptions {
316
+ /** @desc The secret string or array used by cookie-parser for signed cookies */
317
+ secret?: Parameters<typeof cookieParser>[0];
318
+ }
319
+ type CompressionOptions = Pick<
320
+ compression.CompressionOptions,
321
+ "threshold" | "level" | "strategy" | "chunkSize" | "memLevel"
322
+ >;
323
+ interface GracefulOptions {
324
+ /**
325
+ * @desc Time given to drain ongoing requests before closing the server.
326
+ * @default 1000
327
+ * */
328
+ timeout?: number;
329
+ /**
330
+ * @desc Process event (Signal) that triggers the graceful shutdown.
331
+ * @see Signals
332
+ * @default [SIGINT, SIGTERM]
333
+ * */
334
+ events?: string[];
335
+ /** @desc The hook to call after the server was closed, but before terminating the process. */
336
+ beforeExit?: () => void | Promise<void>;
337
+ }
338
+ type ServerHook = (params: {
339
+ app: IRouter;
340
+ /** @desc Returns child logger for the given request (if configured) or the configured logger otherwise */
341
+ getLogger: GetLogger;
342
+ }) => void;
343
+ interface HttpConfig {
344
+ /** @desc Port, UNIX socket or custom options. */
345
+ listen: number | string | ListenOptions;
346
+ }
347
+ interface HttpsConfig extends HttpConfig {
348
+ /** @desc At least "cert" and "key" options required. */
349
+ options: ServerOptions;
350
+ }
351
+ interface ServerConfig extends CommonConfig {
352
+ /** @desc HTTP server configuration. */
353
+ http?: HttpConfig;
354
+ /** @desc HTTPS server configuration. */
355
+ https?: HttpsConfig;
356
+ /**
357
+ * @desc Custom JSON parser applied to all incoming requests.
358
+ * @default express.json()
359
+ * @link https://expressjs.com/en/5x/api.html#express.json
360
+ * */
361
+ jsonParser?: RequestHandler;
362
+ /**
363
+ * @desc Enable or configure uploads handling.
364
+ * @requires express-fileupload
365
+ * */
366
+ upload?: boolean | UploadOptions;
367
+ /**
368
+ * @desc Enable or configure response compression.
369
+ * @requires compression
370
+ */
371
+ compression?: boolean | CompressionOptions;
372
+ /**
373
+ * @desc Enable cookie parsing via cookie-parser.
374
+ * @requires cookie-parser
375
+ * @example true
376
+ * @example { secret: "my-secret" }
377
+ */
378
+ cookies?: boolean | CookieParserOptions;
379
+ /**
380
+ * @desc Configure or customize the parser for request query string
381
+ * @example "simple" // for "node:querystring" module, array elements must be repeated: ?a=1&a=2
382
+ * @example "extended" // for "qs" module, supports nested objects and arrays with brackets: ?a[]=1&a[]=2
383
+ * @example (query) => qs.parse(query, {comma: true}) // for comma-separated arrays: ?a=1,2,3
384
+ * @default "simple"
385
+ * @link https://expressjs.com/en/5x/api.html#req.query
386
+ */
387
+ queryParser?: "simple" | "extended" | ((query: string) => object);
388
+ /**
389
+ * @desc Custom parser for Buffer payloads applied to all incoming requests.
390
+ * @default express.raw()
391
+ * @link https://expressjs.com/en/5x/api.html#express.raw
392
+ * */
393
+ rawParser?: RequestHandler;
394
+ /**
395
+ * @desc Custom parser for URL Encoded requests applied to all incoming requests.
396
+ * @default express.urlencoded()
397
+ * @link https://expressjs.com/en/5x/api.html#express.urlencoded
398
+ * */
399
+ formParser?: RequestHandler;
400
+ /**
401
+ * @desc A code to execute before the installation of parsers (compression, cookies, CORS, body).
402
+ * @example ({ app }) => { app.use(helmet()); }
403
+ * */
404
+ beforeParsers?: ServerHook;
405
+ /**
406
+ * @desc A code to execute before processing the Routing of your API.
407
+ * @desc Runs after compression, cookies, CORS and body parsers are installed.
408
+ * @desc This can be a good place for express middlewares establishing their own routes.
409
+ * @desc It can help to avoid making a DIY solution based on the attachRouting() approach.
410
+ * @example ({ app }) => { app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); }
411
+ * */
412
+ beforeRouting?: ServerHook;
413
+ /**
414
+ * @desc A code to execute after processing the Routing of your API, but before error handling.
415
+ * @see beforeRouting
416
+ * */
417
+ afterRouting?: ServerHook;
418
+ /**
419
+ * @desc Rejects new connections and attempts to finish ongoing ones in the specified time before exit.
420
+ * */
421
+ gracefulShutdown?: boolean | GracefulOptions;
422
+ }
423
+ interface AppConfig extends CommonConfig {
424
+ /** @desc Your custom express app or express router instead. */
425
+ app: IRouter;
426
+ }
427
+ declare function createConfig(config: ServerConfig): ServerConfig;
428
+ declare function createConfig(config: AppConfig): AppConfig;
429
+ /** @since zod 3.25.61 output type fixed */
430
+ declare const emptySchema: z.ZodObject<{}, z.core.$strip>;
431
+ type EmptySchema = typeof emptySchema;
432
+ /** @desc this type does not allow props assignment, but it works for reading them when merged with another interface */
433
+ type EmptyObject = z.output<EmptySchema>;
434
+ type FlatObject = Record<string, unknown>;
435
+ /** @link https://stackoverflow.com/a/65492934 */
436
+ type NoNever<T, F> = [T] extends [never] ? F : T;
437
+ /**
438
+ * @desc Using module augmentation approach you can specify tags as the keys of this interface
439
+ * @example declare module "express-zod-api" { interface TagOverrides { users: unknown } }
440
+ * @link https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
441
+ * */
442
+ interface TagOverrides {}
443
+ type Tag = NoNever<keyof TagOverrides, string>;
444
+ declare const getMessageFromError: (error: Error) => string;
445
+ type LogicalOr<T> = {
446
+ or: T[];
447
+ };
448
+ type LogicalAnd<T> = {
449
+ and: T[];
450
+ };
451
+ type LogicalContainer<T> = LogicalOr<T | LogicalAnd<T>> | LogicalAnd<T | LogicalOr<T>> | T;
452
+ interface BasicSecurity {
453
+ type: "basic";
454
+ }
455
+ interface BearerSecurity {
456
+ type: "bearer";
457
+ format?: "JWT" | string;
458
+ }
459
+ interface InputSecurity<K extends string> {
460
+ type: "input";
461
+ name: K;
462
+ }
463
+ interface HeaderSecurity {
464
+ type: "header";
465
+ name: string;
466
+ }
467
+ interface CookieSecurity {
468
+ type: "cookie";
469
+ name: string;
470
+ }
471
+ /**
472
+ * @see https://swagger.io/docs/specification/authentication/openid-connect-discovery/
473
+ * @desc available scopes has to be provided via the specified URL
474
+ */
475
+ interface OpenIdSecurity {
476
+ type: "openid";
477
+ url: string;
478
+ }
479
+ interface AuthUrl {
480
+ /**
481
+ * @desc The authorization URL to use for this flow. Can be relative to the API server URL.
482
+ * @see https://swagger.io/docs/specification/api-host-and-base-path/
483
+ */
484
+ authorizationUrl: string;
485
+ }
486
+ interface DeviceAuthUrl {
487
+ /** @desc The device authorization URL to use for this flow (RFC 8628). Can be relative to the API server URL. */
488
+ deviceAuthorizationUrl: string;
489
+ }
490
+ interface TokenUrl {
491
+ /** @desc The token URL to use for this flow. Can be relative to the API server URL. */
492
+ tokenUrl: string;
493
+ }
494
+ interface RefreshUrl {
495
+ /** @desc The URL to be used for obtaining refresh tokens. Can be relative to the API server URL. */
496
+ refreshUrl?: string;
497
+ }
498
+ interface Scopes<K extends string> {
499
+ /** @desc The available scopes for the OAuth2 security and their short descriptions. Optional. */
500
+ scopes?: Record<K, string>;
501
+ }
502
+ type AuthCodeFlow<S extends string> = AuthUrl & TokenUrl & RefreshUrl & Scopes<S>;
503
+ type ImplicitFlow<S extends string> = AuthUrl & RefreshUrl & Scopes<S>;
504
+ type PasswordFlow<S extends string> = TokenUrl & RefreshUrl & Scopes<S>;
505
+ type ClientCredFlow<S extends string> = TokenUrl & RefreshUrl & Scopes<S>;
506
+ type DeviceAuthFlow<S extends string> = DeviceAuthUrl & TokenUrl & RefreshUrl & Scopes<S>;
507
+ /**
508
+ * @see https://swagger.io/docs/specification/authentication/oauth2/
509
+ */
510
+ interface OAuth2Security<S extends string> {
511
+ type: "oauth2";
512
+ /**
513
+ * @desc URL to OAuth 2.0 Authorization Server metadata document
514
+ * @link https://www.rfc-editor.org/rfc/rfc8414
515
+ * */
516
+ oauth2MetadataUrl?: string;
517
+ flows?: {
518
+ /** @desc Authorization Code flow (previously called accessCode in OpenAPI 2.0) */
519
+ authorizationCode?: AuthCodeFlow<S>;
520
+ /** @desc Implicit flow */
521
+ implicit?: ImplicitFlow<S>;
522
+ /** @desc Resource Owner Password flow */
523
+ password?: PasswordFlow<S>;
524
+ /** @desc Client Credentials flow (previously called application in OpenAPI 2.0) */
525
+ clientCredentials?: ClientCredFlow<S>;
526
+ /**
527
+ * @desc Device Authorization flow (OAuth 2.0 Device Authorization Grant)
528
+ * @link https://oauth.net/2/device-flow/
529
+ * */
530
+ deviceAuthorization?: DeviceAuthFlow<S>;
531
+ };
532
+ }
533
+ /**
534
+ * @desc Middleware security schema descriptor
535
+ * @param K is an optional input field used by InputSecurity
536
+ * @param S is an optional union of scopes used by OAuth2Security
537
+ * */
538
+ type Security<K extends string = string, S extends string = string> = (
539
+ | BasicSecurity
540
+ | BearerSecurity
541
+ | InputSecurity<K>
542
+ | HeaderSecurity
543
+ | CookieSecurity
544
+ | OpenIdSecurity
545
+ | OAuth2Security<S>
546
+ ) & {
547
+ deprecated?: boolean;
548
+ };
549
+ type Handler$1<IN, CTX, RET> = (params: {
550
+ /** @desc The inputs from the enabled input sources validated against the input schema of the Middleware. */
551
+ input: IN;
552
+ /**
553
+ * @desc The returns of the previously executed Middlewares (typed when chaining Middlewares).
554
+ * @link https://github.com/RobinTail/express-zod-api/discussions/1250
555
+ * */
556
+ ctx: CTX;
557
+ /** @link https://expressjs.com/en/5x/api.html#req */
558
+ request: Request;
559
+ /** @link https://expressjs.com/en/5x/api.html#res */
560
+ response: Response;
561
+ /** @desc The instance of the configured logger. */
562
+ logger: ActualLogger;
563
+ }) => Promise<RET>;
564
+ declare abstract class AbstractMiddleware {
565
+ abstract execute(params: {
566
+ input: unknown;
567
+ ctx: FlatObject;
568
+ request: Request;
569
+ response: Response;
570
+ logger: ActualLogger;
571
+ }): Promise<FlatObject>;
572
+ }
573
+ /**
574
+ * @desc A Middleware that validates its input schema, executes its handler, and returns context properties available to
575
+ * next middlewares and the Endpoint handler. Can also declare security schemas for Documentation.
576
+ * @see EndpointsFactory#addMiddleware
577
+ * */
578
+ declare class Middleware<
579
+ CTX extends FlatObject,
580
+ RET extends FlatObject,
581
+ SCO extends string,
582
+ IN extends IOSchema | undefined = undefined,
583
+ > extends AbstractMiddleware {
584
+ constructor({
585
+ input,
586
+ security,
587
+ handler,
588
+ }: {
589
+ /**
590
+ * @desc Input schema of the Middleware, combining properties from all the enabled input sources
591
+ * @default undefined
592
+ * @see defaultInputSources
593
+ * */
594
+ input?: IN;
595
+ /**
596
+ * @desc Declaration of the security schemas implemented within the handler (used by Documentation).
597
+ * @see Documentation
598
+ * */
599
+ security?: LogicalContainer<Security<Extract<keyof z.input<IN>, string>, SCO>>;
600
+ /** @desc The handler returning a context available to Endpoints. */
601
+ handler: Handler$1<z.output<IN>, CTX, RET>;
602
+ });
603
+ /** @throws InputValidationError */
604
+ execute({
605
+ input,
606
+ ...rest
607
+ }: {
608
+ input: unknown;
609
+ ctx: CTX;
610
+ request: Request;
611
+ response: Response;
612
+ logger: ActualLogger;
613
+ }): Promise<RET>;
614
+ }
615
+ /**
616
+ * @desc A wrapper around native Express middlewares that converts them into the framework's Middleware instances.
617
+ * Optionally, a `provider` can extend the context, and a `transformer` can convert caught errors.
618
+ * @see EndpointsFactory#addExpressMiddleware
619
+ * */
620
+ declare class ExpressMiddleware<R extends Request, S extends Response, RET extends FlatObject> extends Middleware<
621
+ FlatObject,
622
+ RET,
623
+ string
624
+ > {
625
+ constructor(
626
+ nativeMw: (request: R, response: S, next: NextFunction) => any,
627
+ {
628
+ provider,
629
+ transformer,
630
+ }?: {
631
+ /** @desc Extracts context properties from request and response after the native middleware execution. */
632
+ provider?: (request: R, response: S) => RET | Promise<RET>;
633
+ /** @desc Transforms errors caught from the native middleware before they propagate further. */
634
+ transformer?: (err: Error) => Error;
635
+ },
636
+ );
637
+ }
638
+ type Handler<IN, OUT, CTX> = (params: {
639
+ /** @desc The inputs from the enabled input sources validated against the final input schema (incl. Middlewares) */
640
+ input: IN;
641
+ /** @desc The returns of the assigned Middlewares */
642
+ ctx: CTX;
643
+ /** @desc The instance of the configured logger */
644
+ logger: ActualLogger;
645
+ }) => Promise<OUT>;
646
+ declare abstract class AbstractEndpoint {
647
+ /** @desc Enables nested routes within the path assigned to the subject */
648
+ nest(routing: Routing): Routing;
649
+ /** @desc Marks the route as deprecated (makes a copy of the endpoint) */
650
+ abstract deprecated(): this;
651
+ abstract execute(params: {
652
+ request: Request;
653
+ response: Response;
654
+ logger: ActualLogger;
655
+ config: CommonConfig;
656
+ }): Promise<void>;
657
+ }
658
+ declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, CTX extends FlatObject> extends AbstractEndpoint {
659
+ constructor(def: {
660
+ deprecated?: boolean;
661
+ middlewares?: AbstractMiddleware[];
662
+ inputSchema: IN;
663
+ outputSchema: OUT;
664
+ handler: Handler<z.output<IN>, z.input<OUT>, CTX>;
665
+ resultHandler: AbstractResultHandler;
666
+ description?: string;
667
+ summary?: string;
668
+ getOperationId?: (method: ClientMethod) => string | undefined;
669
+ methods?: Method[];
670
+ scopes?: string[];
671
+ tags?: string[];
672
+ });
673
+ deprecated(): this;
674
+ execute({
675
+ request,
676
+ response,
677
+ logger,
678
+ config,
679
+ }: {
680
+ request: Request;
681
+ response: Response;
682
+ logger: ActualLogger;
683
+ config: CommonConfig;
684
+ }): Promise<undefined>;
685
+ }
686
+ type OriginalStatic = typeof express.static;
687
+ declare class ServeStatic {
688
+ constructor(...params: Parameters<OriginalStatic>);
689
+ }
690
+ /**
691
+ * @example { v1: { books: { ":bookId": getBookEndpoint } } }
692
+ * @example { "v1/books/:bookId": getBookEndpoint }
693
+ * @example { "get /v1/books/:bookId": getBookEndpoint }
694
+ * @example { v1: { "patch /books/:bookId": changeBookEndpoint } }
695
+ * @example { dependsOnMethod: { get: retrieveEndpoint, post: createEndpoint } }
696
+ * @see CommonConfig.recognizeMethodDependentRoutes
697
+ * */
698
+ interface Routing {
699
+ [K: string]: Routing | AbstractEndpoint | ServeStatic;
700
+ }
701
+ export {
702
+ ensureHttpError as A,
703
+ ResponseVariant as B,
704
+ CommonConfig as C,
705
+ ResultHandler as D,
706
+ AbstractResultHandler as E,
707
+ Method as F,
708
+ BuiltinLogger as I,
709
+ AbstractLogger as L,
710
+ FinalInputSchema as M,
711
+ IOSchema as N,
712
+ arrayResultHandler as O,
713
+ ClientMethod as P,
714
+ LoggerOverrides as R,
715
+ AppConfig as S,
716
+ createConfig as T,
717
+ EmptySchema as _,
718
+ Handler as a,
719
+ TagOverrides as b,
720
+ Middleware as c,
721
+ CookieSecurity as d,
722
+ HeaderSecurity as f,
723
+ EmptyObject as g,
724
+ OpenIdSecurity as h,
725
+ Endpoint as i,
726
+ Extension as j,
727
+ defaultResultHandler as k,
728
+ BasicSecurity as l,
729
+ OAuth2Security as m,
730
+ ServeStatic as n,
731
+ AbstractMiddleware as o,
732
+ InputSecurity as p,
733
+ AbstractEndpoint as r,
734
+ ExpressMiddleware as s,
735
+ Routing as t,
736
+ BearerSecurity as u,
737
+ FlatObject as v,
738
+ ServerConfig as w,
739
+ getMessageFromError as x,
740
+ Tag as y,
741
+ ApiResponse as z,
742
+ };