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.
package/dist/index.d.ts CHANGED
@@ -1,651 +1,51 @@
1
+ import {
2
+ A as ensureHttpError,
3
+ C as CommonConfig,
4
+ D as ResultHandler,
5
+ E as AbstractResultHandler,
6
+ F as Method,
7
+ I as BuiltinLogger,
8
+ L as AbstractLogger,
9
+ M as FinalInputSchema,
10
+ N as IOSchema,
11
+ O as arrayResultHandler,
12
+ P as ClientMethod,
13
+ R as LoggerOverrides,
14
+ S as AppConfig,
15
+ T as createConfig,
16
+ _ as EmptySchema,
17
+ a as Handler,
18
+ b as TagOverrides,
19
+ c as Middleware,
20
+ d as CookieSecurity,
21
+ f as HeaderSecurity,
22
+ g as EmptyObject,
23
+ h as OpenIdSecurity,
24
+ i as Endpoint,
25
+ j as Extension,
26
+ k as defaultResultHandler,
27
+ l as BasicSecurity,
28
+ m as OAuth2Security,
29
+ n as ServeStatic,
30
+ o as AbstractMiddleware,
31
+ p as InputSecurity,
32
+ r as AbstractEndpoint,
33
+ s as ExpressMiddleware,
34
+ t as Routing,
35
+ u as BearerSecurity,
36
+ v as FlatObject,
37
+ w as ServerConfig,
38
+ x as getMessageFromError,
39
+ y as Tag,
40
+ z as ApiResponse,
41
+ } from "./routing-C0jFxoT6.js";
42
+ import { i as OpenAPIContext } from "./documentation-helpers-BLgXFiWr.js";
1
43
  import { z } from "zod";
2
- import { HttpError } from "http-errors";
3
- import express, { CookieOptions, IRouter, NextFunction, Request, RequestHandler, Response } from "express";
44
+ import express, { CookieOptions, Request, Response } from "express";
4
45
  import http from "node:http";
5
- import { ServerOptions } from "node:https";
6
- import {
7
- InfoObject,
8
- OpenApiBuilder,
9
- ReferenceObject,
10
- SchemaObjectValue,
11
- ServerObject,
12
- TagObject,
13
- } from "openapi3-ts/oas32";
14
46
  import { RequestOptions, ResponseOptions } from "node-mocks-http";
15
- import compression from "compression";
16
- import fileUpload from "express-fileupload";
17
- import cookieParser from "cookie-parser";
18
- import { ListenOptions } from "node:net";
47
+ import "express-fileupload";
19
48
  import { AugmentedRequest, Options, RateLimitInfo, RateLimitRequestHandler } from "express-rate-limit";
