express-zod-api 20.14.0 → 20.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  ## Version 20
4
4
 
5
+ ### v20.14.1
6
+
7
+ - `node-mocks-http` version is `^1.16.1`:
8
+ - This deduplicates the `@types/express` dependency to the version installed in your project;
9
+ - This fix is an addition to the support of Express 5 (v20.10.0) and its types (v20.14.0).
10
+
5
11
  ### v20.14.0
6
12
 
7
13
  - Enabling usage of recently released `@types/express@^5.0.0`:
@@ -57,7 +63,7 @@ createConfig({
57
63
 
58
64
  ### v20.9.0
59
65
 
60
- - `openapi3-ts` vesion is 4.4.0:
66
+ - `openapi3-ts` version is 4.4.0:
61
67
  - Feat: `Documentation::getSpecAsYaml()` accepts the same options as `yaml.stringify`.
62
68
 
63
69
  ### v20.8.0
@@ -605,7 +611,7 @@ const resultHandlerWithCleanup = createResultHandler({
605
611
 
606
612
  ### v18.6.0
607
613
 
608
- - Feat: Supporting async functon as an argument for `EndpointsFactory::addOptions()`:
614
+ - Feat: Supporting async function as an argument for `EndpointsFactory::addOptions()`:
609
615
  - I realized that it does not make sense for `.addOptions` just to proxy the static data;
610
616
  - In case your options are static you can just `import` the corresponding `const` instead;
611
617
  - Static options are deprecated and its support will be removed in v19.
@@ -637,7 +643,7 @@ const endpointsFactory = defaultEndpointsFactory.addOptions(async () => {
637
643
  - ~~`withMeta()`~~ was introduced in version 2.10.0, because I didn't want to alter Zod's prototypes;
638
644
  - However, the [new information](https://github.com/colinhacks/zod/pull/3445#issuecomment-2091463120) arrived
639
645
  recently from the author of Zod on that matter;
640
- - It turned out that altering Zod's prototypes is exatly the recommended approach for extending its functionality;
646
+ - It turned out that altering Zod's prototypes is exactly the recommended approach for extending its functionality;
641
647
  - Therefore `express-zod-api` from now on acts as a plugin for Zod, adding the `.example()` and `.label()` methods to
642
648
  its prototypes that were previously available only after wrapping the schema in ~~`withMeta()`~~.
643
649
 
@@ -970,7 +976,7 @@ export const config = createConfig({
970
976
  - Refinment methods of `ez.file()` removed;
971
977
  - Minimum version of `vitest` supported is 1.0.4.
972
978
  - How to migrate confidently:
973
- - If you're using refinment methods of `ez.file()`:
979
+ - If you're using refinement methods of `ez.file()`:
974
980
  - Replace ~~`ez.file().string()`~~ to `ez.file("string")`;
975
981
  - Replace ~~`ez.file().buffer()`~~ to `ez.file("buffer")`;
976
982
  - Replace ~~`ez.file().base64()`~~ to `ez.file("base64")`;
@@ -1018,7 +1024,7 @@ after:
1018
1024
  - This version relies on `inspect()` method of `node:util` instead, for serializing objects in all cases.
1019
1025
  - When the `level` is set to `debug` the inspected objects will be pretty printed.
1020
1026
  - When the `level` is set to `warn` the inspected objects will be serialized in one line.
1021
- - Additionaly, new option `depth` added to `SimplifiedWinstonConfig` that can be `number | null` being `2` by default.
1027
+ - Additionally, new option `depth` added to `SimplifiedWinstonConfig` that can be `number | null` being `2` by default.
1022
1028
  - The option controls how deeply the objects should be inspected, serialized and printed.
1023
1029
  - It can be set to `null` or `Infinity` for unlimited depth.
1024
1030
 
@@ -1347,7 +1353,7 @@ securitySchemes:
1347
1353
  - Switching to [OpenAPI 3.1](https://swagger.io/specification/) for generating better Documentation for your API.
1348
1354
  - Consider [the new UI](https://editor-next.swagger.io/) for exploring the produced documentation.
1349
1355
  - Improved way of configuring descriptions and naming of the generated documentation components:
1350
- - Intoroducing the new option `descriptions` holding several formatting functions.
1356
+ - Introducing the new option `descriptions` holding several formatting functions.
1351
1357
  - Ability to generate formatted typescript client using the new async method `printFormatted` of the `Integration`
1352
1358
  class when the `prettier` package is installed (detects automatically).
1353
1359
  - Ability to supply your own typescript formatting function into that new method.
@@ -1432,7 +1438,7 @@ operationId:
1432
1438
  - Transitioned from an exclusive approach to the inclusive one:
1433
1439
  - Introducing the list of `files` included into the distribution (instead of ignoring redundant ones).
1434
1440
  - Stable testing environment:
1435
- - Inclusive, stable and extendible `tsconfig.json` files;
1441
+ - Inclusive, stable and extensible `tsconfig.json` files;
1436
1442
  - Stable `package.json` for integration, ESM and compatibility tests;
1437
1443
  - Dedicated environment for Issue #952 test.
1438
1444
  - Simplified development commands.
@@ -1526,7 +1532,7 @@ logger.info("Payload", {});
1526
1532
 
1527
1533
  ### v14.2.4
1528
1534
 
1529
- - Fixed internal logging format when primivite are supplied as a second argument to the logger methods.
1535
+ - Fixed internal logging format when primitive are supplied as a second argument to the logger methods.
1530
1536
 
1531
1537
  ```typescript
1532
1538
  logger.info("Listening", 8090);
@@ -1690,7 +1696,7 @@ defaultEndpointsFactory.build({
1690
1696
  - Featuring the ability to customize the `operationId` in the generated documentation.
1691
1697
  - Using the new property of `EndpointsFactory::build()` method you can now override the value of the
1692
1698
  corresponding `operationId` of the endpoint in generated documentation.
1693
- - When using this feature, you must ensure the uniqness of the IDs you specified across your API endpoints.
1699
+ - When using this feature, you must ensure the uniqueness of the IDs you specified across your API endpoints.
1694
1700
  - The feature is implemented by [@john-schmitz](https://github.com/john-schmitz).
1695
1701
 
1696
1702
  ```typescript
@@ -1741,7 +1747,7 @@ defaultEndpointsFactory.build({
1741
1747
  - Instead of `MiddlewareDefinition` type use `createMiddleware()` method.
1742
1748
  - Instead of `ResultHandlerDefinition` type use `createResultHandler()` method.
1743
1749
  - Instead of the mentioned security types use the `security` property of the `createMiddleware()` argument.
1744
- - The issue 1182 is the continuation of the issue 952 "Infussicient exports" (for consumer's declaration).
1750
+ - The issue 1182 is the continuation of the issue 952 "Insufficient exports" (for consumer's declaration).
1745
1751
  - Found and reported by [@bobgubko](https://github.com/bobgubko)
1746
1752
 
1747
1753
  ### v12.0.2
package/README.md CHANGED
@@ -443,7 +443,7 @@ enough for the `output` schema if you're also aiming to [generate a valid docume
443
443
  because the transformations themselves do not contain schemas. Addressing this case, the library offers the `.remap()`
444
444
  method of the object schema, a part of the [Zod plugin](#zod-plugin), which under the hood, in addition to the
445
445
  transformation, also `.pipe()` the transformed object into a new object schema.
446
- Here is a recommended solution: it is importnant to use shallow transformations only.
446
+ Here is a recommended solution: it is important to use shallow transformations only.
447
447
 
448
448
  ```ts
449
449
  import camelize from "camelize-ts";
@@ -465,7 +465,7 @@ const endpoint = endpointsFactory.build({
465
465
  });
466
466
  ```
467
467
 
468
- The `.remap()` method can also accept an object with an explictly defined naming of your choice. The original keys
468
+ The `.remap()` method can also accept an object with an explicitly defined naming of your choice. The original keys
469
469
  missing in that object remain unchanged (partial mapping).
470
470
 
471
471
  ```ts
package/dist/index.cjs CHANGED
@@ -18,7 +18,7 @@ ${o}888${t}
18
18
  ${r}
19
19
  `.split(`
20
20
  `).map((l,c)=>a[c]?a[c](l):l).join(`
21
- `)};var Qr=e=>{e.startupLogo!==!1&&console.log(Vr());let t=e.errorHandler||be,r=Ir(e.logger)?e.logger:new Oe(e.logger);r.debug("Running","v20.14.0 (CJS)"),$r(r);let o=Br({rootLogger:r,config:e}),i={getChildLogger:qr(r),errorHandler:t},a=Dr(i),p=Hr(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},Jr=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=Qr(e);return Mt({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},Wr=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Qr(e),p=(0,ct.default)().disable("x-powered-by").use(a);if(e.server.compression){let u=await Ce("compression");p.use(u(typeof e.server.compression=="object"?e.server.compression:void 0))}let l={json:[e.server.jsonParser||ct.default.json()],raw:[e.server.rawParser||ct.default.raw(),Kr],upload:e.server.upload?await Fr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Mt({app:p,routing:t,getChildLogger:o,config:e,parsers:l}),p.use(i,n);let c=(u,x)=>u.listen(x,()=>r.info("Listening",x)),m=_r.default.createServer(p),y=e.https&&Yr.default.createServer(e.https.options,p);return e.gracefulShutdown&&Gr({servers:[m].concat(y||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(m,e.server.listen),httpsServer:y&&c(y,e.https?.listen)}};var xo=O(require("node:assert/strict"),1),bo=require("openapi3-ts/oas31"),So=require("ramda");var Q=O(require("node:assert/strict"),1),q=require("openapi3-ts/oas31"),d=require("ramda"),S=require("zod");var Ie=require("zod");var dt=e=>!isNaN(e.getTime());var qe=Symbol("DateIn"),Xr=()=>Ie.z.union([Ie.z.string().date(),Ie.z.string().datetime(),Ie.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ie.z.date().refine(dt)).brand(qe);var eo=require("zod");var $e=Symbol("DateOut"),to=()=>eo.z.date().refine(dt).transform(e=>e.toISOString()).brand($e);var pe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[h]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>pe(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),l=t&&t(e,{prev:p,...n});return l?{...p,...l}:p};var ro=50,no="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",on={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},so=/:([A-Za-z0-9_]+)/g,nn=e=>e.match(so)?.map(t=>t.slice(1))||[],io=e=>e.replace(so,t=>`{${t.slice(1)}}`),sn=({_def:e},{next:t})=>({...t(e.innerType),default:e[h]?.defaultLabel||e.defaultValue()}),an=({_def:{innerType:e}},{next:t})=>t(e),pn=()=>({format:"any"}),cn=({},e)=>((0,Q.default)(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),dn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},ln=({options:e},{next:t})=>({oneOf:e.map(t)}),mn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),un=e=>{let[t,r]=e.filter(q.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));(0,Q.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,d.mergeDeepWith)((n,i)=>Array.isArray(n)&&Array.isArray(i)?(0,d.concat)(n,i):n===i?i:Q.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,d.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=re(t.examples||[],r.examples||[],([n,i])=>(0,d.mergeDeepRight)(n,i))),o},fn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return un(o)}catch{}return{allOf:o}},yn=(e,{next:t})=>t(e.unwrap()),gn=(e,{next:t})=>t(e.unwrap()),hn=(e,{next:t})=>{let r=t(e.unwrap());return(0,q.isSchemaObject)(r)&&(r.type=po(r)),r},ao=e=>{let t=(0,d.toLower)((0,d.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},oo=e=>({type:ao(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),xn=({value:e})=>({type:ao(e),const:e}),bn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Ue(p)?p instanceof S.z.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=lt(e,r)),i.length&&(a.required=i),a},Sn=()=>({type:"null"}),Tn=({},e)=>((0,Q.default)(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:no}}),On=({},e)=>((0,Q.default)(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:no}}),Rn=({},e)=>Q.default.fail(new z({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),An=()=>({type:"boolean"}),Pn=()=>({type:"integer",format:"bigint"}),Cn=e=>e.every(t=>t instanceof S.z.ZodLiteral),In=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.z.ZodEnum||e instanceof S.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=lt(S.z.object((0,d.fromPairs)((0,d.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof S.z.ZodLiteral)return{type:"object",properties:lt(S.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.z.ZodUnion&&Cn(e.options)){let o=(0,d.map)(i=>`${i.value}`,e.options),n=(0,d.fromPairs)((0,d.xprod)(o,[t]));return{type:"object",properties:lt(S.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},zn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},wn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),En=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:l,isEmoji:c,isDatetime:m,_def:{checks:y}})=>{let u=y.find(C=>C.kind==="regex"),x=y.find(C=>C.kind==="datetime"),j=u?u.regex:x?x.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,T={type:"string"},M={"date-time":m,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:l,emoji:c};for(let C in M)if(M[C]){T.format=C;break}return r!==null&&(T.minLength=r),o!==null&&(T.maxLength=o),j&&(T.pattern=j.source),T},Zn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(y=>y.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(y=>y.kind==="max"),l=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=i:m.exclusiveMinimum=i,c?m.maximum=l:m.exclusiveMaximum=l,m},lt=({shape:e},t)=>(0,d.map)(t,e),vn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return on?.[t]},po=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},jn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,q.isSchemaObject)(o)){let i=Xe(e,vn(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.z.any())}if(!t&&n.type==="preprocess"&&(0,q.isSchemaObject)(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},Ln=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Nn=(e,{next:t})=>t(e.unwrap()),kn=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},Mn=(e,{next:t})=>t(e.unwrap().shape.raw),co=e=>e.length?(0,d.fromPairs)((0,d.zip)((0,d.range)(1,e.length+1).map(t=>`example${t}`),(0,d.map)((0,d.objOf)("value"),e))):void 0,lo=(e,t,r=[])=>(0,d.pipe)(K,(0,d.map)((0,d.when)(o=>(0,d.type)(o)==="Object",(0,d.omit)(r))),co)({schema:e,variant:t?"parsed":"original",validate:!0}),Un=(e,t)=>(0,d.pipe)(K,(0,d.filter)((0,d.has)(t)),(0,d.pluck)(t),co)({schema:e,variant:"original",validate:!0}),ce=e=>e instanceof S.z.ZodObject?e:e instanceof S.z.ZodBranded?ce(e.unwrap()):e instanceof S.z.ZodUnion||e instanceof S.z.ZodDiscriminatedUnion?e.options.map(t=>ce(t)).reduce((t,r)=>t.merge(r.partial()),S.z.object({})):e instanceof S.z.ZodEffects?ce(e._def.schema):e instanceof S.z.ZodPipeline?ce(e._def.in):ce(e._def.left).merge(ce(e._def.right)),mo=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:l,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=ce(r),y=nn(e),u=o.includes("query"),x=o.includes("params"),j=o.includes("headers"),T=b=>x&&y.includes(b),M=b=>j&&At(b);return Object.keys(m).map(b=>({name:b,location:T(b)?"path":M(b)?"header":u?"query":void 0})).filter(b=>b.location!==void 0).map(({name:b,location:Ze})=>{let G=pe(m[b],{rules:{...l,...Ht},onEach:Dt,onMissing:Ft,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),X=p==="components"?a(N(c,b),G):G;return{name:b,in:Ze,required:!m[b].isOptional(),description:G.description||c,schema:X,examples:Un(r,b)}})},Ht={ZodString:En,ZodNumber:Zn,ZodBigInt:Pn,ZodBoolean:An,ZodNull:Sn,ZodArray:zn,ZodTuple:wn,ZodRecord:In,ZodObject:bn,ZodLiteral:xn,ZodIntersection:fn,ZodUnion:ln,ZodAny:pn,ZodDefault:sn,ZodEnum:oo,ZodNativeEnum:oo,ZodEffects:jn,ZodOptional:yn,ZodNullable:hn,ZodDiscriminatedUnion:mn,ZodBranded:Nn,ZodDate:Rn,ZodCatch:an,ZodPipeline:Ln,ZodLazy:kn,ZodReadonly:gn,[Y]:dn,[De]:cn,[$e]:On,[qe]:Tn,[se]:Mn},Dt=(e,{isResponse:t,prev:r})=>{if((0,q.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof S.z.ZodLazy,i=r.type!==void 0,a=t&&Ue(e),p=!n&&i&&!a&&e.isNullable(),l=n?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=po(r)),l.length&&(c.examples=l.slice()),c},Ft=(e,t)=>Q.default.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Ut=(e,t)=>{if((0,q.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,d.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,d.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Ut(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Ut(o,t))),r},uo=e=>(0,q.isReferenceObject)(e)?e:(0,d.omit)(["examples"],e),fo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:l,hasMultipleStatusCodes:c,statusCode:m,brandHandling:y,description:u=`${e.toUpperCase()} ${t} ${It(n)} response ${c?m:""}`.trim()})=>{let x=uo(pe(r,{rules:{...y,...Ht},onEach:Dt,onMissing:Ft,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),j={schema:l==="components"?p(N(u),x):x,examples:lo(r,!0)};return{description:u,content:(0,d.fromPairs)((0,d.xprod)(o,[j]))}},Hn=()=>({type:"http",scheme:"basic"}),Dn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Fn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Kn=({name:e})=>({type:"apiKey",in:"header",name:e}),Bn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),qn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),$n=({flows:e={}})=>({type:"oauth2",flows:(0,d.map)(t=>({...t,scopes:t.scopes||{}}),(0,d.reject)(d.isNil,e))}),yo=(e,t)=>{let r={basic:Hn,bearer:Dn,input:Fn,header:Kn,cookie:Bn,openid:qn,oauth2:$n};return nt(e,o=>r[o.type](o,t))},mt=e=>"or"in e?e.or.map(t=>"and"in t?(0,d.mergeAll)((0,d.map)(({name:r,scopes:o})=>(0,d.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?mt(Et(e)):mt({or:[e]}),go=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:l,paramNames:c,description:m=`${e.toUpperCase()} ${t} Request body`})=>{let y=uo(Ut(pe(r,{rules:{...l,...Ht},onEach:Dt,onMissing:Ft,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),u={schema:p==="components"?a(N(m),y):y,examples:lo(r,!1,c)};return{description:m,content:(0,d.fromPairs)((0,d.xprod)(o,[u]))}},ho=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Kt=e=>e.length<=ro?e:e.slice(0,ro-1)+"\u2026";var ut=class extends bo.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||N(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&xo.default.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:l=!0,composition:c="inline",serializer:m=We}){super(),this.addInfo({title:o,version:n});for(let u of typeof i=="string"?[i]:i)this.addServer({url:u});ae({routing:t,onEndpoint:(u,x,j)=>{let T=j,M={path:x,method:T,endpoint:u,composition:c,serializer:m,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[C,b]=["short","long"].map(u.getDescription.bind(u)),Ze=C?Kt(C):l&&b?Kt(b):void 0,G=u.getTags(),X=r.inputSources?.[T]||Ot[T],le=this.ensureUniqOperationId(x,T,u.getOperationId(T)),ve=mo({...M,inputSources:X,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:x,operationId:le})}),Ve={};for(let D of["positive","negative"]){let ee=u.getResponses(D);for(let{mimeTypes:je,schema:R,statusCodes:A}of ee)for(let I of A)Ve[I]=fo({...M,variant:D,schema:R,mimeTypes:je,statusCode:I,hasMultipleStatusCodes:ee.length>1||A.length>1,description:a?.[`${D}Response`]?.call(null,{method:T,path:x,operationId:le,statusCode:I})})}let Tt=X.includes("body")?go({...M,paramNames:(0,So.pluck)("name",ve),schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:x,operationId:le})}):void 0,_e=mt(nt(yo(u.getSecurity(),X),D=>{let ee=this.ensureUniqSecuritySchemaName(D),je=["oauth2","openIdConnect"].includes(D.type)?u.getScopes().slice():[];return this.addSecurityScheme(ee,D),{name:ee,scopes:je}}));this.addPath(io(x),{[T]:{operationId:le,summary:Ze,description:b,tags:G.length>0?G:void 0,parameters:ve.length>0?ve:void 0,requestBody:Tt,security:_e.length>0?_e:void 0,responses:Ve}})}}),this.rootDoc.tags=r.tags?ho(r.tags):[]}};var ft=require("node-mocks-http"),Gn=e=>(0,ft.createRequest)({...e,headers:{"content-type":w.json,...e?.headers}}),Vn=e=>(0,ft.createResponse)(e),_n=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:o in Te?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Yn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Gn(e),i=Vn({req:n,...t});i.req=t?.req||n,n.res=i;let a=_n(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},To=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Yn(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}};var v=O(require("typescript"),1);var H=O(require("typescript"),1),ze=require("ramda"),s=H.default.factory,J=[s.createModifier(H.default.SyntaxKind.ExportKeyword)],Qn=[s.createModifier(H.default.SyntaxKind.AsyncKeyword)],Jn=[s.createModifier(H.default.SyntaxKind.PublicKeyword),s.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],Oo=[s.createModifier(H.default.SyntaxKind.ProtectedKeyword),s.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],Bt=s.createTemplateHead(""),we=s.createTemplateTail(""),qt=s.createTemplateMiddle(" "),$t=e=>s.createTemplateLiteralType(Bt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?we:qt))),Gt=$t(["M","P"]),yt=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),gt=(e,t)=>(0,ze.chain)(([r,o])=>[yt(s.createIdentifier(r),o,t)],(0,ze.toPairs)(e)),Vt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),Ro=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),Ao=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),W=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],H.default.NodeFlags.Const),_t=(e,t)=>s.createTypeAliasDeclaration(J,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),ht=(e,t)=>s.createTypeAliasDeclaration(J,e,void 0,t),Po=(e,t,r)=>s.createPropertyDeclaration(Jn,e,void 0,t,r),Co=(e,t,r)=>s.createClassDeclaration(J,e,void 0,void 0,[t,...r]),Io=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),zo=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(H.default.SyntaxKind.AnyKeyword)]),wo=(e,t,r)=>s.createInterfaceDeclaration(J,e,void 0,t,r),Wn=(0,ze.chain)(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),Eo=e=>Wn((0,ze.toPairs)(e)),Yt=(e,t,r)=>s.createArrowFunction(r?Qn:void 0,void 0,e.map(o=>yt(o)),void 0,void 0,t),Qt=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,gt({acc:void 0,key:void 0}),void 0,void 0,t),r]),Zo=(...e)=>`"${e.join(" ")}"`;var vo=["get","post","put","delete","patch"];var g=O(require("typescript"),1),bt=require("zod");var $=O(require("typescript"),1),{factory:xt}=$.default,Jt=(e,t)=>{$.default.addSyntheticLeadingComment(e,$.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ee=(e,t,r)=>{let o=xt.createTypeAliasDeclaration(void 0,xt.createIdentifier(t),void 0,e);return r&&Jt(o,r),o},Wt=(e,t)=>{let r=$.default.createSourceFile("print.ts","",$.default.ScriptTarget.Latest,!1,$.default.ScriptKind.TS);return $.default.createPrinter(t).printNode($.default.EmitHint.Unspecified,e,r)},Xn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,jo=e=>Xn.test(e)?xt.createIdentifier(e):xt.createStringLiteral(e);var{factory:f}=g.default,es={[g.default.SyntaxKind.AnyKeyword]:"",[g.default.SyntaxKind.BigIntKeyword]:BigInt(0),[g.default.SyntaxKind.BooleanKeyword]:!1,[g.default.SyntaxKind.NumberKeyword]:0,[g.default.SyntaxKind.ObjectKeyword]:{},[g.default.SyntaxKind.StringKeyword]:"",[g.default.SyntaxKind.UndefinedKeyword]:void 0},ts=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),rs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Ue(a)?a instanceof bt.z.ZodOptional:a.isOptional(),l=f.createPropertySignature(void 0,jo(i),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Jt(l,a.description),l});return f.createTypeLiteralNode(n)},os=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),ns=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),Lo=({options:e},{next:t})=>f.createUnionTypeNode(e.map(t)),ss=e=>es?.[e.kind],is=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Xe(e,ss(o)),i={number:g.default.SyntaxKind.NumberKeyword,bigint:g.default.SyntaxKind.BigIntKeyword,boolean:g.default.SyntaxKind.BooleanKeyword,string:g.default.SyntaxKind.StringKeyword,undefined:g.default.SyntaxKind.UndefinedKeyword,object:g.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(n&&i[n]||g.default.SyntaxKind.AnyKeyword)}return o},as=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),ps=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},cs=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),ds=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),ls=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),ms=({_def:e},{next:t})=>f.createIntersectionTypeNode([e.left,e.right].map(t)),us=({_def:e},{next:t})=>t(e.innerType),de=e=>()=>f.createKeywordTypeNode(e),fs=(e,{next:t})=>t(e.unwrap()),ys=(e,{next:t})=>t(e.unwrap()),gs=({_def:e},{next:t})=>t(e.innerType),hs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),xs=()=>f.createLiteralTypeNode(f.createNull()),bs=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,f.createLiteralTypeNode(f.createNull())),r(i,o(e)))},Ss=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),n=f.createUnionTypeNode([r,o]);return t instanceof bt.z.ZodString?r:t instanceof bt.z.ZodUnion?n:o},Ts=(e,{next:t})=>t(e.unwrap().shape.raw),Os={ZodString:de(g.default.SyntaxKind.StringKeyword),ZodNumber:de(g.default.SyntaxKind.NumberKeyword),ZodBigInt:de(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:de(g.default.SyntaxKind.BooleanKeyword),ZodAny:de(g.default.SyntaxKind.AnyKeyword),[qe]:de(g.default.SyntaxKind.StringKeyword),[$e]:de(g.default.SyntaxKind.StringKeyword),ZodNull:xs,ZodArray:os,ZodTuple:ds,ZodRecord:ls,ZodObject:rs,ZodLiteral:ts,ZodIntersection:ms,ZodUnion:Lo,ZodDefault:us,ZodEnum:ns,ZodNativeEnum:as,ZodEffects:is,ZodOptional:ps,ZodNullable:cs,ZodDiscriminatedUnion:Lo,ZodBranded:fs,ZodCatch:gs,ZodPipeline:hs,ZodLazy:bs,ZodReadonly:ys,[Y]:Ss,[se]:Ts},Ge=(e,{brandHandling:t,ctx:r})=>pe(e,{rules:{...t,...Os},onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),ctx:r});var St=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Ee(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=We,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){ae({routing:t,onEndpoint:(R,A,I)=>{let me={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},Le=N(I,A,"input"),Ne=Ge(R.getSchema("input"),{brandHandling:r,ctx:{...me,isResponse:!1}}),L=i?N(I,A,"positive.response"):void 0,Xt=R.getSchema("positive"),er=i?Ge(Xt,{brandHandling:r,ctx:{...me,isResponse:!0}}):void 0,ke=i?N(I,A,"negative.response"):void 0,tr=R.getSchema("negative"),rr=i?Ge(tr,{brandHandling:r,ctx:{...me,isResponse:!0}}):void 0,or=N(I,A,"response"),ko=L&&ke?s.createUnionTypeNode([s.createTypeReferenceNode(L),s.createTypeReferenceNode(ke)]):Ge(Xt.or(tr),{brandHandling:r,ctx:{...me,isResponse:!0}});this.program.push(Ee(Ne,Le)),er&&L&&this.program.push(Ee(er,L)),rr&&ke&&this.program.push(Ee(rr,ke)),this.program.push(Ee(ko,or)),I!=="options"&&(this.paths.push(A),this.registry.set({method:I,path:A},{input:Le,positive:L,negative:ke,response:or,isJson:R.getMimeTypes("positive").includes(w.json),tags:R.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(_t(this.ids.pathType,this.paths)),this.program.push(_t(this.ids.methodType,vo)),this.program.push(ht(this.ids.methodPathType,$t([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(v.default.SyntaxKind.ExtendsKeyword,[Vt(this.ids.methodPathType,v.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let l=[],c=[];for(let[{method:R,path:A},{isJson:I,tags:me,...Le}]of this.registry){let Ne=Zo(R,A);for(let L of this.interfaces)L.kind in Le&&L.props.push(Ao(Ne,Le[L.kind]));o!=="types"&&(I&&l.push(s.createPropertyAssignment(Ne,s.createTrue())),c.push(s.createPropertyAssignment(Ne,s.createArrayLiteralExpression(me.map(L=>s.createStringLiteral(L))))))}for(let{id:R,props:A}of this.interfaces)this.program.push(wo(R,p,A));if(o==="types")return;let m=s.createVariableStatement(J,W(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(l))),y=s.createVariableStatement(J,W(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),u=ht(this.ids.providerType,s.createFunctionTypeNode(Eo({M:this.ids.methodType,P:this.ids.pathType}),gt({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Gt)}),Io(this.ids.responseInterface,Gt))),x=ht(this.ids.implementationType,s.createFunctionTypeNode(void 0,gt({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(v.default.SyntaxKind.StringKeyword),params:Vt(v.default.SyntaxKind.StringKeyword,v.default.SyntaxKind.AnyKeyword)}),zo())),j=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,we)]),T=Qt(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[j,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),M=Qt(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[j]),v.default.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),C=Co(this.ids.clientClass,Ro([yt(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),Oo)]),[Po(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Yt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,M]),!0))]);this.program.push(m,y,u,x,C);let b=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ze=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(w.json))]),void 0,this.ids.undefinedValue)),G=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),X=s.createVariableStatement(void 0,W(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,we)]),s.createObjectLiteralExpression([b,Ze,G])])))),le=s.createVariableStatement(void 0,W(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ve=s.createVariableStatement(void 0,W(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),we)])))),[Ve,Tt]=["json","text"].map(R=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,R),void 0,void 0))),_e=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(Bt,[s.createTemplateSpan(this.ids.methodParameter,qt),s.createTemplateSpan(this.ids.pathParameter,we)]),v.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Ve])),D=s.createVariableStatement(J,W(this.ids.exampleImplementationConst,Yt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([le,ve,X,_e,Tt]),!0),s.createTypeReferenceNode(this.ids.implementationType))),ee=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),je=s.createVariableStatement(void 0,W(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(D,je,ee)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Wt(r,t)).join(`
21
+ `)};var Qr=e=>{e.startupLogo!==!1&&console.log(Vr());let t=e.errorHandler||be,r=Ir(e.logger)?e.logger:new Oe(e.logger);r.debug("Running","v20.14.1 (CJS)"),$r(r);let o=Br({rootLogger:r,config:e}),i={getChildLogger:qr(r),errorHandler:t},a=Dr(i),p=Hr(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},Jr=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=Qr(e);return Mt({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},Wr=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=Qr(e),p=(0,ct.default)().disable("x-powered-by").use(a);if(e.server.compression){let u=await Ce("compression");p.use(u(typeof e.server.compression=="object"?e.server.compression:void 0))}let l={json:[e.server.jsonParser||ct.default.json()],raw:[e.server.rawParser||ct.default.raw(),Kr],upload:e.server.upload?await Fr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Mt({app:p,routing:t,getChildLogger:o,config:e,parsers:l}),p.use(i,n);let c=(u,x)=>u.listen(x,()=>r.info("Listening",x)),m=_r.default.createServer(p),y=e.https&&Yr.default.createServer(e.https.options,p);return e.gracefulShutdown&&Gr({servers:[m].concat(y||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(m,e.server.listen),httpsServer:y&&c(y,e.https?.listen)}};var xo=O(require("node:assert/strict"),1),bo=require("openapi3-ts/oas31"),So=require("ramda");var Q=O(require("node:assert/strict"),1),q=require("openapi3-ts/oas31"),d=require("ramda"),S=require("zod");var Ie=require("zod");var dt=e=>!isNaN(e.getTime());var qe=Symbol("DateIn"),Xr=()=>Ie.z.union([Ie.z.string().date(),Ie.z.string().datetime(),Ie.z.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(Ie.z.date().refine(dt)).brand(qe);var eo=require("zod");var $e=Symbol("DateOut"),to=()=>eo.z.date().refine(dt).transform(e=>e.toISOString()).brand($e);var pe=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[h]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>pe(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),l=t&&t(e,{prev:p,...n});return l?{...p,...l}:p};var ro=50,no="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",on={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},so=/:([A-Za-z0-9_]+)/g,nn=e=>e.match(so)?.map(t=>t.slice(1))||[],io=e=>e.replace(so,t=>`{${t.slice(1)}}`),sn=({_def:e},{next:t})=>({...t(e.innerType),default:e[h]?.defaultLabel||e.defaultValue()}),an=({_def:{innerType:e}},{next:t})=>t(e),pn=()=>({format:"any"}),cn=({},e)=>((0,Q.default)(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),dn=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.z.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},ln=({options:e},{next:t})=>({oneOf:e.map(t)}),mn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),un=e=>{let[t,r]=e.filter(q.isSchemaObject).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));(0,Q.default)(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=(0,d.mergeDeepWith)((n,i)=>Array.isArray(n)&&Array.isArray(i)?(0,d.concat)(n,i):n===i?i:Q.default.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=(0,d.union)(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=re(t.examples||[],r.examples||[],([n,i])=>(0,d.mergeDeepRight)(n,i))),o},fn=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return un(o)}catch{}return{allOf:o}},yn=(e,{next:t})=>t(e.unwrap()),gn=(e,{next:t})=>t(e.unwrap()),hn=(e,{next:t})=>{let r=t(e.unwrap());return(0,q.isSchemaObject)(r)&&(r.type=po(r)),r},ao=e=>{let t=(0,d.toLower)((0,d.type)(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},oo=e=>({type:ao(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),xn=({value:e})=>({type:ao(e),const:e}),bn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Ue(p)?p instanceof S.z.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=lt(e,r)),i.length&&(a.required=i),a},Sn=()=>({type:"null"}),Tn=({},e)=>((0,Q.default)(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:no}}),On=({},e)=>((0,Q.default)(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:no}}),Rn=({},e)=>Q.default.fail(new z({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),An=()=>({type:"boolean"}),Pn=()=>({type:"integer",format:"bigint"}),Cn=e=>e.every(t=>t instanceof S.z.ZodLiteral),In=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.z.ZodEnum||e instanceof S.z.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=lt(S.z.object((0,d.fromPairs)((0,d.xprod)(o,[t]))),r),n.required=o),n}if(e instanceof S.z.ZodLiteral)return{type:"object",properties:lt(S.z.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.z.ZodUnion&&Cn(e.options)){let o=(0,d.map)(i=>`${i.value}`,e.options),n=(0,d.fromPairs)((0,d.xprod)(o,[t]));return{type:"object",properties:lt(S.z.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},zn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},wn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),En=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:l,isEmoji:c,isDatetime:m,_def:{checks:y}})=>{let u=y.find(C=>C.kind==="regex"),x=y.find(C=>C.kind==="datetime"),j=u?u.regex:x?x.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,T={type:"string"},M={"date-time":m,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:l,emoji:c};for(let C in M)if(M[C]){T.format=C;break}return r!==null&&(T.minLength=r),o!==null&&(T.maxLength=o),j&&(T.pattern=j.source),T},Zn=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(y=>y.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(y=>y.kind==="max"),l=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,m={type:e?"integer":"number",format:e?"int64":"double"};return a?m.minimum=i:m.exclusiveMinimum=i,c?m.maximum=l:m.exclusiveMaximum=l,m},lt=({shape:e},t)=>(0,d.map)(t,e),vn=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return on?.[t]},po=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},jn=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&(0,q.isSchemaObject)(o)){let i=Xe(e,vn(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.z.any())}if(!t&&n.type==="preprocess"&&(0,q.isSchemaObject)(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},Ln=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),Nn=(e,{next:t})=>t(e.unwrap()),kn=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},Mn=(e,{next:t})=>t(e.unwrap().shape.raw),co=e=>e.length?(0,d.fromPairs)((0,d.zip)((0,d.range)(1,e.length+1).map(t=>`example${t}`),(0,d.map)((0,d.objOf)("value"),e))):void 0,lo=(e,t,r=[])=>(0,d.pipe)(K,(0,d.map)((0,d.when)(o=>(0,d.type)(o)==="Object",(0,d.omit)(r))),co)({schema:e,variant:t?"parsed":"original",validate:!0}),Un=(e,t)=>(0,d.pipe)(K,(0,d.filter)((0,d.has)(t)),(0,d.pluck)(t),co)({schema:e,variant:"original",validate:!0}),ce=e=>e instanceof S.z.ZodObject?e:e instanceof S.z.ZodBranded?ce(e.unwrap()):e instanceof S.z.ZodUnion||e instanceof S.z.ZodDiscriminatedUnion?e.options.map(t=>ce(t)).reduce((t,r)=>t.merge(r.partial()),S.z.object({})):e instanceof S.z.ZodEffects?ce(e._def.schema):e instanceof S.z.ZodPipeline?ce(e._def.in):ce(e._def.left).merge(ce(e._def.right)),mo=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:l,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:m}=ce(r),y=nn(e),u=o.includes("query"),x=o.includes("params"),j=o.includes("headers"),T=b=>x&&y.includes(b),M=b=>j&&At(b);return Object.keys(m).map(b=>({name:b,location:T(b)?"path":M(b)?"header":u?"query":void 0})).filter(b=>b.location!==void 0).map(({name:b,location:Ze})=>{let G=pe(m[b],{rules:{...l,...Ht},onEach:Dt,onMissing:Ft,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),X=p==="components"?a(N(c,b),G):G;return{name:b,in:Ze,required:!m[b].isOptional(),description:G.description||c,schema:X,examples:Un(r,b)}})},Ht={ZodString:En,ZodNumber:Zn,ZodBigInt:Pn,ZodBoolean:An,ZodNull:Sn,ZodArray:zn,ZodTuple:wn,ZodRecord:In,ZodObject:bn,ZodLiteral:xn,ZodIntersection:fn,ZodUnion:ln,ZodAny:pn,ZodDefault:sn,ZodEnum:oo,ZodNativeEnum:oo,ZodEffects:jn,ZodOptional:yn,ZodNullable:hn,ZodDiscriminatedUnion:mn,ZodBranded:Nn,ZodDate:Rn,ZodCatch:an,ZodPipeline:Ln,ZodLazy:kn,ZodReadonly:gn,[Y]:dn,[De]:cn,[$e]:On,[qe]:Tn,[se]:Mn},Dt=(e,{isResponse:t,prev:r})=>{if((0,q.isReferenceObject)(r))return{};let{description:o}=e,n=e instanceof S.z.ZodLazy,i=r.type!==void 0,a=t&&Ue(e),p=!n&&i&&!a&&e.isNullable(),l=n?[]:K({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=po(r)),l.length&&(c.examples=l.slice()),c},Ft=(e,t)=>Q.default.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),Ut=(e,t)=>{if((0,q.isReferenceObject)(e))return e;let r={...e};return r.properties&&(r.properties=(0,d.omit)(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>(0,d.omit)(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>Ut(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>Ut(o,t))),r},uo=e=>(0,q.isReferenceObject)(e)?e:(0,d.omit)(["examples"],e),fo=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:l,hasMultipleStatusCodes:c,statusCode:m,brandHandling:y,description:u=`${e.toUpperCase()} ${t} ${It(n)} response ${c?m:""}`.trim()})=>{let x=uo(pe(r,{rules:{...y,...Ht},onEach:Dt,onMissing:Ft,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),j={schema:l==="components"?p(N(u),x):x,examples:lo(r,!0)};return{description:u,content:(0,d.fromPairs)((0,d.xprod)(o,[j]))}},Hn=()=>({type:"http",scheme:"basic"}),Dn=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},Fn=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},Kn=({name:e})=>({type:"apiKey",in:"header",name:e}),Bn=({name:e})=>({type:"apiKey",in:"cookie",name:e}),qn=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),$n=({flows:e={}})=>({type:"oauth2",flows:(0,d.map)(t=>({...t,scopes:t.scopes||{}}),(0,d.reject)(d.isNil,e))}),yo=(e,t)=>{let r={basic:Hn,bearer:Dn,input:Fn,header:Kn,cookie:Bn,openid:qn,oauth2:$n};return nt(e,o=>r[o.type](o,t))},mt=e=>"or"in e?e.or.map(t=>"and"in t?(0,d.mergeAll)((0,d.map)(({name:r,scopes:o})=>(0,d.objOf)(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?mt(Et(e)):mt({or:[e]}),go=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:l,paramNames:c,description:m=`${e.toUpperCase()} ${t} Request body`})=>{let y=uo(Ut(pe(r,{rules:{...l,...Ht},onEach:Dt,onMissing:Ft,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),u={schema:p==="components"?a(N(m),y):y,examples:lo(r,!1,c)};return{description:m,content:(0,d.fromPairs)((0,d.xprod)(o,[u]))}},ho=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),Kt=e=>e.length<=ro?e:e.slice(0,ro-1)+"\u2026";var ut=class extends bo.OpenApiBuilder{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||N(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&xo.default.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:l=!0,composition:c="inline",serializer:m=We}){super(),this.addInfo({title:o,version:n});for(let u of typeof i=="string"?[i]:i)this.addServer({url:u});ae({routing:t,onEndpoint:(u,x,j)=>{let T=j,M={path:x,method:T,endpoint:u,composition:c,serializer:m,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[C,b]=["short","long"].map(u.getDescription.bind(u)),Ze=C?Kt(C):l&&b?Kt(b):void 0,G=u.getTags(),X=r.inputSources?.[T]||Ot[T],le=this.ensureUniqOperationId(x,T,u.getOperationId(T)),ve=mo({...M,inputSources:X,schema:u.getSchema("input"),description:a?.requestParameter?.call(null,{method:T,path:x,operationId:le})}),Ve={};for(let D of["positive","negative"]){let ee=u.getResponses(D);for(let{mimeTypes:je,schema:R,statusCodes:A}of ee)for(let I of A)Ve[I]=fo({...M,variant:D,schema:R,mimeTypes:je,statusCode:I,hasMultipleStatusCodes:ee.length>1||A.length>1,description:a?.[`${D}Response`]?.call(null,{method:T,path:x,operationId:le,statusCode:I})})}let Tt=X.includes("body")?go({...M,paramNames:(0,So.pluck)("name",ve),schema:u.getSchema("input"),mimeTypes:u.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:T,path:x,operationId:le})}):void 0,_e=mt(nt(yo(u.getSecurity(),X),D=>{let ee=this.ensureUniqSecuritySchemaName(D),je=["oauth2","openIdConnect"].includes(D.type)?u.getScopes().slice():[];return this.addSecurityScheme(ee,D),{name:ee,scopes:je}}));this.addPath(io(x),{[T]:{operationId:le,summary:Ze,description:b,tags:G.length>0?G:void 0,parameters:ve.length>0?ve:void 0,requestBody:Tt,security:_e.length>0?_e:void 0,responses:Ve}})}}),this.rootDoc.tags=r.tags?ho(r.tags):[]}};var ft=require("node-mocks-http"),Gn=e=>(0,ft.createRequest)({...e,headers:{"content-type":w.json,...e?.headers}}),Vn=e=>(0,ft.createResponse)(e),_n=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:o in Te?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},Yn=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Gn(e),i=Vn({req:n,...t});i.req=t?.req||n,n.res=i;let a=_n(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},To=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=Yn(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}};var v=O(require("typescript"),1);var H=O(require("typescript"),1),ze=require("ramda"),s=H.default.factory,J=[s.createModifier(H.default.SyntaxKind.ExportKeyword)],Qn=[s.createModifier(H.default.SyntaxKind.AsyncKeyword)],Jn=[s.createModifier(H.default.SyntaxKind.PublicKeyword),s.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],Oo=[s.createModifier(H.default.SyntaxKind.ProtectedKeyword),s.createModifier(H.default.SyntaxKind.ReadonlyKeyword)],Bt=s.createTemplateHead(""),we=s.createTemplateTail(""),qt=s.createTemplateMiddle(" "),$t=e=>s.createTemplateLiteralType(Bt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?we:qt))),Gt=$t(["M","P"]),yt=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),gt=(e,t)=>(0,ze.chain)(([r,o])=>[yt(s.createIdentifier(r),o,t)],(0,ze.toPairs)(e)),Vt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),Ro=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),Ao=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),W=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],H.default.NodeFlags.Const),_t=(e,t)=>s.createTypeAliasDeclaration(J,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),ht=(e,t)=>s.createTypeAliasDeclaration(J,e,void 0,t),Po=(e,t,r)=>s.createPropertyDeclaration(Jn,e,void 0,t,r),Co=(e,t,r)=>s.createClassDeclaration(J,e,void 0,void 0,[t,...r]),Io=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),zo=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(H.default.SyntaxKind.AnyKeyword)]),wo=(e,t,r)=>s.createInterfaceDeclaration(J,e,void 0,t,r),Wn=(0,ze.chain)(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),Eo=e=>Wn((0,ze.toPairs)(e)),Yt=(e,t,r)=>s.createArrowFunction(r?Qn:void 0,void 0,e.map(o=>yt(o)),void 0,void 0,t),Qt=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,gt({acc:void 0,key:void 0}),void 0,void 0,t),r]),Zo=(...e)=>`"${e.join(" ")}"`;var vo=["get","post","put","delete","patch"];var g=O(require("typescript"),1),bt=require("zod");var $=O(require("typescript"),1),{factory:xt}=$.default,Jt=(e,t)=>{$.default.addSyntheticLeadingComment(e,$.default.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},Ee=(e,t,r)=>{let o=xt.createTypeAliasDeclaration(void 0,xt.createIdentifier(t),void 0,e);return r&&Jt(o,r),o},Wt=(e,t)=>{let r=$.default.createSourceFile("print.ts","",$.default.ScriptTarget.Latest,!1,$.default.ScriptKind.TS);return $.default.createPrinter(t).printNode($.default.EmitHint.Unspecified,e,r)},Xn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,jo=e=>Xn.test(e)?xt.createIdentifier(e):xt.createStringLiteral(e);var{factory:f}=g.default,es={[g.default.SyntaxKind.AnyKeyword]:"",[g.default.SyntaxKind.BigIntKeyword]:BigInt(0),[g.default.SyntaxKind.BooleanKeyword]:!1,[g.default.SyntaxKind.NumberKeyword]:0,[g.default.SyntaxKind.ObjectKeyword]:{},[g.default.SyntaxKind.StringKeyword]:"",[g.default.SyntaxKind.UndefinedKeyword]:void 0},ts=({value:e})=>f.createLiteralTypeNode(typeof e=="number"?f.createNumericLiteral(e):typeof e=="boolean"?e?f.createTrue():f.createFalse():f.createStringLiteral(e)),rs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Ue(a)?a instanceof bt.z.ZodOptional:a.isOptional(),l=f.createPropertySignature(void 0,jo(i),p&&o?f.createToken(g.default.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Jt(l,a.description),l});return f.createTypeLiteralNode(n)},os=({element:e},{next:t})=>f.createArrayTypeNode(t(e)),ns=({options:e})=>f.createUnionTypeNode(e.map(t=>f.createLiteralTypeNode(f.createStringLiteral(t)))),Lo=({options:e},{next:t})=>f.createUnionTypeNode(e.map(t)),ss=e=>es?.[e.kind],is=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Xe(e,ss(o)),i={number:g.default.SyntaxKind.NumberKeyword,bigint:g.default.SyntaxKind.BigIntKeyword,boolean:g.default.SyntaxKind.BooleanKeyword,string:g.default.SyntaxKind.StringKeyword,undefined:g.default.SyntaxKind.UndefinedKeyword,object:g.default.SyntaxKind.ObjectKeyword};return f.createKeywordTypeNode(n&&i[n]||g.default.SyntaxKind.AnyKeyword)}return o},as=e=>f.createUnionTypeNode(Object.values(e.enum).map(t=>f.createLiteralTypeNode(typeof t=="number"?f.createNumericLiteral(t):f.createStringLiteral(t)))),ps=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?f.createUnionTypeNode([o,f.createKeywordTypeNode(g.default.SyntaxKind.UndefinedKeyword)]):o},cs=(e,{next:t})=>f.createUnionTypeNode([t(e.unwrap()),f.createLiteralTypeNode(f.createNull())]),ds=({items:e,_def:{rest:t}},{next:r})=>f.createTupleTypeNode(e.map(r).concat(t===null?[]:f.createRestTypeNode(r(t)))),ls=({keySchema:e,valueSchema:t},{next:r})=>f.createExpressionWithTypeArguments(f.createIdentifier("Record"),[e,t].map(r)),ms=({_def:e},{next:t})=>f.createIntersectionTypeNode([e.left,e.right].map(t)),us=({_def:e},{next:t})=>t(e.innerType),de=e=>()=>f.createKeywordTypeNode(e),fs=(e,{next:t})=>t(e.unwrap()),ys=(e,{next:t})=>t(e.unwrap()),gs=({_def:e},{next:t})=>t(e.innerType),hs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),xs=()=>f.createLiteralTypeNode(f.createNull()),bs=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,f.createLiteralTypeNode(f.createNull())),r(i,o(e)))},Ss=e=>{let t=e.unwrap(),r=f.createKeywordTypeNode(g.default.SyntaxKind.StringKeyword),o=f.createTypeReferenceNode("Buffer"),n=f.createUnionTypeNode([r,o]);return t instanceof bt.z.ZodString?r:t instanceof bt.z.ZodUnion?n:o},Ts=(e,{next:t})=>t(e.unwrap().shape.raw),Os={ZodString:de(g.default.SyntaxKind.StringKeyword),ZodNumber:de(g.default.SyntaxKind.NumberKeyword),ZodBigInt:de(g.default.SyntaxKind.BigIntKeyword),ZodBoolean:de(g.default.SyntaxKind.BooleanKeyword),ZodAny:de(g.default.SyntaxKind.AnyKeyword),[qe]:de(g.default.SyntaxKind.StringKeyword),[$e]:de(g.default.SyntaxKind.StringKeyword),ZodNull:xs,ZodArray:os,ZodTuple:ds,ZodRecord:ls,ZodObject:rs,ZodLiteral:ts,ZodIntersection:ms,ZodUnion:Lo,ZodDefault:us,ZodEnum:ns,ZodNativeEnum:as,ZodEffects:is,ZodOptional:ps,ZodNullable:cs,ZodDiscriminatedUnion:Lo,ZodBranded:fs,ZodCatch:gs,ZodPipeline:hs,ZodLazy:bs,ZodReadonly:ys,[Y]:Ss,[se]:Ts},Ge=(e,{brandHandling:t,ctx:r})=>pe(e,{rules:{...t,...Os},onMissing:()=>f.createKeywordTypeNode(g.default.SyntaxKind.AnyKeyword),ctx:r});var St=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,Ee(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=We,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){ae({routing:t,onEndpoint:(R,A,I)=>{let me={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},Le=N(I,A,"input"),Ne=Ge(R.getSchema("input"),{brandHandling:r,ctx:{...me,isResponse:!1}}),L=i?N(I,A,"positive.response"):void 0,Xt=R.getSchema("positive"),er=i?Ge(Xt,{brandHandling:r,ctx:{...me,isResponse:!0}}):void 0,ke=i?N(I,A,"negative.response"):void 0,tr=R.getSchema("negative"),rr=i?Ge(tr,{brandHandling:r,ctx:{...me,isResponse:!0}}):void 0,or=N(I,A,"response"),ko=L&&ke?s.createUnionTypeNode([s.createTypeReferenceNode(L),s.createTypeReferenceNode(ke)]):Ge(Xt.or(tr),{brandHandling:r,ctx:{...me,isResponse:!0}});this.program.push(Ee(Ne,Le)),er&&L&&this.program.push(Ee(er,L)),rr&&ke&&this.program.push(Ee(rr,ke)),this.program.push(Ee(ko,or)),I!=="options"&&(this.paths.push(A),this.registry.set({method:I,path:A},{input:Le,positive:L,negative:ke,response:or,isJson:R.getMimeTypes("positive").includes(w.json),tags:R.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(_t(this.ids.pathType,this.paths)),this.program.push(_t(this.ids.methodType,vo)),this.program.push(ht(this.ids.methodPathType,$t([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(v.default.SyntaxKind.ExtendsKeyword,[Vt(this.ids.methodPathType,v.default.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let l=[],c=[];for(let[{method:R,path:A},{isJson:I,tags:me,...Le}]of this.registry){let Ne=Zo(R,A);for(let L of this.interfaces)L.kind in Le&&L.props.push(Ao(Ne,Le[L.kind]));o!=="types"&&(I&&l.push(s.createPropertyAssignment(Ne,s.createTrue())),c.push(s.createPropertyAssignment(Ne,s.createArrayLiteralExpression(me.map(L=>s.createStringLiteral(L))))))}for(let{id:R,props:A}of this.interfaces)this.program.push(wo(R,p,A));if(o==="types")return;let m=s.createVariableStatement(J,W(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(l))),y=s.createVariableStatement(J,W(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),u=ht(this.ids.providerType,s.createFunctionTypeNode(Eo({M:this.ids.methodType,P:this.ids.pathType}),gt({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Gt)}),Io(this.ids.responseInterface,Gt))),x=ht(this.ids.implementationType,s.createFunctionTypeNode(void 0,gt({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(v.default.SyntaxKind.StringKeyword),params:Vt(v.default.SyntaxKind.StringKeyword,v.default.SyntaxKind.AnyKeyword)}),zo())),j=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,we)]),T=Qt(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[j,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),M=Qt(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[j]),v.default.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),C=Co(this.ids.clientClass,Ro([yt(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),Oo)]),[Po(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Yt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,T,M]),!0))]);this.program.push(m,y,u,x,C);let b=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),Ze=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(w.json))]),void 0,this.ids.undefinedValue)),G=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),X=s.createVariableStatement(void 0,W(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,we)]),s.createObjectLiteralExpression([b,Ze,G])])))),le=s.createVariableStatement(void 0,W(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),ve=s.createVariableStatement(void 0,W(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),we)])))),[Ve,Tt]=["json","text"].map(R=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,R),void 0,void 0))),_e=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(Bt,[s.createTemplateSpan(this.ids.methodParameter,qt),s.createTemplateSpan(this.ids.pathParameter,we)]),v.default.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Ve])),D=s.createVariableStatement(J,W(this.ids.exampleImplementationConst,Yt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([le,ve,X,_e,Tt]),!0),s.createTypeReferenceNode(this.ids.implementationType))),ee=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),je=s.createVariableStatement(void 0,W(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(D,je,ee)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Wt(r,t)).join(`
22
22
  `):void 0}print(t){let r=this.printUsage(t),o=r&&v.default.addSyntheticLeadingComment(v.default.addSyntheticLeadingComment(s.createEmptyStatement(),v.default.SyntaxKind.SingleLineCommentTrivia," Usage example:"),v.default.SyntaxKind.MultiLineCommentTrivia,`
23
23
  ${r}`);return this.program.concat(o||[]).map((n,i)=>Wt(n,i<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
24
24
 
package/dist/index.d.cts CHANGED
@@ -747,7 +747,7 @@ interface NextHandlerInc<U> {
747
747
  interface PrevInc<U> {
748
748
  prev: U;
749
749
  }
750
- type SchemaHandler<U, Context extends FlatObject = EmptyObject, Variant extends "regular" | "each" | "last" = "regular"> = (schema: any, // eslint-disable-line @typescript-eslint/no-explicit-any -- for assignmet compatibility
750
+ type SchemaHandler<U, Context extends FlatObject = EmptyObject, Variant extends "regular" | "each" | "last" = "regular"> = (schema: any, // eslint-disable-line @typescript-eslint/no-explicit-any -- for assignment compatibility
751
751
  ctx: Context & (Variant extends "regular" ? NextHandlerInc<U> : Variant extends "each" ? PrevInc<U> : Context)) => U;
752
752
  type HandlingRules<U, Context extends FlatObject = EmptyObject, K extends string | symbol = string | symbol> = Partial<Record<K, SchemaHandler<U, Context>>>;
753
753
 
@@ -908,7 +908,7 @@ interface IntegrationParams {
908
908
  * */
909
909
  variant?: "types" | "client";
910
910
  /**
911
- * @desc Declares positive and negative response types separately and provides them within additional dictoinaries
911
+ * @desc Declares positive and negative response types separately and provides them within additional dictionaries
912
912
  * @default false
913
913
  * */
914
914
  splitResponse?: boolean;
package/dist/index.d.ts CHANGED
@@ -747,7 +747,7 @@ interface NextHandlerInc<U> {
747
747
  interface PrevInc<U> {
748
748
  prev: U;
749
749
  }
750
- type SchemaHandler<U, Context extends FlatObject = EmptyObject, Variant extends "regular" | "each" | "last" = "regular"> = (schema: any, // eslint-disable-line @typescript-eslint/no-explicit-any -- for assignmet compatibility
750
+ type SchemaHandler<U, Context extends FlatObject = EmptyObject, Variant extends "regular" | "each" | "last" = "regular"> = (schema: any, // eslint-disable-line @typescript-eslint/no-explicit-any -- for assignment compatibility
751
751
  ctx: Context & (Variant extends "regular" ? NextHandlerInc<U> : Variant extends "each" ? PrevInc<U> : Context)) => U;
752
752
  type HandlingRules<U, Context extends FlatObject = EmptyObject, K extends string | symbol = string | symbol> = Partial<Record<K, SchemaHandler<U, Context>>>;
753
753
 
@@ -908,7 +908,7 @@ interface IntegrationParams {
908
908
  * */
909
909
  variant?: "types" | "client";
910
910
  /**
911
- * @desc Declares positive and negative response types separately and provides them within additional dictoinaries
911
+ * @desc Declares positive and negative response types separately and provides them within additional dictionaries
912
912
  * @default false
913
913
  * */
914
914
  splitResponse?: boolean;
package/dist/index.js CHANGED
@@ -18,7 +18,7 @@ ${o}888${t}
18
18
  ${r}
19
19
  `.split(`
20
20
  `).map((d,c)=>a[c]?a[c](d):d).join(`
21
- `)};var wr=e=>{e.startupLogo!==!1&&console.log(zr());let t=e.errorHandler||ze,r=ar(e.logger)?e.logger:new Ee(e.logger);r.debug("Running","v20.14.0 (ESM)"),Pr(r);let o=Rr({rootLogger:r,config:e}),i={getChildLogger:Ar(r),errorHandler:t},a=Sr(i),p=br(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},ln=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=wr(e);return Ot({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},mn=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=wr(e),p=Rt().disable("x-powered-by").use(a);if(e.server.compression){let m=await me("compression");p.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let d={json:[e.server.jsonParser||Rt.json()],raw:[e.server.rawParser||Rt.raw(),Or],upload:e.server.upload?await Tr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Ot({app:p,routing:t,getChildLogger:o,config:e,parsers:d}),p.use(i,n);let c=(m,h)=>m.listen(h,()=>r.info("Listening",h)),l=cn.createServer(p),f=e.https&&dn.createServer(e.https.options,p);return e.gracefulShutdown&&Cr({servers:[l].concat(f||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(l,e.server.listen),httpsServer:f&&c(f,e.https?.listen)}};import gs from"node:assert/strict";import{OpenApiBuilder as hs}from"openapi3-ts/oas31";import{pluck as xs}from"ramda";import te from"node:assert/strict";import{isReferenceObject as Pt,isSchemaObject as tt}from"openapi3-ts/oas31";import{concat as fn,type as Lr,filter as yn,fromPairs as ke,has as gn,isNil as hn,map as ue,mergeAll as xn,mergeDeepRight as bn,mergeDeepWith as Sn,objOf as Nr,omit as rt,pipe as kr,pluck as Tn,range as On,reject as Rn,toLower as An,union as Pn,when as Cn,xprod as ot,zip as In}from"ramda";import{z as S}from"zod";import{z as je}from"zod";var Xe=e=>!isNaN(e.getTime());var Le=Symbol("DateIn"),Er=()=>je.union([je.string().date(),je.string().datetime(),je.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(je.date().refine(Xe)).brand(Le);import{z as un}from"zod";var Ne=Symbol("DateOut"),Zr=()=>un.date().refine(Xe).transform(e=>e.toISOString()).brand(Ne);var X=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[g]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>X(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:p,...n});return d?{...p,...d}:p};var vr=50,Mr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",zn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Ur=/:([A-Za-z0-9_]+)/g,wn=e=>e.match(Ur)?.map(t=>t.slice(1))||[],Hr=e=>e.replace(Ur,t=>`{${t.slice(1)}}`),En=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Zn=({_def:{innerType:e}},{next:t})=>t(e),vn=()=>({format:"any"}),jn=({},e)=>(te(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Ln=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Nn=({options:e},{next:t})=>({oneOf:e.map(t)}),kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Mn=e=>{let[t,r]=e.filter(tt).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));te(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=Sn((n,i)=>Array.isArray(n)&&Array.isArray(i)?fn(n,i):n===i?i:te.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Pn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([n,i])=>bn(n,i))),o},Un=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Mn(o)}catch{}return{allOf:o}},Hn=(e,{next:t})=>t(e.unwrap()),Dn=(e,{next:t})=>t(e.unwrap()),Fn=(e,{next:t})=>{let r=t(e.unwrap());return tt(r)&&(r.type=Fr(r)),r},Dr=e=>{let t=An(Lr(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},jr=e=>({type:Dr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Kn=({value:e})=>({type:Dr(e),const:e}),Bn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Re(p)?p instanceof S.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=et(e,r)),i.length&&(a.required=i),a},qn=()=>({type:"null"}),$n=({},e)=>(te(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Mr}}),Gn=({},e)=>(te(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Mr}}),Vn=({},e)=>te.fail(new z({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),_n=()=>({type:"boolean"}),Yn=()=>({type:"integer",format:"bigint"}),Qn=e=>e.every(t=>t instanceof S.ZodLiteral),Jn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=et(S.object(ke(ot(o,[t]))),r),n.required=o),n}if(e instanceof S.ZodLiteral)return{type:"object",properties:et(S.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.ZodUnion&&Qn(e.options)){let o=ue(i=>`${i.value}`,e.options),n=ke(ot(o,[t]));return{type:"object",properties:et(S.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Wn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Xn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),es=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:f}})=>{let m=f.find(R=>R.kind==="regex"),h=f.find(R=>R.kind==="datetime"),C=m?m.regex:h?h.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,b={type:"string"},Z={"date-time":l,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:d,emoji:c};for(let R in Z)if(Z[R]){b.format=R;break}return r!==null&&(b.minLength=r),o!==null&&(b.maxLength=o),C&&(b.pattern=C.source),b},ts=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=i:l.exclusiveMinimum=i,c?l.maximum=d:l.exclusiveMaximum=d,l},et=({shape:e},t)=>ue(t,e),rs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return zn?.[t]},Fr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},os=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&tt(o)){let i=Be(e,rs(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.any())}if(!t&&n.type==="preprocess"&&tt(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},ns=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ss=(e,{next:t})=>t(e.unwrap()),is=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},as=(e,{next:t})=>t(e.unwrap().shape.raw),Kr=e=>e.length?ke(In(On(1,e.length+1).map(t=>`example${t}`),ue(Nr("value"),e))):void 0,Br=(e,t,r=[])=>kr(H,ue(Cn(o=>Lr(o)==="Object",rt(r))),Kr)({schema:e,variant:t?"parsed":"original",validate:!0}),ps=(e,t)=>kr(H,yn(gn(t)),Tn(t),Kr)({schema:e,variant:"original",validate:!0}),ee=e=>e instanceof S.ZodObject?e:e instanceof S.ZodBranded?ee(e.unwrap()):e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?e.options.map(t=>ee(t)).reduce((t,r)=>t.merge(r.partial()),S.object({})):e instanceof S.ZodEffects?ee(e._def.schema):e instanceof S.ZodPipeline?ee(e._def.in):ee(e._def.left).merge(ee(e._def.right)),qr=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=ee(r),f=wn(e),m=o.includes("query"),h=o.includes("params"),C=o.includes("headers"),b=x=>h&&f.includes(x),Z=x=>C&&mt(x);return Object.keys(l).map(x=>({name:x,location:b(x)?"path":Z(x)?"header":m?"query":void 0})).filter(x=>x.location!==void 0).map(({name:x,location:ge})=>{let k=X(l[x],{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),$=p==="components"?a(w(c,x),k):k;return{name:x,in:ge,required:!l[x].isOptional(),description:k.description||c,schema:$,examples:ps(r,x)}})},Ct={ZodString:es,ZodNumber:ts,ZodBigInt:Yn,ZodBoolean:_n,ZodNull:qn,ZodArray:Wn,ZodTuple:Xn,ZodRecord:Jn,ZodObject:Bn,ZodLiteral:Kn,ZodIntersection:Un,ZodUnion:Nn,ZodAny:vn,ZodDefault:En,ZodEnum:jr,ZodNativeEnum:jr,ZodEffects:os,ZodOptional:Hn,ZodNullable:Fn,ZodDiscriminatedUnion:kn,ZodBranded:ss,ZodDate:Vn,ZodCatch:Zn,ZodPipeline:ns,ZodLazy:is,ZodReadonly:Dn,[D]:Ln,[Ae]:jn,[Ne]:Gn,[Le]:$n,[Q]:as},It=(e,{isResponse:t,prev:r})=>{if(Pt(r))return{};let{description:o}=e,n=e instanceof S.ZodLazy,i=r.type!==void 0,a=t&&Re(e),p=!n&&i&&!a&&e.isNullable(),d=n?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Fr(r)),d.length&&(c.examples=d.slice()),c},zt=(e,t)=>te.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),At=(e,t)=>{if(Pt(e))return e;let r={...e};return r.properties&&(r.properties=rt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>rt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>At(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>At(o,t))),r},$r=e=>Pt(e)?e:rt(["examples"],e),Gr=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,brandHandling:f,description:m=`${e.toUpperCase()} ${t} ${yt(n)} response ${c?l:""}`.trim()})=>{let h=$r(X(r,{rules:{...f,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),C={schema:d==="components"?p(w(m),h):h,examples:Br(r,!0)};return{description:m,content:ke(ot(o,[C]))}},cs=()=>({type:"http",scheme:"basic"}),ds=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ls=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ms=({name:e})=>({type:"apiKey",in:"header",name:e}),us=({name:e})=>({type:"apiKey",in:"cookie",name:e}),fs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ys=({flows:e={}})=>({type:"oauth2",flows:ue(t=>({...t,scopes:t.scopes||{}}),Rn(hn,e))}),Vr=(e,t)=>{let r={basic:cs,bearer:ds,input:ls,header:ms,cookie:us,openid:fs,oauth2:ys};return _e(e,o=>r[o.type](o,t))},nt=e=>"or"in e?e.or.map(t=>"and"in t?xn(ue(({name:r,scopes:o})=>Nr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?nt(xt(e)):nt({or:[e]}),_r=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let f=$r(At(X(r,{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),m={schema:p==="components"?a(w(l),f):f,examples:Br(r,!1,c)};return{description:l,content:ke(ot(o,[m]))}},Yr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),wt=e=>e.length<=vr?e:e.slice(0,vr-1)+"\u2026";var Et=class extends hs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||w(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&gs.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:c="inline",serializer:l=Ke}){super(),this.addInfo({title:o,version:n});for(let m of typeof i=="string"?[i]:i)this.addServer({url:m});W({routing:t,onEndpoint:(m,h,C)=>{let b=C,Z={path:h,method:b,endpoint:m,composition:c,serializer:l,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[R,x]=["short","long"].map(m.getDescription.bind(m)),ge=R?wt(R):d&&x?wt(x):void 0,k=m.getTags(),$=r.inputSources?.[b]||dt[b],oe=this.ensureUniqOperationId(h,b,m.getOperationId(b)),he=qr({...Z,inputSources:$,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:h,operationId:oe})}),Ue={};for(let j of["positive","negative"]){let G=m.getResponses(j);for(let{mimeTypes:xe,schema:T,statusCodes:O}of G)for(let A of O)Ue[A]=Gr({...Z,variant:j,schema:T,mimeTypes:xe,statusCode:A,hasMultipleStatusCodes:G.length>1||O.length>1,description:a?.[`${j}Response`]?.call(null,{method:b,path:h,operationId:oe,statusCode:A})})}let ct=$.includes("body")?_r({...Z,paramNames:xs("name",he),schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:h,operationId:oe})}):void 0,He=nt(_e(Vr(m.getSecurity(),$),j=>{let G=this.ensureUniqSecuritySchemaName(j),xe=["oauth2","openIdConnect"].includes(j.type)?m.getScopes().slice():[];return this.addSecurityScheme(G,j),{name:G,scopes:xe}}));this.addPath(Hr(h),{[b]:{operationId:oe,summary:ge,description:x,tags:k.length>0?k:void 0,parameters:he.length>0?he:void 0,requestBody:ct,security:He.length>0?He:void 0,responses:Ue}})}}),this.rootDoc.tags=r.tags?Yr(r.tags):[]}};import{createRequest as bs,createResponse as Ss}from"node-mocks-http";var Ts=e=>bs({...e,headers:{"content-type":P.json,...e?.headers}}),Os=e=>Ss(e),Rs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:o in le?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},As=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ts(e),i=Os({req:n,...t});i.req=t?.req||n,n.res=i;let a=Rs(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},Ps=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=As(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}};import E from"typescript";import N from"typescript";import{chain as Qr,toPairs as Jr}from"ramda";var s=N.factory,K=[s.createModifier(N.SyntaxKind.ExportKeyword)],Cs=[s.createModifier(N.SyntaxKind.AsyncKeyword)],Is=[s.createModifier(N.SyntaxKind.PublicKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],Wr=[s.createModifier(N.SyntaxKind.ProtectedKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],Zt=s.createTemplateHead(""),fe=s.createTemplateTail(""),vt=s.createTemplateMiddle(" "),jt=e=>s.createTemplateLiteralType(Zt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?fe:vt))),Lt=jt(["M","P"]),st=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),it=(e,t)=>Qr(([r,o])=>[st(s.createIdentifier(r),o,t)],Jr(e)),Nt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),Xr=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),eo=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),B=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],N.NodeFlags.Const),kt=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),at=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,t),to=(e,t,r)=>s.createPropertyDeclaration(Is,e,void 0,t,r),ro=(e,t,r)=>s.createClassDeclaration(K,e,void 0,void 0,[t,...r]),oo=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),no=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(N.SyntaxKind.AnyKeyword)]),so=(e,t,r)=>s.createInterfaceDeclaration(K,e,void 0,t,r),zs=Qr(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),io=e=>zs(Jr(e)),Mt=(e,t,r)=>s.createArrowFunction(r?Cs:void 0,void 0,e.map(o=>st(o)),void 0,void 0,t),Ut=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,it({acc:void 0,key:void 0}),void 0,void 0,t),r]),ao=(...e)=>`"${e.join(" ")}"`;var po=["get","post","put","delete","patch"];import y from"typescript";import{z as Ft}from"zod";import q from"typescript";var{factory:pt}=q,Ht=(e,t)=>{q.addSyntheticLeadingComment(e,q.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ye=(e,t,r)=>{let o=pt.createTypeAliasDeclaration(void 0,pt.createIdentifier(t),void 0,e);return r&&Ht(o,r),o},Dt=(e,t)=>{let r=q.createSourceFile("print.ts","",q.ScriptTarget.Latest,!1,q.ScriptKind.TS);return q.createPrinter(t).printNode(q.EmitHint.Unspecified,e,r)},ws=/^[A-Za-z_$][A-Za-z0-9_$]*$/,co=e=>ws.test(e)?pt.createIdentifier(e):pt.createStringLiteral(e);var{factory:u}=y,Es={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},Zs=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),vs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Re(a)?a instanceof Ft.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,co(i),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Ht(d,a.description),d});return u.createTypeLiteralNode(n)},js=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Ls=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),lo=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),Ns=e=>Es?.[e.kind],ks=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Be(e,Ns(o)),i={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(n&&i[n]||y.SyntaxKind.AnyKeyword)}return o},Ms=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Us=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Hs=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),Ds=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),Fs=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),Ks=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),Bs=({_def:e},{next:t})=>t(e.innerType),re=e=>()=>u.createKeywordTypeNode(e),qs=(e,{next:t})=>t(e.unwrap()),$s=(e,{next:t})=>t(e.unwrap()),Gs=({_def:e},{next:t})=>t(e.innerType),Vs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),_s=()=>u.createLiteralTypeNode(u.createNull()),Ys=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,u.createLiteralTypeNode(u.createNull())),r(i,o(e)))},Qs=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),n=u.createUnionTypeNode([r,o]);return t instanceof Ft.ZodString?r:t instanceof Ft.ZodUnion?n:o},Js=(e,{next:t})=>t(e.unwrap().shape.raw),Ws={ZodString:re(y.SyntaxKind.StringKeyword),ZodNumber:re(y.SyntaxKind.NumberKeyword),ZodBigInt:re(y.SyntaxKind.BigIntKeyword),ZodBoolean:re(y.SyntaxKind.BooleanKeyword),ZodAny:re(y.SyntaxKind.AnyKeyword),[Le]:re(y.SyntaxKind.StringKeyword),[Ne]:re(y.SyntaxKind.StringKeyword),ZodNull:_s,ZodArray:js,ZodTuple:Ds,ZodRecord:Fs,ZodObject:vs,ZodLiteral:Zs,ZodIntersection:Ks,ZodUnion:lo,ZodDefault:Bs,ZodEnum:Ls,ZodNativeEnum:Ms,ZodEffects:ks,ZodOptional:Us,ZodNullable:Hs,ZodDiscriminatedUnion:lo,ZodBranded:qs,ZodCatch:Gs,ZodPipeline:Vs,ZodLazy:Ys,ZodReadonly:$s,[D]:Qs,[Q]:Js},Me=(e,{brandHandling:t,ctx:r})=>X(e,{rules:{...t,...Ws},onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),ctx:r});var Kt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ye(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=Ke,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){W({routing:t,onEndpoint:(T,O,A)=>{let ne={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},be=w(A,O,"input"),Se=Me(T.getSchema("input"),{brandHandling:r,ctx:{...ne,isResponse:!1}}),I=i?w(A,O,"positive.response"):void 0,Bt=T.getSchema("positive"),qt=i?Me(Bt,{brandHandling:r,ctx:{...ne,isResponse:!0}}):void 0,Te=i?w(A,O,"negative.response"):void 0,$t=T.getSchema("negative"),Gt=i?Me($t,{brandHandling:r,ctx:{...ne,isResponse:!0}}):void 0,Vt=w(A,O,"response"),mo=I&&Te?s.createUnionTypeNode([s.createTypeReferenceNode(I),s.createTypeReferenceNode(Te)]):Me(Bt.or($t),{brandHandling:r,ctx:{...ne,isResponse:!0}});this.program.push(ye(Se,be)),qt&&I&&this.program.push(ye(qt,I)),Gt&&Te&&this.program.push(ye(Gt,Te)),this.program.push(ye(mo,Vt)),A!=="options"&&(this.paths.push(O),this.registry.set({method:A,path:O},{input:be,positive:I,negative:Te,response:Vt,isJson:T.getMimeTypes("positive").includes(P.json),tags:T.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(kt(this.ids.pathType,this.paths)),this.program.push(kt(this.ids.methodType,po)),this.program.push(at(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(E.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,E.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let d=[],c=[];for(let[{method:T,path:O},{isJson:A,tags:ne,...be}]of this.registry){let Se=ao(T,O);for(let I of this.interfaces)I.kind in be&&I.props.push(eo(Se,be[I.kind]));o!=="types"&&(A&&d.push(s.createPropertyAssignment(Se,s.createTrue())),c.push(s.createPropertyAssignment(Se,s.createArrayLiteralExpression(ne.map(I=>s.createStringLiteral(I))))))}for(let{id:T,props:O}of this.interfaces)this.program.push(so(T,p,O));if(o==="types")return;let l=s.createVariableStatement(K,B(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(d))),f=s.createVariableStatement(K,B(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),m=at(this.ids.providerType,s.createFunctionTypeNode(io({M:this.ids.methodType,P:this.ids.pathType}),it({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Lt)}),oo(this.ids.responseInterface,Lt))),h=at(this.ids.implementationType,s.createFunctionTypeNode(void 0,it({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(E.SyntaxKind.StringKeyword),params:Nt(E.SyntaxKind.StringKeyword,E.SyntaxKind.AnyKeyword)}),no())),C=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,fe)]),b=Ut(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[C,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),Z=Ut(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[C]),E.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),R=ro(this.ids.clientClass,Xr([st(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),Wr)]),[to(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,Z]),!0))]);this.program.push(l,f,m,h,R);let x=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ge=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(P.json))]),void 0,this.ids.undefinedValue)),k=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),$=s.createVariableStatement(void 0,B(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,fe)]),s.createObjectLiteralExpression([x,ge,k])])))),oe=s.createVariableStatement(void 0,B(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),he=s.createVariableStatement(void 0,B(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),fe)])))),[Ue,ct]=["json","text"].map(T=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,T),void 0,void 0))),He=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(Zt,[s.createTemplateSpan(this.ids.methodParameter,vt),s.createTemplateSpan(this.ids.pathParameter,fe)]),E.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Ue])),j=s.createVariableStatement(K,B(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([oe,he,$,He,ct]),!0),s.createTypeReferenceNode(this.ids.implementationType))),G=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),xe=s.createVariableStatement(void 0,B(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(j,xe,G)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
21
+ `)};var wr=e=>{e.startupLogo!==!1&&console.log(zr());let t=e.errorHandler||ze,r=ar(e.logger)?e.logger:new Ee(e.logger);r.debug("Running","v20.14.1 (ESM)"),Pr(r);let o=Rr({rootLogger:r,config:e}),i={getChildLogger:Ar(r),errorHandler:t},a=Sr(i),p=br(i);return{...i,rootLogger:r,notFoundHandler:a,parserFailureHandler:p,loggingMiddleware:o}},ln=(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,loggingMiddleware:i}=wr(e);return Ot({app:e.app.use(i),routing:t,getChildLogger:o,config:e}),{notFoundHandler:n,logger:r}},mn=async(e,t)=>{let{rootLogger:r,getChildLogger:o,notFoundHandler:n,parserFailureHandler:i,loggingMiddleware:a}=wr(e),p=Rt().disable("x-powered-by").use(a);if(e.server.compression){let m=await me("compression");p.use(m(typeof e.server.compression=="object"?e.server.compression:void 0))}let d={json:[e.server.jsonParser||Rt.json()],raw:[e.server.rawParser||Rt.raw(),Or],upload:e.server.upload?await Tr({config:e,getChildLogger:o}):[]};e.server.beforeRouting&&await e.server.beforeRouting({app:p,logger:r,getChildLogger:o}),Ot({app:p,routing:t,getChildLogger:o,config:e,parsers:d}),p.use(i,n);let c=(m,h)=>m.listen(h,()=>r.info("Listening",h)),l=cn.createServer(p),f=e.https&&dn.createServer(e.https.options,p);return e.gracefulShutdown&&Cr({servers:[l].concat(f||[]),logger:r,options:e.gracefulShutdown===!0?{}:e.gracefulShutdown}),{app:p,logger:r,httpServer:c(l,e.server.listen),httpsServer:f&&c(f,e.https?.listen)}};import gs from"node:assert/strict";import{OpenApiBuilder as hs}from"openapi3-ts/oas31";import{pluck as xs}from"ramda";import te from"node:assert/strict";import{isReferenceObject as Pt,isSchemaObject as tt}from"openapi3-ts/oas31";import{concat as fn,type as Lr,filter as yn,fromPairs as ke,has as gn,isNil as hn,map as ue,mergeAll as xn,mergeDeepRight as bn,mergeDeepWith as Sn,objOf as Nr,omit as rt,pipe as kr,pluck as Tn,range as On,reject as Rn,toLower as An,union as Pn,when as Cn,xprod as ot,zip as In}from"ramda";import{z as S}from"zod";import{z as je}from"zod";var Xe=e=>!isNaN(e.getTime());var Le=Symbol("DateIn"),Er=()=>je.union([je.string().date(),je.string().datetime(),je.string().datetime({local:!0})]).transform(t=>new Date(t)).pipe(je.date().refine(Xe)).brand(Le);import{z as un}from"zod";var Ne=Symbol("DateOut"),Zr=()=>un.date().refine(Xe).transform(e=>e.toISOString()).brand(Ne);var X=(e,{onEach:t,rules:r,onMissing:o,ctx:n={}})=>{let i=r[e._def[g]?.brand]||r[e._def.typeName],p=i?i(e,{...n,next:c=>X(c,{ctx:n,onEach:t,rules:r,onMissing:o})}):o(e,n),d=t&&t(e,{prev:p,...n});return d?{...p,...d}:p};var vr=50,Mr="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString",zn={integer:0,number:0,string:"",boolean:!1,object:{},null:null,array:[]},Ur=/:([A-Za-z0-9_]+)/g,wn=e=>e.match(Ur)?.map(t=>t.slice(1))||[],Hr=e=>e.replace(Ur,t=>`{${t.slice(1)}}`),En=({_def:e},{next:t})=>({...t(e.innerType),default:e[g]?.defaultLabel||e.defaultValue()}),Zn=({_def:{innerType:e}},{next:t})=>t(e),vn=()=>({format:"any"}),jn=({},e)=>(te(!e.isResponse,new z({message:"Please use ez.upload() only for input.",...e})),{type:"string",format:"binary"}),Ln=e=>{let t=e.unwrap();return{type:"string",format:t instanceof S.ZodString?t._def.checks.find(r=>r.kind==="base64")?"byte":"file":"binary"}},Nn=({options:e},{next:t})=>({oneOf:e.map(t)}),kn=({options:e,discriminator:t},{next:r})=>({discriminator:{propertyName:t},oneOf:e.map(r)}),Mn=e=>{let[t,r]=e.filter(tt).filter(n=>n.type==="object"&&Object.keys(n).every(i=>["type","properties","required","examples"].includes(i)));te(t&&r,"Can not flatten objects");let o={type:"object"};return(t.properties||r.properties)&&(o.properties=Sn((n,i)=>Array.isArray(n)&&Array.isArray(i)?fn(n,i):n===i?i:te.fail("Can not flatten properties"),t.properties||{},r.properties||{})),(t.required||r.required)&&(o.required=Pn(t.required||[],r.required||[])),(t.examples||r.examples)&&(o.examples=_(t.examples||[],r.examples||[],([n,i])=>bn(n,i))),o},Un=({_def:{left:e,right:t}},{next:r})=>{let o=[e,t].map(r);try{return Mn(o)}catch{}return{allOf:o}},Hn=(e,{next:t})=>t(e.unwrap()),Dn=(e,{next:t})=>t(e.unwrap()),Fn=(e,{next:t})=>{let r=t(e.unwrap());return tt(r)&&(r.type=Fr(r)),r},Dr=e=>{let t=An(Lr(e));return typeof e=="bigint"?"integer":t==="number"||t==="string"||t==="boolean"||t==="object"||t==="null"||t==="array"?t:void 0},jr=e=>({type:Dr(Object.values(e.enum)[0]),enum:Object.values(e.enum)}),Kn=({value:e})=>({type:Dr(e),const:e}),Bn=(e,{isResponse:t,next:r})=>{let o=Object.keys(e.shape),n=p=>t&&Re(p)?p instanceof S.ZodOptional:p.isOptional(),i=o.filter(p=>!n(e.shape[p])),a={type:"object"};return o.length&&(a.properties=et(e,r)),i.length&&(a.required=i),a},qn=()=>({type:"null"}),$n=({},e)=>(te(!e.isResponse,new z({message:"Please use ez.dateOut() for output.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",pattern:/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?)?Z?$/.source,externalDocs:{url:Mr}}),Gn=({},e)=>(te(e.isResponse,new z({message:"Please use ez.dateIn() for input.",...e})),{description:"YYYY-MM-DDTHH:mm:ss.sssZ",type:"string",format:"date-time",externalDocs:{url:Mr}}),Vn=({},e)=>te.fail(new z({message:`Using z.date() within ${e.isResponse?"output":"input"} schema is forbidden. Please use ez.date${e.isResponse?"Out":"In"}() instead. Check out the documentation for details.`,...e})),_n=()=>({type:"boolean"}),Yn=()=>({type:"integer",format:"bigint"}),Qn=e=>e.every(t=>t instanceof S.ZodLiteral),Jn=({keySchema:e,valueSchema:t},{next:r})=>{if(e instanceof S.ZodEnum||e instanceof S.ZodNativeEnum){let o=Object.values(e.enum),n={type:"object"};return o.length&&(n.properties=et(S.object(ke(ot(o,[t]))),r),n.required=o),n}if(e instanceof S.ZodLiteral)return{type:"object",properties:et(S.object({[e.value]:t}),r),required:[e.value]};if(e instanceof S.ZodUnion&&Qn(e.options)){let o=ue(i=>`${i.value}`,e.options),n=ke(ot(o,[t]));return{type:"object",properties:et(S.object(n),r),required:o}}return{type:"object",additionalProperties:r(t)}},Wn=({_def:{minLength:e,maxLength:t},element:r},{next:o})=>{let n={type:"array",items:o(r)};return e&&(n.minItems=e.value),t&&(n.maxItems=t.value),n},Xn=({items:e,_def:{rest:t}},{next:r})=>({type:"array",prefixItems:e.map(r),items:t===null?{not:{}}:r(t)}),es=({isEmail:e,isURL:t,minLength:r,maxLength:o,isUUID:n,isCUID:i,isCUID2:a,isULID:p,isIP:d,isEmoji:c,isDatetime:l,_def:{checks:f}})=>{let m=f.find(R=>R.kind==="regex"),h=f.find(R=>R.kind==="datetime"),C=m?m.regex:h?h.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}:\\d{2})|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$"):void 0,b={type:"string"},Z={"date-time":l,email:e,url:t,uuid:n,cuid:i,cuid2:a,ulid:p,ip:d,emoji:c};for(let R in Z)if(Z[R]){b.format=R;break}return r!==null&&(b.minLength=r),o!==null&&(b.maxLength=o),C&&(b.pattern=C.source),b},ts=({isInt:e,maxValue:t,minValue:r,_def:{checks:o}})=>{let n=o.find(f=>f.kind==="min"),i=r===null?e?Number.MIN_SAFE_INTEGER:-Number.MAX_VALUE:r,a=n?n.inclusive:!0,p=o.find(f=>f.kind==="max"),d=t===null?e?Number.MAX_SAFE_INTEGER:Number.MAX_VALUE:t,c=p?p.inclusive:!0,l={type:e?"integer":"number",format:e?"int64":"double"};return a?l.minimum=i:l.exclusiveMinimum=i,c?l.maximum=d:l.exclusiveMaximum=d,l},et=({shape:e},t)=>ue(t,e),rs=e=>{let t=Array.isArray(e.type)?e.type[0]:e.type;return zn?.[t]},Fr=e=>{let t=typeof e.type=="string"?[e.type]:e.type||[];return t.includes("null")?t:t.concat("null")},os=(e,{isResponse:t,next:r})=>{let o=r(e.innerType()),{effect:n}=e._def;if(t&&n.type==="transform"&&tt(o)){let i=Be(e,rs(o));return i&&["number","string","boolean"].includes(i)?{type:i}:r(S.any())}if(!t&&n.type==="preprocess"&&tt(o)){let{type:i,...a}=o;return{...a,format:`${a.format||i} (preprocessed)`}}return o},ns=({_def:e},{isResponse:t,next:r})=>r(e[t?"out":"in"]),ss=(e,{next:t})=>t(e.unwrap()),is=({schema:e},{next:t,serializer:r,getRef:o,makeRef:n})=>{let i=r(e);return o(i)||(n(i,{}),n(i,t(e)))},as=(e,{next:t})=>t(e.unwrap().shape.raw),Kr=e=>e.length?ke(In(On(1,e.length+1).map(t=>`example${t}`),ue(Nr("value"),e))):void 0,Br=(e,t,r=[])=>kr(H,ue(Cn(o=>Lr(o)==="Object",rt(r))),Kr)({schema:e,variant:t?"parsed":"original",validate:!0}),ps=(e,t)=>kr(H,yn(gn(t)),Tn(t),Kr)({schema:e,variant:"original",validate:!0}),ee=e=>e instanceof S.ZodObject?e:e instanceof S.ZodBranded?ee(e.unwrap()):e instanceof S.ZodUnion||e instanceof S.ZodDiscriminatedUnion?e.options.map(t=>ee(t)).reduce((t,r)=>t.merge(r.partial()),S.object({})):e instanceof S.ZodEffects?ee(e._def.schema):e instanceof S.ZodPipeline?ee(e._def.in):ee(e._def.left).merge(ee(e._def.right)),qr=({path:e,method:t,schema:r,inputSources:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,description:c=`${t.toUpperCase()} ${e} Parameter`})=>{let{shape:l}=ee(r),f=wn(e),m=o.includes("query"),h=o.includes("params"),C=o.includes("headers"),b=x=>h&&f.includes(x),Z=x=>C&&mt(x);return Object.keys(l).map(x=>({name:x,location:b(x)?"path":Z(x)?"header":m?"query":void 0})).filter(x=>x.location!==void 0).map(({name:x,location:ge})=>{let k=X(l[x],{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:e,method:t}}),$=p==="components"?a(w(c,x),k):k;return{name:x,in:ge,required:!l[x].isOptional(),description:k.description||c,schema:$,examples:ps(r,x)}})},Ct={ZodString:es,ZodNumber:ts,ZodBigInt:Yn,ZodBoolean:_n,ZodNull:qn,ZodArray:Wn,ZodTuple:Xn,ZodRecord:Jn,ZodObject:Bn,ZodLiteral:Kn,ZodIntersection:Un,ZodUnion:Nn,ZodAny:vn,ZodDefault:En,ZodEnum:jr,ZodNativeEnum:jr,ZodEffects:os,ZodOptional:Hn,ZodNullable:Fn,ZodDiscriminatedUnion:kn,ZodBranded:ss,ZodDate:Vn,ZodCatch:Zn,ZodPipeline:ns,ZodLazy:is,ZodReadonly:Dn,[D]:Ln,[Ae]:jn,[Ne]:Gn,[Le]:$n,[Q]:as},It=(e,{isResponse:t,prev:r})=>{if(Pt(r))return{};let{description:o}=e,n=e instanceof S.ZodLazy,i=r.type!==void 0,a=t&&Re(e),p=!n&&i&&!a&&e.isNullable(),d=n?[]:H({schema:e,variant:t?"parsed":"original",validate:!0}),c={};return o&&(c.description=o),p&&(c.type=Fr(r)),d.length&&(c.examples=d.slice()),c},zt=(e,t)=>te.fail(new z({message:`Zod type ${e.constructor.name} is unsupported.`,...t})),At=(e,t)=>{if(Pt(e))return e;let r={...e};return r.properties&&(r.properties=rt(t,r.properties)),r.examples&&(r.examples=r.examples.map(o=>rt(t,o))),r.required&&(r.required=r.required.filter(o=>!t.includes(o))),r.allOf&&(r.allOf=r.allOf.map(o=>At(o,t))),r.oneOf&&(r.oneOf=r.oneOf.map(o=>At(o,t))),r},$r=e=>Pt(e)?e:rt(["examples"],e),Gr=({method:e,path:t,schema:r,mimeTypes:o,variant:n,serializer:i,getRef:a,makeRef:p,composition:d,hasMultipleStatusCodes:c,statusCode:l,brandHandling:f,description:m=`${e.toUpperCase()} ${t} ${yt(n)} response ${c?l:""}`.trim()})=>{let h=$r(X(r,{rules:{...f,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!0,serializer:i,getRef:a,makeRef:p,path:t,method:e}})),C={schema:d==="components"?p(w(m),h):h,examples:Br(r,!0)};return{description:m,content:ke(ot(o,[C]))}},cs=()=>({type:"http",scheme:"basic"}),ds=({format:e})=>{let t={type:"http",scheme:"bearer"};return e&&(t.bearerFormat=e),t},ls=({name:e},t)=>{let r={type:"apiKey",in:"query",name:e};return t?.includes("body")&&(t?.includes("query")?(r["x-in-alternative"]="body",r.description=`${e} CAN also be supplied within the request body`):(r["x-in-actual"]="body",r.description=`${e} MUST be supplied within the request body instead of query`)),r},ms=({name:e})=>({type:"apiKey",in:"header",name:e}),us=({name:e})=>({type:"apiKey",in:"cookie",name:e}),fs=({url:e})=>({type:"openIdConnect",openIdConnectUrl:e}),ys=({flows:e={}})=>({type:"oauth2",flows:ue(t=>({...t,scopes:t.scopes||{}}),Rn(hn,e))}),Vr=(e,t)=>{let r={basic:cs,bearer:ds,input:ls,header:ms,cookie:us,openid:fs,oauth2:ys};return _e(e,o=>r[o.type](o,t))},nt=e=>"or"in e?e.or.map(t=>"and"in t?xn(ue(({name:r,scopes:o})=>Nr(r,o),t.and)):{[t.name]:t.scopes}):"and"in e?nt(xt(e)):nt({or:[e]}),_r=({method:e,path:t,schema:r,mimeTypes:o,serializer:n,getRef:i,makeRef:a,composition:p,brandHandling:d,paramNames:c,description:l=`${e.toUpperCase()} ${t} Request body`})=>{let f=$r(At(X(r,{rules:{...d,...Ct},onEach:It,onMissing:zt,ctx:{isResponse:!1,serializer:n,getRef:i,makeRef:a,path:t,method:e}}),c)),m={schema:p==="components"?a(w(l),f):f,examples:Br(r,!1,c)};return{description:l,content:ke(ot(o,[m]))}},Yr=e=>Object.keys(e).map(t=>{let r=e[t],o={name:t,description:typeof r=="string"?r:r.description};return typeof r=="object"&&r.url&&(o.externalDocs={url:r.url}),o}),wt=e=>e.length<=vr?e:e.slice(0,vr-1)+"\u2026";var Et=class extends hs{lastSecuritySchemaIds=new Map;lastOperationIdSuffixes=new Map;makeRef(t,r){return this.addSchema(t,r),this.getRef(t)}getRef(t){return t in(this.rootDoc.components?.schemas||{})?{$ref:`#/components/schemas/${t}`}:void 0}ensureUniqOperationId(t,r,o){let n=o||w(r,t),i=this.lastOperationIdSuffixes.get(n);return i===void 0?(this.lastOperationIdSuffixes.set(n,1),n):(o&&gs.fail(new z({message:`Duplicated operationId: "${o}"`,method:r,isResponse:!1,path:t})),i++,this.lastOperationIdSuffixes.set(n,i),`${n}${i}`)}ensureUniqSecuritySchemaName(t){let r=JSON.stringify(t);for(let n in this.rootDoc.components?.securitySchemes||{})if(r===JSON.stringify(this.rootDoc.components?.securitySchemes?.[n]))return n;let o=(this.lastSecuritySchemaIds.get(t.type)||0)+1;return this.lastSecuritySchemaIds.set(t.type,o),`${t.type.toUpperCase()}_${o}`}constructor({routing:t,config:r,title:o,version:n,serverUrl:i,descriptions:a,brandHandling:p,hasSummaryFromDescription:d=!0,composition:c="inline",serializer:l=Ke}){super(),this.addInfo({title:o,version:n});for(let m of typeof i=="string"?[i]:i)this.addServer({url:m});W({routing:t,onEndpoint:(m,h,C)=>{let b=C,Z={path:h,method:b,endpoint:m,composition:c,serializer:l,brandHandling:p,getRef:this.getRef.bind(this),makeRef:this.makeRef.bind(this)},[R,x]=["short","long"].map(m.getDescription.bind(m)),ge=R?wt(R):d&&x?wt(x):void 0,k=m.getTags(),$=r.inputSources?.[b]||dt[b],oe=this.ensureUniqOperationId(h,b,m.getOperationId(b)),he=qr({...Z,inputSources:$,schema:m.getSchema("input"),description:a?.requestParameter?.call(null,{method:b,path:h,operationId:oe})}),Ue={};for(let j of["positive","negative"]){let G=m.getResponses(j);for(let{mimeTypes:xe,schema:T,statusCodes:O}of G)for(let A of O)Ue[A]=Gr({...Z,variant:j,schema:T,mimeTypes:xe,statusCode:A,hasMultipleStatusCodes:G.length>1||O.length>1,description:a?.[`${j}Response`]?.call(null,{method:b,path:h,operationId:oe,statusCode:A})})}let ct=$.includes("body")?_r({...Z,paramNames:xs("name",he),schema:m.getSchema("input"),mimeTypes:m.getMimeTypes("input"),description:a?.requestBody?.call(null,{method:b,path:h,operationId:oe})}):void 0,He=nt(_e(Vr(m.getSecurity(),$),j=>{let G=this.ensureUniqSecuritySchemaName(j),xe=["oauth2","openIdConnect"].includes(j.type)?m.getScopes().slice():[];return this.addSecurityScheme(G,j),{name:G,scopes:xe}}));this.addPath(Hr(h),{[b]:{operationId:oe,summary:ge,description:x,tags:k.length>0?k:void 0,parameters:he.length>0?he:void 0,requestBody:ct,security:He.length>0?He:void 0,responses:Ue}})}}),this.rootDoc.tags=r.tags?Yr(r.tags):[]}};import{createRequest as bs,createResponse as Ss}from"node-mocks-http";var Ts=e=>bs({...e,headers:{"content-type":P.json,...e?.headers}}),Os=e=>Ss(e),Rs=e=>{let t={warn:[],error:[],info:[],debug:[]};return new Proxy(e||{},{get(r,o,n){return o==="_getLogs"?()=>t:o in le?(...i)=>t[o].push(i):Reflect.get(r,o,n)}})},As=({requestProps:e,responseOptions:t,configProps:r,loggerProps:o})=>{let n=Ts(e),i=Os({req:n,...t});i.req=t?.req||n,n.res=i;let a=Rs(o),p={cors:!1,logger:a,...r};return{requestMock:n,responseMock:i,loggerMock:a,configMock:p}},Ps=async({endpoint:e,...t})=>{let{requestMock:r,responseMock:o,loggerMock:n,configMock:i}=As(t);return await e.execute({request:r,response:o,config:i,logger:n}),{requestMock:r,responseMock:o,loggerMock:n}};import E from"typescript";import N from"typescript";import{chain as Qr,toPairs as Jr}from"ramda";var s=N.factory,K=[s.createModifier(N.SyntaxKind.ExportKeyword)],Cs=[s.createModifier(N.SyntaxKind.AsyncKeyword)],Is=[s.createModifier(N.SyntaxKind.PublicKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],Wr=[s.createModifier(N.SyntaxKind.ProtectedKeyword),s.createModifier(N.SyntaxKind.ReadonlyKeyword)],Zt=s.createTemplateHead(""),fe=s.createTemplateTail(""),vt=s.createTemplateMiddle(" "),jt=e=>s.createTemplateLiteralType(Zt,e.map((t,r)=>s.createTemplateLiteralTypeSpan(s.createTypeReferenceNode(t),r===e.length-1?fe:vt))),Lt=jt(["M","P"]),st=(e,t,r)=>s.createParameterDeclaration(r,void 0,e,void 0,t,void 0),it=(e,t)=>Qr(([r,o])=>[st(s.createIdentifier(r),o,t)],Jr(e)),Nt=(e,t)=>s.createExpressionWithTypeArguments(s.createIdentifier("Record"),[typeof e=="number"?s.createKeywordTypeNode(e):s.createTypeReferenceNode(e),s.createKeywordTypeNode(t)]),Xr=e=>s.createConstructorDeclaration(void 0,e,s.createBlock([])),eo=(e,t)=>s.createPropertySignature(void 0,e,void 0,s.createTypeReferenceNode(t)),B=(e,t,r)=>s.createVariableDeclarationList([s.createVariableDeclaration(e,void 0,r,t)],N.NodeFlags.Const),kt=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,s.createUnionTypeNode(t.map(r=>s.createLiteralTypeNode(s.createStringLiteral(r))))),at=(e,t)=>s.createTypeAliasDeclaration(K,e,void 0,t),to=(e,t,r)=>s.createPropertyDeclaration(Is,e,void 0,t,r),ro=(e,t,r)=>s.createClassDeclaration(K,e,void 0,void 0,[t,...r]),oo=(e,t)=>s.createTypeReferenceNode("Promise",[s.createIndexedAccessTypeNode(s.createTypeReferenceNode(e),t)]),no=()=>s.createTypeReferenceNode("Promise",[s.createKeywordTypeNode(N.SyntaxKind.AnyKeyword)]),so=(e,t,r)=>s.createInterfaceDeclaration(K,e,void 0,t,r),zs=Qr(([e,t])=>[s.createTypeParameterDeclaration([],e,s.createTypeReferenceNode(t))]),io=e=>zs(Jr(e)),Mt=(e,t,r)=>s.createArrowFunction(r?Cs:void 0,void 0,e.map(o=>st(o)),void 0,void 0,t),Ut=(e,t,r)=>s.createCallExpression(s.createPropertyAccessExpression(s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("Object"),"keys"),void 0,[e]),"reduce"),void 0,[s.createArrowFunction(void 0,void 0,it({acc:void 0,key:void 0}),void 0,void 0,t),r]),ao=(...e)=>`"${e.join(" ")}"`;var po=["get","post","put","delete","patch"];import y from"typescript";import{z as Ft}from"zod";import q from"typescript";var{factory:pt}=q,Ht=(e,t)=>{q.addSyntheticLeadingComment(e,q.SyntaxKind.MultiLineCommentTrivia,`* ${t} `,!0)},ye=(e,t,r)=>{let o=pt.createTypeAliasDeclaration(void 0,pt.createIdentifier(t),void 0,e);return r&&Ht(o,r),o},Dt=(e,t)=>{let r=q.createSourceFile("print.ts","",q.ScriptTarget.Latest,!1,q.ScriptKind.TS);return q.createPrinter(t).printNode(q.EmitHint.Unspecified,e,r)},ws=/^[A-Za-z_$][A-Za-z0-9_$]*$/,co=e=>ws.test(e)?pt.createIdentifier(e):pt.createStringLiteral(e);var{factory:u}=y,Es={[y.SyntaxKind.AnyKeyword]:"",[y.SyntaxKind.BigIntKeyword]:BigInt(0),[y.SyntaxKind.BooleanKeyword]:!1,[y.SyntaxKind.NumberKeyword]:0,[y.SyntaxKind.ObjectKeyword]:{},[y.SyntaxKind.StringKeyword]:"",[y.SyntaxKind.UndefinedKeyword]:void 0},Zs=({value:e})=>u.createLiteralTypeNode(typeof e=="number"?u.createNumericLiteral(e):typeof e=="boolean"?e?u.createTrue():u.createFalse():u.createStringLiteral(e)),vs=({shape:e},{isResponse:t,next:r,optionalPropStyle:{withQuestionMark:o}})=>{let n=Object.entries(e).map(([i,a])=>{let p=t&&Re(a)?a instanceof Ft.ZodOptional:a.isOptional(),d=u.createPropertySignature(void 0,co(i),p&&o?u.createToken(y.SyntaxKind.QuestionToken):void 0,r(a));return a.description&&Ht(d,a.description),d});return u.createTypeLiteralNode(n)},js=({element:e},{next:t})=>u.createArrayTypeNode(t(e)),Ls=({options:e})=>u.createUnionTypeNode(e.map(t=>u.createLiteralTypeNode(u.createStringLiteral(t)))),lo=({options:e},{next:t})=>u.createUnionTypeNode(e.map(t)),Ns=e=>Es?.[e.kind],ks=(e,{next:t,isResponse:r})=>{let o=t(e.innerType());if(r&&e._def.effect.type==="transform"){let n=Be(e,Ns(o)),i={number:y.SyntaxKind.NumberKeyword,bigint:y.SyntaxKind.BigIntKeyword,boolean:y.SyntaxKind.BooleanKeyword,string:y.SyntaxKind.StringKeyword,undefined:y.SyntaxKind.UndefinedKeyword,object:y.SyntaxKind.ObjectKeyword};return u.createKeywordTypeNode(n&&i[n]||y.SyntaxKind.AnyKeyword)}return o},Ms=e=>u.createUnionTypeNode(Object.values(e.enum).map(t=>u.createLiteralTypeNode(typeof t=="number"?u.createNumericLiteral(t):u.createStringLiteral(t)))),Us=(e,{next:t,optionalPropStyle:{withUndefined:r}})=>{let o=t(e.unwrap());return r?u.createUnionTypeNode([o,u.createKeywordTypeNode(y.SyntaxKind.UndefinedKeyword)]):o},Hs=(e,{next:t})=>u.createUnionTypeNode([t(e.unwrap()),u.createLiteralTypeNode(u.createNull())]),Ds=({items:e,_def:{rest:t}},{next:r})=>u.createTupleTypeNode(e.map(r).concat(t===null?[]:u.createRestTypeNode(r(t)))),Fs=({keySchema:e,valueSchema:t},{next:r})=>u.createExpressionWithTypeArguments(u.createIdentifier("Record"),[e,t].map(r)),Ks=({_def:e},{next:t})=>u.createIntersectionTypeNode([e.left,e.right].map(t)),Bs=({_def:e},{next:t})=>t(e.innerType),re=e=>()=>u.createKeywordTypeNode(e),qs=(e,{next:t})=>t(e.unwrap()),$s=(e,{next:t})=>t(e.unwrap()),Gs=({_def:e},{next:t})=>t(e.innerType),Vs=({_def:e},{next:t,isResponse:r})=>t(e[r?"out":"in"]),_s=()=>u.createLiteralTypeNode(u.createNull()),Ys=({schema:e},{getAlias:t,makeAlias:r,next:o,serializer:n})=>{let i=`Type${n(e)}`;return t(i)||(r(i,u.createLiteralTypeNode(u.createNull())),r(i,o(e)))},Qs=e=>{let t=e.unwrap(),r=u.createKeywordTypeNode(y.SyntaxKind.StringKeyword),o=u.createTypeReferenceNode("Buffer"),n=u.createUnionTypeNode([r,o]);return t instanceof Ft.ZodString?r:t instanceof Ft.ZodUnion?n:o},Js=(e,{next:t})=>t(e.unwrap().shape.raw),Ws={ZodString:re(y.SyntaxKind.StringKeyword),ZodNumber:re(y.SyntaxKind.NumberKeyword),ZodBigInt:re(y.SyntaxKind.BigIntKeyword),ZodBoolean:re(y.SyntaxKind.BooleanKeyword),ZodAny:re(y.SyntaxKind.AnyKeyword),[Le]:re(y.SyntaxKind.StringKeyword),[Ne]:re(y.SyntaxKind.StringKeyword),ZodNull:_s,ZodArray:js,ZodTuple:Ds,ZodRecord:Fs,ZodObject:vs,ZodLiteral:Zs,ZodIntersection:Ks,ZodUnion:lo,ZodDefault:Bs,ZodEnum:Ls,ZodNativeEnum:Ms,ZodEffects:ks,ZodOptional:Us,ZodNullable:Hs,ZodDiscriminatedUnion:lo,ZodBranded:qs,ZodCatch:Gs,ZodPipeline:Vs,ZodLazy:Ys,ZodReadonly:$s,[D]:Qs,[Q]:Js},Me=(e,{brandHandling:t,ctx:r})=>X(e,{rules:{...t,...Ws},onMissing:()=>u.createKeywordTypeNode(y.SyntaxKind.AnyKeyword),ctx:r});var Kt=class{program=[];usage=[];registry=new Map;paths=[];aliases=new Map;ids={pathType:s.createIdentifier("Path"),methodType:s.createIdentifier("Method"),methodPathType:s.createIdentifier("MethodPath"),inputInterface:s.createIdentifier("Input"),posResponseInterface:s.createIdentifier("PositiveResponse"),negResponseInterface:s.createIdentifier("NegativeResponse"),responseInterface:s.createIdentifier("Response"),jsonEndpointsConst:s.createIdentifier("jsonEndpoints"),endpointTagsConst:s.createIdentifier("endpointTags"),providerType:s.createIdentifier("Provider"),implementationType:s.createIdentifier("Implementation"),clientClass:s.createIdentifier("ExpressZodAPIClient"),keyParameter:s.createIdentifier("key"),pathParameter:s.createIdentifier("path"),paramsArgument:s.createIdentifier("params"),methodParameter:s.createIdentifier("method"),accumulator:s.createIdentifier("acc"),provideMethod:s.createIdentifier("provide"),implementationArgument:s.createIdentifier("implementation"),headersProperty:s.createIdentifier("headers"),hasBodyConst:s.createIdentifier("hasBody"),undefinedValue:s.createIdentifier("undefined"),bodyProperty:s.createIdentifier("body"),responseConst:s.createIdentifier("response"),searchParamsConst:s.createIdentifier("searchParams"),exampleImplementationConst:s.createIdentifier("exampleImplementation"),clientConst:s.createIdentifier("client")};interfaces=[];getAlias(t){return this.aliases.has(t)?s.createTypeReferenceNode(t):void 0}makeAlias(t,r){return this.aliases.set(t,ye(r,t)),this.getAlias(t)}constructor({routing:t,brandHandling:r,variant:o="client",serializer:n=Ke,splitResponse:i=!1,optionalPropStyle:a={withQuestionMark:!0,withUndefined:!0}}){W({routing:t,onEndpoint:(T,O,A)=>{let ne={serializer:n,getAlias:this.getAlias.bind(this),makeAlias:this.makeAlias.bind(this),optionalPropStyle:a},be=w(A,O,"input"),Se=Me(T.getSchema("input"),{brandHandling:r,ctx:{...ne,isResponse:!1}}),I=i?w(A,O,"positive.response"):void 0,Bt=T.getSchema("positive"),qt=i?Me(Bt,{brandHandling:r,ctx:{...ne,isResponse:!0}}):void 0,Te=i?w(A,O,"negative.response"):void 0,$t=T.getSchema("negative"),Gt=i?Me($t,{brandHandling:r,ctx:{...ne,isResponse:!0}}):void 0,Vt=w(A,O,"response"),mo=I&&Te?s.createUnionTypeNode([s.createTypeReferenceNode(I),s.createTypeReferenceNode(Te)]):Me(Bt.or($t),{brandHandling:r,ctx:{...ne,isResponse:!0}});this.program.push(ye(Se,be)),qt&&I&&this.program.push(ye(qt,I)),Gt&&Te&&this.program.push(ye(Gt,Te)),this.program.push(ye(mo,Vt)),A!=="options"&&(this.paths.push(O),this.registry.set({method:A,path:O},{input:be,positive:I,negative:Te,response:Vt,isJson:T.getMimeTypes("positive").includes(P.json),tags:T.getTags()}))}}),this.program.unshift(...this.aliases.values()),this.program.push(kt(this.ids.pathType,this.paths)),this.program.push(kt(this.ids.methodType,po)),this.program.push(at(this.ids.methodPathType,jt([this.ids.methodType,this.ids.pathType])));let p=[s.createHeritageClause(E.SyntaxKind.ExtendsKeyword,[Nt(this.ids.methodPathType,E.SyntaxKind.AnyKeyword)])];this.interfaces.push({id:this.ids.inputInterface,kind:"input",props:[]}),i&&this.interfaces.push({id:this.ids.posResponseInterface,kind:"positive",props:[]},{id:this.ids.negResponseInterface,kind:"negative",props:[]}),this.interfaces.push({id:this.ids.responseInterface,kind:"response",props:[]});let d=[],c=[];for(let[{method:T,path:O},{isJson:A,tags:ne,...be}]of this.registry){let Se=ao(T,O);for(let I of this.interfaces)I.kind in be&&I.props.push(eo(Se,be[I.kind]));o!=="types"&&(A&&d.push(s.createPropertyAssignment(Se,s.createTrue())),c.push(s.createPropertyAssignment(Se,s.createArrayLiteralExpression(ne.map(I=>s.createStringLiteral(I))))))}for(let{id:T,props:O}of this.interfaces)this.program.push(so(T,p,O));if(o==="types")return;let l=s.createVariableStatement(K,B(this.ids.jsonEndpointsConst,s.createObjectLiteralExpression(d))),f=s.createVariableStatement(K,B(this.ids.endpointTagsConst,s.createObjectLiteralExpression(c))),m=at(this.ids.providerType,s.createFunctionTypeNode(io({M:this.ids.methodType,P:this.ids.pathType}),it({method:s.createTypeReferenceNode("M"),path:s.createTypeReferenceNode("P"),params:s.createIndexedAccessTypeNode(s.createTypeReferenceNode(this.ids.inputInterface),Lt)}),oo(this.ids.responseInterface,Lt))),h=at(this.ids.implementationType,s.createFunctionTypeNode(void 0,it({method:s.createTypeReferenceNode(this.ids.methodType),path:s.createKeywordTypeNode(E.SyntaxKind.StringKeyword),params:Nt(E.SyntaxKind.StringKeyword,E.SyntaxKind.AnyKeyword)}),no())),C=s.createTemplateExpression(s.createTemplateHead(":"),[s.createTemplateSpan(this.ids.keyParameter,fe)]),b=Ut(this.ids.paramsArgument,s.createCallExpression(s.createPropertyAccessExpression(this.ids.accumulator,"replace"),void 0,[C,s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter)]),this.ids.pathParameter),Z=Ut(this.ids.paramsArgument,s.createConditionalExpression(s.createBinaryExpression(s.createCallExpression(s.createPropertyAccessExpression(this.ids.pathParameter,"indexOf"),void 0,[C]),E.SyntaxKind.GreaterThanEqualsToken,s.createNumericLiteral(0)),void 0,this.ids.accumulator,void 0,s.createObjectLiteralExpression([s.createSpreadAssignment(this.ids.accumulator),s.createPropertyAssignment(s.createComputedPropertyName(this.ids.keyParameter),s.createElementAccessExpression(this.ids.paramsArgument,this.ids.keyParameter))])),s.createObjectLiteralExpression()),R=ro(this.ids.clientClass,Xr([st(this.ids.implementationArgument,s.createTypeReferenceNode(this.ids.implementationType),Wr)]),[to(this.ids.provideMethod,s.createTypeReferenceNode(this.ids.providerType),Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createCallExpression(s.createPropertyAccessExpression(s.createThis(),this.ids.implementationArgument),void 0,[this.ids.methodParameter,b,Z]),!0))]);this.program.push(l,f,m,h,R);let x=s.createPropertyAssignment(this.ids.methodParameter,s.createCallExpression(s.createPropertyAccessExpression(this.ids.methodParameter,"toUpperCase"),void 0,void 0)),ge=s.createPropertyAssignment(this.ids.headersProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createObjectLiteralExpression([s.createPropertyAssignment(s.createStringLiteral("Content-Type"),s.createStringLiteral(P.json))]),void 0,this.ids.undefinedValue)),k=s.createPropertyAssignment(this.ids.bodyProperty,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createCallExpression(s.createPropertyAccessExpression(s.createIdentifier("JSON"),"stringify"),void 0,[this.ids.paramsArgument]),void 0,this.ids.undefinedValue)),$=s.createVariableStatement(void 0,B(this.ids.responseConst,s.createAwaitExpression(s.createCallExpression(s.createIdentifier("fetch"),void 0,[s.createTemplateExpression(s.createTemplateHead("https://example.com"),[s.createTemplateSpan(this.ids.pathParameter,s.createTemplateMiddle("")),s.createTemplateSpan(this.ids.searchParamsConst,fe)]),s.createObjectLiteralExpression([x,ge,k])])))),oe=s.createVariableStatement(void 0,B(this.ids.hasBodyConst,s.createLogicalNot(s.createCallExpression(s.createPropertyAccessExpression(s.createArrayLiteralExpression([s.createStringLiteral("get"),s.createStringLiteral("delete")]),"includes"),void 0,[this.ids.methodParameter])))),he=s.createVariableStatement(void 0,B(this.ids.searchParamsConst,s.createConditionalExpression(this.ids.hasBodyConst,void 0,s.createStringLiteral(""),void 0,s.createTemplateExpression(s.createTemplateHead("?"),[s.createTemplateSpan(s.createNewExpression(s.createIdentifier("URLSearchParams"),void 0,[this.ids.paramsArgument]),fe)])))),[Ue,ct]=["json","text"].map(T=>s.createReturnStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.responseConst,T),void 0,void 0))),He=s.createIfStatement(s.createBinaryExpression(s.createTemplateExpression(Zt,[s.createTemplateSpan(this.ids.methodParameter,vt),s.createTemplateSpan(this.ids.pathParameter,fe)]),E.SyntaxKind.InKeyword,this.ids.jsonEndpointsConst),s.createBlock([Ue])),j=s.createVariableStatement(K,B(this.ids.exampleImplementationConst,Mt([this.ids.methodParameter,this.ids.pathParameter,this.ids.paramsArgument],s.createBlock([oe,he,$,He,ct]),!0),s.createTypeReferenceNode(this.ids.implementationType))),G=s.createExpressionStatement(s.createCallExpression(s.createPropertyAccessExpression(this.ids.clientConst,this.ids.provideMethod),void 0,[s.createStringLiteral("get"),s.createStringLiteral("/v1/user/retrieve"),s.createObjectLiteralExpression([s.createPropertyAssignment("id",s.createStringLiteral("10"))])])),xe=s.createVariableStatement(void 0,B(this.ids.clientConst,s.createNewExpression(this.ids.clientClass,void 0,[this.ids.exampleImplementationConst])));this.usage.push(j,xe,G)}printUsage(t){return this.usage.length?this.usage.map(r=>typeof r=="string"?r:Dt(r,t)).join(`
22
22
  `):void 0}print(t){let r=this.printUsage(t),o=r&&E.addSyntheticLeadingComment(E.addSyntheticLeadingComment(s.createEmptyStatement(),E.SyntaxKind.SingleLineCommentTrivia," Usage example:"),E.SyntaxKind.MultiLineCommentTrivia,`
23
23
  ${r}`);return this.program.concat(o||[]).map((n,i)=>Dt(n,i<this.program.length?t:{...t,omitTrailingSemicolon:!0})).join(`
24
24
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-zod-api",
3
- "version": "20.14.0",
3
+ "version": "20.14.1",
4
4
  "description": "A Typescript library to help you get an API server up and running with I/O schema validation and custom middlewares in minutes.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -78,7 +78,7 @@
78
78
  },
79
79
  "dependencies": {
80
80
  "ansis": "^3.2.0",
81
- "node-mocks-http": "^1.16.0",
81
+ "node-mocks-http": "^1.16.1",
82
82
  "openapi3-ts": "^4.4.0",
83
83
  "ramda": "^0.30.1"
84
84
  },
@@ -139,7 +139,7 @@
139
139
  "eslint-config-prettier": "^9.1.0",
140
140
  "eslint-plugin-allowed-dependencies": "^1.0.0",
141
141
  "eslint-plugin-prettier": "^5.1.3",
142
- "eslint-plugin-unicorn": "^55.0.0",
142
+ "eslint-plugin-unicorn": "^56.0.0",
143
143
  "express": "^5.0.0",
144
144
  "express-fileupload": "^1.5.0",
145
145
  "globals": "^15.3.0",