express-zod-api 25.0.0-beta.6 → 25.0.0-beta.7
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 +18 -3
- package/CODE_OF_CONDUCT.md +96 -132
- package/dist/index.d.ts +5 -16
- package/dist/index.js +5 -5
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -5,8 +5,11 @@
|
|
|
5
5
|
### v25.0.0
|
|
6
6
|
|
|
7
7
|
- Supported Node.js versions: `^20.19.0 || ^22.12.0 || ^24.0.0`:
|
|
8
|
-
|
|
8
|
+
- The framework distribution is now ESM-only (finally);
|
|
9
9
|
- All the Node.js versions listed above support `require(ESM)` syntax;
|
|
10
|
+
- If facing TypeScript error `TS1479`, ensure either:
|
|
11
|
+
- using the [recommended tsconfig base for Node 20+](https://github.com/tsconfig/bases/blob/main/bases/node20.json);
|
|
12
|
+
- or switching your project to ESM by setting `"type": "module"` in `package.json`;
|
|
10
13
|
- Supported `zod` version: `^4.0.0`;
|
|
11
14
|
- Compatibility with `zod@^3` is dropped;
|
|
12
15
|
- You SHOULD now `import { z } from "zod"` without the `/v4` suffix;
|
|
@@ -18,6 +21,7 @@
|
|
|
18
21
|
- When the `input` schema is not defined, the `input` argument of the `handler` method is now `unknown`;
|
|
19
22
|
- Changes to publicly exposed method:
|
|
20
23
|
- The `getExamples()` helper is removed, use `.meta().examples` or `globalRegistry.get().examples` instead.
|
|
24
|
+
- Consider [the automated migration](https://www.npmjs.com/package/@express-zod-api/migration).
|
|
21
25
|
|
|
22
26
|
```diff
|
|
23
27
|
- z.string().meta({ example: "test" });
|
|
@@ -34,6 +38,17 @@
|
|
|
34
38
|
|
|
35
39
|
## Version 24
|
|
36
40
|
|
|
41
|
+
### v24.7.3
|
|
42
|
+
|
|
43
|
+
- Fixed the depiction of the negative response to `HEAD` requests:
|
|
44
|
+
- Should have no response body, exactly as the positive one;
|
|
45
|
+
- This version corrects the implementation introduced in [v24.7.0](#v2470).
|
|
46
|
+
|
|
47
|
+
### v24.7.2
|
|
48
|
+
|
|
49
|
+
- Fixed the negative response MIME type for ~~`arrayResultHandler`~~ (deprecated entity):
|
|
50
|
+
- Should have been `text/plain`.
|
|
51
|
+
|
|
37
52
|
### v24.7.1
|
|
38
53
|
|
|
39
54
|
- Compatibility fix for `zod@^3.25.68` and `^4.0.0`:
|
|
@@ -51,10 +66,10 @@
|
|
|
51
66
|
- It is the built-in feature of Express to handle `HEAD` requests by the handlers for `GET` requests;
|
|
52
67
|
- Therefore, each `Endpoint` supporting `get` method also handles `head` requests (no work needed);
|
|
53
68
|
- Added `HEAD` method to CORS response headers, along with `OPTIONS`, for `GET` method supporting endpoints;
|
|
54
|
-
- Positive
|
|
69
|
+
- ~~Positive~~ Response to `HEAD` request should contain same headers as `GET` would, but without the body:
|
|
55
70
|
- Added `head` request depiction to the generated `Documentation`;
|
|
56
71
|
- Added `head` request types to the generated `Integration` client;
|
|
57
|
-
- Positive
|
|
72
|
+
- ~~Positive~~ Response to `HEAD` request should contain the `Content-Length` header:
|
|
58
73
|
- `ResultHandler`s using `response.send()` (as well as its shorthands such as `.json()`) automatically do that
|
|
59
74
|
instead of sending the response body (no work needed);
|
|
60
75
|
- Other approaches, such as stream piping, might require to implement `Content-Length` header for `HEAD` requests;
|
package/CODE_OF_CONDUCT.md
CHANGED
|
@@ -1,132 +1,96 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
-
|
|
21
|
-
|
|
22
|
-
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
-
|
|
35
|
-
|
|
36
|
-
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
##
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
**Community Impact**: A serious violation of community standards, including
|
|
98
|
-
sustained inappropriate behavior.
|
|
99
|
-
|
|
100
|
-
**Consequence**: A temporary ban from any sort of interaction or public
|
|
101
|
-
communication with the community for a specified period of time. No public or
|
|
102
|
-
private interaction with the people involved, including unsolicited interaction
|
|
103
|
-
with those enforcing the Code of Conduct, is allowed during this period.
|
|
104
|
-
Violating these terms may lead to a permanent ban.
|
|
105
|
-
|
|
106
|
-
### 4. Permanent Ban
|
|
107
|
-
|
|
108
|
-
**Community Impact**: Demonstrating a pattern of violation of community
|
|
109
|
-
standards, including sustained inappropriate behavior, harassment of an
|
|
110
|
-
individual, or aggression toward or disparagement of classes of individuals.
|
|
111
|
-
|
|
112
|
-
**Consequence**: A permanent ban from any sort of public interaction within the
|
|
113
|
-
community.
|
|
114
|
-
|
|
115
|
-
## Attribution
|
|
116
|
-
|
|
117
|
-
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
|
118
|
-
version 2.1, available at
|
|
119
|
-
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
|
120
|
-
|
|
121
|
-
Community Impact Guidelines were inspired by
|
|
122
|
-
[Mozilla's code of conduct enforcement ladder][mozilla coc].
|
|
123
|
-
|
|
124
|
-
For answers to common questions about this code of conduct, see the FAQ at
|
|
125
|
-
[https://www.contributor-covenant.org/faq][faq]. Translations are available at
|
|
126
|
-
[https://www.contributor-covenant.org/translations][translations].
|
|
127
|
-
|
|
128
|
-
[homepage]: https://www.contributor-covenant.org
|
|
129
|
-
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
|
130
|
-
[mozilla coc]: https://github.com/mozilla/diversity
|
|
131
|
-
[faq]: https://www.contributor-covenant.org/faq
|
|
132
|
-
[translations]: https://www.contributor-covenant.org/translations
|
|
1
|
+
# Code of Conduct for the Express Zod API Community
|
|
2
|
+
|
|
3
|
+
This Code of Conduct is adapted from the [Berlin Code of Conduct](https://berlincodeofconduct.org/en),
|
|
4
|
+
licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/).
|
|
5
|
+
|
|
6
|
+
Our primary goal is to foster an inclusive, friendly, safe, and welcoming environment for all
|
|
7
|
+
contributors, users, and participants in the Express Zod API project, regardless of gender,
|
|
8
|
+
sexual orientation, ability, ethnicity, socioeconomic status, or religion.
|
|
9
|
+
|
|
10
|
+
A supplemental goal is to promote **open-source citizenship** by encouraging all participants to
|
|
11
|
+
understand the impact of their actions on the community and to actively counteract inequality and
|
|
12
|
+
abuses of power within our project spaces.
|
|
13
|
+
|
|
14
|
+
## Key Expectations for Participants
|
|
15
|
+
|
|
16
|
+
The Express Zod API community expects participants to:
|
|
17
|
+
|
|
18
|
+
- **Participate authentically and actively.** Your contributions should be genuine and made in good
|
|
19
|
+
faith towards the project's goals.
|
|
20
|
+
- **Exercise consideration and respect** in your speech and actions within all project communications
|
|
21
|
+
(e.g., GitHub issues, pull requests, discussions, Discord/chat).
|
|
22
|
+
- **Attempt collaboration before conflict.** When disagreements arise, seek to understand different
|
|
23
|
+
perspectives and find common ground respectfully before escalating.
|
|
24
|
+
- **Refrain from demeaning, discriminatory, or harassing behavior and speech.** This applies to all
|
|
25
|
+
online interactions, written communication, and any in-person events related to the project.
|
|
26
|
+
- **Be mindful of your surroundings** in shared online spaces. If you notice a dangerous situation,
|
|
27
|
+
someone in distress, or violations of this Code of Conduct, please report it to the project
|
|
28
|
+
maintainers.
|
|
29
|
+
|
|
30
|
+
## Unacceptable Behaviors
|
|
31
|
+
|
|
32
|
+
The following behaviors are considered unacceptable within the Express Zod API community:
|
|
33
|
+
|
|
34
|
+
- **Intimidating, harassing, abusive, discriminatory, derogatory, or demeaning speech or actions** by
|
|
35
|
+
any participant in our community online or in any related context.
|
|
36
|
+
- **Harmful or prejudiced comments** related to gender, sexual orientation, disability, mental
|
|
37
|
+
illness, neuro(a)typicality, physical appearance, body size, race, ethnicity, age, religion, or
|
|
38
|
+
other personal attributes.
|
|
39
|
+
- **Inappropriate use of nudity and/or sexual images** in public online spaces (e.g., as profile
|
|
40
|
+
pictures, in discussions).
|
|
41
|
+
- **Deliberate intimidation, stalking, or following** of community members.
|
|
42
|
+
- **Harassing photography or recording** of in-person interactions without explicit consent.
|
|
43
|
+
- **Sustained disruption** of discussions, talks, or other online activities.
|
|
44
|
+
- **Inappropriate physical contact** (in in-person contexts).
|
|
45
|
+
- **Unwelcome sexual attention.** This includes sexualized comments or jokes, inappropriate touching,
|
|
46
|
+
groping, and unwelcome sexual advances.
|
|
47
|
+
- **Advocating for, or encouraging, any of the above behaviors.**
|
|
48
|
+
|
|
49
|
+
## Consequences of Unacceptable Behavior
|
|
50
|
+
|
|
51
|
+
Unacceptable behavior from any participant will not be tolerated.
|
|
52
|
+
|
|
53
|
+
- Anyone asked to stop unacceptable behavior is expected to comply **immediately**.
|
|
54
|
+
- If a participant engages in unacceptable behavior, the project maintainers may take any action they
|
|
55
|
+
deem appropriate, including a temporary ban, permanent expulsion from the community, or
|
|
56
|
+
editing/deletion of offending content, without warning or refund (if applicable to any paid
|
|
57
|
+
access/materials).
|
|
58
|
+
|
|
59
|
+
## Reporting Guidelines
|
|
60
|
+
|
|
61
|
+
If you are subject to, or witness, unacceptable behavior, or have any other concerns, please notify
|
|
62
|
+
the project maintainers as soon as possible.
|
|
63
|
+
|
|
64
|
+
**How to Report:**
|
|
65
|
+
|
|
66
|
+
- **For private and sensitive reports:** Contact the core maintainers directly via
|
|
67
|
+
[email](https://github.com/RobinTail/express-zod-api/blob/master/express-zod-api/package.json#L14).
|
|
68
|
+
- **For less sensitive or public issues:** You may open a GitHub issue, but be mindful of privacy and
|
|
69
|
+
consider if direct email is more appropriate.
|
|
70
|
+
|
|
71
|
+
Project maintainers will be available to help participants contact local law enforcement, provide
|
|
72
|
+
escorts, or otherwise assist those experiencing unacceptable behavior to feel safe. Your grievance
|
|
73
|
+
will be handled seriously and investigated according to existing project governing policies. We
|
|
74
|
+
respect concerns about false accusations and will handle them according to our project's dispute
|
|
75
|
+
resolution processes.
|
|
76
|
+
|
|
77
|
+
## Scope and Applicability
|
|
78
|
+
|
|
79
|
+
This Code of Conduct applies to all Express Zod API community participants in all official project
|
|
80
|
+
venues, both online and potentially in-person (e.g., meetups, sprints), and in one-on-one
|
|
81
|
+
communications related to project business. This includes, but is not limited to:
|
|
82
|
+
|
|
83
|
+
- The [GitHub repository](https://github.com/RobinTail/express-zod-api);
|
|
84
|
+
- GitHub Issues and Pull Requests;
|
|
85
|
+
- GitHub Discussions;
|
|
86
|
+
- Project-related chat platforms (e.g., Discord, Slack if applicable);
|
|
87
|
+
- Any official project social media accounts;
|
|
88
|
+
- Any future in-person events or workshops organized by the project.
|
|
89
|
+
|
|
90
|
+
## License
|
|
91
|
+
|
|
92
|
+
This Code of Conduct, being a derivative work of the Berlin Code of Conduct, is also licensed under
|
|
93
|
+
the [CC BY-SA 4.0 License](https://creativecommons.org/licenses/by-sa/4.0/). You are free to share
|
|
94
|
+
and adapt this work, provided you give appropriate credit, provide a link to the license, and
|
|
95
|
+
indicate if changes were made. If you remix, transform, or build upon the material, you must
|
|
96
|
+
distribute your contributions under the same license as the original.
|
package/dist/index.d.ts
CHANGED
|
@@ -34,12 +34,6 @@ type Intact<T, U> = {
|
|
|
34
34
|
[K in Exclude<keyof T, keyof U>]: T[K];
|
|
35
35
|
};
|
|
36
36
|
|
|
37
|
-
/** @todo remove when typed, https://github.com/ramda/types/pull/140 */
|
|
38
|
-
declare module "ramda" {
|
|
39
|
-
function renameKeys<V extends string, T extends object, U extends {
|
|
40
|
-
[P in keyof T]?: V;
|
|
41
|
-
}>(mapping: U): (subject: T) => Remap<T, U, V>;
|
|
42
|
-
}
|
|
43
37
|
declare module "zod/v4/core" {
|
|
44
38
|
interface GlobalMeta {
|
|
45
39
|
default?: unknown;
|
|
@@ -392,7 +386,10 @@ declare const defaultResultHandler: ResultHandler<z.ZodObject<{
|
|
|
392
386
|
* @desc Responding with array is a bad practice keeping your endpoints from evolving without breaking changes.
|
|
393
387
|
* @desc This handler expects your endpoint to have the property 'items' in the output object schema
|
|
394
388
|
* */
|
|
395
|
-
declare const arrayResultHandler: ResultHandler<z.ZodArray<z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>> | z.ZodArray<z.ZodAny>,
|
|
389
|
+
declare const arrayResultHandler: ResultHandler<z.ZodArray<z.core.$ZodType<unknown, unknown, z.core.$ZodTypeInternals<unknown, unknown>>> | z.ZodArray<z.ZodAny>, {
|
|
390
|
+
schema: z.ZodString;
|
|
391
|
+
mimeType: string;
|
|
392
|
+
}>;
|
|
396
393
|
|
|
397
394
|
/** @desc Returns child logger for the given request (if configured) or the configured logger otherwise */
|
|
398
395
|
type GetLogger = (request?: Request) => ActualLogger;
|
|
@@ -929,15 +926,7 @@ declare const extended: <S extends z.core.$ZodShape>(extra: S) => z.core.$ZodBra
|
|
|
929
926
|
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
930
927
|
} & S : ({
|
|
931
928
|
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
932
|
-
} extends infer
|
|
933
|
-
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
934
|
-
}[K]; } : never) & { [K_1 in keyof S]: S[K_1]; }) extends infer T ? { [k in keyof T]: ("raw" & keyof S extends never ? {
|
|
935
|
-
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
936
|
-
} & S : ({
|
|
937
|
-
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
938
|
-
} extends infer T_1 extends z.core.util.SomeObject ? { [K in keyof T_1 as K extends keyof S ? never : K]: {
|
|
939
|
-
raw: z.core.$ZodBranded<z.ZodCustom<Buffer<ArrayBufferLike>, Buffer<ArrayBufferLike>>, symbol>;
|
|
940
|
-
}[K]; } : never) & { [K_1 in keyof S]: S[K_1]; })[k]; } : never, z.core.$strip>, symbol>;
|
|
929
|
+
} extends infer T_1 extends z.core.util.SomeObject ? { [K in keyof T_1 as K extends keyof S ? never : K]: T_1[K]; } : never) & { [K_1 in keyof S]: S[K_1]; }) extends infer T ? { [k in keyof T]: T[k]; } : never, z.core.$strip>, symbol>;
|
|
941
930
|
declare function raw(): Base;
|
|
942
931
|
declare function raw<S extends z.core.$ZodShape>(extra: S): ReturnType<typeof extended<S>>;
|
|
943
932
|
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import*as Z from"ramda";import{globalRegistry as qo,z as W}from"zod";var we=Symbol.for("express-zod-api"),G=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var Fo=W.core.$constructor("$EZBrandCheck",(e,t)=>{W.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),$o=function(e){let t=qo.get(this)?.examples?.slice()||[];return t.push(e),this.meta({examples:t})},Zo=function(){return this.meta({deprecated:!0})},
|
|
2
|
-
Original error: ${e.handled.message}.`:""),{expose:cn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as dn}from"zod";var qt=class{},U=class extends qt{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){return this.#e}async execute({input:t,...r}){try{let o=await(this.#e||Ke).parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof dn.ZodError?new Q(o):o}}},ke=class extends U{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((i,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));i(r(n,s))};t(n,s,d)?.catch(d)})})}};var Ie=class{nest(t){return Object.assign(t,{"":this})}};var _e=class extends Ie{},ft=class e extends _e{#e;#t=pe.once(()=>{if(Mr.get(this.#e.outputSchema)?.examples?.length||!oe(this.#e.outputSchema,"object"))return;let t=zr(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();Mr.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Ir(this.#e.inputSchema);if(t){let r=G(t);if(r===ie)return"upload";if(r===H)return"raw";if(r===Ue)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=pe.pluck("security",this.#e.middlewares||[]);return pe.reject(pe.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Nr.ZodError?new $e(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof ke))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Nr.ZodError?new Q(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){ut({...t,error:new se(re(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=jt(t),i={},p={output:{},error:null},d=pt(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:re(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};var jr=(e,t)=>e&&t?e.and(t):e||t,Lr=(e,t)=>e?e.and(t):t;import{globalRegistry as Je,z as K}from"zod";var ve={positive:200,negative:400},Ae=Object.keys(ve);var Ft=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Se=class extends Ft{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Kt(this.#e,{variant:"positive",args:[t],statusCodes:[ve.positive],mimeTypes:[C.json]})}getNegativeResponse(){return Kt(this.#t,{variant:"negative",args:[],statusCodes:[ve.negative],mimeTypes:[C.json]})}},be=new Se({positive:e=>{let t=K.object({status:K.literal("success"),data:e}),{examples:r}=Je.get(e)||{};return r?.length&&Je.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:K.object({status:K.literal("error"),error:K.object({message:K.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=Ee(e);return De(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:xe(i)}})}n.status(ve.positive).json({status:"success",data:r})}}),$t=new Se({positive:e=>{let t=e instanceof K.ZodObject&&"items"in e.shape&&e.shape.items instanceof K.ZodArray?e.shape.items:K.array(K.any());if(Je.get(t)?.examples?.length)return t;let r=Je.get(e)?.examples?.filter(o=>E(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r?.length){let o=t.meta();Je.remove(t).add(t,{...o,examples:r})}return t},negative:K.string().example("Sample error message"),handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Ee(r);return De(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(xe(i))}if("items"in t&&Array.isArray(t.items))return void e.status(ve.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Re=class e{constructor(t){this.resultHandler=t}schema=void 0;middlewares=[];#e(t){let r=new e(this.resultHandler);return r.middlewares=this.middlewares.concat(t),r.schema=jr(this.schema,t.schema),r}addMiddleware(t){return this.#e(t instanceof U?t:new U(t))}use=this.addExpressMiddleware;addExpressMiddleware(...t){return this.#e(new ke(...t))}addOptions(t){return this.#e(new U({handler:t}))}build({input:t=Ke,output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,y=typeof o=="function"?o:w=>o&&`${o}${w==="head"?"__HEAD":""}`,g=typeof n=="string"?[n]:n||[],h=typeof s=="string"?[s]:s||[];return new ft({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:g,tags:h,methods:m,getOperationId:y,inputSchema:Lr(this.schema,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Ke,handler:async o=>(await t(o),{})})}},mn=new Re(be),ln=new Re($t);import Sn from"ansis";import{inspect as bn}from"node:util";import{performance as $r}from"node:perf_hooks";import{blue as un,green as fn,hex as yn,red as hn,cyanBright as gn}from"ansis";import*as Br from"ramda";var Zt={debug:un,info:fn,warn:yn("#FFA500"),error:hn,ctx:gn},yt={debug:10,info:20,warn:30,error:40},Hr=e=>E(e)&&Object.keys(yt).some(t=>t in e),Kr=e=>e in yt,qr=(e,t)=>yt[e]<yt[t],xn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),ze=Br.memoizeWith((e,t)=>`${e}${t}`,xn),Fr=e=>e<1e-6?ze("nanosecond",3).format(e/1e-6):e<.001?ze("nanosecond").format(e/1e-6):e<1?ze("microsecond").format(e/.001):e<1e3?ze("millisecond").format(e):e<6e4?ze("second",2).format(e/1e3):ze("minute",2).format(e/6e4);var Ve=class e{config;constructor({color:t=Sn.isSupported(),level:r=ue()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return bn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...i},color:p}=this.config;if(n==="silent"||qr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Zt.ctx(s):s),d.push(p?`${Zt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.format(o)),Object.keys(i).length>0&&d.push(this.format(i)),console.log(d.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})}get ctx(){return this.config.ctx}profile(t){let r=$r.now();return()=>{let o=$r.now()-r,{message:n,severity:s="debug",formatter:i=Fr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Zr from"ramda";var Ge=class e extends Ie{#e;constructor(t){super(),this.#e=t}get entries(){let t=Zr.filter(r=>!!r[1],Object.entries(this.#e));return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import Rn from"express";var We=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,Rn.static(...this.#e))}};import St from"express";import Hn from"node:http";import Kn from"node:https";var Ne=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ze(e)};import In from"http-errors";import{z as Dr}from"zod";import*as S from"ramda";var On=e=>e.type==="object",Tn=S.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return S.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties",{cause:{a:e,b:t}})}),Pn=S.pipe(Object.keys,S.without(["type","properties","required","examples","description","additionalProperties"]),S.isEmpty),Ur=S.pair(!0),Me=(e,t="coerce")=>{let r=[S.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&Pn(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(Ur,i.anyOf)),i.oneOf&&r.push(...S.map(Ur,i.oneOf)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=le(o.examples?.filter(E)||[],i.examples.filter(E),([p,d])=>S.mergeDeepRight(p,d))),!!On(i)&&(r.push([s,{examples:wn(i)}]),i.properties&&(o.properties=(t==="throw"?Tn:S.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),E(i.propertyNames))){let p=[];typeof i.propertyNames.const=="string"&&p.push(i.propertyNames.const),i.propertyNames.enum&&p.push(...i.propertyNames.enum.filter(c=>typeof c=="string"));let d={...Object(i.additionalProperties)};for(let c of p)o.properties[c]??=d;s||n.push(...p)}}return n.length&&(o.required=[...new Set(n)]),o},wn=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=E(o)?o:{};return le(t,n.map(S.objOf(r)),([s,i])=>({...s,...i}))},[]);var ht=class{constructor(t){this.logger=t}#e=new WeakSet;#t=new WeakMap;checkSchema(t,r){if(!this.#e.has(t)){for(let o of["input","output"]){let n=[Dr.toJSONSchema(t[`${o}Schema`],{unrepresentable:"any"})];for(;n.length>0;){let s=n.shift();s.type&&s.type!=="object"&&this.logger.warn(`Endpoint ${o} schema is not object-based`,r);for(let i of["allOf","oneOf","anyOf"])s[i]&&n.push(...s[i])}}if(t.requestType==="json"){let o=Ht(t.inputSchema,"input");o&&this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o}))}for(let o of Ae)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(C.json))continue;let i=Ht(s,"output");i&&this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:i}))}this.#e.add(t)}}checkPathParams(t,r,o){let n=this.#t.get(r);if(n?.paths.includes(t))return;let s=at(t);if(s.length===0)return;let i=n?.flat||Me(Dr.toJSONSchema(r.inputSchema,{unrepresentable:"any",io:"input"}));for(let p of s)p in i.properties||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:p}));n?n.paths.push(t):this.#t.set(r,{flat:i,paths:[t]})}};var gt=e=>(t,...r)=>{e(t,...r),t==="get"&&e("head",...r)},Cn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&de(t)?[r,t]:[e]},En=e=>e.trim().split("/").filter(Boolean).join("/"),_r=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Cn(r);return[[t||""].concat(En(n)||[]).join("/"),o,s]}),kn=(e,t)=>{throw new ge("Route with explicit method can only be assigned with Endpoint",e,t)},Jr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ge(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Ut=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ge("Route has a duplicate",e,t);r.add(o)},je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=_r(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof _e)if(p)Ut(p,s,n),Jr(p,s,i.methods),t(p,s,i);else{let{methods:d=["get"]}=i;for(let c of d)Ut(c,s,n),t(c,s,i)}else if(p&&kn(p,s),i instanceof We)r&&i.apply(s,r);else if(i instanceof Ge)for(let[d,c]of i.entries){let{methods:m}=c;Ut(d,s,n),Jr(d,s,m),t(d,s,c)}else o.unshift(..._r(i,s))}};import*as Vr from"ramda";var Gr=e=>e.sort((t,r)=>+de(r)-+de(t)||t.localeCompare(r)).join(", ").toUpperCase(),vn=e=>({method:t},r,o)=>{let n=Gr(e);r.set({Allow:n});let s=In(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},An=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Gr(e),"Access-Control-Allow-Headers":"content-type"}),Dt=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new ht(t()),i=new Map;je({routing:o,onEndpoint:(c,m,y)=>{ue()||(s?.checkSchema(y,{path:m,method:c}),s?.checkPathParams(m,y,{method:c}));let g=n?.[y.requestType]||[],h=Vr.pair(g,y);i.has(m)||i.set(m,new Map(r.cors?[["options",h]]:[])),i.get(m)?.set(c,h)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let y=Array.from(m.keys());y.includes("get")&&y.push("head");for(let[g,[h,w]]of m){let I=h.slice().concat(async(M,b)=>{let v=t(M);return w.execute({request:M,response:b,logger:v,config:r})});r.cors&&I.unshift(async(M,b,v)=>{let A=t(M),B=An(y),z=typeof r.cors=="function"?await r.cors({request:M,endpoint:w,logger:A,defaultHeaders:B}):B;b.set(z),v()}),e[g](c,...I)}r.wrongMethodBehavior!==404&&d.set(c,vn(y))}for(let[c,m]of d)e.all(c,m)};import Nn from"http-errors";import{setInterval as zn}from"node:timers/promises";var Wr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Yr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Qr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Xr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),eo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var to=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Wr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):s(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",Xr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Qr(c)||Yr(c))&&i(c);for await(let c of zn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(eo))};return{sockets:n,shutdown:()=>o??=d()}};var ro=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:re(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),oo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Nn(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){ut({response:o,logger:s,error:new se(re(i),n)})}},Mn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},jn=e=>({log:e.debug.bind(e)}),no=async({getLogger:e,config:t})=>{let r=await Ne("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},i=[];return i.push(async(p,d,c)=>{let m=e(p);return await n?.({request:p,logger:m}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:jn(m)})(p,d,c)}),o&&i.push(Mn(o)),i},so=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},io=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let i=await t?.({request:o,parent:e})||e;r?.(o,i),o.res&&(o.res.locals[we]={logger:i}),s()},ao=e=>t=>t?.res?.locals[we]?.logger||e,po=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
1
|
+
import*as Z from"ramda";import{globalRegistry as qo,z as W}from"zod";var we=Symbol.for("express-zod-api"),G=e=>{let{brand:t}=e._zod.bag||{};if(typeof t=="symbol"||typeof t=="string"||typeof t=="number")return t};var Fo=W.core.$constructor("$EZBrandCheck",(e,t)=>{W.core.$ZodCheck.init(e,t),e._zod.onattach.push(r=>r._zod.bag.brand=t.brand),e._zod.check=()=>{}}),$o=function(e){let t=qo.get(this)?.examples?.slice()||[];return t.push(e),this.meta({examples:t})},Zo=function(){return this.meta({deprecated:!0})},Do=function(e){return this.meta({default:e})},Uo=function(e){return this.check(new Fo({brand:e,check:"$EZBrandCheck"}))},_o=function(e){let t=typeof e=="function"?e:Z.renameKeys(Z.reject(Z.isNil,e)),r=t(Z.map(Z.invoker(0,"clone"),this._zod.def.shape)),n=(this._zod.def.catchall instanceof W.ZodUnknown?W.looseObject:W.object)(r);return this.transform(t).pipe(n)};if(!(we in globalThis)){globalThis[we]=!0;for(let e of Object.keys(W)){if(!e.startsWith("Zod")||/(Success|Error|Function)$/.test(e))continue;let t=W[e];typeof t=="function"&&Object.defineProperties(t.prototype,{example:{value:$o,writable:!1},deprecated:{value:Zo,writable:!1},brand:{set(){},get(){return Uo.bind(this)}}})}Object.defineProperty(W.ZodDefault.prototype,"label",{value:Do,writable:!1}),Object.defineProperty(W.ZodObject.prototype,"remap",{value:_o,writable:!1})}function Jo(e){return e}import*as j from"ramda";import{z as Ce}from"zod";var C={json:"application/json",upload:"multipart/form-data",raw:"application/octet-stream",sse:"text/event-stream",form:"application/x-www-form-urlencoded"};var gr=["get","post","put","delete","patch"],xr=[...gr,"head"],de=e=>gr.includes(e);var Ke=Ce.object({}),Mt=/:([A-Za-z0-9_]+)/g,at=e=>e.match(Mt)?.map(t=>t.slice(1))||[],Vo=e=>{let r=(e.header("content-type")||"").toLowerCase().startsWith(C.upload);return"files"in e&&r},Go={get:["query","params"],post:["body","params","files"],put:["body","params"],patch:["body","params"],delete:["query","params"]},Wo=["body","query","params"],jt=e=>e.method.toLowerCase(),Lt=(e,t={})=>{if(e==="options")return[];let r=e==="head"?"get":de(e)?e:void 0;return(r?t[r]||Go[r]:void 0)||Wo},pt=(e,t={})=>{let r=jt(e);return Lt(r,t).filter(o=>o==="files"?Vo(e):!0).reduce((o,n)=>Object.assign(o,e[n]),{})},te=e=>e instanceof Error?e:e instanceof Ce.ZodError?new Ce.ZodRealError(e.issues):new Error(String(e)),me=e=>e instanceof Ce.ZodError?e.issues.map(({path:t,message:r})=>`${t.length?`${Ce.core.toDotPath(t)}: `:""}${r}`).join("; "):e.message,re=(e,t)=>E(e)&&"_zod"in e&&(t?j.path(["_zod","def","type"],e)===t:!0),le=(e,t,r)=>e.length&&t.length?j.xprod(e,t).map(r):e.concat(t),Bt=e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),oe=(...e)=>{let t=j.chain(o=>o.split(/[^A-Z0-9]/gi),e);return j.chain(o=>o.replaceAll(/[A-Z]+/g,n=>`/${n}`).split("/"),t).map(Bt).join("")},ct=j.tryCatch((e,t)=>typeof Ce.parse(e,t),j.always(void 0)),E=e=>typeof e=="object"&&e!==null,ue=j.memoizeWith(()=>"static",()=>process.env.NODE_ENV==="production"),dt=(e,t)=>!!t&&e!=="head";import*as ae from"ramda";import{z as Nr,globalRegistry as Mr}from"zod";import*as ie from"ramda";import{z as Cr}from"zod";import{z as Yo}from"zod";var fe=Symbol("Buffer"),mt=()=>Yo.custom(e=>Buffer.isBuffer(e),{error:"Expected Buffer"}).brand(fe);import{z as qe}from"zod";var ye=Symbol("DateIn"),Sr=({examples:e,...t}={})=>qe.union([qe.iso.date(),qe.iso.datetime(),qe.iso.datetime({local:!0})]).meta({examples:e}).transform(o=>new Date(o)).pipe(qe.date()).brand(ye).meta(t);import{z as Qo}from"zod";var he=Symbol("DateOut"),br=(e={})=>Qo.date().transform(t=>t.toISOString()).brand(he).meta(e);import{z as Xo}from"zod";var ge=class extends Error{name="RoutingError";cause;constructor(t,r,o){super(t),this.cause={method:r,path:o}}},Y=class extends Error{name="DocumentationError";cause;constructor(t,{method:r,path:o,isResponse:n}){super(t),this.cause=`${n?"Response":"Input"} schema of an Endpoint assigned to ${r.toUpperCase()} method of ${o} path.`}},Fe=class extends Error{name="IOSchemaError"},lt=class extends Fe{constructor(r){super("Found",{cause:r});this.cause=r}name="DeepCheckError"},$e=class extends Fe{constructor(r){let o=new Xo.ZodError(r.issues.map(({path:n,...s})=>({...s,path:["output",...n]})));super(me(o),{cause:r});this.cause=r}name="OutputValidationError"},Q=class extends Fe{constructor(r){super(me(r),{cause:r});this.cause=r}name="InputValidationError"},ne=class extends Error{constructor(r,o){super(me(r),{cause:r});this.cause=r;this.handled=o}name="ResultHandlerError"},Ze=class extends Error{name="MissingPeerError";constructor(t){super(`Missing peer dependency: ${t}. Please install it to use the feature.`)}};import{z as Rr}from"zod";var De=Symbol("Form"),Or=e=>(e instanceof Rr.ZodObject?e:Rr.object(e)).brand(De);import{z as en}from"zod";var se=Symbol("Upload"),Tr=()=>en.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",{error:({input:e})=>({message:`Expected file upload, received ${typeof e}`})}).brand(se);import{z as tn}from"zod";var H=Symbol("Raw"),Pr=tn.object({raw:mt()}),rn=e=>Pr.extend(e).brand(H);function wr(e){return e?rn(e):Pr.brand(H)}var Er=(e,{io:t,condition:r})=>ie.tryCatch(()=>{Cr.toJSONSchema(e,{io:t,unrepresentable:"any",override:({zodSchema:o})=>{if(r(o))throw new lt(o)}})},o=>o.cause)(),kr=(e,{io:t})=>{let o=[Cr.toJSONSchema(e,{io:t,unrepresentable:"any"})];for(;o.length;){let n=o.shift();if(ie.is(Object,n)){if(n.$ref==="#")return!0;o.push(...ie.values(n))}ie.is(Array,n)&&o.push(...ie.values(n))}return!1},Ir=e=>Er(e,{condition:t=>{let r=G(t);return typeof r=="symbol"&&[se,H,De].includes(r)},io:"input"}),on=["nan","symbol","map","set","bigint","void","promise","never"],Ht=(e,t)=>Er(e,{io:t,condition:r=>{let o=G(r),{type:n}=r._zod.def;return!!(on.includes(n)||o===fe||t==="input"&&(n==="date"||o===he)||t==="output"&&(o===ye||o===H||o===se))}});import pn,{isHttpError as cn}from"http-errors";import vr,{isHttpError as nn}from"http-errors";import*as Ar from"ramda";import{globalRegistry as sn,z as an}from"zod";var Kt=(e,{variant:t,args:r,...o})=>{if(typeof e=="function"&&(e=e(...r)),e instanceof an.ZodType)return[{schema:e,...o}];if(Array.isArray(e)&&!e.length){let n=new Error(`At least one ${t} response schema required.`);throw new ne(n)}return(Array.isArray(e)?e:[e]).map(({schema:n,statusCode:s,mimeType:i})=>({schema:n,statusCodes:typeof s=="number"?[s]:s||o.statusCodes,mimeTypes:typeof i=="string"?[i]:i===void 0?o.mimeTypes:i}))},Ue=(e,t,{url:r},o)=>!e.expose&&t.error("Server side error",{error:e,url:r,payload:o}),Ee=e=>nn(e)?e:vr(e instanceof Q?400:500,me(e),{cause:e.cause||e}),xe=e=>ue()&&!e.expose?vr(e.statusCode).message:e.message,zr=e=>Object.entries(e._zod.def.shape).reduce((t,[r,o])=>{let{examples:n=[]}=sn.get(o)||{};return le(t,n.map(Ar.objOf(r)),([s,i])=>({...s,...i}))},[]);var ut=({error:e,logger:t,response:r})=>{t.error("Result handler failure",e);let o=xe(pn(500,`An error occurred while serving the result: ${e.message}.`+(e.handled?`
|
|
2
|
+
Original error: ${e.handled.message}.`:""),{expose:cn(e.cause)?e.cause.expose:!1}));r.status(500).type("text/plain").end(o)};import{z as dn}from"zod";var qt=class{},D=class extends qt{#e;#t;#r;constructor({input:t,security:r,handler:o}){super(),this.#e=t,this.#t=r,this.#r=o}get security(){return this.#t}get schema(){return this.#e}async execute({input:t,...r}){try{let o=await(this.#e||Ke).parseAsync(t);return this.#r({...r,input:o})}catch(o){throw o instanceof dn.ZodError?new Q(o):o}}},ke=class extends D{constructor(t,{provider:r=()=>({}),transformer:o=n=>n}={}){super({handler:async({request:n,response:s})=>new Promise((i,p)=>{let d=c=>{if(c&&c instanceof Error)return p(o(c));i(r(n,s))};t(n,s,d)?.catch(d)})})}};var Ie=class{nest(t){return Object.assign(t,{"":this})}};var _e=class extends Ie{},ft=class e extends _e{#e;#t=ae.once(()=>{if(Mr.get(this.#e.outputSchema)?.examples?.length||!re(this.#e.outputSchema,"object"))return;let t=zr(this.#e.outputSchema);if(!t.length)return;let r=this.#e.outputSchema.meta();Mr.remove(this.#e.outputSchema).add(this.#e.outputSchema,{...r,examples:t})});constructor(t){super(),this.#e=t}#r(t){return new e({...this.#e,...t})}deprecated(){return this.#r({deprecated:!0})}get isDeprecated(){return this.#e.deprecated||!1}get description(){return this.#e.description}get shortDescription(){return this.#e.shortDescription}get methods(){return Object.freeze(this.#e.methods)}get inputSchema(){return this.#e.inputSchema}get outputSchema(){return this.#t(),this.#e.outputSchema}get requestType(){let t=Ir(this.#e.inputSchema);if(t){let r=G(t);if(r===se)return"upload";if(r===H)return"raw";if(r===De)return"form"}return"json"}getResponses(t){return t==="positive"&&this.#t(),Object.freeze(t==="negative"?this.#e.resultHandler.getNegativeResponse():this.#e.resultHandler.getPositiveResponse(this.#e.outputSchema))}get security(){let t=ae.pluck("security",this.#e.middlewares||[]);return ae.reject(ae.isNil,t)}get scopes(){return Object.freeze(this.#e.scopes||[])}get tags(){return Object.freeze(this.#e.tags||[])}getOperationId(t){return this.#e.getOperationId?.(t)}async#o(t){try{return await this.#e.outputSchema.parseAsync(t)}catch(r){throw r instanceof Nr.ZodError?new $e(r):r}}async#n({method:t,logger:r,options:o,response:n,...s}){for(let i of this.#e.middlewares||[])if(!(t==="options"&&!(i instanceof ke))&&(Object.assign(o,await i.execute({...s,options:o,response:n,logger:r})),n.writableEnded)){r.warn("A middleware has closed the stream. Accumulated options:",o);break}}async#s({input:t,...r}){let o;try{o=await this.#e.inputSchema.parseAsync(t)}catch(n){throw n instanceof Nr.ZodError?new Q(n):n}return this.#e.handler({...r,input:o})}async#i(t){try{await this.#e.resultHandler.execute(t)}catch(r){ut({...t,error:new ne(te(r),t.error||void 0)})}}async execute({request:t,response:r,logger:o,config:n}){let s=jt(t),i={},p={output:{},error:null},d=pt(t,n.inputSources);try{if(await this.#n({method:s,input:d,request:t,response:r,logger:o,options:i}),r.writableEnded)return;if(s==="options")return void r.status(200).end();p={output:await this.#o(await this.#s({input:d,logger:o,options:i})),error:null}}catch(c){p={output:null,error:te(c)}}await this.#i({...p,input:d,request:t,response:r,logger:o,options:i})}};var jr=(e,t)=>e&&t?e.and(t):e||t,Lr=(e,t)=>e?e.and(t):t;import{globalRegistry as Je,z as K}from"zod";var ve={positive:200,negative:400},Ae=Object.keys(ve);var Ft=class{#e;constructor(t){this.#e=t}execute(...t){return this.#e(...t)}},Se=class extends Ft{#e;#t;constructor(t){super(t.handler),this.#e=t.positive,this.#t=t.negative}getPositiveResponse(t){return Kt(this.#e,{variant:"positive",args:[t],statusCodes:[ve.positive],mimeTypes:[C.json]})}getNegativeResponse(){return Kt(this.#t,{variant:"negative",args:[],statusCodes:[ve.negative],mimeTypes:[C.json]})}},be=new Se({positive:e=>{let t=K.object({status:K.literal("success"),data:e}),{examples:r}=Je.get(e)||{};return r?.length&&Je.add(t,{examples:r.map(o=>({status:"success",data:o}))}),t},negative:K.object({status:K.literal("error"),error:K.object({message:K.string()})}).example({status:"error",error:{message:"Sample error message"}}),handler:({error:e,input:t,output:r,request:o,response:n,logger:s})=>{if(e){let i=Ee(e);return Ue(i,s,o,t),void n.status(i.statusCode).set(i.headers).json({status:"error",error:{message:xe(i)}})}n.status(ve.positive).json({status:"success",data:r})}}),$t=new Se({positive:e=>{let t=e instanceof K.ZodObject&&"items"in e.shape&&e.shape.items instanceof K.ZodArray?e.shape.items:K.array(K.any());if(Je.get(t)?.examples?.length)return t;let r=Je.get(e)?.examples?.filter(o=>E(o)&&"items"in o&&Array.isArray(o.items)).map(o=>o.items);if(r?.length){let o=t.meta();Je.remove(t).add(t,{...o,examples:r})}return t},negative:{schema:K.string().example("Sample error message"),mimeType:"text/plain"},handler:({response:e,output:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Ee(r);return Ue(i,o,n,s),void e.status(i.statusCode).type("text/plain").send(xe(i))}if("items"in t&&Array.isArray(t.items))return void e.status(ve.positive).json(t.items);throw new Error("Property 'items' is missing in the endpoint output")}});var Re=class e{constructor(t){this.resultHandler=t}schema=void 0;middlewares=[];#e(t){let r=new e(this.resultHandler);return r.middlewares=this.middlewares.concat(t),r.schema=jr(this.schema,t.schema),r}addMiddleware(t){return this.#e(t instanceof D?t:new D(t))}use=this.addExpressMiddleware;addExpressMiddleware(...t){return this.#e(new ke(...t))}addOptions(t){return this.#e(new D({handler:t}))}build({input:t=Ke,output:r,operationId:o,scope:n,tag:s,method:i,...p}){let{middlewares:d,resultHandler:c}=this,m=typeof i=="string"?[i]:i,y=typeof o=="function"?o:w=>o&&`${o}${w==="head"?"__HEAD":""}`,g=typeof n=="string"?[n]:n||[],h=typeof s=="string"?[s]:s||[];return new ft({...p,middlewares:d,outputSchema:r,resultHandler:c,scopes:g,tags:h,methods:m,getOperationId:y,inputSchema:Lr(this.schema,t)})}buildVoid({handler:t,...r}){return this.build({...r,output:Ke,handler:async o=>(await t(o),{})})}},mn=new Re(be),ln=new Re($t);import Sn from"ansis";import{inspect as bn}from"node:util";import{performance as $r}from"node:perf_hooks";import{blue as un,green as fn,hex as yn,red as hn,cyanBright as gn}from"ansis";import*as Br from"ramda";var Zt={debug:un,info:fn,warn:yn("#FFA500"),error:hn,ctx:gn},yt={debug:10,info:20,warn:30,error:40},Hr=e=>E(e)&&Object.keys(yt).some(t=>t in e),Kr=e=>e in yt,qr=(e,t)=>yt[e]<yt[t],xn=(e,t=0)=>Intl.NumberFormat(void 0,{useGrouping:!1,minimumFractionDigits:0,maximumFractionDigits:t,style:"unit",unitDisplay:"long",unit:e}),ze=Br.memoizeWith((e,t)=>`${e}${t}`,xn),Fr=e=>e<1e-6?ze("nanosecond",3).format(e/1e-6):e<.001?ze("nanosecond").format(e/1e-6):e<1?ze("microsecond").format(e/.001):e<1e3?ze("millisecond").format(e):e<6e4?ze("second",2).format(e/1e3):ze("minute",2).format(e/6e4);var Ve=class e{config;constructor({color:t=Sn.isSupported(),level:r=ue()?"warn":"debug",depth:o=2,ctx:n={}}={}){this.config={color:t,level:r,depth:o,ctx:n}}format(t){let{depth:r,color:o,level:n}=this.config;return bn(t,{depth:r,colors:o,breakLength:n==="debug"?80:1/0,compact:n==="debug"?3:!0})}print(t,r,o){let{level:n,ctx:{requestId:s,...i},color:p}=this.config;if(n==="silent"||qr(t,n))return;let d=[new Date().toISOString()];s&&d.push(p?Zt.ctx(s):s),d.push(p?`${Zt[t](t)}:`:`${t}:`,r),o!==void 0&&d.push(this.format(o)),Object.keys(i).length>0&&d.push(this.format(i)),console.log(d.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})}get ctx(){return this.config.ctx}profile(t){let r=$r.now();return()=>{let o=$r.now()-r,{message:n,severity:s="debug",formatter:i=Fr}=typeof t=="object"?t:{message:t};this.print(typeof s=="function"?s(o):s,n,i(o))}}};import*as Zr from"ramda";var Ge=class e extends Ie{#e;constructor(t){super(),this.#e=t}get entries(){let t=Zr.filter(r=>!!r[1],Object.entries(this.#e));return Object.freeze(t)}deprecated(){let t=Object.entries(this.#e).reduce((r,[o,n])=>Object.assign(r,{[o]:n.deprecated()}),{});return new e(t)}};import Rn from"express";var We=class{#e;constructor(...t){this.#e=t}apply(t,r){return r(t,Rn.static(...this.#e))}};import St from"express";import Hn from"node:http";import Kn from"node:https";var Ne=async(e,t="default")=>{try{return(await import(e))[t]}catch{}throw new Ze(e)};import In from"http-errors";import{z as Ur}from"zod";import*as S from"ramda";var On=e=>e.type==="object",Tn=S.mergeDeepWith((e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return S.concat(e,t);if(e===t)return t;throw new Error("Can not flatten properties",{cause:{a:e,b:t}})}),Pn=S.pipe(Object.keys,S.without(["type","properties","required","examples","description","additionalProperties"]),S.isEmpty),Dr=S.pair(!0),Me=(e,t="coerce")=>{let r=[S.pair(!1,e)],o={type:"object",properties:{}},n=[];for(;r.length;){let[s,i]=r.shift();if(i.description&&(o.description??=i.description),i.allOf&&r.push(...i.allOf.map(p=>{if(t==="throw"&&!(p.type==="object"&&Pn(p)))throw new Error("Can not merge");return S.pair(s,p)})),i.anyOf&&r.push(...S.map(Dr,i.anyOf)),i.oneOf&&r.push(...S.map(Dr,i.oneOf)),i.examples?.length&&(s?o.examples=S.concat(o.examples||[],i.examples):o.examples=le(o.examples?.filter(E)||[],i.examples.filter(E),([p,d])=>S.mergeDeepRight(p,d))),!!On(i)&&(r.push([s,{examples:wn(i)}]),i.properties&&(o.properties=(t==="throw"?Tn:S.mergeDeepRight)(o.properties,i.properties),!s&&i.required&&n.push(...i.required)),E(i.propertyNames))){let p=[];typeof i.propertyNames.const=="string"&&p.push(i.propertyNames.const),i.propertyNames.enum&&p.push(...i.propertyNames.enum.filter(c=>typeof c=="string"));let d={...Object(i.additionalProperties)};for(let c of p)o.properties[c]??=d;s||n.push(...p)}}return n.length&&(o.required=[...new Set(n)]),o},wn=e=>Object.entries(e.properties||{}).reduce((t,[r,o])=>{let{examples:n=[]}=E(o)?o:{};return le(t,n.map(S.objOf(r)),([s,i])=>({...s,...i}))},[]);var ht=class{constructor(t){this.logger=t}#e=new WeakSet;#t=new WeakMap;checkSchema(t,r){if(!this.#e.has(t)){for(let o of["input","output"]){let n=[Ur.toJSONSchema(t[`${o}Schema`],{unrepresentable:"any"})];for(;n.length>0;){let s=n.shift();s.type&&s.type!=="object"&&this.logger.warn(`Endpoint ${o} schema is not object-based`,r);for(let i of["allOf","oneOf","anyOf"])s[i]&&n.push(...s[i])}}if(t.requestType==="json"){let o=Ht(t.inputSchema,"input");o&&this.logger.warn("The final input schema of the endpoint contains an unsupported JSON payload type.",Object.assign(r,{reason:o}))}for(let o of Ae)for(let{mimeTypes:n,schema:s}of t.getResponses(o)){if(!n?.includes(C.json))continue;let i=Ht(s,"output");i&&this.logger.warn(`The final ${o} response schema of the endpoint contains an unsupported JSON payload type.`,Object.assign(r,{reason:i}))}this.#e.add(t)}}checkPathParams(t,r,o){let n=this.#t.get(r);if(n?.paths.includes(t))return;let s=at(t);if(s.length===0)return;let i=n?.flat||Me(Ur.toJSONSchema(r.inputSchema,{unrepresentable:"any",io:"input"}));for(let p of s)p in i.properties||this.logger.warn("The input schema of the endpoint is most likely missing the parameter of the path it's assigned to.",Object.assign(o,{path:t,param:p}));n?n.paths.push(t):this.#t.set(r,{flat:i,paths:[t]})}};var gt=e=>(t,...r)=>{e(t,...r),t==="get"&&e("head",...r)},Cn=e=>{let[t,r]=e.trim().split(/ (.+)/,2);return r&&de(t)?[r,t]:[e]},En=e=>e.trim().split("/").filter(Boolean).join("/"),_r=(e,t)=>Object.entries(e).map(([r,o])=>{let[n,s]=Cn(r);return[[t||""].concat(En(n)||[]).join("/"),o,s]}),kn=(e,t)=>{throw new ge("Route with explicit method can only be assigned with Endpoint",e,t)},Jr=(e,t,r)=>{if(!(!r||r.includes(e)))throw new ge(`Method ${e} is not supported by the assigned Endpoint.`,e,t)},Dt=(e,t,r)=>{let o=`${e} ${t}`;if(r.has(o))throw new ge("Route has a duplicate",e,t);r.add(o)},je=({routing:e,onEndpoint:t,onStatic:r})=>{let o=_r(e),n=new Set;for(;o.length;){let[s,i,p]=o.shift();if(i instanceof _e)if(p)Dt(p,s,n),Jr(p,s,i.methods),t(p,s,i);else{let{methods:d=["get"]}=i;for(let c of d)Dt(c,s,n),t(c,s,i)}else if(p&&kn(p,s),i instanceof We)r&&i.apply(s,r);else if(i instanceof Ge)for(let[d,c]of i.entries){let{methods:m}=c;Dt(d,s,n),Jr(d,s,m),t(d,s,c)}else o.unshift(..._r(i,s))}};import*as Vr from"ramda";var Gr=e=>e.sort((t,r)=>+de(r)-+de(t)||t.localeCompare(r)).join(", ").toUpperCase(),vn=e=>({method:t},r,o)=>{let n=Gr(e);r.set({Allow:n});let s=In(405,`${t} is not allowed`,{headers:{Allow:n}});o(s)},An=e=>({"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":Gr(e),"Access-Control-Allow-Headers":"content-type"}),Ut=({app:e,getLogger:t,config:r,routing:o,parsers:n})=>{let s=ue()?void 0:new ht(t()),i=new Map;je({routing:o,onEndpoint:(c,m,y)=>{ue()||(s?.checkSchema(y,{path:m,method:c}),s?.checkPathParams(m,y,{method:c}));let g=n?.[y.requestType]||[],h=Vr.pair(g,y);i.has(m)||i.set(m,new Map(r.cors?[["options",h]]:[])),i.get(m)?.set(c,h)},onStatic:e.use.bind(e)}),s=void 0;let d=new Map;for(let[c,m]of i){let y=Array.from(m.keys());y.includes("get")&&y.push("head");for(let[g,[h,w]]of m){let I=h.slice().concat(async(M,b)=>{let v=t(M);return w.execute({request:M,response:b,logger:v,config:r})});r.cors&&I.unshift(async(M,b,v)=>{let A=t(M),B=An(y),z=typeof r.cors=="function"?await r.cors({request:M,endpoint:w,logger:A,defaultHeaders:B}):B;b.set(z),v()}),e[g](c,...I)}r.wrongMethodBehavior!==404&&d.set(c,vn(y))}for(let[c,m]of d)e.all(c,m)};import Nn from"http-errors";import{setInterval as zn}from"node:timers/promises";var Wr=e=>"_httpMessage"in e&&typeof e._httpMessage=="object"&&e._httpMessage!==null&&"headersSent"in e._httpMessage&&typeof e._httpMessage.headersSent=="boolean"&&"setHeader"in e._httpMessage&&typeof e._httpMessage.setHeader=="function",Yr=e=>"server"in e&&typeof e.server=="object"&&e.server!==null&&"close"in e.server&&typeof e.server.close=="function",Qr=e=>"encrypted"in e&&typeof e.encrypted=="boolean"&&e.encrypted,Xr=({},e)=>void(!e.headersSent&&e.setHeader("connection","close")),eo=e=>new Promise((t,r)=>void e.close(o=>o?r(o):t()));var to=(e,{timeout:t=1e3,logger:r}={})=>{let o,n=new Set,s=c=>void n.delete(c.destroy()),i=c=>void(Wr(c)?!c._httpMessage.headersSent&&c._httpMessage.setHeader("connection","close"):s(c)),p=c=>void(o?c.destroy():n.add(c.once("close",()=>void n.delete(c))));for(let c of e)for(let m of["connection","secureConnection"])c.on(m,p);let d=async()=>{for(let c of e)c.on("request",Xr);r?.info("Graceful shutdown",{sockets:n.size,timeout:t});for(let c of n)(Qr(c)||Yr(c))&&i(c);for await(let c of zn(10,Date.now()))if(n.size===0||Date.now()-c>=t)break;for(let c of n)s(c);return Promise.allSettled(e.map(eo))};return{sockets:n,shutdown:()=>o??=d()}};var ro=({errorHandler:e,getLogger:t})=>async(r,o,n,s)=>r?e.execute({error:te(r),request:o,response:n,input:null,output:null,options:{},logger:t(o)}):s(),oo=({errorHandler:e,getLogger:t})=>async(r,o)=>{let n=Nn(404,`Can not ${r.method} ${r.path}`),s=t(r);try{await e.execute({request:r,response:o,logger:s,error:n,input:null,output:null,options:{}})}catch(i){ut({response:o,logger:s,error:new ne(te(i),n)})}},Mn=e=>(t,{},r)=>{if(Object.values(t?.files||[]).flat().find(({truncated:n})=>n))return r(e);r()},jn=e=>({log:e.debug.bind(e)}),no=async({getLogger:e,config:t})=>{let r=await Ne("express-fileupload"),{limitError:o,beforeUpload:n,...s}={...typeof t.upload=="object"&&t.upload},i=[];return i.push(async(p,d,c)=>{let m=e(p);return await n?.({request:p,logger:m}),r({debug:!0,...s,abortOnLimit:!1,parseNested:!0,logger:jn(m)})(p,d,c)}),o&&i.push(Mn(o)),i},so=(e,{},t)=>{Buffer.isBuffer(e.body)&&(e.body={raw:e.body}),t()},io=({logger:e,config:{childLoggerProvider:t,accessLogger:r=({method:o,path:n},s)=>s.debug(`${o}: ${n}`)}})=>async(o,n,s)=>{let i=await t?.({request:o,parent:e})||e;r?.(o,i),o.res&&(o.res.locals[we]={logger:i}),s()},ao=e=>t=>t?.res?.locals[we]?.logger||e,po=e=>process.on("deprecation",({message:t,namespace:r,name:o,stack:n})=>e.warn(`${o} (${r}): ${t}`,n.split(`
|
|
3
3
|
`).slice(1))),co=({servers:e,logger:t,options:{timeout:r,beforeExit:o,events:n=["SIGINT","SIGTERM"]}})=>{let s=to(e,{logger:t,timeout:r}),i=async()=>{await s.shutdown(),await o?.(),process.exit()};for(let p of n)process.on(p,i)};import{gray as Ln,hex as mo,italic as xt,whiteBright as Bn}from"ansis";var lo=e=>{if(e.columns<132)return;let t=xt("Proudly supports transgender community.".padStart(109)),r=xt("Start your API server with I/O schema validation and custom middlewares in minutes.".padStart(109)),o=xt("Thank you for choosing Express Zod API for your project.".padStart(132)),n=xt("for Sara".padEnd(20)),s=mo("#F5A9B8"),i=mo("#5BCEFA"),p=new Array(14).fill(i,1,3).fill(s,3,5).fill(Bn,5,7).fill(s,7,9).fill(i,9,12).fill(Ln,12,13),d=`
|
|
4
4
|
8888888888 8888888888P 888 d8888 8888888b. 8888888
|
|
5
5
|
888 d88P 888 d88888 888 Y88b 888
|
|
@@ -15,9 +15,9 @@ ${n}888${r}
|
|
|
15
15
|
${o}
|
|
16
16
|
`;e.write(d.split(`
|
|
17
17
|
`).map((c,m)=>p[m]?p[m](c):c).join(`
|
|
18
|
-
`))};var uo=e=>{e.startupLogo!==!1&&lo(process.stdout);let t=e.errorHandler||be,r=Hr(e.logger)?e.logger:new Ve(e.logger);r.debug("Running",{build:"v25.0.0-beta.6",env:process.env.NODE_ENV||"development"}),po(r);let o=io({logger:r,config:e}),s={getLogger:ao(r),errorHandler:t},i=oo(s),p=ro(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},qn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=uo(e);return Dt({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Fn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=uo(e),p=St().disable("x-powered-by").use(i);if(e.compression){let g=await Ne("compression");p.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||St.json()],raw:[e.rawParser||St.raw(),so],form:[e.formParser||St.urlencoded()],upload:e.upload?await no({config:e,getLogger:o}):[]};Dt({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(g,h)=>()=>g.listen(h,()=>r.info("Listening",h)),y=[];if(e.http){let g=Hn.createServer(p);c.push(g),y.push(m(g,e.http.listen))}if(e.https){let g=Kn.createServer(e.https.options,p);c.push(g),y.push(m(g,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&co({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:y.map(g=>g())}};import{OpenApiBuilder as ms}from"openapi3-ts/oas31";import*as Ao from"ramda";import*as R from"ramda";var fo=e=>E(e)&&"or"in e,yo=e=>E(e)&&"and"in e,_t=e=>!yo(e)&&!fo(e),ho=e=>{let t=R.filter(_t,e),r=R.chain(R.prop("and"),R.filter(yo,e)),[o,n]=R.partition(_t,r),s=R.concat(t,o),i=R.filter(fo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>le(d,R.map(m=>_t(m)?[m]:m.and,c),([m,y])=>R.concat(m,y)),R.reject(R.isEmpty,[s]))};import{isReferenceObject as bo,isSchemaObject as bt}from"openapi3-ts/oas31";import*as l from"ramda";import{z as xo}from"zod";var go=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var So=50,Ro="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Zn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Oo=e=>e.replace(Mt,t=>`{${t.slice(1)}}`),Un=({},e)=>{if(e.isResponse)throw new Y("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Dn=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),_n=({zodSchema:e,jsonSchema:t})=>{if(!oe(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Jn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Me(e,"throw")},(e,{jsonSchema:t})=>t),Vn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:es(t.type)})},Ye=e=>e,Gn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new Y("Please use ez.dateOut() for output.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Ro}};return e?.length&&(o.examples=e),o},Wn=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new Y("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ro}};return e?.length&&(o.examples=e),o},Yn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Qn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Xn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Zn?.[t]},es=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],ts=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!oe(o,"transform"))return t;let s=Ye(Gt(n,{ctx:r}));if(bt(s))if(r.isResponse){let i=ct(o,Xn(s));if(i&&["number","string","boolean"].includes(i))return{...t,type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},rs=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!E(t.properties.raw)?e:t.properties.raw},Jt=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,os=(e,t)=>t?.includes(e)||e.startsWith("x-")||go.includes(e),To=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=Me(r),m=at(e),y=o.includes("query"),g=o.includes("params"),h=o.includes("headers"),w=b=>g&&m.includes(b),I=l.chain(l.filter(b=>b.type==="header"),p??[]).map(({name:b})=>b),M=b=>h&&(i?.(b,t,e)??os(b,I));return Object.entries(c.properties).reduce((b,[v,A])=>{if(!E(A))return b;let B=w(v)?"path":M(v)?"header":y?"query":void 0;if(!B)return b;let z=Ye(A),X=s==="components"?n(A.id||JSON.stringify(A),z,ne(d,v)):z;return b.concat({name:v,in:B,deprecated:A.deprecated,required:c.required?.includes(v)||!1,description:z.description||d,schema:X,examples:Jt(bt(z)&&z.examples?.length?z.examples:l.pluck(v,c.examples?.filter(l.both(E,l.has(v)))||[]))})},[])},Vt={nullable:Vn,union:_n,bigint:Yn,intersection:Jn,tuple:Qn,pipe:ts,[ye]:Gn,[he]:Wn,[ie]:Un,[H]:rs,[fe]:Dn},ns=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(bo(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,Ye(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},Gt=(e,{ctx:t,rules:r=Vt})=>{let{$defs:o={},properties:n={}}=xo.toJSONSchema(xo.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=G(s.zodSchema),p=r[i&&i in r?i:s.zodSchema._zod.def.type];if(p){let d={...p(s,t)};for(let c in s.jsonSchema)delete s.jsonSchema[c];Object.assign(s.jsonSchema,d)}}});return ns(E(n.subject)?n.subject:{},o,t)},Po=(e,t)=>{if(bo(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Po(p,t);return r=r||c,d}),n=l.omit(t),s={properties:n,examples:l.map(n),required:l.without(t),allOf:o,oneOf:o,anyOf:o},i=l.evolve(s,e);return[i,r||!!i.required?.length]},wo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:i,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${Bt(n)} response ${p?d:""}`.trim()})=>{if(!o||!dt(e,n))return{description:m};let y=Ye(Gt(r,{rules:{...c,...Vt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),g=[];bt(y)&&y.examples&&(g.push(...y.examples),delete y.examples);let h={schema:i==="components"?s(r,y,ne(m)):y,examples:Jt(g)};return{description:m,content:l.fromPairs(l.xprod(o,[h]))}},ss=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},is=({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},as=({name:e})=>({type:"apiKey",in:"header",name:e}),ps=({name:e})=>({type:"apiKey",in:"cookie",name:e}),cs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ds=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),Co=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ss(o):o.type==="input"?is(o,t):o.type==="header"?as(o):o.type==="cookie"?ps(o):o.type==="openid"?cs(o):ds(o);return e.map(o=>o.map(r))},Eo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let i=r(s),p=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[i]:p?t:[]})},{})),ko=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>Gt(e,{rules:{...t,...Vt},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Io=({method:e,path:t,schema:r,request:o,mimeType:n,makeRef:s,composition:i,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[c,m]=Po(Ye(o),p),y=[];bt(c)&&c.examples&&(y.push(...c.examples),delete c.examples);let g={schema:i==="components"?s(r,c,ne(d)):c,examples:Jt(y.length?y:Me(o).examples?.filter(w=>E(w)&&!Array.isArray(w)).map(l.omit(p))||[])},h={description:d,content:{[n]:g}};return(m||n===C.raw)&&(h.required=!0),h},vo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Wt=e=>e.length<=So?e:e.slice(0,So-1)+"\u2026",Rt=e=>e.length?e.slice():void 0;var Yt=class extends ms{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||ne(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new Y(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,composition:y="inline"}){super(),this.addInfo({title:o,version:n});for(let h of typeof s=="string"?[s]:s)this.addServer({url:h});je({routing:t,onEndpoint:gt((h,w,I)=>{let M={path:w,method:h,endpoint:I,composition:y,brandHandling:p,makeRef:this.#o.bind(this)},{description:b,shortDescription:v,scopes:A,inputSchema:B}=I,z=v?Wt(v):m&&b?Wt(b):void 0,X=Lt(h,r.inputSources),Pe=this.#n(w,h,I.getOperationId(h)),tt=ko({...M,schema:B}),ee=ho(I.security),rt=To({...M,inputSources:X,isHeader:c,security:ee,request:tt,description:i?.requestParameter?.call(null,{method:h,path:w,operationId:Pe})}),ot={};for(let te of Ae){let ce=I.getResponses(te);for(let{mimeTypes:zt,schema:st,statusCodes:it}of ce)for(let Nt of it)ot[Nt]=wo({...M,variant:te,schema:st,mimeTypes:zt,statusCode:Nt,hasMultipleStatusCodes:ce.length>1||it.length>1,description:i?.[`${te}Response`]?.call(null,{method:h,path:w,operationId:Pe,statusCode:Nt})})}let nt=X.includes("body")?Io({...M,request:tt,paramNames:Ao.pluck("name",rt),schema:B,mimeType:C[I.requestType],description:i?.requestBody?.call(null,{method:h,path:w,operationId:Pe})}):void 0,vt=Eo(Co(ee,X),A,te=>{let ce=this.#s(te);return this.addSecurityScheme(ce,te),ce}),At={operationId:Pe,summary:z,description:b,deprecated:I.isDeprecated||void 0,tags:Rt(I.tags),parameters:Rt(rt),requestBody:nt,security:Rt(vt),responses:ot};this.addPath(Oo(w),{[h]:At})})}),d&&(this.rootDoc.tags=vo(d))}};import{createRequest as ls,createResponse as us}from"node-mocks-http";var fs=e=>ls({...e,headers:{"content-type":C.json,...e?.headers}}),ys=e=>us(e),hs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Kr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},zo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=fs(e),s=ys({req:n,...t});s.req=t?.req||n,n.res=s;let i=hs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},gs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=zo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},xs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=be}}=zo(r),d=pt(o,i),c={request:o,response:n,logger:s,input:d,options:t};try{let m=await e.execute(c);return{requestMock:o,responseMock:n,loggerMock:s,output:m}}catch(m){return await p.execute({...c,error:re(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Bo from"ramda";import It from"typescript";import{z as Zs}from"zod";import*as jo from"ramda";import V from"typescript";import*as D from"ramda";import u from"typescript";var a=u.factory,Ot=[a.createModifier(u.SyntaxKind.ExportKeyword)],Ss=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Qe={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Qt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Xt=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},bs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,er=e=>typeof e=="string"&&bs.test(e)?a.createIdentifier(e):O(e),Tt=(e,...t)=>a.createTemplateExpression(a.createTemplateHead(e),t.map(([r,o=""],n)=>a.createTemplateSpan(r,n===t.length-1?a.createTemplateTail(o):a.createTemplateMiddle(o)))),Pt=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Le=e=>Object.entries(e).map(([t,r])=>Pt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),tr=(e,t=[])=>a.createConstructorDeclaration(Qe.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&D.map(f,t)):e,rr=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),_=e=>{let t=new Map;for(let r of e)t.set(Os(r)?r.kind:r,r);return a.createUnionTypeNode(Array.from(t.values()))},Oe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,er(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?_([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=D.reject(D.isNil,[o?"@deprecated":void 0,n]);return p.length?Qt(i,p.join(" ")):i},or=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),nr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),N=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&Ot,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),sr=(e,t)=>J(e,_(D.map(L,t)),{expose:!0}),J=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?Ot:void 0,e,n&&cr(n),t);return o?Qt(s,o):s},No=(e,t)=>a.createPropertyDeclaration(Qe.public,e,void 0,f(t),void 0),ir=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Qe.public,void 0,e,void 0,o&&cr(o),t,n,a.createBlock(r)),ar=(e,t,{typeParams:r}={})=>a.createClassDeclaration(Ot,e,r&&cr(r),void 0,t),pr=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),wt=e=>f(Promise.name,[e]),Ct=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?Ot:void 0,e,void 0,void 0,t);return o?Qt(n,o):n},cr=e=>(Array.isArray(e)?e.map(t=>D.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Te=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?Ss:void 0,void 0,Array.isArray(e)?D.map(Pt,e):Le(e),void 0,void 0,t),T=e=>e,Xe=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.SyntaxKind.QuestionToken),t,a.createToken(u.SyntaxKind.ColonToken),r),P=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Be=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Et=(e,t)=>f("Extract",[e,t]),dr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),q=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),Mo=e=>_([f(e),wt(e)]),mr=(e,t)=>a.createFunctionTypeNode(void 0,Le(e),f(t)),O=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),L=e=>a.createLiteralTypeNode(O(e)),Rs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Os=e=>Rs.includes(e.kind);var kt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:a.createIdentifier("Path"),implementationType:a.createIdentifier("Implementation"),keyParameter:a.createIdentifier("key"),pathParameter:a.createIdentifier("path"),paramsArgument:a.createIdentifier("params"),ctxArgument:a.createIdentifier("ctx"),methodParameter:a.createIdentifier("method"),requestParameter:a.createIdentifier("request"),eventParameter:a.createIdentifier("event"),dataParameter:a.createIdentifier("data"),handlerParameter:a.createIdentifier("handler"),msgParameter:a.createIdentifier("msg"),parseRequestFn:a.createIdentifier("parseRequest"),substituteFn:a.createIdentifier("substitute"),provideMethod:a.createIdentifier("provide"),onMethod:a.createIdentifier("on"),implementationArgument:a.createIdentifier("implementation"),hasBodyConst:a.createIdentifier("hasBody"),undefinedValue:a.createIdentifier("undefined"),responseConst:a.createIdentifier("response"),restConst:a.createIdentifier("rest"),searchParamsConst:a.createIdentifier("searchParams"),defaultImplementationConst:a.createIdentifier("defaultImplementation"),clientConst:a.createIdentifier("client"),contentTypeConst:a.createIdentifier("contentType"),isJsonConst:a.createIdentifier("isJSON"),sourceProp:a.createIdentifier("source")};interfaces={input:a.createIdentifier("Input"),positive:a.createIdentifier("PositiveResponse"),negative:a.createIdentifier("NegativeResponse"),encoded:a.createIdentifier("EncodedResponse"),response:a.createIdentifier("Response")};methodType=sr("Method",xr);someOfType=J("SomeOf",q("T",pr("T")),{params:["T"]});requestType=J("Request",pr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>sr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Ct(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Oe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>N("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(er(t),a.createArrayLiteralExpression(jo.map(O,r))))),{expose:!0});makeImplementationType=()=>J(this.#e.implementationType,mr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:rr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},wt(V.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:V.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>N(this.#e.parseRequestFn,Te({[this.#e.requestParameter.text]:V.SyntaxKind.StringKeyword},a.createAsExpression(P(this.#e.requestParameter,T("split"))(a.createRegularExpressionLiteral("/ (.+)/"),O(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>N(this.#e.substituteFn,Te({[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:rr},a.createBlock([N(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],V.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([dr(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(Tt(":",[this.#e.keyParameter]),Te([],a.createBlock([a.createExpressionStatement(a.createDeleteExpression(a.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),a.createReturnStatement(a.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),a.createReturnStatement(a.createAsExpression(a.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>ir(this.#e.provideMethod,Le({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:q(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[N(nr(this.#e.methodParameter,this.#e.pathParameter),P(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(P(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(P(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:wt(q(this.interfaces.response,"K"))});makeClientClass=t=>ar(t,[tr([Pt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Qe.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Tt("?",[Be(URLSearchParams.name,t)]);#o=()=>Be(URL.name,Tt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),O(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(T("method"),P(this.#e.methodParameter,T("toUpperCase"))()),r=a.createPropertyAssignment(T("headers"),Xe(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(O("Content-Type"),O(C.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(T("body"),Xe(this.#e.hasBodyConst,P(JSON[Symbol.toStringTag],T("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=N(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=N(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([O("get"),O("head"),O("delete")]),T("includes"))(this.#e.methodParameter))),i=N(this.#e.searchParamsConst,Xe(this.#e.hasBodyConst,O(""),this.#r(this.#e.paramsArgument))),p=N(this.#e.contentTypeConst,P(this.#e.responseConst,T("headers"),T("get"))(O("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(V.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=N(this.#e.isJsonConst,P(this.#e.contentTypeConst,T("startsWith"))(O(C.json))),m=a.createReturnStatement(P(this.#e.responseConst,Xe(this.#e.isJsonConst,O(T("json")),O(T("text"))))());return N(this.#e.defaultImplementationConst,Te([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],a.createBlock([s,i,n,p,d,c,m]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>tr(Le({request:"K",params:q(this.interfaces.input,"K")}),[N(nr(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),O(1)),this.#e.paramsArgument)),N(this.#e.searchParamsConst,this.#r(this.#e.restConst)),dr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Be("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Oe(T("event"),t)]);#i=()=>ir(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:mr({[this.#e.dataParameter.text]:q(Et("R",or(this.#s("E"))),L(T("data")))},Mo(V.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,Te([this.#e.msgParameter],P(this.#e.handlerParameter)(P(JSON[Symbol.toStringTag],T("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),T("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:q("R",L(T("event")))}});makeSubscriptionClass=t=>ar(t,[No(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Et(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(V.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Et(q(this.interfaces.positive,"K"),or(this.#s(V.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[N(this.#e.clientConst,Be(t)),P(this.#e.clientConst,this.#e.provideMethod)(O("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",O("10"))])),P(Be(r,O("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(O("time"),Te(["time"],a.createBlock([])))]};import*as k from"ramda";import x from"typescript";import{globalRegistry as Ts}from"zod";var lr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=G(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>lr(m,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),c=t&&t(e,{prev:d,...n});return c?{...d,...c}:d};var{factory:$}=x,Ps={[x.SyntaxKind.AnyKeyword]:"",[x.SyntaxKind.BigIntKeyword]:BigInt(0),[x.SyntaxKind.BooleanKeyword]:!1,[x.SyntaxKind.NumberKeyword]:0,[x.SyntaxKind.ObjectKeyword]:{},[x.SyntaxKind.StringKeyword]:"",[x.SyntaxKind.UndefinedKeyword]:void 0},ur={name:k.path(["name","text"]),type:k.path(["type"]),optional:k.path(["questionToken"])},ws=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.SyntaxKind.UndefinedKeyword):L(r));return t.length===1?t[0]:_(t)},Cs=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(oe(p)){r.unshift(p);break}i+=p??""}return i},n=$.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?$.createTemplateMiddle:$.createTemplateTail;s.push($.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?$.createTemplateLiteralType(n,s):L(n.text)},Es=(e,{isResponse:t,next:r,makeAlias:o})=>{let n=()=>{let s=Object.entries(e._zod.def.shape).map(([i,p])=>{let{description:d,deprecated:c}=Ts.get(p)||{};return Oe(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return $.createTypeLiteralNode(s)};return kr(e,{io:t?"output":"input"})?o(e,n):n()},ks=({_zod:{def:e}},{next:t})=>$.createArrayTypeNode(t(e.element)),Is=({_zod:{def:e}})=>_(Object.values(e.entries).map(L)),vs=({_zod:{def:e}},{next:t})=>_(e.options.map(t)),As=e=>Ps?.[e.kind],zs=({_zod:{def:e}},{next:t})=>_([t(e.innerType),L(null)]),Ns=({_zod:{def:e}},{next:t})=>$.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:$.createRestTypeNode(t(e.rest)))),Ms=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),js=k.tryCatch(e=>{if(!e.every(x.isTypeLiteralNode))throw new Error("Not objects");let t=k.chain(k.prop("members"),e),r=k.uniqWith((...o)=>{if(!k.eqBy(ur.name,...o))return!1;if(k.both(k.eqBy(ur.type),k.eqBy(ur.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return $.createTypeLiteralNode(r)},(e,t)=>$.createIntersectionTypeNode(t)),Ls=({_zod:{def:e}},{next:t})=>js([e.left,e.right].map(t)),F=e=>()=>f(e),et=({_zod:{def:e}},{next:t})=>t(e.innerType),Lo=e=>f(e?x.SyntaxKind.UnknownKeyword:x.SyntaxKind.AnyKeyword),Bs=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!oe(o,"transform"))return t(o);let s=t(n),i=ct(o,As(s)),p={number:x.SyntaxKind.NumberKeyword,bigint:x.SyntaxKind.BigIntKeyword,boolean:x.SyntaxKind.BooleanKeyword,string:x.SyntaxKind.StringKeyword,undefined:x.SyntaxKind.UndefinedKeyword,object:x.SyntaxKind.ObjectKeyword};return f(i&&p[i]||Lo(r))},Hs=()=>L(null),Ks=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),qs=()=>f("Buffer"),Fs=(e,{next:t})=>t(e._zod.def.shape.raw),$s={string:F(x.SyntaxKind.StringKeyword),number:F(x.SyntaxKind.NumberKeyword),bigint:F(x.SyntaxKind.BigIntKeyword),boolean:F(x.SyntaxKind.BooleanKeyword),any:F(x.SyntaxKind.AnyKeyword),undefined:F(x.SyntaxKind.UndefinedKeyword),[ye]:F(x.SyntaxKind.StringKeyword),[he]:F(x.SyntaxKind.StringKeyword),never:F(x.SyntaxKind.NeverKeyword),void:F(x.SyntaxKind.UndefinedKeyword),unknown:F(x.SyntaxKind.UnknownKeyword),null:Hs,array:ks,tuple:Ns,record:Ms,object:Es,literal:ws,template_literal:Cs,intersection:Ls,union:vs,default:et,enum:Is,optional:et,nonoptional:et,nullable:zs,catch:et,pipe:Bs,lazy:Ks,readonly:et,[fe]:qs,[H]:Fs},fr=(e,{brandHandling:t,ctx:r})=>lr(e,{rules:{...t,...$s},onMissing:({},{isResponse:o})=>Lo(o),ctx:r});var yr=class extends kt{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=L(null);this.#t.set(t,J(o,n)),this.#t.set(t,J(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:i="https://example.com",noContent:p=Zs.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};je({routing:t,onEndpoint:gt((g,h,w)=>{let I=ne.bind(null,g,h),{isDeprecated:M,inputSchema:b,tags:v}=w,A=`${g} ${h}`,B=J(I("input"),fr(b,c),{comment:A});this.#e.push(B);let z=Ae.reduce((tt,ee)=>{let rt=w.getResponses(ee),ot=Bo.chain(([vt,{schema:At,mimeTypes:te,statusCodes:ce}])=>{let zt=te&&dt(g,ee),st=J(I(ee,"variant",`${vt+1}`),fr(zt?At:p,m),{comment:A});return this.#e.push(st),ce.map(it=>Oe(it,st.name))},Array.from(rt.entries())),nt=Ct(I(ee,"response","variants"),ot,{comment:A});return this.#e.push(nt),Object.assign(tt,{[ee]:nt})},{});this.paths.add(h);let X=L(A),Pe={input:f(B.name),positive:this.someOf(z.positive),negative:this.someOf(z.negative),response:_([q(this.interfaces.positive,X),q(this.interfaces.negative,X)]),encoded:a.createIntersectionTypeNode([f(z.positive.name),f(z.negative.name)])};this.registry.set(A,{isDeprecated:M,store:Pe}),this.tags.set(A,v)})}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:Xt(r,t)).join(`
|
|
18
|
+
`))};var uo=e=>{e.startupLogo!==!1&&lo(process.stdout);let t=e.errorHandler||be,r=Hr(e.logger)?e.logger:new Ve(e.logger);r.debug("Running",{build:"v25.0.0-beta.7",env:process.env.NODE_ENV||"development"}),po(r);let o=io({logger:r,config:e}),s={getLogger:ao(r),errorHandler:t},i=oo(s),p=ro(s);return{...s,logger:r,notFoundHandler:i,catcher:p,loggingMiddleware:o}},qn=(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,loggingMiddleware:s}=uo(e);return Ut({app:e.app.use(s),routing:t,getLogger:o,config:e}),{notFoundHandler:n,logger:r}},Fn=async(e,t)=>{let{logger:r,getLogger:o,notFoundHandler:n,catcher:s,loggingMiddleware:i}=uo(e),p=St().disable("x-powered-by").use(i);if(e.compression){let g=await Ne("compression");p.use(g(typeof e.compression=="object"?e.compression:void 0))}await e.beforeRouting?.({app:p,getLogger:o});let d={json:[e.jsonParser||St.json()],raw:[e.rawParser||St.raw(),so],form:[e.formParser||St.urlencoded()],upload:e.upload?await no({config:e,getLogger:o}):[]};Ut({app:p,routing:t,getLogger:o,config:e,parsers:d}),p.use(s,n);let c=[],m=(g,h)=>()=>g.listen(h,()=>r.info("Listening",h)),y=[];if(e.http){let g=Hn.createServer(p);c.push(g),y.push(m(g,e.http.listen))}if(e.https){let g=Kn.createServer(e.https.options,p);c.push(g),y.push(m(g,e.https.listen))}return c.length||r.warn("No servers configured."),e.gracefulShutdown&&co({logger:r,servers:c,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,servers:y.map(g=>g())}};import{OpenApiBuilder as ms}from"openapi3-ts/oas31";import*as Ao from"ramda";import*as R from"ramda";var fo=e=>E(e)&&"or"in e,yo=e=>E(e)&&"and"in e,_t=e=>!yo(e)&&!fo(e),ho=e=>{let t=R.filter(_t,e),r=R.chain(R.prop("and"),R.filter(yo,e)),[o,n]=R.partition(_t,r),s=R.concat(t,o),i=R.filter(fo,e);return R.map(R.prop("or"),R.concat(i,n)).reduce((d,c)=>le(d,R.map(m=>_t(m)?[m]:m.and,c),([m,y])=>R.concat(m,y)),R.reject(R.isEmpty,[s]))};import{isReferenceObject as bo,isSchemaObject as bt}from"openapi3-ts/oas31";import*as l from"ramda";import{z as xo}from"zod";var go=["a-im","accept","accept-additions","accept-ch","accept-charset","accept-datetime","accept-encoding","accept-features","accept-language","accept-signature","access-control","access-control-request-headers","access-control-request-method","alpn","alt-used","alternates","amp-cache-transform","apply-to-redirect-ref","authentication-control","authentication-info","authorization","available-dictionary","c-ext","c-man","c-opt","c-pep","c-pep-info","cache-control","cal-managed-id","caldav-timezones","capsule-protocol","cert-not-after","cert-not-before","client-cert","client-cert-chain","close","cmcd-object","cmcd-request","cmcd-session","cmcd-status","cmsd-dynamic","cmsd-static","concealed-auth-export","configuration-context","connection","content-digest","content-disposition","content-encoding","content-id","content-language","content-length","content-location","content-md5","content-range","content-script-type","content-type","cookie","cookie2","cross-origin-embedder-policy","cross-origin-embedder-policy-report-only","cross-origin-opener-policy","cross-origin-opener-policy-report-only","cross-origin-resource-policy","cta-common-access-token","dasl","date","dav","default-style","delta-base","deprecation","depth","derived-from","destination","detached-jws","differential-id","dictionary-id","digest","dpop","dpop-nonce","early-data","ediint-features","expect","expect-ct","ext","forwarded","from","getprofile","hobareg","host","http2-settings","if","if-match","if-modified-since","if-none-match","if-range","if-schedule-tag-match","if-unmodified-since","im","include-referred-token-binding-id","isolation","keep-alive","label","last-event-id","link","link-template","lock-token","man","max-forwards","memento-datetime","meter","method-check","method-check-expires","mime-version","negotiate","nel","odata-entityid","odata-isolation","odata-maxversion","odata-version","opt","ordering-type","origin","origin-agent-cluster","oscore","oslc-core-version","overwrite","p3p","pep","pep-info","permissions-policy","pics-label","ping-from","ping-to","position","pragma","prefer","preference-applied","priority","profileobject","protocol","protocol-info","protocol-query","protocol-request","proxy-authorization","proxy-features","proxy-instruction","public","public-key-pins","public-key-pins-report-only","range","redirect-ref","referer","referer-root","referrer-policy","repeatability-client-id","repeatability-first-sent","repeatability-request-id","repeatability-result","replay-nonce","reporting-endpoints","repr-digest","safe","schedule-reply","schedule-tag","sec-fetch-storage-access","sec-gpc","sec-purpose","sec-token-binding","sec-websocket-extensions","sec-websocket-key","sec-websocket-protocol","sec-websocket-version","security-scheme","setprofile","signature","signature-input","slug","soapaction","status-uri","sunset","surrogate-capability","tcn","te","timeout","topic","traceparent","tracestate","trailer","transfer-encoding","ttl","upgrade","urgency","uri","use-as-dictionary","user-agent","variant-vary","via","want-content-digest","want-digest","want-repr-digest","warning","x-content-type-options","x-frame-options"];var So=50,Ro="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",Zn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Oo=e=>e.replace(Mt,t=>`{${t.slice(1)}}`),Dn=({},e)=>{if(e.isResponse)throw new Y("Please use ez.upload() only for input.",e);return{type:"string",format:"binary"}},Un=({jsonSchema:e})=>({...e,externalDocs:{description:"raw binary data",url:"https://swagger.io/specification/#working-with-binary-data"}}),_n=({zodSchema:e,jsonSchema:t})=>{if(!re(e,"union")||!("discriminator"in e._zod.def))return t;let r=e._zod.def.discriminator;return{...t,discriminator:t.discriminator??{propertyName:r}}},Jn=l.tryCatch(({jsonSchema:e})=>{if(!e.allOf)throw"no allOf";return Me(e,"throw")},(e,{jsonSchema:t})=>t),Vn=({jsonSchema:e})=>{if(!e.anyOf)return e;let t=e.anyOf[0];return Object.assign(t,{type:es(t.type)})},Ye=e=>e,Gn=({jsonSchema:{examples:e,description:t}},r)=>{if(r.isResponse)throw new Y("Please use ez.dateOut() for output.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Ro}};return e?.length&&(o.examples=e),o},Wn=({jsonSchema:{examples:e,description:t}},r)=>{if(!r.isResponse)throw new Y("Please use ez.dateIn() for input.",r);let o={description:t||"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Ro}};return e?.length&&(o.examples=e),o},Yn=()=>({type:"string",format:"bigint",pattern:/^-?\d+$/.source}),Qn=({zodSchema:e,jsonSchema:t})=>e._zod.def.rest!==null?t:{...t,items:{not:{}}},Xn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return Zn?.[t]},es=e=>e==="null"?e:typeof e=="string"?[e,"null"]:e&&[...new Set(e).add("null")],ts=({zodSchema:e,jsonSchema:t},r)=>{let o=e._zod.def[r.isResponse?"out":"in"],n=e._zod.def[r.isResponse?"in":"out"];if(!re(o,"transform"))return t;let s=Ye(Gt(n,{ctx:r}));if(bt(s))if(r.isResponse){let i=ct(o,Xn(s));if(i&&["number","string","boolean"].includes(i))return{...t,type:i}}else{let{type:i,...p}=s;return{...p,format:`${p.format||i} (preprocessed)`}}return t},rs=({jsonSchema:e})=>{if(e.type!=="object")return e;let t=e;return!t.properties||!("raw"in t.properties)||!E(t.properties.raw)?e:t.properties.raw},Jt=e=>e.length?l.fromPairs(l.zip(l.times(t=>`example${t+1}`,e.length),l.map(l.objOf("value"),e))):void 0,os=(e,t)=>t?.includes(e)||e.startsWith("x-")||go.includes(e),To=({path:e,method:t,request:r,inputSources:o,makeRef:n,composition:s,isHeader:i,security:p,description:d=`${t.toUpperCase()} ${e} Parameter`})=>{let c=Me(r),m=at(e),y=o.includes("query"),g=o.includes("params"),h=o.includes("headers"),w=b=>g&&m.includes(b),I=l.chain(l.filter(b=>b.type==="header"),p??[]).map(({name:b})=>b),M=b=>h&&(i?.(b,t,e)??os(b,I));return Object.entries(c.properties).reduce((b,[v,A])=>{if(!E(A))return b;let B=w(v)?"path":M(v)?"header":y?"query":void 0;if(!B)return b;let z=Ye(A),X=s==="components"?n(A.id||JSON.stringify(A),z,oe(d,v)):z;return b.concat({name:v,in:B,deprecated:A.deprecated,required:c.required?.includes(v)||!1,description:z.description||d,schema:X,examples:Jt(bt(z)&&z.examples?.length?z.examples:l.pluck(v,c.examples?.filter(l.both(E,l.has(v)))||[]))})},[])},Vt={nullable:Vn,union:_n,bigint:Yn,intersection:Jn,tuple:Qn,pipe:ts,[ye]:Gn,[he]:Wn,[se]:Dn,[H]:rs,[fe]:Un},ns=(e,t,r)=>{let o=[e,t];for(;o.length;){let n=o.shift();if(l.is(Object,n)){if(bo(n)&&!n.$ref.startsWith("#/components")){let s=n.$ref.split("/").pop(),i=t[s];i&&(n.$ref=r.makeRef(i.id||i,Ye(i)).$ref);continue}o.push(...l.values(n))}l.is(Array,n)&&o.push(...l.values(n))}return e},Gt=(e,{ctx:t,rules:r=Vt})=>{let{$defs:o={},properties:n={}}=xo.toJSONSchema(xo.object({subject:e}),{unrepresentable:"any",io:t.isResponse?"output":"input",override:s=>{let i=G(s.zodSchema),p=r[i&&i in r?i:s.zodSchema._zod.def.type];if(p){let d={...p(s,t)};for(let c in s.jsonSchema)delete s.jsonSchema[c];Object.assign(s.jsonSchema,d)}}});return ns(E(n.subject)?n.subject:{},o,t)},Po=(e,t)=>{if(bo(e))return[e,!1];let r=!1,o=l.map(p=>{let[d,c]=Po(p,t);return r=r||c,d}),n=l.omit(t),s={properties:n,examples:l.map(n),required:l.without(t),allOf:o,oneOf:o,anyOf:o},i=l.evolve(s,e);return[i,r||!!i.required?.length]},wo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,makeRef:s,composition:i,hasMultipleStatusCodes:p,statusCode:d,brandHandling:c,description:m=`${e.toUpperCase()} ${t} ${Bt(n)} response ${p?d:""}`.trim()})=>{if(!dt(e,o))return{description:m};let y=Ye(Gt(r,{rules:{...c,...Vt},ctx:{isResponse:!0,makeRef:s,path:t,method:e}})),g=[];bt(y)&&y.examples&&(g.push(...y.examples),delete y.examples);let h={schema:i==="components"?s(r,y,oe(m)):y,examples:Jt(g)};return{description:m,content:l.fromPairs(l.xprod(o,[h]))}},ss=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},is=({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},as=({name:e})=>({type:"apiKey",in:"header",name:e}),ps=({name:e})=>({type:"apiKey",in:"cookie",name:e}),cs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ds=({flows:e={}})=>({type:"oauth2",flows:l.map(t=>({...t,scopes:t.scopes||{}}),l.reject(l.isNil,e))}),Co=(e,t=[])=>{let r=o=>o.type==="basic"?{type:"http",scheme:"basic"}:o.type==="bearer"?ss(o):o.type==="input"?is(o,t):o.type==="header"?as(o):o.type==="cookie"?ps(o):o.type==="openid"?cs(o):ds(o);return e.map(o=>o.map(r))},Eo=(e,t,r)=>e.map(o=>o.reduce((n,s)=>{let i=r(s),p=["oauth2","openIdConnect"].includes(s.type);return Object.assign(n,{[i]:p?t:[]})},{})),ko=({schema:e,brandHandling:t,makeRef:r,path:o,method:n})=>Gt(e,{rules:{...t,...Vt},ctx:{isResponse:!1,makeRef:r,path:o,method:n}}),Io=({method:e,path:t,schema:r,request:o,mimeType:n,makeRef:s,composition:i,paramNames:p,description:d=`${e.toUpperCase()} ${t} Request body`})=>{let[c,m]=Po(Ye(o),p),y=[];bt(c)&&c.examples&&(y.push(...c.examples),delete c.examples);let g={schema:i==="components"?s(r,c,oe(d)):c,examples:Jt(y.length?y:Me(o).examples?.filter(w=>E(w)&&!Array.isArray(w)).map(l.omit(p))||[])},h={description:d,content:{[n]:g}};return(m||n===C.raw)&&(h.required=!0),h},vo=e=>Object.entries(e).reduce((t,[r,o])=>{if(!o)return t;let n={name:r,description:typeof o=="string"?o:o.description};return typeof o=="object"&&o.url&&(n.externalDocs={url:o.url}),t.concat(n)},[]),Wt=e=>e.length<=So?e:e.slice(0,So-1)+"\u2026",Rt=e=>e.length?e.slice():void 0;var Yt=class extends ms{#e=new Map;#t=new Map;#r=new Map;#o(t,r,o=this.#r.get(t)){return o||(o=`Schema${this.#r.size+1}`,this.#r.set(t,o)),this.addSchema(o,r),{$ref:`#/components/schemas/${o}`}}#n(t,r,o){let n=o||oe(r,t),s=this.#t.get(n);if(s===void 0)return this.#t.set(n,1),n;if(o)throw new Y(`Duplicated operationId: "${o}"`,{method:r,isResponse:!1,path:t});return s++,this.#t.set(n,s),`${n}${s}`}#s(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.#e.get(t.type)||0)+1;return this.#e.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:s,descriptions:i,brandHandling:p,tags:d,isHeader:c,hasSummaryFromDescription:m=!0,composition:y="inline"}){super(),this.addInfo({title:o,version:n});for(let h of typeof s=="string"?[s]:s)this.addServer({url:h});je({routing:t,onEndpoint:gt((h,w,I)=>{let M={path:w,method:h,endpoint:I,composition:y,brandHandling:p,makeRef:this.#o.bind(this)},{description:b,shortDescription:v,scopes:A,inputSchema:B}=I,z=v?Wt(v):m&&b?Wt(b):void 0,X=Lt(h,r.inputSources),Pe=this.#n(w,h,I.getOperationId(h)),tt=ko({...M,schema:B}),pe=ho(I.security),rt=To({...M,inputSources:X,isHeader:c,security:pe,request:tt,description:i?.requestParameter?.call(null,{method:h,path:w,operationId:Pe})}),ot={};for(let ee of Ae){let ce=I.getResponses(ee);for(let{mimeTypes:zt,schema:st,statusCodes:it}of ce)for(let Nt of it)ot[Nt]=wo({...M,variant:ee,schema:st,mimeTypes:zt,statusCode:Nt,hasMultipleStatusCodes:ce.length>1||it.length>1,description:i?.[`${ee}Response`]?.call(null,{method:h,path:w,operationId:Pe,statusCode:Nt})})}let nt=X.includes("body")?Io({...M,request:tt,paramNames:Ao.pluck("name",rt),schema:B,mimeType:C[I.requestType],description:i?.requestBody?.call(null,{method:h,path:w,operationId:Pe})}):void 0,vt=Eo(Co(pe,X),A,ee=>{let ce=this.#s(ee);return this.addSecurityScheme(ce,ee),ce}),At={operationId:Pe,summary:z,description:b,deprecated:I.isDeprecated||void 0,tags:Rt(I.tags),parameters:Rt(rt),requestBody:nt,security:Rt(vt),responses:ot};this.addPath(Oo(w),{[h]:At})})}),d&&(this.rootDoc.tags=vo(d))}};import{createRequest as ls,createResponse as us}from"node-mocks-http";var fs=e=>ls({...e,headers:{"content-type":C.json,...e?.headers}}),ys=e=>us(e),hs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:Kr(o)?(...s)=>t[o].push(s):Reflect.get(r,o,n)}})},zo=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=fs(e),s=ys({req:n,...t});s.req=t?.req||n,n.res=s;let i=hs(o),p={cors:!1,logger:i,...r};return{requestMock:n,responseMock:s,loggerMock:i,configMock:p}},gs=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:s}=zo(t);return await e.execute({request:r,response:o,config:s,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}},xs=async({middleware:e,options:t={},...r})=>{let{requestMock:o,responseMock:n,loggerMock:s,configMock:{inputSources:i,errorHandler:p=be}}=zo(r),d=pt(o,i),c={request:o,response:n,logger:s,input:d,options:t};try{let m=await e.execute(c);return{requestMock:o,responseMock:n,loggerMock:s,output:m}}catch(m){return await p.execute({...c,error:te(m),output:null}),{requestMock:o,responseMock:n,loggerMock:s,output:{}}}};import*as Bo from"ramda";import It from"typescript";import{z as Zs}from"zod";import*as jo from"ramda";import V from"typescript";import*as U from"ramda";import u from"typescript";var a=u.factory,Ot=[a.createModifier(u.SyntaxKind.ExportKeyword)],Ss=[a.createModifier(u.SyntaxKind.AsyncKeyword)],Qe={public:[a.createModifier(u.SyntaxKind.PublicKeyword)],protectedReadonly:[a.createModifier(u.SyntaxKind.ProtectedKeyword),a.createModifier(u.SyntaxKind.ReadonlyKeyword)]},Qt=(e,t)=>u.addSyntheticLeadingComment(e,u.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0),Xt=(e,t)=>{let r=u.createSourceFile("print.ts","",u.ScriptTarget.Latest,!1,u.ScriptKind.TS);return u.createPrinter(t).printNode(u.EmitHint.Unspecified,e,r)},bs=/^[A-Za-z_$][A-Za-z0-9_$]*$/,er=e=>typeof e=="string"&&bs.test(e)?a.createIdentifier(e):O(e),Tt=(e,...t)=>a.createTemplateExpression(a.createTemplateHead(e),t.map(([r,o=""],n)=>a.createTemplateSpan(r,n===t.length-1?a.createTemplateTail(o):a.createTemplateMiddle(o)))),Pt=(e,{type:t,mod:r,init:o,optional:n}={})=>a.createParameterDeclaration(r,void 0,e,n?a.createToken(u.SyntaxKind.QuestionToken):void 0,t?f(t):void 0,o),Le=e=>Object.entries(e).map(([t,r])=>Pt(t,typeof r=="string"||typeof r=="number"||typeof r=="object"&&"kind"in r?{type:r}:r)),tr=(e,t=[])=>a.createConstructorDeclaration(Qe.public,e,a.createBlock(t)),f=(e,t)=>typeof e=="number"?a.createKeywordTypeNode(e):typeof e=="string"||u.isIdentifier(e)?a.createTypeReferenceNode(e,t&&U.map(f,t)):e,rr=f("Record",[u.SyntaxKind.StringKeyword,u.SyntaxKind.AnyKeyword]),_=e=>{let t=new Map;for(let r of e)t.set(Os(r)?r.kind:r,r);return a.createUnionTypeNode(Array.from(t.values()))},Oe=(e,t,{isOptional:r,isDeprecated:o,comment:n}={})=>{let s=f(t),i=a.createPropertySignature(void 0,er(e),r?a.createToken(u.SyntaxKind.QuestionToken):void 0,r?_([s,f(u.SyntaxKind.UndefinedKeyword)]):s),p=U.reject(U.isNil,[o?"@deprecated":void 0,n]);return p.length?Qt(i,p.join(" ")):i},or=e=>u.setEmitFlags(e,u.EmitFlags.SingleLine),nr=(...e)=>a.createArrayBindingPattern(e.map(t=>a.createBindingElement(void 0,void 0,t))),N=(e,t,{type:r,expose:o}={})=>a.createVariableStatement(o&&Ot,a.createVariableDeclarationList([a.createVariableDeclaration(e,void 0,r?f(r):void 0,t)],u.NodeFlags.Const)),sr=(e,t)=>J(e,_(U.map(L,t)),{expose:!0}),J=(e,t,{expose:r,comment:o,params:n}={})=>{let s=a.createTypeAliasDeclaration(r?Ot:void 0,e,n&&cr(n),t);return o?Qt(s,o):s},No=(e,t)=>a.createPropertyDeclaration(Qe.public,e,void 0,f(t),void 0),ir=(e,t,r,{typeParams:o,returns:n}={})=>a.createMethodDeclaration(Qe.public,void 0,e,void 0,o&&cr(o),t,n,a.createBlock(r)),ar=(e,t,{typeParams:r}={})=>a.createClassDeclaration(Ot,e,r&&cr(r),void 0,t),pr=e=>a.createTypeOperatorNode(u.SyntaxKind.KeyOfKeyword,f(e)),wt=e=>f(Promise.name,[e]),Ct=(e,t,{expose:r,comment:o}={})=>{let n=a.createInterfaceDeclaration(r?Ot:void 0,e,void 0,void 0,t);return o?Qt(n,o):n},cr=e=>(Array.isArray(e)?e.map(t=>U.pair(t,void 0)):Object.entries(e)).map(([t,r])=>{let{type:o,init:n}=typeof r=="object"&&"init"in r?r:{type:r};return a.createTypeParameterDeclaration([],t,o?f(o):void 0,n?f(n):void 0)}),Te=(e,t,{isAsync:r}={})=>a.createArrowFunction(r?Ss:void 0,void 0,Array.isArray(e)?U.map(Pt,e):Le(e),void 0,void 0,t),T=e=>e,Xe=(e,t,r)=>a.createConditionalExpression(e,a.createToken(u.SyntaxKind.QuestionToken),t,a.createToken(u.SyntaxKind.ColonToken),r),P=(e,...t)=>(...r)=>a.createCallExpression(t.reduce((o,n)=>typeof n=="string"||u.isIdentifier(n)?a.createPropertyAccessExpression(o,n):a.createElementAccessExpression(o,n),typeof e=="string"?a.createIdentifier(e):e),void 0,r),Be=(e,...t)=>a.createNewExpression(a.createIdentifier(e),void 0,t),Et=(e,t)=>f("Extract",[e,t]),dr=(e,t)=>a.createExpressionStatement(a.createBinaryExpression(e,a.createToken(u.SyntaxKind.EqualsToken),t)),q=(e,t)=>a.createIndexedAccessTypeNode(f(e),f(t)),Mo=e=>_([f(e),wt(e)]),mr=(e,t)=>a.createFunctionTypeNode(void 0,Le(e),f(t)),O=e=>typeof e=="number"?a.createNumericLiteral(e):typeof e=="bigint"?a.createBigIntLiteral(e.toString()):typeof e=="boolean"?e?a.createTrue():a.createFalse():e===null?a.createNull():a.createStringLiteral(e),L=e=>a.createLiteralTypeNode(O(e)),Rs=[u.SyntaxKind.AnyKeyword,u.SyntaxKind.BigIntKeyword,u.SyntaxKind.BooleanKeyword,u.SyntaxKind.NeverKeyword,u.SyntaxKind.NumberKeyword,u.SyntaxKind.ObjectKeyword,u.SyntaxKind.StringKeyword,u.SyntaxKind.SymbolKeyword,u.SyntaxKind.UndefinedKeyword,u.SyntaxKind.UnknownKeyword,u.SyntaxKind.VoidKeyword],Os=e=>Rs.includes(e.kind);var kt=class{constructor(t){this.serverUrl=t}paths=new Set;tags=new Map;registry=new Map;#e={pathType:a.createIdentifier("Path"),implementationType:a.createIdentifier("Implementation"),keyParameter:a.createIdentifier("key"),pathParameter:a.createIdentifier("path"),paramsArgument:a.createIdentifier("params"),ctxArgument:a.createIdentifier("ctx"),methodParameter:a.createIdentifier("method"),requestParameter:a.createIdentifier("request"),eventParameter:a.createIdentifier("event"),dataParameter:a.createIdentifier("data"),handlerParameter:a.createIdentifier("handler"),msgParameter:a.createIdentifier("msg"),parseRequestFn:a.createIdentifier("parseRequest"),substituteFn:a.createIdentifier("substitute"),provideMethod:a.createIdentifier("provide"),onMethod:a.createIdentifier("on"),implementationArgument:a.createIdentifier("implementation"),hasBodyConst:a.createIdentifier("hasBody"),undefinedValue:a.createIdentifier("undefined"),responseConst:a.createIdentifier("response"),restConst:a.createIdentifier("rest"),searchParamsConst:a.createIdentifier("searchParams"),defaultImplementationConst:a.createIdentifier("defaultImplementation"),clientConst:a.createIdentifier("client"),contentTypeConst:a.createIdentifier("contentType"),isJsonConst:a.createIdentifier("isJSON"),sourceProp:a.createIdentifier("source")};interfaces={input:a.createIdentifier("Input"),positive:a.createIdentifier("PositiveResponse"),negative:a.createIdentifier("NegativeResponse"),encoded:a.createIdentifier("EncodedResponse"),response:a.createIdentifier("Response")};methodType=sr("Method",xr);someOfType=J("SomeOf",q("T",pr("T")),{params:["T"]});requestType=J("Request",pr(this.interfaces.input),{expose:!0});someOf=({name:t})=>f(this.someOfType.name,[t]);makePathType=()=>sr(this.#e.pathType,Array.from(this.paths));makePublicInterfaces=()=>Object.keys(this.interfaces).map(t=>Ct(this.interfaces[t],Array.from(this.registry).map(([r,{store:o,isDeprecated:n}])=>Oe(r,o[t],{isDeprecated:n})),{expose:!0}));makeEndpointTags=()=>N("endpointTags",a.createObjectLiteralExpression(Array.from(this.tags).map(([t,r])=>a.createPropertyAssignment(er(t),a.createArrayLiteralExpression(jo.map(O,r))))),{expose:!0});makeImplementationType=()=>J(this.#e.implementationType,mr({[this.#e.methodParameter.text]:this.methodType.name,[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:rr,[this.#e.ctxArgument.text]:{optional:!0,type:"T"}},wt(V.SyntaxKind.AnyKeyword)),{expose:!0,params:{T:{init:V.SyntaxKind.UnknownKeyword}}});makeParseRequestFn=()=>N(this.#e.parseRequestFn,Te({[this.#e.requestParameter.text]:V.SyntaxKind.StringKeyword},a.createAsExpression(P(this.#e.requestParameter,T("split"))(a.createRegularExpressionLiteral("/ (.+)/"),O(2)),a.createTupleTypeNode([f(this.methodType.name),f(this.#e.pathType)]))));makeSubstituteFn=()=>N(this.#e.substituteFn,Te({[this.#e.pathParameter.text]:V.SyntaxKind.StringKeyword,[this.#e.paramsArgument.text]:rr},a.createBlock([N(this.#e.restConst,a.createObjectLiteralExpression([a.createSpreadAssignment(this.#e.paramsArgument)])),a.createForInStatement(a.createVariableDeclarationList([a.createVariableDeclaration(this.#e.keyParameter)],V.NodeFlags.Const),this.#e.paramsArgument,a.createBlock([dr(this.#e.pathParameter,P(this.#e.pathParameter,T("replace"))(Tt(":",[this.#e.keyParameter]),Te([],a.createBlock([a.createExpressionStatement(a.createDeleteExpression(a.createElementAccessExpression(this.#e.restConst,this.#e.keyParameter))),a.createReturnStatement(a.createElementAccessExpression(this.#e.paramsArgument,this.#e.keyParameter))]))))])),a.createReturnStatement(a.createAsExpression(a.createArrayLiteralExpression([this.#e.pathParameter,this.#e.restConst]),f("const")))])));#t=()=>ir(this.#e.provideMethod,Le({[this.#e.requestParameter.text]:"K",[this.#e.paramsArgument.text]:q(this.interfaces.input,"K"),[this.#e.ctxArgument.text]:{optional:!0,type:"T"}}),[N(nr(this.#e.methodParameter,this.#e.pathParameter),P(this.#e.parseRequestFn)(this.#e.requestParameter)),a.createReturnStatement(P(a.createThis(),this.#e.implementationArgument)(this.#e.methodParameter,a.createSpreadElement(P(this.#e.substituteFn)(this.#e.pathParameter,this.#e.paramsArgument)),this.#e.ctxArgument))],{typeParams:{K:this.requestType.name},returns:wt(q(this.interfaces.response,"K"))});makeClientClass=t=>ar(t,[tr([Pt(this.#e.implementationArgument,{type:f(this.#e.implementationType,["T"]),mod:Qe.protectedReadonly,init:this.#e.defaultImplementationConst})]),this.#t()],{typeParams:["T"]});#r=t=>Tt("?",[Be(URLSearchParams.name,t)]);#o=()=>Be(URL.name,Tt("",[this.#e.pathParameter],[this.#e.searchParamsConst]),O(this.serverUrl));makeDefaultImplementation=()=>{let t=a.createPropertyAssignment(T("method"),P(this.#e.methodParameter,T("toUpperCase"))()),r=a.createPropertyAssignment(T("headers"),Xe(this.#e.hasBodyConst,a.createObjectLiteralExpression([a.createPropertyAssignment(O("Content-Type"),O(C.json))]),this.#e.undefinedValue)),o=a.createPropertyAssignment(T("body"),Xe(this.#e.hasBodyConst,P(JSON[Symbol.toStringTag],T("stringify"))(this.#e.paramsArgument),this.#e.undefinedValue)),n=N(this.#e.responseConst,a.createAwaitExpression(P(fetch.name)(this.#o(),a.createObjectLiteralExpression([t,r,o])))),s=N(this.#e.hasBodyConst,a.createLogicalNot(P(a.createArrayLiteralExpression([O("get"),O("head"),O("delete")]),T("includes"))(this.#e.methodParameter))),i=N(this.#e.searchParamsConst,Xe(this.#e.hasBodyConst,O(""),this.#r(this.#e.paramsArgument))),p=N(this.#e.contentTypeConst,P(this.#e.responseConst,T("headers"),T("get"))(O("content-type"))),d=a.createIfStatement(a.createPrefixUnaryExpression(V.SyntaxKind.ExclamationToken,this.#e.contentTypeConst),a.createReturnStatement()),c=N(this.#e.isJsonConst,P(this.#e.contentTypeConst,T("startsWith"))(O(C.json))),m=a.createReturnStatement(P(this.#e.responseConst,Xe(this.#e.isJsonConst,O(T("json")),O(T("text"))))());return N(this.#e.defaultImplementationConst,Te([this.#e.methodParameter,this.#e.pathParameter,this.#e.paramsArgument],a.createBlock([s,i,n,p,d,c,m]),{isAsync:!0}),{type:this.#e.implementationType})};#n=()=>tr(Le({request:"K",params:q(this.interfaces.input,"K")}),[N(nr(this.#e.pathParameter,this.#e.restConst),P(this.#e.substituteFn)(a.createElementAccessExpression(P(this.#e.parseRequestFn)(this.#e.requestParameter),O(1)),this.#e.paramsArgument)),N(this.#e.searchParamsConst,this.#r(this.#e.restConst)),dr(a.createPropertyAccessExpression(a.createThis(),this.#e.sourceProp),Be("EventSource",this.#o()))]);#s=t=>a.createTypeLiteralNode([Oe(T("event"),t)]);#i=()=>ir(this.#e.onMethod,Le({[this.#e.eventParameter.text]:"E",[this.#e.handlerParameter.text]:mr({[this.#e.dataParameter.text]:q(Et("R",or(this.#s("E"))),L(T("data")))},Mo(V.SyntaxKind.VoidKeyword))}),[a.createExpressionStatement(P(a.createThis(),this.#e.sourceProp,T("addEventListener"))(this.#e.eventParameter,Te([this.#e.msgParameter],P(this.#e.handlerParameter)(P(JSON[Symbol.toStringTag],T("parse"))(a.createPropertyAccessExpression(a.createParenthesizedExpression(a.createAsExpression(this.#e.msgParameter,f(MessageEvent.name))),T("data"))))))),a.createReturnStatement(a.createThis())],{typeParams:{E:q("R",L(T("event")))}});makeSubscriptionClass=t=>ar(t,[No(this.#e.sourceProp,"EventSource"),this.#n(),this.#i()],{typeParams:{K:Et(this.requestType.name,a.createTemplateLiteralType(a.createTemplateHead("get "),[a.createTemplateLiteralTypeSpan(f(V.SyntaxKind.StringKeyword),a.createTemplateTail(""))])),R:Et(q(this.interfaces.positive,"K"),or(this.#s(V.SyntaxKind.StringKeyword)))}});makeUsageStatements=(t,r)=>[N(this.#e.clientConst,Be(t)),P(this.#e.clientConst,this.#e.provideMethod)(O("get /v1/user/retrieve"),a.createObjectLiteralExpression([a.createPropertyAssignment("id",O("10"))])),P(Be(r,O("get /v1/events/stream"),a.createObjectLiteralExpression()),this.#e.onMethod)(O("time"),Te(["time"],a.createBlock([])))]};import*as k from"ramda";import x from"typescript";import{globalRegistry as Ts}from"zod";var lr=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let s=G(e),i=s&&s in r?r[s]:r[e._zod.def.type],d=i?i(e,{...n,next:m=>lr(m,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),c=t&&t(e,{prev:d,...n});return c?{...d,...c}:d};var{factory:$}=x,Ps={[x.SyntaxKind.AnyKeyword]:"",[x.SyntaxKind.BigIntKeyword]:BigInt(0),[x.SyntaxKind.BooleanKeyword]:!1,[x.SyntaxKind.NumberKeyword]:0,[x.SyntaxKind.ObjectKeyword]:{},[x.SyntaxKind.StringKeyword]:"",[x.SyntaxKind.UndefinedKeyword]:void 0},ur={name:k.path(["name","text"]),type:k.path(["type"]),optional:k.path(["questionToken"])},ws=({_zod:{def:e}})=>{let t=e.values.map(r=>r===void 0?f(x.SyntaxKind.UndefinedKeyword):L(r));return t.length===1?t[0]:_(t)},Cs=({_zod:{def:e}},{next:t})=>{let r=[...e.parts],o=()=>{let i="";for(;r.length;){let p=r.shift();if(re(p)){r.unshift(p);break}i+=p??""}return i},n=$.createTemplateHead(o()),s=[];for(;r.length;){let i=t(r.shift()),p=o(),d=r.length?$.createTemplateMiddle:$.createTemplateTail;s.push($.createTemplateLiteralTypeSpan(i,d(p)))}return s.length?$.createTemplateLiteralType(n,s):L(n.text)},Es=(e,{isResponse:t,next:r,makeAlias:o})=>{let n=()=>{let s=Object.entries(e._zod.def.shape).map(([i,p])=>{let{description:d,deprecated:c}=Ts.get(p)||{};return Oe(i,r(p),{comment:d,isDeprecated:c,isOptional:(t?p._zod.optout:p._zod.optin)==="optional"})});return $.createTypeLiteralNode(s)};return kr(e,{io:t?"output":"input"})?o(e,n):n()},ks=({_zod:{def:e}},{next:t})=>$.createArrayTypeNode(t(e.element)),Is=({_zod:{def:e}})=>_(Object.values(e.entries).map(L)),vs=({_zod:{def:e}},{next:t})=>_(e.options.map(t)),As=e=>Ps?.[e.kind],zs=({_zod:{def:e}},{next:t})=>_([t(e.innerType),L(null)]),Ns=({_zod:{def:e}},{next:t})=>$.createTupleTypeNode(e.items.map(t).concat(e.rest===null?[]:$.createRestTypeNode(t(e.rest)))),Ms=({_zod:{def:e}},{next:t})=>f("Record",[e.keyType,e.valueType].map(t)),js=k.tryCatch(e=>{if(!e.every(x.isTypeLiteralNode))throw new Error("Not objects");let t=k.chain(k.prop("members"),e),r=k.uniqWith((...o)=>{if(!k.eqBy(ur.name,...o))return!1;if(k.both(k.eqBy(ur.type),k.eqBy(ur.optional))(...o))return!0;throw new Error("Has conflicting prop")},t);return $.createTypeLiteralNode(r)},(e,t)=>$.createIntersectionTypeNode(t)),Ls=({_zod:{def:e}},{next:t})=>js([e.left,e.right].map(t)),F=e=>()=>f(e),et=({_zod:{def:e}},{next:t})=>t(e.innerType),Lo=e=>f(e?x.SyntaxKind.UnknownKeyword:x.SyntaxKind.AnyKeyword),Bs=({_zod:{def:e}},{next:t,isResponse:r})=>{let o=e[r?"out":"in"],n=e[r?"in":"out"];if(!re(o,"transform"))return t(o);let s=t(n),i=ct(o,As(s)),p={number:x.SyntaxKind.NumberKeyword,bigint:x.SyntaxKind.BigIntKeyword,boolean:x.SyntaxKind.BooleanKeyword,string:x.SyntaxKind.StringKeyword,undefined:x.SyntaxKind.UndefinedKeyword,object:x.SyntaxKind.ObjectKeyword};return f(i&&p[i]||Lo(r))},Hs=()=>L(null),Ks=({_zod:{def:e}},{makeAlias:t,next:r})=>t(e.getter,()=>r(e.getter())),qs=()=>f("Buffer"),Fs=(e,{next:t})=>t(e._zod.def.shape.raw),$s={string:F(x.SyntaxKind.StringKeyword),number:F(x.SyntaxKind.NumberKeyword),bigint:F(x.SyntaxKind.BigIntKeyword),boolean:F(x.SyntaxKind.BooleanKeyword),any:F(x.SyntaxKind.AnyKeyword),undefined:F(x.SyntaxKind.UndefinedKeyword),[ye]:F(x.SyntaxKind.StringKeyword),[he]:F(x.SyntaxKind.StringKeyword),never:F(x.SyntaxKind.NeverKeyword),void:F(x.SyntaxKind.UndefinedKeyword),unknown:F(x.SyntaxKind.UnknownKeyword),null:Hs,array:ks,tuple:Ns,record:Ms,object:Es,literal:ws,template_literal:Cs,intersection:Ls,union:vs,default:et,enum:Is,optional:et,nonoptional:et,nullable:zs,catch:et,pipe:Bs,lazy:Ks,readonly:et,[fe]:qs,[H]:Fs},fr=(e,{brandHandling:t,ctx:r})=>lr(e,{rules:{...t,...$s},onMissing:({},{isResponse:o})=>Lo(o),ctx:r});var yr=class extends kt{#e=[this.someOfType];#t=new Map;#r=[];#o(t,r){let o=this.#t.get(t)?.name?.text;if(!o){o=`Type${this.#t.size+1}`;let n=L(null);this.#t.set(t,J(o,n)),this.#t.set(t,J(o,r()))}return f(o)}constructor({routing:t,brandHandling:r,variant:o="client",clientClassName:n="Client",subscriptionClassName:s="Subscription",serverUrl:i="https://example.com",noContent:p=Zs.undefined()}){super(i);let d={makeAlias:this.#o.bind(this)},c={brandHandling:r,ctx:{...d,isResponse:!1}},m={brandHandling:r,ctx:{...d,isResponse:!0}};je({routing:t,onEndpoint:gt((g,h,w)=>{let I=oe.bind(null,g,h),{isDeprecated:M,inputSchema:b,tags:v}=w,A=`${g} ${h}`,B=J(I("input"),fr(b,c),{comment:A});this.#e.push(B);let z=Ae.reduce((tt,pe)=>{let rt=w.getResponses(pe),ot=Bo.chain(([vt,{schema:At,mimeTypes:ee,statusCodes:ce}])=>{let zt=dt(g,ee),st=J(I(pe,"variant",`${vt+1}`),fr(zt?At:p,m),{comment:A});return this.#e.push(st),ce.map(it=>Oe(it,st.name))},Array.from(rt.entries())),nt=Ct(I(pe,"response","variants"),ot,{comment:A});return this.#e.push(nt),Object.assign(tt,{[pe]:nt})},{});this.paths.add(h);let X=L(A),Pe={input:f(B.name),positive:this.someOf(z.positive),negative:this.someOf(z.negative),response:_([q(this.interfaces.positive,X),q(this.interfaces.negative,X)]),encoded:a.createIntersectionTypeNode([f(z.positive.name),f(z.negative.name)])};this.registry.set(A,{isDeprecated:M,store:Pe}),this.tags.set(A,v)})}),this.#e.unshift(...this.#t.values()),this.#e.push(this.makePathType(),this.methodType,...this.makePublicInterfaces(),this.requestType),o!=="types"&&(this.#e.push(this.makeEndpointTags(),this.makeParseRequestFn(),this.makeSubstituteFn(),this.makeImplementationType(),this.makeDefaultImplementation(),this.makeClientClass(n),this.makeSubscriptionClass(s)),this.#r.push(...this.makeUsageStatements(n,s)))}#n(t){return this.#r.length?this.#r.map(r=>typeof r=="string"?r:Xt(r,t)).join(`
|
|
19
19
|
`):void 0}print(t){let r=this.#n(t),o=r&&It.addSyntheticLeadingComment(It.addSyntheticLeadingComment(a.createEmptyStatement(),It.SyntaxKind.SingleLineCommentTrivia," Usage example:"),It.SyntaxKind.MultiLineCommentTrivia,`
|
|
20
20
|
${r}`);return this.#e.concat(o||[]).map((n,s)=>Xt(n,s<this.#e.length?t:{...t,omitTrailingSemicolon:!0})).join(`
|
|
21
21
|
|
|
22
|
-
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await Ne("prettier")).format;o=p=>i(p,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};import{z as He}from"zod";var Ko=(e,t)=>He.object({data:t,event:He.literal(e),id:He.string().optional(),retry:He.int().positive().optional()}),
|
|
23
|
-
`)).parse({event:t,data:r}),
|
|
22
|
+
`)}async printFormatted({printerOptions:t,format:r}={}){let o=r;if(!o)try{let i=(await Ne("prettier")).format;o=p=>i(p,{filepath:"client.ts"})}catch{}let n=this.#n(t);this.#r=n&&o?[await o(n)]:this.#r;let s=this.print(t);return o?o(s):s}};import{z as He}from"zod";var Ko=(e,t)=>He.object({data:t,event:He.literal(e),id:He.string().optional(),retry:He.int().positive().optional()}),Ds=(e,t,r)=>Ko(String(t),e[t]).transform(o=>[`event: ${o.event}`,`data: ${JSON.stringify(o.data)}`,"",""].join(`
|
|
23
|
+
`)).parse({event:t,data:r}),Us=1e4,Ho=e=>e.headersSent||e.writeHead(200,{connection:"keep-alive","content-type":C.sse,"cache-control":"no-cache"}),_s=e=>new D({handler:async({response:t})=>setTimeout(()=>Ho(t),Us)&&{isClosed:()=>t.writableEnded||t.closed,emit:(r,o)=>{Ho(t),t.write(Ds(e,r,o),"utf-8"),t.flush?.()}}}),Js=e=>new Se({positive:()=>{let[t,...r]=Object.entries(e).map(([o,n])=>Ko(o,n));return{mimeType:C.sse,schema:r.length?He.discriminatedUnion("event",[t,...r]):t}},negative:{mimeType:"text/plain",schema:He.string()},handler:async({response:t,error:r,logger:o,request:n,input:s})=>{if(r){let i=Ee(r);Ue(i,o,n,s),t.headersSent||t.status(i.statusCode).type("text/plain").write(xe(i),"utf-8")}t.end()}}),hr=class extends Re{constructor(t){super(Js(t)),this.middlewares=[_s(t)]}};var Vs={dateIn:Sr,dateOut:br,form:Or,upload:Tr,raw:wr,buffer:mt};export{Ve as BuiltinLogger,Ge as DependsOnMethod,Yt as Documentation,Y as DocumentationError,Re as EndpointsFactory,hr as EventStreamFactory,Q as InputValidationError,yr as Integration,D as Middleware,Ze as MissingPeerError,$e as OutputValidationError,Se as ResultHandler,ge as RoutingError,We as ServeStatic,ln as arrayEndpointsFactory,$t as arrayResultHandler,qn as attachRouting,Jo as createConfig,Fn as createServer,mn as defaultEndpointsFactory,be as defaultResultHandler,Ee as ensureHttpError,Vs as ez,me as getMessageFromError,gs as testEndpoint,xs as testMiddleware};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "express-zod-api",
|
|
3
|
-
"version": "25.0.0-beta.
|
|
3
|
+
"version": "25.0.0-beta.7",
|
|
4
4
|
"description": "A Typescript framework to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
"@types/express-fileupload": "^1.5.1",
|
|
80
80
|
"@types/http-errors": "^2.0.5",
|
|
81
81
|
"@types/node-forge": "^1.3.11",
|
|
82
|
-
"@types/ramda": "^0.
|
|
82
|
+
"@types/ramda": "^0.31.0",
|
|
83
83
|
"@types/semver": "^7.7.0",
|
|
84
84
|
"camelize-ts": "^3.0.0",
|
|
85
85
|
"compression": "^1.8.0",
|