20
- import ts from "typescript";
21
- declare const methods: ("get" | "post" | "put" | "delete" | "patch" | "query")[];
22
- declare const clientMethods: ("get" | "post" | "put" | "delete" | "patch" | "head" | "query")[];
23
- /**
24
- * @desc Methods supported by the framework API to produce Endpoints on EndpointsFactory.
25
- * @see BuildProps
26
- * @example "get" | "post" | "put" | "delete" | "patch" | "query"
27
- * */
28
- type Method = (typeof methods)[number];
29
- /**
30
- * @desc Methods usable on the client side, available via generated Integration and Documentation
31
- * @see withHead
32
- * @example Method | "head"
33
- * */
34
- type ClientMethod = (typeof clientMethods)[number];
35
- declare const defaultStatusCodes: {
36
- positive: number;
37
- negative: number;
38
- };
39
- type ResponseVariant = keyof typeof defaultStatusCodes;
40
- /**
41
- * @desc A container for describing an API response: its schema, status code(s) and MIME type(s).
42
- * @see ResultHandler
43
- * */
44
- interface ApiResponse<S extends z.ZodType> {
45
- /** @desc The Zod schema describing the response body. */
46
- schema: S;
47
- /**
48
- * @desc The status code(s) for this response.
49
- * @default 200 for a positive response, 400 for a negative one
50
- * */
51
- statusCode?: number | [number, ...number[]];
52
- /**
53
- * @desc The MIME type(s) of the response.
54
- * @default "application/json"
55
- * @example null — no content, typical for 204 and 302
56
- * */
57
- mimeType?: string | [string, ...string[]] | null;
58
- }
59
- /** @since zod 3.25.61 output type fixed */
60
- declare const emptySchema: z.ZodObject<{}, z.core.$strip>;
61
- type EmptySchema = typeof emptySchema;
62
- /** @desc this type does not allow props assignment, but it works for reading them when merged with another interface */
63
- type EmptyObject = z.output<EmptySchema>;
64
- type FlatObject = Record<string, unknown>;
65
- /** @link https://stackoverflow.com/a/65492934 */
66
- type NoNever<T, F> = [T] extends [never] ? F : T;
67
- /**
68
- * @desc Using module augmentation approach you can specify tags as the keys of this interface
69
- * @example declare module "express-zod-api" { interface TagOverrides { users: unknown } }
70
- * @link https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
71
- * */
72
- interface TagOverrides {}
73
- type Tag = NoNever<keyof TagOverrides, string>;
74
- declare const getMessageFromError: (error: Error) => string;
75
- declare const severity: {
76
- debug: number;
77
- info: number;
78
- warn: number;
79
- error: number;
80
- };
81
- type Severity = keyof typeof severity;
82
- /** @desc You can use any logger compatible with this type. */
83
- type AbstractLogger = Record<Severity, (message: string, meta?: any) => any>;
84
- /**
85
- * @desc Using module augmentation approach you can set the type of the actual logger used
86
- * @example declare module "express-zod-api" { interface LoggerOverrides extends winston.Logger {} }
87
- * @link https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
88
- * */
89
- interface LoggerOverrides {}
90
- type ActualLogger = AbstractLogger & LoggerOverrides;
91
- interface Context extends FlatObject {
92
- requestId?: string;
93
- }
94
- interface BuiltinLoggerConfig {
95
- /**
96
- * @desc The minimal severity to log or "silent" to disable logging
97
- * @example "debug" also enables pretty output for inspected entities
98
- * */
99
- level: "silent" | "warn" | "info" | "debug";
100
- /** @desc Enables colors on printed severity and inspected entities */
101
- color: boolean;
102
- /**
103
- * @desc Control how deeply entities should be inspected
104
- * @example null
105
- * @example Infinity
106
- * */
107
- depth: number | null;
108
- /**
109
- * @desc Context: the metadata applicable for each logged entry, used by .child() method
110
- * @see childLoggerProvider
111
- * */
112
- ctx: Context;
113
- }
114
- interface ProfilerOptions {
115
- message: string;
116
- /** @default "debug" */
117
- severity?: Severity | ((ms: number) => Severity);
118
- /** @default formatDuration - adaptive units and limited fraction */
119
- formatter?: (ms: number) => string | number;
120
- }
121
- /** @desc Built-in console logger with optional colorful inspections */
122
- declare class BuiltinLogger implements AbstractLogger {
123
- protected readonly config: BuiltinLoggerConfig;
124
- /** @example new BuiltinLogger({ level: "debug", color: true, depth: 4 }) */
125
- constructor({ color, level, depth, ctx }?: Partial<BuiltinLoggerConfig>);
126
- protected format(subject: unknown): string;
127
- protected print(method: Severity, message: string, meta?: unknown): void;
128
- debug(message: string, meta?: unknown): void;
129
- info(message: string, meta?: unknown): void;
130
- warn(message: string, meta?: unknown): void;
131
- error(message: string, meta?: unknown): void;
132
- child(ctx: Context): BuiltinLogger;
133
- /**
134
- * @desc The argument used for instance created by .child() method
135
- * @see ChildLoggerProvider
136
- * */
137
- get ctx(): Context;
138
- /** @desc Measures the duration until you invoke the returned callback */
139
- profile(message: string): () => void;
140
- profile(options: ProfilerOptions): () => void;
141
- }
142
- type Base$1 = object & {
143
- [Symbol.iterator]?: never;
144
- };
145
- /** @desc The type allowed on the top level of Middlewares and Endpoints */
146
- type IOSchema = z.ZodType<Base$1>;
147
- /** EndpointsFactory schema extended type when adding a Middleware */
148
- type Extension<Current extends IOSchema | undefined, Inc extends IOSchema | undefined> = Current extends IOSchema
149
- ? Inc extends IOSchema
150
- ? z.ZodIntersection<Current, Inc>
151
- : Current
152
- : Inc;
153
- /** The Endpoint input schema type, condition wrapped into schema to make it z.output-compatible */
154
- type FinalInputSchema<FIN extends IOSchema | undefined, BIN extends IOSchema> = z.ZodIntersection<
155
- FIN extends IOSchema ? FIN : BIN,
156
- BIN
157
- >;
158
- type ResultSchema<R extends Result> = R extends Result<infer S> ? S : never;
159
- type DiscriminatedResult =
160
- | {
161
- output: FlatObject;
162
- error: null;
163
- }
164
- | {
165
- output: null;
166
- error: Error;
167
- };
168
- /**
169
- * @example InputValidationError —> BadRequest(400)
170
- * @example Error —> InternalServerError(500)
171
- * */
172
- declare const ensureHttpError: (error: Error) => HttpError;
173
- type Handler$2<RES = unknown> = (
174
- params: DiscriminatedResult & {
175
- /** null in case of failure to parse or to find the matching endpoint (error: not found) */
176
- input: FlatObject | null;
177
- /** can be empty: check the presence of the required property using the "in" operator */
178
- ctx: FlatObject;
179
- request: Request;
180
- response: Response<RES>;
181
- logger: ActualLogger;
182
- },
183
- ) => void | Promise<void>;
184
- /**
185
- * @desc Result definition for ResultHandler: a plain schema (for JSON and default status codes) or custom ApiResponse.
186
- * @see ApiResponse
187
- * */
188
- type Result<S extends z.ZodType = z.ZodType> = S | ApiResponse<S> | ApiResponse<S>[];
189
- /** @desc A function that lazily produces a Result definition. */
190
- type LazyResult<R extends Result, A extends unknown[] = []> = (...args: A) => R;
191
- declare abstract class AbstractResultHandler {
192
- protected constructor(handler: Handler$2);
193
- execute(...params: Parameters<Handler$2>): Promise<void>;
194
- }
195
- /**
196
- * @desc The entity responsible to respond consistently. Accepts positive and negative Result definitions.
197
- * The positive definition can be a lazy function receiving the output schema of an Endpoint.
198
- * @see Result
199
- * */
200
- declare class ResultHandler<POS extends Result, NEG extends Result> extends AbstractResultHandler {
201
- constructor(params: {
202
- /** @desc A description of the API response in case of success (schema, status code, MIME type) */
203
- positive: POS | LazyResult<POS, [IOSchema]>;
204
- /** @desc A description of the API response in case of error (schema, status code, MIME type) */
205
- negative: NEG | LazyResult<NEG>;
206
- /** @desc The actual implementation to transmit the response in any case */
207
- handler: Handler$2<z.output<ResultSchema<POS> | ResultSchema<NEG>>>;
208
- });
209
- }
210
- /**
211
- * @desc The default ResultHandler wrapping Endpoint output in `{ status: "success", data: output }`
212
- * and errors in `{ status: "error", error: { message } }`. Responds with JSON Content-Type.
213
- * Respects the status of errors from createHttpError(), others become InternalServerError (500).
214
- * @see ensureHttpError
215
- * */
216
- declare const defaultResultHandler: ResultHandler<
217
- z.ZodObject<
218
- {
219
- status: z.ZodLiteral<"success">;
220
- data: IOSchema;
221
- },
222
- z.core.$strip
223
- >,
224
- z.ZodObject<
225
- {
226
- status: z.ZodLiteral<"error">;
227
- error: z.ZodObject<
228
- {
229
- message: z.ZodString;
230
- },
231
- z.core.$strip
232
- >;
233
- },
234
- z.core.$strip
235
- >
236
- >;
237
- /**
238
- * @deprecated Resist the urge of using it: this handler is designed only to simplify the migration of legacy APIs.
239
- * @desc Responding with an array is a bad practice keeping your endpoints from evolving without breaking changes.
240
- * @desc This handler expects your endpoint to have the property 'items' in the output object schema
241
- * */
242
- declare const arrayResultHandler: ResultHandler<
243
- z.ZodArray<z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>> | z.ZodArray<z.ZodAny>,
244
- {
245
- schema: z.ZodString;
246
- mimeType: string;
247
- }
248
- >;
249
- /** @desc Returns child logger for the given request (if configured) or the configured logger otherwise */
250
- type GetLogger = (request?: Request) => ActualLogger;
251
- type InputSource = keyof Pick<Request, "query" | "body" | "files" | "params" | "headers" | "cookies" | "signedCookies">;
252
- type InputSources = Record<Method, InputSource[]>;
253
- type ChildLoggerProvider = (params: { request: Request; parent: ActualLogger }) => ActualLogger | Promise<ActualLogger>;
254
- type LogAccess = (request: Request, logger: ActualLogger) => void;
255
- interface CommonConfig {
256
- /**
257
- * @desc Enables cross-origin resource sharing.
258
- * @desc You can provide custom middleware or the `cors` package.
259
- * @example cors({ origin: "https://example.com" }) // import cors from "cors"
260
- * @link https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
261
- * @link https://www.npmjs.com/package/cors
262
- */
263
- cors: boolean | RequestHandler;
264
- /**
265
- * @desc Controls how to respond to a request to an existing endpoint with an invalid HTTP method.
266
- * @example true — respond with status code 405 and "Allow" header containing a list of valid methods
267
- * @example false — respond with status code 404 (Not found)
268
- * @default true
269
- */
270
- hintAllowedMethods?: boolean;
271
- /**
272
- * @desc Controls how to treat Routing keys matching HTTP methods ("get", "post") and having Endpoint assigned.
273
- * @example true — treat such keys as HTTP methods complementing their parent paths
274
- * { users: { get: ... }} becomes GET /users
275
- * @example false — treat such keys as nested path segments regardless of the name
276
- * { users: { get: ... }} remains /users/get
277
- * @default true
278
- */
279
- recognizeMethodDependentRoutes?: boolean;
280
- /**
281
- * @desc The ResultHandler to use for handling routing, parsing and upload errors
282
- * @default defaultResultHandler
283
- * @see defaultResultHandler
284
- */
285
- errorHandler?: AbstractResultHandler;
286
- /**
287
- * @desc Built-in logger configuration or an instance of any compatible logger.
288
- * @example { level: "debug", color: true }
289
- * @default { level: NODE_ENV === "production" ? "warn" : "debug", color: isSupported(), depth: 2 }
290
- * */
291
- logger?: Partial<BuiltinLoggerConfig> | AbstractLogger;
292
- /**
293
- * @desc A child logger returned by this function can override the logger in all handlers for each request
294
- * @example ({ parent }) => parent.child({ requestId: uuid() })
295
- * */
296
- childLoggerProvider?: ChildLoggerProvider;
297
- /**
298
- * @desc The function for producing access logs
299
- * @default ({ method, path }, logger) => logger.debug(`${method}: ${path}`)
300
- * @example null — disables the feature
301
- * */
302
- accessLogger?: null | LogAccess;
303
- /**
304
- * @desc You can disable the startup logo.
305
- * @default true
306
- */
307
- startupLogo?: boolean;
308
- /**
309
- * @desc Which properties of request are combined into the input for endpoints and middlewares.
310
- * @desc The order matters: priority from lowest to highest
311
- * @default defaultInputSources
312
- * @see defaultInputSources
313
- */
314
- inputSources?: Partial<InputSources>;
315
- }
316
- type BeforeUpload = (params: { request: Request; logger: ActualLogger }) => void | Promise<void>;
317
- type UploadOptions = Pick<
318
- fileUpload.Options,
319
- | "createParentPath"
320
- | "uriDecodeFileNames"
321
- | "safeFileNames"
322
- | "preserveExtension"
323
- | "useTempFiles"
324
- | "tempFileDir"
325
- | "debug"
326
- | "uploadTimeout"
327
- | "limits"
328
- > & {
329
- /**
330
- * @desc The error to throw when the file exceeds the configured fileSize limit (handled by errorHandler).
331
- * @see limits
332
- * @override limitHandler
333
- * @example createHttpError(413, "The file is too large")
334
- * */
335
- limitError?: Error;
336
- /**
337
- * @desc A handler to execute before uploading — it can be used for restrictions by throwing an error.
338
- * @example ({ request }) => { throw createHttpError(403, "Not authorized"); }
339
- * */
340
- beforeUpload?: BeforeUpload;
341
- };
342
- interface CookieParserOptions extends cookieParser.CookieParseOptions {
343
- /** @desc The secret string or array used by cookie-parser for signed cookies */
344
- secret?: Parameters<typeof cookieParser>[0];
345
- }
346
- type CompressionOptions = Pick<
347
- compression.CompressionOptions,
348
- "threshold" | "level" | "strategy" | "chunkSize" | "memLevel"
349
- >;
350
- interface GracefulOptions {
351
- /**
352
- * @desc Time given to drain ongoing requests before closing the server.
353
- * @default 1000
354
- * */
355
- timeout?: number;
356
- /**
357
- * @desc Process event (Signal) that triggers the graceful shutdown.
358
- * @see Signals
359
- * @default [SIGINT, SIGTERM]
360
- * */
361
- events?: string[];
362
- /** @desc The hook to call after the server was closed, but before terminating the process. */
363
- beforeExit?: () => void | Promise<void>;
364
- }
365
- type ServerHook = (params: {
366
- app: IRouter;
367
- /** @desc Returns child logger for the given request (if configured) or the configured logger otherwise */
368
- getLogger: GetLogger;
369
- }) => void;
370
- interface HttpConfig {
371
- /** @desc Port, UNIX socket or custom options. */
372
- listen: number | string | ListenOptions;
373
- }
374
- interface HttpsConfig extends HttpConfig {
375
- /** @desc At least "cert" and "key" options required. */
376
- options: ServerOptions;
377
- }
378
- interface ServerConfig extends CommonConfig {
379
- /** @desc HTTP server configuration. */
380
- http?: HttpConfig;
381
- /** @desc HTTPS server configuration. */
382
- https?: HttpsConfig;
383
- /**
384
- * @desc Custom JSON parser applied to all incoming requests.
385
- * @default express.json()
386
- * @link https://expressjs.com/en/5x/api.html#express.json
387
- * */
388
- jsonParser?: RequestHandler;
389
- /**
390
- * @desc Enable or configure uploads handling.
391
- * @requires express-fileupload
392
- * */
393
- upload?: boolean | UploadOptions;
394
- /**
395
- * @desc Enable or configure response compression.
396
- * @requires compression
397
- */
398
- compression?: boolean | CompressionOptions;
399
- /**
400
- * @desc Enable cookie parsing via cookie-parser.
401
- * @requires cookie-parser
402
- * @example true
403
- * @example { secret: "my-secret" }
404
- */
405
- cookies?: boolean | CookieParserOptions;
406
- /**
407
- * @desc Configure or customize the parser for request query string
408
- * @example "simple" // for "node:querystring" module, array elements must be repeated: ?a=1&a=2
409
- * @example "extended" // for "qs" module, supports nested objects and arrays with brackets: ?a[]=1&a[]=2
410
- * @example (query) => qs.parse(query, {comma: true}) // for comma-separated arrays: ?a=1,2,3
411
- * @default "simple"
412
- * @link https://expressjs.com/en/5x/api.html#req.query
413
- */
414
- queryParser?: "simple" | "extended" | ((query: string) => object);
415
- /**
416
- * @desc Custom parser for Buffer payloads applied to all incoming requests.
417
- * @default express.raw()
418
- * @link https://expressjs.com/en/5x/api.html#express.raw
419
- * */
420
- rawParser?: RequestHandler;
421
- /**
422
- * @desc Custom parser for URL Encoded requests applied to all incoming requests.
423
- * @default express.urlencoded()
424
- * @link https://expressjs.com/en/5x/api.html#express.urlencoded
425
- * */
426
- formParser?: RequestHandler;
427
- /**
428
- * @desc A code to execute before the installation of parsers (compression, cookies, CORS, body).
429
- * @example ({ app }) => { app.use(helmet()); }
430
- * */
431
- beforeParsers?: ServerHook;
432
- /**
433
- * @desc A code to execute before processing the Routing of your API.
434
- * @desc Runs after compression, cookies, CORS and body parsers are installed.
435
- * @desc This can be a good place for express middlewares establishing their own routes.
436
- * @desc It can help to avoid making a DIY solution based on the attachRouting() approach.
437
- * @example ({ app }) => { app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); }
438
- * */
439
- beforeRouting?: ServerHook;
440
- /**
441
- * @desc A code to execute after processing the Routing of your API, but before error handling.
442
- * @see beforeRouting
443
- * */
444
- afterRouting?: ServerHook;
445
- /**
446
- * @desc Rejects new connections and attempts to finish ongoing ones in the specified time before exit.
447
- * */
448
- gracefulShutdown?: boolean | GracefulOptions;
449
- }
450
- interface AppConfig extends CommonConfig {
451
- /** @desc Your custom express app or express router instead. */
452
- app: IRouter;
453
- }
454
- declare function createConfig(config: ServerConfig): ServerConfig;
455
- declare function createConfig(config: AppConfig): AppConfig;
456
- type LogicalOr<T> = {
457
- or: T[];
458
- };
459
- type LogicalAnd<T> = {
460
- and: T[];
461
- };
462
- type LogicalContainer<T> = LogicalOr<T | LogicalAnd<T>> | LogicalAnd<T | LogicalOr<T>> | T;
463
- interface BasicSecurity {
464
- type: "basic";
465
- }
466
- interface BearerSecurity {
467
- type: "bearer";
468
- format?: "JWT" | string;
469
- }
470
- interface InputSecurity<K extends string> {
471
- type: "input";
472
- name: K;
473
- }
474
- interface HeaderSecurity {
475
- type: "header";
476
- name: string;
477
- }
478
- interface CookieSecurity {
479
- type: "cookie";
480
- name: string;
481
- }
482
- /**
483
- * @see https://swagger.io/docs/specification/authentication/openid-connect-discovery/
484
- * @desc available scopes has to be provided via the specified URL
485
- */
486
- interface OpenIdSecurity {
487
- type: "openid";
488
- url: string;
489
- }
490
- interface AuthUrl {
491
- /**
492
- * @desc The authorization URL to use for this flow. Can be relative to the API server URL.
493
- * @see https://swagger.io/docs/specification/api-host-and-base-path/
494
- */
495
- authorizationUrl: string;
496
- }
497
- interface DeviceAuthUrl {
498
- /** @desc The device authorization URL to use for this flow (RFC 8628). Can be relative to the API server URL. */
499
- deviceAuthorizationUrl: string;
500
- }
501
- interface TokenUrl {
502
- /** @desc The token URL to use for this flow. Can be relative to the API server URL. */
503
- tokenUrl: string;
504
- }
505
- interface RefreshUrl {
506
- /** @desc The URL to be used for obtaining refresh tokens. Can be relative to the API server URL. */
507
- refreshUrl?: string;
508
- }
509
- interface Scopes<K extends string> {
510
- /** @desc The available scopes for the OAuth2 security and their short descriptions. Optional. */
511
- scopes?: Record<K, string>;
512
- }
513
- type AuthCodeFlow<S extends string> = AuthUrl & TokenUrl & RefreshUrl & Scopes<S>;
514
- type ImplicitFlow<S extends string> = AuthUrl & RefreshUrl & Scopes<S>;
515
- type PasswordFlow<S extends string> = TokenUrl & RefreshUrl & Scopes<S>;
516
- type ClientCredFlow<S extends string> = TokenUrl & RefreshUrl & Scopes<S>;
517
- type DeviceAuthFlow<S extends string> = DeviceAuthUrl & TokenUrl & RefreshUrl & Scopes<S>;
518
- /**
519
- * @see https://swagger.io/docs/specification/authentication/oauth2/
520
- */
521
- interface OAuth2Security<S extends string> {
522
- type: "oauth2";
523
- /**
524
- * @desc URL to OAuth 2.0 Authorization Server metadata document
525
- * @link https://www.rfc-editor.org/rfc/rfc8414
526
- * */
527
- oauth2MetadataUrl?: string;
528
- flows?: {
529
- /** @desc Authorization Code flow (previously called accessCode in OpenAPI 2.0) */
530
- authorizationCode?: AuthCodeFlow<S>;
531
- /** @desc Implicit flow */
532
- implicit?: ImplicitFlow<S>;
533
- /** @desc Resource Owner Password flow */
534
- password?: PasswordFlow<S>;
535
- /** @desc Client Credentials flow (previously called application in OpenAPI 2.0) */
536
- clientCredentials?: ClientCredFlow<S>;
537
- /**
538
- * @desc Device Authorization flow (OAuth 2.0 Device Authorization Grant)
539
- * @link https://oauth.net/2/device-flow/
540
- * */
541
- deviceAuthorization?: DeviceAuthFlow<S>;
542
- };
543
- }
544
- /**
545
- * @desc Middleware security schema descriptor
546
- * @param K is an optional input field used by InputSecurity
547
- * @param S is an optional union of scopes used by OAuth2Security
548
- * */
549
- type Security<K extends string = string, S extends string = string> = (
550
- | BasicSecurity
551
- | BearerSecurity
552
- | InputSecurity<K>
553
- | HeaderSecurity
554
- | CookieSecurity
555
- | OpenIdSecurity
556
- | OAuth2Security<S>
557
- ) & {
558
- deprecated?: boolean;
559
- };
560
- type Handler$1<IN, CTX, RET> = (params: {
561
- /** @desc The inputs from the enabled input sources validated against the input schema of the Middleware. */
562
- input: IN;
563
- /**
564
- * @desc The returns of the previously executed Middlewares (typed when chaining Middlewares).
565
- * @link https://github.com/RobinTail/express-zod-api/discussions/1250
566
- * */
567
- ctx: CTX;
568
- /** @link https://expressjs.com/en/5x/api.html#req */
569
- request: Request;
570
- /** @link https://expressjs.com/en/5x/api.html#res */
571
- response: Response;
572
- /** @desc The instance of the configured logger. */
573
- logger: ActualLogger;
574
- }) => Promise<RET>;
575
- declare abstract class AbstractMiddleware {
576
- abstract execute(params: {
577
- input: unknown;
578
- ctx: FlatObject;
579
- request: Request;
580
- response: Response;
581
- logger: ActualLogger;
582
- }): Promise<FlatObject>;
583
- }
584
- /**
585
- * @desc A Middleware that validates its input schema, executes its handler, and returns context properties available to
586
- * next middlewares and the Endpoint handler. Can also declare security schemas for Documentation.
587
- * @see EndpointsFactory#addMiddleware
588
- * */
589
- declare class Middleware<
590
- CTX extends FlatObject,
591
- RET extends FlatObject,
592
- SCO extends string,
593
- IN extends IOSchema | undefined = undefined,
594
- > extends AbstractMiddleware {
595
- constructor({
596
- input,
597
- security,
598
- handler,
599
- }: {
600
- /**
601
- * @desc Input schema of the Middleware, combining properties from all the enabled input sources
602
- * @default undefined
603
- * @see defaultInputSources
604
- * */
605
- input?: IN;
606
- /**
607
- * @desc Declaration of the security schemas implemented within the handler (used by Documentation).
608
- * @see Documentation
609
- * */
610
- security?: LogicalContainer<Security<Extract<keyof z.input<IN>, string>, SCO>>;
611
- /** @desc The handler returning a context available to Endpoints. */
612
- handler: Handler$1<z.output<IN>, CTX, RET>;
613
- });
614
- /** @throws InputValidationError */
615
- execute({
616
- input,
617
- ...rest
618
- }: {
619
- input: unknown;
620
- ctx: CTX;
621
- request: Request;
622
- response: Response;
623
- logger: ActualLogger;
624
- }): Promise<RET>;
625
- }
626
- /**
627
- * @desc A wrapper around native Express middlewares that converts them into the framework's Middleware instances.
628
- * Optionally, a `provider` can extend the context, and a `transformer` can convert caught errors.
629
- * @see EndpointsFactory#addExpressMiddleware
630
- * */
631
- declare class ExpressMiddleware<R extends Request, S extends Response, RET extends FlatObject> extends Middleware<
632
- FlatObject,
633
- RET,
634
- string
635
- > {
636
- constructor(
637
- nativeMw: (request: R, response: S, next: NextFunction) => any,
638
- {
639
- provider,
640
- transformer,
641
- }?: {
642
- /** @desc Extracts context properties from request and response after the native middleware execution. */
643
- provider?: (request: R, response: S) => RET | Promise<RET>;
644
- /** @desc Transforms errors caught from the native middleware before they propagate further. */
645
- transformer?: (err: Error) => Error;
646
- },
647
- );
648
- }
649
49
  /**
650
50
  * @desc Directives shared by both request and response Cache-Control headers.
651
51
  * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control#cache_directives
@@ -814,69 +214,6 @@ declare const createCacheMiddleware: (defaultPolicy?: CachePolicy) => Middleware
814
214
  string,
815
215
  undefined
816
216
  >;
817
- type OriginalStatic = typeof express.static;
818
- declare class ServeStatic {
819
- constructor(...params: Parameters<OriginalStatic>);
820
- }
821
- /**
822
- * @example { v1: { books: { ":bookId": getBookEndpoint } } }
823
- * @example { "v1/books/:bookId": getBookEndpoint }
824
- * @example { "get /v1/books/:bookId": getBookEndpoint }
825
- * @example { v1: { "patch /books/:bookId": changeBookEndpoint } }
826
- * @example { dependsOnMethod: { get: retrieveEndpoint, post: createEndpoint } }
827
- * @see CommonConfig.recognizeMethodDependentRoutes
828
- * */
829
- interface Routing {
830
- [K: string]: Routing | AbstractEndpoint | ServeStatic;
831
- }
832
- type Handler<IN, OUT, CTX> = (params: {
833
- /** @desc The inputs from the enabled input sources validated against the final input schema (incl. Middlewares) */
834
- input: IN;
835
- /** @desc The returns of the assigned Middlewares */
836
- ctx: CTX;
837
- /** @desc The instance of the configured logger */
838
- logger: ActualLogger;
839
- }) => Promise<OUT>;
840
- declare abstract class AbstractEndpoint {
841
- /** @desc Enables nested routes within the path assigned to the subject */
842
- nest(routing: Routing): Routing;
843
- /** @desc Marks the route as deprecated (makes a copy of the endpoint) */
844
- abstract deprecated(): this;
845
- abstract execute(params: {
846
- request: Request;
847
- response: Response;
848
- logger: ActualLogger;
849
- config: CommonConfig;
850
- }): Promise<void>;
851
- }
852
- declare class Endpoint<IN extends IOSchema, OUT extends IOSchema, CTX extends FlatObject> extends AbstractEndpoint {
853
- constructor(def: {
854
- deprecated?: boolean;
855
- middlewares?: AbstractMiddleware[];
856
- inputSchema: IN;
857
- outputSchema: OUT;
858
- handler: Handler<z.output<IN>, z.input<OUT>, CTX>;
859
- resultHandler: AbstractResultHandler;
860
- description?: string;
861
- summary?: string;
862
- getOperationId?: (method: ClientMethod) => string | undefined;
863
- methods?: Method[];
864
- scopes?: string[];
865
- tags?: string[];
866
- });
867
- deprecated(): this;
868
- execute({
869
- request,
870
- response,
871
- logger,
872
- config,
873
- }: {
874
- request: Request;
875
- response: Response;
876
- logger: ActualLogger;
877
- config: CommonConfig;
878
- }): Promise<undefined>;
879
- }
880
217
  /**
881
218
  * @desc Creates a Middleware providing cookie-setting convenience methods.
882
219
  * @param baseOptions — Default options applied to every setCookie / clearCookie call.
@@ -1137,91 +474,6 @@ declare const createServer: (
1137
474
  logger: AbstractLogger | BuiltinLogger;
1138
475
  servers: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse>[];
1139
476
  };
1140
- interface ReqResCommons {
1141
- makeRef: (key: object | string, value: SchemaObjectValue | ReferenceObject, proposedName?: string) => ReferenceObject;
1142
- path: string;
1143
- method: ClientMethod;
1144
- }
1145
- interface OpenAPIContext extends ReqResCommons {
1146
- isResponse: boolean;
1147
- }
1148
- type Depicter = (
1149
- zodCtx: {
1150
- zodSchema: z.core.$ZodType;
1151
- jsonSchema: z.core.JSONSchema.BaseSchema;
1152
- },
1153
- oasCtx: OpenAPIContext,
1154
- ) => z.core.JSONSchema.BaseSchema | SchemaObjectValue;
1155
- /** @desc Using defaultIsHeader when returns null or undefined */
1156
- type IsHeader = (name: string, method: ClientMethod, path: string) => boolean | null | undefined;
1157
- type BrandHandling = Record<string | symbol, Depicter>;
1158
- interface TagDetails extends Pick<TagObject, "summary" | "description" | "externalDocs" | "kind"> {
1159
- /** @desc shorthand for externalDocs.url */
1160
- url?: string;
1161
- parent?: Tag;
1162
- }
1163
- declare const depictTags: (tags: Partial<Record<Tag, string | TagDetails>>) => TagObject[];
1164
- /** @desc Ensures the summary string does not exceed the limit */
1165
- declare const trimSummary: (summary?: string, limit?: number) => string | undefined;
1166
- type Component = `${ResponseVariant}Response` | "requestParameter" | "requestBody";
1167
- /** @desc user defined function that creates a component description from its properties */
1168
- type Descriptor = (
1169
- props: Record<"method" | "path" | "operationId", string> & {
1170
- statusCode?: number;
1171
- },
1172
- ) => string;
1173
- type Summarizer = (params: { summary?: string; description?: string; trim: typeof trimSummary }) => string | undefined;
1174
- interface DocumentationParams {
1175
- /** @desc At least title and version properties are required */
1176
- info: InfoObject;
1177
- /** @desc Server URL(s) or their complete definitions */
1178
- server: string | [string, ...string[]] | ServerObject | [ServerObject, ...ServerObject[]];
1179
- routing: Routing;
1180
- config: CommonConfig;
1181
- /**
1182
- * @desc Descriptions of various components based on their properties (method, path, operationId).
1183
- * @desc When composition set to "components", component name is generated from this description
1184
- * @default () => `${method} ${path} ${component}`
1185
- * */
1186
- descriptions?: Partial<Record<Component, Descriptor>>;
1187
- /**
1188
- * @desc The function that ensures the maximum length for summary fields. Can optionally make them from descriptions.
1189
- * @see defaultSummarizer
1190
- * @see trimSummary
1191
- * */
1192
- summarizer?: Summarizer;
1193
- /**
1194
- * @desc Depict the HEAD method for each Endpoint supporting the GET method (feature of Express)
1195
- * @default true
1196
- * */
1197
- hasHeadMethod?: boolean;
1198
- /** @default inline */
1199
- composition?: "inline" | "components";
1200
- /**
1201
- * @desc Handling rules for your own schemas branded with `x-brand` metadata.
1202
- * @desc Keys: brands (recommended to use unique symbols).
1203
- * @desc Values: functions having Zod context as first argument, second one is the framework context.
1204
- * @example { MyBrand: ({ zodSchema, jsonSchema }) => ({ type: "object" })
1205
- * @link https://www.npmjs.com/package/@express-zod-api/zod-plugin
1206
- */
1207
- brandHandling?: BrandHandling;
1208
- /**
1209
- * @desc Ability to configure recognition of headers among other input data
1210
- * @desc Only applicable when "headers" is present within inputSources config option
1211
- * @see defaultIsHeader
1212
- * @link https://www.iana.org/assignments/http-fields/http-fields.xhtml
1213
- * */
1214
- isHeader?: IsHeader;
1215
- /**
1216
- * @desc Extended description of tags used in endpoints. For enforcing constraints:
1217
- * @see TagOverrides
1218
- * @example { users: "About users", files: { description: "About files", url: "https://example.com" } }
1219
- * */
1220
- tags?: Parameters<typeof depictTags>[0];
1221
- }
1222
- declare class Documentation extends OpenApiBuilder {
1223
- constructor({ hasHeadMethod, ...rest }: DocumentationParams);
1224
- }
1225
477
  /** @desc An error related to the wrong Routing declaration */
