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

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