express-zod-api 19.2.0 → 20.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +91 -0
- package/README.md +41 -55
- package/dist/index.cjs +8 -8
- package/dist/index.d.cts +145 -100
- package/dist/index.d.ts +145 -100
- package/dist/index.js +9 -9
- package/package.json +7 -18
package/CHANGELOG.md
CHANGED
|
@@ -1,7 +1,98 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Version 20
|
|
4
|
+
|
|
5
|
+
### v20.0.0
|
|
6
|
+
|
|
7
|
+
- Method `createLogger()` removed — use `new BuiltinLogger()` instead if needed;
|
|
8
|
+
- Method `createResultHandler` removed — use `new ResultHandler()` instead:
|
|
9
|
+
- The argument's properties renamed: `getPositiveResponse` to `positive` and `getNegativeResponse` to `negative`;
|
|
10
|
+
- Both properties can now accept static values (not only functions).
|
|
11
|
+
- Method `createMiddleware()` removed — use either `new Middleware()` or `EndpointsFactory::addMiddleware()` instead:
|
|
12
|
+
- The argument's property `middleware` renamed to `handler`.
|
|
13
|
+
- Method `testEndpoint()` was changed:
|
|
14
|
+
- It was detached from any testing frameworks, `fnMethod` property removed from the argument;
|
|
15
|
+
- Mocked request and response are now fully operational and do not require to mock anything to do the job;
|
|
16
|
+
- The `responseProps` property changed to `responseOptions`, it's no longer meant to be used for custom props;
|
|
17
|
+
- The returned entities `requestMock`, `responseMock` and `loggerMock` no longer rely on testing framework for props.
|
|
18
|
+
Instead, they provide methods to assert expectations in tests:
|
|
19
|
+
- `responseMock._getStatusCode()`, `responseMock._getHeaders()`, `responseMock._getData()`, `loggerMock._getLogs()`;
|
|
20
|
+
- See [the documentation of node-mocks-http library](https://www.npmjs.com/package/node-mocks-http) for details.
|
|
21
|
+
- How to migrate:
|
|
22
|
+
- Consider using the provided ESLint plugin `migration` in order to apply changes automatically (except assertions);
|
|
23
|
+
- Or follow the code samples below in order to rename/remove entities manually as described above.
|
|
24
|
+
|
|
25
|
+
```js
|
|
26
|
+
// eslint.config.mjs — minimal config to apply migrations automatically using "eslint --fix":
|
|
27
|
+
import parser from "@typescript-eslint/parser";
|
|
28
|
+
import { migration } from "express-zod-api";
|
|
29
|
+
|
|
30
|
+
export default [{ languageOptions: { parser } }, migration];
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
// before
|
|
35
|
+
createResultHandler({
|
|
36
|
+
getPositiveResponse: (data) => z.object({ data }),
|
|
37
|
+
getNegativeResponse: () => ({
|
|
38
|
+
schema: z.string(),
|
|
39
|
+
mimeType: "text/plain",
|
|
40
|
+
}),
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
// after
|
|
44
|
+
new ResultHandler({
|
|
45
|
+
positive: (data) => z.object({ data }),
|
|
46
|
+
negative: { schema: z.string(), mimeType: "text/plain" }, // can be static now
|
|
47
|
+
});
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
```ts
|
|
51
|
+
// before
|
|
52
|
+
factory.addMiddleware(
|
|
53
|
+
createMiddleware({
|
|
54
|
+
input: z.object({}),
|
|
55
|
+
middleware: async () => ({}),
|
|
56
|
+
}),
|
|
57
|
+
);
|
|
58
|
+
|
|
59
|
+
// after
|
|
60
|
+
factory // variant 1:
|
|
61
|
+
.addMiddleware(
|
|
62
|
+
new Middleware({
|
|
63
|
+
input: z.object({}),
|
|
64
|
+
handler: async () => ({}),
|
|
65
|
+
}),
|
|
66
|
+
) // variant 2: short syntax now available:
|
|
67
|
+
.addMiddleware({ input: z.object({}), handler: async () => ({}) });
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
// before
|
|
72
|
+
declare module "express-zod-api" {
|
|
73
|
+
interface MockOverrides extends Mock {} // remove it
|
|
74
|
+
}
|
|
75
|
+
const { responseMock: responseMockBefore, loggerMock: loggerMockBefore } =
|
|
76
|
+
testEndpoint({ endpoint });
|
|
77
|
+
expect(responseMockBefore.set).toHaveBeenCalledWith("X-Custom", "one");
|
|
78
|
+
expect(responseMockBefore.status).toHaveBeenCalledWith(200);
|
|
79
|
+
expect(loggerMockBefore.error).not.toHaveBeenCalled();
|
|
80
|
+
|
|
81
|
+
// after
|
|
82
|
+
const { responseMock, loggerMock } = testEndpoint({ endpoint });
|
|
83
|
+
expect(responseMock._getStatusCode()).toBe(200);
|
|
84
|
+
expect(responseMock._getHeaders()).toHaveProperty("x-custom", "one"); // lower case!
|
|
85
|
+
expect(responseMock._getData()).toBe(JSON.stringify({ status: "success" })); // or:
|
|
86
|
+
expect(JSON.parse(responseMock._getData())).toEqual({ status: "success" });
|
|
87
|
+
expect(loggerMock._getLogs().error).toHaveLength(0);
|
|
88
|
+
```
|
|
89
|
+
|
|
3
90
|
## Version 19
|
|
4
91
|
|
|
92
|
+
### v19.2.1
|
|
93
|
+
|
|
94
|
+
- `openapi3-ts` version is 4.3.2 (fixed distribution).
|
|
95
|
+
|
|
5
96
|
### v19.2.0
|
|
6
97
|
|
|
7
98
|
- Feat: `.child()` method for the built-in logger:
|
package/README.md
CHANGED
|
@@ -97,9 +97,6 @@ Therefore, many basic tasks can be accomplished faster and easier, in particular
|
|
|
97
97
|
- Client side types — inspired by [zod-to-ts](https://github.com/sachinraja/zod-to-ts).
|
|
98
98
|
- File uploads — [Express-FileUpload](https://github.com/richardgirges/express-fileupload)
|
|
99
99
|
(based on [Busboy](https://github.com/mscdex/busboy)).
|
|
100
|
-
- Supports any testing framework having a function mocking method;
|
|
101
|
-
- [Jest](https://github.com/jestjs/jest) and [Vitest](https://github.com/vitest-dev/vitest)
|
|
102
|
-
are both supported automatically.
|
|
103
100
|
|
|
104
101
|
## Concept
|
|
105
102
|
|
|
@@ -241,9 +238,9 @@ Here is an example of the authentication middleware, that checks a `key` from in
|
|
|
241
238
|
```typescript
|
|
242
239
|
import { z } from "zod";
|
|
243
240
|
import createHttpError from "http-errors";
|
|
244
|
-
import {
|
|
241
|
+
import { Middleware } from "express-zod-api";
|
|
245
242
|
|
|
246
|
-
const authMiddleware =
|
|
243
|
+
const authMiddleware = new Middleware({
|
|
247
244
|
security: {
|
|
248
245
|
// this information is optional and used for generating documentation
|
|
249
246
|
and: [
|
|
@@ -254,7 +251,7 @@ const authMiddleware = createMiddleware({
|
|
|
254
251
|
input: z.object({
|
|
255
252
|
key: z.string().min(1),
|
|
256
253
|
}),
|
|
257
|
-
|
|
254
|
+
handler: async ({ input: { key }, request, logger }) => {
|
|
258
255
|
logger.debug("Checking the key and token");
|
|
259
256
|
const user = await db.Users.findOne({ key });
|
|
260
257
|
if (!user) {
|
|
@@ -281,16 +278,21 @@ const yourEndpoint = defaultEndpointsFactory
|
|
|
281
278
|
});
|
|
282
279
|
```
|
|
283
280
|
|
|
284
|
-
You can
|
|
281
|
+
You can create a new factory by connecting as many middlewares as you want — they will be executed in the specified
|
|
282
|
+
order for all the endpoints produced on that factory. You may also use a shorter inline syntax within the
|
|
283
|
+
`.addMiddleware()` method, and have access to the output of the previously executed middlewares in chain as `options`:
|
|
285
284
|
|
|
286
285
|
```typescript
|
|
287
286
|
import { defaultEndpointsFactory } from "express-zod-api";
|
|
288
287
|
|
|
289
|
-
const
|
|
288
|
+
const factory = defaultEndpointsFactory
|
|
289
|
+
.addMiddleware(authMiddleware) // add Middleware instance or use shorter syntax:
|
|
290
|
+
.addMiddleware({
|
|
291
|
+
input: z.object({}),
|
|
292
|
+
handler: async ({ options: { user } }) => ({}), // options.user from authMiddleware
|
|
293
|
+
});
|
|
290
294
|
```
|
|
291
295
|
|
|
292
|
-
You can connect as many middlewares as you want, they will be executed in order.
|
|
293
|
-
|
|
294
296
|
## Options
|
|
295
297
|
|
|
296
298
|
In case you'd like to provide your endpoints with options that do not depend on Request, like non-persistent connection
|
|
@@ -312,9 +314,9 @@ const endpointsFactory = defaultEndpointsFactory.addOptions(async () => {
|
|
|
312
314
|
custom [Result Handler](#response-customization):
|
|
313
315
|
|
|
314
316
|
```typescript
|
|
315
|
-
import {
|
|
317
|
+
import { ResultHandler } from "express-zod-api";
|
|
316
318
|
|
|
317
|
-
const resultHandlerWithCleanup =
|
|
319
|
+
const resultHandlerWithCleanup = new ResultHandler({
|
|
318
320
|
handler: ({ options }) => {
|
|
319
321
|
// necessary to check for certain option presence:
|
|
320
322
|
if ("db" in options && options.db) {
|
|
@@ -369,9 +371,9 @@ Validation errors are reported in a response with a status code `400`.
|
|
|
369
371
|
|
|
370
372
|
```typescript
|
|
371
373
|
import { z } from "zod";
|
|
372
|
-
import {
|
|
374
|
+
import { Middleware } from "express-zod-api";
|
|
373
375
|
|
|
374
|
-
const nicknameConstraintMiddleware =
|
|
376
|
+
const nicknameConstraintMiddleware = new Middleware({
|
|
375
377
|
input: z.object({
|
|
376
378
|
nickname: z
|
|
377
379
|
.string()
|
|
@@ -719,18 +721,17 @@ You can create your own result handler by using this example as a template:
|
|
|
719
721
|
```typescript
|
|
720
722
|
import { z } from "zod";
|
|
721
723
|
import {
|
|
722
|
-
|
|
723
|
-
IOSchema,
|
|
724
|
+
ResultHandler,
|
|
724
725
|
getStatusCodeFromError,
|
|
725
726
|
getMessageFromError,
|
|
726
727
|
} from "express-zod-api";
|
|
727
728
|
|
|
728
|
-
const yourResultHandler =
|
|
729
|
-
|
|
730
|
-
schema: z.object({ data
|
|
729
|
+
const yourResultHandler = new ResultHandler({
|
|
730
|
+
positive: (data) => ({
|
|
731
|
+
schema: z.object({ data }),
|
|
731
732
|
mimeType: "application/json", // optinal, or mimeTypes for array
|
|
732
733
|
}),
|
|
733
|
-
|
|
734
|
+
negative: z.object({ error: z.string() }),
|
|
734
735
|
handler: ({ error, input, output, request, response, logger }) => {
|
|
735
736
|
if (!error) {
|
|
736
737
|
// your implementation
|
|
@@ -770,12 +771,9 @@ The response schema generally may be just `z.string()`, but I made more specific
|
|
|
770
771
|
|
|
771
772
|
```typescript
|
|
772
773
|
const fileStreamingEndpointsFactory = new EndpointsFactory(
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
mimeType: "image/*",
|
|
777
|
-
}),
|
|
778
|
-
getNegativeResponse: () => ({ schema: z.string(), mimeType: "text/plain" }),
|
|
774
|
+
new ResultHandler({
|
|
775
|
+
positive: { schema: ez.file("buffer"), mimeType: "image/*" },
|
|
776
|
+
negative: { schema: z.string(), mimeType: "text/plain" },
|
|
779
777
|
handler: ({ response, error, output }) => {
|
|
780
778
|
if (error) {
|
|
781
779
|
response.status(400).send(error.message);
|
|
@@ -906,21 +904,14 @@ then consider using the `beforeRouting` [option in config instead](#using-native
|
|
|
906
904
|
## Testing endpoints
|
|
907
905
|
|
|
908
906
|
The way to test endpoints is to mock the request, response, and logger objects, invoke the `execute()` method, and
|
|
909
|
-
assert the expectations
|
|
910
|
-
makes mocking easier.
|
|
911
|
-
(
|
|
912
|
-
|
|
913
|
-
However, in order to have proper mocking types in your own tests, you also need to specify `MockOverrides` once in your
|
|
914
|
-
tests excplicitly, so the tests should look this way:
|
|
907
|
+
assert the expectations on status, headers and payload. The library provides a special method `testEndpoint` that
|
|
908
|
+
makes mocking easier. Under the hood, request and response object are mocked using the
|
|
909
|
+
[node-mocks-http](https://www.npmjs.com/package/node-mocks-http) library, therefore you can utilize its API for
|
|
910
|
+
settings additional properties and asserting expectation using the provided getters, such as `._getStatusCode()`.
|
|
915
911
|
|
|
916
912
|
```typescript
|
|
917
913
|
import { testEndpoint } from "express-zod-api";
|
|
918
914
|
|
|
919
|
-
// place it once anywhere in your tests
|
|
920
|
-
declare module "express-zod-api" {
|
|
921
|
-
interface MockOverrides extends jest.Mock {} // or Mock from vitest
|
|
922
|
-
}
|
|
923
|
-
|
|
924
915
|
test("should respond successfully", async () => {
|
|
925
916
|
const { responseMock, loggerMock } = await testEndpoint({
|
|
926
917
|
endpoint: yourEndpoint,
|
|
@@ -928,39 +919,34 @@ test("should respond successfully", async () => {
|
|
|
928
919
|
method: "POST", // default: GET
|
|
929
920
|
body: {}, // incoming data as if after parsing (JSON)
|
|
930
921
|
},
|
|
931
|
-
//
|
|
932
|
-
// responseProps, configProps, loggerProps
|
|
933
|
-
});
|
|
934
|
-
expect(loggerMock.error).toHaveBeenCalledTimes(0);
|
|
935
|
-
expect(responseMock.status).toHaveBeenCalledWith(200);
|
|
936
|
-
expect(responseMock.json).toHaveBeenCalledWith({
|
|
937
|
-
status: "success",
|
|
938
|
-
data: {},
|
|
922
|
+
// responseOptions, configProps, loggerProps
|
|
939
923
|
});
|
|
924
|
+
expect(loggerMock._getLogs().error).toHaveLength(0);
|
|
925
|
+
expect(responseMock._getStatusCode()).toBe(200);
|
|
926
|
+
expect(responseMock._getHeaders()).toHaveProperty("x-custom", "one"); // lower case!
|
|
927
|
+
expect(responseMock._getData()).toBe(JSON.stringify({ status: "success" })); // or:
|
|
928
|
+
expect(JSON.parse(responseMock._getData())).toEqual({ status: "success" });
|
|
940
929
|
});
|
|
941
930
|
```
|
|
942
931
|
|
|
943
|
-
_This method is optimized for the `defaultResultHandler`. With the flexibility to customize, you can add additional
|
|
944
|
-
properties as needed._
|
|
945
|
-
|
|
946
932
|
# Special needs
|
|
947
933
|
|
|
948
934
|
## Different responses for different status codes
|
|
949
935
|
|
|
950
936
|
In some special cases you may want the ResultHandler to respond slightly differently depending on the status code,
|
|
951
937
|
for example if your API strictly follows REST standards. It may also be necessary to reflect this difference in the
|
|
952
|
-
generated Documentation.
|
|
953
|
-
|
|
938
|
+
generated Documentation. For that purpose, the constructor of `ResultHandler` accepts flexible declaration of possible
|
|
939
|
+
response schemas and their corresponding status codes.
|
|
954
940
|
|
|
955
941
|
```typescript
|
|
956
|
-
import {
|
|
942
|
+
import { ResultHandler } from "express-zod-api";
|
|
957
943
|
|
|
958
|
-
|
|
959
|
-
|
|
944
|
+
new ResultHandler({
|
|
945
|
+
positive: (data) => ({
|
|
960
946
|
statusCodes: [201, 202], // created or will be created
|
|
961
|
-
schema: z.object({ status: z.literal("created"), data
|
|
947
|
+
schema: z.object({ status: z.literal("created"), data }),
|
|
962
948
|
}),
|
|
963
|
-
|
|
949
|
+
negative: [
|
|
964
950
|
{
|
|
965
951
|
statusCode: 409, // conflict: entity already exists
|
|
966
952
|
schema: z.object({ status: z.literal("exists"), id: z.number().int() }),
|
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},
|
|
1
|
+
"use strict";var Zo=Object.create;var We=Object.defineProperty;var vo=Object.getOwnPropertyDescriptor;var No=Object.getOwnPropertyNames;var Lo=Object.getPrototypeOf,jo=Object.prototype.hasOwnProperty;var ko=(e,t)=>{for(var r in t)We(e,r,{get:t[r],enumerable:!0})},ir=(e,t,r,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of No(t))!jo.call(e,i)&&i!==r&&We(e,i,{get:()=>t[i],enumerable:!(o=vo(t,i))||o.enumerable});return e};var O=(e,t,r)=>(r=e!=null?Zo(Lo(e)):{},ir(t||!e||!e.__esModule?We(r,"default",{value:e,enumerable:!0}):r,e)),Mo=e=>ir(We({},"__esModule",{value:!0}),e);var xi={};ko(xi,{BuiltinLogger:()=>Se,DependsOnMethod:()=>Oe,Documentation:()=>yt,DocumentationError:()=>P,EndpointsFactory:()=>be,InputValidationError:()=>k,Integration:()=>Ot,Middleware:()=>B,MissingPeerError:()=>le,OutputValidationError:()=>_,ResultHandler:()=>he,RoutingError:()=>re,ServeStatic:()=>Ae,arrayEndpointsFactory:()=>Zr,arrayResultHandler:()=>dt,attachRouting:()=>qr,createConfig:()=>mr,createServer:()=>$r,defaultEndpointsFactory:()=>Er,defaultResultHandler:()=>xe,ez:()=>zo,getExamples:()=>F,getMessageFromError:()=>D,getStatusCodeFromError:()=>He,migration:()=>wo,testEndpoint:()=>fo});module.exports=Mo(xi);var lr=require("ramda"),De=require("zod");var sr=require("http-errors"),ar=require("crypto"),me=require("ramda"),pr=require("zod");var re=class extends Error{name="RoutingError"},P=class extends Error{name="DocumentationError";constructor({message:t,method:r,path:o,isResponse:i}){let s=`${t}
|
|
2
|
+
Caused by ${i?"response":"input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`;super(s)}},G=class extends Error{name="IOSchemaError"},_=class extends G{name="OutputValidationError";originalError;constructor(t){super(D(t)),this.originalError=t}},k=class extends G{name="InputValidationError";originalError;constructor(t){super(D(t)),this.originalError=t}},Y=class extends Error{name="ResultHandlerError";originalError;constructor(t,r){super(t),this.originalError=r||void 0}},le=class extends Error{name="MissingPeerError";constructor(t){let r=Array.isArray(t);super(`Missing ${r?"one of the following peer dependencies":"peer dependency"}: ${r?t.join(" | "):t}. Please install it to use the feature.`)}};var z={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream"};var Ho=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(z.upload);return"files"in e&&r},Pt={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Uo=["body","query","params"],It=e=>e.method.toLowerCase(),Ct=e=>e.startsWith("x-"),Do=e=>(0,me.pickBy)((0,me.flip)(Ct),e),cr=(e,t={})=>{let r=It(e);return r==="options"?{}:(t[r]||Pt[r]||Uo).filter(o=>o==="files"?Ho(e):!0).map(o=>o==="headers"?Do(e[o]):e[o]).reduce((o,i)=>({...o,...i}),{})},ue=e=>e instanceof Error?e:new Error(typeof e=="symbol"?e.toString():`${e}`),D=e=>e instanceof pr.z.ZodError?e.issues.map(({path:t,message:r})=>(t.length?[t.join("/")]:[]).concat(r).join(": ")).join("; "):e instanceof _?`output${e.originalError.issues[0]?.path.length>0?"/":": "}${e.message}`:e.message,He=e=>(0,sr.isHttpError)(e)?e.statusCode:e instanceof k?400:500,zt=({logger:e,request:t,input:r,error:o,statusCode:i})=>{i===500&&e.error(`Internal server error
|
|
3
3
|
${o.stack}
|
|
4
|
-
`,{url:t.url,payload:r})},F=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},oe=(e,t,r)=>e.length&&t.length?(0,
|
|
5
|
-
Original error: ${e.originalError.message}.`:""))};var br=require("ramda");var ie=e=>K(e)&&"or"in e,xe=e=>K(e)&&"and"in e,It=e=>({and:(0,br.chain)(t=>xe(t)?t.and:[t],e)}),tt=(e,t)=>xe(e)?{and:e.and.map(r=>ie(r)?{or:r.or.map(t)}:t(r))}:ie(e)?{or:e.or.map(r=>xe(r)?{and:r.and.map(t)}:t(r))}:t(e),wt=e=>e.and.reduce((t,r)=>({or:oe(t.or,ie(r)?r.or:[r],It)}),{or:[]}),he=(e,t)=>xe(e)?ie(t)?he(wt(e),t):It([e,t]):ie(e)?xe(t)?he(t,e):ie(t)?{or:oe(e.or,t.or,It)}:he(e,{and:[t]}):xe(t)||ie(t)?he(t,e):{and:[e,t]};var se=class{},ot=class extends se{#e;#o;#n;#s;#t;#a;#p;#r;#d;#c;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:c=[],tags:l=[],description:m,shortDescription:y}){super(),this.#a=i,this.#p=s,this.#n=c,this.#l=a,this.#o=Object.freeze(t),this.#d=Object.freeze(p),this.#c=Object.freeze(l),this.#e={long:m,short:y},this.#r={input:r,output:o};for(let[u,x]of Object.entries(this.#r))(0,Et.default)(!Xe(x),new V(`Using transformations on the top level of endpoint ${u} schema is not allowed.`));this.#t={positive:Object.freeze(Pt(s.getPositiveResponse(o),{mimeTypes:[N.json],statusCodes:[ge.positive]})),negative:Object.freeze(Pt(s.getNegativeResponse(),{mimeTypes:[N.json],statusCodes:[ge.negative]}))};for(let[u,x]of Object.entries(this.#t))(0,Et.default)(x.length,new te(`ResultHandler must have at least one ${u} response schema specified.`));this.#i=hr(r)?"upload":xr(r)?"raw":"json",this.#s={input:Object.freeze([N[this.#i]]),positive:Object.freeze(this.#t.positive.flatMap(({mimeTypes:u})=>u)),negative:Object.freeze(this.#t.negative.flatMap(({mimeTypes:u})=>u))}}getDescription(t){return this.#e[t]}getMethods(){return this.#o}getSchema(t){return t==="input"||t==="output"?this.#r[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#t[t]}getSecurity(){return this.#n.reduce((t,r)=>r.security?he(t,r.security):t,{and:[]})}getScopes(){return this.#d}getTags(){return this.#c}getOperationId(t){return this.#l(t)}#m(t){return{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":this.#o.concat(t).concat("options").join(", ").toUpperCase(),"Access-Control-Allow-Headers":"content-type"}}async#u(t){try{return await this.#r.output.parseAsync(t)}catch(r){throw r instanceof rt.z.ZodError?new G(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#n){if(t==="options"&&p.type==="proprietary")continue;let c;try{c=await p.input.parseAsync(r)}catch(l){throw l instanceof rt.z.ZodError?new H(l):l}if(Object.assign(a,await p.middleware({input:c,options:a,request:o,response:i,logger:s})),i.writableEnded){s.warn(`The middleware ${p.middleware.name} has closed the stream. Accumulated options:`,a);break}}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#r.input.parseAsync(t)}catch(s){throw s instanceof rt.z.ZodError?new H(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.handler({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(c){et({logger:i,response:o,error:new te(ye(c).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=St(t),p={},c=null,l=null;if(i.cors){let y=this.#m(s);typeof i.cors=="function"&&(y=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:y}));for(let u in y)r.set(u,y[u])}let m=nr(t,i.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}c=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(y){l=ye(y)}await this.#g({input:m,output:c,request:t,response:r,error:l,logger:o,options:p})}};var zt=require("zod");var Tr=(e,t)=>{let r=e.map(({input:i})=>i).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>ir(s,i),o)};var Sr=R(require("assert/strict"),1),nt=e=>((0,Sr.default)(!Xe(e.input),new V("Using transformations on the top level of middleware input schema is not allowed.")),{...e,type:"proprietary"});var v=require("zod");var it=e=>e,be=it({getPositiveResponse:e=>{let t=F({schema:e}),r=v.z.object({status:v.z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},getNegativeResponse:()=>v.z.object({status:v.z.literal("error"),error:v.z.object({message:v.z.string()})}).example({status:"error",error:{message:U(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(ge.positive).json({status:"success",data:r});return}let a=Le(e);Ot({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:U(e)}})}}),st=it({getPositiveResponse:e=>{let t=F({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof v.z.ZodArray?e.shape.items:v.z.array(v.z.any());return t.reduce((o,i)=>K(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},getNegativeResponse:()=>v.z.string().example(U(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=Le(r);Ot({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(ge.positive).json(t.items):e.status(500).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),this.resultHandler)}use=this.addExpressMiddleware;addExpressMiddleware(t,r){let o=r?.transformer||(a=>a),i=r?.provider||(()=>({})),s={type:"express",input:zt.z.object({}),middleware:async({request:a,response:p})=>new Promise((c,l)=>{t(a,p,y=>{if(y&&y instanceof Error)return l(o(y));c(i(a,p))})})};return e.#e(this.middlewares.concat(s),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(nt({input:zt.z.object({}),middleware:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:c,resultHandler:l}=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 ot({handler:r,middlewares:c,outputSchema:o,resultHandler:l,scopes:u,tags:x,methods:m,getOperationId:y,description:i,shortDescription:s,inputSchema:Tr(c,t)})}},Rr=new Te(be),Or=new Te(st);var j=require("ansis"),Pr=require("util");var at={debug:10,info:20,warn:30,error:40},Ar=e=>K(e)&&Object.keys(at).some(t=>t in e);var ae=class e{constructor(t){this.config=t}styles={debug:j.blue,info:j.green,warn:(0,j.hex)("#FFA500"),error:j.red};prettyPrint(t){return(0,Pr.inspect)(t,{colors:this.config.color,depth:this.config.depth,breakLength:this.config.level==="debug"?80:1/0,compact:this.config.level==="debug"?3:!0})}print(t,r,o){if(this.config.level==="silent"||at[t]<at[this.config.level])return;let{requestId:i,...s}=this.config.ctx||{},a=[new Date().toISOString()];i&&a.push(this.config.color?(0,j.cyanBright)(i):i),a.push(this.config.color?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&a.push(this.prettyPrint(o)),Object.keys(s).length>0&&a.push(this.prettyPrint(s)),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})}},Cr=e=>new ae(e);var Re=require("ramda"),Se=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze((0,Re.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=(0,Re.head)(this.pairs)?.[1],this.siblingMethods=Object.freeze((0,Re.tail)(this.pairs).map(([r])=>r))}};var Ir=R(require("express"),1),Oe=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Ir.default.static(...this.params))}};var pt=R(require("express"),1),Lr=R(require("http"),1),jr=R(require("https"),1);var pe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>R(require(e))))[t]}catch{}throw new re(e)},wr=async e=>{for(let{moduleName:t,moduleExport:r}of e)try{return await pe(t,r)}catch{}throw new re(e.map(({moduleName:t})=>t))};var Zt=R(require("assert/strict"),1);var de=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){Zt.default.doesNotMatch(a,/\//,new ee(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let c=`${o||""}${a?`/${a}`:""}`;if(p instanceof se){let l=p.getMethods().slice();i&&l.push("options");for(let m of l)t(p,c,m)}else if(p instanceof Oe)r&&p.apply(c,r);else if(p instanceof Se){for(let[l,m]of p.pairs)(0,Zt.default)(m.getMethods().includes(l),new ee(`Endpoint assigned to ${l} method of ${c} must support ${l} method.`)),t(m,c,l);i&&p.firstEndpoint&&t(p.firstEndpoint,c,"options",p.siblingMethods)}else de({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:c})}};var Nt=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>de({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,c)=>{e[p](a,...i?.[s.getRequestType()]||[],async(l,m)=>s.execute({request:l,response:m,logger:m.locals[g]?.logger||t,config:r,siblingMethods:c}))},onStatic:(s,a)=>{e.use(s,a)}});var Ue=R(require("http-errors"),1);var Er=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.handler({error:(0,Ue.isHttpError)(r)?r:(0,Ue.default)(400,ye(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[g]?.logger||t})},zr=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=(0,Ue.default)(404,`Can not ${r.method} ${r.path}`),s=o.locals[g]?.logger||t;try{e.handler({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){et({response:o,logger:s,error:new te(ye(a).message,i)})}},Ho=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},Uo=e=>({log:e.debug.bind(e)}),Zr=async({rootLogger:e,config:t})=>{let r=await pe("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,c,l)=>{let m=c.locals[g]?.logger||e;try{await i?.({request:p,logger:m})}catch(y){return l(y)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Uo(m)})(p,c,l)}),o&&a.push(Ho(o)),a},Nr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Mr=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[g]={logger:s},i()};var w=require("ansis"),vr=()=>{let e=(0,w.italic)("Proudly supports transgender community.".padStart(109)),t=(0,w.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,w.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,w.italic)("for Dime".padEnd(20)),i=(0,w.hex)("#F5A9B8"),s=(0,w.hex)("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(w.whiteBright,5,7).fill(i,7,9).fill(s,9,12).fill(w.gray,12,13);return`
|
|
4
|
+
`,{url:t.url,payload:r})},F=({schema:e,variant:t="original",validate:r=t==="parsed"})=>{let o=e._def[g]?.examples||[];if(!r&&t==="original")return o;let i=[];for(let s of o){let a=e.safeParse(s);a.success&&i.push(t==="parsed"?a.data:s)}return i},oe=(e,t,r)=>e.length&&t.length?(0,me.xprod)(e,t).map(r):e.concat(t),Ue=e=>"coerce"in e._def&&typeof e._def.coerce=="boolean"?e._def.coerce:!1,wt=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(wt).join(""),Xe=e=>(0,ar.createHash)("sha1").update(JSON.stringify(e),"utf8").digest("hex"),et=(e,t)=>{try{return typeof e.parse(t)}catch{return}},K=e=>typeof e=="object"&&e!==null;var tt=require("ramda"),g=Symbol.for("express-zod-api"),rt=e=>{let t=e.describe(e.description);return t._def[g]=(0,tt.clone)(t._def[g])||{examples:[]},t},dr=(e,t)=>{if(!(g in e._def))return t;let r=rt(t);return r._def[g].examples=oe(r._def[g].examples,e._def[g].examples,([o,i])=>typeof o=="object"&&typeof i=="object"?(0,tt.mergeDeepRight)({...o},{...i}):i),r};var Fo=function(e){let t=rt(this);return t._def[g].examples.push(e),t},Ko=function(e){let t=rt(this);return t._def[g].defaultLabel=e,t},Bo=function(e){return new De.z.ZodBranded({typeName:De.z.ZodFirstPartyTypeKind.ZodBranded,type:this,description:this._def.description,errorMap:this._def.errorMap,[g]:{examples:[],...(0,lr.clone)(this._def[g]),brand:e}})};g in globalThis||(globalThis[g]=!0,Object.defineProperties(De.z.ZodType.prototype,{example:{get(){return Fo.bind(this)}},brand:{set(){},get(){return Bo.bind(this)}}}),Object.defineProperty(De.z.ZodDefault.prototype,"label",{get(){return Ko.bind(this)}}));function mr(e){return e}var wr=require("zod");var Pr=O(require("assert/strict"),1),jt=require("zod");var br=require("zod");var fr=require("zod");var Fe=require("zod"),Q=Symbol("File"),ur=Fe.z.custom(e=>Buffer.isBuffer(e),{message:"Expected Buffer"}),qo={buffer:()=>ur.brand(Q),string:()=>Fe.z.string().brand(Q),binary:()=>ur.or(Fe.z.string()).brand(Q),base64:()=>Fe.z.string().base64().brand(Q)};function ot(e){return qo[e||"string"]()}var ne=Symbol("Raw"),yr=(e={})=>fr.z.object({raw:ot("buffer")}).extend(e).brand(ne);var gr=require("zod"),Ke=Symbol("Upload"),hr=()=>gr.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(Ke);var Et=(e,{next:t})=>e.options.some(t),Tr=({_def:e},{next:t})=>[e.left,e.right].some(t),xr=(e,{next:t})=>t(e.unwrap()),$o={ZodObject:({shape:e},{next:t})=>Object.values(e).some(t),ZodUnion:Et,ZodDiscriminatedUnion:Et,ZodIntersection:Tr,ZodEffects:(e,{next:t})=>t(e.innerType()),ZodOptional:xr,ZodNullable:xr,ZodRecord:({valueSchema:e},{next:t})=>t(e),ZodArray:({element:e},{next:t})=>t(e),ZodDefault:({_def:e},{next:t})=>t(e.innerType)},nt=(e,{condition:t,rules:r=$o,depth:o=1,maxDepth:i=Number.POSITIVE_INFINITY})=>{if(t(e))return!0;let s=o<i?r[e._def.typeName]:void 0;return s?s(e,{next:a=>nt(a,{condition:t,rules:r,maxDepth:i,depth:o+1})}):!1},it=e=>nt(e,{maxDepth:3,rules:{ZodUnion:Et,ZodIntersection:Tr},condition:t=>t instanceof br.z.ZodEffects&&t._def.effect.type!=="refinement"}),Sr=e=>nt(e,{condition:t=>t._def[g]?.brand===Ke}),Or=e=>nt(e,{condition:t=>t._def[g]?.brand===ne,maxDepth:3});var st=({error:e,logger:t,response:r})=>{t.error(`Result handler failure: ${e.message}.`),r.status(500).end(`An error occurred while serving the result: ${e.message}.`+(e.originalError?`
|
|
5
|
+
Original error: ${e.originalError.message}.`:""))};var Rr=require("ramda");var ie=e=>K(e)&&"or"in e,ye=e=>K(e)&&"and"in e,Zt=e=>({and:(0,Rr.chain)(t=>ye(t)?t.and:[t],e)}),at=(e,t)=>ye(e)?{and:e.and.map(r=>ie(r)?{or:r.or.map(t)}:t(r))}:ie(e)?{or:e.or.map(r=>ye(r)?{and:r.and.map(t)}:t(r))}:t(e),vt=e=>e.and.reduce((t,r)=>({or:oe(t.or,ie(r)?r.or:[r],Zt)}),{or:[]}),fe=(e,t)=>ye(e)?ie(t)?fe(vt(e),t):Zt([e,t]):ie(e)?ye(t)?fe(t,e):ie(t)?{or:oe(e.or,t.or,Zt)}:fe(e,{and:[t]}):ye(t)||ie(t)?fe(t,e):{and:[e,t]};var Lt=require("zod");var Ar=O(require("assert/strict"),1),Nt=class{},B=class extends Nt{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),(0,Ar.default)(!it(t),new G("Using transformations on the top level of middleware input schema is not allowed.")),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 Lt.z.ZodError?new k(o):o}}},ge=class extends B{constructor(t,{provider:r=()=>({}),transformer:o=i=>i}={}){super({input:Lt.z.object({}),handler:async({request:i,response:s})=>new Promise((a,p)=>{t(i,s,l=>{if(l&&l instanceof Error)return p(o(l));a(r(i,s))})})})}};var Be=class{},pt=class extends Be{#e;#t;#r;#s;#n;#a;#p;#o;#c;#d;#l;#i;constructor({methods:t,inputSchema:r,outputSchema:o,handler:i,resultHandler:s,getOperationId:a=()=>{},scopes:p=[],middlewares:d=[],tags:l=[],description:m,shortDescription:y}){super(),this.#a=i,this.#p=s,this.#r=d,this.#l=a,this.#t=Object.freeze(t),this.#c=Object.freeze(p),this.#d=Object.freeze(l),this.#e={long:m,short:y},this.#o={input:r,output:o};for(let[f,b]of Object.entries(this.#o))(0,Pr.default)(!it(b),new G(`Using transformations on the top level of endpoint ${f} schema is not allowed.`));this.#n={positive:Object.freeze(s.getPositiveResponse(o)),negative:Object.freeze(s.getNegativeResponse())},this.#i=Sr(r)?"upload":Or(r)?"raw":"json",this.#s={input:Object.freeze([z[this.#i]]),positive:Object.freeze(this.#n.positive.flatMap(({mimeTypes:f})=>f)),negative:Object.freeze(this.#n.negative.flatMap(({mimeTypes:f})=>f))}}getDescription(t){return this.#e[t]}getMethods(){return this.#t}getSchema(t){return t==="input"||t==="output"?this.#o[t]:this.getResponses(t).map(({schema:r})=>r).reduce((r,o)=>r.or(o))}getMimeTypes(t){return this.#s[t]}getRequestType(){return this.#i}getResponses(t){return this.#n[t]}getSecurity(){return this.#r.reduce((t,r)=>{let o=r.getSecurity();return o?fe(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.#o.output.parseAsync(t)}catch(r){throw r instanceof jt.z.ZodError?new _(r):r}}async#f({method:t,input:r,request:o,response:i,logger:s,options:a}){for(let p of this.#r)if(!(t==="options"&&!(p instanceof ge))&&(Object.assign(a,await p.execute({input:r,options:a,request:o,response:i,logger:s})),i.writableEnded)){s.warn("A middleware has closed the stream. Accumulated options:",a);break}}async#y({input:t,options:r,logger:o}){let i;try{i=await this.#o.input.parseAsync(t)}catch(s){throw s instanceof jt.z.ZodError?new k(s):s}return this.#a({input:i,options:r,logger:o})}async#g({error:t,request:r,response:o,logger:i,input:s,output:a,options:p}){try{await this.#p.execute({error:t,output:a,request:r,response:o,logger:i,input:s,options:p})}catch(d){st({logger:i,response:o,error:new Y(ue(d).message,t)})}}async execute({request:t,response:r,logger:o,config:i,siblingMethods:s=[]}){let a=It(t),p={},d=null,l=null;if(i.cors){let y=this.#m(s);typeof i.cors=="function"&&(y=await i.cors({request:t,logger:o,endpoint:this,defaultHeaders:y}));for(let f in y)r.set(f,y[f])}let m=cr(t,i.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}d=await this.#u(await this.#y({input:m,logger:o,options:p}))}catch(y){l=ue(y)}await this.#g({input:m,output:d,request:t,response:r,error:l,logger:o,options:p})}};var Ir=(e,t)=>{let r=e.map(i=>i.getSchema()).concat(t),o=r.reduce((i,s)=>i.and(s));return r.reduce((i,s)=>dr(s,i),o)};var L=require("zod");var qe={positive:200,negative:400};var Cr=O(require("assert/strict"),1),zr=require("zod");var ct=(e,t)=>typeof e=="function"?ct(e(...t.arguments),t):e instanceof zr.z.ZodType?[{...t,schema:e}]:(Array.isArray(e)&&(0,Cr.default)(e.length,new Y(`At least one ${t.variant} response schema required.`)),(Array.isArray(e)?e:[e]).map(({schema:r,statusCodes:o,statusCode:i,mimeTypes:s,mimeType:a})=>({schema:r,statusCodes:i?[i]:o||t.statusCodes,mimeTypes:a?[a]:s||t.mimeTypes})));var kt=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},he=class extends kt{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return ct(this.#e,{variant:"positive",arguments:[t],statusCodes:[qe.positive],mimeTypes:[z.json]})}getNegativeResponse(){return ct(this.#t,{variant:"negative",arguments:[],statusCodes:[qe.negative],mimeTypes:[z.json]})}},xe=new he({positive:e=>{let t=F({schema:e}),r=L.z.object({status:L.z.literal("success"),data:e});return t.reduce((o,i)=>o.example({status:"success",data:i}),r)},negative:L.z.object({status:L.z.literal("error"),error:L.z.object({message:L.z.string()})}).example({status:"error",error:{message:D(new Error("Sample error message"))}}),handler:({error:e,input:t,output:r,request:o,response:i,logger:s})=>{if(!e){i.status(qe.positive).json({status:"success",data:r});return}let a=He(e);zt({logger:s,statusCode:a,request:o,error:e,input:t}),i.status(a).json({status:"error",error:{message:D(e)}})}}),dt=new he({positive:e=>{let t=F({schema:e}),r="shape"in e&&"items"in e.shape&&e.shape.items instanceof L.z.ZodArray?e.shape.items:L.z.array(L.z.any());return t.reduce((o,i)=>K(i)&&"items"in i&&Array.isArray(i.items)?o.example(i.items):o,r)},negative:L.z.string().example(D(new Error("Sample error message"))),handler:({response:e,output:t,error:r,logger:o,request:i,input:s})=>{if(r){let a=He(r);zt({logger:o,statusCode:a,request:i,error:r,input:s}),e.status(a).send(r.message);return}t&&"items"in t&&Array.isArray(t.items)?e.status(qe.positive).json(t.items):e.status(500).send("Property 'items' is missing in the endpoint output")}});var be=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 ge(...t)),this.resultHandler)}addOptions(t){return e.#e(this.middlewares.concat(new B({input:wr.z.object({}),handler:t})),this.resultHandler)}build({input:t,handler:r,output:o,description:i,shortDescription:s,operationId:a,...p}){let{middlewares:d,resultHandler:l}=this,m="methods"in p?p.methods:[p.method],y=typeof a=="function"?a:()=>a,f="scopes"in p?p.scopes:"scope"in p&&p.scope?[p.scope]:[],b="tags"in p?p.tags:"tag"in p&&p.tag?[p.tag]:[];return new pt({handler:r,middlewares:d,outputSchema:o,resultHandler:l,scopes:f,tags:b,methods:m,getOperationId:y,description:i,shortDescription:s,inputSchema:Ir(d,t)})}},Er=new be(xe),Zr=new be(dt);var M=require("ansis"),Nr=require("util");var Te={debug:10,info:20,warn:30,error:40},vr=e=>K(e)&&Object.keys(Te).some(t=>t in e);var Se=class e{constructor(t){this.config=t}styles={debug:M.blue,info:M.green,warn:(0,M.hex)("#FFA500"),error:M.red};prettyPrint(t){return(0,Nr.inspect)(t,{colors:this.config.color,depth:this.config.depth,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:i,...s}=this.config.ctx||{},a=[new Date().toISOString()];i&&a.push(this.config.color?(0,M.cyanBright)(i):i),a.push(this.config.color?`${this.styles[t](t)}:`:`${t}:`,r),o!==void 0&&a.push(this.prettyPrint(o)),Object.keys(s).length>0&&a.push(this.prettyPrint(s)),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})}};var Re=require("ramda"),Oe=class{pairs;firstEndpoint;siblingMethods;constructor(t){this.pairs=Object.freeze((0,Re.toPairs)(t).filter(r=>r!==void 0&&r[1]!==void 0)),this.firstEndpoint=(0,Re.head)(this.pairs)?.[1],this.siblingMethods=Object.freeze((0,Re.tail)(this.pairs).map(([r])=>r))}};var Lr=O(require("express"),1),Ae=class{params;constructor(...t){this.params=t}apply(t,r){return r(t,Lr.default.static(...this.params))}};var lt=O(require("express"),1),Fr=O(require("http"),1),Kr=O(require("https"),1);var Pe=async(e,t="default")=>{try{return(await Promise.resolve().then(()=>O(require(e))))[t]}catch{}throw new le(e)};var Mt=O(require("assert/strict"),1);var se=({routing:e,onEndpoint:t,onStatic:r,parentPath:o,hasCors:i})=>{let s=Object.entries(e).map(([a,p])=>[a.trim(),p]);for(let[a,p]of s){Mt.default.doesNotMatch(a,/\//,new re(`The entry '${a}' must avoid having slashes \u2014 use nesting instead.`));let d=`${o||""}${a?`/${a}`:""}`;if(p instanceof Be){let l=p.getMethods().slice();i&&l.push("options");for(let m of l)t(p,d,m)}else if(p instanceof Ae)r&&p.apply(d,r);else if(p instanceof Oe){for(let[l,m]of p.pairs)(0,Mt.default)(m.getMethods().includes(l),new re(`Endpoint assigned to ${l} method of ${d} must support ${l} method.`)),t(m,d,l);i&&p.firstEndpoint&&t(p.firstEndpoint,d,"options",p.siblingMethods)}else se({onEndpoint:t,onStatic:r,hasCors:i,routing:p,parentPath:d})}};var Ht=({app:e,rootLogger:t,config:r,routing:o,parsers:i})=>se({routing:o,hasCors:!!r.cors,onEndpoint:(s,a,p,d)=>{e[p](a,...i?.[s.getRequestType()]||[],async(l,m)=>s.execute({request:l,response:m,logger:m.locals[g]?.logger||t,config:r,siblingMethods:d}))},onStatic:(s,a)=>{e.use(s,a)}});var $e=O(require("http-errors"),1);var jr=({errorHandler:e,rootLogger:t})=>async(r,o,i,s)=>{if(!r)return s();e.execute({error:(0,$e.isHttpError)(r)?r:(0,$e.default)(400,ue(r).message),request:o,response:i,input:null,output:null,options:{},logger:i.locals[g]?.logger||t})},kr=({errorHandler:e,rootLogger:t})=>async(r,o)=>{let i=(0,$e.default)(404,`Can not ${r.method} ${r.path}`),s=o.locals[g]?.logger||t;try{e.execute({request:r,response:o,logger:s,error:i,input:null,output:null,options:{}})}catch(a){st({response:o,logger:s,error:new Y(ue(a).message,i)})}},Vo=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:i})=>i))return r(e);r()},Go=e=>({log:e.debug.bind(e)}),Mr=async({rootLogger:e,config:t})=>{let r=await Pe("express-fileupload"),{limitError:o,beforeUpload:i,...s}={...typeof t.server.upload=="object"&&t.server.upload},a=[];return a.push(async(p,d,l)=>{let m=d.locals[g]?.logger||e;try{await i?.({request:p,logger:m})}catch(y){return l(y)}r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:Go(m)})(p,d,l)}),o&&a.push(Vo(o)),a},Hr=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},Ur=({rootLogger:e,config:t})=>async(r,o,i)=>{let s=t.childLoggerProvider?await t.childLoggerProvider({request:r,parent:e}):e;s.debug(`${r.method}: ${r.path}`),o.locals[g]={logger:s},i()};var w=require("ansis"),Dr=()=>{let e=(0,w.italic)("Proudly supports transgender community.".padStart(109)),t=(0,w.italic)("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),r=(0,w.italic)("Thank you for choosing Express Zod API for your project.".padStart(132)),o=(0,w.italic)("for Zoey".padEnd(20)),i=(0,w.hex)("#F5A9B8"),s=(0,w.hex)("#5BCEFA"),a=new Array(14).fill(s,1,3).fill(i,3,5).fill(w.whiteBright,5,7).fill(i,7,9).fill(s,9,12).fill(w.gray,12,13);return`
|
|
6
6
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
7
7
|
888 d88P 888 d88888 888 Y88b 888
|
|
8
8
|
888 d88P 888 d88P888 888 888 888
|
|
@@ -16,9 +16,9 @@ Original error: ${e.originalError.message}.`:""))};var br=require("ramda");var i
|
|
|
16
16
|
${o}888${t}
|
|
17
17
|
${r}
|
|
18
18
|
`.split(`
|
|
19
|
-
`).map((
|
|
20
|
-
`)};var Dr=e=>{e.startupLogo!==!1&&console.log(vr());let t=e.errorHandler||be,r=Ar(e.logger)?e.logger:new ae(e.logger);r.debug("Running","v19.2.0 (CJS)");let o=Mr({rootLogger:r,config:e}),i=zr({rootLogger:r,errorHandler:t}),s=Er({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},kr=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=Dr(e);return Nt({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},Hr=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=Dr(e),a=(0,pt.default)().disable("x-powered-by").use(s);if(e.server.compression){let m=await pe("compression");a.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||pt.default.json()],raw:[e.server.rawParser||pt.default.raw(),Nr],upload:e.server.upload?await Zr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),Nt({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let c=(m,y)=>m.listen(y,()=>{r.info("Listening",y)}),l={httpServer:c(Lr.default.createServer(a),e.server.listen),httpsServer:e.https?c(jr.default.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...l,logger:r}};var no=R(require("assert/strict"),1),io=require("openapi3-ts/oas31"),so=require("ramda");var B=R(require("assert/strict"),1),Y=require("openapi3-ts/oas31"),d=require("ramda"),S=require("zod");var Ae=require("zod");var dt=e=>!isNaN(e.getTime());var Fe=Symbol("DateIn"),Ur=()=>Ae.z.union([Ae.z.string().date(),Ae.z.string().datetime(),Ae.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ae.z.date().refine(dt)).brand(Fe);var Fr=require("zod");var Ke=Symbol("DateOut"),Kr=()=>Fr.z.date().refine(dt).transform(e=>e.toISOString()).brand(Ke);var ce=(e,{onEach:t,rules:r,onMissing:o,ctx:i={}})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],p=s?s(e,{...i,next:l=>ce(l,{ctx:i,onEach:t,rules:r,onMissing:o})}):o(e,i),c=t&&t(e,{prev:p,...i});return c?{...p,...c}:p};var Br=50,$r="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Fo={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Vr=/:([A-Za-z0-9_]+)/g,Ko=e=>e.match(Vr)?.map(t=>t.slice(1))||[],Gr=e=>e.replace(Vr,t=>`{${t.slice(1)}}`),Bo=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),qo=({_def:{innerType:e}},{next:t})=>t(e),$o=()=>({format:"any"}),Vo=({},e)=>((0,B.default)(!e.isResponse,new P({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Go=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"}},_o=({options:e},{next:t})=>({oneOf:e.map(t)}),Yo=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Qo=e=>{let[t,r]=e.filter(i=>!(0,Y.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,B.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,d.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,d.concat)(i,s):i===s?s:B.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=oe(t.examples||[],r.examples||[],([i,s])=>(0,d.mergeDeepRight)(i,s))),o},Jo=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Qo(o)}catch{}return{allOf:o}},Wo=(e,{next:t})=>t(e.unwrap()),Xo=(e,{next:t})=>t(e.unwrap()),en=(e,{next:t})=>{let r=t(e.unwrap());return(0,Y.isReferenceObject)(r)||(r.type=Yr(r)),r},_r=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},qr=e=>({type:_r(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),tn=({value:e})=>({type:_r(e),const:e}),rn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),i=p=>t&&je(p)?p instanceof S.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=ct(e,r)),s.length&&(a.required=s),a},on=()=>({type:"null"}),nn=({},e)=>((0,B.default)(!e.isResponse,new P({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:$r}}),sn=({},e)=>((0,B.default)(e.isResponse,new P({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:$r}}),an=({},e)=>B.default.fail(new P({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})),pn=()=>({type:"boolean"}),dn=()=>({type:"integer",format:"bigint"}),cn=e=>e.every(t=>t instanceof S.z.ZodLiteral),ln=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.z.ZodEnum||e instanceof S.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=ct(S.z.object((0,d.fromPairs)((0,d.xprod)(o,[t]))),r),i.required=o),i}if(e instanceof S.z.ZodLiteral)return{type:"object",properties:ct(S.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.z.ZodUnion&&cn(e.options)){let o=(0,d.map)(s=>`${s.value}`,e.options),i=(0,d.fromPairs)((0,d.xprod)(o,[t]));return{type:"object",properties:ct(S.z.object(i),r),required:o}}return{type:"object",additionalProperties:r(t)}},mn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let i={type:"array",items:o(r)};return e&&(i.minItems=e.value),t&&(i.maxItems=t.value),i},un=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),fn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:c,isEmoji:l,isDatetime:m,_def:{checks:y}})=>{let u=y.find(C=>C.kind==="regex"),x=y.find(C=>C.kind==="datetime"),z=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"},L={"date-time":m,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:c,emoji:l};for(let C in L)if(L[C]){T.format=C;break}return r!==null&&(T.minLength=r),o!==null&&(T.maxLength=o),z&&(T.pattern=z.source),T},yn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let i=o.find(({kind:y})=>y==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=i?i.inclusive:!0,p=o.find(({kind:y})=>y==="max"),c=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,l=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,l?m.maximum=c:m.exclusiveMaximum=c,m},ct=({shape:e},t)=>(0,d.map)(t,e),gn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Fo?.[t]},Yr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},hn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,Y.isReferenceObject)(o)){let s=_e(e,gn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(S.z.any())}if(!t&&i.type==="preprocess"&&!(0,Y.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},xn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),bn=(e,{next:t})=>t(e.unwrap()),Tn=({schema:e},{next:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(e);return o(s)||(i(s,{}),i(s,t(e)))},Sn=(e,{next:t})=>t(e.unwrap().shape.raw),Qr=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,Jr=(e,t,r=[])=>(0,d.pipe)(F,(0,d.map)((0,d.when)((0,d.both)(K,(0,d.complement)(Array.isArray)),(0,d.omit)(r))),Qr)({schema:e,variant:t?"parsed":"original",validate:!0}),Rn=(e,t)=>(0,d.pipe)(F,(0,d.filter)((0,d.has)(t)),(0,d.pluck)(t),Qr)({schema:e,variant:"original",validate:!0}),Pe=(e,t)=>e instanceof S.z.ZodObject?e:e instanceof S.z.ZodBranded?Pe(e.unwrap(),t):e instanceof S.z.ZodUnion||e instanceof S.z.ZodDiscriminatedUnion?e.options.map(r=>Pe(r,t)).reduce((r,o)=>r.merge(o.partial()),S.z.object({})):e instanceof S.z.ZodEffects?((0,B.default)(e._def.effect.type==="refinement",t),Pe(e._def.schema,t)):Pe(e._def.left,t).merge(Pe(e._def.right,t)),Wr=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:c,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=Pe(r,new P({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),y=Ko(e),u=o.includes("query"),x=o.includes("params"),z=o.includes("headers"),T=b=>x&&y.includes(b),L=b=>z&&Rt(b);return Object.keys(m).map(b=>({name:b,location:T(b)?"path":L(b)?"header":u?"query":void 0})).filter(b=>b.location!==void 0).map(({name:b,location:Ee})=>{let $=ce(m[b],{rules:{...c,...vt},onEach:Lt,onMissing:jt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:e,method:t}}),W=p==="components"?a(M(l,b),$):$;return{name:b,in:Ee,required:!m[b].isOptional(),description:$.description||l,schema:W,examples:Rn(r,b)}})},vt={ZodString:fn,ZodNumber:yn,ZodBigInt:dn,ZodBoolean:pn,ZodNull:on,ZodArray:mn,ZodTuple:un,ZodRecord:ln,ZodObject:rn,ZodLiteral:tn,ZodIntersection:Jo,ZodUnion:_o,ZodAny:$o,ZodDefault:Bo,ZodEnum:qr,ZodNativeEnum:qr,ZodEffects:hn,ZodOptional:Wo,ZodNullable:en,ZodDiscriminatedUnion:Yo,ZodBranded:bn,ZodDate:an,ZodCatch:qo,ZodPipeline:xn,ZodLazy:Tn,ZodReadonly:Xo,[_]:Go,[He]:Vo,[Ke]:sn,[Fe]:nn,[ne]:Sn},Lt=(e,{isResponse:t,prev:r})=>{if((0,Y.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof S.z.ZodLazy,s=r.type!==void 0,a=t&&je(e),p=!i&&s&&!a&&e.isNullable(),c=i?[]:F({schema:e,variant:t?"parsed":"original",validate:!0}),l={};return o&&(l.description=o),p&&(l.type=Yr(r)),c.length&&(l.examples=c.slice()),l},jt=(e,t)=>B.default.fail(new P({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Mt=(e,t)=>{if((0,Y.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=>Mt(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Mt(o,t))),r},Xr=e=>(0,Y.isReferenceObject)(e)?e:(0,d.omit)(["examples"],e),eo=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:c,hasMultipleStatusCodes:l,statusCode:m,brandHandling:y,description:u=`${e.toUpperCase()} ${t} ${At(i)} response ${l?m:""}`.trim()})=>{let x=Xr(ce(r,{rules:{...y,...vt},onEach:Lt,onMissing:jt,ctx:{isResponse:!0,serializer:s,getRef:a,makeRef:p,path:t,method:e}})),z={schema:c==="components"?p(M(u),x):x,examples:Jr(r,!0)};return{description:u,content:(0,d.fromPairs)((0,d.xprod)(o,[z]))}},On=()=>({type:"http",scheme:"basic"}),An=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Pn=({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},Cn=({name:e})=>({type:"apiKey",in:"header",name:e}),In=({name:e})=>({type:"apiKey",in:"cookie",name:e}),wn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),En=({flows:e={}})=>({type:"oauth2",flows:(0,d.map)(t=>({...t,scopes:t.scopes||{}}),(0,d.reject)(d.isNil,e))}),to=(e,t)=>{let r={basic:On,bearer:An,input:Pn,header:Cn,cookie:In,openid:wn,oauth2:En};return tt(e,o=>r[o.type](o,t))},lt=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?lt(wt(e)):lt({or:[e]}),ro=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:c,paramNames:l,description:m=`${e.toUpperCase()} ${t} Request body`})=>{let y=Xr(Mt(ce(r,{rules:{...c,...vt},onEach:Lt,onMissing:jt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:t,method:e}}),l)),u={schema:p==="components"?a(M(m),y):y,examples:Jr(r,!1,l)};return{description:m,content:(0,d.fromPairs)((0,d.xprod)(o,[u]))}},oo=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}),Dt=e=>e.length<=Br?e:e.slice(0,Br-1)+"\u2026";var mt=class extends io.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 i=o||M(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&no.default.fail(new P({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;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:i,serverUrl:s,descriptions:a,brandHandling:p,hasSummaryFromDescription:c=!0,composition:l="inline",serializer:m=Ge}){super(),this.addInfo({title:o,version:i});for(let u of typeof s=="string"?[s]:s)this.addServer({url:u});de({routing:t,onEndpoint:(u,x,z)=>{let T=z,L={path:x,method:T,endpoint:u,composition:l,serializer:m,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[C,b]=["short","long"].map(u.getDescription.bind(u)),Ee=C?Dt(C):c&&b?Dt(b):void 0,$=u.getTags(),W=r.inputSources?.[T]||Tt[T],me=this.ensureUniqOperationId(x,T,u.getOperationId(T)),ze=Wr({...L,inputSources:W,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:x,operationId:me})}),qe={};for(let k of["positive","negative"]){let X=u.getResponses(k);for(let{mimeTypes:Ze,schema:O,statusCodes:A}of X)for(let I of A)qe[I]=eo({...L,variant:k,schema:O,mimeTypes:Ze,statusCode:I,hasMultipleStatusCodes:X.length>1||A.length>1,description:a?.[`${k}Response`]?.call(null,{method:T,path:x,operationId:me,statusCode:I})})}let bt=W.includes("body")?ro({...L,paramNames:(0,so.pluck)("name",ze),schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:x,operationId:me})}):void 0,$e=lt(tt(to(u.getSecurity(),W),k=>{let X=this.ensureUniqSecuritySchemaName(k),Ze=["oauth2","openIdConnect"].includes(k.type)?u.getScopes().slice():[];return this.addSecurityScheme(X,k),{name:X,scopes:Ze}}));this.addPath(Gr(x),{[T]:{operationId:me,summary:Ee,description:b,tags:$.length>0?$:void 0,parameters:ze.length>0?ze:void 0,requestBody:bt,security:$e.length>0?$e:void 0,responses:qe}})}}),this.rootDoc.tags=r.tags?oo(r.tags):[]}};var kt=R(require("http"),1);var zn=({fnMethod:e,requestProps:t})=>({method:"GET",header:e(()=>N.json),...t}),Zn=({fnMethod:e,responseProps:t})=>{let r={writableEnded:!1,statusCode:200,statusMessage:kt.default.STATUS_CODES[200],set:e(()=>r),setHeader:e(()=>r),header:e(()=>r),status:e(o=>(r.statusCode=o,r.statusMessage=kt.default.STATUS_CODES[o],r)),json:e(()=>r),send:e(()=>r),end:e(()=>(r.writableEnded=!0,r)),locals:{},...t};return r},Nn=({fnMethod:e,loggerProps:t})=>({info:e(),warn:e(),error:e(),debug:e(),...t}),ao=async({endpoint:e,requestProps:t,responseProps:r,configProps:o,loggerProps:i,fnMethod:s})=>{let a=s||(await wr([{moduleName:"vitest",moduleExport:"vi"},{moduleName:"@jest/globals",moduleExport:"jest"}])).fn,p=zn({fnMethod:a,requestProps:t}),c=Zn({fnMethod:a,responseProps:r}),l=Nn({fnMethod:a,loggerProps:i}),m={cors:!1,logger:l,...o};return await e.execute({request:p,response:c,config:m,logger:l}),{requestMock:p,responseMock:c,loggerMock:l}};var E=R(require("typescript"),1);var D=R(require("typescript"),1),Ce=require("ramda"),n=D.default.factory,Q=[n.createModifier(D.default.SyntaxKind.ExportKeyword)],Mn=[n.createModifier(D.default.SyntaxKind.AsyncKeyword)],vn=[n.createModifier(D.default.SyntaxKind.PublicKeyword),n.createModifier(D.default.SyntaxKind.ReadonlyKeyword)],po=[n.createModifier(D.default.SyntaxKind.ProtectedKeyword),n.createModifier(D.default.SyntaxKind.ReadonlyKeyword)],Ht=n.createTemplateHead(""),Ie=n.createTemplateTail(""),Ut=n.createTemplateMiddle(" "),Ft=e=>n.createTemplateLiteralType(Ht,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?Ie:Ut))),Kt=Ft(["M","P"]),ut=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),ft=(e,t)=>(0,Ce.chain)(([r,o])=>[ut(n.createIdentifier(r),o,t)],(0,Ce.toPairs)(e)),Bt=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),co=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),lo=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),J=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],D.default.NodeFlags.Const),qt=(e,t)=>n.createTypeAliasDeclaration(Q,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),yt=(e,t)=>n.createTypeAliasDeclaration(Q,e,void 0,t),mo=(e,t,r)=>n.createPropertyDeclaration(vn,e,void 0,t,r),uo=(e,t,r)=>n.createClassDeclaration(Q,e,void 0,void 0,[t,...r]),fo=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),yo=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(D.default.SyntaxKind.AnyKeyword)]),go=(e,t,r)=>n.createInterfaceDeclaration(Q,e,void 0,t,r),ho=e=>(0,Ce.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,Ce.toPairs)(e)),$t=(e,t,r)=>n.createArrowFunction(r?Mn:void 0,void 0,e.map(o=>ut(o)),void 0,void 0,t),Vt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,ft({acc:void 0,key:void 0}),void 0,void 0,t),r]),xo=(...e)=>`"${e.join(" ")}"`;var bo=["get","post","put","delete","patch"];var h=R(require("typescript"),1),ht=require("zod");var q=R(require("typescript"),1),{factory:gt}=q.default,Gt=(e,t)=>{q.default.addSyntheticLeadingComment(e,q.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},we=(e,t,r)=>{let o=gt.createTypeAliasDeclaration(void 0,gt.createIdentifier(t),void 0,e);return r&&Gt(o,r),o},_t=(e,t)=>{let r=q.default.createSourceFile("print.ts","",q.default.ScriptTarget.Latest,!1,q.default.ScriptKind.TS);return q.default.createPrinter(t).printNode(q.default.EmitHint.Unspecified,e,r)},Ln=/^[A-Za-z_$][A-Za-z0-9_$]*$/,To=e=>Ln.test(e)?gt.createIdentifier(e):gt.createStringLiteral(e);var{factory:f}=h.default,jn={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},Dn=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),kn=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&je(a)?a instanceof ht.z.ZodOptional:a.isOptional(),c=f.createPropertySignature(void 0,To(s),p&&o?f.createToken(h.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Gt(c,a.description),c});return f.createTypeLiteralNode(i)},Hn=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),Un=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),So=({options:e},{next:t})=>f.createUnionTypeNode(e.map(t)),Fn=e=>jn?.[e.kind],Kn=(e,{next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=_e(e,Fn(o)),a={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(s&&a[s]||h.default.SyntaxKind.AnyKeyword)}return o},Bn=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),qn=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(h.default.SyntaxKind.UndefinedKeyword)]):o},$n=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),Vn=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),Gn=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),_n=({_def:e},{next:t})=>f.createIntersectionTypeNode([e.left,e.right].map(t)),Yn=({_def:e},{next:t})=>t(e.innerType),le=e=>()=>f.createKeywordTypeNode(e),Qn=(e,{next:t})=>t(e.unwrap()),Jn=(e,{next:t})=>t(e.unwrap()),Wn=({_def:e},{next:t})=>t(e.innerType),Xn=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ei=()=>f.createLiteralTypeNode(f.createNull()),ti=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:i})=>{let s=`Type${i(e)}`;return t(s)||(r(s,f.createLiteralTypeNode(f.createNull())),r(s,o(e)))},ri=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(h.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),i=f.createUnionTypeNode([r,o]);return t instanceof ht.z.ZodString?r:t instanceof ht.z.ZodUnion?i:o},oi=(e,{next:t})=>t(e.unwrap().shape.raw),ni={ZodString:le(h.default.SyntaxKind.StringKeyword),ZodNumber:le(h.default.SyntaxKind.NumberKeyword),ZodBigInt:le(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:le(h.default.SyntaxKind.BooleanKeyword),ZodAny:le(h.default.SyntaxKind.AnyKeyword),[Fe]:le(h.default.SyntaxKind.StringKeyword),[Ke]:le(h.default.SyntaxKind.StringKeyword),ZodNull:ei,ZodArray:Hn,ZodTuple:Vn,ZodRecord:Gn,ZodObject:kn,ZodLiteral:Dn,ZodIntersection:_n,ZodUnion:So,ZodDefault:Yn,ZodEnum:Un,ZodNativeEnum:Bn,ZodEffects:Kn,ZodOptional:qn,ZodNullable:$n,ZodDiscriminatedUnion:So,ZodBranded:Qn,ZodCatch:Wn,ZodPipeline:Xn,ZodLazy:ti,ZodReadonly:Jn,[_]:ri,[ne]:oi},Be=(e,{brandHandling:t,ctx:r})=>ce(e,{rules:{...t,...ni},onMissing:()=>f.createKeywordTypeNode(h.default.SyntaxKind.AnyKeyword),ctx:r});var xt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,we(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:i=Ge,splitResponse:s=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){de({routing:t,onEndpoint:(O,A,I)=>{let ue={serializer:i,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},Ne=M(I,A,"input"),Me=Be(O.getSchema("input"),{brandHandling:r,ctx:{...ue,isResponse:!1}}),Z=s?M(I,A,"positive.response"):void 0,Yt=O.getSchema("positive"),Qt=s?Be(Yt,{brandHandling:r,ctx:{...ue,isResponse:!0}}):void 0,ve=s?M(I,A,"negative.response"):void 0,Jt=O.getSchema("negative"),Wt=s?Be(Jt,{brandHandling:r,ctx:{...ue,isResponse:!0}}):void 0,Xt=M(I,A,"response"),Oo=Z&&ve?n.createUnionTypeNode([n.createTypeReferenceNode(Z),n.createTypeReferenceNode(ve)]):Be(Yt.or(Jt),{brandHandling:r,ctx:{...ue,isResponse:!0}});this.program.push(we(Me,Ne)),Qt&&Z&&this.program.push(we(Qt,Z)),Wt&&ve&&this.program.push(we(Wt,ve)),this.program.push(we(Oo,Xt)),I!=="options"&&(this.paths.push(A),this.registry.set({method:I,path:A},{input:Ne,positive:Z,negative:ve,response:Xt,isJson:O.getMimeTypes("positive").includes(N.json),tags:O.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(qt(this.ids.pathType,this.paths)),this.program.push(qt(this.ids.methodType,bo)),this.program.push(yt(this.ids.methodPathType,Ft([this.ids.methodType,this.ids.pathType])));let p=[n.createHeritageClause(E.default.SyntaxKind.ExtendsKeyword,[Bt(this.ids.methodPathType,E.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),s&&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 c=[],l=[];for(let[{method:O,path:A},{isJson:I,tags:ue,...Ne}]of this.registry){let Me=xo(O,A);for(let Z of this.interfaces)Z.kind in Ne&&Z.props.push(lo(Me,Ne[Z.kind]));o!=="types"&&(I&&c.push(n.createPropertyAssignment(Me,n.createTrue())),l.push(n.createPropertyAssignment(Me,n.createArrayLiteralExpression(ue.map(Z=>n.createStringLiteral(Z))))))}for(let{id:O,props:A}of this.interfaces)this.program.push(go(O,p,A));if(o==="types")return;let m=n.createVariableStatement(Q,J(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(c))),y=n.createVariableStatement(Q,J(this.ids.endpointTagsConst,n.createObjectLiteralExpression(l))),u=yt(this.ids.providerType,n.createFunctionTypeNode(ho({M:this.ids.methodType,P:this.ids.pathType}),ft({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Kt)}),fo(this.ids.responseInterface,Kt))),x=yt(this.ids.implementationType,n.createFunctionTypeNode(void 0,ft({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(E.default.SyntaxKind.StringKeyword),params:Bt(E.default.SyntaxKind.StringKeyword,E.default.SyntaxKind.AnyKeyword)}),yo())),z=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,Ie)]),T=Vt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[z,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),L=Vt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[z]),E.default.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),C=uo(this.ids.clientClass,co([ut(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),po)]),[mo(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),$t([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,L]),!0))]);this.program.push(m,y,u,x,C);let b=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ee=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(N.json))]),void 0,this.ids.undefinedValue)),$=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),W=n.createVariableStatement(void 0,J(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,Ie)]),n.createObjectLiteralExpression([b,Ee,$])])))),me=n.createVariableStatement(void 0,J(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ze=n.createVariableStatement(void 0,J(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),Ie)])))),[qe,bt]=["json","text"].map(O=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,O),void 0,void 0))),$e=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(Ht,[n.createTemplateSpan(this.ids.methodParameter,Ut),n.createTemplateSpan(this.ids.pathParameter,Ie)]),E.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([qe])),k=n.createVariableStatement(Q,J(this.ids.exampleImplementationConst,$t([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([me,ze,W,$e,bt]),!0),n.createTypeReferenceNode(this.ids.implementationType))),X=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),Ze=n.createVariableStatement(void 0,J(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(k,Ze,X)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:_t(r,t)).join(`
|
|
19
|
+
`).map((d,l)=>a[l]?a[l](d):d).join(`
|
|
20
|
+
`)};var Br=e=>{e.startupLogo!==!1&&console.log(Dr());let t=e.errorHandler||xe,r=vr(e.logger)?e.logger:new Se(e.logger);r.debug("Running","v20.0.0-beta.1 (CJS)");let o=Ur({rootLogger:r,config:e}),i=kr({rootLogger:r,errorHandler:t}),s=jr({rootLogger:r,errorHandler:t});return{rootLogger:r,errorHandler:t,notFoundHandler:i,parserFailureHandler:s,loggingMiddleware:o}},qr=(e,t)=>{let{rootLogger:r,notFoundHandler:o,loggingMiddleware:i}=Br(e);return Ht({app:e.app.use(i),routing:t,rootLogger:r,config:e}),{notFoundHandler:o,logger:r}},$r=async(e,t)=>{let{rootLogger:r,notFoundHandler:o,parserFailureHandler:i,loggingMiddleware:s}=Br(e),a=(0,lt.default)().disable("x-powered-by").use(s);if(e.server.compression){let m=await Pe("compression");a.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let p={json:[e.server.jsonParser||lt.default.json()],raw:[e.server.rawParser||lt.default.raw(),Hr],upload:e.server.upload?await Mr({config:e,rootLogger:r}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:a,logger:r}),Ht({app:a,routing:t,rootLogger:r,config:e,parsers:p}),a.use(i,o);let d=(m,y)=>m.listen(y,()=>{r.info("Listening",y)}),l={httpServer:d(Fr.default.createServer(a),e.server.listen),httpsServer:e.https?d(Kr.default.createServer(e.https.options,a),e.https.listen):void 0};return{app:a,...l,logger:r}};var lo=O(require("assert/strict"),1),mo=require("openapi3-ts/oas31"),uo=require("ramda");var q=O(require("assert/strict"),1),J=require("openapi3-ts/oas31"),c=require("ramda"),S=require("zod");var Ie=require("zod");var mt=e=>!isNaN(e.getTime());var Ve=Symbol("DateIn"),Vr=()=>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(mt)).brand(Ve);var Gr=require("zod");var Ge=Symbol("DateOut"),_r=()=>Gr.z.date().refine(mt).transform(e=>e.toISOString()).brand(Ge);var ae=(e,{onEach:t,rules:r,onMissing:o,ctx:i={}})=>{let s=r[e._def[g]?.brand]||r[e._def.typeName],p=s?s(e,{...i,next:l=>ae(l,{ctx:i,onEach:t,rules:r,onMissing:o})}):o(e,i),d=t&&t(e,{prev:p,...i});return d?{...p,...d}:p};var Yr=50,Jr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",_o={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Wr=/:([A-Za-z0-9_]+)/g,Yo=e=>e.match(Wr)?.map(t=>t.slice(1))||[],Xr=e=>e.replace(Wr,t=>`{${t.slice(1)}}`),Qo=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Jo=({_def:{innerType:e}},{next:t})=>t(e),Wo=()=>({format:"any"}),Xo=({},e)=>((0,q.default)(!e.isResponse,new P({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),en=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"}},tn=({options:e},{next:t})=>({oneOf:e.map(t)}),rn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),on=e=>{let[t,r]=e.filter(i=>!(0,J.isReferenceObject)(i)&&i.type==="object"&&Object.keys(i).every(s=>["type","properties","required","examples"].includes(s)));(0,q.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,c.mergeDeepWith)((i,s)=>Array.isArray(i)&&Array.isArray(s)?(0,c.concat)(i,s):i===s?s:q.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,c.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=oe(t.examples||[],r.examples||[],([i,s])=>(0,c.mergeDeepRight)(i,s))),o},nn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return on(o)}catch{}return{allOf:o}},sn=(e,{next:t})=>t(e.unwrap()),an=(e,{next:t})=>t(e.unwrap()),pn=(e,{next:t})=>{let r=t(e.unwrap());return(0,J.isReferenceObject)(r)||(r.type=to(r)),r},eo=e=>{let t=(0,c.toLower)((0,c.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},Qr=e=>({type:eo(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),cn=({value:e})=>({type:eo(e),const:e}),dn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),i=p=>t&&Ue(p)?p instanceof S.z.ZodOptional:p.isOptional(),s=o.filter(p=>!i(e.shape[p])),a={type:"object"};return o.length&&(a.properties=ut(e,r)),s.length&&(a.required=s),a},ln=()=>({type:"null"}),mn=({},e)=>((0,q.default)(!e.isResponse,new P({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:Jr}}),un=({},e)=>((0,q.default)(e.isResponse,new P({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Jr}}),fn=({},e)=>q.default.fail(new P({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})),yn=()=>({type:"boolean"}),gn=()=>({type:"integer",format:"bigint"}),hn=e=>e.every(t=>t instanceof S.z.ZodLiteral),xn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.z.ZodEnum||e instanceof S.z.ZodNativeEnum){let o=Object.values(e.enum),i={type:"object"};return o.length&&(i.properties=ut(S.z.object((0,c.fromPairs)((0,c.xprod)(o,[t]))),r),i.required=o),i}if(e instanceof S.z.ZodLiteral)return{type:"object",properties:ut(S.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.z.ZodUnion&&hn(e.options)){let o=(0,c.map)(s=>`${s.value}`,e.options),i=(0,c.fromPairs)((0,c.xprod)(o,[t]));return{type:"object",properties:ut(S.z.object(i),r),required:o}}return{type:"object",additionalProperties:r(t)}},bn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let i={type:"array",items:o(r)};return e&&(i.minItems=e.value),t&&(i.maxItems=t.value),i},Tn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),Sn=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:i,isCUID:s,isCUID2:a,isULID:p,isIP:d,isEmoji:l,isDatetime:m,_def:{checks:y}})=>{let f=y.find(I=>I.kind==="regex"),b=y.find(I=>I.kind==="datetime"),Z=f?f.regex:b?b.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"},j={"date-time":m,email:e,url:t,uuid:i,cuid:s,cuid2:a,ulid:p,ip:d,emoji:l};for(let I in j)if(j[I]){T.format=I;break}return r!==null&&(T.minLength=r),o!==null&&(T.maxLength=o),Z&&(T.pattern=Z.source),T},On=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let i=o.find(({kind:y})=>y==="min"),s=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=i?i.inclusive:!0,p=o.find(({kind:y})=>y==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,l=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=s:m.exclusiveMinimum=s,l?m.maximum=d:m.exclusiveMaximum=d,m},ut=({shape:e},t)=>(0,c.map)(t,e),Rn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return _o?.[t]},to=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},An=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:i}=e._def;if(t&&i.type==="transform"&&!(0,J.isReferenceObject)(o)){let s=et(e,Rn(o));return s&&["number","string","boolean"].includes(s)?{type:s}:r(S.z.any())}if(!t&&i.type==="preprocess"&&!(0,J.isReferenceObject)(o)){let{type:s,...a}=o;return{...a,format:`${a.format||s} (preprocessed)`}}return o},Pn=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),In=(e,{next:t})=>t(e.unwrap()),Cn=({schema:e},{next:t,serializer:r,getRef:o,makeRef:i})=>{let s=r(e);return o(s)||(i(s,{}),i(s,t(e)))},zn=(e,{next:t})=>t(e.unwrap().shape.raw),ro=e=>e.length?(0,c.fromPairs)((0,c.zip)((0,c.range)(1,e.length+1).map(t=>`example${t}`),(0,c.map)((0,c.objOf)("value"),e))):void 0,oo=(e,t,r=[])=>(0,c.pipe)(F,(0,c.map)((0,c.when)((0,c.both)(K,(0,c.complement)(Array.isArray)),(0,c.omit)(r))),ro)({schema:e,variant:t?"parsed":"original",validate:!0}),wn=(e,t)=>(0,c.pipe)(F,(0,c.filter)((0,c.has)(t)),(0,c.pluck)(t),ro)({schema:e,variant:"original",validate:!0}),Ce=(e,t)=>e instanceof S.z.ZodObject?e:e instanceof S.z.ZodBranded?Ce(e.unwrap(),t):e instanceof S.z.ZodUnion||e instanceof S.z.ZodDiscriminatedUnion?e.options.map(r=>Ce(r,t)).reduce((r,o)=>r.merge(o.partial()),S.z.object({})):e instanceof S.z.ZodEffects?((0,q.default)(e._def.effect.type==="refinement",t),Ce(e._def.schema,t)):Ce(e._def.left,t).merge(Ce(e._def.right,t)),no=({path:e,method:t,schema:r,inputSources:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,description:l=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=Ce(r,new P({message:"Using transformations on the top level schema is not allowed.",path:e,method:t,isResponse:!1})),y=Yo(e),f=o.includes("query"),b=o.includes("params"),Z=o.includes("headers"),T=x=>b&&y.includes(x),j=x=>Z&&Ct(x);return Object.keys(m).map(x=>({name:x,location:T(x)?"path":j(x)?"header":f?"query":void 0})).filter(x=>x.location!==void 0).map(({name:x,location:ve})=>{let V=ae(m[x],{rules:{...d,...Dt},onEach:Ft,onMissing:Kt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:e,method:t}}),ee=p==="components"?a(N(l,x),V):V;return{name:x,in:ve,required:!m[x].isOptional(),description:V.description||l,schema:ee,examples:wn(r,x)}})},Dt={ZodString:Sn,ZodNumber:On,ZodBigInt:gn,ZodBoolean:yn,ZodNull:ln,ZodArray:bn,ZodTuple:Tn,ZodRecord:xn,ZodObject:dn,ZodLiteral:cn,ZodIntersection:nn,ZodUnion:tn,ZodAny:Wo,ZodDefault:Qo,ZodEnum:Qr,ZodNativeEnum:Qr,ZodEffects:An,ZodOptional:sn,ZodNullable:pn,ZodDiscriminatedUnion:rn,ZodBranded:In,ZodDate:fn,ZodCatch:Jo,ZodPipeline:Pn,ZodLazy:Cn,ZodReadonly:an,[Q]:en,[Ke]:Xo,[Ge]:un,[Ve]:mn,[ne]:zn},Ft=(e,{isResponse:t,prev:r})=>{if((0,J.isReferenceObject)(r))return{};let{description:o}=e,i=e instanceof S.z.ZodLazy,s=r.type!==void 0,a=t&&Ue(e),p=!i&&s&&!a&&e.isNullable(),d=i?[]:F({schema:e,variant:t?"parsed":"original",validate:!0}),l={};return o&&(l.description=o),p&&(l.type=to(r)),d.length&&(l.examples=d.slice()),l},Kt=(e,t)=>q.default.fail(new P({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Ut=(e,t)=>{if((0,J.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,c.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,c.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},io=e=>(0,J.isReferenceObject)(e)?e:(0,c.omit)(["examples"],e),so=({method:e,path:t,schema:r,mimeTypes:o,variant:i,serializer:s,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:l,statusCode:m,brandHandling:y,description:f=`${e.toUpperCase()} ${t} ${wt(i)} response ${l?m:""}`.trim()})=>{let b=io(ae(r,{rules:{...y,...Dt},onEach:Ft,onMissing:Kt,ctx:{isResponse:!0,serializer:s,getRef:a,makeRef:p,path:t,method:e}})),Z={schema:d==="components"?p(N(f),b):b,examples:oo(r,!0)};return{description:f,content:(0,c.fromPairs)((0,c.xprod)(o,[Z]))}},En=()=>({type:"http",scheme:"basic"}),Zn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},vn=({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},Nn=({name:e})=>({type:"apiKey",in:"header",name:e}),Ln=({name:e})=>({type:"apiKey",in:"cookie",name:e}),jn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),kn=({flows:e={}})=>({type:"oauth2",flows:(0,c.map)(t=>({...t,scopes:t.scopes||{}}),(0,c.reject)(c.isNil,e))}),ao=(e,t)=>{let r={basic:En,bearer:Zn,input:vn,header:Nn,cookie:Ln,openid:jn,oauth2:kn};return at(e,o=>r[o.type](o,t))},ft=e=>"or"in e?e.or.map(t=>"and"in t?(0,c.mergeAll)((0,c.map)(({name:r,scopes:o})=>(0,c.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?ft(vt(e)):ft({or:[e]}),po=({method:e,path:t,schema:r,mimeTypes:o,serializer:i,getRef:s,makeRef:a,composition:p,brandHandling:d,paramNames:l,description:m=`${e.toUpperCase()} ${t} Request body`})=>{let y=io(Ut(ae(r,{rules:{...d,...Dt},onEach:Ft,onMissing:Kt,ctx:{isResponse:!1,serializer:i,getRef:s,makeRef:a,path:t,method:e}}),l)),f={schema:p==="components"?a(N(m),y):y,examples:oo(r,!1,l)};return{description:m,content:(0,c.fromPairs)((0,c.xprod)(o,[f]))}},co=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<=Yr?e:e.slice(0,Yr-1)+"\u2026";var yt=class extends mo.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 i=o||N(r,t),s=this.lastOperationIdSuffixes.get(i);return s===void 0?(this.lastOperationIdSuffixes.set(i,1),i):(o&&lo.default.fail(new P({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),s++,this.lastOperationIdSuffixes.set(i,s),`${i}${s}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let i in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[i]))return i;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:i,serverUrl:s,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:l="inline",serializer:m=Xe}){super(),this.addInfo({title:o,version:i});for(let f of typeof s=="string"?[s]:s)this.addServer({url:f});se({routing:t,onEndpoint:(f,b,Z)=>{let T=Z,j={path:b,method:T,endpoint:f,composition:l,serializer:m,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[I,x]=["short","long"].map(f.getDescription.bind(f)),ve=I?Bt(I):d&&x?Bt(x):void 0,V=f.getTags(),ee=r.inputSources?.[T]||Pt[T],ce=this.ensureUniqOperationId(b,T,f.getOperationId(T)),Ne=no({...j,inputSources:ee,schema:f.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:b,operationId:ce})}),Qe={};for(let U of["positive","negative"]){let te=f.getResponses(U);for(let{mimeTypes:Le,schema:R,statusCodes:A}of te)for(let C of A)Qe[C]=so({...j,variant:U,schema:R,mimeTypes:Le,statusCode:C,hasMultipleStatusCodes:te.length>1||A.length>1,description:a?.[`${U}Response`]?.call(null,{method:T,path:b,operationId:ce,statusCode:C})})}let At=ee.includes("body")?po({...j,paramNames:(0,uo.pluck)("name",Ne),schema:f.getSchema("input"),mimeTypes:f.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:b,operationId:ce})}):void 0,Je=ft(at(ao(f.getSecurity(),ee),U=>{let te=this.ensureUniqSecuritySchemaName(U),Le=["oauth2","openIdConnect"].includes(U.type)?f.getScopes().slice():[];return this.addSecurityScheme(te,U),{name:te,scopes:Le}}));this.addPath(Xr(b),{[T]:{operationId:ce,summary:ve,description:x,tags:V.length>0?V:void 0,parameters:Ne.length>0?Ne:void 0,requestBody:At,security:Je.length>0?Je:void 0,responses:Qe}})}}),this.rootDoc.tags=r.tags?co(r.tags):[]}};var gt=require("node-mocks-http"),Mn=e=>(0,gt.createRequest)({...e,headers:{"content-type":z.json,...e?.headers}}),Hn=e=>(0,gt.createResponse)(e),Un=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,i){return o==="_getLogs"?()=>t:o in Te?(...s)=>t[o].push(s):Reflect.get(r,o,i)}})},fo=async({endpoint:e,requestProps:t,responseOptions:r,configProps:o,loggerProps:i})=>{let s=Mn(t),a=Hn({req:s,...r}),p=Un(i),d={cors:!1,logger:p,...o};return await e.execute({request:s,response:a,config:d,logger:p}),{requestMock:s,responseMock:a,loggerMock:p}};var E=O(require("typescript"),1);var H=O(require("typescript"),1),ze=require("ramda"),n=H.default.factory,W=[n.createModifier(H.default.SyntaxKind.ExportKeyword)],Dn=[n.createModifier(H.default.SyntaxKind.AsyncKeyword)],Fn=[n.createModifier(H.default.SyntaxKind.PublicKeyword),n.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],yo=[n.createModifier(H.default.SyntaxKind.ProtectedKeyword),n.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],qt=n.createTemplateHead(""),we=n.createTemplateTail(""),$t=n.createTemplateMiddle(" "),Vt=e=>n.createTemplateLiteralType(qt,e.map((t,r)=>n.createTemplateLiteralTypeSpan(n.createTypeReferenceNode(t),r===e.length-1?we:$t))),Gt=Vt(["M","P"]),ht=(e,t,r)=>n.createParameterDeclaration(r,void 0,e,void 0,t,void 0),xt=(e,t)=>(0,ze.chain)(([r,o])=>[ht(n.createIdentifier(r),o,t)],(0,ze.toPairs)(e)),_t=(e,t)=>n.createExpressionWithTypeArguments(n.createIdentifier("Record"),[typeof e=="number"?n.createKeywordTypeNode(e):n.createTypeReferenceNode(e),n.createKeywordTypeNode(t)]),go=e=>n.createConstructorDeclaration(void 0,e,n.createBlock([])),ho=(e,t)=>n.createPropertySignature(void 0,e,void 0,n.createTypeReferenceNode(t)),X=(e,t,r)=>n.createVariableDeclarationList([n.createVariableDeclaration(e,void 0,r,t)],H.default.NodeFlags.Const),Yt=(e,t)=>n.createTypeAliasDeclaration(W,e,void 0,n.createUnionTypeNode(t.map(r=>n.createLiteralTypeNode(n.createStringLiteral(r))))),bt=(e,t)=>n.createTypeAliasDeclaration(W,e,void 0,t),xo=(e,t,r)=>n.createPropertyDeclaration(Fn,e,void 0,t,r),bo=(e,t,r)=>n.createClassDeclaration(W,e,void 0,void 0,[t,...r]),To=(e,t)=>n.createTypeReferenceNode("Promise",[n.createIndexedAccessTypeNode(n.createTypeReferenceNode(e),t)]),So=()=>n.createTypeReferenceNode("Promise",[n.createKeywordTypeNode(H.default.SyntaxKind.AnyKeyword)]),Oo=(e,t,r)=>n.createInterfaceDeclaration(W,e,void 0,t,r),Ro=e=>(0,ze.chain)(([t,r])=>[n.createTypeParameterDeclaration([],t,n.createTypeReferenceNode(r))],(0,ze.toPairs)(e)),Qt=(e,t,r)=>n.createArrowFunction(r?Dn:void 0,void 0,e.map(o=>ht(o)),void 0,void 0,t),Jt=(e,t,r)=>n.createCallExpression(n.createPropertyAccessExpression(n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[n.createArrowFunction(void 0,void 0,xt({acc:void 0,key:void 0}),void 0,void 0,t),r]),Ao=(...e)=>`"${e.join(" ")}"`;var Po=["get","post","put","delete","patch"];var h=O(require("typescript"),1),St=require("zod");var $=O(require("typescript"),1),{factory:Tt}=$.default,Wt=(e,t)=>{$.default.addSyntheticLeadingComment(e,$.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ee=(e,t,r)=>{let o=Tt.createTypeAliasDeclaration(void 0,Tt.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)},Kn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Io=e=>Kn.test(e)?Tt.createIdentifier(e):Tt.createStringLiteral(e);var{factory:u}=h.default,Bn={[h.default.SyntaxKind.AnyKeyword]:"",[h.default.SyntaxKind.BigIntKeyword]:BigInt(0),[h.default.SyntaxKind.BooleanKeyword]:!1,[h.default.SyntaxKind.NumberKeyword]:0,[h.default.SyntaxKind.ObjectKeyword]:{},[h.default.SyntaxKind.StringKeyword]:"",[h.default.SyntaxKind.UndefinedKeyword]:void 0},qn=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),$n=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let i=Object.entries(e).map(([s,a])=>{let p=t&&Ue(a)?a instanceof St.z.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,Io(s),p&&o?u.createToken(h.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Wt(d,a.description),d});return u.createTypeLiteralNode(i)},Vn=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Gn=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),Co=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),_n=e=>Bn?.[e.kind],Yn=(e,{next:t,isResponse:r})=>{let o=t(e.innerType()),i=e._def.effect;if(r&&i.type==="transform"){let s=et(e,_n(o)),a={number:h.default.SyntaxKind.NumberKeyword,bigint:h.default.SyntaxKind.BigIntKeyword,boolean:h.default.SyntaxKind.BooleanKeyword,string:h.default.SyntaxKind.StringKeyword,undefined:h.default.SyntaxKind.UndefinedKeyword,object:h.default.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(s&&a[s]||h.default.SyntaxKind.AnyKeyword)}return o},Qn=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Jn=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(h.default.SyntaxKind.UndefinedKeyword)]):o},Wn=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),Xn=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),ei=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),ti=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),ri=({_def:e},{next:t})=>t(e.innerType),pe=e=>()=>u.createKeywordTypeNode(e),oi=(e,{next:t})=>t(e.unwrap()),ni=(e,{next:t})=>t(e.unwrap()),ii=({_def:e},{next:t})=>t(e.innerType),si=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),ai=()=>u.createLiteralTypeNode(u.createNull()),pi=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:i})=>{let s=`Type${i(e)}`;return t(s)||(r(s,u.createLiteralTypeNode(u.createNull())),r(s,o(e)))},ci=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(h.default.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),i=u.createUnionTypeNode([r,o]);return t instanceof St.z.ZodString?r:t instanceof St.z.ZodUnion?i:o},di=(e,{next:t})=>t(e.unwrap().shape.raw),li={ZodString:pe(h.default.SyntaxKind.StringKeyword),ZodNumber:pe(h.default.SyntaxKind.NumberKeyword),ZodBigInt:pe(h.default.SyntaxKind.BigIntKeyword),ZodBoolean:pe(h.default.SyntaxKind.BooleanKeyword),ZodAny:pe(h.default.SyntaxKind.AnyKeyword),[Ve]:pe(h.default.SyntaxKind.StringKeyword),[Ge]:pe(h.default.SyntaxKind.StringKeyword),ZodNull:ai,ZodArray:Vn,ZodTuple:Xn,ZodRecord:ei,ZodObject:$n,ZodLiteral:qn,ZodIntersection:ti,ZodUnion:Co,ZodDefault:ri,ZodEnum:Gn,ZodNativeEnum:Qn,ZodEffects:Yn,ZodOptional:Jn,ZodNullable:Wn,ZodDiscriminatedUnion:Co,ZodBranded:oi,ZodCatch:ii,ZodPipeline:si,ZodLazy:pi,ZodReadonly:ni,[Q]:ci,[ne]:di},_e=(e,{brandHandling:t,ctx:r})=>ae(e,{rules:{...t,...li},onMissing:()=>u.createKeywordTypeNode(h.default.SyntaxKind.AnyKeyword),ctx:r});var Ot=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:n.createIdentifier("Path"),methodType:n.createIdentifier("Method"),methodPathType:n.createIdentifier("MethodPath"),inputInterface:n.createIdentifier("Input"),posResponseInterface:n.createIdentifier("PositiveResponse"),negResponseInterface:n.createIdentifier("NegativeResponse"),responseInterface:n.createIdentifier("Response"),jsonEndpointsConst:n.createIdentifier("jsonEndpoints"),endpointTagsConst:n.createIdentifier("endpointTags"),providerType:n.createIdentifier("Provider"),implementationType:n.createIdentifier("Implementation"),clientClass:n.createIdentifier("ExpressZodAPIClient"),keyParameter:n.createIdentifier("key"),pathParameter:n.createIdentifier("path"),paramsArgument:n.createIdentifier("params"),methodParameter:n.createIdentifier("method"),accumulator:n.createIdentifier("acc"),provideMethod:n.createIdentifier("provide"),implementationArgument:n.createIdentifier("implementation"),headersProperty:n.createIdentifier("headers"),hasBodyConst:n.createIdentifier("hasBody"),undefinedValue:n.createIdentifier("undefined"),bodyProperty:n.createIdentifier("body"),responseConst:n.createIdentifier("response"),searchParamsConst:n.createIdentifier("searchParams"),exampleImplementationConst:n.createIdentifier("exampleImplementation"),clientConst:n.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?n.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:i=Xe,splitResponse:s=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){se({routing:t,onEndpoint:(R,A,C)=>{let de={serializer:i,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},je=N(C,A,"input"),ke=_e(R.getSchema("input"),{brandHandling:r,ctx:{...de,isResponse:!1}}),v=s?N(C,A,"positive.response"):void 0,er=R.getSchema("positive"),tr=s?_e(er,{brandHandling:r,ctx:{...de,isResponse:!0}}):void 0,Me=s?N(C,A,"negative.response"):void 0,rr=R.getSchema("negative"),or=s?_e(rr,{brandHandling:r,ctx:{...de,isResponse:!0}}):void 0,nr=N(C,A,"response"),Eo=v&&Me?n.createUnionTypeNode([n.createTypeReferenceNode(v),n.createTypeReferenceNode(Me)]):_e(er.or(rr),{brandHandling:r,ctx:{...de,isResponse:!0}});this.program.push(Ee(ke,je)),tr&&v&&this.program.push(Ee(tr,v)),or&&Me&&this.program.push(Ee(or,Me)),this.program.push(Ee(Eo,nr)),C!=="options"&&(this.paths.push(A),this.registry.set({method:C,path:A},{input:je,positive:v,negative:Me,response:nr,isJson:R.getMimeTypes("positive").includes(z.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,Po)),this.program.push(bt(this.ids.methodPathType,Vt([this.ids.methodType,this.ids.pathType])));let p=[n.createHeritageClause(E.default.SyntaxKind.ExtendsKeyword,[_t(this.ids.methodPathType,E.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),s&&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=[],l=[];for(let[{method:R,path:A},{isJson:C,tags:de,...je}]of this.registry){let ke=Ao(R,A);for(let v of this.interfaces)v.kind in je&&v.props.push(ho(ke,je[v.kind]));o!=="types"&&(C&&d.push(n.createPropertyAssignment(ke,n.createTrue())),l.push(n.createPropertyAssignment(ke,n.createArrayLiteralExpression(de.map(v=>n.createStringLiteral(v))))))}for(let{id:R,props:A}of this.interfaces)this.program.push(Oo(R,p,A));if(o==="types")return;let m=n.createVariableStatement(W,X(this.ids.jsonEndpointsConst,n.createObjectLiteralExpression(d))),y=n.createVariableStatement(W,X(this.ids.endpointTagsConst,n.createObjectLiteralExpression(l))),f=bt(this.ids.providerType,n.createFunctionTypeNode(Ro({M:this.ids.methodType,P:this.ids.pathType}),xt({method:n.createTypeReferenceNode("M"),path:n.createTypeReferenceNode("P"),params:n.createIndexedAccessTypeNode(n.createTypeReferenceNode(this.ids.inputInterface),Gt)}),To(this.ids.responseInterface,Gt))),b=bt(this.ids.implementationType,n.createFunctionTypeNode(void 0,xt({method:n.createTypeReferenceNode(this.ids.methodType),path:n.createKeywordTypeNode(E.default.SyntaxKind.StringKeyword),params:_t(E.default.SyntaxKind.StringKeyword,E.default.SyntaxKind.AnyKeyword)}),So())),Z=n.createTemplateExpression(n.createTemplateHead(":"),[n.createTemplateSpan(this.ids.keyParameter,we)]),T=Jt(this.ids.paramsArgument,n.createCallExpression(n.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[Z,n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),j=Jt(this.ids.paramsArgument,n.createConditionalExpression(n.createBinaryExpression(n.createCallExpression(n.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[Z]),E.default.SyntaxKind.GreaterThanEqualsToken,n.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,n.createObjectLiteralExpression([n.createSpreadAssignment(this.ids.accumulator),n.createPropertyAssignment(n.createComputedPropertyName(this.ids.keyParameter),n.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),n.createObjectLiteralExpression()),I=bo(this.ids.clientClass,go([ht(this.ids.implementationArgument,n.createTypeReferenceNode(this.ids.implementationType),yo)]),[xo(this.ids.provideMethod,n.createTypeReferenceNode(this.ids.providerType),Qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createCallExpression(n.createPropertyAccessExpression(n.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,j]),!0))]);this.program.push(m,y,f,b,I);let x=n.createPropertyAssignment(this.ids.methodParameter,n.createCallExpression(n.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ve=n.createPropertyAssignment(this.ids.headersProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createObjectLiteralExpression([n.createPropertyAssignment(n.createStringLiteral("Content-Type"),n.createStringLiteral(z.json))]),void 0,this.ids.undefinedValue)),V=n.createPropertyAssignment(this.ids.bodyProperty,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createCallExpression(n.createPropertyAccessExpression(n.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),ee=n.createVariableStatement(void 0,X(this.ids.responseConst,n.createAwaitExpression(n.createCallExpression(n.createIdentifier("fetch"),void 0,[n.createTemplateExpression(n.createTemplateHead("https://example.com"),[n.createTemplateSpan(this.ids.pathParameter,n.createTemplateMiddle("")),n.createTemplateSpan(this.ids.searchParamsConst,we)]),n.createObjectLiteralExpression([x,ve,V])])))),ce=n.createVariableStatement(void 0,X(this.ids.hasBodyConst,n.createLogicalNot(n.createCallExpression(n.createPropertyAccessExpression(n.createArrayLiteralExpression([n.createStringLiteral("get"),n.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),Ne=n.createVariableStatement(void 0,X(this.ids.searchParamsConst,n.createConditionalExpression(this.ids.hasBodyConst,void 0,n.createStringLiteral(""),void 0,n.createTemplateExpression(n.createTemplateHead("?"),[n.createTemplateSpan(n.createNewExpression(n.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),we)])))),[Qe,At]=["json","text"].map(R=>n.createReturnStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.responseConst,R),void 0,void 0))),Je=n.createIfStatement(n.createBinaryExpression(n.createTemplateExpression(qt,[n.createTemplateSpan(this.ids.methodParameter,$t),n.createTemplateSpan(this.ids.pathParameter,we)]),E.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),n.createBlock([Qe])),U=n.createVariableStatement(W,X(this.ids.exampleImplementationConst,Qt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],n.createBlock([ce,Ne,ee,Je,At]),!0),n.createTypeReferenceNode(this.ids.implementationType))),te=n.createExpressionStatement(n.createCallExpression(n.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[n.createStringLiteral("get"),n.createStringLiteral("/v1/user/retrieve"),n.createObjectLiteralExpression([n.createPropertyAssignment("id",n.createStringLiteral("10"))])])),Le=n.createVariableStatement(void 0,X(this.ids.clientConst,n.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(U,Le,te)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Xt(r,t)).join(`
|
|
21
21
|
`):void 0}print(t){let r=this.printUsage(t),o=r&&E.default.addSyntheticLeadingComment(E.default.addSyntheticLeadingComment(n.createEmptyStatement(),E.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),E.default.SyntaxKind.MultiLineCommentTrivia,`
|
|
22
|
-
${r}`);return this.program.concat(o||[]).map((i,s)=>
|
|
22
|
+
${r}`);return this.program.concat(o||[]).map((i,s)=>Xt(i,s<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
23
23
|
|
|
24
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await
|
|
24
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let a=(await Pe("prettier")).format;o=p=>a(p,{filepath:"client.ts"})}catch{}let i=this.printUsage(t);this.usage=i&&o?[await o(i)]:this.usage;let s=this.print(t);return o?o(s):s}};var zo={dateIn:Vr,dateOut:_r,file:ot,upload:hr,raw:yr};var mi="ez-migration",ui="express-zod-api",fi="testEndpoint",Ze={createLogger:"BuiltinLogger",createResultHandler:"ResultHandler",createMiddleware:"Middleware"},Rt={getPositiveResponse:"positive",getNegativeResponse:"negative",responseProps:"responseOptions",middleware:"handler"},yi={fnMethod:null},Ye=(e,t)=>typeof e=="string"&&e in t,gi={meta:{type:"problem",fixable:"code"},create:e=>({ImportDeclaration:t=>{if(t.source.value===ui){for(let r of t.specifiers)if(r.type==="ImportSpecifier"&&Ye(r.imported.name,Ze)){let o=Ze[r.imported.name];e.report({node:r.imported,message:`Change import "${r.imported.name}" to "${o}".`,fix:i=>i.replaceText(r,o)})}}},CallExpression:t=>{if(t.callee.type==="Identifier"&&Ye(t.callee.name,Ze)){let r=`new ${Ze[t.callee.name]}`;e.report({node:t.callee,message:`Change "${t.callee.name}" to "${r}".`,fix:o=>o.replaceText(t.callee,r)})}if(t.callee.type==="Identifier"&&t.callee.name===fi&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let r of t.arguments[0].properties)if(r.type==="Property"&&r.key.type==="Identifier"){if(Ye(r.key.name,Rt)){let o=Rt[r.key.name];e.report({node:r,message:`Change property "${r.key.name}" to "${o}".`,fix:i=>i.replaceText(r.key,o)})}Ye(r.key.name,yi)&&e.report({node:r,message:`Remove property "${r.key.name}".`,fix:o=>e.sourceCode.getTokenAfter(r)?.value===","&&r.range?o.removeRange([r.range[0],r.range[1]+1]):o.remove(r)})}}},NewExpression:t=>{if(t.callee.type==="Identifier"&&[Ze.createResultHandler,Ze.createMiddleware].includes(t.callee.name)&&t.arguments.length===1&&t.arguments[0].type==="ObjectExpression"){for(let r of t.arguments[0].properties)if(r.type==="Property"&&r.key.type==="Identifier"&&Ye(r.key.name,Rt)){let o=Rt[r.key.name];e.report({node:r,message:`Change property "${r.key.name}" to "${o}".`,fix:i=>i.replaceText(r.key,o)})}}},Identifier:t=>{t.name==="MockOverrides"&&t.parent.type==="TSInterfaceDeclaration"&&e.report({node:t,message:`Remove augmentation of the "${t.name}" interface \u2014 no longer needed.`,fix:r=>r.remove(t.parent)})}})},hi={v20:gi},wo={rules:{"ez-migration/v20":"error"},plugins:{[mi]:{rules:hi}}};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,migration,testEndpoint});
|