1226
478
  declare class RoutingError extends Error {
1227
479
  name: string;
@@ -1334,90 +586,6 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
1334
586
  _getLogs: () => Record<"error" | "debug" | "info" | "warn", unknown[]>;
1335
587
  };
1336
588
  }>;
1337
- declare abstract class IntegrationBase {
1338
- protected readonly serverUrl: string;
1339
- protected constructor(typescript: typeof ts, serverUrl: string);
1340
- }
1341
- interface NextHandlerInc<U> {
1342
- next: (schema: z.core.$ZodType) => U;
1343
- }
1344
- type SchemaHandler<U, Context extends FlatObject = EmptyObject, Variant extends "regular" | "last" = "regular"> = (
1345
- schema: any, // eslint-disable-line @typescript-eslint/no-explicit-any -- for assignment compatibility
1346
- ctx: Context & (Variant extends "regular" ? NextHandlerInc<U> : Context),
1347
- ) => U;
1348
- type HandlingRules<U, Context extends FlatObject = EmptyObject, K extends string | symbol = string | symbol> = Partial<
1349
- Record<K, SchemaHandler<U, Context>>
1350
- >;
1351
- interface ZTSContext extends FlatObject {
1352
- isResponse: boolean;
1353
- makeAlias: (key: object, produce: () => ts.TypeNode) => ts.TypeNode;
1354
- }
1355
- type Producer = SchemaHandler<ts.TypeNode, ZTSContext>;
1356
- interface IntegrationParams {
1357
- /** @default loadPeer("typescript") */
1358
- typescript?: typeof ts;
1359
- routing: Routing;
1360
- config: CommonConfig;
1361
- /**
1362
- * @desc What should be generated
1363
- * @example "types" — types of your endpoint requests and responses (for a DIY solution)
1364
- * @example "client" — an entity for performing typed requests and receiving typed responses
1365
- * @default "client"
1366
- * */
1367
- variant?: "types" | "client";
1368
- /** @default Client */
1369
- clientClassName?: string;
1370
- /** @default Subscription */
1371
- subscriptionClassName?: string;
1372
- /**
1373
- * @desc The API URL to use in the generated code
1374
- * @default https://example.com
1375
- * */
1376
- serverUrl?: string;
1377
- /**
1378
- * @desc The schema to use for responses without body such as 204
1379
- * @default z.undefined()
1380
- * */
1381
- noBodySchema?: z.ZodType;
1382
- /**
1383
- * @desc Depict the HEAD method for each Endpoint supporting the GET method (feature of Express)
1384
- * @default true
1385
- * */
1386
- hasHeadMethod?: boolean;
1387
- /**
1388
- * @desc Handling rules for your own schemas branded with `x-brand` metadata.
1389
- * @desc Keys: brands (recommended to use unique symbols).
1390
- * @desc Values: functions having schema as first argument that you should assign type to, second one is a context.
1391
- * @example { MyBrand: (schema: typeof myBrandSchema, { next }) => createKeywordTypeNode(SyntaxKind.AnyKeyword)
1392
- * @link https://www.npmjs.com/package/@express-zod-api/zod-plugin
1393
- */
1394
- brandHandling?: HandlingRules<ts.TypeNode, ZTSContext>;
1395
- }
1396
- interface FormattedPrintingOptions {
1397
- /** @desc Typescript printer options */
1398
- printerOptions?: ts.PrinterOptions;
1399
- /**
1400
- * @desc Typescript code formatter
1401
- * @default prettier.format
1402
- * */
1403
- format?: (program: string) => Promise<string>;
1404
- }
1405
- declare class Integration extends IntegrationBase {
1406
- constructor({
1407
- typescript,
1408
- routing,
1409
- config,
1410
- brandHandling,
1411
- variant,
1412
- clientClassName,
1413
- subscriptionClassName,
1414
- serverUrl,
1415
- noBodySchema,
1416
- hasHeadMethod,
1417
- }: IntegrationParams);
1418
- print(printerOptions?: ts.PrinterOptions): string;
1419
- printFormatted({ printerOptions, format: userDefined }?: FormattedPrintingOptions): Promise<string>;
1420
- }
1421
589
  type EventsMap = Record<string, z.ZodType>;
1422
590
  interface Emitter<E extends EventsMap> extends FlatObject {
1423
591
  /** @desc Returns true when the connection was closed or terminated */
@@ -1611,8 +779,6 @@ export {
1611
779
  type CachePolicy,
1612
780
  type CommonConfig,
1613
781
  type CookieSecurity,
1614
- type Depicter,
1615
- Documentation,
1616
782
  DocumentationError,
1617
783
  EndpointsFactory,
1618
784
  EventStreamFactory,
@@ -1621,7 +787,6 @@ export {
1621
787
  type IOSchema,
1622
788
  type InputSecurity,
1623
789
  InputValidationError,
1624
- Integration,
1625
790
  type LoggerOverrides,
1626
791
  type Method,
1627
792
  Middleware,
@@ -1629,7 +794,6 @@ export {
1629
794
  type OAuth2Security,
1630
795
  type OpenIdSecurity,
1631
796
  OutputValidationError,
1632
- type Producer,
1633
797
  ResultHandler,
1634
798
  type Routing,
1635
799
  RoutingError,