express-zod-api 26.2.0 → 26.3.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,19 @@
2
2
 
3
3
  ## Version 26
4
4
 
5
+ ### v26.3.1
6
+
7
+ - Fixed the type of `ctx` for Endpoints built on factories having at least one Middleware:
8
+ - Removed `Record<string, never>` from the type union;
9
+ - This prevents accessing non-existing properties on `ctx`;
10
+ - The issue was reported by [@pycanis](https://github.com/pycanis).
11
+
12
+ ### v26.3.0
13
+
14
+ - Supporting several latest features of Zod 4.2 and 4.3 by the `Integration` generator:
15
+ - `z.looseRecord()` schema;
16
+ - Object properties wrapped by `z.exactOptional()` or created by `ZodType::exactOptional()` method.
17
+
5
18
  ### v26.2.0
6
19
 
7
20
  - Ability to specify a custom name for a schema in the generated Documentation:
@@ -1045,8 +1058,8 @@ createMiddleware({
1045
1058
  ### v21.7.0
1046
1059
 
1047
1060
  - Feature: introducing `EncodedResponse` public interface in the code generated by `Integration`:
1048
- - The new entity should enable making custom clients having response type awereness based on the status code;
1049
- - The difference between `Response` and `EndcodedResponse` is the second hierarchical level.
1061
+ - The new entity should enable making custom clients having response type awareness based on the status code;
1062
+ - The difference between `Response` and `EncodedResponse` is the second hierarchical level.
1050
1063
 
1051
1064
  ```ts
1052
1065
  import { EncodedResponse } from "./generated.ts";
@@ -1131,7 +1144,7 @@ source.addEventListener("time", (event) => {
1131
1144
  - Introducing stricter overload for the generated `ExpressZodAPIClient::provide()` method:
1132
1145
  - The method can now also accept two arguments: space-separated method with path and parameters;
1133
1146
  - Using this overload provides strict constraints on the first argument so that undeclared routes can not be used;
1134
- - This design is inspired by the OctoKit and aims to prevent the misuse by throwing a Typescript error.
1147
+ - This design is inspired by the OctoKit and aims to prevent the misuse by throwing a TypeScript error.
1135
1148
  - Using `ExpressZodAPIClient::provide()` with three arguments is deprecated:
1136
1149
  - The return type when using undeclared routes corrected to `unknown`.
1137
1150
  - The `Provider` type of the generated client is deprecated;
@@ -1289,7 +1302,7 @@ const after: Routing = {
1289
1302
  - The `input` property can be now omitted on the argument of the following methods:
1290
1303
  `Middlware::constructor`, `EndpointsFactory::build()`, `EndpointsFactory::addMiddleware()`;
1291
1304
  - When the input schema is not specified `z.object({})` is used;
1292
- - This feature aims to simplify the implementation for Endpoints and Middlwares having no inputs.
1305
+ - This feature aims to simplify the implementation for Endpoints and Middlewares having no inputs.
1293
1306
 
1294
1307
  ### v20.20.1
1295
1308
 
@@ -1613,7 +1626,7 @@ declare module "express-zod-api" {
1613
1626
 
1614
1627
  - Technical update due to improved builder configuration:
1615
1628
  - Removed crutches for the `migration/index.d.cts` file;
1616
- - Fixed missing `node:` protocol in the imports of core modules in the distributed javascript files.
1629
+ - Fixed missing `node:` protocol in the imports of core modules in the distributed JavaScript files.
1617
1630
 
1618
1631
  ### v20.4.0
1619
1632
 
@@ -1651,7 +1664,7 @@ expect(output).toEqual({ collectedOptions: ["prev"], testLength: 9 });
1651
1664
  ### v20.3.1
1652
1665
 
1653
1666
  - Removed `eslint` and `prettier` from the list of the optional peer dependencies:
1654
- - `eslint` with a flat config support (v8 or v9) is only required to use [the migration codemod](#v2000);
1667
+ - `eslint` with a flat config support (v8 or v9) is only required to use [the migration code mod](#v2000);
1655
1668
  - `prettier` is only a fallback for `Integration::printFormatted()`, which can work without it as well;
1656
1669
  - These changes aim to reduce the confusion and ease the installation;
1657
1670
  - The issue was found and reported by **Bogdan** who does not have a GitHub account.
@@ -1829,7 +1842,7 @@ expect(loggerMock._getLogs().error).toHaveLength(0);
1829
1842
  - `ansis` version `^3.2.0`;
1830
1843
  - `openapi3-ts` version `^4.3.3`;
1831
1844
  - `ramda` version `^0.30.1`;
1832
- - Several optimizations to the implementation enabled by Typescript 5.5;
1845
+ - Several optimizations to the implementation enabled by TypeScript 5.5;
1833
1846
 
1834
1847
  ### v19.2.2
1835
1848
 
@@ -1936,7 +1949,7 @@ new Integration({
1936
1949
  - For `express-fileupload` and `@types/express-fileupload`: 1.5.0.
1937
1950
  - Removed the deprecated method ~~`withMeta()`~~ (see [v18.5.0](#v1850) for details);
1938
1951
  - Removed support for static options by `EndpointsFactory::addOptions()` (see [v18.6.0](#v1860) for details);
1939
- - Freezed the arrays returned by the methods or exposed by properties of `Endpoint` and `DependsOnMethod`;
1952
+ - Freezes the arrays returned by the methods or exposed by properties of `Endpoint` and `DependsOnMethod`;
1940
1953
  - Changed interface for `ez.raw()`: additional properties should be supplied as its argument, not via `.extend()`;
1941
1954
  - Changed the following config options:
1942
1955
  - The function assigned to `server.upload.beforeUpload` now accepts `request` instead of `app`;
@@ -2782,9 +2795,9 @@ securitySchemes:
2782
2795
  - Consider [the new UI](https://editor-next.swagger.io/) for exploring the produced documentation.
2783
2796
  - Improved way of configuring descriptions and naming of the generated documentation components:
2784
2797
  - Introducing the new option `descriptions` holding several formatting functions.
2785
- - Ability to generate formatted typescript client using the new async method `printFormatted` of the `Integration`
2798
+ - Ability to generate formatted TypeScript client using the new async method `printFormatted` of the `Integration`
2786
2799
  class when the `prettier` package is installed (detects automatically).
2787
- - Ability to supply your own typescript formatting function into that new method.
2800
+ - Ability to supply your own TypeScript formatting function into that new method.
2788
2801
  - Ability to split the response types (to positive and negative ones) when generating the client or API types.
2789
2802
  - Featuring the `splitResponse` option of the `Integration` class constructor;
2790
2803
  - The feature suggested by [@shawncarr](https://github.com/shawncarr).
@@ -3168,7 +3181,7 @@ defaultEndpointsFactory.build({
3168
3181
 
3169
3182
  ### v12.1.0
3170
3183
 
3171
- - This version fixes the issue 1182 introduced in version 10.0.0-beta1, manifesting as Typescript errors `TS4023` and
3184
+ - This version fixes the issue 1182 introduced in version 10.0.0-beta1, manifesting as TypeScript errors `TS4023` and
3172
3185
  `TS4094` only when `declaration` feature is enabled in your `tsconfig.json`.
3173
3186
  - Several protected properties of `Endpoint` are made entirely private.
3174
3187
  - Several types are exposed: `CommonConfig`, `MiddlewareDefinition`, `ResultHandlerDefinition`, `BasicSecurity`,
@@ -3501,7 +3514,7 @@ after:
3501
3514
  - Proprietary schemas are now exported under the namespace `ez`.
3502
3515
  - Imports and utilization should be adjusted accordingly.
3503
3516
  - Affected schemas: `file`, `dateIn`, `dateOut`, `upload`.
3504
- - If facing Typescript errors `TS4023` or `TS4094`, ensure disabling `declaration` option in your `tsconfig.json`.
3517
+ - If facing TypeScript errors `TS4023` or `TS4094`, ensure disabling `declaration` option in your `tsconfig.json`.
3505
3518
  - The minimal Node version is now 14.18.0.
3506
3519
  - Due to switching to `tsup` builder, the file structure has changed:
3507
3520
  - `/dist/index.js` — CommonJS bundle;
@@ -3880,7 +3893,7 @@ interface Changes<T> {
3880
3893
  - Output validation errors now cause HTTP status code `500` instead of `400`.
3881
3894
  - HTTP status codes `4xx` are supposed to reflect client errors (bad requests).
3882
3895
  - The case when Endpoint's handler returns do not comply the Endpoint's output schema is the internal API error.
3883
- - Use [Typescript's strict mode](https://www.typescriptlang.org/tsconfig#strict) in order to prevent such cases
3896
+ - Use [TypeScript's strict mode](https://www.typescriptlang.org/tsconfig#strict) in order to prevent such cases
3884
3897
  during the development.
3885
3898
  - Added [Code of Conduct](CODE_OF_CONDUCT.md).
3886
3899
  - Output validation error messages changed slightly in the response:
@@ -3896,7 +3909,7 @@ output/anything: Number must be greater than 0
3896
3909
 
3897
3910
  - `typescript` version is 4.9.4.
3898
3911
  - Following the changes made in v8.4.2, I'm switching to the [forked zod-to-ts](https://github.com/RobinTail/zod-to-ts)
3899
- - Typescript made a regular dependency inside that fork, since it's used for code generation.
3912
+ - TypeScript made a regular dependency inside that fork, since it's used for code generation.
3900
3913
  - `@express-zod-api/zod-to-ts` version is v1.1.5.
3901
3914
  - Fixed all warnings while generating a frontend client.
3902
3915
 
@@ -3912,13 +3925,13 @@ const after = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/;
3912
3925
 
3913
3926
  ### v8.4.2
3914
3927
 
3915
- - Fixing issue of inability to generate Client having Typescript 4.1-4.6.x installed.
3916
- - Making Typescript a regular dependency of the library (it was dev + peer).
3928
+ - Fixing issue of inability to generate Client having TypeScript 4.1-4.6.x installed.
3929
+ - Making TypeScript a regular dependency of the library (it was dev + peer).
3917
3930
  - Using `typescript` version 4.9.3.
3918
- - This version also partially fixes the deprecation warnings in case you're using Typescript 4.9.x.
3931
+ - This version also partially fixes the deprecation warnings in case you're using TypeScript 4.9.x.
3919
3932
  - The issue introduced in version 7.9.1 of the library due to changing the implementation in accordance with the
3920
3933
  `typescript` upgrade to v4.8.2.
3921
- - The library uses Typescript's factory methods to generate the frontend client.
3934
+ - The library uses TypeScript's factory methods to generate the frontend client.
3922
3935
 
3923
3936
  ### v8.4.1
3924
3937
 
@@ -4184,7 +4197,7 @@ const myEndpoint = defaultEndpointsFactory.build({
4184
4197
 
4185
4198
  ### v7.9.1
4186
4199
 
4187
- - Minor refactoring in order to support the recently released Typescript 4.8.2.
4200
+ - Minor refactoring in order to support the recently released TypeScript 4.8.2.
4188
4201
 
4189
4202
  ### v7.9.0
4190
4203
 
@@ -4462,7 +4475,7 @@ interface After {
4462
4475
 
4463
4476
  - Feature #403: API Client Generator:
4464
4477
  - A new way of informing the frontend about the I/O types of endpoints;
4465
- - The new approach offers automatic generation of a client based on routing to a typescript file;
4478
+ - The new approach offers automatic generation of a client based on routing to a TypeScript file;
4466
4479
  - The generated client is flexibly configurable on the frontend side using an implementation function that
4467
4480
  directly makes requests to an endpoint using the libraries and methods of your choice;
4468
4481
  - The client asserts the type of request parameters and response;
@@ -5355,7 +5368,7 @@ const fileStreamingEndpointsFactoryAfter = new EndpointsFactory(
5355
5368
  to be specified as an argument of `EndpointsFactory` constructor. You can use `defaultResultHandler` or
5356
5369
  `createResultHandler()` for this, or you can use `defaultEndpointsFactory`.
5357
5370
  - Added the [Security policy](SECURITY.md).
5358
- - Some private methods have been made "entirely private" using the new typescript hashtag syntax.
5371
+ - Some private methods have been made "entirely private" using the new TypeScript hashtag syntax.
5359
5372
  - New methods of `Endpoint` class `getPositiveResponseSchema()` and `getNegativeResponseSchema()` return the
5360
5373
  complete response of the endpoint taking into account the `ResultHandlerDefinition` schemas.
5361
5374
  New methods: `getPositiveMimeTypes()` and `getNegativeMimeTypes()` return the array of mime types.
@@ -5373,7 +5386,7 @@ const fileStreamingEndpointsFactoryAfter = new EndpointsFactory(
5373
5386
  - For creating your own `ResultHandlerDefinition` please use `createResultHandler()`. It also requires
5374
5387
  `createApiResponse()` to be used that takes a response schema and optional mime types as arguments.
5375
5388
  The endpoint output should be wrapped in `markOutput()`. So far this is the only way I have come up with to
5376
- facilitate type inference with essentially double nesting of generic types. Typescript does not yet support such
5389
+ facilitate type inference with essentially double nesting of generic types. TypeScript does not yet support such
5377
5390
  features as `MyGenericType<A<B>>`.
5378
5391
 
5379
5392
  ```ts
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 Anna Bocharova
3
+ Copyright (c) 2026 Anna Bocharova
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -74,7 +74,7 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
74
74
  - You can keep the endpoint's input and output type declarations right next to its handler.
75
75
  - All input and output data types are validated, so it ensures you won't have an empty string, null or undefined where
76
76
  you expect a number.
77
- - Variables within an endpoint handler have types according to the declared schema, so your IDE and Typescript will
77
+ - Variables within an endpoint handler have types according to the declared schema, so your IDE and TypeScript will
78
78
  provide you with necessary hints to focus on bringing your vision to life.
79
79
  - All of your endpoints can respond in a consistent way.
80
80
  - The expected endpoint input and response types can be exported to the frontend, so you don't get confused about the
@@ -85,6 +85,7 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
85
85
 
86
86
  These people contributed to the improvement of the framework by reporting bugs, making changes and suggesting ideas:
87
87
 
88
+ [<img src="https://github.com/pycanis.png" alt="@pycanis" width="50" />](https://github.com/pycanis)
88
89
  [<img src="https://github.com/arlyon.png" alt="@arlyon" width="50" />](https://github.com/arlyon)
89
90
  [<img src="https://github.com/Upsilon-Iridani.png" alt="@Upsilon-Iridani" width="50" />](https://github.com/Upsilon-Iridani)
90
91
  [<img src="https://github.com/NicolasMahe.png" alt="@NicolasMahe" width="50" />](https://github.com/NicolasMahe)
@@ -321,7 +322,7 @@ const routing: Routing = {
321
322
 
322
323
  Same Endpoint can be reused on different routes or handle multiple methods if needed. Path parameters (the `:id` above)
323
324
  should be declared in the endpoint’s input schema. Properties assigned with Endpoint can explicitly declare a method.
324
- When the method is not specified, the one(s) supported by the Endpoint applied (or `get` as a fallback).
325
+ If no method is specified, the methods supported by the endpoint are used (or `get` as a fallback).
325
326
 
326
327
  ## Middlewares
327
328
 
@@ -567,7 +568,7 @@ z.object({ user_name: z.string(), id: z.number() }).remap({
567
568
 
568
569
  ## Dealing with dates
569
570
 
570
- Dates in Javascript are one of the most troublesome entities. In addition, `Date` cannot be passed directly in JSON
571
+ Dates in JavaScript are one of the most troublesome entities. In addition, `Date` cannot be passed directly in JSON
571
572
  format. Therefore, attempting to return `Date` from the endpoint handler results in it being converted to an ISO string
572
573
  in actual response by calling
573
574
  [toJSON()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON),
@@ -1075,7 +1076,7 @@ adding the runtime helpers the framework relies on.
1075
1076
 
1076
1077
  ## Generating a Frontend Client
1077
1078
 
1078
- You can generate a Typescript file containing the IO types of your API and a client for it.
1079
+ You can generate a TypeScript file containing the IO types of your API and a client for it.
1079
1080
  Consider installing `prettier` and using the async `printFormatted()` method.
1080
1081
 
1081
1082
  ```ts
@@ -1093,14 +1094,14 @@ const prettierFormattedTypescriptCode = await client.printFormatted(); // or jus
1093
1094
  Alternatively, you can supply your own `format` function into that method or use a regular `print()` method instead.
1094
1095
  The generated client is flexibly configurable on the frontend side for using a custom implementation function that
1095
1096
  makes requests using the libraries and methods of your choice. The default implementation uses `fetch`. The client
1096
- asserts the type of request parameters and response. Consuming the generated client requires Typescript version 4.1+.
1097
+ asserts the type of request parameters and response. Consuming the generated client requires TypeScript version 4.1+.
1097
1098
 
1098
1099
  ```ts
1099
1100
  import { Client, Implementation, Subscription } from "./client.ts"; // the generated file
1100
1101
 
1101
1102
  const client = new Client(/* optional custom Implementation */);
1102
1103
  client.provide("get /v1/user/retrieve", { id: "10" });
1103
- client.provide("post /v1/user/:id", { id: "10" }); // it also substitues path params
1104
+ client.provide("post /v1/user/:id", { id: "10" }); // it also substitutes path params
1104
1105
  new Subscription("get /v1/events/stream", {}).on("time", (time) => {}); // Server-sent events (SSE)
1105
1106
  ```
1106
1107
 
@@ -1394,7 +1395,7 @@ should be aware of them.
1394
1395
 
1395
1396
  ## Excessive properties in endpoint output
1396
1397
 
1397
- The schema validator removes excessive properties by default. However, Typescript
1398
+ The schema validator removes excessive properties by default. However, TypeScript
1398
1399
  [does not yet display errors](https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks)
1399
1400
  in this case during development. You can achieve this verification by assigning the output schema to a constant and
1400
1401
  reusing it in forced type of the output:
package/dist/index.d.ts CHANGED
@@ -661,19 +661,20 @@ interface BuildProps<IN extends IOSchema, OUT extends IOSchema | z.ZodVoid, MIN
661
661
  /** @desc Marks the operation deprecated in the generated Documentation */
662
662
  deprecated?: boolean;
663
663
  }
664
+ /** @todo consider having CTX based on unknown in the next major */
664
665
  declare class EndpointsFactory<IN extends IOSchema | undefined = undefined, CTX extends FlatObject = EmptyObject, SCO extends string = string> {
665
666
  #private;
666
667
  protected resultHandler: AbstractResultHandler;
667
668
  protected schema: IN;
668
669
  protected middlewares: AbstractMiddleware[];
669
670
  constructor(resultHandler: AbstractResultHandler);
670
- addMiddleware<RET extends FlatObject, ASCO extends string, AIN extends IOSchema | undefined = undefined>(subject: Middleware<CTX, RET, ASCO, AIN> | ConstructorParameters<typeof Middleware<CTX, RET, ASCO, AIN>>[0]): EndpointsFactory<Extension<IN, AIN>, CTX & RET, SCO & ASCO>;
671
+ addMiddleware<RET extends FlatObject, ASCO extends string, AIN extends IOSchema | undefined = undefined>(subject: Middleware<CTX, RET, ASCO, AIN> | ConstructorParameters<typeof Middleware<CTX, RET, ASCO, AIN>>[0]): EndpointsFactory<Extension<IN, AIN>, (CTX extends Record<string, never> ? RET : CTX) & RET, SCO & ASCO>;
671
672
  use: <R extends Request, S extends Response, AOUT extends FlatObject = Record<string, never>>(nativeMw: (request: R, response: S, next: express0.NextFunction) => any, params_1?: {
672
673
  provider?: ((request: R, response: S) => AOUT | Promise<AOUT>) | undefined;
673
674
  transformer?: (err: Error) => Error;
674
- } | undefined) => EndpointsFactory<Extension<IN, undefined>, CTX & AOUT, SCO>;
675
- addExpressMiddleware<R extends Request, S extends Response, AOUT extends FlatObject = EmptyObject>(...params: ConstructorParameters<typeof ExpressMiddleware<R, S, AOUT>>): EndpointsFactory<Extension<IN, undefined>, CTX & AOUT, SCO>;
676
- addContext<RET extends FlatObject>(getContext: () => Promise<RET>): EndpointsFactory<Extension<IN, undefined>, CTX & RET, SCO>;
675
+ } | undefined) => EndpointsFactory<Extension<IN, undefined>, (CTX extends Record<string, never> ? AOUT : CTX) & AOUT, SCO>;
676
+ addExpressMiddleware<R extends Request, S extends Response, AOUT extends FlatObject = EmptyObject>(...params: ConstructorParameters<typeof ExpressMiddleware<R, S, AOUT>>): EndpointsFactory<Extension<IN, undefined>, (CTX extends Record<string, never> ? AOUT : CTX) & AOUT, SCO>;
677
+ addContext<RET extends FlatObject>(getContext: () => Promise<RET>): EndpointsFactory<Extension<IN, undefined>, (CTX extends Record<string, never> ? RET : CTX) & RET, SCO>;
677
678
  build<BOUT extends IOSchema, BIN extends IOSchema = EmptySchema>({
678
679
  input,
679
680
  output: outputSchema,
@@ -700,11 +701,11 @@ declare const arrayEndpointsFactory: EndpointsFactory<undefined, Record<string,
700
701
  //#region src/server.d.ts
701
702
  declare const attachRouting: (config: AppConfig, routing: Routing) => {
702
703
  notFoundHandler: express.RequestHandler<express_serve_static_core0.ParamsDictionary, any, any, qs0.ParsedQs, Record<string, any>>;
703
- logger: AbstractLogger | BuiltinLogger;
704
+ logger: BuiltinLogger | AbstractLogger;
704
705
  };
705
706
  declare const createServer: (config: ServerConfig, routing: Routing) => Promise<{
706
707
  app: express_serve_static_core0.Express;
707
- logger: AbstractLogger | BuiltinLogger;
708
+ logger: BuiltinLogger | AbstractLogger;
708
709
  servers: (http.Server<typeof http.IncomingMessage, typeof http.ServerResponse> | https.Server<typeof http.IncomingMessage, typeof http.ServerResponse>)[];
709
710
  }>;
710
711
  //#endregion
@@ -871,7 +872,7 @@ declare const testEndpoint: <LOG extends FlatObject, REQ extends RequestOptions>
871
872
  requestMock: node_mocks_http0.MockRequest<Request<express_serve_static_core0.ParamsDictionary, any, any, qs0.ParsedQs, Record<string, any>> & REQ>;
872
873
  responseMock: node_mocks_http0.MockResponse<Response<any, Record<string, any>>>;
873
874
  loggerMock: AbstractLogger & LOG & {
874
- _getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
875
+ _getLogs: () => Record<"warn" | "info" | "debug" | "error", unknown[]>;
875
876
  };
876
877
  }>;
877
878
  declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOptions>({
@@ -887,7 +888,7 @@ declare const testMiddleware: <LOG extends FlatObject, REQ extends RequestOption
887
888
  requestMock: node_mocks_http0.MockRequest<Request<express_serve_static_core0.ParamsDictionary, any, any, qs0.ParsedQs, Record<string, any>> & REQ>;
888
889
  responseMock: node_mocks_http0.MockResponse<Response<any, Record<string, any>>>;
889
890
  loggerMock: AbstractLogger & LOG & {
890
- _getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
891
+ _getLogs: () => Record<"warn" | "info" | "debug" | "error", unknown[]>;
891
892
  };
892
893
  output: FlatObject;
893
894
  }>;
@@ -1011,14 +1012,14 @@ interface DateOutParams extends Omit<Parameters<z.ZodString["meta"]>[0], "exampl
1011
1012
  //#endregion
1012
1013
  //#region src/raw-schema.d.ts
1013
1014
  declare const base: z.ZodObject<{
1014
- raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
1015
+ raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol, "out">;
1015
1016
  }, z.core.$strip>;
1016
1017
  type Base = ReturnType<typeof base.brand<symbol>>;
1017
1018
  declare const extended: <S extends z.core.$ZodShape>(extra: S) => z.core.$ZodBranded<z.ZodObject<("raw" & keyof S extends never ? {
1018
- raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
1019
+ raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol, "out">;
1019
1020
  } & S : ({
1020
- raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
1021
- } extends infer T_1 extends z.core.util.SomeObject ? { [K in keyof T_1 as K extends keyof S ? never : K]: T_1[K] } : never) & { [K_1 in keyof S]: S[K_1] }) extends infer T ? { [k in keyof T]: T[k] } : never, z.core.$strip>, symbol>;
1021
+ raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol, "out">;
1022
+ } extends infer T_1 extends z.core.util.SomeObject ? { [K in keyof T_1 as K extends keyof S ? never : K]: T_1[K] } : never) & { [K_1 in keyof S]: S[K_1] }) extends infer T ? { [k in keyof T]: T[k] } : never, z.core.$strip>, symbol, "out">;
1022
1023
  declare function raw(): Base;
1023
1024
  declare function raw<S extends z.core.$ZodShape>(extra: S): ReturnType<typeof extended<S>>;
1024
1025
  //#endregion
@@ -1027,12 +1028,12 @@ declare const ez: {
1027
1028
  dateIn: ({
1028
1029
  examples,
1029
1030
  ...rest
1030
- }?: DateInParams) => zod_v4_core0.$ZodBranded<zod0.ZodPipe<zod0.ZodPipe<zod0.ZodUnion<readonly [zod0.ZodISODate, zod0.ZodISODateTime, zod0.ZodISODateTime]>, zod0.ZodTransform<Date, string>>, zod0.ZodDate>, symbol>;
1031
- dateOut: (meta?: DateOutParams) => zod_v4_core0.$ZodBranded<zod0.ZodPipe<zod0.ZodDate, zod0.ZodTransform<string, Date>>, symbol>;
1032
- form: <S extends zod_v4_core0.$ZodShape>(base: S | zod0.ZodObject<S>) => zod_v4_core0.$ZodBranded<zod0.ZodObject<S, zod_v4_core0.$strip>, symbol>;
1033
- upload: () => zod_v4_core0.$ZodBranded<zod0.ZodCustom<express_fileupload0.UploadedFile, express_fileupload0.UploadedFile>, symbol>;
1031
+ }?: DateInParams) => zod_v4_core0.$ZodBranded<zod0.ZodPipe<zod0.ZodPipe<zod0.ZodUnion<readonly [zod0.ZodISODate, zod0.ZodISODateTime, zod0.ZodISODateTime]>, zod0.ZodTransform<Date, string>>, zod0.ZodDate>, symbol, "out">;
1032
+ dateOut: (meta?: DateOutParams) => zod_v4_core0.$ZodBranded<zod0.ZodPipe<zod0.ZodDate, zod0.ZodTransform<string, Date>>, symbol, "out">;
1033
+ form: <S extends zod_v4_core0.$ZodShape>(base: S | zod0.ZodObject<S>) => zod_v4_core0.$ZodBranded<zod0.ZodObject<S, zod_v4_core0.$strip>, symbol, "out">;
1034
+ upload: () => zod_v4_core0.$ZodBranded<zod0.ZodCustom<express_fileupload0.UploadedFile, express_fileupload0.UploadedFile>, symbol, "out">;
1034
1035
  raw: typeof raw;
1035
- buffer: () => zod_v4_core0.$ZodBranded<zod0.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
1036
+ buffer: () => zod_v4_core0.$ZodBranded<zod0.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol, "out">;
1036
1037
  };
1037
1038
  //#endregion
1038
1039
  export { type ApiResponse, type AppConfig, type BasicSecurity, type BearerSecurity, BuiltinLogger, type CommonConfig, type CookieSecurity, type Depicter, Documentation, DocumentationError, EndpointsFactory, EventStreamFactory, type FlatObject, type HeaderSecurity, type IOSchema, type InputSecurity, InputValidationError, Integration, type LoggerOverrides, type Method, Middleware, MissingPeerError, type OAuth2Security, type OpenIdSecurity, OutputValidationError, type Producer, ResultHandler, type Routing, RoutingError, ServeStatic, type ServerConfig, type TagOverrides, arrayEndpointsFactory, arrayResultHandler, attachRouting, createConfig, createServer, defaultEndpointsFactory, defaultResultHandler, ensureHttpError, ez, getMessageFromError, testEndpoint, testMiddleware };
package/dist/index.js CHANGED
@@ -14,7 +14,7 @@ ${i}888${n}
14
14
  ${r}
15
15
  `;e.write(c.split(`
16
16
  `).map((e,t)=>s[t]?s[t](e):e).join(`
17
- `))},qt=e=>{e.startupLogo!==!1&&Kt(process.stdout);let t=e.errorHandler||W,n=rt(e.logger)?e.logger:new st(e.logger);n.debug(`Running`,{build:`v26.2.0`,env:process.env.NODE_ENV||`development`}),Wt(n);let r=Ht({logger:n,config:e}),i={getLogger:Ut(n),errorHandler:t},a=Lt(i),o=It(i);return{...i,logger:n,notFoundHandler:a,catcher:o,loggingMiddleware:r}},Jt=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=qt(e);return Ot({app:e.app.use(a),routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},Yt=async(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=qt(e),s=v().disable(`x-powered-by`).set(`query parser`,e.queryParser??`simple`).use(o);if(e.compression){let t=await lt(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}await e.beforeRouting?.({app:s,getLogger:r}),Ot({app:s,routing:t,getLogger:r,config:e,parsers:{json:[e.jsonParser||v.json()],raw:[e.rawParser||v.raw(),Vt],form:[e.formParser||v.urlencoded()],upload:e.upload?await Bt({config:e,getLogger:r}):[]}}),await e.afterRouting?.({app:s,getLogger:r}),s.use(a,i);let c=[],l=(e,t)=>()=>e.listen(t,()=>n.info(`Listening`,t)),u=[];if(e.http){let t=y.createServer(s);c.push(t),u.push(l(t,e.http.listen))}if(e.https){let t=ee.createServer(e.https.options,s);c.push(t),u.push(l(t,e.https.listen))}return c.length||n.warn(`No servers configured.`),e.gracefulShutdown&&Gt({logger:n,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:s,logger:n,servers:u.map(e=>e())}},Xt=e=>O(e)&&`or`in e,Zt=e=>O(e)&&`and`in e,Qt=e=>!Zt(e)&&!Xt(e),$t=e=>{let t=n.filter(Qt,e),r=n.chain(n.prop(`and`),n.filter(Zt,e)),[i,a]=n.partition(Qt,r),o=n.concat(t,i),s=n.filter(Xt,e);return n.map(n.prop(`or`),n.concat(s,a)).reduce((e,t)=>E(e,n.map(e=>Qt(e)?[e]:e.and,t),([e,t])=>n.concat(e,t)),n.reject(n.isEmpty,[o]))};var en=`a-im.accept.accept-additions.accept-ch.accept-charset.accept-datetime.accept-encoding.accept-features.accept-language.accept-signature.access-control.access-control-request-headers.access-control-request-method.alpn.alt-used.alternates.amp-cache-transform.apply-to-redirect-ref.authentication-control.authentication-info.authorization.available-dictionary.c-ext.c-man.c-opt.c-pep.c-pep-info.cache-control.cal-managed-id.caldav-timezones.capsule-protocol.cert-not-after.cert-not-before.client-cert.client-cert-chain.close.cmcd-object.cmcd-request.cmcd-session.cmcd-status.cmsd-dynamic.cmsd-static.concealed-auth-export.configuration-context.connection.content-digest.content-disposition.content-encoding.content-id.content-language.content-length.content-location.content-md5.content-range.content-script-type.content-type.cookie.cookie2.cross-origin-embedder-policy.cross-origin-embedder-policy-report-only.cross-origin-opener-policy.cross-origin-opener-policy-report-only.cross-origin-resource-policy.cta-common-access-token.dasl.date.dav.default-style.delta-base.deprecation.depth.derived-from.destination.detached-jws.differential-id.dictionary-id.digest.dpop.dpop-nonce.early-data.ediint-features.expect.expect-ct.ext.forwarded.from.getprofile.hobareg.host.http2-settings.if.if-match.if-modified-since.if-none-match.if-range.if-schedule-tag-match.if-unmodified-since.im.include-referred-token-binding-id.isolation.keep-alive.label.last-event-id.link.link-template.lock-token.man.max-forwards.memento-datetime.meter.method-check.method-check-expires.mime-version.negotiate.nel.odata-entityid.odata-isolation.odata-maxversion.odata-version.opt.ordering-type.origin.origin-agent-cluster.oscore.oslc-core-version.overwrite.p3p.pep.pep-info.permissions-policy.pics-label.ping-from.ping-to.position.pragma.prefer.preference-applied.priority.profileobject.protocol.protocol-info.protocol-query.protocol-request.proxy-authorization.proxy-features.proxy-instruction.public.public-key-pins.public-key-pins-report-only.range.redirect-ref.referer.referer-root.referrer-policy.repeatability-client-id.repeatability-first-sent.repeatability-request-id.repeatability-result.replay-nonce.reporting-endpoints.repr-digest.safe.schedule-reply.schedule-tag.sec-fetch-storage-access.sec-gpc.sec-purpose.sec-token-binding.sec-websocket-extensions.sec-websocket-key.sec-websocket-protocol.sec-websocket-version.security-scheme.setprofile.signature.signature-input.slug.soapaction.status-uri.sunset.surrogate-capability.tcn.te.timeout.topic.traceparent.tracestate.trailer.transfer-encoding.ttl.upgrade.urgency.uri.use-as-dictionary.user-agent.variant-vary.via.want-content-digest.want-digest.want-repr-digest.warning.x-content-type-options.x-frame-options`.split(`.`);const tn=`https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString`,nn={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},rn=e=>e.replace(ue,e=>`{${e.slice(1)}}`),an=({},e)=>{if(e.isResponse)throw new N(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},on=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),sn=({zodSchema:e,jsonSchema:t})=>{if(!T(e,`union`)||!(`discriminator`in e._zod.def))return t;let n=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:n}}},cn=n.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return J(e,`throw`)},(e,{jsonSchema:t})=>t),ln=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:hn(t.type)})},Y=e=>e,un=({jsonSchema:{examples:e,description:t}},n)=>{if(n.isResponse)throw new N(`Please use ez.dateOut() for output.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,pattern:`^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?)?Z?$`,externalDocs:{url:tn}};return e?.length&&(r.examples=e),r},dn=({jsonSchema:{examples:e,description:t}},n)=>{if(!n.isResponse)throw new N(`Please use ez.dateIn() for input.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,externalDocs:{url:tn}};return e?.length&&(r.examples=e),r},fn=()=>({type:`string`,format:`bigint`,pattern:`^-?\\d+$`}),pn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,mn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return nn?.[t]},hn=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],gn=({zodSchema:e,jsonSchema:t},n)=>{let r=e._zod.def[n.isResponse?`out`:`in`],i=e._zod.def[n.isResponse?`in`:`out`];if(!T(r,`transform`))return t;let a=Y(Cn(i,{ctx:n}));if(b(a))if(n.isResponse){let e=ye(r,mn(a));if(e&&[`number`,`string`,`boolean`].includes(e))return{...t,type:e}}else{let{type:e,...t}=a;return{...t,format:`${t.format||e} (preprocessed)`}}return t},_n=({jsonSchema:e})=>{if(e.type!==`object`)return e;let t=e;return!t.properties||!(`raw`in t.properties)||!O(t.properties.raw)?e:t.properties.raw},vn=e=>e.length?n.fromPairs(n.zip(n.times(e=>`example${e+1}`,e.length),n.map(n.objOf(`value`),e))):void 0,yn=(e,t)=>t?.includes(e)||e.startsWith(`x-`)||en.includes(e),bn=({path:e,method:t,request:r,inputSources:i,makeRef:a,composition:o,isHeader:s,security:c,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let u=J(r),d=de(e),f=i.includes(`query`),p=i.includes(`params`),m=i.includes(`headers`),h=e=>p&&d.includes(e),g=n.chain(n.filter(e=>e.type===`header`),c??[]).map(({name:e})=>e),_=n=>m&&(s?.(n,t,e)??yn(n,g));return Object.entries(u.properties).reduce((e,[t,r])=>{if(!O(r))return e;let i=h(t)?`path`:_(t)?`header`:f?`query`:void 0;if(!i)return e;let s=Y(r),c=o===`components`?a(r.id||JSON.stringify(r),s,r.id||D(l,t)):s;return e.concat({name:t,in:i,deprecated:r.deprecated,required:u.required?.includes(t)||!1,description:s.description||l,schema:c,examples:vn(b(s)&&s.examples?.length?s.examples:n.pluck(t,u.examples?.filter(n.both(O,n.has(t)))||[]))})},[])},xn={nullable:ln,union:sn,bigint:fn,intersection:cn,tuple:pn,pipe:gn,[A]:un,[j]:dn,[F]:an,[I]:_n,[k]:on},Sn=(e,t,r)=>{let i=[e,t];for(;i.length;){let e=i.shift();if(n.is(Object,e)){if(re(e)&&!e.$ref.startsWith(`#/components`)){let n=t[e.$ref.split(`/`).pop()];n&&(e.$ref=r.makeRef(n.id||n,Y(n),n.id).$ref);continue}i.push(...n.values(e))}n.is(Array,e)&&i.push(...n.values(e))}return e},Cn=(e,{ctx:n,rules:r=xn})=>{let{$defs:a={},properties:o={}}=i.toJSONSchema(i.object({subject:e}),{unrepresentable:`any`,io:n.isResponse?`output`:`input`,override:e=>{let i=t(e.zodSchema),a=r[i&&i in r?i:e.zodSchema._zod.def.type];if(a){let t={...a(e,n)};for(let t in e.jsonSchema)delete e.jsonSchema[t];Object.assign(e.jsonSchema,t)}}});return Sn(O(o.subject)?o.subject:{},a,n)},wn=(e,t)=>{if(re(e))return[e,!1];let r=!1,i=n.map(e=>{let[n,i]=wn(e,t);return r||=i,n}),a=n.omit(t),o={properties:a,examples:n.map(a),required:n.without(t),allOf:i,oneOf:i,anyOf:i},s=n.evolve(o,e);return[s,r||!!s.required?.length]},Tn=({method:e,path:t,schema:r,mimeTypes:i,variant:a,makeRef:o,composition:s,hasMultipleStatusCodes:c,statusCode:l,brandHandling:u,description:d=`${e.toUpperCase()} ${t} ${ve(a)} response ${c?l:``}`.trim()})=>{if(!xe(e,i))return{description:d};let f=Y(Cn(r,{rules:{...u,...xn},ctx:{isResponse:!0,makeRef:o,path:t,method:e}})),p=[];b(f)&&f.examples&&(p.push(...f.examples),delete f.examples);let m={schema:s===`components`?o(r,f,D(d)):f,examples:vn(p)};return{description:d,content:n.fromPairs(n.xprod(i,[m]))}},En=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},Dn=({name:e},t)=>{let n={type:`apiKey`,in:`query`,name:e};return t?.includes(`body`)&&(t?.includes(`query`)?(n[`x-in-alternative`]=`body`,n.description=`${e} CAN also be supplied within the request body`):(n[`x-in-actual`]=`body`,n.description=`${e} MUST be supplied within the request body instead of query`)),n},On=({name:e})=>({type:`apiKey`,in:`header`,name:e}),kn=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),An=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),jn=({flows:e={}})=>({type:`oauth2`,flows:n.map(e=>({...e,scopes:e.scopes||{}}),n.reject(n.isNil,e))}),Mn=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?En(e):e.type===`input`?Dn(e,t):e.type===`header`?On(e):e.type===`cookie`?kn(e):e.type===`openid`?An(e):jn(e);return e.map(e=>e.map(n))},Nn=(e,t,n)=>e.map(e=>e.reduce((e,r)=>{let i=n(r),a=[`oauth2`,`openIdConnect`].includes(r.type);return Object.assign(e,{[i]:a?t:[]})},{})),Pn=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>Cn(e,{rules:{...t,...xn},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),Fn=({method:e,path:t,schema:r,request:i,mimeType:a,makeRef:o,composition:s,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let[u,d]=wn(Y(i),c),f=[];b(u)&&u.examples&&(f.push(...u.examples),delete u.examples);let p={schema:s===`components`?o(r,u,D(l)):u,examples:vn(f.length?f:J(i).examples?.filter(e=>O(e)&&!Array.isArray(e)).map(n.omit(c))||[])},m={description:l,content:{[a]:p}};return(d||a===x.raw)&&(m.required=!0),m},In=e=>Object.entries(e).reduce((e,[t,n])=>{if(!n)return e;let r={name:t,description:typeof n==`string`?n:n.description};return typeof n==`object`&&n.url&&(r.externalDocs={url:n.url}),e.concat(r)},[]),Ln=e=>e.length<=50?e:e.slice(0,49)+`…`,X=e=>e.length?e.slice():void 0;var Rn=class extends ne{#e=new Map;#t=new Map;#n=new Map;#r(e,t,n){let r=this.#n.get(e);if(!r){let t=n?0:1;do r=`${n??`Schema`}${t?this.#n.size+t:``}`,t++;while(this.rootDoc.components?.schemas?.[r]);this.#n.set(e,r)}return this.addSchema(r,t),{$ref:`#/components/schemas/${r}`}}#i(e,t,n){let r=n||D(t,e),i=this.#t.get(r);if(i===void 0)return this.#t.set(r,1),r;if(n)throw new N(`Duplicated operationId: "${n}"`,{method:t,isResponse:!1,path:e});return i++,this.#t.set(r,i),`${r}${i}`}#a(e){let t=JSON.stringify(e);for(let e in this.rootDoc.components?.securitySchemes||{})if(t===JSON.stringify(this.rootDoc.components?.securitySchemes?.[e]))return e;let n=(this.#e.get(e.type)||0)+1;return this.#e.set(e.type,n),`${e.type.toUpperCase()}_${n}`}constructor({routing:e,config:t,title:r,version:i,serverUrl:a,descriptions:o,brandHandling:s,tags:c,isHeader:l,hasSummaryFromDescription:u=!0,hasHeadMethod:d=!0,composition:f=`inline`}){super(),this.addInfo({title:r,version:i});for(let e of typeof a==`string`?[a]:a)this.addServer({url:e});let p=(e,r,i)=>{let a={path:r,method:e,endpoint:i,composition:f,brandHandling:s,makeRef:this.#r.bind(this)},{description:c,shortDescription:d,scopes:p,inputSchema:m}=i,h=d?Ln(d):u&&c?Ln(c):void 0,g=ge(e,t.inputSources),_=this.#i(r,e,i.getOperationId(e)),v=Pn({...a,schema:m}),y=$t(i.security),ee=bn({...a,inputSources:g,isHeader:l,security:y,request:v,description:o?.requestParameter?.call(null,{method:e,path:r,operationId:_})}),te={};for(let t of H){let n=i.getResponses(t);for(let{mimeTypes:i,schema:s,statusCodes:c}of n)for(let l of c)te[l]=Tn({...a,variant:t,schema:s,mimeTypes:i,statusCode:l,hasMultipleStatusCodes:n.length>1||c.length>1,description:o?.[`${t}Response`]?.call(null,{method:e,path:r,operationId:_,statusCode:l})})}let ne=g.includes(`body`)?Fn({...a,request:v,paramNames:n.pluck(`name`,ee),schema:m,mimeType:x[i.requestType],description:o?.requestBody?.call(null,{method:e,path:r,operationId:_})}):void 0,re=Nn(Mn(y,g),p,e=>{let t=this.#a(e);return this.addSecurityScheme(t,e),t}),b={operationId:_,summary:h,description:c,deprecated:i.isDeprecated||void 0,tags:X(i.tags),parameters:X(ee),requestBody:ne,security:X(re),responses:te};this.addPath(rn(r),{[e]:b})};Ct({routing:e,config:t,onEndpoint:d?gt(p):p}),c&&(this.rootDoc.tags=In(c))}};const zn=e=>ie({...e,headers:{"content-type":x.json,...e?.headers}}),Bn=e=>ae(e),Vn=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:it(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},Hn=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=zn(e),a=Bn({req:i,...t});a.req=t?.req||i,i.res=a;let o=Vn(r);return{requestMock:i,responseMock:a,loggerMock:o,configMock:{cors:!1,logger:o,...n}}},Un=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=Hn(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},Wn=async({middleware:e,ctx:t={},...n})=>{let{requestMock:r,responseMock:i,loggerMock:a,configMock:{inputSources:o,errorHandler:s=W}}=Hn(n),c={request:r,response:i,logger:a,input:_e(r,o),ctx:t};try{return{requestMock:r,responseMock:i,loggerMock:a,output:await e.execute(c)}}catch(e){return await s.execute({...c,error:C(e),output:null}),{requestMock:r,responseMock:i,loggerMock:a,output:{}}}};var Gn=class t{ts;f;exportModifier;asyncModifier;accessModifiers;#e;static#t=/^[A-Za-z_$][A-Za-z0-9_$]*$/;constructor(){this.ts=e(import.meta.url)(`typescript`),this.f=this.ts.factory,this.exportModifier=[this.f.createModifier(this.ts.SyntaxKind.ExportKeyword)],this.asyncModifier=[this.f.createModifier(this.ts.SyntaxKind.AsyncKeyword)],this.accessModifiers={public:[this.f.createModifier(this.ts.SyntaxKind.PublicKeyword)],protectedReadonly:[this.f.createModifier(this.ts.SyntaxKind.ProtectedKeyword),this.f.createModifier(this.ts.SyntaxKind.ReadonlyKeyword)]},this.#e=[this.ts.SyntaxKind.AnyKeyword,this.ts.SyntaxKind.BigIntKeyword,this.ts.SyntaxKind.BooleanKeyword,this.ts.SyntaxKind.NeverKeyword,this.ts.SyntaxKind.NumberKeyword,this.ts.SyntaxKind.ObjectKeyword,this.ts.SyntaxKind.StringKeyword,this.ts.SyntaxKind.SymbolKeyword,this.ts.SyntaxKind.UndefinedKeyword,this.ts.SyntaxKind.UnknownKeyword,this.ts.SyntaxKind.VoidKeyword]}addJsDoc=(e,t)=>this.ts.addSyntheticLeadingComment(e,this.ts.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0);printNode=(e,t)=>{let n=this.ts.createSourceFile(`print.ts`,``,this.ts.ScriptTarget.Latest,!1,this.ts.ScriptKind.TS);return this.ts.createPrinter(t).printNode(this.ts.EmitHint.Unspecified,e,n)};makePropertyIdentifier=e=>typeof e==`string`&&t.#t.test(e)?this.f.createIdentifier(e):this.literally(e);makeTemplate=(e,...t)=>this.f.createTemplateExpression(this.f.createTemplateHead(e),t.map(([e,n=``],r)=>this.f.createTemplateSpan(e,r===t.length-1?this.f.createTemplateTail(n):this.f.createTemplateMiddle(n))));makeParam=(e,{type:t,mod:n,init:r,optional:i}={})=>this.f.createParameterDeclaration(n,void 0,e,i?this.f.createToken(this.ts.SyntaxKind.QuestionToken):void 0,t?this.ensureTypeNode(t):void 0,r);makeParams=e=>Object.entries(e).map(([e,t])=>this.makeParam(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t));makePublicConstructor=(e,t=[])=>this.f.createConstructorDeclaration(this.accessModifiers.public,e,this.f.createBlock(t));ensureTypeNode=(e,t)=>typeof e==`number`?this.f.createKeywordTypeNode(e):typeof e==`string`||this.ts.isIdentifier(e)?this.f.createTypeReferenceNode(e,t&&n.map(this.ensureTypeNode.bind(this),t)):e;makeRecordStringAny=()=>this.ensureTypeNode(`Record`,[this.ts.SyntaxKind.StringKeyword,this.ts.SyntaxKind.AnyKeyword]);makeUnion=e=>{let t=new Map;for(let n of e)t.set(this.isPrimitive(n)?n.kind:n,n);return this.f.createUnionTypeNode(Array.from(t.values()))};makeInterfaceProp=(e,t,{isOptional:r,isDeprecated:i,comment:a}={})=>{let o=this.ensureTypeNode(t),s=this.f.createPropertySignature(void 0,this.makePropertyIdentifier(e),r?this.f.createToken(this.ts.SyntaxKind.QuestionToken):void 0,r?this.makeUnion([o,this.ensureTypeNode(this.ts.SyntaxKind.UndefinedKeyword)]):o),c=n.reject(n.isNil,[i?`@deprecated`:void 0,a]);return c.length?this.addJsDoc(s,c.join(` `)):s};makeOneLine=e=>this.ts.setEmitFlags(e,this.ts.EmitFlags.SingleLine);makeDeconstruction=(...e)=>this.f.createArrayBindingPattern(e.map(e=>this.f.createBindingElement(void 0,void 0,e)));makeConst=(e,t,{type:n,expose:r}={})=>this.f.createVariableStatement(r&&this.exportModifier,this.f.createVariableDeclarationList([this.f.createVariableDeclaration(e,void 0,n?this.ensureTypeNode(n):void 0,t)],this.ts.NodeFlags.Const));makePublicLiteralType=(e,t)=>this.makeType(e,this.makeUnion(n.map(this.makeLiteralType.bind(this),t)),{expose:!0});makeType=(e,t,{expose:n,comment:r,params:i}={})=>{let a=this.f.createTypeAliasDeclaration(n?this.exportModifier:void 0,e,i&&this.makeTypeParams(i),t);return r?this.addJsDoc(a,r):a};makePublicProperty=(e,t)=>this.f.createPropertyDeclaration(this.accessModifiers.public,e,void 0,this.ensureTypeNode(t),void 0);makePublicMethod=(e,t,n,{typeParams:r,returns:i}={})=>this.f.createMethodDeclaration(this.accessModifiers.public,void 0,e,void 0,r&&this.makeTypeParams(r),t,i,this.f.createBlock(n));makePublicClass=(e,t,{typeParams:n}={})=>this.f.createClassDeclaration(this.exportModifier,e,n&&this.makeTypeParams(n),void 0,t);makeKeyOf=e=>this.f.createTypeOperatorNode(this.ts.SyntaxKind.KeyOfKeyword,this.ensureTypeNode(e));makePromise=e=>this.ensureTypeNode(Promise.name,[e]);makeInterface=(e,t,{expose:n,comment:r}={})=>{let i=this.f.createInterfaceDeclaration(n?this.exportModifier:void 0,e,void 0,void 0,t);return r?this.addJsDoc(i,r):i};makeTypeParams=e=>(Array.isArray(e)?e.map(e=>n.pair(e,void 0)):Object.entries(e)).map(([e,t])=>{let{type:n,init:r}=typeof t==`object`&&`init`in t?t:{type:t};return this.f.createTypeParameterDeclaration([],e,n?this.ensureTypeNode(n):void 0,r?this.ensureTypeNode(r):void 0)});makeArrowFn=(e,t,{isAsync:r}={})=>this.f.createArrowFunction(r?this.asyncModifier:void 0,void 0,Array.isArray(e)?n.map(this.makeParam.bind(this),e):this.makeParams(e),void 0,void 0,t);makeTernary=(e,t,n)=>this.f.createConditionalExpression(e,this.f.createToken(this.ts.SyntaxKind.QuestionToken),t,this.f.createToken(this.ts.SyntaxKind.ColonToken),n);makeCall=(e,...t)=>(...n)=>this.f.createCallExpression(t.reduce((e,t)=>typeof t==`string`||this.ts.isIdentifier(t)?this.f.createPropertyAccessExpression(e,t):this.f.createElementAccessExpression(e,t),typeof e==`string`?this.f.createIdentifier(e):e),void 0,n);makeNew=(e,...t)=>this.f.createNewExpression(this.f.createIdentifier(e),void 0,t);makeExtract=(e,t)=>this.ensureTypeNode(`Extract`,[e,t]);makeAssignment=(e,t)=>this.f.createExpressionStatement(this.f.createBinaryExpression(e,this.f.createToken(this.ts.SyntaxKind.EqualsToken),t));makeIndexed=(e,t)=>this.f.createIndexedAccessTypeNode(this.ensureTypeNode(e),this.ensureTypeNode(t));makeMaybeAsync=e=>this.makeUnion([this.ensureTypeNode(e),this.makePromise(e)]);makeFnType=(e,t)=>this.f.createFunctionTypeNode(void 0,this.makeParams(e),this.ensureTypeNode(t));literally=e=>typeof e==`number`?this.f.createNumericLiteral(e):typeof e==`bigint`?this.f.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?this.f.createTrue():this.f.createFalse():e===null?this.f.createNull():this.f.createStringLiteral(e);makeLiteralType=e=>this.f.createLiteralTypeNode(this.literally(e));isPrimitive=e=>this.#e.includes(e.kind)};const Z=e=>e;var Kn=class{api=new Gn;paths=new Set;tags=new Map;registry=new Map;#e={pathType:this.api.f.createIdentifier(`Path`),implementationType:this.api.f.createIdentifier(`Implementation`),keyParameter:this.api.f.createIdentifier(`key`),pathParameter:this.api.f.createIdentifier(`path`),paramsArgument:this.api.f.createIdentifier(`params`),ctxArgument:this.api.f.createIdentifier(`ctx`),methodParameter:this.api.f.createIdentifier(`method`),requestParameter:this.api.f.createIdentifier(`request`),eventParameter:this.api.f.createIdentifier(`event`),dataParameter:this.api.f.createIdentifier(`data`),handlerParameter:this.api.f.createIdentifier(`handler`),msgParameter:this.api.f.createIdentifier(`msg`),parseRequestFn:this.api.f.createIdentifier(`parseRequest`),substituteFn:this.api.f.createIdentifier(`substitute`),provideMethod:this.api.f.createIdentifier(`provide`),onMethod:this.api.f.createIdentifier(`on`),implementationArgument:this.api.f.createIdentifier(`implementation`),hasBodyConst:this.api.f.createIdentifier(`hasBody`),undefinedValue:this.api.f.createIdentifier(`undefined`),responseConst:this.api.f.createIdentifier(`response`),restConst:this.api.f.createIdentifier(`rest`),searchParamsConst:this.api.f.createIdentifier(`searchParams`),defaultImplementationConst:this.api.f.createIdentifier(`defaultImplementation`),clientConst:this.api.f.createIdentifier(`client`),contentTypeConst:this.api.f.createIdentifier(`contentType`),isJsonConst:this.api.f.createIdentifier(`isJSON`),sourceProp:this.api.f.createIdentifier(`source`)};interfaces={input:this.api.f.createIdentifier(`Input`),positive:this.api.f.createIdentifier(`PositiveResponse`),negative:this.api.f.createIdentifier(`NegativeResponse`),encoded:this.api.f.createIdentifier(`EncodedResponse`),response:this.api.f.createIdentifier(`Response`)};methodType=this.api.makePublicLiteralType(`Method`,ce);someOfType=this.api.makeType(`SomeOf`,this.api.makeIndexed(`T`,this.api.makeKeyOf(`T`)),{params:[`T`]});requestType=this.api.makeType(`Request`,this.api.makeKeyOf(this.interfaces.input),{expose:!0});constructor(e){this.serverUrl=e}someOf=({name:e})=>this.api.ensureTypeNode(this.someOfType.name,[e]);makePathType=()=>this.api.makePublicLiteralType(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>this.api.makeInterface(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>this.api.makeInterfaceProp(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>this.api.makeConst(`endpointTags`,this.api.f.createObjectLiteralExpression(Array.from(this.tags).map(([e,t])=>this.api.f.createPropertyAssignment(this.api.makePropertyIdentifier(e),this.api.f.createArrayLiteralExpression(n.map(this.api.literally.bind(this.api),t))))),{expose:!0});makeImplementationType=()=>this.api.makeType(this.#e.implementationType,this.api.makeFnType({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:this.api.ts.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:this.api.makeRecordStringAny(),[this.#e.ctxArgument.text]:{optional:!0,type:`T`}},this.api.makePromise(this.api.ts.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:this.api.ts.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>this.api.makeConst(this.#e.parseRequestFn,this.api.makeArrowFn({[this.#e.requestParameter.text]:this.api.ts.SyntaxKind.StringKeyword},this.api.f.createAsExpression(this.api.makeCall(this.#e.requestParameter,Z(`split`))(this.api.f.createRegularExpressionLiteral(`/ (.+)/`),this.api.literally(2)),this.api.f.createTupleTypeNode([this.api.ensureTypeNode(this.methodType.name),this.api.ensureTypeNode(this.#e.pathType)]))));makeSubstituteFn=()=>this.api.makeConst(this.#e.substituteFn,this.api.makeArrowFn({[this.#e.pathParameter.text]:this.api.ts.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:this.api.makeRecordStringAny()},this.api.f.createBlock([this.api.makeConst(this.#e.restConst,this.api.f.createObjectLiteralExpression([this.api.f.createSpreadAssignment(this.#e.paramsArgument)])),this.api.f.createForInStatement(this.api.f.createVariableDeclarationList([this.api.f.createVariableDeclaration(this.#e.keyParameter)],this.api.ts.NodeFlags.Const),this.#e.paramsArgument,this.api.f.createBlock([this.api.makeAssignment(this.#e.pathParameter,this.api.makeCall(this.#e.pathParameter,Z(`replace`))(this.api.makeTemplate(`:`,[this.#e.keyParameter]),this.api.makeArrowFn([],this.api.f.createBlock([this.api.f.createExpressionStatement(this.api.f.createDeleteExpression(this.api.f.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),this.api.f.createReturnStatement(this.api.f.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),this.api.f.createReturnStatement(this.api.f.createAsExpression(this.api.f.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),this.api.ensureTypeNode(`const`)))])));#t=()=>this.api.makePublicMethod(this.#e.provideMethod,this.api.makeParams({[this.#e.requestParameter.text]:`K`,[this.#e.paramsArgument.text]:this.api.makeIndexed(this.interfaces.input,`K`),[this.#e.ctxArgument.text]:{optional:!0,type:`T`}}),[this.api.makeConst(this.api.makeDeconstruction(this.#e.methodParameter,this.#e.pathParameter),this.api.makeCall(this.#e.parseRequestFn)(this.#e.requestParameter)),this.api.f.createReturnStatement(this.api.makeCall(this.api.f.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,this.api.f.createSpreadElement(this.api.makeCall(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:this.api.makePromise(this.api.makeIndexed(this.interfaces.response,`K`))});makeClientClass=e=>this.api.makePublicClass(e,[this.api.makePublicConstructor([this.api.makeParam(this.#e.implementationArgument,{type:this.api.ensureTypeNode(this.#e.implementationType,[`T`]),mod:this.api.accessModifiers.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:[`T`]});#n=e=>this.api.makeTemplate(`?`,[this.api.makeNew(URLSearchParams.name,e)]);#r=()=>this.api.makeNew(URL.name,this.api.makeTemplate(``,[this.#e.pathParameter],[this.#e.searchParamsConst]),this.api.literally(this.serverUrl));makeDefaultImplementation=()=>{let e=this.api.f.createPropertyAssignment(Z(`method`),this.api.makeCall(this.#e.methodParameter,Z(`toUpperCase`))()),t=this.api.f.createPropertyAssignment(Z(`headers`),this.api.makeTernary(this.#e.hasBodyConst,this.api.f.createObjectLiteralExpression([this.api.f.createPropertyAssignment(this.api.literally(`Content-Type`),this.api.literally(x.json))]),this.#e.undefinedValue)),n=this.api.f.createPropertyAssignment(Z(`body`),this.api.makeTernary(this.#e.hasBodyConst,this.api.makeCall(JSON[Symbol.toStringTag],Z(`stringify`))(this.#e.paramsArgument),this.#e.undefinedValue)),r=this.api.makeConst(this.#e.responseConst,this.api.f.createAwaitExpression(this.api.makeCall(fetch.name)(this.#r(),this.api.f.createObjectLiteralExpression([e,t,n])))),i=this.api.makeConst(this.#e.hasBodyConst,this.api.f.createLogicalNot(this.api.makeCall(this.api.f.createArrayLiteralExpression([this.api.literally(`get`),this.api.literally(`head`),this.api.literally(`delete`)]),Z(`includes`))(this.#e.methodParameter))),a=this.api.makeConst(this.#e.searchParamsConst,this.api.makeTernary(this.#e.hasBodyConst,this.api.literally(``),this.#n(this.#e.paramsArgument))),o=this.api.makeConst(this.#e.contentTypeConst,this.api.makeCall(this.#e.responseConst,Z(`headers`),Z(`get`))(this.api.literally(`content-type`))),s=this.api.f.createIfStatement(this.api.f.createPrefixUnaryExpression(this.api.ts.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),this.api.f.createReturnStatement()),c=this.api.makeConst(this.#e.isJsonConst,this.api.makeCall(this.#e.contentTypeConst,Z(`startsWith`))(this.api.literally(x.json))),l=this.api.f.createReturnStatement(this.api.makeCall(this.#e.responseConst,this.api.makeTernary(this.#e.isJsonConst,this.api.literally(Z(`json`)),this.api.literally(Z(`text`))))());return this.api.makeConst(this.#e.defaultImplementationConst,this.api.makeArrowFn([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],this.api.f.createBlock([i,a,r,o,s,c,l]),{isAsync:!0}),{type:this.#e.implementationType})};#i=()=>this.api.makePublicConstructor(this.api.makeParams({request:`K`,params:this.api.makeIndexed(this.interfaces.input,`K`)}),[this.api.makeConst(this.api.makeDeconstruction(this.#e.pathParameter,this.#e.restConst),this.api.makeCall(this.#e.substituteFn)(this.api.f.createElementAccessExpression(this.api.makeCall(this.#e.parseRequestFn)(this.#e.requestParameter),this.api.literally(1)),this.#e.paramsArgument)),this.api.makeConst(this.#e.searchParamsConst,this.#n(this.#e.restConst)),this.api.makeAssignment(this.api.f.createPropertyAccessExpression(this.api.f.createThis(),this.#e.sourceProp),this.api.makeNew(`EventSource`,this.#r()))]);#a=e=>this.api.f.createTypeLiteralNode([this.api.makeInterfaceProp(Z(`event`),e)]);#o=()=>this.api.makePublicMethod(this.#e.onMethod,this.api.makeParams({[this.#e.eventParameter.text]:`E`,[this.#e.handlerParameter.text]:this.api.makeFnType({[this.#e.dataParameter.text]:this.api.makeIndexed(this.api.makeExtract(`R`,this.api.makeOneLine(this.#a(`E`))),this.api.makeLiteralType(Z(`data`)))},this.api.makeMaybeAsync(this.api.ts.SyntaxKind.VoidKeyword))}),[this.api.f.createExpressionStatement(this.api.makeCall(this.api.f.createThis(),this.#e.sourceProp,Z(`addEventListener`))(this.#e.eventParameter,this.api.makeArrowFn([this.#e.msgParameter],this.api.makeCall(this.#e.handlerParameter)(this.api.makeCall(JSON[Symbol.toStringTag],Z(`parse`))(this.api.f.createPropertyAccessExpression(this.api.f.createParenthesizedExpression(this.api.f.createAsExpression(this.#e.msgParameter,this.api.ensureTypeNode(MessageEvent.name))),Z(`data`))))))),this.api.f.createReturnStatement(this.api.f.createThis())],{typeParams:{E:this.api.makeIndexed(`R`,this.api.makeLiteralType(Z(`event`)))}});makeSubscriptionClass=e=>this.api.makePublicClass(e,[this.api.makePublicProperty(this.#e.sourceProp,`EventSource`),this.#i(),this.#o()],{typeParams:{K:this.api.makeExtract(this.requestType.name,this.api.f.createTemplateLiteralType(this.api.f.createTemplateHead(`get `),[this.api.f.createTemplateLiteralTypeSpan(this.api.ensureTypeNode(this.api.ts.SyntaxKind.StringKeyword),this.api.f.createTemplateTail(``))])),R:this.api.makeExtract(this.api.makeIndexed(this.interfaces.positive,`K`),this.api.makeOneLine(this.#a(this.api.ts.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[this.api.makeConst(this.#e.clientConst,this.api.makeNew(e)),this.api.makeCall(this.#e.clientConst,this.#e.provideMethod)(this.api.literally(`get /v1/user/retrieve`),this.api.f.createObjectLiteralExpression([this.api.f.createPropertyAssignment(`id`,this.api.literally(`10`))])),this.api.makeCall(this.api.makeNew(t,this.api.literally(`get /v1/events/stream`),this.api.f.createObjectLiteralExpression()),this.#e.onMethod)(this.api.literally(`time`),this.api.makeArrowFn([`time`],this.api.f.createBlock([])))]};const qn=(e,{onEach:n,rules:r,onMissing:i,ctx:a={}})=>{let o=t(e),s=o&&o in r?r[o]:r[e._zod.def.type],c=e=>qn(e,{ctx:a,onEach:n,rules:r,onMissing:i}),l=s?s(e,{...a,next:c}):i(e,a),u=n&&n(e,{prev:l,...a});return u?{...l,...u}:l},Jn={name:n.path([`name`,`text`]),type:n.path([`type`]),optional:n.path([`questionToken`])},Yn=({_zod:{def:e}},{api:t})=>{let n=e.values.map(e=>e===void 0?t.ensureTypeNode(t.ts.SyntaxKind.UndefinedKeyword):t.makeLiteralType(e));return n.length===1?n[0]:t.makeUnion(n)},Xn=({_zod:{def:e}},{next:t,api:n})=>{let r=[...e.parts],i=()=>{let e=``;for(;r.length;){let t=r.shift();if(T(t)){r.unshift(t);break}e+=t??``}return e},a=n.f.createTemplateHead(i()),o=[];for(;r.length;){let e=t(r.shift()),a=i(),s=r.length?n.f.createTemplateMiddle:n.f.createTemplateTail;o.push(n.f.createTemplateLiteralTypeSpan(e,s(a)))}return o.length?n.f.createTemplateLiteralType(a,o):n.makeLiteralType(a.text)},Zn=(e,{isResponse:t,next:n,makeAlias:i,api:a})=>{let o=()=>{let i=Object.entries(e._zod.def.shape).map(([e,i])=>{let{description:o,deprecated:s}=r.get(i)||{};return a.makeInterfaceProp(e,n(i),{comment:o,isDeprecated:s,isOptional:(t?i._zod.optout:i._zod.optin)===`optional`})});return a.f.createTypeLiteralNode(i)};return Le(e,{io:t?`output`:`input`})?i(e,o):o()},Qn=({_zod:{def:e}},{next:t,api:n})=>n.f.createArrayTypeNode(t(e.element)),$n=({_zod:{def:e}},{api:t})=>t.makeUnion(Object.values(e.entries).map(t.makeLiteralType.bind(t))),er=({_zod:{def:e}},{next:t,api:n})=>n.makeUnion(e.options.map(t)),tr=({_zod:{def:e}},{next:t,api:n})=>n.makeUnion([t(e.innerType),n.makeLiteralType(null)]),nr=({_zod:{def:e}},{next:t,api:n})=>n.f.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:n.f.createRestTypeNode(t(e.rest)))),rr=({_zod:{def:e}},{next:t,api:n})=>n.ensureTypeNode(`Record`,[e.keyType,e.valueType].map(t)),ir=n.tryCatch((e,t)=>{if(!t.every(e.ts.isTypeLiteralNode))throw Error(`Not objects`);let r=n.chain(n.prop(`members`),t),i=n.uniqWith((...e)=>{if(!n.eqBy(Jn.name,...e))return!1;if(n.both(n.eqBy(Jn.type),n.eqBy(Jn.optional))(...e))return!0;throw Error(`Has conflicting prop`)},r);return e.f.createTypeLiteralNode(i)},(e,t,n)=>t.f.createIntersectionTypeNode(n)),ar=({_zod:{def:e}},{next:t,api:n})=>ir(n,[e.left,e.right].map(t)),Q=e=>({},{api:t})=>t.ensureTypeNode(t.ts.SyntaxKind[e]),$=({_zod:{def:e}},{next:t})=>t(e.innerType),or=(e,t)=>e.ensureTypeNode(t?e.ts.SyntaxKind.UnknownKeyword:e.ts.SyntaxKind.AnyKeyword),sr=({_zod:{def:e}},{next:t,isResponse:n,api:r})=>{let i=e[n?`out`:`in`],a=e[n?`in`:`out`];if(!T(i,`transform`))return t(i);let o=t(a),s={[r.ts.SyntaxKind.AnyKeyword]:``,[r.ts.SyntaxKind.BigIntKeyword]:BigInt(0),[r.ts.SyntaxKind.BooleanKeyword]:!1,[r.ts.SyntaxKind.NumberKeyword]:0,[r.ts.SyntaxKind.ObjectKeyword]:{},[r.ts.SyntaxKind.StringKeyword]:``,[r.ts.SyntaxKind.UndefinedKeyword]:void 0}[o.kind],c=ye(i,s),l={number:r.ts.SyntaxKind.NumberKeyword,bigint:r.ts.SyntaxKind.BigIntKeyword,boolean:r.ts.SyntaxKind.BooleanKeyword,string:r.ts.SyntaxKind.StringKeyword,undefined:r.ts.SyntaxKind.UndefinedKeyword,object:r.ts.SyntaxKind.ObjectKeyword};return r.ensureTypeNode(c&&l[c]||or(r,n))},cr=({},{api:e})=>e.makeLiteralType(null),lr=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),ur=({},{api:e})=>e.ensureTypeNode(`Buffer`),dr=(e,{next:t})=>t(e._zod.def.shape.raw),fr={string:Q(`StringKeyword`),number:Q(`NumberKeyword`),bigint:Q(`BigIntKeyword`),boolean:Q(`BooleanKeyword`),any:Q(`AnyKeyword`),undefined:Q(`UndefinedKeyword`),[A]:Q(`StringKeyword`),[j]:Q(`StringKeyword`),never:Q(`NeverKeyword`),void:Q(`UndefinedKeyword`),unknown:Q(`UnknownKeyword`),null:cr,array:Qn,tuple:nr,record:rr,object:Zn,literal:Yn,template_literal:Xn,intersection:ar,union:er,default:$,enum:$n,optional:$,nonoptional:$,nullable:tr,catch:$,pipe:sr,lazy:lr,readonly:$,[k]:ur,[I]:dr},pr=(e,{brandHandling:t,ctx:n})=>qn(e,{rules:{...t,...fr},onMissing:({},{isResponse:e,api:t})=>or(t,e),ctx:n});var mr=class extends Kn{#e=[this.someOfType];#t=new Map;#n=[];#r(e,t){let n=this.#t.get(e)?.name?.text;if(!n){n=`Type${this.#t.size+1}`;let r=this.api.makeLiteralType(null);this.#t.set(e,this.api.makeType(n,r)),this.#t.set(e,this.api.makeType(n,t()))}return this.api.ensureTypeNode(n)}constructor({routing:e,config:t,brandHandling:r,variant:a=`client`,clientClassName:o=`Client`,subscriptionClassName:s=`Subscription`,serverUrl:c=`https://example.com`,noContent:l=i.undefined(),hasHeadMethod:u=!0}){super(c);let d={makeAlias:this.#r.bind(this),api:this.api},f={brandHandling:r,ctx:{...d,isResponse:!1}},p={brandHandling:r,ctx:{...d,isResponse:!0}},m=(e,t,r)=>{let i=D.bind(null,e,t),{isDeprecated:a,inputSchema:o,tags:s}=r,c=`${e} ${t}`,u=this.api.makeType(i(`input`),pr(o,f),{comment:c});this.#e.push(u);let d=H.reduce((t,a)=>{let o=r.getResponses(a),s=n.chain(([t,{schema:n,mimeTypes:r,statusCodes:o}])=>{let s=xe(e,r),u=this.api.makeType(i(a,`variant`,`${t+1}`),pr(s?n:l,p),{comment:c});return this.#e.push(u),o.map(e=>this.api.makeInterfaceProp(e,u.name))},Array.from(o.entries())),u=this.api.makeInterface(i(a,`response`,`variants`),s,{comment:c});return this.#e.push(u),Object.assign(t,{[a]:u})},{});this.paths.add(t);let m=this.api.makeLiteralType(c),h={input:this.api.ensureTypeNode(u.name),positive:this.someOf(d.positive),negative:this.someOf(d.negative),response:this.api.makeUnion([this.api.makeIndexed(this.interfaces.positive,m),this.api.makeIndexed(this.interfaces.negative,m)]),encoded:this.api.f.createIntersectionTypeNode([this.api.ensureTypeNode(d.positive.name),this.api.ensureTypeNode(d.negative.name)])};this.registry.set(c,{isDeprecated:a,store:h}),this.tags.set(c,s)};Ct({routing:e,config:t,onEndpoint:u?gt(m):m}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),a!==`types`&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(o),this.makeSubscriptionClass(s)),this.#n.push(...this.makeUsageStatements(o,s)))}#i(e){return this.#n.length?this.#n.map(t=>typeof t==`string`?t:this.api.printNode(t,e)).join(`
17
+ `))},qt=e=>{e.startupLogo!==!1&&Kt(process.stdout);let t=e.errorHandler||W,n=rt(e.logger)?e.logger:new st(e.logger);n.debug(`Running`,{build:`v26.3.1-beta.1`,env:process.env.NODE_ENV||`development`}),Wt(n);let r=Ht({logger:n,config:e}),i={getLogger:Ut(n),errorHandler:t},a=Lt(i),o=It(i);return{...i,logger:n,notFoundHandler:a,catcher:o,loggingMiddleware:r}},Jt=(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,loggingMiddleware:a}=qt(e);return Ot({app:e.app.use(a),routing:t,getLogger:r,config:e}),{notFoundHandler:i,logger:n}},Yt=async(e,t)=>{let{logger:n,getLogger:r,notFoundHandler:i,catcher:a,loggingMiddleware:o}=qt(e),s=v().disable(`x-powered-by`).set(`query parser`,e.queryParser??`simple`).use(o);if(e.compression){let t=await lt(`compression`);s.use(t(typeof e.compression==`object`?e.compression:void 0))}await e.beforeRouting?.({app:s,getLogger:r}),Ot({app:s,routing:t,getLogger:r,config:e,parsers:{json:[e.jsonParser||v.json()],raw:[e.rawParser||v.raw(),Vt],form:[e.formParser||v.urlencoded()],upload:e.upload?await Bt({config:e,getLogger:r}):[]}}),await e.afterRouting?.({app:s,getLogger:r}),s.use(a,i);let c=[],l=(e,t)=>()=>e.listen(t,()=>n.info(`Listening`,t)),u=[];if(e.http){let t=y.createServer(s);c.push(t),u.push(l(t,e.http.listen))}if(e.https){let t=ee.createServer(e.https.options,s);c.push(t),u.push(l(t,e.https.listen))}return c.length||n.warn(`No servers configured.`),e.gracefulShutdown&&Gt({logger:n,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:s,logger:n,servers:u.map(e=>e())}},Xt=e=>O(e)&&`or`in e,Zt=e=>O(e)&&`and`in e,Qt=e=>!Zt(e)&&!Xt(e),$t=e=>{let t=n.filter(Qt,e),r=n.chain(n.prop(`and`),n.filter(Zt,e)),[i,a]=n.partition(Qt,r),o=n.concat(t,i),s=n.filter(Xt,e);return n.map(n.prop(`or`),n.concat(s,a)).reduce((e,t)=>E(e,n.map(e=>Qt(e)?[e]:e.and,t),([e,t])=>n.concat(e,t)),n.reject(n.isEmpty,[o]))};var en=`a-im.accept.accept-additions.accept-ch.accept-charset.accept-datetime.accept-encoding.accept-features.accept-language.accept-signature.access-control.access-control-request-headers.access-control-request-method.alpn.alt-used.alternates.amp-cache-transform.apply-to-redirect-ref.authentication-control.authentication-info.authorization.available-dictionary.c-ext.c-man.c-opt.c-pep.c-pep-info.cache-control.cal-managed-id.caldav-timezones.capsule-protocol.cert-not-after.cert-not-before.client-cert.client-cert-chain.close.cmcd-object.cmcd-request.cmcd-session.cmcd-status.cmsd-dynamic.cmsd-static.concealed-auth-export.configuration-context.connection.content-digest.content-disposition.content-encoding.content-id.content-language.content-length.content-location.content-md5.content-range.content-script-type.content-type.cookie.cookie2.cross-origin-embedder-policy.cross-origin-embedder-policy-report-only.cross-origin-opener-policy.cross-origin-opener-policy-report-only.cross-origin-resource-policy.cta-common-access-token.dasl.date.dav.default-style.delta-base.deprecation.depth.derived-from.destination.detached-jws.differential-id.dictionary-id.digest.dpop.dpop-nonce.early-data.ediint-features.expect.expect-ct.ext.forwarded.from.getprofile.hobareg.host.http2-settings.if.if-match.if-modified-since.if-none-match.if-range.if-schedule-tag-match.if-unmodified-since.im.include-referred-token-binding-id.isolation.keep-alive.label.last-event-id.link.link-template.lock-token.man.max-forwards.memento-datetime.meter.method-check.method-check-expires.mime-version.negotiate.nel.odata-entityid.odata-isolation.odata-maxversion.odata-version.opt.ordering-type.origin.origin-agent-cluster.oscore.oslc-core-version.overwrite.p3p.pep.pep-info.permissions-policy.pics-label.ping-from.ping-to.position.pragma.prefer.preference-applied.priority.profileobject.protocol.protocol-info.protocol-query.protocol-request.proxy-authorization.proxy-features.proxy-instruction.public.public-key-pins.public-key-pins-report-only.range.redirect-ref.referer.referer-root.referrer-policy.repeatability-client-id.repeatability-first-sent.repeatability-request-id.repeatability-result.replay-nonce.reporting-endpoints.repr-digest.safe.schedule-reply.schedule-tag.sec-fetch-storage-access.sec-gpc.sec-purpose.sec-token-binding.sec-websocket-extensions.sec-websocket-key.sec-websocket-protocol.sec-websocket-version.security-scheme.setprofile.signature.signature-input.slug.soapaction.status-uri.sunset.surrogate-capability.tcn.te.timeout.topic.traceparent.tracestate.trailer.transfer-encoding.ttl.upgrade.urgency.uri.use-as-dictionary.user-agent.variant-vary.via.want-content-digest.want-digest.want-repr-digest.warning.x-content-type-options.x-frame-options`.split(`.`);const tn=`https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString`,nn={integer:0,number:0,string:``,boolean:!1,object:{},null:null,array:[]},rn=e=>e.replace(ue,e=>`{${e.slice(1)}}`),an=({},e)=>{if(e.isResponse)throw new N(`Please use ez.upload() only for input.`,e);return{type:`string`,format:`binary`}},on=({jsonSchema:e})=>({...e,externalDocs:{description:`raw binary data`,url:`https://swagger.io/specification/#working-with-binary-data`}}),sn=({zodSchema:e,jsonSchema:t})=>{if(!T(e,`union`)||!(`discriminator`in e._zod.def))return t;let n=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:n}}},cn=n.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw`no allOf`;return J(e,`throw`)},(e,{jsonSchema:t})=>t),ln=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:hn(t.type)})},Y=e=>e,un=({jsonSchema:{examples:e,description:t}},n)=>{if(n.isResponse)throw new N(`Please use ez.dateOut() for output.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,pattern:`^\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?)?Z?$`,externalDocs:{url:tn}};return e?.length&&(r.examples=e),r},dn=({jsonSchema:{examples:e,description:t}},n)=>{if(!n.isResponse)throw new N(`Please use ez.dateIn() for input.`,n);let r={description:t||`YYYY-MM-DDTHH:mm:ss.sssZ`,type:`string`,format:`date-time`,externalDocs:{url:tn}};return e?.length&&(r.examples=e),r},fn=()=>({type:`string`,format:`bigint`,pattern:`^-?\\d+$`}),pn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest===null?{...t,items:{not:{}}}:t,mn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return nn?.[t]},hn=e=>e===`null`?e:typeof e==`string`?[e,`null`]:e&&[...new Set(e).add(`null`)],gn=({zodSchema:e,jsonSchema:t},n)=>{let r=e._zod.def[n.isResponse?`out`:`in`],i=e._zod.def[n.isResponse?`in`:`out`];if(!T(r,`transform`))return t;let a=Y(Cn(i,{ctx:n}));if(b(a))if(n.isResponse){let e=ye(r,mn(a));if(e&&[`number`,`string`,`boolean`].includes(e))return{...t,type:e}}else{let{type:e,...t}=a;return{...t,format:`${t.format||e} (preprocessed)`}}return t},_n=({jsonSchema:e})=>{if(e.type!==`object`)return e;let t=e;return!t.properties||!(`raw`in t.properties)||!O(t.properties.raw)?e:t.properties.raw},vn=e=>e.length?n.fromPairs(n.zip(n.times(e=>`example${e+1}`,e.length),n.map(n.objOf(`value`),e))):void 0,yn=(e,t)=>t?.includes(e)||e.startsWith(`x-`)||en.includes(e),bn=({path:e,method:t,request:r,inputSources:i,makeRef:a,composition:o,isHeader:s,security:c,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let u=J(r),d=de(e),f=i.includes(`query`),p=i.includes(`params`),m=i.includes(`headers`),h=e=>p&&d.includes(e),g=n.chain(n.filter(e=>e.type===`header`),c??[]).map(({name:e})=>e),_=n=>m&&(s?.(n,t,e)??yn(n,g));return Object.entries(u.properties).reduce((e,[t,r])=>{if(!O(r))return e;let i=h(t)?`path`:_(t)?`header`:f?`query`:void 0;if(!i)return e;let s=Y(r),c=o===`components`?a(r.id||JSON.stringify(r),s,r.id||D(l,t)):s;return e.concat({name:t,in:i,deprecated:r.deprecated,required:u.required?.includes(t)||!1,description:s.description||l,schema:c,examples:vn(b(s)&&s.examples?.length?s.examples:n.pluck(t,u.examples?.filter(n.both(O,n.has(t)))||[]))})},[])},xn={nullable:ln,union:sn,bigint:fn,intersection:cn,tuple:pn,pipe:gn,[A]:un,[j]:dn,[F]:an,[I]:_n,[k]:on},Sn=(e,t,r)=>{let i=[e,t];for(;i.length;){let e=i.shift();if(n.is(Object,e)){if(re(e)&&!e.$ref.startsWith(`#/components`)){let n=t[e.$ref.split(`/`).pop()];n&&(e.$ref=r.makeRef(n.id||n,Y(n),n.id).$ref);continue}i.push(...n.values(e))}n.is(Array,e)&&i.push(...n.values(e))}return e},Cn=(e,{ctx:n,rules:r=xn})=>{let{$defs:a={},properties:o={}}=i.toJSONSchema(i.object({subject:e}),{unrepresentable:`any`,io:n.isResponse?`output`:`input`,override:e=>{let i=t(e.zodSchema),a=r[i&&i in r?i:e.zodSchema._zod.def.type];if(a){let t={...a(e,n)};for(let t in e.jsonSchema)delete e.jsonSchema[t];Object.assign(e.jsonSchema,t)}}});return Sn(O(o.subject)?o.subject:{},a,n)},wn=(e,t)=>{if(re(e))return[e,!1];let r=!1,i=n.map(e=>{let[n,i]=wn(e,t);return r||=i,n}),a=n.omit(t),o={properties:a,examples:n.map(a),required:n.without(t),allOf:i,oneOf:i,anyOf:i},s=n.evolve(o,e);return[s,r||!!s.required?.length]},Tn=({method:e,path:t,schema:r,mimeTypes:i,variant:a,makeRef:o,composition:s,hasMultipleStatusCodes:c,statusCode:l,brandHandling:u,description:d=`${e.toUpperCase()} ${t} ${ve(a)} response ${c?l:``}`.trim()})=>{if(!xe(e,i))return{description:d};let f=Y(Cn(r,{rules:{...u,...xn},ctx:{isResponse:!0,makeRef:o,path:t,method:e}})),p=[];b(f)&&f.examples&&(p.push(...f.examples),delete f.examples);let m={schema:s===`components`?o(r,f,D(d)):f,examples:vn(p)};return{description:d,content:n.fromPairs(n.xprod(i,[m]))}},En=({format:e})=>{let t={type:`http`,scheme:`bearer`};return e&&(t.bearerFormat=e),t},Dn=({name:e},t)=>{let n={type:`apiKey`,in:`query`,name:e};return t?.includes(`body`)&&(t?.includes(`query`)?(n[`x-in-alternative`]=`body`,n.description=`${e} CAN also be supplied within the request body`):(n[`x-in-actual`]=`body`,n.description=`${e} MUST be supplied within the request body instead of query`)),n},On=({name:e})=>({type:`apiKey`,in:`header`,name:e}),kn=({name:e})=>({type:`apiKey`,in:`cookie`,name:e}),An=({url:e})=>({type:`openIdConnect`,openIdConnectUrl:e}),jn=({flows:e={}})=>({type:`oauth2`,flows:n.map(e=>({...e,scopes:e.scopes||{}}),n.reject(n.isNil,e))}),Mn=(e,t=[])=>{let n=e=>e.type===`basic`?{type:`http`,scheme:`basic`}:e.type===`bearer`?En(e):e.type===`input`?Dn(e,t):e.type===`header`?On(e):e.type===`cookie`?kn(e):e.type===`openid`?An(e):jn(e);return e.map(e=>e.map(n))},Nn=(e,t,n)=>e.map(e=>e.reduce((e,r)=>{let i=n(r),a=[`oauth2`,`openIdConnect`].includes(r.type);return Object.assign(e,{[i]:a?t:[]})},{})),Pn=({schema:e,brandHandling:t,makeRef:n,path:r,method:i})=>Cn(e,{rules:{...t,...xn},ctx:{isResponse:!1,makeRef:n,path:r,method:i}}),Fn=({method:e,path:t,schema:r,request:i,mimeType:a,makeRef:o,composition:s,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let[u,d]=wn(Y(i),c),f=[];b(u)&&u.examples&&(f.push(...u.examples),delete u.examples);let p={schema:s===`components`?o(r,u,D(l)):u,examples:vn(f.length?f:J(i).examples?.filter(e=>O(e)&&!Array.isArray(e)).map(n.omit(c))||[])},m={description:l,content:{[a]:p}};return(d||a===x.raw)&&(m.required=!0),m},In=e=>Object.entries(e).reduce((e,[t,n])=>{if(!n)return e;let r={name:t,description:typeof n==`string`?n:n.description};return typeof n==`object`&&n.url&&(r.externalDocs={url:n.url}),e.concat(r)},[]),Ln=e=>e.length<=50?e:e.slice(0,49)+`…`,X=e=>e.length?e.slice():void 0;var Rn=class extends ne{#e=new Map;#t=new Map;#n=new Map;#r(e,t,n){let r=this.#n.get(e);if(!r){let t=n?0:1;do r=`${n??`Schema`}${t?this.#n.size+t:``}`,t++;while(this.rootDoc.components?.schemas?.[r]);this.#n.set(e,r)}return this.addSchema(r,t),{$ref:`#/components/schemas/${r}`}}#i(e,t,n){let r=n||D(t,e),i=this.#t.get(r);if(i===void 0)return this.#t.set(r,1),r;if(n)throw new N(`Duplicated operationId: "${n}"`,{method:t,isResponse:!1,path:e});return i++,this.#t.set(r,i),`${r}${i}`}#a(e){let t=JSON.stringify(e);for(let e in this.rootDoc.components?.securitySchemes||{})if(t===JSON.stringify(this.rootDoc.components?.securitySchemes?.[e]))return e;let n=(this.#e.get(e.type)||0)+1;return this.#e.set(e.type,n),`${e.type.toUpperCase()}_${n}`}constructor({routing:e,config:t,title:r,version:i,serverUrl:a,descriptions:o,brandHandling:s,tags:c,isHeader:l,hasSummaryFromDescription:u=!0,hasHeadMethod:d=!0,composition:f=`inline`}){super(),this.addInfo({title:r,version:i});for(let e of typeof a==`string`?[a]:a)this.addServer({url:e});let p=(e,r,i)=>{let a={path:r,method:e,endpoint:i,composition:f,brandHandling:s,makeRef:this.#r.bind(this)},{description:c,shortDescription:d,scopes:p,inputSchema:m}=i,h=d?Ln(d):u&&c?Ln(c):void 0,g=ge(e,t.inputSources),_=this.#i(r,e,i.getOperationId(e)),v=Pn({...a,schema:m}),y=$t(i.security),ee=bn({...a,inputSources:g,isHeader:l,security:y,request:v,description:o?.requestParameter?.call(null,{method:e,path:r,operationId:_})}),te={};for(let t of H){let n=i.getResponses(t);for(let{mimeTypes:i,schema:s,statusCodes:c}of n)for(let l of c)te[l]=Tn({...a,variant:t,schema:s,mimeTypes:i,statusCode:l,hasMultipleStatusCodes:n.length>1||c.length>1,description:o?.[`${t}Response`]?.call(null,{method:e,path:r,operationId:_,statusCode:l})})}let ne=g.includes(`body`)?Fn({...a,request:v,paramNames:n.pluck(`name`,ee),schema:m,mimeType:x[i.requestType],description:o?.requestBody?.call(null,{method:e,path:r,operationId:_})}):void 0,re=Nn(Mn(y,g),p,e=>{let t=this.#a(e);return this.addSecurityScheme(t,e),t}),b={operationId:_,summary:h,description:c,deprecated:i.isDeprecated||void 0,tags:X(i.tags),parameters:X(ee),requestBody:ne,security:X(re),responses:te};this.addPath(rn(r),{[e]:b})};Ct({routing:e,config:t,onEndpoint:d?gt(p):p}),c&&(this.rootDoc.tags=In(c))}};const zn=e=>ie({...e,headers:{"content-type":x.json,...e?.headers}}),Bn=e=>ae(e),Vn=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(e,n,r){return n===`_getLogs`?()=>t:it(n)?(...e)=>t[n].push(e):Reflect.get(e,n,r)}})},Hn=({requestProps:e,responseOptions:t,configProps:n,loggerProps:r})=>{let i=zn(e),a=Bn({req:i,...t});a.req=t?.req||i,i.res=a;let o=Vn(r);return{requestMock:i,responseMock:a,loggerMock:o,configMock:{cors:!1,logger:o,...n}}},Un=async({endpoint:e,...t})=>{let{requestMock:n,responseMock:r,loggerMock:i,configMock:a}=Hn(t);return await e.execute({request:n,response:r,config:a,logger:i}),{requestMock:n,responseMock:r,loggerMock:i}},Wn=async({middleware:e,ctx:t={},...n})=>{let{requestMock:r,responseMock:i,loggerMock:a,configMock:{inputSources:o,errorHandler:s=W}}=Hn(n),c={request:r,response:i,logger:a,input:_e(r,o),ctx:t};try{return{requestMock:r,responseMock:i,loggerMock:a,output:await e.execute(c)}}catch(e){return await s.execute({...c,error:C(e),output:null}),{requestMock:r,responseMock:i,loggerMock:a,output:{}}}};var Gn=class t{ts;f;exportModifier;asyncModifier;accessModifiers;#e;static#t=/^[A-Za-z_$][A-Za-z0-9_$]*$/;constructor(){this.ts=e(import.meta.url)(`typescript`),this.f=this.ts.factory,this.exportModifier=[this.f.createModifier(this.ts.SyntaxKind.ExportKeyword)],this.asyncModifier=[this.f.createModifier(this.ts.SyntaxKind.AsyncKeyword)],this.accessModifiers={public:[this.f.createModifier(this.ts.SyntaxKind.PublicKeyword)],protectedReadonly:[this.f.createModifier(this.ts.SyntaxKind.ProtectedKeyword),this.f.createModifier(this.ts.SyntaxKind.ReadonlyKeyword)]},this.#e=[this.ts.SyntaxKind.AnyKeyword,this.ts.SyntaxKind.BigIntKeyword,this.ts.SyntaxKind.BooleanKeyword,this.ts.SyntaxKind.NeverKeyword,this.ts.SyntaxKind.NumberKeyword,this.ts.SyntaxKind.ObjectKeyword,this.ts.SyntaxKind.StringKeyword,this.ts.SyntaxKind.SymbolKeyword,this.ts.SyntaxKind.UndefinedKeyword,this.ts.SyntaxKind.UnknownKeyword,this.ts.SyntaxKind.VoidKeyword]}addJsDoc=(e,t)=>this.ts.addSyntheticLeadingComment(e,this.ts.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0);printNode=(e,t)=>{let n=this.ts.createSourceFile(`print.ts`,``,this.ts.ScriptTarget.Latest,!1,this.ts.ScriptKind.TS);return this.ts.createPrinter(t).printNode(this.ts.EmitHint.Unspecified,e,n)};makePropertyIdentifier=e=>typeof e==`string`&&t.#t.test(e)?this.f.createIdentifier(e):this.literally(e);makeTemplate=(e,...t)=>this.f.createTemplateExpression(this.f.createTemplateHead(e),t.map(([e,n=``],r)=>this.f.createTemplateSpan(e,r===t.length-1?this.f.createTemplateTail(n):this.f.createTemplateMiddle(n))));makeParam=(e,{type:t,mod:n,init:r,optional:i}={})=>this.f.createParameterDeclaration(n,void 0,e,i?this.f.createToken(this.ts.SyntaxKind.QuestionToken):void 0,t?this.ensureTypeNode(t):void 0,r);makeParams=e=>Object.entries(e).map(([e,t])=>this.makeParam(e,typeof t==`string`||typeof t==`number`||typeof t==`object`&&`kind`in t?{type:t}:t));makePublicConstructor=(e,t=[])=>this.f.createConstructorDeclaration(this.accessModifiers.public,e,this.f.createBlock(t));ensureTypeNode=(e,t)=>typeof e==`number`?this.f.createKeywordTypeNode(e):typeof e==`string`||this.ts.isIdentifier(e)?this.f.createTypeReferenceNode(e,t&&n.map(this.ensureTypeNode.bind(this),t)):e;makeRecordStringAny=()=>this.ensureTypeNode(`Record`,[this.ts.SyntaxKind.StringKeyword,this.ts.SyntaxKind.AnyKeyword]);makeUnion=e=>{let t=new Map;for(let n of e)t.set(this.isPrimitive(n)?n.kind:n,n);return this.f.createUnionTypeNode(Array.from(t.values()))};makeInterfaceProp=(e,t,{isOptional:r,hasUndefined:i=r,isDeprecated:a,comment:o}={})=>{let s=this.ensureTypeNode(t),c=this.f.createPropertySignature(void 0,this.makePropertyIdentifier(e),r?this.f.createToken(this.ts.SyntaxKind.QuestionToken):void 0,i?this.makeUnion([s,this.ensureTypeNode(this.ts.SyntaxKind.UndefinedKeyword)]):s),l=n.reject(n.isNil,[a?`@deprecated`:void 0,o]);return l.length?this.addJsDoc(c,l.join(` `)):c};makeOneLine=e=>this.ts.setEmitFlags(e,this.ts.EmitFlags.SingleLine);makeDeconstruction=(...e)=>this.f.createArrayBindingPattern(e.map(e=>this.f.createBindingElement(void 0,void 0,e)));makeConst=(e,t,{type:n,expose:r}={})=>this.f.createVariableStatement(r&&this.exportModifier,this.f.createVariableDeclarationList([this.f.createVariableDeclaration(e,void 0,n?this.ensureTypeNode(n):void 0,t)],this.ts.NodeFlags.Const));makePublicLiteralType=(e,t)=>this.makeType(e,this.makeUnion(n.map(this.makeLiteralType.bind(this),t)),{expose:!0});makeType=(e,t,{expose:n,comment:r,params:i}={})=>{let a=this.f.createTypeAliasDeclaration(n?this.exportModifier:void 0,e,i&&this.makeTypeParams(i),t);return r?this.addJsDoc(a,r):a};makePublicProperty=(e,t)=>this.f.createPropertyDeclaration(this.accessModifiers.public,e,void 0,this.ensureTypeNode(t),void 0);makePublicMethod=(e,t,n,{typeParams:r,returns:i}={})=>this.f.createMethodDeclaration(this.accessModifiers.public,void 0,e,void 0,r&&this.makeTypeParams(r),t,i,this.f.createBlock(n));makePublicClass=(e,t,{typeParams:n}={})=>this.f.createClassDeclaration(this.exportModifier,e,n&&this.makeTypeParams(n),void 0,t);makeKeyOf=e=>this.f.createTypeOperatorNode(this.ts.SyntaxKind.KeyOfKeyword,this.ensureTypeNode(e));makePromise=e=>this.ensureTypeNode(Promise.name,[e]);makeInterface=(e,t,{expose:n,comment:r}={})=>{let i=this.f.createInterfaceDeclaration(n?this.exportModifier:void 0,e,void 0,void 0,t);return r?this.addJsDoc(i,r):i};makeTypeParams=e=>(Array.isArray(e)?e.map(e=>n.pair(e,void 0)):Object.entries(e)).map(([e,t])=>{let{type:n,init:r}=typeof t==`object`&&`init`in t?t:{type:t};return this.f.createTypeParameterDeclaration([],e,n?this.ensureTypeNode(n):void 0,r?this.ensureTypeNode(r):void 0)});makeArrowFn=(e,t,{isAsync:r}={})=>this.f.createArrowFunction(r?this.asyncModifier:void 0,void 0,Array.isArray(e)?n.map(this.makeParam.bind(this),e):this.makeParams(e),void 0,void 0,t);makeTernary=(e,t,n)=>this.f.createConditionalExpression(e,this.f.createToken(this.ts.SyntaxKind.QuestionToken),t,this.f.createToken(this.ts.SyntaxKind.ColonToken),n);makeCall=(e,...t)=>(...n)=>this.f.createCallExpression(t.reduce((e,t)=>typeof t==`string`||this.ts.isIdentifier(t)?this.f.createPropertyAccessExpression(e,t):this.f.createElementAccessExpression(e,t),typeof e==`string`?this.f.createIdentifier(e):e),void 0,n);makeNew=(e,...t)=>this.f.createNewExpression(this.f.createIdentifier(e),void 0,t);makeExtract=(e,t)=>this.ensureTypeNode(`Extract`,[e,t]);makeAssignment=(e,t)=>this.f.createExpressionStatement(this.f.createBinaryExpression(e,this.f.createToken(this.ts.SyntaxKind.EqualsToken),t));makeIndexed=(e,t)=>this.f.createIndexedAccessTypeNode(this.ensureTypeNode(e),this.ensureTypeNode(t));makeMaybeAsync=e=>this.makeUnion([this.ensureTypeNode(e),this.makePromise(e)]);makeFnType=(e,t)=>this.f.createFunctionTypeNode(void 0,this.makeParams(e),this.ensureTypeNode(t));literally=e=>typeof e==`number`?this.f.createNumericLiteral(e):typeof e==`bigint`?this.f.createBigIntLiteral(e.toString()):typeof e==`boolean`?e?this.f.createTrue():this.f.createFalse():e===null?this.f.createNull():this.f.createStringLiteral(e);makeLiteralType=e=>this.f.createLiteralTypeNode(this.literally(e));isPrimitive=e=>this.#e.includes(e.kind)};const Z=e=>e;var Kn=class{api=new Gn;paths=new Set;tags=new Map;registry=new Map;#e={pathType:this.api.f.createIdentifier(`Path`),implementationType:this.api.f.createIdentifier(`Implementation`),keyParameter:this.api.f.createIdentifier(`key`),pathParameter:this.api.f.createIdentifier(`path`),paramsArgument:this.api.f.createIdentifier(`params`),ctxArgument:this.api.f.createIdentifier(`ctx`),methodParameter:this.api.f.createIdentifier(`method`),requestParameter:this.api.f.createIdentifier(`request`),eventParameter:this.api.f.createIdentifier(`event`),dataParameter:this.api.f.createIdentifier(`data`),handlerParameter:this.api.f.createIdentifier(`handler`),msgParameter:this.api.f.createIdentifier(`msg`),parseRequestFn:this.api.f.createIdentifier(`parseRequest`),substituteFn:this.api.f.createIdentifier(`substitute`),provideMethod:this.api.f.createIdentifier(`provide`),onMethod:this.api.f.createIdentifier(`on`),implementationArgument:this.api.f.createIdentifier(`implementation`),hasBodyConst:this.api.f.createIdentifier(`hasBody`),undefinedValue:this.api.f.createIdentifier(`undefined`),responseConst:this.api.f.createIdentifier(`response`),restConst:this.api.f.createIdentifier(`rest`),searchParamsConst:this.api.f.createIdentifier(`searchParams`),defaultImplementationConst:this.api.f.createIdentifier(`defaultImplementation`),clientConst:this.api.f.createIdentifier(`client`),contentTypeConst:this.api.f.createIdentifier(`contentType`),isJsonConst:this.api.f.createIdentifier(`isJSON`),sourceProp:this.api.f.createIdentifier(`source`)};interfaces={input:this.api.f.createIdentifier(`Input`),positive:this.api.f.createIdentifier(`PositiveResponse`),negative:this.api.f.createIdentifier(`NegativeResponse`),encoded:this.api.f.createIdentifier(`EncodedResponse`),response:this.api.f.createIdentifier(`Response`)};methodType=this.api.makePublicLiteralType(`Method`,ce);someOfType=this.api.makeType(`SomeOf`,this.api.makeIndexed(`T`,this.api.makeKeyOf(`T`)),{params:[`T`]});requestType=this.api.makeType(`Request`,this.api.makeKeyOf(this.interfaces.input),{expose:!0});constructor(e){this.serverUrl=e}someOf=({name:e})=>this.api.ensureTypeNode(this.someOfType.name,[e]);makePathType=()=>this.api.makePublicLiteralType(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(e=>this.api.makeInterface(this.interfaces[e],Array.from(this.registry).map(([t,{store:n,isDeprecated:r}])=>this.api.makeInterfaceProp(t,n[e],{isDeprecated:r})),{expose:!0}));makeEndpointTags=()=>this.api.makeConst(`endpointTags`,this.api.f.createObjectLiteralExpression(Array.from(this.tags).map(([e,t])=>this.api.f.createPropertyAssignment(this.api.makePropertyIdentifier(e),this.api.f.createArrayLiteralExpression(n.map(this.api.literally.bind(this.api),t))))),{expose:!0});makeImplementationType=()=>this.api.makeType(this.#e.implementationType,this.api.makeFnType({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:this.api.ts.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:this.api.makeRecordStringAny(),[this.#e.ctxArgument.text]:{optional:!0,type:`T`}},this.api.makePromise(this.api.ts.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:this.api.ts.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>this.api.makeConst(this.#e.parseRequestFn,this.api.makeArrowFn({[this.#e.requestParameter.text]:this.api.ts.SyntaxKind.StringKeyword},this.api.f.createAsExpression(this.api.makeCall(this.#e.requestParameter,Z(`split`))(this.api.f.createRegularExpressionLiteral(`/ (.+)/`),this.api.literally(2)),this.api.f.createTupleTypeNode([this.api.ensureTypeNode(this.methodType.name),this.api.ensureTypeNode(this.#e.pathType)]))));makeSubstituteFn=()=>this.api.makeConst(this.#e.substituteFn,this.api.makeArrowFn({[this.#e.pathParameter.text]:this.api.ts.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:this.api.makeRecordStringAny()},this.api.f.createBlock([this.api.makeConst(this.#e.restConst,this.api.f.createObjectLiteralExpression([this.api.f.createSpreadAssignment(this.#e.paramsArgument)])),this.api.f.createForInStatement(this.api.f.createVariableDeclarationList([this.api.f.createVariableDeclaration(this.#e.keyParameter)],this.api.ts.NodeFlags.Const),this.#e.paramsArgument,this.api.f.createBlock([this.api.makeAssignment(this.#e.pathParameter,this.api.makeCall(this.#e.pathParameter,Z(`replace`))(this.api.makeTemplate(`:`,[this.#e.keyParameter]),this.api.makeArrowFn([],this.api.f.createBlock([this.api.f.createExpressionStatement(this.api.f.createDeleteExpression(this.api.f.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),this.api.f.createReturnStatement(this.api.f.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),this.api.f.createReturnStatement(this.api.f.createAsExpression(this.api.f.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),this.api.ensureTypeNode(`const`)))])));#t=()=>this.api.makePublicMethod(this.#e.provideMethod,this.api.makeParams({[this.#e.requestParameter.text]:`K`,[this.#e.paramsArgument.text]:this.api.makeIndexed(this.interfaces.input,`K`),[this.#e.ctxArgument.text]:{optional:!0,type:`T`}}),[this.api.makeConst(this.api.makeDeconstruction(this.#e.methodParameter,this.#e.pathParameter),this.api.makeCall(this.#e.parseRequestFn)(this.#e.requestParameter)),this.api.f.createReturnStatement(this.api.makeCall(this.api.f.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,this.api.f.createSpreadElement(this.api.makeCall(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:this.api.makePromise(this.api.makeIndexed(this.interfaces.response,`K`))});makeClientClass=e=>this.api.makePublicClass(e,[this.api.makePublicConstructor([this.api.makeParam(this.#e.implementationArgument,{type:this.api.ensureTypeNode(this.#e.implementationType,[`T`]),mod:this.api.accessModifiers.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:[`T`]});#n=e=>this.api.makeTemplate(`?`,[this.api.makeNew(URLSearchParams.name,e)]);#r=()=>this.api.makeNew(URL.name,this.api.makeTemplate(``,[this.#e.pathParameter],[this.#e.searchParamsConst]),this.api.literally(this.serverUrl));makeDefaultImplementation=()=>{let e=this.api.f.createPropertyAssignment(Z(`method`),this.api.makeCall(this.#e.methodParameter,Z(`toUpperCase`))()),t=this.api.f.createPropertyAssignment(Z(`headers`),this.api.makeTernary(this.#e.hasBodyConst,this.api.f.createObjectLiteralExpression([this.api.f.createPropertyAssignment(this.api.literally(`Content-Type`),this.api.literally(x.json))]),this.#e.undefinedValue)),n=this.api.f.createPropertyAssignment(Z(`body`),this.api.makeTernary(this.#e.hasBodyConst,this.api.makeCall(JSON[Symbol.toStringTag],Z(`stringify`))(this.#e.paramsArgument),this.#e.undefinedValue)),r=this.api.makeConst(this.#e.responseConst,this.api.f.createAwaitExpression(this.api.makeCall(fetch.name)(this.#r(),this.api.f.createObjectLiteralExpression([e,t,n])))),i=this.api.makeConst(this.#e.hasBodyConst,this.api.f.createLogicalNot(this.api.makeCall(this.api.f.createArrayLiteralExpression([this.api.literally(`get`),this.api.literally(`head`),this.api.literally(`delete`)]),Z(`includes`))(this.#e.methodParameter))),a=this.api.makeConst(this.#e.searchParamsConst,this.api.makeTernary(this.#e.hasBodyConst,this.api.literally(``),this.#n(this.#e.paramsArgument))),o=this.api.makeConst(this.#e.contentTypeConst,this.api.makeCall(this.#e.responseConst,Z(`headers`),Z(`get`))(this.api.literally(`content-type`))),s=this.api.f.createIfStatement(this.api.f.createPrefixUnaryExpression(this.api.ts.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),this.api.f.createReturnStatement()),c=this.api.makeConst(this.#e.isJsonConst,this.api.makeCall(this.#e.contentTypeConst,Z(`startsWith`))(this.api.literally(x.json))),l=this.api.f.createReturnStatement(this.api.makeCall(this.#e.responseConst,this.api.makeTernary(this.#e.isJsonConst,this.api.literally(Z(`json`)),this.api.literally(Z(`text`))))());return this.api.makeConst(this.#e.defaultImplementationConst,this.api.makeArrowFn([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],this.api.f.createBlock([i,a,r,o,s,c,l]),{isAsync:!0}),{type:this.#e.implementationType})};#i=()=>this.api.makePublicConstructor(this.api.makeParams({request:`K`,params:this.api.makeIndexed(this.interfaces.input,`K`)}),[this.api.makeConst(this.api.makeDeconstruction(this.#e.pathParameter,this.#e.restConst),this.api.makeCall(this.#e.substituteFn)(this.api.f.createElementAccessExpression(this.api.makeCall(this.#e.parseRequestFn)(this.#e.requestParameter),this.api.literally(1)),this.#e.paramsArgument)),this.api.makeConst(this.#e.searchParamsConst,this.#n(this.#e.restConst)),this.api.makeAssignment(this.api.f.createPropertyAccessExpression(this.api.f.createThis(),this.#e.sourceProp),this.api.makeNew(`EventSource`,this.#r()))]);#a=e=>this.api.f.createTypeLiteralNode([this.api.makeInterfaceProp(Z(`event`),e)]);#o=()=>this.api.makePublicMethod(this.#e.onMethod,this.api.makeParams({[this.#e.eventParameter.text]:`E`,[this.#e.handlerParameter.text]:this.api.makeFnType({[this.#e.dataParameter.text]:this.api.makeIndexed(this.api.makeExtract(`R`,this.api.makeOneLine(this.#a(`E`))),this.api.makeLiteralType(Z(`data`)))},this.api.makeMaybeAsync(this.api.ts.SyntaxKind.VoidKeyword))}),[this.api.f.createExpressionStatement(this.api.makeCall(this.api.f.createThis(),this.#e.sourceProp,Z(`addEventListener`))(this.#e.eventParameter,this.api.makeArrowFn([this.#e.msgParameter],this.api.makeCall(this.#e.handlerParameter)(this.api.makeCall(JSON[Symbol.toStringTag],Z(`parse`))(this.api.f.createPropertyAccessExpression(this.api.f.createParenthesizedExpression(this.api.f.createAsExpression(this.#e.msgParameter,this.api.ensureTypeNode(MessageEvent.name))),Z(`data`))))))),this.api.f.createReturnStatement(this.api.f.createThis())],{typeParams:{E:this.api.makeIndexed(`R`,this.api.makeLiteralType(Z(`event`)))}});makeSubscriptionClass=e=>this.api.makePublicClass(e,[this.api.makePublicProperty(this.#e.sourceProp,`EventSource`),this.#i(),this.#o()],{typeParams:{K:this.api.makeExtract(this.requestType.name,this.api.f.createTemplateLiteralType(this.api.f.createTemplateHead(`get `),[this.api.f.createTemplateLiteralTypeSpan(this.api.ensureTypeNode(this.api.ts.SyntaxKind.StringKeyword),this.api.f.createTemplateTail(``))])),R:this.api.makeExtract(this.api.makeIndexed(this.interfaces.positive,`K`),this.api.makeOneLine(this.#a(this.api.ts.SyntaxKind.StringKeyword)))}});makeUsageStatements=(e,t)=>[this.api.makeConst(this.#e.clientConst,this.api.makeNew(e)),this.api.makeCall(this.#e.clientConst,this.#e.provideMethod)(this.api.literally(`get /v1/user/retrieve`),this.api.f.createObjectLiteralExpression([this.api.f.createPropertyAssignment(`id`,this.api.literally(`10`))])),this.api.makeCall(this.api.makeNew(t,this.api.literally(`get /v1/events/stream`),this.api.f.createObjectLiteralExpression()),this.#e.onMethod)(this.api.literally(`time`),this.api.makeArrowFn([`time`],this.api.f.createBlock([])))]};const qn=(e,{onEach:n,rules:r,onMissing:i,ctx:a={}})=>{let o=t(e),s=o&&o in r?r[o]:r[e._zod.def.type],c=e=>qn(e,{ctx:a,onEach:n,rules:r,onMissing:i}),l=s?s(e,{...a,next:c}):i(e,a),u=n&&n(e,{prev:l,...a});return u?{...l,...u}:l},Jn={name:n.path([`name`,`text`]),type:n.path([`type`]),optional:n.path([`questionToken`])},Yn=({_zod:{def:e}},{api:t})=>{let n=e.values.map(e=>e===void 0?t.ensureTypeNode(t.ts.SyntaxKind.UndefinedKeyword):t.makeLiteralType(e));return n.length===1?n[0]:t.makeUnion(n)},Xn=({_zod:{def:e}},{next:t,api:n})=>{let r=[...e.parts],i=()=>{let e=``;for(;r.length;){let t=r.shift();if(T(t)){r.unshift(t);break}e+=t??``}return e},a=n.f.createTemplateHead(i()),o=[];for(;r.length;){let e=t(r.shift()),a=i(),s=r.length?n.f.createTemplateMiddle:n.f.createTemplateTail;o.push(n.f.createTemplateLiteralTypeSpan(e,s(a)))}return o.length?n.f.createTemplateLiteralType(a,o):n.makeLiteralType(a.text)},Zn=(e,{isResponse:t,next:n,makeAlias:a,api:o})=>{let s=()=>{let a=Object.entries(e._zod.def.shape).map(([e,a])=>{let{description:s,deprecated:c}=r.get(a)||{},l=(t?a._zod.optout:a._zod.optin)===`optional`,u=l&&!(a instanceof i.core.$ZodExactOptional);return o.makeInterfaceProp(e,n(a),{comment:s,isDeprecated:c,isOptional:l,hasUndefined:u})});return o.f.createTypeLiteralNode(a)};return Le(e,{io:t?`output`:`input`})?a(e,s):s()},Qn=({_zod:{def:e}},{next:t,api:n})=>n.f.createArrayTypeNode(t(e.element)),$n=({_zod:{def:e}},{api:t})=>t.makeUnion(Object.values(e.entries).map(t.makeLiteralType.bind(t))),er=({_zod:{def:e}},{next:t,api:n})=>n.makeUnion(e.options.map(t)),tr=({_zod:{def:e}},{next:t,api:n})=>n.makeUnion([t(e.innerType),n.makeLiteralType(null)]),nr=({_zod:{def:e}},{next:t,api:n})=>n.f.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:n.f.createRestTypeNode(t(e.rest)))),rr=({_zod:{def:e}},{next:t,api:n})=>{let[r,i]=[e.keyType,e.valueType].map(t),a=n.ensureTypeNode(`Record`,[r,i]);return e.mode===`loose`?n.f.createIntersectionTypeNode([a,n.ensureTypeNode(`Record`,[`PropertyKey`,i])]):a},ir=n.tryCatch((e,t)=>{if(!t.every(e.ts.isTypeLiteralNode))throw Error(`Not objects`);let r=n.chain(n.prop(`members`),t),i=n.uniqWith((...e)=>{if(!n.eqBy(Jn.name,...e))return!1;if(n.both(n.eqBy(Jn.type),n.eqBy(Jn.optional))(...e))return!0;throw Error(`Has conflicting prop`)},r);return e.f.createTypeLiteralNode(i)},(e,t,n)=>t.f.createIntersectionTypeNode(n)),ar=({_zod:{def:e}},{next:t,api:n})=>ir(n,[e.left,e.right].map(t)),Q=e=>({},{api:t})=>t.ensureTypeNode(t.ts.SyntaxKind[e]),$=({_zod:{def:e}},{next:t})=>t(e.innerType),or=(e,t)=>e.ensureTypeNode(t?e.ts.SyntaxKind.UnknownKeyword:e.ts.SyntaxKind.AnyKeyword),sr=({_zod:{def:e}},{next:t,isResponse:n,api:r})=>{let i=e[n?`out`:`in`],a=e[n?`in`:`out`];if(!T(i,`transform`))return t(i);let o=t(a),s={[r.ts.SyntaxKind.AnyKeyword]:``,[r.ts.SyntaxKind.BigIntKeyword]:BigInt(0),[r.ts.SyntaxKind.BooleanKeyword]:!1,[r.ts.SyntaxKind.NumberKeyword]:0,[r.ts.SyntaxKind.ObjectKeyword]:{},[r.ts.SyntaxKind.StringKeyword]:``,[r.ts.SyntaxKind.UndefinedKeyword]:void 0}[o.kind],c=ye(i,s),l={number:r.ts.SyntaxKind.NumberKeyword,bigint:r.ts.SyntaxKind.BigIntKeyword,boolean:r.ts.SyntaxKind.BooleanKeyword,string:r.ts.SyntaxKind.StringKeyword,undefined:r.ts.SyntaxKind.UndefinedKeyword,object:r.ts.SyntaxKind.ObjectKeyword};return r.ensureTypeNode(c&&l[c]||or(r,n))},cr=({},{api:e})=>e.makeLiteralType(null),lr=({_zod:{def:e}},{makeAlias:t,next:n})=>t(e.getter,()=>n(e.getter())),ur=({},{api:e})=>e.ensureTypeNode(`Buffer`),dr=(e,{next:t})=>t(e._zod.def.shape.raw),fr={string:Q(`StringKeyword`),number:Q(`NumberKeyword`),bigint:Q(`BigIntKeyword`),boolean:Q(`BooleanKeyword`),any:Q(`AnyKeyword`),undefined:Q(`UndefinedKeyword`),[A]:Q(`StringKeyword`),[j]:Q(`StringKeyword`),never:Q(`NeverKeyword`),void:Q(`UndefinedKeyword`),unknown:Q(`UnknownKeyword`),null:cr,array:Qn,tuple:nr,record:rr,object:Zn,literal:Yn,template_literal:Xn,intersection:ar,union:er,default:$,enum:$n,optional:$,nonoptional:$,nullable:tr,catch:$,pipe:sr,lazy:lr,readonly:$,[k]:ur,[I]:dr},pr=(e,{brandHandling:t,ctx:n})=>qn(e,{rules:{...t,...fr},onMissing:({},{isResponse:e,api:t})=>or(t,e),ctx:n});var mr=class extends Kn{#e=[this.someOfType];#t=new Map;#n=[];#r(e,t){let n=this.#t.get(e)?.name?.text;if(!n){n=`Type${this.#t.size+1}`;let r=this.api.makeLiteralType(null);this.#t.set(e,this.api.makeType(n,r)),this.#t.set(e,this.api.makeType(n,t()))}return this.api.ensureTypeNode(n)}constructor({routing:e,config:t,brandHandling:r,variant:a=`client`,clientClassName:o=`Client`,subscriptionClassName:s=`Subscription`,serverUrl:c=`https://example.com`,noContent:l=i.undefined(),hasHeadMethod:u=!0}){super(c);let d={makeAlias:this.#r.bind(this),api:this.api},f={brandHandling:r,ctx:{...d,isResponse:!1}},p={brandHandling:r,ctx:{...d,isResponse:!0}},m=(e,t,r)=>{let i=D.bind(null,e,t),{isDeprecated:a,inputSchema:o,tags:s}=r,c=`${e} ${t}`,u=this.api.makeType(i(`input`),pr(o,f),{comment:c});this.#e.push(u);let d=H.reduce((t,a)=>{let o=r.getResponses(a),s=n.chain(([t,{schema:n,mimeTypes:r,statusCodes:o}])=>{let s=xe(e,r),u=this.api.makeType(i(a,`variant`,`${t+1}`),pr(s?n:l,p),{comment:c});return this.#e.push(u),o.map(e=>this.api.makeInterfaceProp(e,u.name))},Array.from(o.entries())),u=this.api.makeInterface(i(a,`response`,`variants`),s,{comment:c});return this.#e.push(u),Object.assign(t,{[a]:u})},{});this.paths.add(t);let m=this.api.makeLiteralType(c),h={input:this.api.ensureTypeNode(u.name),positive:this.someOf(d.positive),negative:this.someOf(d.negative),response:this.api.makeUnion([this.api.makeIndexed(this.interfaces.positive,m),this.api.makeIndexed(this.interfaces.negative,m)]),encoded:this.api.f.createIntersectionTypeNode([this.api.ensureTypeNode(d.positive.name),this.api.ensureTypeNode(d.negative.name)])};this.registry.set(c,{isDeprecated:a,store:h}),this.tags.set(c,s)};Ct({routing:e,config:t,onEndpoint:u?gt(m):m}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),a!==`types`&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(o),this.makeSubscriptionClass(s)),this.#n.push(...this.makeUsageStatements(o,s)))}#i(e){return this.#n.length?this.#n.map(t=>typeof t==`string`?t:this.api.printNode(t,e)).join(`
18
18
  `):void 0}print(e){let t=this.#i(e),n=t&&this.api.ts.addSyntheticLeadingComment(this.api.ts.addSyntheticLeadingComment(this.api.f.createEmptyStatement(),this.api.ts.SyntaxKind.SingleLineCommentTrivia,` Usage example:`),this.api.ts.SyntaxKind.MultiLineCommentTrivia,`\n${t}`);return this.#e.concat(n||[]).map((t,n)=>this.api.printNode(t,n<this.#e.length?e:{...e,omitTrailingSemicolon:!0})).join(`
19
19
 
20
20
  `)}async printFormatted({printerOptions:e,format:t}={}){let n=t;if(!n)try{let e=(await lt(`prettier`)).format;n=t=>e(t,{filepath:`client.ts`})}catch{}let r=this.#i(e);this.#n=r&&n?[await n(r)]:this.#n;let i=this.print(e);return n?n(i):i}};const hr=(e,t)=>i.object({data:t,event:i.literal(e),id:i.string().optional(),retry:i.int().positive().optional()}),gr=(e,t,n)=>hr(String(t),e[t]).transform(e=>[`event: ${e.event}`,`data: ${JSON.stringify(e.data)}`,``,``].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "26.2.0",
3
+ "version": "26.3.1-beta.1",
4
4
  "description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -34,7 +34,7 @@
34
34
  "node": "^20.19.0 || ^22.12.0 || ^24.0.0"
35
35
  },
36
36
  "dependencies": {
37
- "ansis": "^4.1.0",
37
+ "ansis": "^4.2.0",
38
38
  "node-mocks-http": "^1.17.2",
39
39
  "openapi3-ts": "^4.5.0",
40
40
  "ramda": "^0.32.0",
@@ -76,23 +76,23 @@
76
76
  "@types/compression": "^1.8.1",
77
77
  "@types/cors": "^2.8.19",
78
78
  "@types/depd": "^1.1.37",
79
- "@types/express": "^5.0.3",
79
+ "@types/express": "^5.0.6",
80
80
  "@types/express-fileupload": "^1.5.1",
81
81
  "@types/http-errors": "^2.0.5",
82
- "@types/node-forge": "^1.3.11",
83
- "@types/ramda": "^0.31.0",
82
+ "@types/node-forge": "^1.3.14",
83
+ "@types/ramda": "^0.31.1",
84
84
  "camelize-ts": "^3.0.0",
85
- "compression": "^1.8.0",
85
+ "compression": "^1.8.1",
86
86
  "cors": "^2.8.5",
87
87
  "depd": "^2.0.0",
88
- "express": "^5.2.0",
89
- "express-fileupload": "^1.5.1",
88
+ "express": "^5.2.1",
89
+ "express-fileupload": "^1.5.2",
90
90
  "http-errors": "^2.0.1",
91
- "node-forge": "^1.3.2",
91
+ "node-forge": "^1.3.3",
92
92
  "snakify-ts": "^2.3.0",
93
- "typescript": "^5.9.2",
94
- "undici": "^7.10.0",
95
- "zod": "^4.2.0"
93
+ "typescript": "^5.9.3",
94
+ "undici": "^7.16.0",
95
+ "zod": "^4.3.4"
96
96
  },
97
97
  "keywords": [
98
98
  "nodejs",