express-zod-api 20.14.0 → 20.14.2

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,18 @@
2
2
 
3
3
  ## Version 20
4
4
 
5
+ ### v20.14.2
6
+
7
+ - Documentation: promoting Express 5 as the recommended version for new projects;
8
+ - Minor refactoring: response variant constraints, inverted definition of `AbstractLogger` type;
9
+ - There is now an opportunity to support the project with sponsorship: https://github.com/sponsors/RobinTail
10
+
11
+ ### v20.14.1
12
+
13
+ - `node-mocks-http` version is `^1.16.1`:
14
+ - This deduplicates the `@types/express` dependency to the version installed in your project;
15
+ - This fix is an addition to the support of Express 5 (v20.10.0) and its types (v20.14.0).
16
+
5
17
  ### v20.14.0
6
18
 
7
19
  - Enabling usage of recently released `@types/express@^5.0.0`:
@@ -57,7 +69,7 @@ createConfig({
57
69
 
58
70
  ### v20.9.0
59
71
 
60
- - `openapi3-ts` vesion is 4.4.0:
72
+ - `openapi3-ts` version is 4.4.0:
61
73
  - Feat: `Documentation::getSpecAsYaml()` accepts the same options as `yaml.stringify`.
62
74
 
63
75
  ### v20.8.0
@@ -605,7 +617,7 @@ const resultHandlerWithCleanup = createResultHandler({
605
617
 
606
618
  ### v18.6.0
607
619
 
608
- - Feat: Supporting async functon as an argument for `EndpointsFactory::addOptions()`:
620
+ - Feat: Supporting async function as an argument for `EndpointsFactory::addOptions()`:
609
621
  - I realized that it does not make sense for `.addOptions` just to proxy the static data;
610
622
  - In case your options are static you can just `import` the corresponding `const` instead;
611
623
  - Static options are deprecated and its support will be removed in v19.
@@ -637,7 +649,7 @@ const endpointsFactory = defaultEndpointsFactory.addOptions(async () => {
637
649
  - ~~`withMeta()`~~ was introduced in version 2.10.0, because I didn't want to alter Zod's prototypes;
638
650
  - However, the [new information](https://github.com/colinhacks/zod/pull/3445#issuecomment-2091463120) arrived
639
651
  recently from the author of Zod on that matter;
640
- - It turned out that altering Zod's prototypes is exatly the recommended approach for extending its functionality;
652
+ - It turned out that altering Zod's prototypes is exactly the recommended approach for extending its functionality;
641
653
  - Therefore `express-zod-api` from now on acts as a plugin for Zod, adding the `.example()` and `.label()` methods to
642
654
  its prototypes that were previously available only after wrapping the schema in ~~`withMeta()`~~.
643
655
 
@@ -970,7 +982,7 @@ export const config = createConfig({
970
982
  - Refinment methods of `ez.file()` removed;
971
983
  - Minimum version of `vitest` supported is 1.0.4.
972
984
  - How to migrate confidently:
973
- - If you're using refinment methods of `ez.file()`:
985
+ - If you're using refinement methods of `ez.file()`:
974
986
  - Replace ~~`ez.file().string()`~~ to `ez.file("string")`;
975
987
  - Replace ~~`ez.file().buffer()`~~ to `ez.file("buffer")`;
976
988
  - Replace ~~`ez.file().base64()`~~ to `ez.file("base64")`;
@@ -1018,7 +1030,7 @@ after:
1018
1030
  - This version relies on `inspect()` method of `node:util` instead, for serializing objects in all cases.
1019
1031
  - When the `level` is set to `debug` the inspected objects will be pretty printed.
1020
1032
  - When the `level` is set to `warn` the inspected objects will be serialized in one line.
1021
- - Additionaly, new option `depth` added to `SimplifiedWinstonConfig` that can be `number | null` being `2` by default.
1033
+ - Additionally, new option `depth` added to `SimplifiedWinstonConfig` that can be `number | null` being `2` by default.
1022
1034
  - The option controls how deeply the objects should be inspected, serialized and printed.
1023
1035
  - It can be set to `null` or `Infinity` for unlimited depth.
1024
1036
 
@@ -1347,7 +1359,7 @@ securitySchemes:
1347
1359
  - Switching to [OpenAPI 3.1](https://swagger.io/specification/) for generating better Documentation for your API.
1348
1360
  - Consider [the new UI](https://editor-next.swagger.io/) for exploring the produced documentation.
1349
1361
  - Improved way of configuring descriptions and naming of the generated documentation components:
1350
- - Intoroducing the new option `descriptions` holding several formatting functions.
1362
+ - Introducing the new option `descriptions` holding several formatting functions.
1351
1363
  - Ability to generate formatted typescript client using the new async method `printFormatted` of the `Integration`
1352
1364
  class when the `prettier` package is installed (detects automatically).
1353
1365
  - Ability to supply your own typescript formatting function into that new method.
@@ -1432,7 +1444,7 @@ operationId:
1432
1444
  - Transitioned from an exclusive approach to the inclusive one:
1433
1445
  - Introducing the list of `files` included into the distribution (instead of ignoring redundant ones).
1434
1446
  - Stable testing environment:
1435
- - Inclusive, stable and extendible `tsconfig.json` files;
1447
+ - Inclusive, stable and extensible `tsconfig.json` files;
1436
1448
  - Stable `package.json` for integration, ESM and compatibility tests;
1437
1449
  - Dedicated environment for Issue #952 test.
1438
1450
  - Simplified development commands.
@@ -1526,7 +1538,7 @@ logger.info("Payload", {});
1526
1538
 
1527
1539
  ### v14.2.4
1528
1540
 
1529
- - Fixed internal logging format when primivite are supplied as a second argument to the logger methods.
1541
+ - Fixed internal logging format when primitive are supplied as a second argument to the logger methods.
1530
1542
 
1531
1543
  ```typescript
1532
1544
  logger.info("Listening", 8090);
@@ -1690,7 +1702,7 @@ defaultEndpointsFactory.build({
1690
1702
  - Featuring the ability to customize the `operationId` in the generated documentation.
1691
1703
  - Using the new property of `EndpointsFactory::build()` method you can now override the value of the
1692
1704
  corresponding `operationId` of the endpoint in generated documentation.
1693
- - When using this feature, you must ensure the uniqness of the IDs you specified across your API endpoints.
1705
+ - When using this feature, you must ensure the uniqueness of the IDs you specified across your API endpoints.
1694
1706
  - The feature is implemented by [@john-schmitz](https://github.com/john-schmitz).
1695
1707
 
1696
1708
  ```typescript
@@ -1741,7 +1753,7 @@ defaultEndpointsFactory.build({
1741
1753
  - Instead of `MiddlewareDefinition` type use `createMiddleware()` method.
1742
1754
  - Instead of `ResultHandlerDefinition` type use `createResultHandler()` method.
1743
1755
  - Instead of the mentioned security types use the `security` property of the `createMiddleware()` argument.
1744
- - The issue 1182 is the continuation of the issue 952 "Infussicient exports" (for consumer's declaration).
1756
+ - The issue 1182 is the continuation of the issue 952 "Insufficient exports" (for consumer's declaration).
1745
1757
  - Found and reported by [@bobgubko](https://github.com/bobgubko)
1746
1758
 
1747
1759
  ### v12.0.2
package/README.md CHANGED
@@ -13,18 +13,9 @@
13
13
 
14
14
  Start your API server with I/O schema validation and custom middlewares in minutes.
15
15
 
16
- 1. [Why and what is it for](#why-and-what-is-it-for)
16
+ 1. [Overview](#overview)
17
17
  2. [How it works](#how-it-works)
18
- 1. [Technologies](#technologies)
19
- 2. [Concept](#concept)
20
- 3. [Quick start](#quick-start) — Fast Track
21
- 1. [Installation](#installation)
22
- 2. [Set up config](#set-up-config)
23
- 3. [Create an endpoints factory](#create-an-endpoints-factory)
24
- 4. [Create your first endpoint](#create-your-first-endpoint)
25
- 5. [Set up routing](#set-up-routing)
26
- 6. [Create your server](#create-your-server)
27
- 7. [Try it](#try-it)
18
+ 3. [Quick start](#quick-start) — **Fast Track**
28
19
  4. [Basic features](#basic-features)
29
20
  1. [Middlewares](#middlewares)
30
21
  2. [Options](#options)
@@ -71,7 +62,7 @@ Start your API server with I/O schema validation and custom middlewares in minut
71
62
 
72
63
  You can find the release notes and migration guides in [Changelog](CHANGELOG.md).
73
64
 
74
- # Why and what is it for
65
+ # Overview
75
66
 
76
67
  I made this library because of the often repetitive tasks of starting a web server APIs with the need to validate input
77
68
  data. It integrates and provides the capabilities of popular web server, logging, validation and documenting solutions.
@@ -88,8 +79,49 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
88
79
  field names when you implement the client for your API.
89
80
  - You can generate your API documentation in OpenAPI 3.1 and JSON Schema compatible format.
90
81
 
82
+ ## Contributors
83
+
84
+ These people contributed to the improvement of the library by reporting bugs, making changes and suggesting ideas:
85
+
86
+ [<img src="https://github.com/rottmann.png" alt="@rottmann" width="50px" />](https://github.com/rottmann)
87
+ [<img src="https://github.com/boarush.png" alt="@boarush" width="50px" />](https://github.com/boarush)
88
+ [<img src="https://github.com/daniel-white.png" alt="@daniel-white" width="50px" />](https://github.com/daniel-white)
89
+ [<img src="https://github.com/kotsmile.png" alt="@kotsmile" width="50px" />](https://github.com/kotsmile)
90
+ [<img src="https://github.com/arlyon.png" alt="@arlyon" width="50px" />](https://github.com/arlyon)
91
+ [<img src="https://github.com/elee1766.png" alt="@elee1766" width="50px" />](https://github.com/elee1766)
92
+ [<img src="https://github.com/danclaytondev.png" alt="@danclaytondev" width="50px" />](https://github.com/danclaytondev)
93
+ [<img src="https://github.com/huyhoang160593.png" alt="@huyhoang160593" width="50px" />](https://github.com/huyhoang160593)
94
+ [<img src="https://github.com/sarahssharkey.png" alt="@sarahssharkey" width="50px" />](https://github.com/sarahssharkey)
95
+ [<img src="https://github.com/shawncarr.png" alt="@shawncarr" width="50px" />](https://github.com/shawncarr)
96
+ [<img src="https://github.com/alindsay55661.png" alt="@alindsay55661" width="50px" />](https://github.com/alindsay55661)
97
+ [<img src="https://github.com/john-schmitz.png" alt="@john-schmitz" width="50px" />](https://github.com/john-schmitz)
98
+ [<img src="https://github.com/bobgubko.png" alt="@bobgubko" width="50px" />](https://github.com/bobgubko)
99
+ [<img src="https://github.com/miki725.png" alt="@miki725" width="50px" />](https://github.com/miki725)
100
+ [<img src="https://github.com/dev-m1-macbook.png" alt="@dev-m1-macbook" width="50px" />](https://github.com/dev-m1-macbook)
101
+ [<img src="https://github.com/McMerph.png" alt="@McMerph" width="50px" />](https://github.com/McMerph)
102
+ [<img src="https://github.com/shroudedcode.png" alt="@shroudedcode" width="50px" />](https://github.com/shroudedcode)
103
+ [<img src="https://github.com/maxcohn.png" alt="@maxcohn" width="50px" />](https://github.com/maxcohn)
104
+ [<img src="https://github.com/VideoSystemsTech.png" alt="@VideoSystemsTech" width="50px" />](https://github.com/VideoSystemsTech)
105
+ [<img src="https://github.com/TheWisestOne.png" alt="@TheWisestOne" width="50px" />](https://github.com/TheWisestOne)
106
+ [<img src="https://github.com/lazylace37.png" alt="@lazylace37" width="50px" />](https://github.com/lazylace37)
107
+ [<img src="https://github.com/leosuncin.png" alt="@leosuncin" width="50px" />](https://github.com/leosuncin)
108
+ [<img src="https://github.com/kirdk.png" alt="@kirdk" width="50px" />](https://github.com/kirdk)
109
+ [<img src="https://github.com/rayzr522.png" alt="@rayzr522" width="50px" />](https://github.com/rayzr522)
110
+
91
111
  # How it works
92
112
 
113
+ ## Concept
114
+
115
+ The API operates object schemas for input and output validation.
116
+ The object being validated is the combination of certain `request` properties.
117
+ It is available to the endpoint handler as the `input` parameter.
118
+ Middlewares have access to all `request` properties, they can provide endpoints with `options`.
119
+ The object returned by the endpoint handler is called `output`. It goes to the `ResultHandler` which is
120
+ responsible for transmitting consistent responses containing the `output` or possible error.
121
+ Much can be customized to fit your needs.
122
+
123
+ ![Dataflow](https://raw.githubusercontent.com/RobinTail/express-zod-api/master/dataflow.svg)
124
+
93
125
  ## Technologies
94
126
 
95
127
  - [Typescript](https://www.typescriptlang.org/) first.
@@ -103,34 +135,17 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
103
135
  - File uploads — [Express-FileUpload](https://github.com/richardgirges/express-fileupload)
104
136
  (based on [Busboy](https://github.com/mscdex/busboy)).
105
137
 
106
- ## Concept
107
-
108
- The API operates object schemas for input and output validation.
109
- The object being validated is the combination of certain `request` properties.
110
- It is available to the endpoint handler as the `input` parameter.
111
- Middlewares have access to all `request` properties, they can provide endpoints with `options`.
112
- The object returned by the endpoint handler is called `output`. It goes to the `ResultHandler` which is
113
- responsible for transmitting consistent responses containing the `output` or possible error.
114
- Much can be customized to fit your needs.
115
-
116
- ![Dataflow](https://raw.githubusercontent.com/RobinTail/express-zod-api/master/dataflow.svg)
117
-
118
138
  # Quick start
119
139
 
120
140
  ## Installation
121
141
 
122
- Run one of the following commands to install the library, its peer dependencies and packages for types assistance.
123
-
124
- ```shell
125
- yarn add express-zod-api express zod typescript http-errors
126
- yarn add --dev @types/express @types/node @types/http-errors
127
- ```
128
-
129
- or
142
+ Install the library, its peer dependencies and type assistance packages using your favorite
143
+ [package manager](https://nodesource.com/blog/nodejs-package-manager-comparative-guide-2024/).
130
144
 
131
145
  ```shell
132
- npm install express-zod-api express zod typescript http-errors
133
- npm install -D @types/express @types/node @types/http-errors
146
+ # example for yarn and express 5 (recommended):
147
+ yarn add express-zod-api express@^5 zod typescript http-errors
148
+ yarn add -D @types/express@^5 @types/node @types/http-errors
134
149
  ```
135
150
 
136
151
  Ensure having the following options in your `tsconfig.json` file in order to make it work as expected:
@@ -443,7 +458,7 @@ enough for the `output` schema if you're also aiming to [generate a valid docume
443
458
  because the transformations themselves do not contain schemas. Addressing this case, the library offers the `.remap()`
444
459
  method of the object schema, a part of the [Zod plugin](#zod-plugin), which under the hood, in addition to the
445
460
  transformation, also `.pipe()` the transformed object into a new object schema.
446
- Here is a recommended solution: it is importnant to use shallow transformations only.
461
+ Here is a recommended solution: it is important to use shallow transformations only.
447
462
 
448
463
  ```ts
449
464
  import camelize from "camelize-ts";
@@ -465,7 +480,7 @@ const endpoint = endpointsFactory.build({
465
480
  });
466
481
  ```
467
482
 
468
- The `.remap()` method can also accept an object with an explictly defined naming of your choice. The original keys
483
+ The `.remap()` method can also accept an object with an explicitly defined naming of your choice. The original keys
469
484
  missing in that object remain unchanged (partial mapping).
470
485
 
471
486
  ```ts
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
- "use strict";var Mo=Object.create;var Ye=Object.defineProperty;var Uo=Object.getOwnPropertyDescriptor;var Ho=Object.getOwnPropertyNames;var Do=Object.getPrototypeOf,Fo=Object.prototype.hasOwnProperty;var Ko=(e,t)=>{for(var r in t)Ye(e,r,{get:t[r],enumerable:!0})},nr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Ho(t))!Fo.call(e,n)&&n!==r&&Ye(e,n,{get:()=>t[n],enumerable:!(o=Uo(t,n))||o.enumerable});return e};var O=(e,t,r)=>(r=e!=null?Mo(Do(e)):{},nr(t||!e||!e.__esModule?Ye(r,"default",{value:e,enumerable:!0}):r,e)),Bo=e=>nr(Ye({},"__esModule",{value:!0}),e);var Rs={};Ko(Rs,{BuiltinLogger:()=>Oe,DependsOnMethod:()=>Re,Documentation:()=>ut,DocumentationError:()=>z,EndpointsFactory:()=>Se,InputValidationError:()=>U,Integration:()=>St,Middleware:()=>B,MissingPeerError:()=>ue,OutputValidationError:()=>V,ResultHandler:()=>xe,RoutingError:()=>te,ServeStatic:()=>Pe,arrayEndpointsFactory:()=>Pr,arrayResultHandler:()=>at,attachRouting:()=>Jr,createConfig:()=>cr,createServer:()=>Wr,defaultEndpointsFactory:()=>Ar,defaultResultHandler:()=>be,ez:()=>No,getExamples:()=>K,getMessageFromError:()=>F,getStatusCodeFromError:()=>Me,testEndpoint:()=>To});module.exports=Bo(Rs);var P=require("ramda"),ne=require("zod");var sr=require("http-errors"),ir=require("node:crypto"),Je=require("ramda"),ar=require("zod");var te=class extends Error{name="RoutingError"},z=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:n}){let i=`${t}
2
- Caused by ${n?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(i)}},Qe=class extends Error{name="IOSchemaError"},V=class extends Qe{constructor(r){super(F(r));this.originalError=r}name="OutputValidationError"},U=class extends Qe{constructor(r){super(F(r));this.originalError=r}name="InputValidationError"},_=class extends Error{constructor(r,o){super(r);this.originalError=o}name="ResultHandlerError"},ue=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var qo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},Ot={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},$o=["body","query","params"],Rt=e=>e.method.toLowerCase(),At=e=>e.startsWith("x-"),Go=e=>(0,Je.pickBy)((t,r)=>At(r),e),Pt=(e,t={})=>{let r=Rt(e);return r==="options"?{}:(t[r]||Ot[r]||$o).filter(o=>o==="files"?qo(e):!0).map(o=>o==="headers"?Go(e[o]):e[o]).reduce((o,n)=>({...o,...n}),{})},fe=e=>e instanceof Error?e:new Error(String(e)),F=e=>e instanceof ar.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof V?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Me=e=>(0,sr.isHttpError)(e)?e.statusCode:e instanceof U?400:500,Ct=({logger:e,request:t,input:r,error:o,statusCode:n})=>{n===500&&e.error(`Internal server error
1
+ "use strict";var Ho=Object.create;var _e=Object.defineProperty;var Do=Object.getOwnPropertyDescriptor;var Fo=Object.getOwnPropertyNames;var Ko=Object.getPrototypeOf,Bo=Object.prototype.hasOwnProperty;var qo=(e,t)=>{for(var r in t)_e(e,r,{get:t[r],enumerable:!0})},sr=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Fo(t))!Bo.call(e,n)&&n!==r&&_e(e,n,{get:()=>t[n],enumerable:!(o=Do(t,n))||o.enumerable});return e};var O=(e,t,r)=>(r=e!=null?Ho(Ko(e)):{},sr(t||!e||!e.__esModule?_e(r,"default",{value:e,enumerable:!0}):r,e)),$o=e=>sr(_e({},"__esModule",{value:!0}),e);var Ps={};qo(Ps,{BuiltinLogger:()=>Oe,DependsOnMethod:()=>Re,Documentation:()=>ut,DocumentationError:()=>z,EndpointsFactory:()=>Te,InputValidationError:()=>U,Integration:()=>Tt,Middleware:()=>B,MissingPeerError:()=>fe,OutputValidationError:()=>G,ResultHandler:()=>be,RoutingError:()=>te,ServeStatic:()=>Pe,arrayEndpointsFactory:()=>Cr,arrayResultHandler:()=>it,attachRouting:()=>eo,createConfig:()=>dr,createServer:()=>to,defaultEndpointsFactory:()=>Pr,defaultResultHandler:()=>Se,ez:()=>Mo,getExamples:()=>K,getMessageFromError:()=>F,getStatusCodeFromError:()=>Me,testEndpoint:()=>Ro});module.exports=$o(Ps);var P=require("ramda"),ne=require("zod");var ir=require("http-errors"),ar=require("node:crypto"),Qe=require("ramda"),pr=require("zod");var te=class extends Error{name="RoutingError"},z=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:n}){let i=`${t}
2
+ Caused by ${n?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(i)}},Ye=class extends Error{name="IOSchemaError"},G=class extends Ye{constructor(r){super(F(r));this.originalError=r}name="OutputValidationError"},U=class extends Ye{constructor(r){super(F(r));this.originalError=r}name="InputValidationError"},_=class extends Error{constructor(r,o){super(r);this.originalError=o}name="ResultHandlerError"},fe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var w={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var Vo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(w.upload);return"files"in e&&r},Rt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Go=["body","query","params"],At=e=>e.method.toLowerCase(),Pt=e=>e.startsWith("x-"),_o=e=>(0,Qe.pickBy)((t,r)=>Pt(r),e),Ct=(e,t={})=>{let r=At(e);return r==="options"?{}:(t[r]||Rt[r]||Go).filter(o=>o==="files"?Vo(e):!0).map(o=>o==="headers"?_o(e[o]):e[o]).reduce((o,n)=>({...o,...n}),{})},ye=e=>e instanceof Error?e:new Error(String(e)),F=e=>e instanceof pr.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof G?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Me=e=>(0,ir.isHttpError)(e)?e.statusCode:e instanceof U?400:500,It=({logger:e,request:t,input:r,error:o,statusCode:n})=>{n===500&&e.error(`Internal server error
3
3
  ${o.stack}
4
- `,{url:t.url,payload:r})},K=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[h]?.examples||[];if(!r&&t==="original")return o;let n=[];for(let i of o){let a=e.safeParse(i);a.success&&n.push(t==="parsed"?a.data:i)}return n},re=(e,t,r)=>e.length&&t.length?(0,Je.xprod)(e,t).map(r):e.concat(t),Ue=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,It=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),N=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(It).join(""),We=e=>(0,ir.createHash)("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Xe=(e,t)=>{try{return typeof e.parse(t)}catch{return}},oe=e=>typeof e=="object"&&e!==null;var et=require("ramda"),h=Symbol.for("express-zod-api"),tt=e=>{let t=e.describe(e.description);return t._def[h]=(0,et.clone)(t._def[h])||{examples:[]},t},pr=(e,t)=>{if(!(h in e._def))return t;let r=tt(t);return r._def[h].examples=re(r._def[h].examples,e._def[h].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?(0,et.mergeDeepRight)({...o},{...n}):n),r};var Vo=function(e){let t=tt(this);return t._def[h].examples.push(e),t},_o=function(e){let t=tt(this);return t._def[h].defaultLabel=e,t},Yo=function(e){return new ne.z.ZodBranded({typeName:ne.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[h]:{examples:[],...(0,P.clone)(this._def[h]),brand:e}})},Qo=function(e){let t=typeof e=="function"?e:(0,P.pipe)(P.toPairs,(0,P.map)(([n,i])=>(0,P.pair)(e[String(n)]||n,i)),P.fromPairs),r=t((0,P.clone)(this.shape)),o=ne.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};h in globalThis||(globalThis[h]=!0,Object.defineProperties(ne.z.ZodType.prototype,{example:{get(){return Vo.bind(this)}},brand:{set(){},get(){return Yo.bind(this)}}}),Object.defineProperty(ne.z.ZodDefault.prototype,"label",{get(){return _o.bind(this)}}),Object.defineProperty(ne.z.ZodObject.prototype,"remap",{get(){return Qo.bind(this)}}));function cr(e){return e}var Rr=require("zod");var jt=require("zod");var lr=require("zod");var He=require("zod"),Y=Symbol("File"),dr=He.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Jo={buffer:()=>dr.brand(Y),string:()=>He.z.string().brand(Y),binary:()=>dr.or(He.z.string()).brand(Y),base64:()=>He.z.string().base64().brand(Y)};function rt(e){return Jo[e||"string"]()}var se=Symbol("Raw"),mr=(e={})=>lr.z.object({raw:rt("buffer")}).extend(e).brand(se);var ur=require("zod"),De=Symbol("Upload"),fr=()=>ur.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(De);var yr=(e,{next:t})=>e.options.some(t),Wo=({_def:e},{next:t})=>[e.left,e.right].some(t),gr=(e,{next:t})=>t(e.unwrap()),Xo={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:yr,ZodDiscriminatedUnion:yr,ZodIntersection:Wo,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:gr,ZodNullable:gr,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},zt=(e,{condition:t,rules:r=Xo,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let i=o<n?r[e._def.typeName]:void 0;return i?i(e,{next:a=>zt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},hr=e=>zt(e,{condition:t=>t._def[h]?.brand===De}),xr=e=>zt(e,{condition:t=>t._def[h]?.brand===se,maxDepth:3});var ot=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).type("text/plain").end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
5
- Original error: ${e.originalError.message}.`:""))};var br=require("ramda");var ie=e=>oe(e)&&"or"in e,ge=e=>oe(e)&&"and"in e,wt=e=>({and:(0,br.chain)(t=>ge(t)?t.and:[t],e)}),nt=(e,t)=>ge(e)?{and:e.and.map(r=>ie(r)?{or:r.or.map(t)}:t(r))}:ie(e)?{or:e.or.map(r=>ge(r)?{and:r.and.map(t)}:t(r))}:t(e),Et=e=>e.and.reduce((t,r)=>({or:re(t.or,ie(r)?r.or:[r],wt)}),{or:[]}),ye=(e,t)=>ge(e)?ie(t)?ye(Et(e),t):wt([e,t]):ie(e)?ge(t)?ye(t,e):ie(t)?{or:re(e.or,t.or,wt)}:ye(e,{and:[t]}):ge(t)||ie(t)?ye(t,e):{and:[e,t]};var vt=require("zod");var Zt=class{},B=class extends Zt{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof vt.z.ZodError?new U(o):o}}},he=class extends B{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({input:vt.z.object({}),handler:async({request:n,response:i})=>new Promise((a,p)=>{let l=c=>{if(c&&c instanceof Error)return p(o(c));a(r(n,i))};t(n,i,l)?.catch(l)})})}};var Fe=class{},st=class extends Fe{#e;#t;#r;#i;#o;#a;#p;#n;#c;#d;#l;#s;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:i,getOperationId:a=()=>{},scopes:p=[],middlewares:l=[],tags:c=[],description:m,shortDescription:y}){super(),this.#a=n,this.#p=i,this.#r=l,this.#l=a,this.#t=Object.freeze(t),this.#c=Object.freeze(p),this.#d=Object.freeze(c),this.#e={long:m,short:y},this.#n={input:r,output:o},this.#o={positive:Object.freeze(i.getPositiveResponse(o)),negative:Object.freeze(i.getNegativeResponse())},this.#s=hr(r)?"upload":xr(r)?"raw":"json",this.#i={input:Object.freeze([w[this.#s]]),positive:Object.freeze(this.#o.positive.flatMap(({mimeTypes:u})=>u)),negative:Object.freeze(this.#o.negative.flatMap(({mimeTypes:u})=>u))}}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return t==="input"||t==="output"?this.#n[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#i[t]}getRequestType(){return this.#s}getResponses(t){return this.#o[t]}getSecurity(){return this.#r.reduce((t,r)=>{let o=r.getSecurity();return o?ye(t,o):t},{and:[]})}getScopes(){return this.#c}getTags(){return this.#d}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#t.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#n.output.parseAsync(t)}catch(r){throw r instanceof jt.z.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:n,logger:i,options:a}){for(let p of this.#r)if(!(t==="options"&&!(p instanceof he))&&(Object.assign(a,await p.execute({input:r,options:a,request:o,response:n,logger:i})),n.writableEnded)){i.warn("A middleware has closed the stream. Accumulated options:",a);break}}async#y({input:t,options:r,logger:o}){let n;try{n=await this.#n.input.parseAsync(t)}catch(i){throw i instanceof jt.z.ZodError?new U(i):i}return this.#a({input:n,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:n,input:i,output:a,options:p}){try{await this.#p.execute({error:t,output:a,request:r,response:o,logger:n,input:i,options:p})}catch(l){ot({logger:n,response:o,error:new _(fe(l).message,t||void 0)})}}async execute({request:t,response:r,logger:o,config:n,siblingMethods:i=[]}){let a=Rt(t),p={},l=null,c=null;if(n.cors){let y=this.#m(i);typeof n.cors=="function"&&(y=await n.cors({request:t,logger:o,endpoint:this,defaultHeaders:y}));for(let u in y)r.set(u,y[u])}let m=Pt(t,n.inputSources);try{if(await this.#f({method:a,input:m,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}l=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(y){c=fe(y)}await this.#g({input:m,output:l,request:t,response:r,error:c,logger:o,options:p})}};var Sr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>pr(i,n),o)};var k=require("zod");var Ke={positive:200,negative:400};var Tr=O(require("node:assert/strict"),1),Or=require("zod");var it=(e,t)=>typeof e=="function"?it(e(...t.arguments),t):e instanceof Or.z.ZodType?[{...t,schema:e}]:(Array.isArray(e)&&(0,Tr.default)(e.length,new _(`At least one ${t.variant} response schema required.`)),(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:n,mimeTypes:i,mimeType:a})=>({schema:r,statusCodes:n?[n]:o||t.statusCodes,mimeTypes:a?[a]:i||t.mimeTypes})));var Lt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},xe=class extends Lt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return it(this.#e,{variant:"positive",arguments:[t],statusCodes:[Ke.positive],mimeTypes:[w.json]})}getNegativeResponse(){return it(this.#t,{variant:"negative",arguments:[],statusCodes:[Ke.negative],mimeTypes:[w.json]})}},be=new xe({positive:e=>{let t=K({schema:e}),r=k.z.object({status:k.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:k.z.object({status:k.z.literal("error"),error:k.z.object({message:k.z.string()})}).example({status:"error",error:{message:F(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(!e){n.status(Ke.positive).json({status:"success",data:r});return}let a=Me(e);Ct({logger:i,statusCode:a,request:o,error:e,input:t}),n.status(a).json({status:"error",error:{message:F(e)}})}}),at=new xe({positive:e=>{let t=K({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof k.z.ZodArray?e.shape.items:k.z.array(k.z.any());return t.reduce((o,n)=>oe(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:k.z.string().example(F(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:n,input:i})=>{if(r){let a=Me(r);Ct({logger:o,statusCode:a,request:n,error:r,input:i}),e.status(a).type("text/plain").send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(Ke.positive).json(t.items):e.status(500).type("text/plain").send("Property 'items' is missing in the endpoint output")}});var Se=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof B?t:new B(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new he(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new B({input:Rr.z.object({}),handler:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:n,shortDescription:i,operationId:a,...p}){let{middlewares:l,resultHandler:c}=this,m="methods"in p?p.methods:[p.method],y=typeof a=="function"?a:()=>a,u="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],x="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new st({handler:r,middlewares:l,outputSchema:o,resultHandler:c,scopes:u,tags:x,methods:m,getOperationId:y,description:n,shortDescription:i,inputSchema:Sr(l,t)})}},Ar=new Se(be),Pr=new Se(at);var E=require("ansis"),Er=require("node:util"),Nt=require("node:perf_hooks");var Te={debug:10,info:20,warn:30,error:40},Ir=e=>oe(e)&&Object.keys(Te).some(t=>t in e),zr=(e=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}),pt=zr(),Cr=zr(2),en=e=>e<1e-6?["picosecond",e/1e-9,pt]:e<.001?["nanosecond",e/1e-6,pt]:e<1?["microsecond",e/.001,pt]:e<1e3?["millisecond",e,pt]:e<6e4?["second",e/1e3,Cr]:["minute",e/6e4,Cr],wr=e=>{let[t,r,o]=en(e);return`${o.format(r)} ${t}${r>1?"s":""}`};var Oe=class e{constructor(t){this.config=t;let{color:r=new E.Ansis().isSupported()}=t;this.hasColor=r}hasColor;styles={debug:E.blue,info:E.green,warn:(0,E.hex)("#FFA500"),error:E.red};prettyPrint(t){let{depth:r=2}=this.config;return(0,Er.inspect)(t,{depth:r,colors:this.hasColor,breakLength:this.config.level==="debug"?80:1/0,compact:this.config.level==="debug"?3:!0})}print(t,r,o){if(this.config.level==="silent"||Te[t]<Te[this.config.level])return;let{requestId:n,...i}=this.config.ctx||{},a=[new Date().toISOString()];n&&a.push(this.hasColor?(0,E.cyanBright)(n):n),a.push(this.hasColor?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&a.push(this.prettyPrint(o)),Object.keys(i).length>0&&a.push(this.prettyPrint(i)),console.log(a.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}profile(t){let r=Nt.performance.now();return()=>{let o=Nt.performance.now()-r,{message:n,severity:i="debug",formatter:a=wr}=typeof t=="object"?t:{message:t};this.print(typeof i=="function"?i(o):i,n,a(o))}}};var Ae=require("ramda"),Re=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze((0,Ae.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=(0,Ae.head)(this.pairs)?.[1],this.siblingMethods=Object.freeze((0,Ae.tail)(this.pairs).map(([r])=>r))}};var Zr=O(require("express"),1),Pe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Zr.default.static(...this.params))}};var ct=O(require("express"),1),_r=O(require("node:http"),1),Yr=O(require("node:https"),1);var Ce=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>O(require(e))))[t]}catch{}throw new ue(e)};var kt=O(require("node:assert/strict"),1);var ae=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:n})=>{let i=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of i){kt.default.doesNotMatch(a,/\//,new te(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let l=`${o||""}${a?`/${a}`:""}`;if(p instanceof Fe){let c=p.getMethods().slice();n&&c.push("options");for(let m of c)t(p,l,m)}else if(p instanceof Pe)r&&p.apply(l,r);else if(p instanceof Re){for(let[c,m]of p.pairs)(0,kt.default)(m.getMethods().includes(c),new te(`Endpoint assigned to ${c} method of ${l} must support ${c} method.`)),t(m,l,c);n&&p.firstEndpoint&&t(p.firstEndpoint,l,"options",p.siblingMethods)}else ae({onEndpoint:t,onStatic:r,hasCors:n,routing:p,parentPath:l})}};var Mt=({app:e,getChildLogger:t,config:r,routing:o,parsers:n})=>ae({routing:o,hasCors:!!r.cors,onEndpoint:(i,a,p,l)=>{e[p](a,...n?.[i.getRequestType()]||[],async(c,m)=>i.execute({request:c,response:m,logger:t(c),config:r,siblingMethods:l}))},onStatic:(i,a)=>{e.use(i,a)}});var Be=O(require("http-errors"),1);var Mr=require("node:timers/promises");var vr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",jr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Lr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Nr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),kr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Ur=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,i=c=>void n.delete(c.destroy()),a=c=>void(vr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):i(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let l=async()=>{for(let c of e)c.on("request",Nr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Lr(c)||jr(c))&&a(c);for await(let c of(0,Mr.setInterval)(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)i(c);return Promise.allSettled(e.map(kr))};return{sockets:n,shutdown:()=>o??=l()}};var Hr=({errorHandler:e,getChildLogger:t})=>async(r,o,n,i)=>r?e.execute({error:(0,Be.isHttpError)(r)?r:(0,Be.default)(400,fe(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):i(),Dr=({errorHandler:e,getChildLogger:t})=>async(r,o)=>{let n=(0,Be.default)(404,`Can not ${r.method} ${r.path}`),i=t(r);try{e.execute({request:r,response:o,logger:i,error:n,input:null,output:null,options:{}})}catch(a){ot({response:o,logger:i,error:new _(fe(a).message,n)})}},tn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},rn=e=>({log:e.debug.bind(e)}),Fr=async({getChildLogger:e,config:t})=>{let r=await Ce("express-fileupload"),{limitError:o,beforeUpload:n,...i}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,l,c)=>{let m=e(p);try{await n?.({request:p,logger:m})}catch(y){return c(y)}return r({debug:!0,...i,abortOnLimit:!1,parseNested:!0,logger:rn(m)})(p,l,c)}),o&&a.push(tn(o)),a},Kr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Br=({rootLogger:e,config:t})=>async(r,o,n)=>{let i=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;i.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[h]={logger:i}),n()},qr=e=>t=>t.res?.locals[h]?.logger||e,$r=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
6
- `).slice(1))),Gr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=Ur(e,{logger:t,timeout:r}),i=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,i)};var Z=require("ansis"),Vr=()=>{let e=(0,Z.italic)("Proudly supports transgender community.".padStart(109)),t=(0,Z.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,Z.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,Z.italic)("for Zoey".padEnd(20)),n=(0,Z.hex)("#F5A9B8"),i=(0,Z.hex)("#5BCEFA"),a=new Array(14).fill(i,1,3).fill(n,3,5).fill(Z.whiteBright,5,7).fill(n,7,9).fill(i,9,12).fill(Z.gray,12,13);return`
4
+ `,{url:t.url,payload:r})},K=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[h]?.examples||[];if(!r&&t==="original")return o;let n=[];for(let i of o){let a=e.safeParse(i);a.success&&n.push(t==="parsed"?a.data:i)}return n},re=(e,t,r)=>e.length&&t.length?(0,Qe.xprod)(e,t).map(r):e.concat(t),Ue=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,zt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),N=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(zt).join(""),Je=e=>(0,ar.createHash)("sha1").update(JSON.stringify(e),"utf8").digest("hex"),We=(e,t)=>{try{return typeof e.parse(t)}catch{return}},oe=e=>typeof e=="object"&&e!==null;var Xe=require("ramda"),h=Symbol.for("express-zod-api"),et=e=>{let t=e.describe(e.description);return t._def[h]=(0,Xe.clone)(t._def[h])||{examples:[]},t},cr=(e,t)=>{if(!(h in e._def))return t;let r=et(t);return r._def[h].examples=re(r._def[h].examples,e._def[h].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?(0,Xe.mergeDeepRight)({...o},{...n}):n),r};var Yo=function(e){let t=et(this);return t._def[h].examples.push(e),t},Qo=function(e){let t=et(this);return t._def[h].defaultLabel=e,t},Jo=function(e){return new ne.z.ZodBranded({typeName:ne.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[h]:{examples:[],...(0,P.clone)(this._def[h]),brand:e}})},Wo=function(e){let t=typeof e=="function"?e:(0,P.pipe)(P.toPairs,(0,P.map)(([n,i])=>(0,P.pair)(e[String(n)]||n,i)),P.fromPairs),r=t((0,P.clone)(this.shape)),o=ne.z.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};h in globalThis||(globalThis[h]=!0,Object.defineProperties(ne.z.ZodType.prototype,{example:{get(){return Yo.bind(this)}},brand:{set(){},get(){return Jo.bind(this)}}}),Object.defineProperty(ne.z.ZodDefault.prototype,"label",{get(){return Qo.bind(this)}}),Object.defineProperty(ne.z.ZodObject.prototype,"remap",{get(){return Wo.bind(this)}}));function dr(e){return e}var Ar=require("zod");var Lt=require("zod");var mr=require("zod");var He=require("zod"),Y=Symbol("File"),lr=He.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),Xo={buffer:()=>lr.brand(Y),string:()=>He.z.string().brand(Y),binary:()=>lr.or(He.z.string()).brand(Y),base64:()=>He.z.string().base64().brand(Y)};function tt(e){return Xo[e||"string"]()}var se=Symbol("Raw"),ur=(e={})=>mr.z.object({raw:tt("buffer")}).extend(e).brand(se);var fr=require("zod"),De=Symbol("Upload"),yr=()=>fr.z.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(De);var gr=(e,{next:t})=>e.options.some(t),en=({_def:e},{next:t})=>[e.left,e.right].some(t),hr=(e,{next:t})=>t(e.unwrap()),tn={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:gr,ZodDiscriminatedUnion:gr,ZodIntersection:en,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:hr,ZodNullable:hr,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},wt=(e,{condition:t,rules:r=tn,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let i=o<n?r[e._def.typeName]:void 0;return i?i(e,{next:a=>wt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},xr=e=>wt(e,{condition:t=>t._def[h]?.brand===De}),br=e=>wt(e,{condition:t=>t._def[h]?.brand===se,maxDepth:3});var rt=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).type("text/plain").end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
5
+ Original error: ${e.originalError.message}.`:""))};var Sr=require("ramda");var ie=e=>oe(e)&&"or"in e,he=e=>oe(e)&&"and"in e,Et=e=>({and:(0,Sr.chain)(t=>he(t)?t.and:[t],e)}),ot=(e,t)=>he(e)?{and:e.and.map(r=>ie(r)?{or:r.or.map(t)}:t(r))}:ie(e)?{or:e.or.map(r=>he(r)?{and:r.and.map(t)}:t(r))}:t(e),Zt=e=>e.and.reduce((t,r)=>({or:re(t.or,ie(r)?r.or:[r],Et)}),{or:[]}),ge=(e,t)=>he(e)?ie(t)?ge(Zt(e),t):Et([e,t]):ie(e)?he(t)?ge(t,e):ie(t)?{or:re(e.or,t.or,Et)}:ge(e,{and:[t]}):he(t)||ie(t)?ge(t,e):{and:[e,t]};var jt=require("zod");var vt=class{},B=class extends vt{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof jt.z.ZodError?new U(o):o}}},xe=class extends B{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({input:jt.z.object({}),handler:async({request:n,response:i})=>new Promise((a,p)=>{let l=c=>{if(c&&c instanceof Error)return p(o(c));a(r(n,i))};t(n,i,l)?.catch(l)})})}};var Fe=class{},nt=class extends Fe{#e;#t;#r;#i;#o;#a;#p;#n;#c;#d;#l;#s;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:i,getOperationId:a=()=>{},scopes:p=[],middlewares:l=[],tags:c=[],description:m,shortDescription:y}){super(),this.#a=n,this.#p=i,this.#r=l,this.#l=a,this.#t=Object.freeze(t),this.#c=Object.freeze(p),this.#d=Object.freeze(c),this.#e={long:m,short:y},this.#n={input:r,output:o},this.#o={positive:Object.freeze(i.getPositiveResponse(o)),negative:Object.freeze(i.getNegativeResponse())},this.#s=xr(r)?"upload":br(r)?"raw":"json",this.#i={input:Object.freeze([w[this.#s]]),positive:Object.freeze(this.#o.positive.flatMap(({mimeTypes:u})=>u)),negative:Object.freeze(this.#o.negative.flatMap(({mimeTypes:u})=>u))}}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return t==="input"||t==="output"?this.#n[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#i[t]}getRequestType(){return this.#s}getResponses(t){return this.#o[t]}getSecurity(){return this.#r.reduce((t,r)=>{let o=r.getSecurity();return o?ge(t,o):t},{and:[]})}getScopes(){return this.#c}getTags(){return this.#d}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#t.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#n.output.parseAsync(t)}catch(r){throw r instanceof Lt.z.ZodError?new G(r):r}}async#f({method:t,input:r,request:o,response:n,logger:i,options:a}){for(let p of this.#r)if(!(t==="options"&&!(p instanceof xe))&&(Object.assign(a,await p.execute({input:r,options:a,request:o,response:n,logger:i})),n.writableEnded)){i.warn("A middleware has closed the stream. Accumulated options:",a);break}}async#y({input:t,options:r,logger:o}){let n;try{n=await this.#n.input.parseAsync(t)}catch(i){throw i instanceof Lt.z.ZodError?new U(i):i}return this.#a({input:n,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:n,input:i,output:a,options:p}){try{await this.#p.execute({error:t,output:a,request:r,response:o,logger:n,input:i,options:p})}catch(l){rt({logger:n,response:o,error:new _(ye(l).message,t||void 0)})}}async execute({request:t,response:r,logger:o,config:n,siblingMethods:i=[]}){let a=At(t),p={},l=null,c=null;if(n.cors){let y=this.#m(i);typeof n.cors=="function"&&(y=await n.cors({request:t,logger:o,endpoint:this,defaultHeaders:y}));for(let u in y)r.set(u,y[u])}let m=Ct(t,n.inputSources);try{if(await this.#f({method:a,input:m,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}l=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(y){c=ye(y)}await this.#g({input:m,output:l,request:t,response:r,error:c,logger:o,options:p})}};var Tr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>cr(i,n),o)};var k=require("zod");var ae={positive:200,negative:400};var Or=O(require("node:assert/strict"),1),Rr=require("zod");var st=(e,t)=>typeof e=="function"?st(e(...t.arguments),t):e instanceof Rr.z.ZodType?[{...t,schema:e}]:(Array.isArray(e)&&(0,Or.default)(e.length,new _(`At least one ${t.variant} response schema required.`)),(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:n,mimeTypes:i,mimeType:a})=>({schema:r,statusCodes:n?[n]:o||t.statusCodes,mimeTypes:a?[a]:i||t.mimeTypes})));var Nt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},be=class extends Nt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return st(this.#e,{variant:"positive",arguments:[t],statusCodes:[ae.positive],mimeTypes:[w.json]})}getNegativeResponse(){return st(this.#t,{variant:"negative",arguments:[],statusCodes:[ae.negative],mimeTypes:[w.json]})}},Se=new be({positive:e=>{let t=K({schema:e}),r=k.z.object({status:k.z.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:k.z.object({status:k.z.literal("error"),error:k.z.object({message:k.z.string()})}).example({status:"error",error:{message:F(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(!e){n.status(ae.positive).json({status:"success",data:r});return}let a=Me(e);It({logger:i,statusCode:a,request:o,error:e,input:t}),n.status(a).json({status:"error",error:{message:F(e)}})}}),it=new be({positive:e=>{let t=K({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof k.z.ZodArray?e.shape.items:k.z.array(k.z.any());return t.reduce((o,n)=>oe(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:k.z.string().example(F(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:n,input:i})=>{if(r){let a=Me(r);It({logger:o,statusCode:a,request:n,error:r,input:i}),e.status(a).type("text/plain").send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(ae.positive).json(t.items):e.status(500).type("text/plain").send("Property 'items' is missing in the endpoint output")}});var Te=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof B?t:new B(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new xe(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new B({input:Ar.z.object({}),handler:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:n,shortDescription:i,operationId:a,...p}){let{middlewares:l,resultHandler:c}=this,m="methods"in p?p.methods:[p.method],y=typeof a=="function"?a:()=>a,u="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],x="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new nt({handler:r,middlewares:l,outputSchema:o,resultHandler:c,scopes:u,tags:x,methods:m,getOperationId:y,description:n,shortDescription:i,inputSchema:Tr(l,t)})}},Pr=new Te(Se),Cr=new Te(it);var E=require("ansis"),jr=require("node:util"),kt=require("node:perf_hooks");var pt={debug:10,info:20,warn:30,error:40},zr=e=>oe(e)&&Object.keys(pt).some(t=>t in e),wr=e=>e in pt,Er=(e,t)=>pt[e]<pt[t],Zr=(e=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}),at=Zr(),Ir=Zr(2),rn=e=>e<1e-6?["picosecond",e/1e-9,at]:e<.001?["nanosecond",e/1e-6,at]:e<1?["microsecond",e/.001,at]:e<1e3?["millisecond",e,at]:e<6e4?["second",e/1e3,Ir]:["minute",e/6e4,Ir],vr=e=>{let[t,r,o]=rn(e);return`${o.format(r)} ${t}${r>1?"s":""}`};var Oe=class e{constructor(t){this.config=t;let{color:r=new E.Ansis().isSupported()}=t;this.hasColor=r}hasColor;styles={debug:E.blue,info:E.green,warn:(0,E.hex)("#FFA500"),error:E.red};prettyPrint(t){let{depth:r=2}=this.config;return(0,jr.inspect)(t,{depth:r,colors:this.hasColor,breakLength:this.config.level==="debug"?80:1/0,compact:this.config.level==="debug"?3:!0})}print(t,r,o){if(this.config.level==="silent"||Er(t,this.config.level))return;let{requestId:n,...i}=this.config.ctx||{},a=[new Date().toISOString()];n&&a.push(this.hasColor?(0,E.cyanBright)(n):n),a.push(this.hasColor?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&a.push(this.prettyPrint(o)),Object.keys(i).length>0&&a.push(this.prettyPrint(i)),console.log(a.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}profile(t){let r=kt.performance.now();return()=>{let o=kt.performance.now()-r,{message:n,severity:i="debug",formatter:a=vr}=typeof t=="object"?t:{message:t};this.print(typeof i=="function"?i(o):i,n,a(o))}}};var Ae=require("ramda"),Re=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze((0,Ae.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=(0,Ae.head)(this.pairs)?.[1],this.siblingMethods=Object.freeze((0,Ae.tail)(this.pairs).map(([r])=>r))}};var Lr=O(require("express"),1),Pe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Lr.default.static(...this.params))}};var ct=O(require("express"),1),Jr=O(require("node:http"),1),Wr=O(require("node:https"),1);var Ce=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>O(require(e))))[t]}catch{}throw new fe(e)};var Mt=O(require("node:assert/strict"),1);var pe=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:n})=>{let i=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of i){Mt.default.doesNotMatch(a,/\//,new te(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let l=`${o||""}${a?`/${a}`:""}`;if(p instanceof Fe){let c=p.getMethods().slice();n&&c.push("options");for(let m of c)t(p,l,m)}else if(p instanceof Pe)r&&p.apply(l,r);else if(p instanceof Re){for(let[c,m]of p.pairs)(0,Mt.default)(m.getMethods().includes(c),new te(`Endpoint assigned to ${c} method of ${l} must support ${c} method.`)),t(m,l,c);n&&p.firstEndpoint&&t(p.firstEndpoint,l,"options",p.siblingMethods)}else pe({onEndpoint:t,onStatic:r,hasCors:n,routing:p,parentPath:l})}};var Ut=({app:e,getChildLogger:t,config:r,routing:o,parsers:n})=>pe({routing:o,hasCors:!!r.cors,onEndpoint:(i,a,p,l)=>{e[p](a,...n?.[i.getRequestType()]||[],async(c,m)=>i.execute({request:c,response:m,logger:t(c),config:r,siblingMethods:l}))},onStatic:(i,a)=>{e.use(i,a)}});var Ke=O(require("http-errors"),1);var Dr=require("node:timers/promises");var Nr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",kr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Mr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Ur=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),Hr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var Fr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,i=c=>void n.delete(c.destroy()),a=c=>void(Nr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):i(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let l=async()=>{for(let c of e)c.on("request",Ur);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Mr(c)||kr(c))&&a(c);for await(let c of(0,Dr.setInterval)(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)i(c);return Promise.allSettled(e.map(Hr))};return{sockets:n,shutdown:()=>o??=l()}};var Kr=({errorHandler:e,getChildLogger:t})=>async(r,o,n,i)=>r?e.execute({error:(0,Ke.isHttpError)(r)?r:(0,Ke.default)(400,ye(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):i(),Br=({errorHandler:e,getChildLogger:t})=>async(r,o)=>{let n=(0,Ke.default)(404,`Can not ${r.method} ${r.path}`),i=t(r);try{e.execute({request:r,response:o,logger:i,error:n,input:null,output:null,options:{}})}catch(a){rt({response:o,logger:i,error:new _(ye(a).message,n)})}},on=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},nn=e=>({log:e.debug.bind(e)}),qr=async({getChildLogger:e,config:t})=>{let r=await Ce("express-fileupload"),{limitError:o,beforeUpload:n,...i}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,l,c)=>{let m=e(p);try{await n?.({request:p,logger:m})}catch(y){return c(y)}return r({debug:!0,...i,abortOnLimit:!1,parseNested:!0,logger:nn(m)})(p,l,c)}),o&&a.push(on(o)),a},$r=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Vr=({rootLogger:e,config:t})=>async(r,o,n)=>{let i=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;i.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[h]={logger:i}),n()},Gr=e=>t=>t.res?.locals[h]?.logger||e,_r=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
6
+ `).slice(1))),Yr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=Fr(e,{logger:t,timeout:r}),i=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,i)};var Z=require("ansis"),Qr=()=>{let e=(0,Z.italic)("Proudly supports transgender community.".padStart(109)),t=(0,Z.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,Z.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,Z.italic)("for Zoey".padEnd(20)),n=(0,Z.hex)("#F5A9B8"),i=(0,Z.hex)("#5BCEFA"),a=new Array(14).fill(i,1,3).fill(n,3,5).fill(Z.whiteBright,5,7).fill(n,7,9).fill(i,9,12).fill(Z.gray,12,13);return`
7
7
  8888888888 8888888888P 888 d8888 8888888b. 8888888
8
8
  888 d88P 888 d88888 888 Y88b 888
9
9
  888 d88P 888 d88P888 888 888 888
@@ -18,8 +18,8 @@ ${o}888${t}
18
18
  ${r}
19
19
  `.split(`
20
20
  `).map((l,c)=>a[c]?a[c](l):l).join(`
21
- `)};var Qr=e=>{e.startupLogo!==!1&&console.log(Vr());let t=e.errorHandler||be,r=Ir(e.logger)?e.logger:new Oe(e.logger);r.debug("Running","v20.14.0 (CJS)"),$r(r);let o=Br({rootLogger:r,config:e}),i={getChildLogger:qr(r),errorHandler:t},a=Dr(i),p=Hr(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},Jr=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=Qr(e);return Mt({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},Wr=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Qr(e),p=(0,ct.default)().disable("x-powered-by").use(a);if(e.server.compression){let u=await Ce("compression");p.use(u(typeof e.server.compression=="object"?e.server.compression:void 0))}let l={json:[e.server.jsonParser||ct.default.json()],raw:[e.server.rawParser||ct.default.raw(),Kr],upload:e.server.upload?await Fr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Mt({app:p,routing:t,getChildLogger:o,config:e,parsers:l}),p.use(i,n);let c=(u,x)=>u.listen(x,()=>r.info("Listening",x)),m=_r.default.createServer(p),y=e.https&&Yr.default.createServer(e.https.options,p);return e.gracefulShutdown&&Gr({servers:[m].concat(y||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(m,e.server.listen),httpsServer:y&&c(y,e.https?.listen)}};var xo=O(require("node:assert/strict"),1),bo=require("openapi3-ts/oas31"),So=require("ramda");var Q=O(require("node:assert/strict"),1),q=require("openapi3-ts/oas31"),d=require("ramda"),S=require("zod");var Ie=require("zod");var dt=e=>!isNaN(e.getTime());var qe=Symbol("DateIn"),Xr=()=>Ie.z.union([Ie.z.string().date(),Ie.z.string().datetime(),Ie.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ie.z.date().refine(dt)).brand(qe);var eo=require("zod");var $e=Symbol("DateOut"),to=()=>eo.z.date().refine(dt).transform(e=>e.toISOString()).brand($e);var pe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[h]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>pe(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),l=t&&t(e,{prev:p,...n});return l?{...p,...l}:p};var ro=50,no="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",on={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},so=/:([A-Za-z0-9_]+)/g,nn=e=>e.match(so)?.map(t=>t.slice(1))||[],io=e=>e.replace(so,t=>`{${t.slice(1)}}`),sn=({_def:e},{next:t})=>({...t(e.innerType),default:e[h]?.defaultLabel||e.defaultValue()}),an=({_def:{innerType:e}},{next:t})=>t(e),pn=()=>({format:"any"}),cn=({},e)=>((0,Q.default)(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),dn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},ln=({options:e},{next:t})=>({oneOf:e.map(t)}),mn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),un=e=>{let[t,r]=e.filter(q.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));(0,Q.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,d.mergeDeepWith)((n,i)=>Array.isArray(n)&&Array.isArray(i)?(0,d.concat)(n,i):n===i?i:Q.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,d.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=re(t.examples||[],r.examples||[],([n,i])=>(0,d.mergeDeepRight)(n,i))),o},fn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return un(o)}catch{}return{allOf:o}},yn=(e,{next:t})=>t(e.unwrap()),gn=(e,{next:t})=>t(e.unwrap()),hn=(e,{next:t})=>{let r=t(e.unwrap());return(0,q.isSchemaObject)(r)&&(r.type=po(r)),r},ao=e=>{let t=(0,d.toLower)((0,d.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},oo=e=>({type:ao(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),xn=({value:e})=>({type:ao(e),const:e}),bn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Ue(p)?p instanceof S.z.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=lt(e,r)),i.length&&(a.required=i),a},Sn=()=>({type:"null"}),Tn=({},e)=>((0,Q.default)(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"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?$/.source,externalDocs:{url:no}}),On=({},e)=>((0,Q.default)(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:no}}),Rn=({},e)=>Q.default.fail(new z({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),An=()=>({type:"boolean"}),Pn=()=>({type:"integer",format:"bigint"}),Cn=e=>e.every(t=>t instanceof S.z.ZodLiteral),In=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.z.ZodEnum||e instanceof S.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=lt(S.z.object((0,d.fromPairs)((0,d.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof S.z.ZodLiteral)return{type:"object",properties:lt(S.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.z.ZodUnion&&Cn(e.options)){let o=(0,d.map)(i=>`${i.value}`,e.options),n=(0,d.fromPairs)((0,d.xprod)(o,[t]));return{type:"object",properties:lt(S.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},zn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},wn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),En=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:l,isEmoji:c,isDatetime:m,_def:{checks:y}})=>{let u=y.find(C=>C.kind==="regex"),x=y.find(C=>C.kind==="datetime"),j=u?u.regex:x?x.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,T={type:"string"},M={"date-time":m,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:l,emoji:c};for(let C in M)if(M[C]){T.format=C;break}return r!==null&&(T.minLength=r),o!==null&&(T.maxLength=o),j&&(T.pattern=j.source),T},Zn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(y=>y.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(y=>y.kind==="max"),l=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=i:m.exclusiveMinimum=i,c?m.maximum=l:m.exclusiveMaximum=l,m},lt=({shape:e},t)=>(0,d.map)(t,e),vn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return on?.[t]},po=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},jn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,q.isSchemaObject)(o)){let i=Xe(e,vn(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.z.any())}if(!t&&n.type==="preprocess"&&(0,q.isSchemaObject)(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},Ln=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Nn=(e,{next:t})=>t(e.unwrap()),kn=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},Mn=(e,{next:t})=>t(e.unwrap().shape.raw),co=e=>e.length?(0,d.fromPairs)((0,d.zip)((0,d.range)(1,e.length+1).map(t=>`example${t}`),(0,d.map)((0,d.objOf)("value"),e))):void 0,lo=(e,t,r=[])=>(0,d.pipe)(K,(0,d.map)((0,d.when)(o=>(0,d.type)(o)==="Object",(0,d.omit)(r))),co)({schema:e,variant:t?"parsed":"original",validate:!0}),Un=(e,t)=>(0,d.pipe)(K,(0,d.filter)((0,d.has)(t)),(0,d.pluck)(t),co)({schema:e,variant:"original",validate:!0}),ce=e=>e instanceof S.z.ZodObject?e:e instanceof S.z.ZodBranded?ce(e.unwrap()):e instanceof S.z.ZodUnion||e instanceof S.z.ZodDiscriminatedUnion?e.options.map(t=>ce(t)).reduce((t,r)=>t.merge(r.partial()),S.z.object({})):e instanceof S.z.ZodEffects?ce(e._def.schema):e instanceof S.z.ZodPipeline?ce(e._def.in):ce(e._def.left).merge(ce(e._def.right)),mo=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:l,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=ce(r),y=nn(e),u=o.includes("query"),x=o.includes("params"),j=o.includes("headers"),T=b=>x&&y.includes(b),M=b=>j&&At(b);return Object.keys(m).map(b=>({name:b,location:T(b)?"path":M(b)?"header":u?"query":void 0})).filter(b=>b.location!==void 0).map(({name:b,location:Ze})=>{let G=pe(m[b],{rules:{...l,...Ht},onEach:Dt,onMissing:Ft,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),X=p==="components"?a(N(c,b),G):G;return{name:b,in:Ze,required:!m[b].isOptional(),description:G.description||c,schema:X,examples:Un(r,b)}})},Ht={ZodString:En,ZodNumber:Zn,ZodBigInt:Pn,ZodBoolean:An,ZodNull:Sn,ZodArray:zn,ZodTuple:wn,ZodRecord:In,ZodObject:bn,ZodLiteral:xn,ZodIntersection:fn,ZodUnion:ln,ZodAny:pn,ZodDefault:sn,ZodEnum:oo,ZodNativeEnum:oo,ZodEffects:jn,ZodOptional:yn,ZodNullable:hn,ZodDiscriminatedUnion:mn,ZodBranded:Nn,ZodDate:Rn,ZodCatch:an,ZodPipeline:Ln,ZodLazy:kn,ZodReadonly:gn,[Y]:dn,[De]:cn,[$e]:On,[qe]:Tn,[se]:Mn},Dt=(e,{isResponse:t,prev:r})=>{if((0,q.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof S.z.ZodLazy,i=r.type!==void 0,a=t&&Ue(e),p=!n&&i&&!a&&e.isNullable(),l=n?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=po(r)),l.length&&(c.examples=l.slice()),c},Ft=(e,t)=>Q.default.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Ut=(e,t)=>{if((0,q.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,d.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,d.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Ut(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Ut(o,t))),r},uo=e=>(0,q.isReferenceObject)(e)?e:(0,d.omit)(["examples"],e),fo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:l,hasMultipleStatusCodes:c,statusCode:m,brandHandling:y,description:u=`${e.toUpperCase()} ${t} ${It(n)} response ${c?m:""}`.trim()})=>{let x=uo(pe(r,{rules:{...y,...Ht},onEach:Dt,onMissing:Ft,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),j={schema:l==="components"?p(N(u),x):x,examples:lo(r,!0)};return{description:u,content:(0,d.fromPairs)((0,d.xprod)(o,[j]))}},Hn=()=>({type:"http",scheme:"basic"}),Dn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Fn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Kn=({name:e})=>({type:"apiKey",in:"header",name:e}),Bn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),qn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),$n=({flows:e={}})=>({type:"oauth2",flows:(0,d.map)(t=>({...t,scopes:t.scopes||{}}),(0,d.reject)(d.isNil,e))}),yo=(e,t)=>{let r={basic:Hn,bearer:Dn,input:Fn,header:Kn,cookie:Bn,openid:qn,oauth2:$n};return nt(e,o=>r[o.type](o,t))},mt=e=>"or"in e?e.or.map(t=>"and"in t?(0,d.mergeAll)((0,d.map)(({name:r,scopes:o})=>(0,d.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?mt(Et(e)):mt({or:[e]}),go=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:l,paramNames:c,description:m=`${e.toUpperCase()} ${t} Request body`})=>{let y=uo(Ut(pe(r,{rules:{...l,...Ht},onEach:Dt,onMissing:Ft,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),u={schema:p==="components"?a(N(m),y):y,examples:lo(r,!1,c)};return{description:m,content:(0,d.fromPairs)((0,d.xprod)(o,[u]))}},ho=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Kt=e=>e.length<=ro?e:e.slice(0,ro-1)+"\u2026";var ut=class extends bo.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||N(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&xo.default.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:l=!0,composition:c="inline",serializer:m=We}){super(),this.addInfo({title:o,version:n});for(let u of typeof i=="string"?[i]:i)this.addServer({url:u});ae({routing:t,onEndpoint:(u,x,j)=>{let T=j,M={path:x,method:T,endpoint:u,composition:c,serializer:m,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[C,b]=["short","long"].map(u.getDescription.bind(u)),Ze=C?Kt(C):l&&b?Kt(b):void 0,G=u.getTags(),X=r.inputSources?.[T]||Ot[T],le=this.ensureUniqOperationId(x,T,u.getOperationId(T)),ve=mo({...M,inputSources:X,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:x,operationId:le})}),Ve={};for(let D of["positive","negative"]){let ee=u.getResponses(D);for(let{mimeTypes:je,schema:R,statusCodes:A}of ee)for(let I of A)Ve[I]=fo({...M,variant:D,schema:R,mimeTypes:je,statusCode:I,hasMultipleStatusCodes:ee.length>1||A.length>1,description:a?.[`${D}Response`]?.call(null,{method:T,path:x,operationId:le,statusCode:I})})}let Tt=X.includes("body")?go({...M,paramNames:(0,So.pluck)("name",ve),schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:x,operationId:le})}):void 0,_e=mt(nt(yo(u.getSecurity(),X),D=>{let ee=this.ensureUniqSecuritySchemaName(D),je=["oauth2","openIdConnect"].includes(D.type)?u.getScopes().slice():[];return this.addSecurityScheme(ee,D),{name:ee,scopes:je}}));this.addPath(io(x),{[T]:{operationId:le,summary:Ze,description:b,tags:G.length>0?G:void 0,parameters:ve.length>0?ve:void 0,requestBody:Tt,security:_e.length>0?_e:void 0,responses:Ve}})}}),this.rootDoc.tags=r.tags?ho(r.tags):[]}};var ft=require("node-mocks-http"),Gn=e=>(0,ft.createRequest)({...e,headers:{"content-type":w.json,...e?.headers}}),Vn=e=>(0,ft.createResponse)(e),_n=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:o in Te?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Yn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Gn(e),i=Vn({req:n,...t});i.req=t?.req||n,n.res=i;let a=_n(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},To=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Yn(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}};var v=O(require("typescript"),1);var H=O(require("typescript"),1),ze=require("ramda"),s=H.default.factory,J=[s.createModifier(H.default.SyntaxKind.ExportKeyword)],Qn=[s.createModifier(H.default.SyntaxKind.AsyncKeyword)],Jn=[s.createModifier(H.default.SyntaxKind.PublicKeyword),s.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],Oo=[s.createModifier(H.default.SyntaxKind.ProtectedKeyword),s.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],Bt=s.createTemplateHead(""),we=s.createTemplateTail(""),qt=s.createTemplateMiddle(" "),$t=e=>s.createTemplateLiteralType(Bt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?we:qt))),Gt=$t(["M","P"]),yt=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),gt=(e,t)=>(0,ze.chain)(([r,o])=>[yt(s.createIdentifier(r),o,t)],(0,ze.toPairs)(e)),Vt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),Ro=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),Ao=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),W=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],H.default.NodeFlags.Const),_t=(e,t)=>s.createTypeAliasDeclaration(J,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),ht=(e,t)=>s.createTypeAliasDeclaration(J,e,void 0,t),Po=(e,t,r)=>s.createPropertyDeclaration(Jn,e,void 0,t,r),Co=(e,t,r)=>s.createClassDeclaration(J,e,void 0,void 0,[t,...r]),Io=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),zo=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(H.default.SyntaxKind.AnyKeyword)]),wo=(e,t,r)=>s.createInterfaceDeclaration(J,e,void 0,t,r),Wn=(0,ze.chain)(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),Eo=e=>Wn((0,ze.toPairs)(e)),Yt=(e,t,r)=>s.createArrowFunction(r?Qn:void 0,void 0,e.map(o=>yt(o)),void 0,void 0,t),Qt=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,gt({acc:void 0,key:void 0}),void 0,void 0,t),r]),Zo=(...e)=>`"${e.join(" ")}"`;var vo=["get","post","put","delete","patch"];var g=O(require("typescript"),1),bt=require("zod");var $=O(require("typescript"),1),{factory:xt}=$.default,Jt=(e,t)=>{$.default.addSyntheticLeadingComment(e,$.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ee=(e,t,r)=>{let o=xt.createTypeAliasDeclaration(void 0,xt.createIdentifier(t),void 0,e);return r&&Jt(o,r),o},Wt=(e,t)=>{let r=$.default.createSourceFile("print.ts","",$.default.ScriptTarget.Latest,!1,$.default.ScriptKind.TS);return $.default.createPrinter(t).printNode($.default.EmitHint.Unspecified,e,r)},Xn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,jo=e=>Xn.test(e)?xt.createIdentifier(e):xt.createStringLiteral(e);var{factory:f}=g.default,es={[g.default.SyntaxKind.AnyKeyword]:"",[g.default.SyntaxKind.BigIntKeyword]:BigInt(0),[g.default.SyntaxKind.BooleanKeyword]:!1,[g.default.SyntaxKind.NumberKeyword]:0,[g.default.SyntaxKind.ObjectKeyword]:{},[g.default.SyntaxKind.StringKeyword]:"",[g.default.SyntaxKind.UndefinedKeyword]:void 0},ts=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),rs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Ue(a)?a instanceof bt.z.ZodOptional:a.isOptional(),l=f.createPropertySignature(void 0,jo(i),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Jt(l,a.description),l});return f.createTypeLiteralNode(n)},os=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),ns=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),Lo=({options:e},{next:t})=>f.createUnionTypeNode(e.map(t)),ss=e=>es?.[e.kind],is=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Xe(e,ss(o)),i={number:g.default.SyntaxKind.NumberKeyword,bigint:g.default.SyntaxKind.BigIntKeyword,boolean:g.default.SyntaxKind.BooleanKeyword,string:g.default.SyntaxKind.StringKeyword,undefined:g.default.SyntaxKind.UndefinedKeyword,object:g.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(n&&i[n]||g.default.SyntaxKind.AnyKeyword)}return o},as=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),ps=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},cs=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),ds=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),ls=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),ms=({_def:e},{next:t})=>f.createIntersectionTypeNode([e.left,e.right].map(t)),us=({_def:e},{next:t})=>t(e.innerType),de=e=>()=>f.createKeywordTypeNode(e),fs=(e,{next:t})=>t(e.unwrap()),ys=(e,{next:t})=>t(e.unwrap()),gs=({_def:e},{next:t})=>t(e.innerType),hs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),xs=()=>f.createLiteralTypeNode(f.createNull()),bs=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,f.createLiteralTypeNode(f.createNull())),r(i,o(e)))},Ss=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),n=f.createUnionTypeNode([r,o]);return t instanceof bt.z.ZodString?r:t instanceof bt.z.ZodUnion?n:o},Ts=(e,{next:t})=>t(e.unwrap().shape.raw),Os={ZodString:de(g.default.SyntaxKind.StringKeyword),ZodNumber:de(g.default.SyntaxKind.NumberKeyword),ZodBigInt:de(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:de(g.default.SyntaxKind.BooleanKeyword),ZodAny:de(g.default.SyntaxKind.AnyKeyword),[qe]:de(g.default.SyntaxKind.StringKeyword),[$e]:de(g.default.SyntaxKind.StringKeyword),ZodNull:xs,ZodArray:os,ZodTuple:ds,ZodRecord:ls,ZodObject:rs,ZodLiteral:ts,ZodIntersection:ms,ZodUnion:Lo,ZodDefault:us,ZodEnum:ns,ZodNativeEnum:as,ZodEffects:is,ZodOptional:ps,ZodNullable:cs,ZodDiscriminatedUnion:Lo,ZodBranded:fs,ZodCatch:gs,ZodPipeline:hs,ZodLazy:bs,ZodReadonly:ys,[Y]:Ss,[se]:Ts},Ge=(e,{brandHandling:t,ctx:r})=>pe(e,{rules:{...t,...Os},onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),ctx:r});var St=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Ee(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=We,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){ae({routing:t,onEndpoint:(R,A,I)=>{let me={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},Le=N(I,A,"input"),Ne=Ge(R.getSchema("input"),{brandHandling:r,ctx:{...me,isResponse:!1}}),L=i?N(I,A,"positive.response"):void 0,Xt=R.getSchema("positive"),er=i?Ge(Xt,{brandHandling:r,ctx:{...me,isResponse:!0}}):void 0,ke=i?N(I,A,"negative.response"):void 0,tr=R.getSchema("negative"),rr=i?Ge(tr,{brandHandling:r,ctx:{...me,isResponse:!0}}):void 0,or=N(I,A,"response"),ko=L&&ke?s.createUnionTypeNode([s.createTypeReferenceNode(L),s.createTypeReferenceNode(ke)]):Ge(Xt.or(tr),{brandHandling:r,ctx:{...me,isResponse:!0}});this.program.push(Ee(Ne,Le)),er&&L&&this.program.push(Ee(er,L)),rr&&ke&&this.program.push(Ee(rr,ke)),this.program.push(Ee(ko,or)),I!=="options"&&(this.paths.push(A),this.registry.set({method:I,path:A},{input:Le,positive:L,negative:ke,response:or,isJson:R.getMimeTypes("positive").includes(w.json),tags:R.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(_t(this.ids.pathType,this.paths)),this.program.push(_t(this.ids.methodType,vo)),this.program.push(ht(this.ids.methodPathType,$t([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(v.default.SyntaxKind.ExtendsKeyword,[Vt(this.ids.methodPathType,v.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let l=[],c=[];for(let[{method:R,path:A},{isJson:I,tags:me,...Le}]of this.registry){let Ne=Zo(R,A);for(let L of this.interfaces)L.kind in Le&&L.props.push(Ao(Ne,Le[L.kind]));o!=="types"&&(I&&l.push(s.createPropertyAssignment(Ne,s.createTrue())),c.push(s.createPropertyAssignment(Ne,s.createArrayLiteralExpression(me.map(L=>s.createStringLiteral(L))))))}for(let{id:R,props:A}of this.interfaces)this.program.push(wo(R,p,A));if(o==="types")return;let m=s.createVariableStatement(J,W(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(l))),y=s.createVariableStatement(J,W(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),u=ht(this.ids.providerType,s.createFunctionTypeNode(Eo({M:this.ids.methodType,P:this.ids.pathType}),gt({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Gt)}),Io(this.ids.responseInterface,Gt))),x=ht(this.ids.implementationType,s.createFunctionTypeNode(void 0,gt({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(v.default.SyntaxKind.StringKeyword),params:Vt(v.default.SyntaxKind.StringKeyword,v.default.SyntaxKind.AnyKeyword)}),zo())),j=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,we)]),T=Qt(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[j,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),M=Qt(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[j]),v.default.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),C=Co(this.ids.clientClass,Ro([yt(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),Oo)]),[Po(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Yt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,M]),!0))]);this.program.push(m,y,u,x,C);let b=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ze=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(w.json))]),void 0,this.ids.undefinedValue)),G=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),X=s.createVariableStatement(void 0,W(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,we)]),s.createObjectLiteralExpression([b,Ze,G])])))),le=s.createVariableStatement(void 0,W(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ve=s.createVariableStatement(void 0,W(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),we)])))),[Ve,Tt]=["json","text"].map(R=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,R),void 0,void 0))),_e=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(Bt,[s.createTemplateSpan(this.ids.methodParameter,qt),s.createTemplateSpan(this.ids.pathParameter,we)]),v.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Ve])),D=s.createVariableStatement(J,W(this.ids.exampleImplementationConst,Yt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([le,ve,X,_e,Tt]),!0),s.createTypeReferenceNode(this.ids.implementationType))),ee=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),je=s.createVariableStatement(void 0,W(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(D,je,ee)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Wt(r,t)).join(`
21
+ `)};var Xr=e=>{e.startupLogo!==!1&&console.log(Qr());let t=e.errorHandler||Se,r=zr(e.logger)?e.logger:new Oe(e.logger);r.debug("Running","v20.14.2 (CJS)"),_r(r);let o=Vr({rootLogger:r,config:e}),i={getChildLogger:Gr(r),errorHandler:t},a=Br(i),p=Kr(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},eo=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=Xr(e);return Ut({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},to=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Xr(e),p=(0,ct.default)().disable("x-powered-by").use(a);if(e.server.compression){let u=await Ce("compression");p.use(u(typeof e.server.compression=="object"?e.server.compression:void 0))}let l={json:[e.server.jsonParser||ct.default.json()],raw:[e.server.rawParser||ct.default.raw(),$r],upload:e.server.upload?await qr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Ut({app:p,routing:t,getChildLogger:o,config:e,parsers:l}),p.use(i,n);let c=(u,x)=>u.listen(x,()=>r.info("Listening",x)),m=Jr.default.createServer(p),y=e.https&&Wr.default.createServer(e.https.options,p);return e.gracefulShutdown&&Yr({servers:[m].concat(y||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(m,e.server.listen),httpsServer:y&&c(y,e.https?.listen)}};var To=O(require("node:assert/strict"),1),Oo=require("openapi3-ts/oas31"),ft=require("ramda");var Q=O(require("node:assert/strict"),1),q=require("openapi3-ts/oas31"),d=require("ramda"),S=require("zod");var Ie=require("zod");var dt=e=>!isNaN(e.getTime());var Be=Symbol("DateIn"),ro=()=>Ie.z.union([Ie.z.string().date(),Ie.z.string().datetime(),Ie.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ie.z.date().refine(dt)).brand(Be);var oo=require("zod");var qe=Symbol("DateOut"),no=()=>oo.z.date().refine(dt).transform(e=>e.toISOString()).brand(qe);var ce=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[h]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>ce(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),l=t&&t(e,{prev:p,...n});return l?{...p,...l}:p};var so=50,ao="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",sn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},po=/:([A-Za-z0-9_]+)/g,an=e=>e.match(po)?.map(t=>t.slice(1))||[],co=e=>e.replace(po,t=>`{${t.slice(1)}}`),pn=({_def:e},{next:t})=>({...t(e.innerType),default:e[h]?.defaultLabel||e.defaultValue()}),cn=({_def:{innerType:e}},{next:t})=>t(e),dn=()=>({format:"any"}),ln=({},e)=>((0,Q.default)(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),mn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},un=({options:e},{next:t})=>({oneOf:e.map(t)}),fn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),yn=e=>{let[t,r]=e.filter(q.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));(0,Q.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,d.mergeDeepWith)((n,i)=>Array.isArray(n)&&Array.isArray(i)?(0,d.concat)(n,i):n===i?i:Q.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,d.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=re(t.examples||[],r.examples||[],([n,i])=>(0,d.mergeDeepRight)(n,i))),o},gn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return yn(o)}catch{}return{allOf:o}},hn=(e,{next:t})=>t(e.unwrap()),xn=(e,{next:t})=>t(e.unwrap()),bn=(e,{next:t})=>{let r=t(e.unwrap());return(0,q.isSchemaObject)(r)&&(r.type=mo(r)),r},lo=e=>{let t=(0,d.toLower)((0,d.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},io=e=>({type:lo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Sn=({value:e})=>({type:lo(e),const:e}),Tn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Ue(p)?p instanceof S.z.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=lt(e,r)),i.length&&(a.required=i),a},On=()=>({type:"null"}),Rn=({},e)=>((0,Q.default)(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"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?$/.source,externalDocs:{url:ao}}),An=({},e)=>((0,Q.default)(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:ao}}),Pn=({},e)=>Q.default.fail(new z({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),Cn=()=>({type:"boolean"}),In=()=>({type:"integer",format:"bigint"}),zn=e=>e.every(t=>t instanceof S.z.ZodLiteral),wn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.z.ZodEnum||e instanceof S.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=lt(S.z.object((0,d.fromPairs)((0,d.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof S.z.ZodLiteral)return{type:"object",properties:lt(S.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.z.ZodUnion&&zn(e.options)){let o=(0,d.map)(i=>`${i.value}`,e.options),n=(0,d.fromPairs)((0,d.xprod)(o,[t]));return{type:"object",properties:lt(S.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},En=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Zn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),vn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:l,isEmoji:c,isDatetime:m,_def:{checks:y}})=>{let u=y.find(C=>C.kind==="regex"),x=y.find(C=>C.kind==="datetime"),j=u?u.regex:x?x.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,T={type:"string"},M={"date-time":m,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:l,emoji:c};for(let C in M)if(M[C]){T.format=C;break}return r!==null&&(T.minLength=r),o!==null&&(T.maxLength=o),j&&(T.pattern=j.source),T},jn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(y=>y.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(y=>y.kind==="max"),l=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=i:m.exclusiveMinimum=i,c?m.maximum=l:m.exclusiveMaximum=l,m},lt=({shape:e},t)=>(0,d.map)(t,e),Ln=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return sn?.[t]},mo=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},Nn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,q.isSchemaObject)(o)){let i=We(e,Ln(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.z.any())}if(!t&&n.type==="preprocess"&&(0,q.isSchemaObject)(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},kn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Mn=(e,{next:t})=>t(e.unwrap()),Un=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},Hn=(e,{next:t})=>t(e.unwrap().shape.raw),uo=e=>e.length?(0,d.fromPairs)((0,d.zip)((0,d.range)(1,e.length+1).map(t=>`example${t}`),(0,d.map)((0,d.objOf)("value"),e))):void 0,fo=(e,t,r=[])=>(0,d.pipe)(K,(0,d.map)((0,d.when)(o=>(0,d.type)(o)==="Object",(0,d.omit)(r))),uo)({schema:e,variant:t?"parsed":"original",validate:!0}),Dn=(e,t)=>(0,d.pipe)(K,(0,d.filter)((0,d.has)(t)),(0,d.pluck)(t),uo)({schema:e,variant:"original",validate:!0}),de=e=>e instanceof S.z.ZodObject?e:e instanceof S.z.ZodBranded?de(e.unwrap()):e instanceof S.z.ZodUnion||e instanceof S.z.ZodDiscriminatedUnion?e.options.map(t=>de(t)).reduce((t,r)=>t.merge(r.partial()),S.z.object({})):e instanceof S.z.ZodEffects?de(e._def.schema):e instanceof S.z.ZodPipeline?de(e._def.in):de(e._def.left).merge(de(e._def.right)),yo=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:l,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=de(r),y=an(e),u=o.includes("query"),x=o.includes("params"),j=o.includes("headers"),T=b=>x&&y.includes(b),M=b=>j&&Pt(b);return Object.keys(m).map(b=>({name:b,location:T(b)?"path":M(b)?"header":u?"query":void 0})).filter(b=>b.location!==void 0).map(({name:b,location:Ze})=>{let V=ce(m[b],{rules:{...l,...Dt},onEach:Ft,onMissing:Kt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),X=p==="components"?a(N(c,b),V):V;return{name:b,in:Ze,required:!m[b].isOptional(),description:V.description||c,schema:X,examples:Dn(r,b)}})},Dt={ZodString:vn,ZodNumber:jn,ZodBigInt:In,ZodBoolean:Cn,ZodNull:On,ZodArray:En,ZodTuple:Zn,ZodRecord:wn,ZodObject:Tn,ZodLiteral:Sn,ZodIntersection:gn,ZodUnion:un,ZodAny:dn,ZodDefault:pn,ZodEnum:io,ZodNativeEnum:io,ZodEffects:Nn,ZodOptional:hn,ZodNullable:bn,ZodDiscriminatedUnion:fn,ZodBranded:Mn,ZodDate:Pn,ZodCatch:cn,ZodPipeline:kn,ZodLazy:Un,ZodReadonly:xn,[Y]:mn,[De]:ln,[qe]:An,[Be]:Rn,[se]:Hn},Ft=(e,{isResponse:t,prev:r})=>{if((0,q.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof S.z.ZodLazy,i=r.type!==void 0,a=t&&Ue(e),p=!n&&i&&!a&&e.isNullable(),l=n?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=mo(r)),l.length&&(c.examples=l.slice()),c},Kt=(e,t)=>Q.default.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Ht=(e,t)=>{if((0,q.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,d.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,d.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Ht(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Ht(o,t))),r},go=e=>(0,q.isReferenceObject)(e)?e:(0,d.omit)(["examples"],e),ho=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:l,hasMultipleStatusCodes:c,statusCode:m,brandHandling:y,description:u=`${e.toUpperCase()} ${t} ${zt(n)} response ${c?m:""}`.trim()})=>{let x=go(ce(r,{rules:{...y,...Dt},onEach:Ft,onMissing:Kt,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),j={schema:l==="components"?p(N(u),x):x,examples:fo(r,!0)};return{description:u,content:(0,d.fromPairs)((0,d.xprod)(o,[j]))}},Fn=()=>({type:"http",scheme:"basic"}),Kn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Bn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},qn=({name:e})=>({type:"apiKey",in:"header",name:e}),$n=({name:e})=>({type:"apiKey",in:"cookie",name:e}),Vn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),Gn=({flows:e={}})=>({type:"oauth2",flows:(0,d.map)(t=>({...t,scopes:t.scopes||{}}),(0,d.reject)(d.isNil,e))}),xo=(e,t)=>{let r={basic:Fn,bearer:Kn,input:Bn,header:qn,cookie:$n,openid:Vn,oauth2:Gn};return ot(e,o=>r[o.type](o,t))},mt=e=>"or"in e?e.or.map(t=>"and"in t?(0,d.mergeAll)((0,d.map)(({name:r,scopes:o})=>(0,d.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?mt(Zt(e)):mt({or:[e]}),bo=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:l,paramNames:c,description:m=`${e.toUpperCase()} ${t} Request body`})=>{let y=go(Ht(ce(r,{rules:{...l,...Dt},onEach:Ft,onMissing:Kt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),u={schema:p==="components"?a(N(m),y):y,examples:fo(r,!1,c)};return{description:m,content:(0,d.fromPairs)((0,d.xprod)(o,[u]))}},So=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Bt=e=>e.length<=so?e:e.slice(0,so-1)+"\u2026";var ut=class extends Oo.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=(0,ft.keys)(ae);makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||N(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&To.default.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:l=!0,composition:c="inline",serializer:m=Je}){super(),this.addInfo({title:o,version:n});for(let u of typeof i=="string"?[i]:i)this.addServer({url:u});pe({routing:t,onEndpoint:(u,x,j)=>{let T=j,M={path:x,method:T,endpoint:u,composition:c,serializer:m,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[C,b]=["short","long"].map(u.getDescription.bind(u)),Ze=C?Bt(C):l&&b?Bt(b):void 0,V=u.getTags(),X=r.inputSources?.[T]||Rt[T],me=this.ensureUniqOperationId(x,T,u.getOperationId(T)),ve=yo({...M,inputSources:X,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:x,operationId:me})}),Ve={};for(let D of this.responseVariants){let ee=u.getResponses(D);for(let{mimeTypes:je,schema:R,statusCodes:A}of ee)for(let I of A)Ve[I]=ho({...M,variant:D,schema:R,mimeTypes:je,statusCode:I,hasMultipleStatusCodes:ee.length>1||A.length>1,description:a?.[`${D}Response`]?.call(null,{method:T,path:x,operationId:me,statusCode:I})})}let Ot=X.includes("body")?bo({...M,paramNames:(0,ft.pluck)("name",ve),schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:x,operationId:me})}):void 0,Ge=mt(ot(xo(u.getSecurity(),X),D=>{let ee=this.ensureUniqSecuritySchemaName(D),je=["oauth2","openIdConnect"].includes(D.type)?u.getScopes().slice():[];return this.addSecurityScheme(ee,D),{name:ee,scopes:je}}));this.addPath(co(x),{[T]:{operationId:me,summary:Ze,description:b,tags:V.length>0?V:void 0,parameters:ve.length>0?ve:void 0,requestBody:Ot,security:Ge.length>0?Ge:void 0,responses:Ve}})}}),this.rootDoc.tags=r.tags?So(r.tags):[]}};var yt=require("node-mocks-http"),_n=e=>(0,yt.createRequest)({...e,headers:{"content-type":w.json,...e?.headers}}),Yn=e=>(0,yt.createResponse)(e),Qn=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:wr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Jn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=_n(e),i=Yn({req:n,...t});i.req=t?.req||n,n.res=i;let a=Qn(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},Ro=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Jn(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}};var v=O(require("typescript"),1);var H=O(require("typescript"),1),ze=require("ramda"),s=H.default.factory,J=[s.createModifier(H.default.SyntaxKind.ExportKeyword)],Wn=[s.createModifier(H.default.SyntaxKind.AsyncKeyword)],Xn=[s.createModifier(H.default.SyntaxKind.PublicKeyword),s.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],Ao=[s.createModifier(H.default.SyntaxKind.ProtectedKeyword),s.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],qt=s.createTemplateHead(""),we=s.createTemplateTail(""),$t=s.createTemplateMiddle(" "),Vt=e=>s.createTemplateLiteralType(qt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?we:$t))),Gt=Vt(["M","P"]),gt=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),ht=(e,t)=>(0,ze.chain)(([r,o])=>[gt(s.createIdentifier(r),o,t)],(0,ze.toPairs)(e)),_t=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),Po=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),Co=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),W=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],H.default.NodeFlags.Const),Yt=(e,t)=>s.createTypeAliasDeclaration(J,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),xt=(e,t)=>s.createTypeAliasDeclaration(J,e,void 0,t),Io=(e,t,r)=>s.createPropertyDeclaration(Xn,e,void 0,t,r),zo=(e,t,r)=>s.createClassDeclaration(J,e,void 0,void 0,[t,...r]),wo=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),Eo=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(H.default.SyntaxKind.AnyKeyword)]),Zo=(e,t,r)=>s.createInterfaceDeclaration(J,e,void 0,t,r),es=(0,ze.chain)(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),vo=e=>es((0,ze.toPairs)(e)),Qt=(e,t,r)=>s.createArrowFunction(r?Wn:void 0,void 0,e.map(o=>gt(o)),void 0,void 0,t),Jt=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,ht({acc:void 0,key:void 0}),void 0,void 0,t),r]),jo=(...e)=>`"${e.join(" ")}"`;var Lo=["get","post","put","delete","patch"];var g=O(require("typescript"),1),St=require("zod");var $=O(require("typescript"),1),{factory:bt}=$.default,Wt=(e,t)=>{$.default.addSyntheticLeadingComment(e,$.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ee=(e,t,r)=>{let o=bt.createTypeAliasDeclaration(void 0,bt.createIdentifier(t),void 0,e);return r&&Wt(o,r),o},Xt=(e,t)=>{let r=$.default.createSourceFile("print.ts","",$.default.ScriptTarget.Latest,!1,$.default.ScriptKind.TS);return $.default.createPrinter(t).printNode($.default.EmitHint.Unspecified,e,r)},ts=/^[A-Za-z_$][A-Za-z0-9_$]*$/,No=e=>ts.test(e)?bt.createIdentifier(e):bt.createStringLiteral(e);var{factory:f}=g.default,rs={[g.default.SyntaxKind.AnyKeyword]:"",[g.default.SyntaxKind.BigIntKeyword]:BigInt(0),[g.default.SyntaxKind.BooleanKeyword]:!1,[g.default.SyntaxKind.NumberKeyword]:0,[g.default.SyntaxKind.ObjectKeyword]:{},[g.default.SyntaxKind.StringKeyword]:"",[g.default.SyntaxKind.UndefinedKeyword]:void 0},os=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),ns=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Ue(a)?a instanceof St.z.ZodOptional:a.isOptional(),l=f.createPropertySignature(void 0,No(i),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Wt(l,a.description),l});return f.createTypeLiteralNode(n)},ss=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),is=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),ko=({options:e},{next:t})=>f.createUnionTypeNode(e.map(t)),as=e=>rs?.[e.kind],ps=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=We(e,as(o)),i={number:g.default.SyntaxKind.NumberKeyword,bigint:g.default.SyntaxKind.BigIntKeyword,boolean:g.default.SyntaxKind.BooleanKeyword,string:g.default.SyntaxKind.StringKeyword,undefined:g.default.SyntaxKind.UndefinedKeyword,object:g.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(n&&i[n]||g.default.SyntaxKind.AnyKeyword)}return o},cs=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),ds=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},ls=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),ms=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),us=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),fs=({_def:e},{next:t})=>f.createIntersectionTypeNode([e.left,e.right].map(t)),ys=({_def:e},{next:t})=>t(e.innerType),le=e=>()=>f.createKeywordTypeNode(e),gs=(e,{next:t})=>t(e.unwrap()),hs=(e,{next:t})=>t(e.unwrap()),xs=({_def:e},{next:t})=>t(e.innerType),bs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Ss=()=>f.createLiteralTypeNode(f.createNull()),Ts=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,f.createLiteralTypeNode(f.createNull())),r(i,o(e)))},Os=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),n=f.createUnionTypeNode([r,o]);return t instanceof St.z.ZodString?r:t instanceof St.z.ZodUnion?n:o},Rs=(e,{next:t})=>t(e.unwrap().shape.raw),As={ZodString:le(g.default.SyntaxKind.StringKeyword),ZodNumber:le(g.default.SyntaxKind.NumberKeyword),ZodBigInt:le(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:le(g.default.SyntaxKind.BooleanKeyword),ZodAny:le(g.default.SyntaxKind.AnyKeyword),[Be]:le(g.default.SyntaxKind.StringKeyword),[qe]:le(g.default.SyntaxKind.StringKeyword),ZodNull:Ss,ZodArray:ss,ZodTuple:ms,ZodRecord:us,ZodObject:ns,ZodLiteral:os,ZodIntersection:fs,ZodUnion:ko,ZodDefault:ys,ZodEnum:is,ZodNativeEnum:cs,ZodEffects:ps,ZodOptional:ds,ZodNullable:ls,ZodDiscriminatedUnion:ko,ZodBranded:gs,ZodCatch:xs,ZodPipeline:bs,ZodLazy:Ts,ZodReadonly:hs,[Y]:Os,[se]:Rs},$e=(e,{brandHandling:t,ctx:r})=>ce(e,{rules:{...t,...As},onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),ctx:r});var Tt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Ee(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=Je,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){pe({routing:t,onEndpoint:(R,A,I)=>{let ue={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},Le=N(I,A,"input"),Ne=$e(R.getSchema("input"),{brandHandling:r,ctx:{...ue,isResponse:!1}}),L=i?N(I,A,"positive.response"):void 0,er=R.getSchema("positive"),tr=i?$e(er,{brandHandling:r,ctx:{...ue,isResponse:!0}}):void 0,ke=i?N(I,A,"negative.response"):void 0,rr=R.getSchema("negative"),or=i?$e(rr,{brandHandling:r,ctx:{...ue,isResponse:!0}}):void 0,nr=N(I,A,"response"),Uo=L&&ke?s.createUnionTypeNode([s.createTypeReferenceNode(L),s.createTypeReferenceNode(ke)]):$e(er.or(rr),{brandHandling:r,ctx:{...ue,isResponse:!0}});this.program.push(Ee(Ne,Le)),tr&&L&&this.program.push(Ee(tr,L)),or&&ke&&this.program.push(Ee(or,ke)),this.program.push(Ee(Uo,nr)),I!=="options"&&(this.paths.push(A),this.registry.set({method:I,path:A},{input:Le,positive:L,negative:ke,response:nr,isJson:R.getMimeTypes("positive").includes(w.json),tags:R.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(Yt(this.ids.pathType,this.paths)),this.program.push(Yt(this.ids.methodType,Lo)),this.program.push(xt(this.ids.methodPathType,Vt([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(v.default.SyntaxKind.ExtendsKeyword,[_t(this.ids.methodPathType,v.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let l=[],c=[];for(let[{method:R,path:A},{isJson:I,tags:ue,...Le}]of this.registry){let Ne=jo(R,A);for(let L of this.interfaces)L.kind in Le&&L.props.push(Co(Ne,Le[L.kind]));o!=="types"&&(I&&l.push(s.createPropertyAssignment(Ne,s.createTrue())),c.push(s.createPropertyAssignment(Ne,s.createArrayLiteralExpression(ue.map(L=>s.createStringLiteral(L))))))}for(let{id:R,props:A}of this.interfaces)this.program.push(Zo(R,p,A));if(o==="types")return;let m=s.createVariableStatement(J,W(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(l))),y=s.createVariableStatement(J,W(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),u=xt(this.ids.providerType,s.createFunctionTypeNode(vo({M:this.ids.methodType,P:this.ids.pathType}),ht({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Gt)}),wo(this.ids.responseInterface,Gt))),x=xt(this.ids.implementationType,s.createFunctionTypeNode(void 0,ht({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(v.default.SyntaxKind.StringKeyword),params:_t(v.default.SyntaxKind.StringKeyword,v.default.SyntaxKind.AnyKeyword)}),Eo())),j=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,we)]),T=Jt(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[j,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),M=Jt(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[j]),v.default.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),C=zo(this.ids.clientClass,Po([gt(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),Ao)]),[Io(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,M]),!0))]);this.program.push(m,y,u,x,C);let b=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ze=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(w.json))]),void 0,this.ids.undefinedValue)),V=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),X=s.createVariableStatement(void 0,W(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,we)]),s.createObjectLiteralExpression([b,Ze,V])])))),me=s.createVariableStatement(void 0,W(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ve=s.createVariableStatement(void 0,W(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),we)])))),[Ve,Ot]=["json","text"].map(R=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,R),void 0,void 0))),Ge=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(qt,[s.createTemplateSpan(this.ids.methodParameter,$t),s.createTemplateSpan(this.ids.pathParameter,we)]),v.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Ve])),D=s.createVariableStatement(J,W(this.ids.exampleImplementationConst,Qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([me,ve,X,Ge,Ot]),!0),s.createTypeReferenceNode(this.ids.implementationType))),ee=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),je=s.createVariableStatement(void 0,W(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(D,je,ee)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Xt(r,t)).join(`
22
22
  `):void 0}print(t){let r=this.printUsage(t),o=r&&v.default.addSyntheticLeadingComment(v.default.addSyntheticLeadingComment(s.createEmptyStatement(),v.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),v.default.SyntaxKind.MultiLineCommentTrivia,`
23
- ${r}`);return this.program.concat(o||[]).map((n,i)=>Wt(n,i<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
23
+ ${r}`);return this.program.concat(o||[]).map((n,i)=>Xt(n,i<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
24
24
 
25
- `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await Ce("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let i=this.print(t);return o?o(i):i}};var No={dateIn:Xr,dateOut:to,file:rt,upload:fr,raw:mr};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ez,getExamples,getMessageFromError,getStatusCodeFromError,testEndpoint});
25
+ `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await Ce("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let i=this.print(t);return o?o(i):i}};var Mo={dateIn:ro,dateOut:no,file:tt,upload:yr,raw:ur};0&&(module.exports={BuiltinLogger,DependsOnMethod,Documentation,DocumentationError,EndpointsFactory,InputValidationError,Integration,Middleware,MissingPeerError,OutputValidationError,ResultHandler,RoutingError,ServeStatic,arrayEndpointsFactory,arrayResultHandler,attachRouting,createConfig,createServer,defaultEndpointsFactory,defaultResultHandler,ez,getExamples,getMessageFromError,getStatusCodeFromError,testEndpoint});
package/dist/index.d.cts CHANGED
@@ -16,8 +16,15 @@ import * as node_mocks_http from 'node-mocks-http';
16
16
  import { RequestOptions, ResponseOptions } from 'node-mocks-http';
17
17
  import ts from 'typescript';
18
18
 
19
+ declare const severity: {
20
+ debug: number;
21
+ info: number;
22
+ warn: number;
23
+ error: number;
24
+ };
25
+ type Severity = keyof typeof severity;
19
26
  /** @desc You can use any logger compatible with this type. */
20
- type AbstractLogger = Record<"info" | "debug" | "warn" | "error", (message: string, meta?: any) => any>;
27
+ type AbstractLogger = Record<Severity, (message: string, meta?: any) => any>;
21
28
  /**
22
29
  * @desc Using module augmentation approach you can set the type of the actual logger used
23
30
  * @example declare module "express-zod-api" { interface LoggerOverrides extends winston.Logger {} }
@@ -57,7 +64,7 @@ interface BuiltinLoggerConfig {
57
64
  interface ProfilerOptions {
58
65
  message: string;
59
66
  /** @default "debug" */
60
- severity?: keyof AbstractLogger | ((ms: number) => keyof AbstractLogger);
67
+ severity?: Severity | ((ms: number) => Severity);
61
68
  /** @default formatDuration - adaptive units and limited fraction */
62
69
  formatter?: (ms: number) => string | number;
63
70
  }
@@ -65,11 +72,11 @@ interface ProfilerOptions {
65
72
  declare class BuiltinLogger implements AbstractLogger {
66
73
  protected config: BuiltinLoggerConfig;
67
74
  protected hasColor: boolean;
68
- protected readonly styles: Record<keyof AbstractLogger, Ansis>;
75
+ protected readonly styles: Record<Severity, Ansis>;
69
76
  /** @example new BuiltinLogger({ level: "debug", color: true, depth: 4 }) */
70
77
  constructor(config: BuiltinLoggerConfig);
71
78
  protected prettyPrint(subject: unknown): string;
72
- protected print(method: keyof AbstractLogger, message: string, meta?: unknown): void;
79
+ protected print(method: Severity, message: string, meta?: unknown): void;
73
80
  debug(message: string, meta?: unknown): void;
74
81
  info(message: string, meta?: unknown): void;
75
82
  warn(message: string, meta?: unknown): void;
@@ -80,6 +87,11 @@ declare class BuiltinLogger implements AbstractLogger {
80
87
  profile(options: ProfilerOptions): () => void;
81
88
  }
82
89
 
90
+ declare const defaultStatusCodes: {
91
+ positive: number;
92
+ negative: number;
93
+ };
94
+ type ResponseVariant = keyof typeof defaultStatusCodes;
83
95
  interface ApiResponse<S extends z.ZodTypeAny> {
84
96
  schema: S;
85
97
  /**
@@ -340,7 +352,6 @@ type Handler<IN, OUT, OPT> = (params: {
340
352
  }) => Promise<OUT>;
341
353
  type DescriptionVariant = "short" | "long";
342
354
  type IOVariant = "input" | "output";
343
- type ResponseVariant = "positive" | "negative";
344
355
  type MimeVariant = Extract<IOVariant, "input"> | ResponseVariant;
345
356
  declare abstract class AbstractEndpoint {
346
357
  abstract execute(params: {
@@ -747,7 +758,7 @@ interface NextHandlerInc<U> {
747
758
  interface PrevInc<U> {
748
759
  prev: U;
749
760
  }
750
- type SchemaHandler<U, Context extends FlatObject = EmptyObject, Variant extends "regular" | "each" | "last" = "regular"> = (schema: any, // eslint-disable-line @typescript-eslint/no-explicit-any -- for assignmet compatibility
761
+ type SchemaHandler<U, Context extends FlatObject = EmptyObject, Variant extends "regular" | "each" | "last" = "regular"> = (schema: any, // eslint-disable-line @typescript-eslint/no-explicit-any -- for assignment compatibility
751
762
  ctx: Context & (Variant extends "regular" ? NextHandlerInc<U> : Variant extends "each" ? PrevInc<U> : Context)) => U;
752
763
  type HandlingRules<U, Context extends FlatObject = EmptyObject, K extends string | symbol = string | symbol> = Partial<Record<K, SchemaHandler<U, Context>>>;
753
764
 
@@ -798,6 +809,7 @@ interface DocumentationParams {
798
809
  declare class Documentation extends OpenApiBuilder {
799
810
  protected lastSecuritySchemaIds: Map<SecuritySchemeType, number>;
800
811
  protected lastOperationIdSuffixes: Map<string, number>;
812
+ protected responseVariants: ("positive" | "negative")[];
801
813
  protected makeRef(name: string, schema: SchemaObject | ReferenceObject): ReferenceObject;
802
814
  protected getRef(name: string): ReferenceObject | undefined;
803
815
  protected ensureUniqOperationId(path: string, method: Method, userDefined?: string): string;
@@ -881,7 +893,7 @@ declare const testEndpoint: <LOG extends FlatObject, REQ extends RequestOptions>
881
893
  } & REQ;
882
894
  responseMock: node_mocks_http.MockResponse<Response<any, Record<string, any>>>;
883
895
  loggerMock: AbstractLogger & LOG & {
884
- _getLogs: () => Record<"info" | "debug" | "warn" | "error", unknown[]>;
896
+ _getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
885
897
  };
886
898
  }>;
887
899
 
@@ -897,7 +909,7 @@ interface ZTSContext extends FlatObject {
897
909
  }
898
910
  type Producer = SchemaHandler<ts.TypeNode, ZTSContext>;
899
911
 
900
- type IOKind = "input" | "response" | "positive" | "negative";
912
+ type IOKind = "input" | "response" | ResponseVariant;
901
913
  interface IntegrationParams {
902
914
  routing: Routing;
903
915
  /**
@@ -908,7 +920,7 @@ interface IntegrationParams {
908
920
  * */
909
921
  variant?: "types" | "client";
910
922
  /**
911
- * @desc Declares positive and negative response types separately and provides them within additional dictoinaries
923
+ * @desc Declares positive and negative response types separately and provides them within additional dictionaries
912
924
  * @default false
913
925
  * */
914
926
  splitResponse?: boolean;
package/dist/index.d.ts CHANGED
@@ -16,8 +16,15 @@ import * as node_mocks_http from 'node-mocks-http';
16
16
  import { RequestOptions, ResponseOptions } from 'node-mocks-http';
17
17
  import ts from 'typescript';
18
18
 
19
+ declare const severity: {
20
+ debug: number;
21
+ info: number;
22
+ warn: number;
23
+ error: number;
24
+ };
25
+ type Severity = keyof typeof severity;
19
26
  /** @desc You can use any logger compatible with this type. */
20
- type AbstractLogger = Record<"info" | "debug" | "warn" | "error", (message: string, meta?: any) => any>;
27
+ type AbstractLogger = Record<Severity, (message: string, meta?: any) => any>;
21
28
  /**
22
29
  * @desc Using module augmentation approach you can set the type of the actual logger used
23
30
  * @example declare module "express-zod-api" { interface LoggerOverrides extends winston.Logger {} }
@@ -57,7 +64,7 @@ interface BuiltinLoggerConfig {
57
64
  interface ProfilerOptions {
58
65
  message: string;
59
66
  /** @default "debug" */
60
- severity?: keyof AbstractLogger | ((ms: number) => keyof AbstractLogger);
67
+ severity?: Severity | ((ms: number) => Severity);
61
68
  /** @default formatDuration - adaptive units and limited fraction */
62
69
  formatter?: (ms: number) => string | number;
63
70
  }
@@ -65,11 +72,11 @@ interface ProfilerOptions {
65
72
  declare class BuiltinLogger implements AbstractLogger {
66
73
  protected config: BuiltinLoggerConfig;
67
74
  protected hasColor: boolean;
68
- protected readonly styles: Record<keyof AbstractLogger, Ansis>;
75
+ protected readonly styles: Record<Severity, Ansis>;
69
76
  /** @example new BuiltinLogger({ level: "debug", color: true, depth: 4 }) */
70
77
  constructor(config: BuiltinLoggerConfig);
71
78
  protected prettyPrint(subject: unknown): string;
72
- protected print(method: keyof AbstractLogger, message: string, meta?: unknown): void;
79
+ protected print(method: Severity, message: string, meta?: unknown): void;
73
80
  debug(message: string, meta?: unknown): void;
74
81
  info(message: string, meta?: unknown): void;
75
82
  warn(message: string, meta?: unknown): void;
@@ -80,6 +87,11 @@ declare class BuiltinLogger implements AbstractLogger {
80
87
  profile(options: ProfilerOptions): () => void;
81
88
  }
82
89
 
90
+ declare const defaultStatusCodes: {
91
+ positive: number;
92
+ negative: number;
93
+ };
94
+ type ResponseVariant = keyof typeof defaultStatusCodes;
83
95
  interface ApiResponse<S extends z.ZodTypeAny> {
84
96
  schema: S;
85
97
  /**
@@ -340,7 +352,6 @@ type Handler<IN, OUT, OPT> = (params: {
340
352
  }) => Promise<OUT>;
341
353
  type DescriptionVariant = "short" | "long";
342
354
  type IOVariant = "input" | "output";
343
- type ResponseVariant = "positive" | "negative";
344
355
  type MimeVariant = Extract<IOVariant, "input"> | ResponseVariant;
345
356
  declare abstract class AbstractEndpoint {
346
357
  abstract execute(params: {
@@ -747,7 +758,7 @@ interface NextHandlerInc<U> {
747
758
  interface PrevInc<U> {
748
759
  prev: U;
749
760
  }
750
- type SchemaHandler<U, Context extends FlatObject = EmptyObject, Variant extends "regular" | "each" | "last" = "regular"> = (schema: any, // eslint-disable-line @typescript-eslint/no-explicit-any -- for assignmet compatibility
761
+ type SchemaHandler<U, Context extends FlatObject = EmptyObject, Variant extends "regular" | "each" | "last" = "regular"> = (schema: any, // eslint-disable-line @typescript-eslint/no-explicit-any -- for assignment compatibility
751
762
  ctx: Context & (Variant extends "regular" ? NextHandlerInc<U> : Variant extends "each" ? PrevInc<U> : Context)) => U;
752
763
  type HandlingRules<U, Context extends FlatObject = EmptyObject, K extends string | symbol = string | symbol> = Partial<Record<K, SchemaHandler<U, Context>>>;
753
764
 
@@ -798,6 +809,7 @@ interface DocumentationParams {
798
809
  declare class Documentation extends OpenApiBuilder {
799
810
  protected lastSecuritySchemaIds: Map<SecuritySchemeType, number>;
800
811
  protected lastOperationIdSuffixes: Map<string, number>;
812
+ protected responseVariants: ("positive" | "negative")[];
801
813
  protected makeRef(name: string, schema: SchemaObject | ReferenceObject): ReferenceObject;
802
814
  protected getRef(name: string): ReferenceObject | undefined;
803
815
  protected ensureUniqOperationId(path: string, method: Method, userDefined?: string): string;
@@ -881,7 +893,7 @@ declare const testEndpoint: <LOG extends FlatObject, REQ extends RequestOptions>
881
893
  } & REQ;
882
894
  responseMock: node_mocks_http.MockResponse<Response<any, Record<string, any>>>;
883
895
  loggerMock: AbstractLogger & LOG & {
884
- _getLogs: () => Record<"info" | "debug" | "warn" | "error", unknown[]>;
896
+ _getLogs: () => Record<"debug" | "info" | "warn" | "error", unknown[]>;
885
897
  };
886
898
  }>;
887
899
 
@@ -897,7 +909,7 @@ interface ZTSContext extends FlatObject {
897
909
  }
898
910
  type Producer = SchemaHandler<ts.TypeNode, ZTSContext>;
899
911
 
900
- type IOKind = "input" | "response" | "positive" | "negative";
912
+ type IOKind = "input" | "response" | ResponseVariant;
901
913
  interface IntegrationParams {
902
914
  routing: Routing;
903
915
  /**
@@ -908,7 +920,7 @@ interface IntegrationParams {
908
920
  * */
909
921
  variant?: "types" | "client";
910
922
  /**
911
- * @desc Declares positive and negative response types separately and provides them within additional dictoinaries
923
+ * @desc Declares positive and negative response types separately and provides them within additional dictionaries
912
924
  * @default false
913
925
  * */
914
926
  splitResponse?: boolean;
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import{clone as Yt,fromPairs as Ro,map as Ao,pipe as Po,toPairs as Co,pair as Io}from"ramda";import{z as ae}from"zod";import{isHttpError as uo}from"http-errors";import{createHash as fo}from"node:crypto";import{pickBy as yo,xprod as go}from"ramda";import{z as ho}from"zod";var se=class extends Error{name="RoutingError"},z=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:n}){let i=`${t}
2
- Caused by ${n?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(i)}},De=class extends Error{name="IOSchemaError"},V=class extends De{constructor(r){super(U(r));this.originalError=r}name="OutputValidationError"},L=class extends De{constructor(r){super(U(r));this.originalError=r}name="InputValidationError"},M=class extends Error{constructor(r,o){super(r);this.originalError=o}name="ResultHandlerError"},Oe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var P={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var xo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(P.upload);return"files"in e&&r},dt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},bo=["body","query","params"],lt=e=>e.method.toLowerCase(),mt=e=>e.startsWith("x-"),So=e=>yo((t,r)=>mt(r),e),ut=(e,t={})=>{let r=lt(e);return r==="options"?{}:(t[r]||dt[r]||bo).filter(o=>o==="files"?xo(e):!0).map(o=>o==="headers"?So(e[o]):e[o]).reduce((o,n)=>({...o,...n}),{})},ie=e=>e instanceof Error?e:new Error(String(e)),U=e=>e instanceof ho.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof V?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,Fe=e=>uo(e)?e.statusCode:e instanceof L?400:500,ft=({logger:e,request:t,input:r,error:o,statusCode:n})=>{n===500&&e.error(`Internal server error
1
+ import{clone as Yt,fromPairs as Po,map as Co,pipe as Io,toPairs as zo,pair as wo}from"ramda";import{z as pe}from"zod";import{isHttpError as yo}from"http-errors";import{createHash as go}from"node:crypto";import{pickBy as ho,xprod as xo}from"ramda";import{z as bo}from"zod";var ie=class extends Error{name="RoutingError"},z=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:n}){let i=`${t}
2
+ Caused by ${n?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(i)}},He=class extends Error{name="IOSchemaError"},G=class extends He{constructor(r){super(U(r));this.originalError=r}name="OutputValidationError"},L=class extends He{constructor(r){super(U(r));this.originalError=r}name="InputValidationError"},M=class extends Error{constructor(r,o){super(r);this.originalError=o}name="ResultHandlerError"},Oe=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};var P={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var So=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(P.upload);return"files"in e&&r},dt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},To=["body","query","params"],lt=e=>e.method.toLowerCase(),mt=e=>e.startsWith("x-"),Oo=e=>ho((t,r)=>mt(r),e),ut=(e,t={})=>{let r=lt(e);return r==="options"?{}:(t[r]||dt[r]||To).filter(o=>o==="files"?So(e):!0).map(o=>o==="headers"?Oo(e[o]):e[o]).reduce((o,n)=>({...o,...n}),{})},ae=e=>e instanceof Error?e:new Error(String(e)),U=e=>e instanceof bo.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof G?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,De=e=>yo(e)?e.statusCode:e instanceof L?400:500,ft=({logger:e,request:t,input:r,error:o,statusCode:n})=>{n===500&&e.error(`Internal server error
3
3
  ${o.stack}
4
- `,{url:t.url,payload:r})},H=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let n=[];for(let i of o){let a=e.safeParse(i);a.success&&n.push(t==="parsed"?a.data:i)}return n},_=(e,t,r)=>e.length&&t.length?go(e,t).map(r):e.concat(t),Re=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,yt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),w=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(yt).join(""),Ke=e=>fo("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Be=(e,t)=>{try{return typeof e.parse(t)}catch{return}},Y=e=>typeof e=="object"&&e!==null;import{clone as To,mergeDeepRight as Oo}from"ramda";var g=Symbol.for("express-zod-api"),qe=e=>{let t=e.describe(e.description);return t._def[g]=To(t._def[g])||{examples:[]},t},_t=(e,t)=>{if(!(g in e._def))return t;let r=qe(t);return r._def[g].examples=_(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?Oo({...o},{...n}):n),r};var zo=function(e){let t=qe(this);return t._def[g].examples.push(e),t},wo=function(e){let t=qe(this);return t._def[g].defaultLabel=e,t},Eo=function(e){return new ae.ZodBranded({typeName:ae.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...Yt(this._def[g]),brand:e}})},Zo=function(e){let t=typeof e=="function"?e:Po(Co,Ao(([n,i])=>Io(e[String(n)]||n,i)),Ro),r=t(Yt(this.shape)),o=ae.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(ae.ZodType.prototype,{example:{get(){return zo.bind(this)}},brand:{set(){},get(){return Eo.bind(this)}}}),Object.defineProperty(ae.ZodDefault.prototype,"label",{get(){return wo.bind(this)}}),Object.defineProperty(ae.ZodObject.prototype,"remap",{get(){return Zo.bind(this)}}));function vo(e){return e}import{z as Fo}from"zod";import{z as nr}from"zod";import{z as Lo}from"zod";import{z as $e}from"zod";var D=Symbol("File"),Qt=$e.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),jo={buffer:()=>Qt.brand(D),string:()=>$e.string().brand(D),binary:()=>Qt.or($e.string()).brand(D),base64:()=>$e.string().base64().brand(D)};function Ge(e){return jo[e||"string"]()}var Q=Symbol("Raw"),Jt=(e={})=>Lo.object({raw:Ge("buffer")}).extend(e).brand(Q);import{z as No}from"zod";var Ae=Symbol("Upload"),Wt=()=>No.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Ae);var Xt=(e,{next:t})=>e.options.some(t),ko=({_def:e},{next:t})=>[e.left,e.right].some(t),er=(e,{next:t})=>t(e.unwrap()),Mo={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Xt,ZodDiscriminatedUnion:Xt,ZodIntersection:ko,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:er,ZodNullable:er,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},gt=(e,{condition:t,rules:r=Mo,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let i=o<n?r[e._def.typeName]:void 0;return i?i(e,{next:a=>gt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},tr=e=>gt(e,{condition:t=>t._def[g]?.brand===Ae}),rr=e=>gt(e,{condition:t=>t._def[g]?.brand===Q,maxDepth:3});var Ve=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).type("text/plain").end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
5
- Original error: ${e.originalError.message}.`:""))};import{chain as Uo}from"ramda";var J=e=>Y(e)&&"or"in e,ce=e=>Y(e)&&"and"in e,ht=e=>({and:Uo(t=>ce(t)?t.and:[t],e)}),_e=(e,t)=>ce(e)?{and:e.and.map(r=>J(r)?{or:r.or.map(t)}:t(r))}:J(e)?{or:e.or.map(r=>ce(r)?{and:r.and.map(t)}:t(r))}:t(e),xt=e=>e.and.reduce((t,r)=>({or:_(t.or,J(r)?r.or:[r],ht)}),{or:[]}),pe=(e,t)=>ce(e)?J(t)?pe(xt(e),t):ht([e,t]):J(e)?ce(t)?pe(t,e):J(t)?{or:_(e.or,t.or,ht)}:pe(e,{and:[t]}):ce(t)||J(t)?pe(t,e):{and:[e,t]};import{z as or}from"zod";var bt=class{},F=class extends bt{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof or.ZodError?new L(o):o}}},de=class extends F{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({input:or.object({}),handler:async({request:n,response:i})=>new Promise((a,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));a(r(n,i))};t(n,i,d)?.catch(d)})})}};var Pe=class{},Ye=class extends Pe{#e;#t;#r;#i;#o;#a;#p;#n;#c;#d;#l;#s;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:i,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:l,shortDescription:f}){super(),this.#a=n,this.#p=i,this.#r=d,this.#l=a,this.#t=Object.freeze(t),this.#c=Object.freeze(p),this.#d=Object.freeze(c),this.#e={long:l,short:f},this.#n={input:r,output:o},this.#o={positive:Object.freeze(i.getPositiveResponse(o)),negative:Object.freeze(i.getNegativeResponse())},this.#s=tr(r)?"upload":rr(r)?"raw":"json",this.#i={input:Object.freeze([P[this.#s]]),positive:Object.freeze(this.#o.positive.flatMap(({mimeTypes:m})=>m)),negative:Object.freeze(this.#o.negative.flatMap(({mimeTypes:m})=>m))}}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return t==="input"||t==="output"?this.#n[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#i[t]}getRequestType(){return this.#s}getResponses(t){return this.#o[t]}getSecurity(){return this.#r.reduce((t,r)=>{let o=r.getSecurity();return o?pe(t,o):t},{and:[]})}getScopes(){return this.#c}getTags(){return this.#d}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#t.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#n.output.parseAsync(t)}catch(r){throw r instanceof nr.ZodError?new V(r):r}}async#f({method:t,input:r,request:o,response:n,logger:i,options:a}){for(let p of this.#r)if(!(t==="options"&&!(p instanceof de))&&(Object.assign(a,await p.execute({input:r,options:a,request:o,response:n,logger:i})),n.writableEnded)){i.warn("A middleware has closed the stream. Accumulated options:",a);break}}async#y({input:t,options:r,logger:o}){let n;try{n=await this.#n.input.parseAsync(t)}catch(i){throw i instanceof nr.ZodError?new L(i):i}return this.#a({input:n,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:n,input:i,output:a,options:p}){try{await this.#p.execute({error:t,output:a,request:r,response:o,logger:n,input:i,options:p})}catch(d){Ve({logger:n,response:o,error:new M(ie(d).message,t||void 0)})}}async execute({request:t,response:r,logger:o,config:n,siblingMethods:i=[]}){let a=lt(t),p={},d=null,c=null;if(n.cors){let f=this.#m(i);typeof n.cors=="function"&&(f=await n.cors({request:t,logger:o,endpoint:this,defaultHeaders:f}));for(let m in f)r.set(m,f[m])}let l=ut(t,n.inputSources);try{if(await this.#f({method:a,input:l,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:l,logger:o,options:p}))}catch(f){c=ie(f)}await this.#g({input:l,output:d,request:t,response:r,error:c,logger:o,options:p})}};var sr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>_t(i,n),o)};import{z as v}from"zod";var Ce={positive:200,negative:400};import Ho from"node:assert/strict";import{z as Do}from"zod";var Qe=(e,t)=>typeof e=="function"?Qe(e(...t.arguments),t):e instanceof Do.ZodType?[{...t,schema:e}]:(Array.isArray(e)&&Ho(e.length,new M(`At least one ${t.variant} response schema required.`)),(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:n,mimeTypes:i,mimeType:a})=>({schema:r,statusCodes:n?[n]:o||t.statusCodes,mimeTypes:a?[a]:i||t.mimeTypes})));var St=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Ie=class extends St{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Qe(this.#e,{variant:"positive",arguments:[t],statusCodes:[Ce.positive],mimeTypes:[P.json]})}getNegativeResponse(){return Qe(this.#t,{variant:"negative",arguments:[],statusCodes:[Ce.negative],mimeTypes:[P.json]})}},ze=new Ie({positive:e=>{let t=H({schema:e}),r=v.object({status:v.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:v.object({status:v.literal("error"),error:v.object({message:v.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(!e){n.status(Ce.positive).json({status:"success",data:r});return}let a=Fe(e);ft({logger:i,statusCode:a,request:o,error:e,input:t}),n.status(a).json({status:"error",error:{message:U(e)}})}}),Tt=new Ie({positive:e=>{let t=H({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof v.ZodArray?e.shape.items:v.array(v.any());return t.reduce((o,n)=>Y(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:v.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:n,input:i})=>{if(r){let a=Fe(r);ft({logger:o,statusCode:a,request:n,error:r,input:i}),e.status(a).type("text/plain").send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(Ce.positive).json(t.items):e.status(500).type("text/plain").send("Property 'items' is missing in the endpoint output")}});var we=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new de(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({input:Fo.object({}),handler:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:n,shortDescription:i,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,l="methods"in p?p.methods:[p.method],f=typeof a=="function"?a:()=>a,m="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],h="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new Ye({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:m,tags:h,methods:l,getOperationId:f,description:n,shortDescription:i,inputSchema:sr(d,t)})}},Ko=new we(ze),Bo=new we(Tt);import{Ansis as $o,blue as Go,cyanBright as Vo,green as _o,hex as Yo,red as Qo}from"ansis";import{inspect as Jo}from"node:util";import{performance as dr}from"node:perf_hooks";var le={debug:10,info:20,warn:30,error:40},ar=e=>Y(e)&&Object.keys(le).some(t=>t in e),pr=(e=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}),Je=pr(),ir=pr(2),qo=e=>e<1e-6?["picosecond",e/1e-9,Je]:e<.001?["nanosecond",e/1e-6,Je]:e<1?["microsecond",e/.001,Je]:e<1e3?["millisecond",e,Je]:e<6e4?["second",e/1e3,ir]:["minute",e/6e4,ir],cr=e=>{let[t,r,o]=qo(e);return`${o.format(r)} ${t}${r>1?"s":""}`};var Ee=class e{constructor(t){this.config=t;let{color:r=new $o().isSupported()}=t;this.hasColor=r}hasColor;styles={debug:Go,info:_o,warn:Yo("#FFA500"),error:Qo};prettyPrint(t){let{depth:r=2}=this.config;return Jo(t,{depth:r,colors:this.hasColor,breakLength:this.config.level==="debug"?80:1/0,compact:this.config.level==="debug"?3:!0})}print(t,r,o){if(this.config.level==="silent"||le[t]<le[this.config.level])return;let{requestId:n,...i}=this.config.ctx||{},a=[new Date().toISOString()];n&&a.push(this.hasColor?Vo(n):n),a.push(this.hasColor?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&a.push(this.prettyPrint(o)),Object.keys(i).length>0&&a.push(this.prettyPrint(i)),console.log(a.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}profile(t){let r=dr.now();return()=>{let o=dr.now()-r,{message:n,severity:i="debug",formatter:a=cr}=typeof t=="object"?t:{message:t};this.print(typeof i=="function"?i(o):i,n,a(o))}}};import{head as Wo,tail as Xo,toPairs as en}from"ramda";var Ze=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(en(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=Wo(this.pairs)?.[1],this.siblingMethods=Object.freeze(Xo(this.pairs).map(([r])=>r))}};import tn from"express";var ve=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,tn.static(...this.params))}};import Rt from"express";import cn from"node:http";import dn from"node:https";var me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Oe(e)};import lr from"node:assert/strict";var W=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:n})=>{let i=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of i){lr.doesNotMatch(a,/\//,new se(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof Pe){let c=p.getMethods().slice();n&&c.push("options");for(let l of c)t(p,d,l)}else if(p instanceof ve)r&&p.apply(d,r);else if(p instanceof Ze){for(let[c,l]of p.pairs)lr(l.getMethods().includes(c),new se(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(l,d,c);n&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else W({onEndpoint:t,onStatic:r,hasCors:n,routing:p,parentPath:d})}};var Ot=({app:e,getChildLogger:t,config:r,routing:o,parsers:n})=>W({routing:o,hasCors:!!r.cors,onEndpoint:(i,a,p,d)=>{e[p](a,...n?.[i.getRequestType()]||[],async(c,l)=>i.execute({request:c,response:l,logger:t(c),config:r,siblingMethods:d}))},onStatic:(i,a)=>{e.use(i,a)}});import xr,{isHttpError as on}from"http-errors";import{setInterval as rn}from"node:timers/promises";var mr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",ur=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",fr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,yr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),gr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var hr=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,i=c=>void n.delete(c.destroy()),a=c=>void(mr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):i(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let l of["connection","secureConnection"])c.on(l,p);let d=async()=>{for(let c of e)c.on("request",yr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(fr(c)||ur(c))&&a(c);for await(let c of rn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)i(c);return Promise.allSettled(e.map(gr))};return{sockets:n,shutdown:()=>o??=d()}};var br=({errorHandler:e,getChildLogger:t})=>async(r,o,n,i)=>r?e.execute({error:on(r)?r:xr(400,ie(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):i(),Sr=({errorHandler:e,getChildLogger:t})=>async(r,o)=>{let n=xr(404,`Can not ${r.method} ${r.path}`),i=t(r);try{e.execute({request:r,response:o,logger:i,error:n,input:null,output:null,options:{}})}catch(a){Ve({response:o,logger:i,error:new M(ie(a).message,n)})}},nn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},sn=e=>({log:e.debug.bind(e)}),Tr=async({getChildLogger:e,config:t})=>{let r=await me("express-fileupload"),{limitError:o,beforeUpload:n,...i}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let l=e(p);try{await n?.({request:p,logger:l})}catch(f){return c(f)}return r({debug:!0,...i,abortOnLimit:!1,parseNested:!0,logger:sn(l)})(p,d,c)}),o&&a.push(nn(o)),a},Or=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Rr=({rootLogger:e,config:t})=>async(r,o,n)=>{let i=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;i.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:i}),n()},Ar=e=>t=>t.res?.locals[g]?.logger||e,Pr=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
6
- `).slice(1))),Cr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=hr(e,{logger:t,timeout:r}),i=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,i)};import{gray as an,hex as Ir,italic as We,whiteBright as pn}from"ansis";var zr=()=>{let e=We("Proudly supports transgender community.".padStart(109)),t=We("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=We("Thank you for choosing Express Zod API for your project.".padStart(132)),o=We("for Zoey".padEnd(20)),n=Ir("#F5A9B8"),i=Ir("#5BCEFA"),a=new Array(14).fill(i,1,3).fill(n,3,5).fill(pn,5,7).fill(n,7,9).fill(i,9,12).fill(an,12,13);return`
4
+ `,{url:t.url,payload:r})},H=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let n=[];for(let i of o){let a=e.safeParse(i);a.success&&n.push(t==="parsed"?a.data:i)}return n},_=(e,t,r)=>e.length&&t.length?xo(e,t).map(r):e.concat(t),Re=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,yt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),w=(...e)=>e.flatMap(t=>t.split(/[^A-Z0-9]/gi)).flatMap(t=>t.replaceAll(/[A-Z]+/g,r=>`/${r}`).split("/")).map(yt).join(""),Fe=e=>go("sha1").update(JSON.stringify(e),"utf8").digest("hex"),Ke=(e,t)=>{try{return typeof e.parse(t)}catch{return}},Y=e=>typeof e=="object"&&e!==null;import{clone as Ro,mergeDeepRight as Ao}from"ramda";var g=Symbol.for("express-zod-api"),Be=e=>{let t=e.describe(e.description);return t._def[g]=Ro(t._def[g])||{examples:[]},t},_t=(e,t)=>{if(!(g in e._def))return t;let r=Be(t);return r._def[g].examples=_(r._def[g].examples,e._def[g].examples,([o,n])=>typeof o=="object"&&typeof n=="object"?Ao({...o},{...n}):n),r};var Eo=function(e){let t=Be(this);return t._def[g].examples.push(e),t},Zo=function(e){let t=Be(this);return t._def[g].defaultLabel=e,t},vo=function(e){return new pe.ZodBranded({typeName:pe.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...Yt(this._def[g]),brand:e}})},jo=function(e){let t=typeof e=="function"?e:Io(zo,Co(([n,i])=>wo(e[String(n)]||n,i)),Po),r=t(Yt(this.shape)),o=pe.object(r)[this._def.unknownKeys]();return this.transform(t).pipe(o)};g in globalThis||(globalThis[g]=!0,Object.defineProperties(pe.ZodType.prototype,{example:{get(){return Eo.bind(this)}},brand:{set(){},get(){return vo.bind(this)}}}),Object.defineProperty(pe.ZodDefault.prototype,"label",{get(){return Zo.bind(this)}}),Object.defineProperty(pe.ZodObject.prototype,"remap",{get(){return jo.bind(this)}}));function Lo(e){return e}import{z as Bo}from"zod";import{z as nr}from"zod";import{z as ko}from"zod";import{z as qe}from"zod";var D=Symbol("File"),Qt=qe.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),No={buffer:()=>Qt.brand(D),string:()=>qe.string().brand(D),binary:()=>Qt.or(qe.string()).brand(D),base64:()=>qe.string().base64().brand(D)};function $e(e){return No[e||"string"]()}var Q=Symbol("Raw"),Jt=(e={})=>ko.object({raw:$e("buffer")}).extend(e).brand(Q);import{z as Mo}from"zod";var Ae=Symbol("Upload"),Wt=()=>Mo.custom(e=>typeof e=="object"&&e!==null&&"name"in e&&"encoding"in e&&"mimetype"in e&&"data"in e&&"tempFilePath"in e&&"truncated"in e&&"size"in e&&"md5"in e&&"mv"in e&&typeof e.name=="string"&&typeof e.encoding=="string"&&typeof e.mimetype=="string"&&Buffer.isBuffer(e.data)&&typeof e.tempFilePath=="string"&&typeof e.truncated=="boolean"&&typeof e.size=="number"&&typeof e.md5=="string"&&typeof e.mv=="function",e=>({message:`Expected file upload, received ${typeof e}`})).brand(Ae);var Xt=(e,{next:t})=>e.options.some(t),Uo=({_def:e},{next:t})=>[e.left,e.right].some(t),er=(e,{next:t})=>t(e.unwrap()),Ho={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Xt,ZodDiscriminatedUnion:Xt,ZodIntersection:Uo,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:er,ZodNullable:er,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},gt=(e,{condition:t,rules:r=Ho,depth:o=1,maxDepth:n=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let i=o<n?r[e._def.typeName]:void 0;return i?i(e,{next:a=>gt(a,{condition:t,rules:r,maxDepth:n,depth:o+1})}):!1},tr=e=>gt(e,{condition:t=>t._def[g]?.brand===Ae}),rr=e=>gt(e,{condition:t=>t._def[g]?.brand===Q,maxDepth:3});var Ve=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).type("text/plain").end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
5
+ Original error: ${e.originalError.message}.`:""))};import{chain as Do}from"ramda";var J=e=>Y(e)&&"or"in e,de=e=>Y(e)&&"and"in e,ht=e=>({and:Do(t=>de(t)?t.and:[t],e)}),Ge=(e,t)=>de(e)?{and:e.and.map(r=>J(r)?{or:r.or.map(t)}:t(r))}:J(e)?{or:e.or.map(r=>de(r)?{and:r.and.map(t)}:t(r))}:t(e),xt=e=>e.and.reduce((t,r)=>({or:_(t.or,J(r)?r.or:[r],ht)}),{or:[]}),ce=(e,t)=>de(e)?J(t)?ce(xt(e),t):ht([e,t]):J(e)?de(t)?ce(t,e):J(t)?{or:_(e.or,t.or,ht)}:ce(e,{and:[t]}):de(t)||J(t)?ce(t,e):{and:[e,t]};import{z as or}from"zod";var bt=class{},F=class extends bt{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}getSecurity(){return this.#t}getSchema(){return this.#e}async execute({input:t,...r}){try{let o=await this.#e.parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof or.ZodError?new L(o):o}}},le=class extends F{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({input:or.object({}),handler:async({request:n,response:i})=>new Promise((a,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));a(r(n,i))};t(n,i,d)?.catch(d)})})}};var Pe=class{},_e=class extends Pe{#e;#t;#r;#i;#o;#a;#p;#n;#c;#d;#l;#s;constructor({methods:t,inputSchema:r,outputSchema:o,handler:n,resultHandler:i,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:c=[],description:l,shortDescription:f}){super(),this.#a=n,this.#p=i,this.#r=d,this.#l=a,this.#t=Object.freeze(t),this.#c=Object.freeze(p),this.#d=Object.freeze(c),this.#e={long:l,short:f},this.#n={input:r,output:o},this.#o={positive:Object.freeze(i.getPositiveResponse(o)),negative:Object.freeze(i.getNegativeResponse())},this.#s=tr(r)?"upload":rr(r)?"raw":"json",this.#i={input:Object.freeze([P[this.#s]]),positive:Object.freeze(this.#o.positive.flatMap(({mimeTypes:m})=>m)),negative:Object.freeze(this.#o.negative.flatMap(({mimeTypes:m})=>m))}}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return t==="input"||t==="output"?this.#n[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#i[t]}getRequestType(){return this.#s}getResponses(t){return this.#o[t]}getSecurity(){return this.#r.reduce((t,r)=>{let o=r.getSecurity();return o?ce(t,o):t},{and:[]})}getScopes(){return this.#c}getTags(){return this.#d}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#t.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#n.output.parseAsync(t)}catch(r){throw r instanceof nr.ZodError?new G(r):r}}async#f({method:t,input:r,request:o,response:n,logger:i,options:a}){for(let p of this.#r)if(!(t==="options"&&!(p instanceof le))&&(Object.assign(a,await p.execute({input:r,options:a,request:o,response:n,logger:i})),n.writableEnded)){i.warn("A middleware has closed the stream. Accumulated options:",a);break}}async#y({input:t,options:r,logger:o}){let n;try{n=await this.#n.input.parseAsync(t)}catch(i){throw i instanceof nr.ZodError?new L(i):i}return this.#a({input:n,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:n,input:i,output:a,options:p}){try{await this.#p.execute({error:t,output:a,request:r,response:o,logger:n,input:i,options:p})}catch(d){Ve({logger:n,response:o,error:new M(ae(d).message,t||void 0)})}}async execute({request:t,response:r,logger:o,config:n,siblingMethods:i=[]}){let a=lt(t),p={},d=null,c=null;if(n.cors){let f=this.#m(i);typeof n.cors=="function"&&(f=await n.cors({request:t,logger:o,endpoint:this,defaultHeaders:f}));for(let m in f)r.set(m,f[m])}let l=ut(t,n.inputSources);try{if(await this.#f({method:a,input:l,request:t,response:r,logger:o,options:p}),r.writableEnded)return;if(a==="options"){r.status(200).end();return}d=await this.#u(await this.#y({input:l,logger:o,options:p}))}catch(f){c=ae(f)}await this.#g({input:l,output:d,request:t,response:r,error:c,logger:o,options:p})}};var sr=(e,t)=>{let r=e.map(n=>n.getSchema()).concat(t),o=r.reduce((n,i)=>n.and(i));return r.reduce((n,i)=>_t(i,n),o)};import{z as v}from"zod";var W={positive:200,negative:400};import Fo from"node:assert/strict";import{z as Ko}from"zod";var Ye=(e,t)=>typeof e=="function"?Ye(e(...t.arguments),t):e instanceof Ko.ZodType?[{...t,schema:e}]:(Array.isArray(e)&&Fo(e.length,new M(`At least one ${t.variant} response schema required.`)),(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:n,mimeTypes:i,mimeType:a})=>({schema:r,statusCodes:n?[n]:o||t.statusCodes,mimeTypes:a?[a]:i||t.mimeTypes})));var St=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Ce=class extends St{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Ye(this.#e,{variant:"positive",arguments:[t],statusCodes:[W.positive],mimeTypes:[P.json]})}getNegativeResponse(){return Ye(this.#t,{variant:"negative",arguments:[],statusCodes:[W.negative],mimeTypes:[P.json]})}},Ie=new Ce({positive:e=>{let t=H({schema:e}),r=v.object({status:v.literal("success"),data:e});return t.reduce((o,n)=>o.example({status:"success",data:n}),r)},negative:v.object({status:v.literal("error"),error:v.object({message:v.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:i})=>{if(!e){n.status(W.positive).json({status:"success",data:r});return}let a=De(e);ft({logger:i,statusCode:a,request:o,error:e,input:t}),n.status(a).json({status:"error",error:{message:U(e)}})}}),Tt=new Ce({positive:e=>{let t=H({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof v.ZodArray?e.shape.items:v.array(v.any());return t.reduce((o,n)=>Y(n)&&"items"in n&&Array.isArray(n.items)?o.example(n.items):o,r)},negative:v.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:n,input:i})=>{if(r){let a=De(r);ft({logger:o,statusCode:a,request:n,error:r,input:i}),e.status(a).type("text/plain").send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(W.positive).json(t.items):e.status(500).type("text/plain").send("Property 'items' is missing in the endpoint output")}});var ze=class e{resultHandler;middlewares=[];constructor(t){this.resultHandler="resultHandler"in t?t.resultHandler:t}static#e(t,r){let o=new e(r);return o.middlewares=t,o}addMiddleware(t){return e.#e(this.middlewares.concat(t instanceof F?t:new F(t)),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(...t){return e.#e(this.middlewares.concat(new le(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new F({input:Bo.object({}),handler:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:n,shortDescription:i,operationId:a,...p}){let{middlewares:d,resultHandler:c}=this,l="methods"in p?p.methods:[p.method],f=typeof a=="function"?a:()=>a,m="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],h="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new _e({handler:r,middlewares:d,outputSchema:o,resultHandler:c,scopes:m,tags:h,methods:l,getOperationId:f,description:n,shortDescription:i,inputSchema:sr(d,t)})}},qo=new ze(Ie),$o=new ze(Tt);import{Ansis as Go,blue as _o,cyanBright as Yo,green as Qo,hex as Jo,red as Wo}from"ansis";import{inspect as Xo}from"node:util";import{performance as mr}from"node:perf_hooks";var Je={debug:10,info:20,warn:30,error:40},ar=e=>Y(e)&&Object.keys(Je).some(t=>t in e),pr=e=>e in Je,cr=(e,t)=>Je[e]<Je[t],dr=(e=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:e}),Qe=dr(),ir=dr(2),Vo=e=>e<1e-6?["picosecond",e/1e-9,Qe]:e<.001?["nanosecond",e/1e-6,Qe]:e<1?["microsecond",e/.001,Qe]:e<1e3?["millisecond",e,Qe]:e<6e4?["second",e/1e3,ir]:["minute",e/6e4,ir],lr=e=>{let[t,r,o]=Vo(e);return`${o.format(r)} ${t}${r>1?"s":""}`};var we=class e{constructor(t){this.config=t;let{color:r=new Go().isSupported()}=t;this.hasColor=r}hasColor;styles={debug:_o,info:Qo,warn:Jo("#FFA500"),error:Wo};prettyPrint(t){let{depth:r=2}=this.config;return Xo(t,{depth:r,colors:this.hasColor,breakLength:this.config.level==="debug"?80:1/0,compact:this.config.level==="debug"?3:!0})}print(t,r,o){if(this.config.level==="silent"||cr(t,this.config.level))return;let{requestId:n,...i}=this.config.ctx||{},a=[new Date().toISOString()];n&&a.push(this.hasColor?Yo(n):n),a.push(this.hasColor?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&a.push(this.prettyPrint(o)),Object.keys(i).length>0&&a.push(this.prettyPrint(i)),console.log(a.join(" "))}debug(t,r){this.print("debug",t,r)}info(t,r){this.print("info",t,r)}warn(t,r){this.print("warn",t,r)}error(t,r){this.print("error",t,r)}child(t){return new e({...this.config,ctx:t})}profile(t){let r=mr.now();return()=>{let o=mr.now()-r,{message:n,severity:i="debug",formatter:a=lr}=typeof t=="object"?t:{message:t};this.print(typeof i=="function"?i(o):i,n,a(o))}}};import{head as en,tail as tn,toPairs as rn}from"ramda";var Ee=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze(rn(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=en(this.pairs)?.[1],this.siblingMethods=Object.freeze(tn(this.pairs).map(([r])=>r))}};import on from"express";var Ze=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,on.static(...this.params))}};import Rt from"express";import ln from"node:http";import mn from"node:https";var me=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Oe(e)};import ur from"node:assert/strict";var X=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:n})=>{let i=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of i){ur.doesNotMatch(a,/\//,new ie(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof Pe){let c=p.getMethods().slice();n&&c.push("options");for(let l of c)t(p,d,l)}else if(p instanceof Ze)r&&p.apply(d,r);else if(p instanceof Ee){for(let[c,l]of p.pairs)ur(l.getMethods().includes(c),new ie(`Endpoint assigned to ${c} method of ${d} must support ${c} method.`)),t(l,d,c);n&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else X({onEndpoint:t,onStatic:r,hasCors:n,routing:p,parentPath:d})}};var Ot=({app:e,getChildLogger:t,config:r,routing:o,parsers:n})=>X({routing:o,hasCors:!!r.cors,onEndpoint:(i,a,p,d)=>{e[p](a,...n?.[i.getRequestType()]||[],async(c,l)=>i.execute({request:c,response:l,logger:t(c),config:r,siblingMethods:d}))},onStatic:(i,a)=>{e.use(i,a)}});import Sr,{isHttpError as sn}from"http-errors";import{setInterval as nn}from"node:timers/promises";var fr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",yr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",gr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,hr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),xr=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var br=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,i=c=>void n.delete(c.destroy()),a=c=>void(fr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):i(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let l of["connection","secureConnection"])c.on(l,p);let d=async()=>{for(let c of e)c.on("request",hr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(gr(c)||yr(c))&&a(c);for await(let c of nn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)i(c);return Promise.allSettled(e.map(xr))};return{sockets:n,shutdown:()=>o??=d()}};var Tr=({errorHandler:e,getChildLogger:t})=>async(r,o,n,i)=>r?e.execute({error:sn(r)?r:Sr(400,ae(r).message),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):i(),Or=({errorHandler:e,getChildLogger:t})=>async(r,o)=>{let n=Sr(404,`Can not ${r.method} ${r.path}`),i=t(r);try{e.execute({request:r,response:o,logger:i,error:n,input:null,output:null,options:{}})}catch(a){Ve({response:o,logger:i,error:new M(ae(a).message,n)})}},an=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},pn=e=>({log:e.debug.bind(e)}),Rr=async({getChildLogger:e,config:t})=>{let r=await me("express-fileupload"),{limitError:o,beforeUpload:n,...i}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,c)=>{let l=e(p);try{await n?.({request:p,logger:l})}catch(f){return c(f)}return r({debug:!0,...i,abortOnLimit:!1,parseNested:!0,logger:pn(l)})(p,d,c)}),o&&a.push(an(o)),a},Ar=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Pr=({rootLogger:e,config:t})=>async(r,o,n)=>{let i=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;i.debug(`${r.method}: ${r.path}`),r.res&&(r.res.locals[g]={logger:i}),n()},Cr=e=>t=>t.res?.locals[g]?.logger||e,Ir=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
6
+ `).slice(1))),zr=({servers:e,logger:t,options:{timeout:r,events:o=["SIGINT","SIGTERM"]}})=>{let n=br(e,{logger:t,timeout:r}),i=()=>n.shutdown().then(()=>process.exit());for(let a of o)process.on(a,i)};import{gray as cn,hex as wr,italic as We,whiteBright as dn}from"ansis";var Er=()=>{let e=We("Proudly supports transgender community.".padStart(109)),t=We("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=We("Thank you for choosing Express Zod API for your project.".padStart(132)),o=We("for Zoey".padEnd(20)),n=wr("#F5A9B8"),i=wr("#5BCEFA"),a=new Array(14).fill(i,1,3).fill(n,3,5).fill(dn,5,7).fill(n,7,9).fill(i,9,12).fill(cn,12,13);return`
7
7
  8888888888 8888888888P 888 d8888 8888888b. 8888888
8
8
  888 d88P 888 d88888 888 Y88b 888
9
9
  888 d88P 888 d88P888 888 888 888
@@ -18,8 +18,8 @@ ${o}888${t}
18
18
  ${r}
19
19
  `.split(`
20
20
  `).map((d,c)=>a[c]?a[c](d):d).join(`
21
- `)};var wr=e=>{e.startupLogo!==!1&&console.log(zr());let t=e.errorHandler||ze,r=ar(e.logger)?e.logger:new Ee(e.logger);r.debug("Running","v20.14.0 (ESM)"),Pr(r);let o=Rr({rootLogger:r,config:e}),i={getChildLogger:Ar(r),errorHandler:t},a=Sr(i),p=br(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},ln=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=wr(e);return Ot({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},mn=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=wr(e),p=Rt().disable("x-powered-by").use(a);if(e.server.compression){let m=await me("compression");p.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let d={json:[e.server.jsonParser||Rt.json()],raw:[e.server.rawParser||Rt.raw(),Or],upload:e.server.upload?await Tr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Ot({app:p,routing:t,getChildLogger:o,config:e,parsers:d}),p.use(i,n);let c=(m,h)=>m.listen(h,()=>r.info("Listening",h)),l=cn.createServer(p),f=e.https&&dn.createServer(e.https.options,p);return e.gracefulShutdown&&Cr({servers:[l].concat(f||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(l,e.server.listen),httpsServer:f&&c(f,e.https?.listen)}};import gs from"node:assert/strict";import{OpenApiBuilder as hs}from"openapi3-ts/oas31";import{pluck as xs}from"ramda";import te from"node:assert/strict";import{isReferenceObject as Pt,isSchemaObject as tt}from"openapi3-ts/oas31";import{concat as fn,type as Lr,filter as yn,fromPairs as ke,has as gn,isNil as hn,map as ue,mergeAll as xn,mergeDeepRight as bn,mergeDeepWith as Sn,objOf as Nr,omit as rt,pipe as kr,pluck as Tn,range as On,reject as Rn,toLower as An,union as Pn,when as Cn,xprod as ot,zip as In}from"ramda";import{z as S}from"zod";import{z as je}from"zod";var Xe=e=>!isNaN(e.getTime());var Le=Symbol("DateIn"),Er=()=>je.union([je.string().date(),je.string().datetime(),je.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(je.date().refine(Xe)).brand(Le);import{z as un}from"zod";var Ne=Symbol("DateOut"),Zr=()=>un.date().refine(Xe).transform(e=>e.toISOString()).brand(Ne);var X=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[g]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>X(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:p,...n});return d?{...p,...d}:p};var vr=50,Mr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",zn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Ur=/:([A-Za-z0-9_]+)/g,wn=e=>e.match(Ur)?.map(t=>t.slice(1))||[],Hr=e=>e.replace(Ur,t=>`{${t.slice(1)}}`),En=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Zn=({_def:{innerType:e}},{next:t})=>t(e),vn=()=>({format:"any"}),jn=({},e)=>(te(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Ln=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Nn=({options:e},{next:t})=>({oneOf:e.map(t)}),kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Mn=e=>{let[t,r]=e.filter(tt).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));te(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=Sn((n,i)=>Array.isArray(n)&&Array.isArray(i)?fn(n,i):n===i?i:te.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Pn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([n,i])=>bn(n,i))),o},Un=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Mn(o)}catch{}return{allOf:o}},Hn=(e,{next:t})=>t(e.unwrap()),Dn=(e,{next:t})=>t(e.unwrap()),Fn=(e,{next:t})=>{let r=t(e.unwrap());return tt(r)&&(r.type=Fr(r)),r},Dr=e=>{let t=An(Lr(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},jr=e=>({type:Dr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Kn=({value:e})=>({type:Dr(e),const:e}),Bn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Re(p)?p instanceof S.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=et(e,r)),i.length&&(a.required=i),a},qn=()=>({type:"null"}),$n=({},e)=>(te(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"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?$/.source,externalDocs:{url:Mr}}),Gn=({},e)=>(te(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Mr}}),Vn=({},e)=>te.fail(new z({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),_n=()=>({type:"boolean"}),Yn=()=>({type:"integer",format:"bigint"}),Qn=e=>e.every(t=>t instanceof S.ZodLiteral),Jn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=et(S.object(ke(ot(o,[t]))),r),n.required=o),n}if(e instanceof S.ZodLiteral)return{type:"object",properties:et(S.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.ZodUnion&&Qn(e.options)){let o=ue(i=>`${i.value}`,e.options),n=ke(ot(o,[t]));return{type:"object",properties:et(S.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Wn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Xn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),es=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:f}})=>{let m=f.find(R=>R.kind==="regex"),h=f.find(R=>R.kind==="datetime"),C=m?m.regex:h?h.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,b={type:"string"},Z={"date-time":l,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:d,emoji:c};for(let R in Z)if(Z[R]){b.format=R;break}return r!==null&&(b.minLength=r),o!==null&&(b.maxLength=o),C&&(b.pattern=C.source),b},ts=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=i:l.exclusiveMinimum=i,c?l.maximum=d:l.exclusiveMaximum=d,l},et=({shape:e},t)=>ue(t,e),rs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return zn?.[t]},Fr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},os=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&tt(o)){let i=Be(e,rs(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.any())}if(!t&&n.type==="preprocess"&&tt(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},ns=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ss=(e,{next:t})=>t(e.unwrap()),is=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},as=(e,{next:t})=>t(e.unwrap().shape.raw),Kr=e=>e.length?ke(In(On(1,e.length+1).map(t=>`example${t}`),ue(Nr("value"),e))):void 0,Br=(e,t,r=[])=>kr(H,ue(Cn(o=>Lr(o)==="Object",rt(r))),Kr)({schema:e,variant:t?"parsed":"original",validate:!0}),ps=(e,t)=>kr(H,yn(gn(t)),Tn(t),Kr)({schema:e,variant:"original",validate:!0}),ee=e=>e instanceof S.ZodObject?e:e instanceof S.ZodBranded?ee(e.unwrap()):e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?e.options.map(t=>ee(t)).reduce((t,r)=>t.merge(r.partial()),S.object({})):e instanceof S.ZodEffects?ee(e._def.schema):e instanceof S.ZodPipeline?ee(e._def.in):ee(e._def.left).merge(ee(e._def.right)),qr=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=ee(r),f=wn(e),m=o.includes("query"),h=o.includes("params"),C=o.includes("headers"),b=x=>h&&f.includes(x),Z=x=>C&&mt(x);return Object.keys(l).map(x=>({name:x,location:b(x)?"path":Z(x)?"header":m?"query":void 0})).filter(x=>x.location!==void 0).map(({name:x,location:ge})=>{let k=X(l[x],{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),$=p==="components"?a(w(c,x),k):k;return{name:x,in:ge,required:!l[x].isOptional(),description:k.description||c,schema:$,examples:ps(r,x)}})},Ct={ZodString:es,ZodNumber:ts,ZodBigInt:Yn,ZodBoolean:_n,ZodNull:qn,ZodArray:Wn,ZodTuple:Xn,ZodRecord:Jn,ZodObject:Bn,ZodLiteral:Kn,ZodIntersection:Un,ZodUnion:Nn,ZodAny:vn,ZodDefault:En,ZodEnum:jr,ZodNativeEnum:jr,ZodEffects:os,ZodOptional:Hn,ZodNullable:Fn,ZodDiscriminatedUnion:kn,ZodBranded:ss,ZodDate:Vn,ZodCatch:Zn,ZodPipeline:ns,ZodLazy:is,ZodReadonly:Dn,[D]:Ln,[Ae]:jn,[Ne]:Gn,[Le]:$n,[Q]:as},It=(e,{isResponse:t,prev:r})=>{if(Pt(r))return{};let{description:o}=e,n=e instanceof S.ZodLazy,i=r.type!==void 0,a=t&&Re(e),p=!n&&i&&!a&&e.isNullable(),d=n?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Fr(r)),d.length&&(c.examples=d.slice()),c},zt=(e,t)=>te.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),At=(e,t)=>{if(Pt(e))return e;let r={...e};return r.properties&&(r.properties=rt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>rt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>At(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>At(o,t))),r},$r=e=>Pt(e)?e:rt(["examples"],e),Gr=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,brandHandling:f,description:m=`${e.toUpperCase()} ${t} ${yt(n)} response ${c?l:""}`.trim()})=>{let h=$r(X(r,{rules:{...f,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),C={schema:d==="components"?p(w(m),h):h,examples:Br(r,!0)};return{description:m,content:ke(ot(o,[C]))}},cs=()=>({type:"http",scheme:"basic"}),ds=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ls=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ms=({name:e})=>({type:"apiKey",in:"header",name:e}),us=({name:e})=>({type:"apiKey",in:"cookie",name:e}),fs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ys=({flows:e={}})=>({type:"oauth2",flows:ue(t=>({...t,scopes:t.scopes||{}}),Rn(hn,e))}),Vr=(e,t)=>{let r={basic:cs,bearer:ds,input:ls,header:ms,cookie:us,openid:fs,oauth2:ys};return _e(e,o=>r[o.type](o,t))},nt=e=>"or"in e?e.or.map(t=>"and"in t?xn(ue(({name:r,scopes:o})=>Nr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?nt(xt(e)):nt({or:[e]}),_r=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let f=$r(At(X(r,{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),m={schema:p==="components"?a(w(l),f):f,examples:Br(r,!1,c)};return{description:l,content:ke(ot(o,[m]))}},Yr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),wt=e=>e.length<=vr?e:e.slice(0,vr-1)+"\u2026";var Et=class extends hs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||w(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&gs.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:c="inline",serializer:l=Ke}){super(),this.addInfo({title:o,version:n});for(let m of typeof i=="string"?[i]:i)this.addServer({url:m});W({routing:t,onEndpoint:(m,h,C)=>{let b=C,Z={path:h,method:b,endpoint:m,composition:c,serializer:l,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[R,x]=["short","long"].map(m.getDescription.bind(m)),ge=R?wt(R):d&&x?wt(x):void 0,k=m.getTags(),$=r.inputSources?.[b]||dt[b],oe=this.ensureUniqOperationId(h,b,m.getOperationId(b)),he=qr({...Z,inputSources:$,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:h,operationId:oe})}),Ue={};for(let j of["positive","negative"]){let G=m.getResponses(j);for(let{mimeTypes:xe,schema:T,statusCodes:O}of G)for(let A of O)Ue[A]=Gr({...Z,variant:j,schema:T,mimeTypes:xe,statusCode:A,hasMultipleStatusCodes:G.length>1||O.length>1,description:a?.[`${j}Response`]?.call(null,{method:b,path:h,operationId:oe,statusCode:A})})}let ct=$.includes("body")?_r({...Z,paramNames:xs("name",he),schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:h,operationId:oe})}):void 0,He=nt(_e(Vr(m.getSecurity(),$),j=>{let G=this.ensureUniqSecuritySchemaName(j),xe=["oauth2","openIdConnect"].includes(j.type)?m.getScopes().slice():[];return this.addSecurityScheme(G,j),{name:G,scopes:xe}}));this.addPath(Hr(h),{[b]:{operationId:oe,summary:ge,description:x,tags:k.length>0?k:void 0,parameters:he.length>0?he:void 0,requestBody:ct,security:He.length>0?He:void 0,responses:Ue}})}}),this.rootDoc.tags=r.tags?Yr(r.tags):[]}};import{createRequest as bs,createResponse as Ss}from"node-mocks-http";var Ts=e=>bs({...e,headers:{"content-type":P.json,...e?.headers}}),Os=e=>Ss(e),Rs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:o in le?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},As=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ts(e),i=Os({req:n,...t});i.req=t?.req||n,n.res=i;let a=Rs(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},Ps=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=As(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}};import E from"typescript";import N from"typescript";import{chain as Qr,toPairs as Jr}from"ramda";var s=N.factory,K=[s.createModifier(N.SyntaxKind.ExportKeyword)],Cs=[s.createModifier(N.SyntaxKind.AsyncKeyword)],Is=[s.createModifier(N.SyntaxKind.PublicKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],Wr=[s.createModifier(N.SyntaxKind.ProtectedKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],Zt=s.createTemplateHead(""),fe=s.createTemplateTail(""),vt=s.createTemplateMiddle(" "),jt=e=>s.createTemplateLiteralType(Zt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?fe:vt))),Lt=jt(["M","P"]),st=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),it=(e,t)=>Qr(([r,o])=>[st(s.createIdentifier(r),o,t)],Jr(e)),Nt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),Xr=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),eo=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),B=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],N.NodeFlags.Const),kt=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),at=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,t),to=(e,t,r)=>s.createPropertyDeclaration(Is,e,void 0,t,r),ro=(e,t,r)=>s.createClassDeclaration(K,e,void 0,void 0,[t,...r]),oo=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),no=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(N.SyntaxKind.AnyKeyword)]),so=(e,t,r)=>s.createInterfaceDeclaration(K,e,void 0,t,r),zs=Qr(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),io=e=>zs(Jr(e)),Mt=(e,t,r)=>s.createArrowFunction(r?Cs:void 0,void 0,e.map(o=>st(o)),void 0,void 0,t),Ut=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,it({acc:void 0,key:void 0}),void 0,void 0,t),r]),ao=(...e)=>`"${e.join(" ")}"`;var po=["get","post","put","delete","patch"];import y from"typescript";import{z as Ft}from"zod";import q from"typescript";var{factory:pt}=q,Ht=(e,t)=>{q.addSyntheticLeadingComment(e,q.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ye=(e,t,r)=>{let o=pt.createTypeAliasDeclaration(void 0,pt.createIdentifier(t),void 0,e);return r&&Ht(o,r),o},Dt=(e,t)=>{let r=q.createSourceFile("print.ts","",q.ScriptTarget.Latest,!1,q.ScriptKind.TS);return q.createPrinter(t).printNode(q.EmitHint.Unspecified,e,r)},ws=/^[A-Za-z_$][A-Za-z0-9_$]*$/,co=e=>ws.test(e)?pt.createIdentifier(e):pt.createStringLiteral(e);var{factory:u}=y,Es={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},Zs=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),vs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Re(a)?a instanceof Ft.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,co(i),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Ht(d,a.description),d});return u.createTypeLiteralNode(n)},js=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Ls=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),lo=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),Ns=e=>Es?.[e.kind],ks=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Be(e,Ns(o)),i={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(n&&i[n]||y.SyntaxKind.AnyKeyword)}return o},Ms=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Us=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Hs=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),Ds=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),Fs=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),Ks=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),Bs=({_def:e},{next:t})=>t(e.innerType),re=e=>()=>u.createKeywordTypeNode(e),qs=(e,{next:t})=>t(e.unwrap()),$s=(e,{next:t})=>t(e.unwrap()),Gs=({_def:e},{next:t})=>t(e.innerType),Vs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),_s=()=>u.createLiteralTypeNode(u.createNull()),Ys=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,u.createLiteralTypeNode(u.createNull())),r(i,o(e)))},Qs=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),n=u.createUnionTypeNode([r,o]);return t instanceof Ft.ZodString?r:t instanceof Ft.ZodUnion?n:o},Js=(e,{next:t})=>t(e.unwrap().shape.raw),Ws={ZodString:re(y.SyntaxKind.StringKeyword),ZodNumber:re(y.SyntaxKind.NumberKeyword),ZodBigInt:re(y.SyntaxKind.BigIntKeyword),ZodBoolean:re(y.SyntaxKind.BooleanKeyword),ZodAny:re(y.SyntaxKind.AnyKeyword),[Le]:re(y.SyntaxKind.StringKeyword),[Ne]:re(y.SyntaxKind.StringKeyword),ZodNull:_s,ZodArray:js,ZodTuple:Ds,ZodRecord:Fs,ZodObject:vs,ZodLiteral:Zs,ZodIntersection:Ks,ZodUnion:lo,ZodDefault:Bs,ZodEnum:Ls,ZodNativeEnum:Ms,ZodEffects:ks,ZodOptional:Us,ZodNullable:Hs,ZodDiscriminatedUnion:lo,ZodBranded:qs,ZodCatch:Gs,ZodPipeline:Vs,ZodLazy:Ys,ZodReadonly:$s,[D]:Qs,[Q]:Js},Me=(e,{brandHandling:t,ctx:r})=>X(e,{rules:{...t,...Ws},onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),ctx:r});var Kt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ye(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=Ke,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){W({routing:t,onEndpoint:(T,O,A)=>{let ne={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},be=w(A,O,"input"),Se=Me(T.getSchema("input"),{brandHandling:r,ctx:{...ne,isResponse:!1}}),I=i?w(A,O,"positive.response"):void 0,Bt=T.getSchema("positive"),qt=i?Me(Bt,{brandHandling:r,ctx:{...ne,isResponse:!0}}):void 0,Te=i?w(A,O,"negative.response"):void 0,$t=T.getSchema("negative"),Gt=i?Me($t,{brandHandling:r,ctx:{...ne,isResponse:!0}}):void 0,Vt=w(A,O,"response"),mo=I&&Te?s.createUnionTypeNode([s.createTypeReferenceNode(I),s.createTypeReferenceNode(Te)]):Me(Bt.or($t),{brandHandling:r,ctx:{...ne,isResponse:!0}});this.program.push(ye(Se,be)),qt&&I&&this.program.push(ye(qt,I)),Gt&&Te&&this.program.push(ye(Gt,Te)),this.program.push(ye(mo,Vt)),A!=="options"&&(this.paths.push(O),this.registry.set({method:A,path:O},{input:be,positive:I,negative:Te,response:Vt,isJson:T.getMimeTypes("positive").includes(P.json),tags:T.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(kt(this.ids.pathType,this.paths)),this.program.push(kt(this.ids.methodType,po)),this.program.push(at(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(E.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,E.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let d=[],c=[];for(let[{method:T,path:O},{isJson:A,tags:ne,...be}]of this.registry){let Se=ao(T,O);for(let I of this.interfaces)I.kind in be&&I.props.push(eo(Se,be[I.kind]));o!=="types"&&(A&&d.push(s.createPropertyAssignment(Se,s.createTrue())),c.push(s.createPropertyAssignment(Se,s.createArrayLiteralExpression(ne.map(I=>s.createStringLiteral(I))))))}for(let{id:T,props:O}of this.interfaces)this.program.push(so(T,p,O));if(o==="types")return;let l=s.createVariableStatement(K,B(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(d))),f=s.createVariableStatement(K,B(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),m=at(this.ids.providerType,s.createFunctionTypeNode(io({M:this.ids.methodType,P:this.ids.pathType}),it({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Lt)}),oo(this.ids.responseInterface,Lt))),h=at(this.ids.implementationType,s.createFunctionTypeNode(void 0,it({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(E.SyntaxKind.StringKeyword),params:Nt(E.SyntaxKind.StringKeyword,E.SyntaxKind.AnyKeyword)}),no())),C=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,fe)]),b=Ut(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[C,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),Z=Ut(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[C]),E.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),R=ro(this.ids.clientClass,Xr([st(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),Wr)]),[to(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,Z]),!0))]);this.program.push(l,f,m,h,R);let x=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ge=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(P.json))]),void 0,this.ids.undefinedValue)),k=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),$=s.createVariableStatement(void 0,B(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,fe)]),s.createObjectLiteralExpression([x,ge,k])])))),oe=s.createVariableStatement(void 0,B(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),he=s.createVariableStatement(void 0,B(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),fe)])))),[Ue,ct]=["json","text"].map(T=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,T),void 0,void 0))),He=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(Zt,[s.createTemplateSpan(this.ids.methodParameter,vt),s.createTemplateSpan(this.ids.pathParameter,fe)]),E.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Ue])),j=s.createVariableStatement(K,B(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([oe,he,$,He,ct]),!0),s.createTypeReferenceNode(this.ids.implementationType))),G=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),xe=s.createVariableStatement(void 0,B(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(j,xe,G)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
21
+ `)};var Zr=e=>{e.startupLogo!==!1&&console.log(Er());let t=e.errorHandler||Ie,r=ar(e.logger)?e.logger:new we(e.logger);r.debug("Running","v20.14.2 (ESM)"),Ir(r);let o=Pr({rootLogger:r,config:e}),i={getChildLogger:Cr(r),errorHandler:t},a=Or(i),p=Tr(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},un=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=Zr(e);return Ot({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},fn=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Zr(e),p=Rt().disable("x-powered-by").use(a);if(e.server.compression){let m=await me("compression");p.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let d={json:[e.server.jsonParser||Rt.json()],raw:[e.server.rawParser||Rt.raw(),Ar],upload:e.server.upload?await Rr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Ot({app:p,routing:t,getChildLogger:o,config:e,parsers:d}),p.use(i,n);let c=(m,h)=>m.listen(h,()=>r.info("Listening",h)),l=ln.createServer(p),f=e.https&&mn.createServer(e.https.options,p);return e.gracefulShutdown&&zr({servers:[l].concat(f||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(l,e.server.listen),httpsServer:f&&c(f,e.https?.listen)}};import xs from"node:assert/strict";import{OpenApiBuilder as bs}from"openapi3-ts/oas31";import{keys as Ss,pluck as Ts}from"ramda";import re from"node:assert/strict";import{isReferenceObject as Pt,isSchemaObject as tt}from"openapi3-ts/oas31";import{concat as gn,type as kr,filter as hn,fromPairs as Ne,has as xn,isNil as bn,map as ue,mergeAll as Sn,mergeDeepRight as Tn,mergeDeepWith as On,objOf as Mr,omit as rt,pipe as Ur,pluck as Rn,range as An,reject as Pn,toLower as Cn,union as In,when as zn,xprod as ot,zip as wn}from"ramda";import{z as S}from"zod";import{z as ve}from"zod";var Xe=e=>!isNaN(e.getTime());var je=Symbol("DateIn"),vr=()=>ve.union([ve.string().date(),ve.string().datetime(),ve.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(ve.date().refine(Xe)).brand(je);import{z as yn}from"zod";var Le=Symbol("DateOut"),jr=()=>yn.date().refine(Xe).transform(e=>e.toISOString()).brand(Le);var ee=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[g]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>ee(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:p,...n});return d?{...p,...d}:p};var Lr=50,Hr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",En={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Dr=/:([A-Za-z0-9_]+)/g,Zn=e=>e.match(Dr)?.map(t=>t.slice(1))||[],Fr=e=>e.replace(Dr,t=>`{${t.slice(1)}}`),vn=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),jn=({_def:{innerType:e}},{next:t})=>t(e),Ln=()=>({format:"any"}),Nn=({},e)=>(re(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),kn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Mn=({options:e},{next:t})=>({oneOf:e.map(t)}),Un=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Hn=e=>{let[t,r]=e.filter(tt).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));re(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=On((n,i)=>Array.isArray(n)&&Array.isArray(i)?gn(n,i):n===i?i:re.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=In(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([n,i])=>Tn(n,i))),o},Dn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Hn(o)}catch{}return{allOf:o}},Fn=(e,{next:t})=>t(e.unwrap()),Kn=(e,{next:t})=>t(e.unwrap()),Bn=(e,{next:t})=>{let r=t(e.unwrap());return tt(r)&&(r.type=Br(r)),r},Kr=e=>{let t=Cn(kr(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Nr=e=>({type:Kr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),qn=({value:e})=>({type:Kr(e),const:e}),$n=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Re(p)?p instanceof S.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=et(e,r)),i.length&&(a.required=i),a},Vn=()=>({type:"null"}),Gn=({},e)=>(re(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"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?$/.source,externalDocs:{url:Hr}}),_n=({},e)=>(re(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Hr}}),Yn=({},e)=>re.fail(new z({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),Qn=()=>({type:"boolean"}),Jn=()=>({type:"integer",format:"bigint"}),Wn=e=>e.every(t=>t instanceof S.ZodLiteral),Xn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=et(S.object(Ne(ot(o,[t]))),r),n.required=o),n}if(e instanceof S.ZodLiteral)return{type:"object",properties:et(S.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.ZodUnion&&Wn(e.options)){let o=ue(i=>`${i.value}`,e.options),n=Ne(ot(o,[t]));return{type:"object",properties:et(S.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},es=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},ts=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),rs=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:f}})=>{let m=f.find(R=>R.kind==="regex"),h=f.find(R=>R.kind==="datetime"),C=m?m.regex:h?h.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,b={type:"string"},Z={"date-time":l,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:d,emoji:c};for(let R in Z)if(Z[R]){b.format=R;break}return r!==null&&(b.minLength=r),o!==null&&(b.maxLength=o),C&&(b.pattern=C.source),b},os=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=i:l.exclusiveMinimum=i,c?l.maximum=d:l.exclusiveMaximum=d,l},et=({shape:e},t)=>ue(t,e),ns=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return En?.[t]},Br=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},ss=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&tt(o)){let i=Ke(e,ns(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.any())}if(!t&&n.type==="preprocess"&&tt(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},is=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),as=(e,{next:t})=>t(e.unwrap()),ps=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},cs=(e,{next:t})=>t(e.unwrap().shape.raw),qr=e=>e.length?Ne(wn(An(1,e.length+1).map(t=>`example${t}`),ue(Mr("value"),e))):void 0,$r=(e,t,r=[])=>Ur(H,ue(zn(o=>kr(o)==="Object",rt(r))),qr)({schema:e,variant:t?"parsed":"original",validate:!0}),ds=(e,t)=>Ur(H,hn(xn(t)),Rn(t),qr)({schema:e,variant:"original",validate:!0}),te=e=>e instanceof S.ZodObject?e:e instanceof S.ZodBranded?te(e.unwrap()):e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?e.options.map(t=>te(t)).reduce((t,r)=>t.merge(r.partial()),S.object({})):e instanceof S.ZodEffects?te(e._def.schema):e instanceof S.ZodPipeline?te(e._def.in):te(e._def.left).merge(te(e._def.right)),Vr=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=te(r),f=Zn(e),m=o.includes("query"),h=o.includes("params"),C=o.includes("headers"),b=x=>h&&f.includes(x),Z=x=>C&&mt(x);return Object.keys(l).map(x=>({name:x,location:b(x)?"path":Z(x)?"header":m?"query":void 0})).filter(x=>x.location!==void 0).map(({name:x,location:ge})=>{let k=ee(l[x],{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),$=p==="components"?a(w(c,x),k):k;return{name:x,in:ge,required:!l[x].isOptional(),description:k.description||c,schema:$,examples:ds(r,x)}})},Ct={ZodString:rs,ZodNumber:os,ZodBigInt:Jn,ZodBoolean:Qn,ZodNull:Vn,ZodArray:es,ZodTuple:ts,ZodRecord:Xn,ZodObject:$n,ZodLiteral:qn,ZodIntersection:Dn,ZodUnion:Mn,ZodAny:Ln,ZodDefault:vn,ZodEnum:Nr,ZodNativeEnum:Nr,ZodEffects:ss,ZodOptional:Fn,ZodNullable:Bn,ZodDiscriminatedUnion:Un,ZodBranded:as,ZodDate:Yn,ZodCatch:jn,ZodPipeline:is,ZodLazy:ps,ZodReadonly:Kn,[D]:kn,[Ae]:Nn,[Le]:_n,[je]:Gn,[Q]:cs},It=(e,{isResponse:t,prev:r})=>{if(Pt(r))return{};let{description:o}=e,n=e instanceof S.ZodLazy,i=r.type!==void 0,a=t&&Re(e),p=!n&&i&&!a&&e.isNullable(),d=n?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Br(r)),d.length&&(c.examples=d.slice()),c},zt=(e,t)=>re.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),At=(e,t)=>{if(Pt(e))return e;let r={...e};return r.properties&&(r.properties=rt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>rt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>At(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>At(o,t))),r},Gr=e=>Pt(e)?e:rt(["examples"],e),_r=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,brandHandling:f,description:m=`${e.toUpperCase()} ${t} ${yt(n)} response ${c?l:""}`.trim()})=>{let h=Gr(ee(r,{rules:{...f,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),C={schema:d==="components"?p(w(m),h):h,examples:$r(r,!0)};return{description:m,content:Ne(ot(o,[C]))}},ls=()=>({type:"http",scheme:"basic"}),ms=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},us=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},fs=({name:e})=>({type:"apiKey",in:"header",name:e}),ys=({name:e})=>({type:"apiKey",in:"cookie",name:e}),gs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),hs=({flows:e={}})=>({type:"oauth2",flows:ue(t=>({...t,scopes:t.scopes||{}}),Pn(bn,e))}),Yr=(e,t)=>{let r={basic:ls,bearer:ms,input:us,header:fs,cookie:ys,openid:gs,oauth2:hs};return Ge(e,o=>r[o.type](o,t))},nt=e=>"or"in e?e.or.map(t=>"and"in t?Sn(ue(({name:r,scopes:o})=>Mr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?nt(xt(e)):nt({or:[e]}),Qr=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let f=Gr(At(ee(r,{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),m={schema:p==="components"?a(w(l),f):f,examples:$r(r,!1,c)};return{description:l,content:Ne(ot(o,[m]))}},Jr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),wt=e=>e.length<=Lr?e:e.slice(0,Lr-1)+"\u2026";var Et=class extends bs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;responseVariants=Ss(W);makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||w(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&xs.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:c="inline",serializer:l=Fe}){super(),this.addInfo({title:o,version:n});for(let m of typeof i=="string"?[i]:i)this.addServer({url:m});X({routing:t,onEndpoint:(m,h,C)=>{let b=C,Z={path:h,method:b,endpoint:m,composition:c,serializer:l,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[R,x]=["short","long"].map(m.getDescription.bind(m)),ge=R?wt(R):d&&x?wt(x):void 0,k=m.getTags(),$=r.inputSources?.[b]||dt[b],ne=this.ensureUniqOperationId(h,b,m.getOperationId(b)),he=Vr({...Z,inputSources:$,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:h,operationId:ne})}),Me={};for(let j of this.responseVariants){let V=m.getResponses(j);for(let{mimeTypes:xe,schema:T,statusCodes:O}of V)for(let A of O)Me[A]=_r({...Z,variant:j,schema:T,mimeTypes:xe,statusCode:A,hasMultipleStatusCodes:V.length>1||O.length>1,description:a?.[`${j}Response`]?.call(null,{method:b,path:h,operationId:ne,statusCode:A})})}let ct=$.includes("body")?Qr({...Z,paramNames:Ts("name",he),schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:h,operationId:ne})}):void 0,Ue=nt(Ge(Yr(m.getSecurity(),$),j=>{let V=this.ensureUniqSecuritySchemaName(j),xe=["oauth2","openIdConnect"].includes(j.type)?m.getScopes().slice():[];return this.addSecurityScheme(V,j),{name:V,scopes:xe}}));this.addPath(Fr(h),{[b]:{operationId:ne,summary:ge,description:x,tags:k.length>0?k:void 0,parameters:he.length>0?he:void 0,requestBody:ct,security:Ue.length>0?Ue:void 0,responses:Me}})}}),this.rootDoc.tags=r.tags?Jr(r.tags):[]}};import{createRequest as Os,createResponse as Rs}from"node-mocks-http";var As=e=>Os({...e,headers:{"content-type":P.json,...e?.headers}}),Ps=e=>Rs(e),Cs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:pr(o)?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Is=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=As(e),i=Ps({req:n,...t});i.req=t?.req||n,n.res=i;let a=Cs(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},zs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Is(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}};import E from"typescript";import N from"typescript";import{chain as Wr,toPairs as Xr}from"ramda";var s=N.factory,K=[s.createModifier(N.SyntaxKind.ExportKeyword)],ws=[s.createModifier(N.SyntaxKind.AsyncKeyword)],Es=[s.createModifier(N.SyntaxKind.PublicKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],eo=[s.createModifier(N.SyntaxKind.ProtectedKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],Zt=s.createTemplateHead(""),fe=s.createTemplateTail(""),vt=s.createTemplateMiddle(" "),jt=e=>s.createTemplateLiteralType(Zt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?fe:vt))),Lt=jt(["M","P"]),st=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),it=(e,t)=>Wr(([r,o])=>[st(s.createIdentifier(r),o,t)],Xr(e)),Nt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),to=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),ro=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),B=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],N.NodeFlags.Const),kt=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),at=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,t),oo=(e,t,r)=>s.createPropertyDeclaration(Es,e,void 0,t,r),no=(e,t,r)=>s.createClassDeclaration(K,e,void 0,void 0,[t,...r]),so=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),io=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(N.SyntaxKind.AnyKeyword)]),ao=(e,t,r)=>s.createInterfaceDeclaration(K,e,void 0,t,r),Zs=Wr(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),po=e=>Zs(Xr(e)),Mt=(e,t,r)=>s.createArrowFunction(r?ws:void 0,void 0,e.map(o=>st(o)),void 0,void 0,t),Ut=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,it({acc:void 0,key:void 0}),void 0,void 0,t),r]),co=(...e)=>`"${e.join(" ")}"`;var lo=["get","post","put","delete","patch"];import y from"typescript";import{z as Ft}from"zod";import q from"typescript";var{factory:pt}=q,Ht=(e,t)=>{q.addSyntheticLeadingComment(e,q.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ye=(e,t,r)=>{let o=pt.createTypeAliasDeclaration(void 0,pt.createIdentifier(t),void 0,e);return r&&Ht(o,r),o},Dt=(e,t)=>{let r=q.createSourceFile("print.ts","",q.ScriptTarget.Latest,!1,q.ScriptKind.TS);return q.createPrinter(t).printNode(q.EmitHint.Unspecified,e,r)},vs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,mo=e=>vs.test(e)?pt.createIdentifier(e):pt.createStringLiteral(e);var{factory:u}=y,js={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},Ls=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),Ns=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Re(a)?a instanceof Ft.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,mo(i),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Ht(d,a.description),d});return u.createTypeLiteralNode(n)},ks=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Ms=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),uo=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),Us=e=>js?.[e.kind],Hs=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Ke(e,Us(o)),i={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(n&&i[n]||y.SyntaxKind.AnyKeyword)}return o},Ds=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Fs=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Ks=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),Bs=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),qs=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),$s=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),Vs=({_def:e},{next:t})=>t(e.innerType),oe=e=>()=>u.createKeywordTypeNode(e),Gs=(e,{next:t})=>t(e.unwrap()),_s=(e,{next:t})=>t(e.unwrap()),Ys=({_def:e},{next:t})=>t(e.innerType),Qs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),Js=()=>u.createLiteralTypeNode(u.createNull()),Ws=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,u.createLiteralTypeNode(u.createNull())),r(i,o(e)))},Xs=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),n=u.createUnionTypeNode([r,o]);return t instanceof Ft.ZodString?r:t instanceof Ft.ZodUnion?n:o},ei=(e,{next:t})=>t(e.unwrap().shape.raw),ti={ZodString:oe(y.SyntaxKind.StringKeyword),ZodNumber:oe(y.SyntaxKind.NumberKeyword),ZodBigInt:oe(y.SyntaxKind.BigIntKeyword),ZodBoolean:oe(y.SyntaxKind.BooleanKeyword),ZodAny:oe(y.SyntaxKind.AnyKeyword),[je]:oe(y.SyntaxKind.StringKeyword),[Le]:oe(y.SyntaxKind.StringKeyword),ZodNull:Js,ZodArray:ks,ZodTuple:Bs,ZodRecord:qs,ZodObject:Ns,ZodLiteral:Ls,ZodIntersection:$s,ZodUnion:uo,ZodDefault:Vs,ZodEnum:Ms,ZodNativeEnum:Ds,ZodEffects:Hs,ZodOptional:Fs,ZodNullable:Ks,ZodDiscriminatedUnion:uo,ZodBranded:Gs,ZodCatch:Ys,ZodPipeline:Qs,ZodLazy:Ws,ZodReadonly:_s,[D]:Xs,[Q]:ei},ke=(e,{brandHandling:t,ctx:r})=>ee(e,{rules:{...t,...ti},onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),ctx:r});var Kt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ye(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=Fe,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){X({routing:t,onEndpoint:(T,O,A)=>{let se={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},be=w(A,O,"input"),Se=ke(T.getSchema("input"),{brandHandling:r,ctx:{...se,isResponse:!1}}),I=i?w(A,O,"positive.response"):void 0,Bt=T.getSchema("positive"),qt=i?ke(Bt,{brandHandling:r,ctx:{...se,isResponse:!0}}):void 0,Te=i?w(A,O,"negative.response"):void 0,$t=T.getSchema("negative"),Vt=i?ke($t,{brandHandling:r,ctx:{...se,isResponse:!0}}):void 0,Gt=w(A,O,"response"),fo=I&&Te?s.createUnionTypeNode([s.createTypeReferenceNode(I),s.createTypeReferenceNode(Te)]):ke(Bt.or($t),{brandHandling:r,ctx:{...se,isResponse:!0}});this.program.push(ye(Se,be)),qt&&I&&this.program.push(ye(qt,I)),Vt&&Te&&this.program.push(ye(Vt,Te)),this.program.push(ye(fo,Gt)),A!=="options"&&(this.paths.push(O),this.registry.set({method:A,path:O},{input:be,positive:I,negative:Te,response:Gt,isJson:T.getMimeTypes("positive").includes(P.json),tags:T.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(kt(this.ids.pathType,this.paths)),this.program.push(kt(this.ids.methodType,lo)),this.program.push(at(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(E.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,E.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let d=[],c=[];for(let[{method:T,path:O},{isJson:A,tags:se,...be}]of this.registry){let Se=co(T,O);for(let I of this.interfaces)I.kind in be&&I.props.push(ro(Se,be[I.kind]));o!=="types"&&(A&&d.push(s.createPropertyAssignment(Se,s.createTrue())),c.push(s.createPropertyAssignment(Se,s.createArrayLiteralExpression(se.map(I=>s.createStringLiteral(I))))))}for(let{id:T,props:O}of this.interfaces)this.program.push(ao(T,p,O));if(o==="types")return;let l=s.createVariableStatement(K,B(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(d))),f=s.createVariableStatement(K,B(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),m=at(this.ids.providerType,s.createFunctionTypeNode(po({M:this.ids.methodType,P:this.ids.pathType}),it({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Lt)}),so(this.ids.responseInterface,Lt))),h=at(this.ids.implementationType,s.createFunctionTypeNode(void 0,it({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(E.SyntaxKind.StringKeyword),params:Nt(E.SyntaxKind.StringKeyword,E.SyntaxKind.AnyKeyword)}),io())),C=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,fe)]),b=Ut(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[C,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),Z=Ut(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[C]),E.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),R=no(this.ids.clientClass,to([st(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),eo)]),[oo(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,Z]),!0))]);this.program.push(l,f,m,h,R);let x=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ge=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(P.json))]),void 0,this.ids.undefinedValue)),k=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),$=s.createVariableStatement(void 0,B(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,fe)]),s.createObjectLiteralExpression([x,ge,k])])))),ne=s.createVariableStatement(void 0,B(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),he=s.createVariableStatement(void 0,B(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),fe)])))),[Me,ct]=["json","text"].map(T=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,T),void 0,void 0))),Ue=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(Zt,[s.createTemplateSpan(this.ids.methodParameter,vt),s.createTemplateSpan(this.ids.pathParameter,fe)]),E.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Me])),j=s.createVariableStatement(K,B(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([ne,he,$,Ue,ct]),!0),s.createTypeReferenceNode(this.ids.implementationType))),V=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),xe=s.createVariableStatement(void 0,B(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(j,xe,V)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
22
22
  `):void 0}print(t){let r=this.printUsage(t),o=r&&E.addSyntheticLeadingComment(E.addSyntheticLeadingComment(s.createEmptyStatement(),E.SyntaxKind.SingleLineCommentTrivia," Usage example:"),E.SyntaxKind.MultiLineCommentTrivia,`
23
23
  ${r}`);return this.program.concat(o||[]).map((n,i)=>Dt(n,i<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
24
24
 
25
- `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await me("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let i=this.print(t);return o?o(i):i}};var Xs={dateIn:Er,dateOut:Zr,file:Ge,upload:Wt,raw:Jt};export{Ee as BuiltinLogger,Ze as DependsOnMethod,Et as Documentation,z as DocumentationError,we as EndpointsFactory,L as InputValidationError,Kt as Integration,F as Middleware,Oe as MissingPeerError,V as OutputValidationError,Ie as ResultHandler,se as RoutingError,ve as ServeStatic,Bo as arrayEndpointsFactory,Tt as arrayResultHandler,ln as attachRouting,vo as createConfig,mn as createServer,Ko as defaultEndpointsFactory,ze as defaultResultHandler,Xs as ez,H as getExamples,U as getMessageFromError,Fe as getStatusCodeFromError,Ps as testEndpoint};
25
+ `)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await me("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let n=this.printUsage(t);this.usage=n&&o?[await o(n)]:this.usage;let i=this.print(t);return o?o(i):i}};var ri={dateIn:vr,dateOut:jr,file:$e,upload:Wt,raw:Jt};export{we as BuiltinLogger,Ee as DependsOnMethod,Et as Documentation,z as DocumentationError,ze as EndpointsFactory,L as InputValidationError,Kt as Integration,F as Middleware,Oe as MissingPeerError,G as OutputValidationError,Ce as ResultHandler,ie as RoutingError,Ze as ServeStatic,$o as arrayEndpointsFactory,Tt as arrayResultHandler,un as attachRouting,Lo as createConfig,fn as createServer,qo as defaultEndpointsFactory,Ie as defaultResultHandler,ri as ez,H as getExamples,U as getMessageFromError,De as getStatusCodeFromError,zs as testEndpoint};
@@ -1 +1 @@
1
- "use strict";var p=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var y=(s,t)=>{for(var e in t)p(s,e,{get:t[e],enumerable:!0})},g=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of m(t))!u.call(s,i)&&i!==e&&p(s,i,{get:()=>t[i],enumerable:!(r=d(t,i))||r.enumerable});return s};var f=s=>g(p({},"__esModule",{value:!0}),s);var w={};y(w,{default:()=>k});module.exports=f(w);var c=require("@typescript-eslint/utils");var l="express-zod-api";var h="testEndpoint",n={createLogger:"BuiltinLogger",createResultHandler:"ResultHandler",createMiddleware:"Middleware"},o={getPositiveResponse:"positive",getNegativeResponse:"negative",responseProps:"responseOptions",middleware:"handler"},b={fnMethod:null},a=(s,t)=>typeof s=="string"&&s in t,v=c.ESLintUtils.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{change:"Change {{subject}} {{from}} to {{to}}.",remove:"Remove {{subject}} {{name}}."}},defaultOptions:[],create:s=>({ImportDeclaration:t=>{if(t.source.value===l){for(let e of t.specifiers)if(e.type==="ImportSpecifier"&&a(e.imported.name,n)){let r=n[e.imported.name];s.report({node:e.imported,messageId:"change",data:{subject:"import",from:e.imported.name,to:r},fix:i=>i.replaceText(e,r)})}}},CallExpression:t=>{if(t.callee.type==="Identifier"&&a(t.callee.name,n)){let e=`new ${n[t.callee.name]}`;s.report({node:t.callee,messageId:"change",data:{subject:"call",from:t.callee.name,to:e},fix:r=>r.replaceText(t.callee,e)})}if(t.callee.type==="Identifier"&&t.callee.name===h&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let e of t.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"){if(a(e.key.name,o)){let r=o[e.key.name];s.report({node:e,messageId:"change",data:{subject:"property",from:e.key.name,to:r},fix:i=>i.replaceText(e.key,r)})}a(e.key.name,b)&&s.report({node:e,messageId:"remove",data:{subject:"property",name:e.key.name},fix:r=>s.sourceCode.getTokenAfter(e)?.value===","&&e.range?r.removeRange([e.range[0],e.range[1]+1]):r.remove(e)})}}},NewExpression:t=>{if(t.callee.type==="Identifier"&&[n.createResultHandler,n.createMiddleware].includes(t.callee.name)&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let e of t.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"&&a(e.key.name,o)){let r=o[e.key.name];s.report({node:e,messageId:"change",data:{subject:"property",from:e.key.name,to:r},fix:i=>i.replaceText(e.key,r)})}}},Identifier:t=>{t.name==="MockOverrides"&&t.parent.type==="TSInterfaceDeclaration"&&s.report({node:t,messageId:"remove",data:{subject:"augmentation",name:t.name},fix:e=>e.remove(t.parent)})}})}),k={rules:{v20:v}};
1
+ "use strict";var p=Object.defineProperty;var d=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var u=Object.prototype.hasOwnProperty;var y=(s,t)=>{for(var e in t)p(s,e,{get:t[e],enumerable:!0})},g=(s,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of m(t))!u.call(s,i)&&i!==e&&p(s,i,{get:()=>t[i],enumerable:!(r=d(t,i))||r.enumerable});return s};var f=s=>g(p({},"__esModule",{value:!0}),s);var w={};y(w,{default:()=>k});module.exports=f(w);var c=require("@typescript-eslint/utils");var l="express-zod-api";var x="testEndpoint",n={createLogger:"BuiltinLogger",createResultHandler:"ResultHandler",createMiddleware:"Middleware"},o={getPositiveResponse:"positive",getNegativeResponse:"negative",responseProps:"responseOptions",middleware:"handler"},b={fnMethod:null},a=(s,t)=>typeof s=="string"&&s in t,v=c.ESLintUtils.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{change:"Change {{subject}} {{from}} to {{to}}.",remove:"Remove {{subject}} {{name}}."}},defaultOptions:[],create:s=>({ImportDeclaration:t=>{if(t.source.value===l){for(let e of t.specifiers)if(e.type==="ImportSpecifier"&&a(e.imported.name,n)){let r=n[e.imported.name];s.report({node:e.imported,messageId:"change",data:{subject:"import",from:e.imported.name,to:r},fix:i=>i.replaceText(e,r)})}}},CallExpression:t=>{if(t.callee.type==="Identifier"&&a(t.callee.name,n)){let e=`new ${n[t.callee.name]}`;s.report({node:t.callee,messageId:"change",data:{subject:"call",from:t.callee.name,to:e},fix:r=>r.replaceText(t.callee,e)})}if(t.callee.type==="Identifier"&&t.callee.name===x&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let e of t.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"){if(a(e.key.name,o)){let r=o[e.key.name];s.report({node:e,messageId:"change",data:{subject:"property",from:e.key.name,to:r},fix:i=>i.replaceText(e.key,r)})}a(e.key.name,b)&&s.report({node:e,messageId:"remove",data:{subject:"property",name:e.key.name},fix:r=>s.sourceCode.getTokenAfter(e)?.value===","&&e.range?r.removeRange([e.range[0],e.range[1]+1]):r.remove(e)})}}},NewExpression:t=>{if(t.callee.type==="Identifier"&&[n.createResultHandler,n.createMiddleware].includes(t.callee.name)&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let e of t.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"&&a(e.key.name,o)){let r=o[e.key.name];s.report({node:e,messageId:"change",data:{subject:"property",from:e.key.name,to:r},fix:i=>i.replaceText(e.key,r)})}}},Identifier:t=>{t.name==="MockOverrides"&&t.parent.type==="TSInterfaceDeclaration"&&s.report({node:t,messageId:"remove",data:{subject:"augmentation",name:t.name},fix:e=>e.remove(t.parent)})}})}),k={rules:{v20:v}};
@@ -1 +1 @@
1
- import{ESLintUtils as c}from"@typescript-eslint/utils";var p="express-zod-api";var d="testEndpoint",i={createLogger:"BuiltinLogger",createResultHandler:"ResultHandler",createMiddleware:"Middleware"},o={getPositiveResponse:"positive",getNegativeResponse:"negative",responseProps:"responseOptions",middleware:"handler"},m={fnMethod:null},a=(r,t)=>typeof r=="string"&&r in t,u=c.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{change:"Change {{subject}} {{from}} to {{to}}.",remove:"Remove {{subject}} {{name}}."}},defaultOptions:[],create:r=>({ImportDeclaration:t=>{if(t.source.value===p){for(let e of t.specifiers)if(e.type==="ImportSpecifier"&&a(e.imported.name,i)){let s=i[e.imported.name];r.report({node:e.imported,messageId:"change",data:{subject:"import",from:e.imported.name,to:s},fix:n=>n.replaceText(e,s)})}}},CallExpression:t=>{if(t.callee.type==="Identifier"&&a(t.callee.name,i)){let e=`new ${i[t.callee.name]}`;r.report({node:t.callee,messageId:"change",data:{subject:"call",from:t.callee.name,to:e},fix:s=>s.replaceText(t.callee,e)})}if(t.callee.type==="Identifier"&&t.callee.name===d&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let e of t.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"){if(a(e.key.name,o)){let s=o[e.key.name];r.report({node:e,messageId:"change",data:{subject:"property",from:e.key.name,to:s},fix:n=>n.replaceText(e.key,s)})}a(e.key.name,m)&&r.report({node:e,messageId:"remove",data:{subject:"property",name:e.key.name},fix:s=>r.sourceCode.getTokenAfter(e)?.value===","&&e.range?s.removeRange([e.range[0],e.range[1]+1]):s.remove(e)})}}},NewExpression:t=>{if(t.callee.type==="Identifier"&&[i.createResultHandler,i.createMiddleware].includes(t.callee.name)&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let e of t.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"&&a(e.key.name,o)){let s=o[e.key.name];r.report({node:e,messageId:"change",data:{subject:"property",from:e.key.name,to:s},fix:n=>n.replaceText(e.key,s)})}}},Identifier:t=>{t.name==="MockOverrides"&&t.parent.type==="TSInterfaceDeclaration"&&r.report({node:t,messageId:"remove",data:{subject:"augmentation",name:t.name},fix:e=>e.remove(t.parent)})}})}),x={rules:{v20:u}};export{x as default};
1
+ import{ESLintUtils as c}from"@typescript-eslint/utils";var p="express-zod-api";var d="testEndpoint",i={createLogger:"BuiltinLogger",createResultHandler:"ResultHandler",createMiddleware:"Middleware"},o={getPositiveResponse:"positive",getNegativeResponse:"negative",responseProps:"responseOptions",middleware:"handler"},m={fnMethod:null},a=(r,t)=>typeof r=="string"&&r in t,u=c.RuleCreator.withoutDocs({meta:{type:"problem",fixable:"code",schema:[],messages:{change:"Change {{subject}} {{from}} to {{to}}.",remove:"Remove {{subject}} {{name}}."}},defaultOptions:[],create:r=>({ImportDeclaration:t=>{if(t.source.value===p){for(let e of t.specifiers)if(e.type==="ImportSpecifier"&&a(e.imported.name,i)){let s=i[e.imported.name];r.report({node:e.imported,messageId:"change",data:{subject:"import",from:e.imported.name,to:s},fix:n=>n.replaceText(e,s)})}}},CallExpression:t=>{if(t.callee.type==="Identifier"&&a(t.callee.name,i)){let e=`new ${i[t.callee.name]}`;r.report({node:t.callee,messageId:"change",data:{subject:"call",from:t.callee.name,to:e},fix:s=>s.replaceText(t.callee,e)})}if(t.callee.type==="Identifier"&&t.callee.name===d&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let e of t.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"){if(a(e.key.name,o)){let s=o[e.key.name];r.report({node:e,messageId:"change",data:{subject:"property",from:e.key.name,to:s},fix:n=>n.replaceText(e.key,s)})}a(e.key.name,m)&&r.report({node:e,messageId:"remove",data:{subject:"property",name:e.key.name},fix:s=>r.sourceCode.getTokenAfter(e)?.value===","&&e.range?s.removeRange([e.range[0],e.range[1]+1]):s.remove(e)})}}},NewExpression:t=>{if(t.callee.type==="Identifier"&&[i.createResultHandler,i.createMiddleware].includes(t.callee.name)&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let e of t.arguments[0].properties)if(e.type==="Property"&&e.key.type==="Identifier"&&a(e.key.name,o)){let s=o[e.key.name];r.report({node:e,messageId:"change",data:{subject:"property",from:e.key.name,to:s},fix:n=>n.replaceText(e.key,s)})}}},Identifier:t=>{t.name==="MockOverrides"&&t.parent.type==="TSInterfaceDeclaration"&&r.report({node:t,messageId:"remove",data:{subject:"augmentation",name:t.name},fix:e=>e.remove(t.parent)})}})}),h={rules:{v20:u}};export{h as default};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "20.14.0",
3
+ "version": "20.14.2",
4
4
  "description": "A Typescript library 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": {
@@ -13,9 +13,8 @@
13
13
  "url": "https://robintail.cz",
14
14
  "email": "me@robintail.cz"
15
15
  },
16
- "bugs": {
17
- "url": "https://github.com/RobinTail/express-zod-api/issues"
18
- },
16
+ "bugs": "https://github.com/RobinTail/express-zod-api/issues",
17
+ "funding": "https://github.com/sponsors/RobinTail",
19
18
  "scripts": {
20
19
  "start": "tsx example/index.ts",
21
20
  "build": "yarn build:compile && yarn build:tests && yarn build:assets",
@@ -78,7 +77,7 @@
78
77
  },
79
78
  "dependencies": {
80
79
  "ansis": "^3.2.0",
81
- "node-mocks-http": "^1.16.0",
80
+ "node-mocks-http": "^1.16.1",
82
81
  "openapi3-ts": "^4.4.0",
83
82
  "ramda": "^0.30.1"
84
83
  },
@@ -139,7 +138,7 @@
139
138
  "eslint-config-prettier": "^9.1.0",
140
139
  "eslint-plugin-allowed-dependencies": "^1.0.0",
141
140
  "eslint-plugin-prettier": "^5.1.3",
142
- "eslint-plugin-unicorn": "^55.0.0",
141
+ "eslint-plugin-unicorn": "^56.0.0",
143
142
  "express": "^5.0.0",
144
143
  "express-fileupload": "^1.5.0",
145
144
  "globals": "^15.3.0",